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
088d3bc74527922bc221e514f2e012df3542ed77
remove focus from text when not editable anymore
isso/js/app/edit.js
isso/js/app/edit.js
/* Copyright Théo Zimmermann 2014 * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define(["app/dom", "app/i18n", "app/utils", "diff_match_patch"], function($, i18n, utils) { "use strict"; // mode can take values "reading", "reading_modification" and "commenting" var mode = "reading"; // if mode is "reading_modification", currently_showing stores id of comment var currently_showing; // there must be only one <article> on the page var article = $("article"); // but there can be many blocks in an article var blocks = $(".block", article, false); // in the case there is no block, current_block will always represent the full article var current_block = article; var original_content, new_content; // button to show the original version var original_button = $.htmlify('<button type="button">' + i18n.translate("show-original") + '</button>'); // make a diff_match_patch object once and for all var dmp = new diff_match_patch(); // remember some of the DOM elements var cancel_button, comment_field; // FUNCTION WHICH ENABLE COMMENTING AND EDITING var init = function(comment_postbox) { comment_field = $(".textarea", comment_postbox); // let's curry! return function() { show_original(); if (mode === "reading" && comment_field.innerHTML !== "") { mode = "commenting"; original_content = utils.clean_html(current_block.innerHTML); new_content = null; current_block.setAttribute("contenteditable", true); // first time : create cancel button and associate event if (!cancel_button) { cancel_button = $(".post-action", comment_postbox).prepend( '<input type="reset" value="' + i18n.translate("postbox-cancel") + '"></input>'); cancel_button.on("click", function(e) { if (new_content === null || confirm(i18n.translate("postbox-confirm-cancel"))) { comment_field.innerHTML = ""; cancel(); } }); } else { cancel_button.style.display = "inline"; } } else if (mode === "commenting" && comment_field.innerHTML === "" && new_content === null) { cancel(); } }; }; var maybe_article_just_changed = function() { var current = utils.clean_html(current_block.innerHTML); if (current !== original_content) { new_content = current; } else { new_content = null; if (comment_field.innerHTML === i18n.translate("postbox-text") || comment_field.innerHTML === "") { cancel(); } } }; var cancel = function() { if (mode === "commenting") { current_block.setAttribute("contenteditable", false); if (new_content !== null) { current_block.innerHTML = original_content; new_content = null; } cancel_button.hide(); mode = "reading"; } }; // FUNCTIONS TO SHOW COMMENTS / EDITS var show_block_comments = function() { // when showing an edit or commenting, the current block is locked // this function is useless if there are no blocks if (mode == "reading" && blocks !== null) { // current block = block in the middle var center = window.pageYOffset + window.innerHeight/2; var i = 0; while (i < blocks.length && blocks[i].offsetTop <= center) { i++; } current_block = blocks[i - 1]; for (var i = 0; i < blocks.length; i++) { blocks[i].style.background = "transparent"; } current_block.style.background = "rgba(211,211,211,0.5)"; } }; var show_edit = function(el, comment) { // let's curry! return function() { if (mode === "reading" || mode === "reading_modification") { if (currently_showing === comment.id) { show_original(); } else { // print diffs var array = JSON.parse(utils.tags_from_text(comment.edit)); var html = dmp.diff_prettyHtml(array); current_block.innerHTML = html; // add button to go back to standard reading mode original_button.style.visibility = "visible"; // display selected comment in green and all others are set back to default var comments = $(".isso-comment", null, false); for (var i = 0; i < comments.length; i++) { comments[i].style.background = "transparent"; } el.style.background = "#e6ffe6"; // scroll to first change $("#edit").scrollIntoView(); mode = "reading_modification"; currently_showing = comment.id; } } }; }; var show_original = function() { if (mode === "reading_modification") { // restore original display current_block.innerHTML = original_content; original_button.style.visibility = "hidden"; var comments = $(".isso-comment", null, false); for (var i = 0; i < comments.length; i++) { comments[i].style.background = "transparent"; } mode = "reading"; currently_showing = null; // now show the current block like if we had just scrolled show_block_comments(); } }; // DEFINE EVENTS original_button.on("click", show_original); article.on("keyup", maybe_article_just_changed); document.addEventListener("keydown", function(e) { if (e.keyCode === 27) { show_original(); } }); window.addEventListener("scroll", show_block_comments); // ADD HTML ELEMENTS original_button.style.visibility = "hidden"; $("#isso-thread").prepend(original_button); // FIRST CALLS show_block_comments(); // PUBLIC METHODS return { init: init, new_article: function() { if (new_content === null) { return null; } // otherwise we apply some pre-treatment before returning var new_text = utils.tags_from_text(new_content); var diffs = dmp.diff_main(original_content, new_text); dmp.diff_cleanupSemantic(diffs); return JSON.stringify(diffs); }, cancel: cancel, show: show_edit }; });
JavaScript
0
@@ -3101,32 +3101,70 @@ rHTML === %22%22) %7B%0A + current_block.blur();%0A
20ac781b81810a6719e5c8603b458fbaca2baed7
fix destructive packages handling
lib/packageConstructor.js
lib/packageConstructor.js
const xmlbuilder = require('xmlbuilder'); const metadata = require('./utils/metadata'); module.exports = function(config){ this.constructPackage = function(structuredDiffs) { return new Promise(function(resolve,reject){ let filesContent = {}; const sorted_packageType = Object.keys(structuredDiffs).sort(); sorted_packageType.forEach(function(packageType){ if(Object.keys(structuredDiffs[packageType]).length > 0 ) { const strucDiffPerType = structuredDiffs[packageType]; let xml = xmlbuilder.create('Package') .att('xmlns', 'http://soap.sforce.com/2006/04/metadata') .dec('1.0', 'UTF-8'); for(let structuredDiff in strucDiffPerType) { if(metadata[structuredDiff] !== undefined) { // Handle different type of package.xml build let type = xml.ele('types'); for(var elem in strucDiffPerType[structuredDiff]) if(elem) { type.ele('members') .t(strucDiffPerType[structuredDiff][elem]); } type.ele('name').t(metadata[structuredDiff].xmlName); } } xml.ele('version') .t(config.apiVersion); filesContent[packageType] = xml.end({ pretty: true, indent: ' ', newline: '\n' }); } }); resolve(filesContent); }); }; };
JavaScript
0.000001
@@ -115,16 +115,17 @@ (config) + %7B%0A this @@ -144,25 +144,16 @@ ckage = -function( structur @@ -159,17 +159,19 @@ redDiffs -) + =%3E %7B%0A r @@ -188,24 +188,16 @@ Promise( -function (resolve @@ -204,16 +204,20 @@ ,reject) + =%3E %7B%0A @@ -342,25 +342,16 @@ forEach( -function( packageT @@ -357,77 +357,11 @@ Type -)%7B%0A if(Object.keys(structuredDiffs%5BpackageType%5D).length %3E 0 ) + =%3E %7B%0A @@ -363,26 +363,24 @@ %3E %7B%0A - const strucD @@ -426,26 +426,24 @@ e%5D;%0A - let xml = xm @@ -489,18 +489,16 @@ - - .att('xm @@ -566,18 +566,16 @@ - .dec('1. @@ -592,26 +592,24 @@ ');%0A - - for(let stru @@ -652,18 +652,16 @@ - if(metad @@ -693,26 +693,24 @@ ndefined) %7B%0A - @@ -763,26 +763,24 @@ - let type = x @@ -792,26 +792,24 @@ e('types');%0A - @@ -877,34 +877,32 @@ - - type.ele('member @@ -905,18 +905,16 @@ mbers')%0A - @@ -965,18 +965,16 @@ elem%5D);%0A - @@ -983,34 +983,32 @@ %7D%0A - type.ele('name') @@ -1045,18 +1045,16 @@ lName);%0A - @@ -1057,38 +1057,34 @@ %7D%0A - %7D%0A +%7D%0A xml.ele( @@ -1102,18 +1102,16 @@ - .t(confi @@ -1125,18 +1125,16 @@ rsion);%0A - @@ -1217,26 +1217,16 @@ %5Cn' %7D);%0A - %7D%0A %7D)
59a7e04a75de00f31c76feedfcf1f70025ed4e27
Update npmcheckversion.js
packages/strapi-helper-plugin/lib/internals/scripts/npmcheckversion.js
packages/strapi-helper-plugin/lib/internals/scripts/npmcheckversion.js
/* eslint-disable */ var shell = require('shelljs'); shell.exec('npm -v', {silent: true}, function (code, stdout, stderr) { if (code) throw stderr; if (parseFloat(stdout) < 3) { throw new Error('[ERROR: Strapi plugin] You need npm version @>=3'); process.exit(1); } });
JavaScript
0.000002
@@ -18,11 +18,13 @@ */%0A -var +const she
bf7cb932de7d44e74b192d09028236e583ff28d1
fix Error.captureStackTrace
bridge/bridge.js
bridge/bridge.js
/* Copyright (c) 2015, Kotaro Endo. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var process = {}; process.binding = (function() { var bindings = { contextify : {}, natives : {}, smalloc : {}, constants : {}, fs : {}, uv : {}, http_parser : {}, crypto : {}, tty_wrap : {}, timer_wrap : {}, pipe_wrap : {}, cares_wrap : {}, tcp_wrap : {}, udp_wrap : {}, stream_wrap : {}, signal_wrap : {}, }; return function(name) { return bindings[name]; } })(); Object.defineProperty(Object.prototype, "__defineGetter__", { value : function(n, getter) { Object.defineProperty(this, n, { get : getter }); }, writable : true, enumerable : false, configurable : true }); Object.defineProperty(Number, "isFinite", { value : function(value) { return typeof value === "number" && isFinite(value); }, writable : true, enumerable : false, configurable : true }); Object.defineProperty(Error, "stackTraceLimit", { get : function() { return getSystemProperty("stackTraceLimit"); }, set : function(value) { setSystemProperty("stackTraceLimit", value); }, enumerable : true, configurable : true }); Error.captureStackTrace = (function() { function StackTraceEntry(info) { this.info = info; } StackTraceEntry.prototype.getFileName = function() { return this.info.filename; } StackTraceEntry.prototype.getLineNumber = function() { return this.info.lineNumber; } StackTraceEntry.prototype.getColumnNumber = function() { return this.info.columnNumber; } StackTraceEntry.prototype.getFunctionName = function() { return this.info.functionName; } StackTraceEntry.prototype.getMethodName = function() { return undefined; //TODO } StackTraceEntry.prototype.isEval = function() { return false; //TODO } return function(obj) { Error.stackTraceLimit++; var e = new Error(); Error.stackTraceLimit--; var stack = []; for (var i = 1;; i++) { var info = e.getStackTraceEntry(i); if (!info) { break; } stack.push(new StackTraceEntry(info)); } obj.stack = stack; } })();
JavaScript
0.000003
@@ -2635,17 +2635,16 @@ Trace = -( function @@ -2648,883 +2648,547 @@ ion( +obj ) %7B%0A%09 -function StackTraceEntry(info) %7B%0A%09%09this.info = info;%0A%09%7D%0A%09StackTraceEntry.prototype.getFileName = function() %7B%0A%09%09return this.info.filename;%0A%09%7D%0A%09StackTraceEntry.prototype.getLineNumber = function() %7B%0A%09%09return this.info.lineNumber;%0A%09%7D%0A%09StackTraceEntry.prototype.getColumnNumber = function() %7B%0A%09%09return this.info.columnNumber;%0A%09%7D%0A%09StackTraceEntry.prototype.getFunctionName = function() %7B%0A%09%09return this.info.functionName;%0A%09%7D%0A%09StackTraceEntry.prototype.getMethodName = function() %7B%0A%09%09return undefined; //TODO%0A%09%7D%0A%09StackTraceEntry.prototype.isEval = function() %7B%0A%09%09return false; //TODO%0A%09%7D%0A%0A%09return function(obj) %7B%0A%09%09Error.stackTraceLimit++;%0A%09%09var e = new Error();%0A%09%09Error.stackTraceLimit--;%0A%09%09var stack = %5B%5D;%0A%09%09for (var i = 1;; i++) %7B%0A%09%09%09var info = e.getStackTraceEntry(i);%0A%09%09%09if (!info) %7B%0A%09%09%09%09break;%0A%09%09%09%7D%0A%09%09%09stack.push(new StackTraceEntry(info));%0A%09%09%7D%0A%09%09obj.stack = stack;%0A%09%7D%0A%7D)() +Error.stackTraceLimit++;%0A%09var e = new Error();%0A%09Error.stackTraceLimit--;%0A%09var A = %5B%5D;%0A%09A%5B0%5D = %22Error%22;%0A%09for (var i = 1;; i++) %7B%0A%09%09var info = e.getStackTraceEntry(i);%0A%09%09if (!info) %7B%0A%09%09%09break;%0A%09%09%7D%0A%09%09var finfo = info.filename + %22:%22 + info.lineNumber + %22:%22 + info.columnNumber;%0A%09%09A%5Bi%5D = finfo;%0A%09%09if (info.functionName) %7B%0A%09%09%09A%5Bi%5D = info.functionName + %22 (%22 + finfo + %22)%22;%0A%09%09%7D%0A%09%7D%0A%09var stack = A.join(%22%5Cn at %22);%0A%09Object.defineProperty(obj, %22stack%22, %7B%0A%09%09value : stack,%0A%09%09writable : true,%0A%09%09enumerable : false,%0A%09%09configurable : true%0A%09%7D);%0A%7D ;%0A
1c22f724b292b66cc3910a98e85e0849851b8a38
remove piche console.log
qpanel/themes/qpanel/static/js/qpanel.index.js
qpanel/themes/qpanel/static/js/qpanel.index.js
$(document).ready(function () { getDataQueue(); //load data on page ready :) setInterval(function () { getDataQueue(); }, REQUEST_INTERVAL); }); // parse data and put values on view function parseDataQueue(data){ console.log(data); var answers = 0, unattended = 0, incoming = 0; var c_hold = 0, holdtime = 0, c_talk = 0, talktime = 0; var call_in_service_level = 0; for (var d in data) { answers = answers + parseInt(data[d].Completed); unattended = unattended + parseInt(data[d].Abandoned); incoming = incoming + parseInt(data[d].Calls); $("[id='data-"+ d + "'] #queue_completed").html(parseInt(data[d].Completed)); $("[id='data-"+ d + "'] #queue_abandoned").html(parseInt(data[d].Abandoned)); $("[id='data-"+ d + "'] #queue_incoming").html(parseInt(data[d].Calls)); $("[id='data-"+ d + "'] #queue_users").html(len(data[d].members)); $(".header-"+ d + " #strategy").html(data[d].Strategy); if (SHOW_SERVICE_LEVEL === true) { $("[id='data-"+ d + "'] #queue_servicelevel").html(data[d].ServicelevelPerf + '%'); call_in_service_level += data[d].Completed * parseFloat(data[d].ServicelevelPerf) / 100; } if (data[d].Abandoned > 0) { $("[id='"+ d + "-percent_abandoned']") .html(parseInt(parseInt(data[d].Abandoned) * 100 / (parseInt(data[d].Abandoned) + parseInt(data[d].Completed) ))); } if (parseInt(data[d].TalkTime) > 0 ) { talktime = talktime + parseInt(data[d].TalkTime); c_talk++; } if (parseInt(data[d].Holdtime) > 0 ) { holdtime = holdtime + parseInt(data[d].Holdtime); c_hold++; } var agent_free = 0, agent_busy = 0, agent_unavailable = 0; for (agent in data[d].members) { var status_agent = parseInt(data[d].members[agent].Status); if (data[d].members[agent].Paused == true) { agent_busy++; } else if (C.status_agent.NOT_INUSE == status_agent) { agent_free++; } else if (status_agent.isUnavailableInAsterisk()) { agent_unavailable++; } else { agent_busy++; } } agents = agent_free + agent_busy + agent_unavailable; //bugfix NaN division by 0 if (agents == 0) { agents = 1; } $("[id='data-"+ d + "'] #queue_free") .html( "{agents} ({percent}% {status})" .format({agents: agent_free, percent: Math.round(agent_free * 100 / agents), status: STATUSES.free })); $("[id='data-"+ d + "'] #queue_busy") .html( "{agents} ({percent}% {status})" .format({agents: agent_busy, percent: Math.round(agent_busy * 100 / agents), status: STATUSES.busy })); $("[id='data-"+ d + "'] #queue_unavailable") .html( "{agents} ({percent}% {status})" .format({agents: agent_unavailable, percent: Math.round(agent_unavailable * 100 / agents), status: STATUSES.unavailable})); } $('#answered').html(answers); $('#abandoned').html(unattended); $('#incoming').html(incoming); if (c_hold > 0 ) { $('#av_wait').html(parseInt((holdtime / c_hold)).toString().toMMSS()); } if (c_talk > 0){ $('#av_time').html(parseInt((talktime / c_talk)).toString().toMMSS()); } if (SHOW_SERVICE_LEVEL === true) { if (answers == 0) { $('#servicelevel').html( "{percent}%".format({percent: 0.0})); } else { $('#servicelevel').html( "{percent}%".format({percent: Math.round(call_in_service_level * 100 / answers)})); } } } function getDataQueue() { var result; var r = $.ajax({ type: 'GET', url: URL_QUEUE_DATA }); r.done(function (response) { if (response) { result = response.data; parseDataQueue(result); } }); r.fail(function (response) { }); r.always(function () { }); }
JavaScript
0
@@ -295,39 +295,8 @@ a)%7B%0A - console.log(data);%0A
3ce06463b7424fdb0d28fdf7ba2d58d314422397
fix header
src/notebook/api/messaging/index.js
src/notebook/api/messaging/index.js
/* eslint camelcase: 0 */ // <-- Per Jupyter message spec import * as uuid from 'uuid'; const Rx = require('@reactivex/rxjs'); const Observable = Rx.Observable; const session = uuid.v4(); export function createMessage(msg_type) { const username = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; return { header: { username, session, msg_type, msg_id: uuid.v4(), date: new Date(), version: '5.0', }, metadata: {}, parent_header: {}, content: {}, }; } export function createExecuteRequest(code) { const executeRequest = createMessage('execute_request'); executeRequest.content = { code, silent: false, store_history: true, user_expressions: {}, allow_stdin: false, stop_on_error: false, }; return executeRequest; } export function msgSpecToNotebookFormat(msg) { return Object.assign({}, msg.content, { output_type: msg.header.msg_type, }); } /** * childOf filters out messages that don't have the parent header matching parentMessage * @param {Object} parentMessage Jupyter message protocol message * @return {Observable} the resulting observable */ export function childOf(parentMessage) { const parentMessageID = parentMessage.header.msg_id; return Observable.create(subscriber => { // since we're in an arrow function `this` is from the outer scope. // save our inner subscription const subscription = this.subscribe(msg => { console.info('looking for complete_reply...', msg.parent_header.msg_type); if (!msg.parent_header || !msg.parent_header.msg_id) { subscriber.error(new Error('no parent_header.msg_id on message')); return; } if (parentMessageID === msg.parent_header.msg_id) { subscriber.next(msg); } }, // be sure to handle errors and completions as appropriate and // send them along err => subscriber.error(err), () => subscriber.complete()); // to return now return subscription; }); } /** * ofMessageType is an Rx Operator that filters on msg.header.msg_type * being one of messageTypes * @param {Array} messageTypes e.g. ['stream', 'error'] * @return {Observable} the resulting observable */ export function ofMessageType(messageTypes) { return Observable.create(subscriber => { // since we're in an arrow function `this` is from the outer scope. // save our inner subscription const subscription = this.subscribe(msg => { if (!msg.header || !msg.header.msg_type) { subscriber.error(new Error('no header.msg_type on message')); return; } if (messageTypes.indexOf(msg.header.msg_type) !== -1) { subscriber.next(msg); } }, // be sure to handle errors and completions as appropriate and // send them along err => subscriber.error(err), () => subscriber.complete()); // to return now return subscription; }); } Observable.prototype.childOf = childOf; Observable.prototype.ofMessageType = ofMessageType;
JavaScript
0.000001
@@ -1574,31 +1574,24 @@ ly...', msg. -parent_ header.msg_t
d4fbfa374d34b71e8aa8308e1e44e178c68f3c9b
Allow images to load from myemma.com
server/config/security.js
server/config/security.js
BrowserPolicy.content.allowOriginForAll("*.googleapis.com"); BrowserPolicy.content.allowOriginForAll("*.gstatic.com"); BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com"); BrowserPolicy.content.allowFontDataUrl();
JavaScript
0
@@ -174,16 +174,71 @@ n.com%22); +%0ABrowserPolicy.content.allowOriginForAll(%22myemma.com%22); %0A%0ABrowse
48910fa05af97ff10dc0ad2fa07b7bb2647635c0
Use this.route instead of this.resource to make transition to pods easier.
tests/dummy/app/router.js
tests/dummy/app/router.js
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType, scrollToTopAfterRouteTransition: Ember.observer( 'url', function() { window.scrollTo( 0, 0 ); }) }); Router.map( function() { this.route( 'index', { path: '/' }); this.route( 'browsers' ); this.resource( 'demos', function() { this.route( 'sl-alert' ); this.route( 'sl-button' ); this.route( 'sl-calendar' ); this.route( 'sl-chart' ); this.route( 'sl-checkbox' ); this.route( 'sl-date-picker' ); this.route( 'sl-date-range-picker' ); this.route( 'sl-date-time' ); this.route( 'sl-dialog' ); this.route( 'sl-drop-button' ); this.route( 'sl-input' ); this.route( 'sl-grid' ); this.route( 'sl-loading-icon' ); this.route( 'sl-menu' ); this.route( 'sl-pagination' ); this.route( 'sl-panel' ); this.route( 'sl-progress-bar' ); this.route( 'sl-radio' ); this.route( 'sl-radio-group' ); this.route( 'sl-select' ); this.route( 'sl-span' ); this.route( 'sl-tab-panel' ); this.route( 'sl-textarea' ); this.route( 'sl-tooltip' ); }); }); export default Router;
JavaScript
0
@@ -364,14 +364,11 @@ is.r -esourc +out e( '
d3c66ba1ece0bace394022e023b0c4ade959503e
Fix cache headers on CSS file.
lib/serve-css.js
lib/serve-css.js
var prepare = require('prepare-response') , autoprefixer = require('autoprefixer-core')() , fs = require('fs') var cache = new Map() , isProd = process.env.NODE_ENV == 'production' module.exports = serveCss function serveCss(path) { var cacheKey = JSON.stringify(path) return function(req, res, next) { if (isProd && cache.has(cacheKey)) { return cache.get(cacheKey).send(req, res) } fs.readFile(path, { encoding: 'utf8' }, (err, data) => { if (err) return next(err) var css = autoprefixer.process(data, { from: path, to: req.path, map: (isProd ? false : { inline: true }) }).css var headers = { 'content-type': 'text/css' } if (isProd) { headers.cache = 'public, max-age=60' } prepare(css, headers, { gzip: isProd }).nodeify((err, response) => { if (err) return next(err) if (isProd) { cache.set(cacheKey, response) } response.send(req, res) }) }) } }
JavaScript
0
@@ -737,36 +737,36 @@ ders -. +%5B' cache - = 'public, max-age=60 +-control'%5D = '14 days '%0A
392deac1c1ef94234fdcacdbd145edf6b8f198f3
Add board size to config
config/config.example.js
config/config.example.js
module.exports = { "secret": "CHANGETHISDONTUSETHISITSINSECURE", // <------- CHANGE THIS DONT USE THE DEFAULT YOU'LL GET HACKED AND DIE 100% "database": "mongodb://localhost/place", "port": 3000, "onlyListenLocal": true, "trustProxyDepth": 1, // How many levels of proxy to trust for IP "debug": false, "googleAnalyticsTrackingID": "", // UA-XXXXXXXX-XX "host": "http://place.dynastic.co", // the publicly accessible URL of the site "placeTimeout": 60, //"sentryDSN": "", UNCOMMENT IF YOU HAVE A KEY "cachet": { // Setup reporting error count as a metric to Cachet "apiKey": "", "site": "", "metricID": 0 }, "recaptcha": { // Leave blank to disable "siteKey": "", "secretKey": "" }, "oauth": { // No field here is required. // To use an oauth option, set enabled to true, and drop your keys in. "google": { "enabled": false, "clientID": "", "clientSecret": "" }, "reddit": { "enabled": false, "clientID": "", "clientSecret": "" }, "discord": { "enabled": false, "clientID": "", "clientSecret": "" }, "twitter": { "enabled": false, "clientID": "", "clientSecret": "" }, "github": { "enabled": false, "clientID": "", "clientSecret": "" }, "facebook": { "enabled": false, "clientID": "", "clientSecret": "" } } };
JavaScript
0.000001
@@ -201,16 +201,39 @@ : 3000,%0A + %22boardSize%22: 1400,%0A %22onl @@ -1666,8 +1666,9 @@ %7D%0A%7D; +%0A
27c543b60d8f32cabe773700aee61f3066073f25
Fix generate method
lib/shortlink.js
lib/shortlink.js
(function() { 'use strict'; var alphabetList = { base52: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', base58: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', base64: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' }; var alphabet = alphabetList.base58, alphabetLength = alphabet.length; /** * Generate random string from alphabet * * @param {Number} count Number of characters * @param {String} alphabet * @return {String} */ var generate = function(count, alphabet) { var result = '', count = parseInt(count, 10) || 5, alphabetArray = alphabet.split(''); for (var i = 0; i < count; i++) { var index = Math.floor(Math.random() * alphabetLength); if (index === 0 && i === 0) {index = 1;} result += alphabetArray[index]; } return result; }; /** * Encode number to string * * @param {Number} num * @param {String} alphabet * @return {String} */ var encode = function (num, alphabet) { var encode = ''; num = parseInt(num, 10); while (num >= alphabetLength) { var mod = num % alphabetLength; encode = alphabet[mod] + encode; num = parseInt(num / alphabetLength, 10); } if (num) { encode = alphabet[num] + encode; } return encode; }; /** * Decode string to number * * @param {String} str * @param {String} alphabet * @return {Number} */ var decode = function(str, alphabet) { var decode = 0, multi = 1; for (var i = str.length - 1; i >= 0; i--) { decode = decode + multi * alphabet.indexOf(str[i]); multi = multi * alphabetLength; } return decode; }; /** * Set alphabet: from alphabetList by name or custom string * * @param {String} alpha * @return {Object} */ exports.set = function(alpha) { if (alpha && alphabetList.hasOwnProperty(alpha)) { alphabet = alphabetList[alpha]; } else if (alpha && typeof alpha === 'string' && alpha.length > 10) { alphabet = alpha; } alphabetLength = alphabet.length; return this; }; /////////// Public Methods /////////// exports.generate = function(count) { return generate(count, alphabet); }; exports.encode = function(num) { return encode(num, alphabet); }; exports.decode = function(str) { return decode(str, alphabet); }; })();
JavaScript
0.000019
@@ -666,56 +666,8 @@ %7C%7C 5 -,%0A alphabetArray = alphabet.split('') ;%0A%0A @@ -862,13 +862,8 @@ abet -Array %5Bind @@ -2315,24 +2315,25 @@ bet.length;%0A +%0A retu
01eb0edb64e1ce82894c5de924d84116f44ff5e1
work on twitter API
api/api.js
api/api.js
import express from 'express'; import bodyParser from 'body-parser'; import config from '../src/config'; import * as actions from './actions/index'; import {mapUrl} from 'utils/url.js'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; import passport from'passport'; const TwitterStrategy = require('passport-twitter').Strategy; const session = require('express-session'); const MongoStore = require('connect-mongo')(session); const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const io = new SocketIo(server); io.path('/ws'); app.use(bodyParser.json()); app.use(session({ secret: config.sessionKey, store: new MongoStore({ url: 'mongodb://localhost/eyfApp' }) })); console.log('_______ config: ', config); const twitterCallbackUrl = `${config.host}:${config.port}/login/twitter/return`; console.log('return api: ', twitterCallbackUrl); var twitterConfig = require('./../keys/twitter.json'); var keys = Object.assign({ callbackUrl: twitterCallbackUrl }, { consumerKey: twitterConfig.consumer_key, consumerSecret: twitterConfig.consumer_secret }); passport.use(new TwitterStrategy(keys, function (token, tokenSecret, profile, cb) { console.log('profile: ', profile); cb(null, profile); } )); passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); }); app.use(passport.initialize()); app.use(passport.session()); app.get('/login/twitter', passport.authenticate('twitter')); app.get('/login/twitter/auth', passport.authenticate('twitter', {failureRedirect: `$(config.host}:${config.port}/login`}), function (req, res) { res.redirect(`$(config.host}:${config.port}/`); }); /* passport.authenticate('twitter', {failureRedirect: `$(config.host}:${config.port}/login`}), function (req, res) { res.redirect(`$(config.host}:${config.port}/`); }); */ app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const {action, params} = mapUrl(actions, splittedUrlPath); if (action) { action(req, params) .then((result) => { if (result instanceof Function) { result(res); } else { res.json(result); } }, (reason) => { if (reason && reason.redirect) { res.redirect(reason.redirect); } else { console.error('API ERROR:', pretty.render(reason)); res.status(reason.status || 500).json(reason); } }); } else { res.status(404).end('NOT FOUND'); } }); const bufferSize = 100; const messageBuffer = new Array(bufferSize); let messageIndex = 0; if (config.apiPort) { const runnable = app.listen(config.apiPort, (err) => { if (err) { console.error(err); } console.info('----\n==> 🌎 API is running on port %s', config.apiPort); console.info('==> 💻 Send requests to http://%s:%s', config.apiHost, config.apiPort); }); io.on('connection', (socket) => { socket.emit('news', {msg: `'Hello World!' from server`}); socket.on('history', () => { for (let index = 0; index < bufferSize; index++) { const msgNo = (messageIndex + index) % bufferSize; const msg = messageBuffer[msgNo]; if (msg) { socket.emit('msg', msg); } } }); socket.on('msg', (data) => { data.id = messageIndex; messageBuffer[messageIndex % bufferSize] = data; messageIndex++; io.emit('msg', data); }); }); io.listen(runnable); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
JavaScript
0
@@ -850,25 +850,28 @@ = %60$%7Bconfig. -h +apiH ost%7D:$%7Bconfi @@ -864,33 +864,36 @@ iHost%7D:$%7Bconfig. -p +apiP ort%7D/login/twitt @@ -895,22 +895,20 @@ twitter/ -return +auth %60;%0Aconso @@ -1022,22 +1022,8 @@ s = -Object.assign( %7B%0A @@ -1033,18 +1033,18 @@ allbackU -rl +RL : twitte @@ -1059,13 +1059,9 @@ kUrl -%0A%7D, %7B +, %0A @@ -1153,17 +1153,16 @@ secret%0A%7D -) ;%0A%0Apassp @@ -1355,16 +1355,17 @@ function + (user, c @@ -1427,16 +1427,17 @@ function + (obj, cb @@ -1472,36 +1472,157 @@ app. -use(passport.initialize( +get('/login/twitter/auth',%0A passport.authenticate('twitter', %7B%0A failureRedirect: %60/login%60,%0A successRedirect: '/api/login'%0A %7D ));%0A +%0A app. @@ -1638,82 +1638,48 @@ ort. -session +initialize ());%0A -%0A app. -get('/login/twitter',%0A passport.authenticate('twitter' +use(passport.session( ));%0A @@ -1694,37 +1694,32 @@ ('/login/twitter -/auth ',%0A passport. @@ -1744,158 +1744,12 @@ ter' -, %7BfailureRedirect: %60$(config.host%7D:$%7Bconfig.port%7D/login%60%7D),%0A function (req, res) %7B%0A res.redirect(%60$(config.host%7D:$%7Bconfig.port%7D/%60);%0A %7D); +));%0A %0A/*
aaf44a6dc8761b01a453fd4cfccc94f07653a0d7
Allow zero-value transactions
lib/simulator.js
lib/simulator.js
var vm = require('vm') var extend = require('extend') var clone = require('clone') var EventEmitter = require('events').EventEmitter var Contract = require('./contract.js') var Transaction = require('./transaction.js') var Wallet = require('./wallet.js') var Block = require('./block.js') module.exports = Simulator function Simulator(opts) { if (!(this instanceof Simulator)) return new Simulator(opts) this._initialize(opts) } Simulator.prototype._initialize = function(opts) { this.contracts = {} this.wallets = {} this.transactions = {} this.blocks = {} extend(this,new EventEmitter()) } Simulator.prototype.createContract = function(opts) { var wallet = opts.wallet = new Wallet({value: opts.value}) var newContract = new Contract(opts) this.contracts[newContract.id] = newContract this.createBlock({newContracts:[newContract]}) this.emit('contract',newContract.toJSON(),wallet.toJSON()) return newContract } Simulator.prototype.createTransaction = function(opts) { var newTransaction = new Transaction(opts) this.transactions[newTransaction.id] = newTransaction this.processTransaction(newTransaction) return newTransaction } Simulator.prototype.createWallet = function(opts) { var newWallet = new Wallet(opts) this.wallets[newWallet.id] = newWallet this.emit('wallet',newWallet.toJSON()) return newWallet } Simulator.prototype.processTransaction = function(transaction) { var targetContract = this.contracts[transaction.target], senderContract = this.contracts[transaction.sender], targetWallet, senderWallet // determine in sender+Target are contracts or simple wallets if (senderContract) { senderWallet = senderContract.wallet } else { senderWallet = this.wallets[transaction.sender] } if (targetContract) { targetWallet = targetContract.wallet } else { targetWallet = this.wallets[transaction.target] } // validate transaction var isValid = (true && transaction.value > 0 && transaction.fee >= 0 && (transaction.value+transaction.fee) <= senderWallet.value ) if (!isValid) throw new Error('Invalid Transaction.') // announce activation of transaction this.emit('transaction',transaction.toJSON()) // exchange values senderWallet.value -= (transaction.value + transaction.fee) targetWallet.value += transaction.value this.emit('wallet.update',senderWallet.toJSON()) this.emit('wallet.update',targetWallet.toJSON()) // update contracts, trigger contract run if (senderContract) { this.emit('contract.update',senderContract.toJSON(),senderWallet.toJSON()) } if (targetContract) { this.emit('contract.update',targetContract.toJSON(),targetWallet.toJSON()) this.runContract(targetContract, transaction) } // mine a block for this transaction this.createBlock({ transactions:[transaction], runContracts: targetContract ? [targetContract] : [], }) } Simulator.prototype.runContract = function(contract,transaction) { var sim = this // announce activation of contract this.emit('contract.activate',contract.toJSON(),transaction.toJSON()) var programSrc = '(function(){\n\n\n'+contract.js+'\n\n\n})()' vm.runInNewContext(programSrc, { contract: { storage: contract.storage, mem: [], }, tx: { sender: transaction.sender, value: transaction.value, fee: transaction.fee, data: clone(transaction.data), datan: transaction.datan, }, block: { contract_storage: function(id) { return clone(sim.contracts[id].storage) }, basefee: 1, // time in seconds timestamp: (new Date()).getTime()/1000, }, mktx: function(target, value, fee, data) { this.createTransaction({ target: target, sender: transaction.sender, value: value, fee: fee || 0, data: data || [], }) }, }) } Simulator.prototype.createBlock = function(opts) { var newBlock = new Block(opts) this.blocks[newBlock.id] = newBlock this.emit('block',newBlock.toJSON()) }
JavaScript
0.000052
@@ -1977,16 +1977,17 @@ .value %3E += 0%0A &
83de46d9d198626ae7676b9c2032b37b5c2a1228
use the correct hash function
plugins/gui/frontend/gosa/source/class/gosa/ui/form/WebhookListItem.js
plugins/gui/frontend/gosa/source/class/gosa/ui/form/WebhookListItem.js
/* * This file is part of the GOsa project - http://gosa-project.org * * Copyright: * (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de * * License: * LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html * * See the LICENSE file in the project's top-level directory for details. */ qx.Class.define("gosa.ui.form.WebhookListItem", { extend: qx.ui.core.Widget, implement : [qx.ui.form.IModel], include : [qx.ui.form.MModelProperty], /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.base(arguments); this._setLayout(new qx.ui.layout.VBox()); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { appearance : { refine : true, init : "gosa-listitem-webhook" }, label: { check: "String", nullable: true, apply: "_applyLabel" }, mimeType: { check: "String", nullable: true }, secret: { check: "String", nullable: true, apply: "_applySecret" }, expanded: { check: "Boolean", init: false, apply: "_applyExpanded" }, /** * How this list item should behave like group or normal ListItem */ listItemType: { check: ['group', 'item'], init: 'item', apply: '_applyListItemType' } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // overridden _createChildControlImpl: function(id) { var control; switch(id) { case "label": control = new qx.ui.basic.Label(); control.setAnonymous(true); this._addAt(control, 0); break; case "expansion": control = new qx.ui.container.Composite(new qx.ui.layout.Grid(5, 5)); control.setAnonymous(true); control.exclude(); this._addAt(control, 2, {flex: 1}); break; case "hint": var headers = '<ul><li><strong>Content-Type:</strong> <i>'+ this.getMimeType()+'</i></li><li><strong>HTTP_X_HUB_SENDER:</strong> <i>'+ this.getLabel()+'</i></li><li><strong>HTTP_X_HUB_SIGNATURE:</strong> '+ this.tr("SHA2 hash of the content body encrypted with secret:")+' <i>'+this.getSecret()+'</i></li></ul>'; var msg = this.tr("Use the following headers when you POST data to %1", "<strong>"+gosa.ui.settings.Webhooks.URL+"</strong>"); msg += headers; control = new qx.ui.basic.Label(msg).set({rich: true, wrap: true}); this.getChildControl("expansion").add(control, {row: 0, column: 0}); break; } return control || this.base(arguments, id); }, _applyExpanded: function(value) { if (value === true) { this.getChildControl("expansion").show(); } else { this.getChildControl("expansion").exclude(); } }, // property apply _applyLabel: function(value) { this.__handleValue(this.getChildControl("label"), value); }, // property apply _applySecret: function() { if (!this.hasChildControl("hint")) { this._createChildControl("hint"); } }, // property apply _applyListItemType: function(value) { if (value === "group") { this.setAppearance("gosa-listitem-webhook-group"); this.setEnabled(false); } else { this.setAppearance("gosa-listitem-webhook"); this.setEnabled(true); } }, __handleValue: function(control, value) { if (value) { control.setValue(value); control.show(); } else { control.exclude(); } } } });
JavaScript
0.979626
@@ -2616,16 +2616,19 @@ .tr(%22SHA +-51 2 hash o
fd04ba63d4194800195bdde57adea5f441fac035
clean up unused parts of script
lib/slim2html.js
lib/slim2html.js
var util = require('util'); var spawn = require('child_process').spawn var createSlimPreprocessor = function(logger, basePath, config) { config = typeof config === 'object' ? config : {}; var log = logger.create('preprocessor.slim'); var stripPrefix = new RegExp('^' + (config.stripPrefix || '')); var prependPrefix = config.prependPrefix || ''; var cacheIdFromPath = config && config.cacheIdFromPath || function(filepath) { return prependPrefix + filepath.replace(stripPrefix, ''); }; return function(content, file, done) { var child, html log.debug('Processing "%s".', file.originalPath); var htmlPath = cacheIdFromPath(file.originalPath.replace(basePath + '/', '')); var origPath = file.path // TODO ??? file.path = file.path + '.js'; // TODO origPath = origPath.split("queue-web-client/")[1] log.debug("Spawning", origPath) html = '' child = spawn("slimrb", [origPath]) child.stdout.on('data', function (buf) { html += String(buf); }); child.stdout.on('close', function (buf) { done(html); }); child.stderr.on('data', function (buf) { throw String(buf); }); }; }; createSlimPreprocessor.$inject = ['logger', 'config.basePath', 'config.ngHtml2JsPreprocessor']; module.exports = createSlimPreprocessor;
JavaScript
0.000005
@@ -113,30 +113,12 @@ gger -, basePath, config ) %7B%0A + co @@ -220,273 +220,8 @@ );%0A%0A - var stripPrefix = new RegExp('%5E' + (config.stripPrefix %7C%7C ''));%0A var prependPrefix = config.prependPrefix %7C%7C '';%0A var cacheIdFromPath = config && config.cacheIdFromPath %7C%7C function(filepath) %7B%0A return prependPrefix + filepath.replace(stripPrefix, '');%0A %7D;%0A%0A re @@ -276,16 +276,26 @@ ld, html +, origPath %0A%0A lo @@ -351,271 +351,36 @@ -var htmlPath = cacheIdFromPath(file.originalPath.replace(basePath + '/', ''));%0A%0A var origPath = file.path%0A // TODO ???%0A file.path = file.path + '.js';%0A%0A // TODO%0A origPath = origPath.split(%22queue-web-client/%22)%5B1%5D%0A log.debug(%22Spawning%22, orig +origPath = file.original Path -)%0A %0A @@ -672,16 +672,16 @@ %7D;%0A%7D;%0A%0A + createSl @@ -718,59 +718,8 @@ ger' -, 'config.basePath', 'config.ngHtml2JsPreprocessor' %5D;%0A%0A
4ff6ea8ecfafe1abfbf56996111488ba9a186888
make it better
config/env/production.js
config/env/production.js
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/phonebuzz', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', 'public/lib/jquery.scrollbar/jquery.scrollbar.css', 'public/lib/font-awesome/css/font-awesome.css' ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/lib/jquery/dist/jquery.min.js', 'public/lib/jquery.scrollbar/jquery.scrollbar.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
JavaScript
0.000086
@@ -1026,16 +1026,291 @@ ,%0A%09%09css: + %5B%0A%09%09%09'public/modules/**/css/*.css'%0A%09%09%5D,%0A%09%09js: %5B%0A%09%09%09'public/config.js',%0A%09%09%09'public/application.js',%0A%09%09%09'public/modules/*/*.js',%0A%09%09%09'public/modules/*/*%5B!tests%5D*/*.js'%0A%09%09%5D,%0A%09%09tests: %5B%0A%09%09%09'public/lib/angular-mocks/angular-mocks.js',%0A%09%09%09'public/modules/*/tests/*.js'%0A%09%09%5D%0A%09%09/*css: 'public @@ -1375,16 +1375,18 @@ .min.js' +*/ %0A%09%7D,%0A%09fa
b3f5076373a5790d6068d24da769f7a80543d812
work on dbcontroller
server/db/dbController.js
server/db/dbController.js
var model = require('./dbModel.js'); var getUser = function (user) { model.User.findOne({ where: { username: user.username }}) .then(function (match) { if (!match) { throw (new Error('User does not exist!')); } else { return match; } }) }; var addUser = function (user) { model.User.findOne({ where: { username: user.username } }) .then(function (match) { if (match) { throw (new Error('Username already exists')); } else { return user; } }) .then(function (newUser) { return model.User.create({ username: newUser.username, password: newUser.password }); }) }; var addItem = function (object) { // object will have the following format { item: { name: 'xyz' }, user: { id: 'INTEGER', name: 'abc' } } model.Item.findOrCreate({ where: { name: object.itemName } }) .then(function (item) { return model.ItemUser.findOrCreate({ where: { item_id: item.id, used_id: object.user } }); }) }; var getRelatedItems = function (itemList) { }; var addCategory = function (req, res) { }; var getCategory = function (req, res) { }; var getAllCategories = function (req, res) { }; module.exports = { getUser: getUser, addUser: addUser, addItem: addItem, getRelatedItems: getRelatedItems, addCategory: addCategory, getCategory: getCategory, getAllCategories: getAllCategories };
JavaScript
0
@@ -1040,24 +1040,78 @@ itemList) %7B%0A + for (var i = 0; i %3C itemList.length; i++) %7B%0A %0A %7D %0A%7D;%0A%0Avar add
353795683afc30a050caa4b76369377ea184bfdd
Update defer.js
javascript/defer.js
javascript/defer.js
function defer(fn) { var timer = null; return function() { clearTimeout(timer); timer = setTimeout(fn, 400); } } // TODO: add some variations; like on utilizes RAF etc.
JavaScript
0.000001
@@ -193,8 +193,94 @@ AF etc.%0A +// TODO: maybe make this things modular; and write in ES6 and transpile to ES5 maybe.%0A
88a8eb74291f179ea44ac28626e7602f9a2d47c4
Work around sync event on proxy attach
packages/stream-dom/src/nodes/stream.js
packages/stream-dom/src/nodes/stream.js
import { merge } from 'most' import create from 'lodash.create' import { initializeChildren } from './util' export function stream(context, children$) { return (scope) => { const { document } = context const { destroy$ } = scope const domStartNode = document.createComment('') const domEndNode = document.createComment('') const childDescriptors$ = children$ .until(destroy$) .map(children => initializeChildren(children, create(scope, { destroy$: merge(children$, destroy$).take(1), }))) .tap(childDescriptors => { const { document, sharedRange } = context const fragment = document.createDocumentFragment() childDescriptors.forEach(childDescriptor => childDescriptor.insert(fragment)) sharedRange.setStartAfter(domStartNode) sharedRange.setEndBefore(domEndNode) sharedRange.deleteContents() sharedRange.insertNode(fragment) }) childDescriptors$.drain() return new StreamNodeDescriptor({ sharedRange: context.sharedRange, domStartNode, domEndNode, childDescriptors$ }) } } class StreamNodeDescriptor { get type() { return 'stream' } constructor({ sharedRange, domStartNode, domEndNode, childDescriptors$ }) { this.sharedRange = sharedRange this.domStartNode = domStartNode this.domEndNode = domEndNode this.childDescriptors$ = childDescriptors$ } insert(domParentNode, domBeforeNode = null) { domParentNode.insertBefore(this.domStartNode, domBeforeNode) domParentNode.insertBefore(this.domEndNode, domBeforeNode) } remove() { const { sharedRange } = this sharedRange.setStartBefore(this.domStartNode) sharedRange.setEndAfter(this.domEndNode) sharedRange.deleteContents() } }
JavaScript
0
@@ -214,16 +214,26 @@ const %7B + mounted$, destroy @@ -478,16 +478,146 @@ cope, %7B%0A + // TODO: Remove use of delay() workaround for most-proxy sync dispatch during attach%0A mounted$: mounted$.delay(1),%0A
bec2387801a3902d2e9fe028e970718e11fe6486
Reset unread count for active contact on focus.
clientapp/models/state.js
clientapp/models/state.js
/*global app, $*/ "use strict"; var HumanModel = require('human-model'); module.exports = HumanModel.define({ initialize: function () { var self = this; $(window).blur(function () { self.focused = false; }); $(window).focus(function () { self.focused = true; self.markActive(); }); if (window.macgap) { document.addEventListener('sleep', function () { clearTimeout(this.idleTimer); self.markInactive(); }, true); } this.markActive(); }, session: { focused: ['bool', true, true], active: ['bool', true, false], connected: ['bool', true, false], hasConnected: ['bool', true, false], idleTimeout: ['number', true, 600000], idleSince: 'date', allowAlerts: ['bool', true, false], badge: ['string', true, ''], pageTitle: ['string', true, ''] }, derived: { title: { deps: ['pageTitle', 'badge'], fn: function () { var base = this.pageTitle ? 'Otalk - ' + this.pageTitle : 'Otalk'; if (this.badge) { return this.badge + ' • ' + base; } return base; } } }, markActive: function () { clearTimeout(this.idleTimer); var wasInactive = !this.active; this.active = true; this.idleSince = new Date(Date.now()); this.idleTimer = setTimeout(this.markInactive.bind(this), this.idleTimeout); }, markInactive: function () { if (this.focused) { return this.markActive(); } this.active = false; this.idleSince = new Date(Date.now()); } });
JavaScript
0
@@ -12,11 +12,15 @@ p, $ +, me */%0A - %22use @@ -310,32 +310,139 @@ focused = true;%0A + if (me._activeContact) %7B%0A me.setActiveContact(me._activeContact);%0A %7D%0A self @@ -550,32 +550,32 @@ , function () %7B%0A - @@ -604,16 +604,62 @@ Timer);%0A + console.log('went to sleep');%0A
0ddcee0784d3a33e2e16b16181f047ac62d9464e
Update fba.js
asset/js/fba.js
asset/js/fba.js
/********************************************************************* * #### CI File Browser Awesome v01 #### * Coded by Ican Bachors 2015. * https://github.com/bachors/CI-FIle-Browser-Awesome * Updates will be posted to this site. *********************************************************************/ // Setting: Base_URL/Controllers_name var baseurl = 'http://your-domain.com/file'; /* Testing di localhost */ var fix = /\\/; /* atau jika tombol back bermasalah ketika sudah di hosting gunakan script dibawah ini: var fix = /\//; */ var value = getParameterByName('dir'); if(value != ''){ ibc_fba(scan,sub=value,fix); }else{ ibc_fba(baseurl,sub="",fix) } function ibc_fba(baseurl,sub,fix) { $.ajax( { url:baseurl+'/map?sub='+sub, crossDomain:true, dataType:"json" }).done(function(data) { var r=""; r+="<table>"; r+='<thead><tr><th class="name">Name</th><th class="size">Size</th><th class="modif">Last Modified</th></tr></thead><tbody>'; if(data.back!="") { r+='<tr><td colspan="3" class="root"><i class="bsub fa fa-reply" data-bsub="'+data.back.replace(fix,"")+'"></i> '+data.root+"</td></tr>" } $.each(data.items,function(i,item) { var size=ibc_ukurana(data.items[i].size); if(data.items[i].type=="folder") { r+='<tr><td class="name"><span class="sub fa" data-sub="'+data.items[i].path+'"><i class="fa fa-folder"></i> '+data.items[i].name+'</span></td><td class="size">'+data.items[i].items.length+' item</td><td class="modif">'+data.items[i].modif+"</td></tr>" } else { var s=data.items[i].path.substr(data.items[i].path.lastIndexOf(".")+1); switch(s) { // List read file. Custom/add example case"asp":case"jsp" etc case"html": case"php": case"js": case"css": case"txt": r+='<tr><td class="name"><span class="rfile fa" data-rfile="'+data.items[i].path+'"><i class="fa fa-file-text"></i> '+data.items[i].name+'</span></td><td class="size">'+size+'</td><td class="modif">'+data.items[i].modif+"</td></tr>"; break; // List download file default: r+='<tr><td class="name"><a href="'+data.items[i].link+data.items[i].path+'" target="_blank"><i class="fa fa-archive"></i> '+data.items[i].name+'</a></td><td class="size">'+size+'</td><td class="modif">'+data.items[i].modif+"</td></tr>" } } }); r+='<tr><td colspan="3" style="text-align:center;font-size:8px;padding-top:30px">'+unescape("%3C%61%20%68%72%65%66%3D%22%68%74%74%70%3A%2F%2F%69%62%61%63%6F%72%2E%63%6F%6D%2F%6C%61%62%73%2F%6A%71%75%65%72%79%2D%66%69%6C%65%2D%62%72%6F%77%73%65%72%2D%61%77%65%73%6F%6D%65%2F%22%20%74%61%72%67%65%74%3D%22%5F%42%4C%41%4E%4B%22%3E%46%69%6C%65%20%42%72%6F%77%73%65%72%20%41%77%65%73%6F%6D%65%3C%2F%61%3E")+"</td></tr>"; r+="</tbody></table>"; $(".ibc_fba").html(r); $("#ibc_fba_file").html(''); $(".sub").click(function() { var t=$(this).data("sub"); ibc_fba(baseurl,t,fix); window.history.pushState(null, null, "?dir="+t); return false }); $(".bsub").click(function() { var t=$(this).data("bsub"); ibc_fba(baseurl,t,fix); window.history.pushState(null, null, "?dir="+t); return false }); $(".rfile").click(function() { var file=$(this).data("rfile"); ibc_fba_file(baseurl,file); return false }); }); } function ibc_fba_file(baseurl,file) { $.ajax( { url:baseurl+'/read?file='+file, crossDomain:true, dataType:"json" }).done(function(data) { var t='<div class="pan_code"><i class="fa fa-code pull-left"></i> <strong>Ctrl-F / Cmd-F:</strong> Start searching, <strong>Ctrl-G / Cmd-G:</strong> Find next, <strong>Shift-Ctrl-G / Shift-Cmd-G:</strong> Find previous, <strong>Shift-Ctrl-F / Cmd-Option-F:</strong> Replace, <strong>Shift-Ctrl-R / Shift-Cmd-Option-F:</strong> Replace all</div><textarea id="text" name="text">'+data.text+'</textarea><script>var editor = CodeMirror.fromTextArea(document.getElementById("text"), { mode: "text/html", lineNumbers: true, theme: "monokai"});</script>'; $("#ibc_fba_file").html(t) }); } function ibc_ukurana(e) { var t=["Bytes","KB","MB","GB","TB"]; if(e==0)return"0 Bytes"; var n=parseInt(Math.floor(Math.log(e)/Math.log(1024))); return Math.round(e/Math.pow(1024,n),2)+" "+t[n] } function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }
JavaScript
0
@@ -1106,17 +1106,17 @@ ta.root+ -%22 +' %3C/td%3E%3C/t @@ -1117,17 +1117,18 @@ td%3E%3C/tr%3E -%22 +'; %0A%09%09%7D%0A%09%09$
27508c770edfc78e6023508482dfc87f4d0cac03
Fix a bug introduced by pull request #2315
frontend/tasks/server.js
frontend/tasks/server.js
const fs = require('fs'); const url = require('url'); const gulp = require('gulp'); const config = require('../config.js'); const connect = require('gulp-connect'); const pkey = fs.readFileSync('./frontend/certs/server/my-server.key.pem'); const pcert = fs.readFileSync('./frontend/certs/server/my-server.crt.pem'); const pca = fs.readFileSync('./frontend/certs/server/my-private-root-ca.crt.pem'); const serverOptions = { root: config.DEST_PATH, livereload: false, host: '0.0.0.0', port: config.SERVER_PORT, middleware: (connect, ops) => [ // Rewrite /path to /path/index.html (req, res, next) => { const parsed = url.parse(req.url); const { pathname } = parsed; // If no dot or trailing slash, try rewriting if (pathname.indexOf('.') === -1 && pathname.substring(pathname.length - 1) !== '/') { parsed.pathname = pathname + '/index.html'; req.url = url.format(parsed); } next(); } ] }; if (config.USE_HTTPS) { serverOptions.https = { key: pkey, cert: pcert, ca: pca, passphrase: '' }; } gulp.task('server', () => { connect.server(serverOptions); });
JavaScript
0
@@ -710,18 +710,19 @@ no dot -or +and trailin @@ -847,16 +847,16 @@ '/') %7B%0A - @@ -945,16 +945,229 @@ %7D%0A + // Rewrite /static/addon/latest to /static/addon/addon.xpi%0A if (pathname === '/static/addon/latest') %7B%0A parsed.pathname = '/static/addon/addon.xpi';%0A req.url = url.format(parsed);%0A %7D%0A ne
b2a1fc2c38ecd22a981fe2d187052ccbe9ad79e0
Set cross origin tag for html5 embeds
react/gameday2/components/embeds/EmbedHtml5.js
react/gameday2/components/embeds/EmbedHtml5.js
/* global videojs */ import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' export default class EmbedHtml5 extends React.Component { static propTypes = { webcast: webcastPropType.isRequired, } componentDidMount() { videojs(this.props.webcast.id, { width: '100%', height: '100%', autoplay: true, }) } render() { return ( <video controls id={this.props.webcast.id} className="video-js vjs-default-skin" > <source src={this.props.webcast.channel} type="application/x-mpegurl" /> </video> ) } }
JavaScript
0
@@ -421,16 +421,48 @@ ontrols%0A + crossorigin=%22anonymous%22%0A
380ebe5e6c204b9cdded18e444ce0b9b498f4467
Add Action URL to the features API
server/lib/api/feature.js
server/lib/api/feature.js
module.exports = function(app, db) { //*****************************// Index //**********************************// app.get('/api/features', function(req, res) { var cb = function(error, features) { if (!error) { res.json(features); // Write the jsonified features to the response object } else { res.json(error); } }; features = db.feature.findAll(cb); }); //******************************// Show //**********************************// app.get('/api/features/:id', function(req, res) { db.feature.find({ id: req.params.id }, function(error, feature) { if (!error) { if (feature.length) { res.json(feature[0]); } else { res.json({ message: 'Object Not Found' }); } } else { res.json(error); } }); }); //*****************************// Create //*********************************// app.post('/api/features', function(req, res) { var data = req.body; db.feature.create({ message: data.message, action: data.action, image: data.image, //we save the InkBLob of the image to delete it when the project is deleted InkBlob: (data.InkBlob && typeof data.InkBlob === "object")? JSON.stringify(data.InkBlob) : data.InkBlob, published: data.published }, function(error, feature) { if (!error) { res.json(feature); } else { res.json(error); } }); }); //*****************************// Update //*********************************// app.put('/api/features/:id', function(req, res) { var data = req.body; db.feature.update(req.params.id, req.body, function(error, feature) { if (error) { return res.send(error); } else { res.json(feature); } }); }); //*****************************// Destroy //********************************// app.del('/api/features/:id', function (req, res){ return db.feature.remove(req.params.id, function (error) { if (!error) { res.send(''); } else { res.send(error); } }); }); };
JavaScript
0
@@ -1135,16 +1135,49 @@ action,%0A + actionUrl: data.actionUrl,%0A im
a99459a9dfbee49d1c6a4ae0c4029d9efb8208db
Remove webpack2 conditional in postcss
packages/postcss/index.js
packages/postcss/index.js
/** * PostCSS webpack block. * * @see https://github.com/postcss/postcss-loader */ module.exports = postcss /** * @param {PostCSSPlugin[]} [plugins] Will read `postcss.config.js` file if not supplied. * @param {object} [options] * @param {RegExp|Function|string} [options.exclude] Directories to exclude. * @param {string} [options.parser] Package name of custom PostCSS parser to use. * @param {string} [options.stringifier] Package name of custom PostCSS stringifier to use. * @param {string} [options.syntax] Package name of custom PostCSS parser/stringifier to use. * @return {Function} */ function postcss (plugins, options) { plugins = plugins || [] options = options || {} // https://github.com/postcss/postcss-loader#options const postcssOptions = Object.assign( {}, options.parser && { parser: options.parser }, options.stringifier && { stringifier: options.stringifier }, options.syntax && { syntax: options.syntax } ) return (context) => Object.assign( { module: { loaders: [ Object.assign({ test: context.fileType('text/css'), loaders: [ 'style-loader', 'css-loader', 'postcss-loader?' + JSON.stringify(postcssOptions) ] }, options.exclude ? { exclude: Array.isArray(options.exclude) ? options.exclude : [ options.exclude ] } : {}) ] } }, plugins ? createPostcssPluginsConfig(context.webpack, plugins) : {} ) } function createPostcssPluginsConfig (webpack, plugins) { const isWebpack2 = typeof webpack.validateSchema !== 'undefined' if (isWebpack2) { return { plugins: [ new webpack.LoaderOptionsPlugin({ options: { postcss: plugins, // Hacky fix for a strange issue involving the postcss-loader, sass-loader and webpack@2 // (see https://github.com/andywer/webpack-blocks/issues/116) // Might be removed again once the `sass` block uses a newer `sass-loader` context: '/' } }) ] } } else { return { postcss: plugins } } }
JavaScript
0.000002
@@ -1623,98 +1623,8 @@ ) %7B%0A - const isWebpack2 = typeof webpack.validateSchema !== 'undefined'%0A%0A if (isWebpack2) %7B%0A re @@ -1634,18 +1634,16 @@ n %7B%0A - plugins: @@ -1641,26 +1641,24 @@ plugins: %5B%0A - new we @@ -1693,18 +1693,16 @@ - options: @@ -1710,26 +1710,24 @@ %7B%0A - - postcss: plu @@ -1733,18 +1733,16 @@ ugins,%0A%0A - @@ -1842,18 +1842,16 @@ - // (see @@ -1914,18 +1914,16 @@ - - // Might @@ -1999,18 +1999,16 @@ - context: @@ -2012,18 +2012,16 @@ xt: '/'%0A - @@ -2032,79 +2032,16 @@ - %7D)%0A - %5D%0A %7D%0A %7D else %7B%0A return %7B%0A postcss: plugins%0A %7D +%5D %0A %7D
2db44c797ec7bdafbeef66f20f8adffaaac83dca
Remove dead code
src/grid.js
src/grid.js
var component = require('omniscient'), EventEmitter = require('events').EventEmitter, Immutable = require('immutable'), bind = require('lodash.bind'), React = require('react/addons'); var CELL_SIZE = 30, BORDER_SIZE = 1, TEXT_X_OFFSET = 7, TEXT_Y_OFFSET = 25; function position(a) { return (Math.floor(a / 3) + 2) * BORDER_SIZE + a * (CELL_SIZE + BORDER_SIZE); } var Cell = component(function (props, statics) { var x = props.cursor.get('x'), y = props.cursor.get('y'), value = props.cursor.get('value'); function onClick(e) { statics.events.emit('click', { x: x, y: y }); } return React.DOM.g({ className: React.addons.classSet({ "sudoku__cell": true, "sudoku__cell--not-editable": !props.cursor.get('editable'), "sudoku__cell--highlighted": props.cursor.get('highlighted'), "sudoku__cell--focussed": props.cursor.get('focussed') }) }, React.DOM.rect({ x: position(x), y: position(y), width: CELL_SIZE, height: CELL_SIZE, onClick: onClick }), value ? [ React.DOM.text({ key: "text", x: position(x) + TEXT_X_OFFSET, y: position(y) + TEXT_Y_OFFSET, className: "sudoku__cell-text", onClick: onClick }, value) ] : [] ); }); function highlights(focusX, focusY) { var focusSquareX = Math.floor(focusX / 3), focusSquareY = Math.floor(focusY / 3); return function (x, y) { var squareX = Math.floor(x / 3), squareY = Math.floor(y / 3); return x == focusX || y == focusY || squareX == focusSquareX && squareY == focusSquareY; }; } function fConst(a) { return function () { return a; }; }; var events = new EventEmitter(); function mapCells(grid, f) { return grid.map(function (column) { return column.map(f); }); } var Grid = component({ focusCell: function (position) { var isHighlighted = highlights(position.x, position.y), cells = this.props.cells; cells.update(function (state) { return mapCells(state, function (cell) { return cell.merge({ focussed: cell.get('x') === position.x && cell.get('y') === position.y, highlighted: isHighlighted(cell.get('x'), cell.get('y')) }); }); }); this.focus = cells.get([position.x, position.y]); }, blurCell: function () { this.props.cells.update(function (state) { return mapCells(state, function (cell) { return cell.merge({ focussed: false, highlighted: false }); }); }); }, componentDidMount: function () { events.on('click', bind(this.focusCell, this)); }, componentWillUnmount: function () { events.removeAllListeners(); } }, function (props) { var cells = props.cells.flatMap(function (column) { return column.map(function (cell) { return Cell(cell.get('x') + "_" + cell.get('y'), { cursor: cell, statics: { events: events } }); }); }); return React.DOM.svg({ width: position(9), height: position(9), tabIndex: "0", onBlur: this.blurCell }, React.DOM.rect({ x: 0, y: 0, width: position(9), height: position(9), className: "sudoku__background" }), cells.toJS()); }); module.exports = Grid;
JavaScript
0.001497
@@ -1873,83 +1873,8 @@ %0A%7D%0A%0A -function fConst(a) %7B%0A return function () %7B%0A return a;%0A %7D;%0A%7D;%0A%0A var
5d0b638ec1341b6f1d5f7d476373a8d37919e83c
use grunt command to start grunt
frontend/Gruntfile.js
frontend/Gruntfile.js
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ copy:{ html: { src: './index.html', dest: 'dist/index.html' }, dist: { files: [ { expand: true, dot: true, cwd: './', dest: 'dist', src: [ 'images/**/*', 'style/fonts/*', ] }, { expand: true, cwd: '.', dest: 'dist', src: ['bower_components/requirejs/*.js','bower_components/requirejs-domready/*.js'] }] }, leaflet: { src: '.tmp/concat/app/leaflet.js', dest:'dist/app/leaflet.js', }, templates: { files: [{ expand: true, flatten: true, dot: true, cwd: './', dest: 'dist/app/templates/', src: ['.tmp/scripts/templates/*'], }] }, jstemplates: { src: '.tmp/templates.js', dest: 'bower_components/templates.js' }, }, useminPrepare: { html: 'index.html', options: { dest: 'dist' } }, usemin:{ html:['dist/index.html'] }, htmlmin: { // Task dist: { // Target options: { // Target options removeComments: true, collapseWhitespace: true }, files: [{ expand: true, src: ['app/**/*.html','*.html'], dest:'dist/', }] } }, html2js: { options: { base: '.', module: 'app.templates', singleModule: true, useStrict: true, htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } }, main: { src: ['app/templates/*.html'], dest: 'app/templates/maintemplate.js' }, }, requirejs: { generated: { options: { dir: '.tmp/scripts/', modules: [{ name: 'main' }], preserveLicenseComments: false, removeCombined: true, baseUrl: 'app', mainConfigFile: 'app/main.js', optimize: 'uglify2', uglify2: { mangle: false } } } }, concat: { dist: { src: ['.tmp/scripts/main.js'], dest: 'dist/app/main.js' } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', 'dist/{,*/}*' ] }] }, tmp: { files: [{ dot: true, src: '.tmp', }] } }, bower: { install: { options: { targetDir: "./bower_components", copy: false } } }, }); // Default task(s). and build task grunt.registerTask('default', [ 'clean:dist', 'copy:html', 'copy:dist', 'useminPrepare', 'concat:generated', 'cssmin:generated', 'requirejs:generated', 'concat', 'copy:leaflet', 'usemin' ]); grunt.registerTask('build', [ //'bower', 'clean', 'copy:html', 'copy:dist', 'useminPrepare', 'concat:generated', 'cssmin:generated', 'requirejs:generated', 'concat', 'copy:leaflet', 'copy:templates', 'copy:jstemplates', 'usemin', 'clean:tmp', ]); grunt.registerTask('build2', [ //'bower', 'html2js', //'copy:templates', 'copy:html', 'copy:dist', 'useminPrepare', 'concat:generated', 'cssmin:generated', 'requirejs:generated', 'concat', 'copy:leaflet', //'copy:templates', 'copy:jstemplates', 'usemin', //'clean:tmp', ]); };
JavaScript
0.000003
@@ -4012,24 +4012,26 @@ build task%0A +%0A%0A grunt.re @@ -4053,1021 +4053,8 @@ ault -', %5B%0A 'clean:dist',%0A 'copy:html',%0A 'copy:dist',%0A 'useminPrepare',%0A 'concat:generated',%0A 'cssmin:generated',%0A 'requirejs:generated',%0A 'concat',%0A 'copy:leaflet',%0A 'usemin'%0A %5D);%0A grunt.registerTask('build', %5B%0A //'bower',%0A 'clean',%0A 'copy:html',%0A 'copy:dist',%0A 'useminPrepare',%0A 'concat:generated',%0A 'cssmin:generated',%0A 'requirejs:generated',%0A 'concat',%0A 'copy:leaflet',%0A 'copy:templates',%0A 'copy:jstemplates',%0A 'usemin',%0A 'clean:tmp',%0A %5D);%0A grunt.registerTask('build2 ', %5B
85e1158111ad953270e8d4f9799bf590a7922a4d
Add put request to save file
glark/app/js/services/filesystem/RemoteFile.js
glark/app/js/services/filesystem/RemoteFile.js
/* Copyright 2013 Florent Galland & Luc Verdier This file is part of glark.io. glark.io is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. glark.io is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with glark.io. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; angular.module('glark.services') /* Create a glark.services.File object from a html5 File or Blob object. */ .factory('RemoteFile', function (base64, $q, $http) { /* Create a remote file from his name and * params, where params contains information * to connect the Rest API. */ var RemoteFile = function (name, params, basename) { this.isDirectory = false; this.isFile = true; this.name = name; this.basename = '/'; this.changed = false; if (basename !== undefined) { this.basename = basename; } this.params = params; this.baseurl = 'http://' + params.adress + ':' + params.port + '/connector'; this.baseurl += this.basename + this.name; this.authenticationHeader = 'Basic ' + base64.encode(params.username + ':' + params.password); }; /* Get the content of the remote file. */ RemoteFile.prototype.getContent = function () { var defered = $q.defer(); $http.get(this.baseurl, {headers: {'Authorization': this.authenticationHeader}}) .success(function (response) { defered.resolve(response.data.content); }) .error(function (response, status) { console.log('Error in $http get. Unable to get content of remote file.'); console.log(status); console.log(response); }); return defered.promise; }; /* Set the content of the remote file. */ RemoteFile.prototype.setContent = function (content) { var defered = $q.defer(); defered.resolve(); return defered.promise; }; return RemoteFile; });
JavaScript
0
@@ -2529,32 +2529,528 @@ -defered.resolve( +$http.put(this.baseurl, %7B'path': this.basename + this.name, 'content': content%7D,%0A %7Bheaders: %7B'Authorization': this.authenticationHeader%7D%7D)%0A .success(function (response) %7B%0A defered.resolve(response.data.content);%0A %7D)%0A .error(function (response, status) %7B%0A console.log('Error in $http put. Unable to set content of remote file.');%0A console.log(status);%0A console.log(response);%0A %7D );%0A
91bd41399bf979a733bf7c8691d2991b07c3a63a
Update redshift driver to use new postgres driver
lib/Drivers/DML/redshift.js
lib/Drivers/DML/redshift.js
var util = require("util"); var postgres = require("./postgres"); exports.Driver = Driver; function Driver(config, connection, opts) { postgres.Driver.call(this, config, connection, opts); } util.inherits(Driver, postgres.Driver); Driver.prototype.insert = function (table, data, id_prop, cb) { var q = this.query.insert() .into(table) .set(data) .build(); if (this.opts.debug) { require("../../Debug").sql('postgres', q); } this.db.query(q, function (err, result) { if (err) { return cb(err); } this.db.query("SELECT LASTVAL() AS id", function (err, result) { return cb(null, { id: !err && result.rows[0].id || null }); }); }.bind(this)); };
JavaScript
0
@@ -492,28 +492,29 @@ );%0A%09%7D%0A%09this. -db.q +execQ uery(q, func @@ -582,12 +582,13 @@ his. -db.q +execQ uery @@ -631,24 +631,25 @@ (err, result +s ) %7B%0A%09%09%09retur @@ -687,12 +687,8 @@ sult -.row s%5B0%5D
4883c2f905f5fffc5b1f94052766a82620495591
Remove duplicated parsing code
quest-checker/hiscores.js
quest-checker/hiscores.js
'use strict'; var express = require('express'); var parser = require('body-parser'); var http = require('http'); var app = express(); app.use(parser.urlencoded({ extended: true })); app.use(parser.json()); var port = process.env.PORT || 3000; var router = express.Router(); router.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE'); console.log(req.method + ' ' + req.url); next(); }); var hiscoresUrl = 'http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player='; router.route('/stats/:username').get(function (req, res) { getStats(req.params.username, function (data) { if (data.length === 0) { return res.status(404).json({ message: 'Player not found.' }); } var skills = ['overall', 'attack', 'defence', 'strength', 'constitution', 'ranged', 'prayer', 'magic', 'cooking', 'woodcutting', 'fletching', 'fishing', 'firemaking', 'crafting', 'smithing', 'mining', 'herblore', 'agility', 'thieving', 'slayer', 'farming', 'runecrafting', 'hunter', 'construction']; var raw = data.join().split('\n'); var stats = {}; for (var i in skills) { var row = raw[i].split(','); stats[skills[i]] = { rank: row[0], level: row[1], xp: row[2] }; } return res.status(200).json(stats); }); function getStats(username, callback) { http.get(hiscoresUrl + username, function (res) { var data = []; res.on('data', function (chunk) { data.push(chunk); }); res.on('end', function () { if (res.statusCode === 404) { data = []; } callback(data); }); }).end(); } }); function extractStats(raw) { var stats = {}; var skills = ['overall', 'attack', 'defence', 'strength', 'constitution', 'ranged', 'prayer', 'magic', 'cooking', 'woodcutting', 'fletching', 'fishing', 'firemaking', 'crafting', 'smithing', 'mining', 'herblore', 'agility', 'thieving', 'slayer', 'farming', 'runecrafting', 'hunter', 'construction']; for (var i in skills) { var row = raw[i].split(','); stats[skills[i]] = { rank: row[0], level: row[1], xp: row[2] }; } return stats; } app.use('/', router); app.listen(port); console.log('Running on localhost:' + port);
JavaScript
0.000823
@@ -1962,573 +1962,8 @@ );%0A%0A -function extractStats(raw) %7B%0A var stats = %7B%7D;%0A%0A var skills = %5B'overall', 'attack', 'defence', 'strength', 'constitution', 'ranged', 'prayer', 'magic', 'cooking', 'woodcutting', 'fletching', 'fishing', 'firemaking', 'crafting', 'smithing', 'mining', 'herblore', 'agility', 'thieving', 'slayer', 'farming', 'runecrafting', 'hunter', 'construction'%5D;%0A%0A for (var i in skills) %7B%0A var row = raw%5Bi%5D.split(',');%0A%0A stats%5Bskills%5Bi%5D%5D = %7B%0A rank: row%5B0%5D,%0A level: row%5B1%5D,%0A xp: row%5B2%5D%0A %7D;%0A %7D%0A%0A return stats;%0A%7D%0A%0A app.
3bb323ebd9461e69f21cf58351f9c689ae5d5385
Update game.js
javascripts/game.js
javascripts/game.js
var money = 10; var tickSpeedCost = 1000; var tickspeed = 1000; var firstCost = 10; var secondCost = 100; var thirdCost = 10000; var fourthCost = 1000000; var firstAmount = 0; var secondAmount = 0; var thirdAmount = 0; var fourthAmount = 0; var interval; function updateMoney() { var element = document.getElementById("coinAmount"); element.innerHTML = 'You have ' + shorten(Math.round(money * 10) /10) + ' antimatter.' } function updateCoinPerSec() { var element = document.getElementById("coinsPerSec") element.innerHTML = 'You are getting ' + shorten(Math.round(firstAmount*(1000/tickspeed)*10)/10) + ' antimatter per second.' } function updateDimensions() { document.getElementById("firstAmount").innerHTML = shorten(firstAmount); document.getElementById("secondAmount").innerHTML = shorten(secondAmount); document.getElementById("thirdAmount").innerHTML = shorten(thirdAmount); document.getElementById("fourthAmount").innerHTML = shorten(fourthAmount); } function updateInterval() { clearInterval(interval) interval = setInterval(function() { firstAmount += secondAmount; secondAmount += thirdAmount; thirdAmount += fourthAmount; updateDimensions(); }, tickspeed*10); } function updateCosts() { document.getElementById("third").innerHTML = 'Cost ' + shorten(thirdCost) document.getElementById("fourth").innerHTML = 'Cost ' + shorten(fourthCost) } function shorten(x) { if (x < 1000) return x; else if (x < 1000000) return Math.round(x/1000 * 100)/100 + ' K'; else if (x < 1000000000) return Math.round(x/1000000 * 100)/100 + ' M'; else if (x < 1000000000000) return Math.round(x/1000000000 * 100)/100 + ' B'; } document.getElementById("tickSpeed").onclick = function() { if (money >= tickSpeedCost) { money -= tickSpeedCost; tickspeed = tickspeed * .9; tickSpeedCost = tickSpeedCost*5; document.getElementById("tickSpeedAmount").innerHTML = 'Tickspeed: ' + tickspeed; document.getElementById("tickSpeed").innerHTML = 'Cost: ' + shorten(tickSpeedCost); updateMoney(); updateInterval(); } } document.getElementById("first").onclick = function() { if (money >= firstCost) { firstAmount++; money -= firstCost; firstCost = Math.round(firstCost*1.15 * 10) / 10; updateCoinPerSec(); var element = document.getElementById("first"); element.innerHTML = 'Cost: ' + shorten(firstCost); updateMoney(); document.getElementById("firstAmount").innerHTML = firstAmount; } } document.getElementById("second").onclick = function() { if (money >= secondCost) { secondAmount++; money -= secondCost; secondCost = Math.round(secondCost*1.15 * 10) / 10; updateCoinPerSec(); var element = document.getElementById("second"); element.innerHTML = 'Cost: ' + shorten(secondCost); updateMoney(); document.getElementById("secondAmount").innerHTML = secondAmount; } } document.getElementById("third").onclick = function() { if (money >= thirdCost) { thirdAmount++; money -= thirdCost; thirdCost = Math.round(thirdCost * 1.15 * 10) / 10; updateCoinPerSec(); var element = document.getElementById("third"); element.innerHTML = 'Cost: ' + shorten(thirdCost); updateMoney(); document.getElementById("thirdAmount").innerHTML = thirdAmount; } } document.getElementById("fourth").onclick = function() { if (money >= fourthCost) { fourthAmount++; money -= fourthCost; fourthCost = Math.round(fourthCost * 1.15 * 10) / 10; updateCoinPerSec(); var element = document.getElementById("fourth"); element.innerHTML = 'Fourth Dimension: ' + shorten(fourthCost); updateMoney(); document.getElementById("fourthAmount").innerHTML = fourthAmount; } } setInterval(function() { money += firstAmount/(tickspeed/100); updateMoney(); updateCoinPerSec();; }, 100); updateCosts(); updateInterval();
JavaScript
0.000001
@@ -248,16 +248,224 @@ terval;%0A +var firstButton = document.getElementById(%22first%22)%0Avar secondButton = document.getElementById(%22second%22)%0Avar thirdButton = document.getElementById(%22third%22)%0Avar fourthButton = document.getElementById(%22fourth%22)%0A function @@ -1574,24 +1574,25 @@ rthCost)%0A%7D%0A%0A +%0A function sho @@ -3966,17 +3966,16 @@ erSec(); -; %0A%7D, 100)
774ee22bda918b0255f71297d3e7f2010e1a6c16
Use correct GCF URL in Slack sample (#1756)
functions/slack/index.js
functions/slack/index.js
// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; // [START functions_slack_setup] const {google} = require('googleapis'); const {verifyRequestSignature} = require('@slack/events-api'); // Get a reference to the Knowledge Graph Search component const kgsearch = google.kgsearch('v1'); // [END functions_slack_setup] // [START functions_slack_format] /** * Format the Knowledge Graph API response into a richly formatted Slack message. * * @param {string} query The user's search query. * @param {object} response The response from the Knowledge Graph API. * @returns {object} The formatted message. */ const formatSlackMessage = (query, response) => { let entity; // Extract the first entity from the result list, if any if ( response && response.data && response.data.itemListElement && response.data.itemListElement.length > 0 ) { entity = response.data.itemListElement[0].result; } // Prepare a rich Slack message // See https://api.slack.com/docs/message-formatting const slackMessage = { response_type: 'in_channel', text: `Query: ${query}`, attachments: [], }; if (entity) { const attachment = { color: '#3367d6', }; if (entity.name) { attachment.title = entity.name; if (entity.description) { attachment.title = `${attachment.title}: ${entity.description}`; } } if (entity.detailedDescription) { if (entity.detailedDescription.url) { attachment.title_link = entity.detailedDescription.url; } if (entity.detailedDescription.articleBody) { attachment.text = entity.detailedDescription.articleBody; } } if (entity.image && entity.image.contentUrl) { attachment.image_url = entity.image.contentUrl; } slackMessage.attachments.push(attachment); } else { slackMessage.attachments.push({ text: 'No results match your query...', }); } return slackMessage; }; // [END functions_slack_format] // [START functions_verify_webhook] /** * Verify that the webhook request came from Slack. * * @param {object} req Cloud Function request object. * @param {string} req.headers Headers Slack SDK uses to authenticate request. * @param {string} req.rawBody Raw body of webhook request to check signature against. */ const verifyWebhook = (req) => { const signature = { signingSecret: process.env.SLACK_SECRET, requestSignature: req.headers['x-slack-signature'], requestTimestamp: req.headers['x-slack-request-timestamp'], body: req.rawBody, }; if (!verifyRequestSignature(signature)) { const error = new Error('Invalid credentials'); error.code = 401; throw error; } }; // [END functions_verify_webhook] // [START functions_slack_request] /** * Send the user's search query to the Knowledge Graph API. * * @param {string} query The user's search query. */ const makeSearchRequest = (query) => { return new Promise((resolve, reject) => { kgsearch.entities.search( { auth: process.env.KG_API_KEY, query: query, limit: 1, }, (err, response) => { console.log(err); if (err) { reject(err); return; } // Return a formatted message resolve(formatSlackMessage(query, response)); } ); }); }; // [END functions_slack_request] // [START functions_slack_search] /** * Receive a Slash Command request from Slack. * * Trigger this function by creating a Slack slash command with this URL: * https://[YOUR_REGION].[YOUR_PROJECT_ID].cloudfunctions.net/kgsearch * * @param {object} req Cloud Function request object. * @param {object} req.body The request payload. * @param {string} req.rawBody Raw request payload used to validate Slack's message signature. * @param {string} req.body.text The user's search query. * @param {object} res Cloud Function response object. */ exports.kgSearch = async (req, res) => { try { if (req.method !== 'POST') { const error = new Error('Only POST requests are accepted'); error.code = 405; throw error; } // Verify that this request came from Slack verifyWebhook(req); // Make the request to the Knowledge Graph Search API const response = await makeSearchRequest(req.body.text); // Send the formatted message back to Slack res.json(response); return Promise.resolve(); } catch (err) { console.error(err); res.status(err.code || 500).send(err); return Promise.reject(err); } }; // [END functions_slack_search]
JavaScript
0
@@ -4105,17 +4105,17 @@ _REGION%5D -. +- %5BYOUR_PR @@ -4145,17 +4145,17 @@ s.net/kg -s +S earch%0A *
435c6c453944f495ea09ab1ee9e805abbb6d9083
Update CHANGELOG.js
src/parser/priest/holy/CHANGELOG.js
src/parser/priest/holy/CHANGELOG.js
import React from 'react'; import { Khadaj, niseko, Yajinni, Zerotorescue, blazyb } from 'CONTRIBUTORS'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; import { change, date } from 'common/changelog'; export default [ change(date(2019, 8, 6), 'Added essence Lucid Dreams.', [blazyb]), change(date(2019, 4, 9), <>Adding Holy Nova card and updating spreadsheet</>, [Khadaj]), change(date(2019, 3, 12), <>Fixed an error in the <SpellLink id={SPELLS.PRAYERFUL_LITANY.id} /> analyzer.</>, [Zerotorescue]), change(date(2018, 12, 18), <>Adding <SpellLink id={SPELLS.PROMISE_OF_DELIVERANCE.id} /> and <SpellLink id={SPELLS.DEATH_DENIED.id} />.</>, [Khadaj]), change(date(2018, 11, 5), 'Adding Renew suggestion.', [Khadaj]), change(date(2018, 10, 22), 'Adding mana efficiency tab.', [Khadaj]), change(date(2018, 9, 13), 'Adding Holy Priest Azerite traits.', [Khadaj]), change(date(2018, 9, 7), 'Creating Holy Priest spreadsheet export.', [Khadaj]), change(date(2018, 9, 6), 'Updating base Holy Priest checklist.', [Khadaj]), change(date(2018, 7, 28), <>Added suggestion for maintaining <SpellLink id={SPELLS.PERSEVERANCE_TALENT.id} /> and <SpellLink id={SPELLS.POWER_WORD_FORTITUDE.id} /> buffs.</>, [Yajinni]), change(date(2018, 7, 28), <>Added Stat box for <SpellLink id={SPELLS.COSMIC_RIPPLE_TALENT.id} />.</>, [Yajinni]), change(date(2018, 7, 26), <>Added Stat box for <SpellLink id={SPELLS.TRAIL_OF_LIGHT_TALENT.id} />.</>, [Yajinni]), change(date(2018, 7, 5), 'Updated Holy Priest spells for BFA and accounted for Holy Words cooldown reductions.', [niseko]), ];
JavaScript
0.000001
@@ -267,17 +267,18 @@ 019, 8, -6 +12 ), 'Adde
3348acadd2f9da7aaf47b9bfa26feef873dfea45
add navbar component
resources/assets/components/Wimf/WimfNavbar.js
resources/assets/components/Wimf/WimfNavbar.js
import React from 'react'; import { connect } from 'react-redux'; import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap'; const mapStateToProps = ({ user }) => { return { user }; } const WimfNavbar = ({ user }) => ( <Navbar inverse> <Navbar.Header> <Navbar.Brand> <a href="#">What&apos;s in my Freezer?</a> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavItem eventKey={1} href="#">Link</NavItem> <NavItem eventKey={2} href="#">Link</NavItem> </Nav> <Nav pullRight> <NavItem eventKey={1} href="#">Link Right</NavItem> <NavDropdown eventKey={3} title={user.name} id="basic-nav-dropdown"> <MenuItem eventKey={3.1}>Action</MenuItem> <MenuItem eventKey={3.2}>Another action</MenuItem> <MenuItem eventKey={3.3}>Something else here</MenuItem> <MenuItem divider /> <MenuItem eventKey={3.3}>Separated link</MenuItem> </NavDropdown> </Nav> </Navbar.Collapse> </Navbar> ); export default connect(mapStateToProps)(WimfNavbar);
JavaScript
0.000001
@@ -773,14 +773,41 @@ .1%7D%3E -Action +%3Ca href='/auth/logout'%3ELogout%3C/a%3E %3C/Me @@ -1108,16 +1108,17 @@ ar%3E%0A);%0A%0A +%0A export d
6a05a93c0aa2f6372c48834aa3d4e78226efe679
Remove open from deploy task
gulpfile.js/tasks/deploy.js
gulpfile.js/tasks/deploy.js
var ghPages = require('gulp-gh-pages') var gulp = require('gulp') var open = require('open') var os = require('os') var path = require('path') var deployTask = function() { var pkg = require(path.resolve(process.env.PWD, 'package.json')) var settings = { url: pkg.homepage, src: path.resolve(process.env.PWD, PATH_CONFIG.dest, '**/*'), ghPages: { cacheDir: path.join(os.tmpdir(), pkg.name) } } return gulp.src(settings.src) .pipe(ghPages(settings.ghPages)) .on('end', function(){ open(settings.url) }) } gulp.task('deploy', ['production'], deployTask) module.exports = deployTask
JavaScript
0.000002
@@ -66,38 +66,8 @@ p')%0A -var open = require('open')%0A var @@ -86,24 +86,24 @@ quire('os')%0A + var path @@ -312,17 +312,22 @@ _CONFIG. -d +finalD est, '** @@ -439,16 +439,16 @@ gs.src)%0A + .pip @@ -480,67 +480,8 @@ s))%0A - .on('end', function()%7B%0A open(settings.url)%0A %7D)%0A %7D%0A%0Ag
1f952d72518d4a5958f33b17521cffff5830760f
test for correct port and host passing
spec/sequelize.spec.js
spec/sequelize.spec.js
var config = require("./config/config") , Sequelize = require("../index") describe('Sequelize', function() { it('should pass the global options correctly', function() { var sequelize = new Sequelize(config.database, config.username, config.password, { logging: false, define: { underscored:true } }) var Model = sequelize.define('model', {name: Sequelize.STRING}) expect(Model.options.underscored).toBeTruthy() }) })
JavaScript
0
@@ -444,12 +444,343 @@ y()%0A %7D) +%0A%0A it('should correctly set the host and the port', function() %7B%0A var options = %7B host: '127.0.0.1', port: 1234 %7D%0A , sequelize = new Sequelize(config.database, config.username, config.password, options)%0A%0A expect(sequelize.config.host).toEqual(options.host)%0A expect(sequelize.config.port).toEqual(options.port)%0A %7D) %0A%7D)%0A
e8a0e33b389dd7f19454d647996178ab7fee76cb
test changes
src/rules/comment-no-loud/__tests__/index.js
src/rules/comment-no-loud/__tests__/index.js
import rule, { ruleName, messages } from ".."; testRule(rule, { ruleName, config: [true], syntax: "scss", accept: [ { code: "// comment", description: "Double slash comments" } ], reject: [ { code: ` /* comment */ `, description: "One line with optional ending", message: messages.expected }, { code: "/* comment", description: "One line with no ending", message: messages.expected }, { code: ` /* comment line 1 comment line 2 `, description: "Multline comment with no ending", message: messages.expected }, { code: ` /* comment line 1 comment line 2 */ `, description: "Multline comment with optional ending on next line", message: messages.expected } ] });
JavaScript
0.000001
@@ -366,300 +366,8 @@ %7B%0A - code: %22/* comment%22,%0A description: %22One line with no ending%22,%0A message: messages.expected%0A %7D,%0A %7B%0A code: %60%0A /* comment line 1%0A comment line 2 %0A %60,%0A description: %22Multline comment with no ending%22,%0A message: messages.expected%0A %7D,%0A %7B%0A
7a99bf6379232d4d2481e4f57d766b2ddd03ac65
Allow transformations to tooltip name & value
react-chartist-tooltip.js
react-chartist-tooltip.js
import React from 'react'; import Chartist from 'chartist'; import classnames from 'classnames'; export default class Chart extends React.Component { constructor(props) { super(props); this.state = { datapoint: { name: '', value: '', }, tooltip: { top: 0, left: 0 } }; this.onMouseOver = this.onMouseOver.bind(this); } componentDidMount() { this.updateChart(this.props); } componentWillReceiveProps(newProps) { this.updateChart(newProps); } componentWillUnmount() { this.chartist.detach(); } render() { return ( <div style = {{ position: 'relative' }}> <div ref = "chart" className = {classnames('ct-chart', this.props.classnames)} onMouseOver = {this.onMouseOver}></div> <div ref = "tooltip" className = {['ct-tooltip', this.state.tooltip.classname].join(' ').trim()} style = {{ position: 'absolute', top: this.state.tooltip.top, left: this.state.tooltip.left, padding: '0.25rem 1rem', border: '1px #fff solid', textAlign: 'center', fontSize: 12, lineHeight: 1.4, color: '#fff', opacity: 0.75 }}> <div className = "ct-tooltip-name">{this.state.datapoint.name}</div> <div className = "ct-tooltip-value">{this.state.datapoint.value}</div> </div> </div> ); } updateChart(props) { const {type, data, options = {}, responsiveOptions = [], events = {}} = props, create = () => { this.chartist = new Chartist[type](React.findDOMNode(this.refs.chart), data, options, responsiveOptions); Object.keys(events).forEach(x => this.chartist.on(x, events[x].bind(this.chartist))); }; this.chartist ? this.chartist.update(data, options, true) : data.series ? create() : null; } onMouseOver({target}) { let $parent = target.parentNode; const targetRect = target.getBoundingClientRect(), chartRect = React.findDOMNode(this.refs.chart).getBoundingClientRect(), tooltipRect = React.findDOMNode(this.refs.tooltip).getBoundingClientRect(), name = $parent.attributes['ct:series-name'], value = target.attributes['ct:value']; value && this.setState({ datapoint: { name: name ? name.value : '', value: value.value }, tooltip: { classname: `ct-tooltip-${$parent.classList[1].substr(3)}`, top: targetRect.top - chartRect.top - tooltipRect.height, left: targetRect.left - chartRect.left - 1 } }); } } Chart.propTypes = { type: React.PropTypes.string.isRequired, classnames: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.object ]), data: React.PropTypes.shape({ labels: React.PropTypes.array, series: React.PropTypes.array }), options: React.PropTypes.object, responsiveOptions: React.PropTypes.array, events: React.PropTypes.object };
JavaScript
0.000001
@@ -91,16 +91,42 @@ ames';%0A%0A +const identity = x =%3E x;%0A%0A export d @@ -627,24 +627,81 @@ render() %7B%0A + let props = this.props,%0A state = this.state;%0A%0A return ( @@ -848,21 +848,16 @@ chart', -this. props.cl @@ -990,21 +990,16 @@ oltip', -this. state.to @@ -1114,21 +1114,16 @@ top: -this. state.to @@ -1154,21 +1154,16 @@ left: -this. state.to @@ -1470,29 +1470,67 @@ ltip-name%22%3E%7B -this. +(props.tooltip.transform.name %7C%7C identity)( state.datapo @@ -1537,16 +1537,17 @@ int.name +) %7D%3C/div%3E%0A @@ -1593,21 +1593,60 @@ value%22%3E%7B -this. +(props.tooltip.transform.value %7C%7C identity)( state.da @@ -1658,16 +1658,17 @@ nt.value +) %7D%3C/div%3E%0A @@ -1760,21 +1760,16 @@ options - = %7B%7D , respon @@ -1783,21 +1783,16 @@ ions - = %5B%5D , events = %7B @@ -1791,13 +1791,8 @@ ents - = %7B%7D %7D = @@ -3376,12 +3376,332 @@ s.object +,%0A tooltip: React.PropTypes.shape(%7B%0A transform: React.PropTypes.shape(%7B%0A name: React.PropTypes.func,%0A value: React.PropTypes.func%0A %7D)%0A %7D)%0A%7D;%0A%0AChart.defaultProps = %7B%0A options: %7B%7D,%0A responsiveOptions: %5B%5D,%0A events: %7B%7D,%0A tooltip: %7B%0A transform: %7B%0A name: identity,%0A value: identity%0A %7D%0A %7D %0A%7D;%0A
2288da6141bbf53ded67892c83a8ff55ec2cfbac
Use custom success handler for saving list of subscribers
src/apps/omis/apps/edit/controllers/subscribers.js
src/apps/omis/apps/edit/controllers/subscribers.js
const { sortBy } = require('lodash') const { EditController } = require('../../../controllers') const { getAdvisers } = require('../../../../adviser/repos') const { transformObjectToOption } = require('../../../../transformers') class EditSubscribersController extends EditController { async configure (req, res, next) { const advisers = await getAdvisers(req.session.token) const options = advisers.results.map(transformObjectToOption) req.form.options.fields.subscribers.options = sortBy(options, 'label') super.configure(req, res, next) } } module.exports = EditSubscribersController
JavaScript
0
@@ -7,16 +7,22 @@ %7B sortBy +, pick %7D = req @@ -36,16 +36,16 @@ odash')%0A - %0Aconst %7B @@ -188,16 +188,37 @@ ToOption +, transformIdToObject %7D = req @@ -249,16 +249,61 @@ ormers') +%0Aconst %7B Order %7D = require('../../../models') %0A%0Aclass @@ -590,16 +590,16 @@ label')%0A - supe @@ -629,16 +629,585 @@ ext)%0A %7D +%0A%0A async successHandler (req, res, next) %7B%0A const data = pick(req.sessionModel.toJSON(), Object.keys(req.form.options.fields))%0A const subscribers = data.subscribers.map(transformIdToObject)%0A%0A try %7B%0A await Order.saveSubscribers(req.session.token, res.locals.order.id, subscribers)%0A%0A req.journeyModel.reset()%0A req.journeyModel.destroy()%0A req.sessionModel.reset()%0A req.sessionModel.destroy()%0A%0A req.flash('success', 'Order updated')%0A res.redirect(%60/omis/$%7Bres.locals.order.id%7D%60)%0A %7D catch (error) %7B%0A next(error)%0A %7D%0A %7D %0A%7D%0A%0Amodu
42fdedf6ee23c04b33410e2ff1a54043dd29ac8c
save teardown state
tests/mocks/sw-toolbox.js
tests/mocks/sw-toolbox.js
/*** * Copyright (c) 2015, 2016 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. * * A simple mock for sw-toolbox. * * Intended for use via mockery (or equiv) as a configurable drop-in that loads * in-place of sw-toolbox so modules that use it can be tested in NodeJS unit * tests. * * Assumes NodeJS >= 4 (stable) * * After the mock substitution is setup, the test must also get a reference * to the mock (and prime the require cache) to call mockSetup. mockSetup must * be called at least once to create the sw-toolbox interface. * @see mockSetup * * Reuses sw-toolbox/lib/options, sw-toolbox/lib/router as-is. */ /* global Promise */ 'use strict'; var urlLib = require('url'); var teardown = { self: false, url: false }; var cleanOptions; var mockCacheObject; var mockCacheValue = 'dummy'; /** * A mock strategy to reject or resolve. * * @param {Object} response - A response to resolve to, must pre-bind. * @param {Any} request - ignored. * @param {Any} values - ignored. * @param {Object} options - The sw-toolbox options passed to strategy. * @param {Boolean} [options.emulateError] - Set to test reject path. */ function mockStrategy (response, request, values, options) { if (options.emulateError) { return Promise.reject(new Error('mock error')); } return Promise.resolve(response); } /** * Mock cache implementation. * * @param {String|Request} request - The item to cache. * @returns {Promise} Always resolves to undefined. */ function mockCache (request) { var urlString = typeof request === 'string' ? request : request.url; mockCacheObject[urlString] = mockCacheValue; return Promise.resolve(); } /** * Mock uncache implementation. * * @param {String|Request} request - The item to delete from cache. * @returns {Promise} Resolves to true if the item was deleted, false otherwise. */ function mockUncache (request) { var urlString = typeof request === 'string' ? request : request.url; var hit = mockCacheObject[urlString] === mockCacheValue; if (hit) { delete mockCacheObject[urlString]; } return Promise.resolve(hit); } /** * Simplified mock URL constructor for global mock purpose. * * @param {String} urlString - An absolute or relative url. * @param {String|Object} [base] - if urlString is relative, a string or url * object to resolve the urlString on. */ function MockURL (urlString, base) { var baseUrlString; if (!base || urlString.indexOf(':') !== -1) { baseUrlString = urlString; urlString = ''; } else { baseUrlString = typeof base === 'string' ? base : base.href; } this.href = urlLib.resolve(baseUrlString, urlString); var urlObj = urlLib.parse(this.href, true, this.href.indexOf(':') === -1); this.pathname = urlObj.pathname; this.port = urlObj.port; this.protocol = urlObj.protocol || 'http:'; this.hash = urlObj.hash; this.origin = this.protocol + (urlObj.slashes ? '//' : '') + urlObj.host; } /** * Setup global prerequisites for the re-used modules of sw-toolbox. * * @param {String} scope - The scope for sw-toolbox. */ function setupGlobals (scope) { // This is required to re-use sw-toolbox/lib/options global.self = global.self || (teardown.self = true, {}); global.self.scope = scope || global.self.scope || 'http://localhost'; // This is required to re-use sw-toolbox/lib/router global.URL = global.URL || (teardown.url = true, MockURL); global.self.location = global.self.location || new global.URL('/', global.self.scope); } module.exports = { /** * Call to setup and configure the sw-toolbox mock interface. * MUST be called at least once to create the sw-toolbox mock interface. * Can be called repeatedly to change handler responses, scope, or options. * * @param {Object} [response] - The response any strategies will resolve to. * Actually can be any type/value of use to the test. * @param {String} [scope] - A scope to use for sw-toolbox purposes. defaults * to 'http://localhost'. * @param {Object} [options] - options to substitute in sw-toolbox options. */ mockSetup: function mockSetup (response, scope, options) { setupGlobals(scope); // First time only, keep a clean copy of the global, mutable options. if (!cleanOptions) { cleanOptions = Object.assign({}, require('sw-toolbox/lib/options')); } // Reset the global toolbox options, mixin changes, expose the result var dirtyOptions = require('sw-toolbox/lib/options'); options = Object.assign( Object.assign(dirtyOptions, cleanOptions), options || {} ); // Clear the route map var router = require('sw-toolbox/lib/router'); router.routes.clear(); // Clear/create the mockCache mockCacheObject = Object.create(null); // Mock the sw-toolbox interface this.cacheFirst = this.cacheOnly = this.networkFirst = this.networkOnly = this.fastest = mockStrategy.bind(this, response); this.router = router; this.options = options; this.cache = mockCache; this.uncache = mockUncache; // Can't use orig b/c we can't load sw-toolbox main w/o mocking its deps. this.precache = function (items) { if (!Array.isArray(items)) { items = [items]; } this.options.preCacheItems = this.options.preCacheItems.concat(items); }; }, /** * Cleanup globals created during setup (optional). */ mockTeardown: function mockTeardown () { if (teardown.self) { delete global.self; } if (teardown.url) { delete global.URL; } }, /** * Fetch driver. Must call mockSetup first. * * @param {String|Request} url - The url to use to drive a test. * @param {String} [method] - if url is a string, supply this method. * Defaults to 'any'. * @returns {Promise} resolves or rejects as configured. If no handler is * found, resolves to undefined. */ mockFetch: function mockFetch (url, method) { if (!this.router) { throw new Error('Must call mockSetup before mockFetch'); } var request = typeof url === 'string' ? { url: url, method: method || 'any' } : url; var response, handler = this.router.match(request); if (handler) { response = handler(request); } else if (this.router.default && request.method === 'GET') { response = this.router.default(request); } return response || Promise.resolve(); } };
JavaScript
0
@@ -5559,24 +5559,53 @@ own.self) %7B%0A + teardown.self = false;%0A delete @@ -5644,24 +5644,52 @@ down.url) %7B%0A + teardown.url = false;%0A delete
1ed5c1c2141e64056d6264e9dceb4e113a9a5ec9
Add debug messages for missing strings.
packages/vulcan-lib/lib/modules/intl.js
packages/vulcan-lib/lib/modules/intl.js
import SimpleSchema from 'simpl-schema'; import { getSetting } from '../modules/settings'; export const Strings = {}; export const Domains = {}; export const addStrings = (language, strings) => { if (typeof Strings[language] === 'undefined') { Strings[language] = {}; } Strings[language] = { ...Strings[language], ...strings }; }; export const getString = ({id, values, defaultMessage, locale}) => { const messages = Strings[locale] || Strings[defaultLocale] || {}; let message = messages[id] || defaultMessage; if (message && values) { Object.keys(values).forEach(key => { // note: see replaceAll definition in vulcan:lib/utils message = message.replaceAll(`{${key}}`, values[key]); }); } return message; }; export const registerDomain = (locale, domain) => { Domains[domain] = locale; }; export const defaultLocale = getSetting('locale', 'en'); export const Locales = []; export const registerLocale = locale => { Locales.push(locale); }; /* Look for type name in a few different places Note: look into simplifying this */ export const isIntlField = fieldSchema => { return fieldSchema.intl; }; /* Generate custom IntlString SimpleSchema type */ export const getIntlString = () => { const schema = { locale: { type: String, optional: true }, value: { type: String, optional: true } }; const IntlString = new SimpleSchema(schema); IntlString.name = 'IntlString'; return IntlString; }; /* Check if a schema has at least one intl field */ export const schemaHasIntlFields = schema => Object.keys(schema).some(fieldName => isIntlField(schema[fieldName])); /* Custom validation function to check for required locales See https://github.com/aldeed/simple-schema-js#custom-field-validation */ export const validateIntlField = function() { let errors = []; // go through locales to check which one are required const requiredLocales = Locales.filter(locale => locale.required); requiredLocales.forEach((locale, index) => { const strings = this.value; const hasString = strings && Array.isArray(strings) && strings.some(s => s && s.locale === locale.id && s.value); if (!hasString) { const originalFieldName = this.key.replace('_intl', ''); errors.push({ id: 'errors.required', path: `${this.key}.${index}`, properties: { name: originalFieldName, locale: locale.id } }); } }); if (errors.length > 0) { // hack to work around the fact that custom validation function can only return a single string return `intlError|${JSON.stringify(errors)}`; } };
JavaScript
0
@@ -83,16 +83,59 @@ ttings'; +%0Aimport %7B debug %7D from 'meteor/vulcan:lib'; %0A%0Aexport @@ -502,85 +502,461 @@ %7C%7C -Strings%5BdefaultLocale%5D %7C%7C %7B%7D +%7B%7D;%0A let message = messages%5Bid%5D;%0A%0A // use default locale%0A if(!message) %7B%0A debug(%60%5Cx1b%5B32m%3E%3E INTL: No string found for id %22$%7Bid%7D%22 in locale %22$%7Blocale%7D%22.%5Cx1b%5B0m%60);%0A message = Strings%5BdefaultLocale%5D && Strings%5BdefaultLocale%5D%5Bid%5D ;%0A +%0A -let message = messages%5Bid%5D %7C%7C defaultMessage; + // if default locale hasn't got the message too%0A if(!message && locale !== defaultLocale)%0A debug(%60%5Cx1b%5B32m%3E%3E INTL: No string found for id %22$%7Bid%7D%22 in the default locale (%22$%7BdefaultLocale%7D%22).%5Cx1b%5B0m%60);%0A %7D%0A %0A i
c103fbabc6422a37f24df845a7cd9e1dd80b1696
Set google satelite as the default layer
app/Map.js
app/Map.js
//a wrapper around leaflet that configures it as well var map_config=require('../config/map-config'); var path=require('path'); var MapDraw=require('./models/MapDraw'); var MapMeasure=require('./models/MapMeasure'); var MapPath=require('./models/MapPath'); var Map=function(L){ var leaflet=L;//reference to the window leaflet object var map=null; var mapPath= new MapPath(leaflet); //Set up paths var tiles_path=path.join(__dirname,'../assets/sat_tiles'); var images_path=path.join(__dirname,'../assets/images'); leaflet.Icon.Default.imagePath = path.join(__dirname,'../assets/leaflet'); var base_layers={}; var overlay_layers={}; base_layers['Satellite']=leaflet.tileLayer(tiles_path+'/{z}/{x}/{y}.png', { maxZoom: 19 }); base_layers['Streets']=leaflet.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }); base_layers['Google Satellite']=new leaflet.Google('SATELLITE'); overlay_layers['Plane']=new leaflet.RotatedMarker(map_config.get('default_lat_lang'), { icon: leaflet.icon({ iconUrl: images_path+'/plane.png', iconSize: [30, 30] }) }); overlay_layers['Plane Trail']=new leaflet.Polyline([], { color: '#190019', opacity: 0.6, weight: 5, clickable: true, }); var centerToPlaneButton=L.easyButton( 'icon ion-pinpoint', function(){ if (overlay_layers['Plane']) { map.panTo(overlay_layers['Plane'].getLatLng()); } }); this.createMap=function(id){ map = leaflet.map(id,{ center: map_config.get('default_lat_lang'), zoom: 17, layers: [base_layers['Satellite'], overlay_layers['Plane'],overlay_layers['Plane Trail']] //the default layers of the map }); //allow the user to turn on and off specific layers leaflet.control.layers(base_layers, overlay_layers).addTo(map); leaflet.control.mousePosition().addTo(map); //displays lat and lon coordinates at bottom left of the map map.addControl(centerToPlaneButton); mapPath.addTo(map); MapMeasure(leaflet).addTo(map); new MapDraw(leaflet).addTo(map); //adds draw controls to map }; this.movePlane=function(lat,lng, heading){ overlay_layers['Plane'].setLatLng([lat,lng]); overlay_layers['Plane'].angle = heading; overlay_layers['Plane'].update(); }; this.expandPlaneTrail=function(lat,lng){ overlay_layers['Plane Trail'].addLatLng([lat,lng]); }; this.clearPlaneTrail=function(){ overlay_layers['Plane Trail'].setLatLngs([]); }; }; module.exports=Map;
JavaScript
0
@@ -1679,32 +1679,39 @@ : %5Bbase_layers%5B' +Google Satellite'%5D, ove
23657a55026f6637bc4a4db1f902e9d2d6ea2355
Delete the databases between tests rather than nuking all entries since that doesn't remove indexes
spec/util/db-helper.js
spec/util/db-helper.js
/* * Helper class for cleaning nedb state */ "use strict"; var Promise = require("bluebird"); var promiseutil = require("../../lib/promiseutil"); var Datastore = require("nedb"); /** * Reset the database, wiping all data. * @param {String} databaseUri : The database URI to wipe all data from. * @return {Promise} Which is resolved when the database has been cleared. */ module.exports._reset = function(databaseUri) { if (databaseUri.indexOf("nedb://") !== 0) { return Promise.reject("Must be nedb:// URI"); } var baseDbName = databaseUri.substring("nedb://".length); function delDatabase(name) { var d = promiseutil.defer(); var db = new Datastore({ filename: baseDbName + name, autoload: true, onload: function() { db.remove({}, {multi: true}, function(err, docs) { if (err) { console.error("db-helper %s Failed to delete: %s", name, err); console.error(err.stack); d.reject(err); return; } d.resolve(docs); }); } }); return d.promise; } return Promise.all([ delDatabase("/rooms.db"), delDatabase("/users.db"), ]); };
JavaScript
0.000001
@@ -85,24 +85,48 @@ bluebird%22);%0A +var fs = require(%22fs%22);%0A var promiseu @@ -664,153 +664,149 @@ ar d - = promiseutil.defer();%0A var db = new Datastore(%7B%0A filename: baseDbName + name,%0A autoload: true,%0A onload: +bPath = baseDbName + name;%0A return new Promise(function(resolve, reject) %7B%0A // nuke the world%0A fs.unlink(dbPath, fun @@ -811,16 +811,19 @@ unction( +err ) %7B%0A @@ -838,226 +838,169 @@ -db.remove(%7B%7D, %7Bmulti: true%7D, function(err, docs) %7B%0A if (err) %7B%0A console.error(%22db-helper %25s Failed to delete: %25s%22, name, err);%0A console.error(err.stack); +if (err) %7B%0A if (err.code == %22ENOENT%22) %7B // already deleted%0A resolve();%0A %7D%0A else %7B %0A @@ -1020,18 +1020,16 @@ -d. reject(e @@ -1057,19 +1057,27 @@ +%7D%0A -return; + %7D %0A @@ -1081,37 +1081,38 @@ - %7D +else %7B %0A @@ -1120,18 +1120,16 @@ -d. resolve( docs @@ -1128,19 +1128,29 @@ lve( -docs );%0A + %7D%0A @@ -1177,46 +1177,19 @@ -%7D%0A %7D);%0A return d.promise +%0A %7D) ;%0A
972e265830b54957a6afb554be45605a76031847
Update the closure slider to have a getThumbCssClass, similar to getCssClass protected method. This allows implementations of this class to have more control over the CSS structure.
closure/goog/ui/slider.js
closure/goog/ui/slider.js
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A slider implementation that allows to select a value within a * range by dragging a thumb. The selected value is exposed through getValue(). * * To decorate, the slider should be bound to an element with the class name * 'goog-slider' containing a child with the class name 'goog-slider-thumb', * whose position is set to relative. * Note that you won't be able to see these elements unless they are styled. * * Slider orientation is horizontal by default. * Use setOrientation(goog.ui.Slider.Orientation.VERTICAL) for a vertical * slider. * * Decorate Example: * <div id="slider" class="goog-slider"> * <div class="goog-slider-thumb"></div> * </div> * * JavaScript code: * <code> * var slider = new goog.ui.Slider; * slider.decorate(document.getElementById('slider')); * </code> * * @author [email protected] (Erik Arvidsson) * @see ../demos/slider.html */ // Implementation note: We implement slider by inheriting from baseslider, // which allows to select sub-ranges within a range using two thumbs. All we do // is we co-locate the two thumbs into one. goog.provide('goog.ui.Slider'); goog.provide('goog.ui.Slider.Orientation'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.ui.SliderBase'); /** * This creates a slider object. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @param {(function(number):?string)=} opt_labelFn An optional function mapping * slider values to a description of the value. * @constructor * @extends {goog.ui.SliderBase} */ goog.ui.Slider = function(opt_domHelper, opt_labelFn) { goog.ui.SliderBase.call(this, opt_domHelper, opt_labelFn); this.rangeModel.setExtent(0); }; goog.inherits(goog.ui.Slider, goog.ui.SliderBase); goog.tagUnsealableClass(goog.ui.Slider); /** * Expose Enum of superclass (representing the orientation of the slider) within * Slider namespace. * * @enum {string} */ goog.ui.Slider.Orientation = goog.ui.SliderBase.Orientation; /** * The prefix we use for the CSS class names for the slider and its elements. * @type {string} */ goog.ui.Slider.CSS_CLASS_PREFIX = goog.getCssName('goog-slider'); /** * CSS class name for the single thumb element. * @type {string} */ goog.ui.Slider.THUMB_CSS_CLASS = goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'thumb'); /** * Returns CSS class applied to the slider element. * @param {goog.ui.SliderBase.Orientation} orient Orientation of the slider. * @return {string} The CSS class applied to the slider element. * @protected * @override */ goog.ui.Slider.prototype.getCssClass = function(orient) { return orient == goog.ui.SliderBase.Orientation.VERTICAL ? goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'vertical') : goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'horizontal'); }; /** @override */ goog.ui.Slider.prototype.createThumbs = function() { // find thumb var element = this.getElement(); var thumb = goog.dom.getElementsByTagNameAndClass( null, goog.ui.Slider.THUMB_CSS_CLASS, element)[0]; if (!thumb) { thumb = this.createThumb_(); element.appendChild(thumb); } this.valueThumb = this.extentThumb = /** @type {!HTMLDivElement} */ (thumb); }; /** * Creates the thumb element. * @return {!HTMLDivElement} The created thumb element. * @private */ goog.ui.Slider.prototype.createThumb_ = function() { var thumb = this.getDomHelper().createDom( goog.dom.TagName.DIV, goog.ui.Slider.THUMB_CSS_CLASS); goog.a11y.aria.setRole(thumb, goog.a11y.aria.Role.BUTTON); return /** @type {!HTMLDivElement} */ (thumb); };
JavaScript
0.000001
@@ -3541,16 +3541,274 @@ );%0A%7D;%0A%0A%0A +/**%0A * Returns CSS class applied to the slider's thumb element.%0A * @return %7Bstring%7D The CSS class applied to the slider's thumb element.%0A * @protected%0A */%0Agoog.ui.Slider.prototype.getThumbCssClass = function() %7B%0A return goog.ui.Slider.THUMB_CSS_CLASS;%0A%7D;%0A%0A%0A /** @ove @@ -3812,24 +3812,24 @@ override */%0A - goog.ui.Slid @@ -3989,38 +3989,31 @@ ll, -goog.ui.Slider.THUMB_CSS_CLASS +this.getThumbCssClass() , el @@ -4428,38 +4428,31 @@ IV, -goog.ui.Slider.THUMB_CSS_CLASS +this.getThumbCssClass() );%0A
0aff44504c01cc1895202f998b783763af4e2b3f
Use a factory function for simple arg-passing actions
src/actions/LessonActions.js
src/actions/LessonActions.js
var { ADD_LESSON, ADD_STEP, DELETE_LESSON, DELETE_STEP, IMPORT_LESSONS, SELECT_LESSON, SELECT_STEP, TOGGLE_EDITING, UPDATE_LESSON, UPDATE_STEP } = require('../ActionTypes') function addLesson() { return { type: ADD_LESSON } } function addStep() { return { type: ADD_STEP } } function deleteLesson() { return { type: DELETE_LESSON } } function deleteStep() { return { type: DELETE_STEP } } function importLessons(lessons) { return { type: IMPORT_LESSONS, lessons } } function selectLesson(lessonIndex) { return { type: SELECT_LESSON, lessonIndex } } function selectStep(stepIndex) { return { type: SELECT_STEP, stepIndex } } function toggleEditing(editing) { return { type: TOGGLE_EDITING, editing } } function updateLesson(update) { return { type: UPDATE_LESSON, update } } function updateStep(update) { return { type: UPDATE_STEP, update } } module.exports = { toggleEditing, addLesson, selectLesson, updateLesson, deleteLesson, importLessons, addStep, selectStep, updateStep, deleteStep }
JavaScript
0.000001
@@ -191,120 +191,233 @@ ')%0A%0A -function addLesson() %7B%0A return %7B%0A type: ADD_LESSON%0A %7D%0A%7D%0A%0Afunction addStep() %7B%0A return %7B%0A type: +var createAction = (type, ...props) =%3E%0A (...args) =%3E%0A props.reduce((action, prop, i) =%3E (action%5Bprop%5D = args%5Bi%5D, action), %7Btype%7D)%0A%0Amodule.exports = %7B%0A addLesson: createAction(ADD_LESSON),%0A addStep: createAction( ADD_STEP %0A %7D @@ -416,63 +416,40 @@ STEP +), %0A -%7D%0A%7D%0A%0Afunction deleteLesson() %7B%0A return %7B%0A type: +deleteLesson: createAction( DELE @@ -461,61 +461,38 @@ SSON +), %0A -%7D%0A%7D%0A%0Afunction deleteStep() %7B%0A return %7B%0A type: +deleteStep: createAction( DELE @@ -502,71 +502,41 @@ STEP +), %0A -%7D%0A%7D%0A%0Afunction importLessons(lessons) %7B%0A return %7B%0A type: +importLessons: createAction( IMPO @@ -550,86 +550,50 @@ ONS, -%0A +' lessons -%0A %7D%0A%7D%0A%0Afunction selectLesson(lessonIndex) %7B%0A return %7B%0A type: +'),%0A selectLesson: createAction( SELE @@ -602,21 +602,18 @@ _LESSON, -%0A +' lessonIn @@ -619,70 +619,39 @@ ndex -%0A %7D%0A%7D%0A%0Afunction selectStep(stepIndex) %7B%0A return %7B%0A type: +'),%0A selectStep: createAction( SELE @@ -658,21 +658,18 @@ CT_STEP, -%0A +' stepInde @@ -673,71 +673,42 @@ ndex -%0A %7D%0A%7D%0A%0Afunction toggleEditing(editing) %7B%0A return %7B%0A type: +'),%0A toggleEditing: createAction( TOGG @@ -722,81 +722,50 @@ ING, -%0A +' editing -%0A %7D%0A%7D%0A%0Afunction updateLesson(update) %7B%0A return %7B%0A type: +'),%0A updateLesson: createAction( UPDA @@ -778,78 +778,47 @@ SON, -%0A +' update -%0A %7D%0A%7D%0A%0Afunction updateStep(update) %7B%0A return %7B%0A type: +'),%0A updateStep: createAction( UPDA @@ -829,177 +829,17 @@ TEP, -%0A +' update -%0A %7D%0A%7D%0A%0Amodule.exports = %7B%0A toggleEditing,%0A addLesson, selectLesson, updateLesson, deleteLesson, importLessons,%0A addStep, selectStep, updateStep, deleteStep +') %0A%7D%0A
d5043fabe8c254287f3a5d0ec328c17239237bc0
Change description
reportcomm.user.js
reportcomm.user.js
// ==UserScript== // @name Reddit Steam Group Comment Reporter // @namespace MilkGames // @version 0.1 // @description More options to delete comments // @author MilkGames -- Royalgamer06 for original script // @match *://steamcommunity.com/groups/reddit* // @grant none // ==/UserScript== (function() { var $comments = jQuery("[class*='commentthread_comment_timestamp']"); if ($comments.length > 0) { $comments.after(' <a class="actionlink repcomment">Report Comment</a><a class="actionlink">'); } jQuery(".repcomment").click(function() { var reason = prompt("Please enter the reason for reporting this comment.", ""); if (reason) { var $this = jQuery(this); var author = $this.parent().find(".commentthread_author_link").attr("data-miniprofile"); var date = $this.parent().find(".commentthread_comment_timestamp").attr("title"); // Ugly code pls no to kill var datatosend = "comment=Author: " + author + "\n" + date + "\nReason: " + reason + "&count=15&sessionid=" + g_sessionID + "&extended_data=%7B%22topic_permissions%22%3A%7B%22can_view%22%3A1%2C%22can_post%22%3A1%2C%22can_reply%22%3A1%2C%22can_moderate%22%3A1%2C%22can_edit_others_posts%22%3A1%2C%22can_purge_topics%22%3A1%2C%22is_banned%22%3A0%2C%22can_delete%22%3A1%2C%22can_edit%22%3A1%7D%2C%22original_poster%22%3A144601510%2C%22forum_appid%22%3A0%2C%22forum_public%22%3A0%2C%22forum_type%22%3A%22General%22%2C%22forum_gidfeature%22%3A%220%22%7D&feature2=1456202492181247164&oldestfirst=true&include_raw=true"; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.open("POST", "http://steamcommunity.com/comment/ForumTopic/post/103582791429796426/864943227215847264/"); xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xhr.send(datatosend); ShowAlertDialog('Thank You!', 'Thank you for reporting a comment to the Reddit Group Moderators. \nYou may view your report <a href="http://steamcommunity.com/groups/reddit/discussions/0/1456202492181247164">here</a>.'); // IT WORKS! ... I hope. } }); })();
JavaScript
0.000004
@@ -133,39 +133,50 @@ on -More opti +Report comments on -s t -o delete comments +he Reddit Steam group. %0A//
1f0b2cf8ece80fd30245807ae4233bbc55ad458a
Update toggle.js
source/utility/toggle.js
source/utility/toggle.js
import acid from '../namespace/index'; import { assign } from '../internal/object'; <<<<<<< HEAD import { isEqual } from './isEqual'; /** * Performs a toggle between 2 values using a deep or strict comparison. ======= import { hasValue } from '../internal/is'; let count = 0; const uuidFree = []; const uuidClosed = {}; /** * Creates a numerical unique ID and recycles old ones. UID numerically ascends however freed UIDs are later reused. >>>>>>> origin/master * * @function uid * @type {Function} <<<<<<< HEAD <<<<<<< HEAD * @param {(string|number|Object|Array)} value - Strictly compared against the on argument. * @param {(string|number|Object|Array)} on - Strictly compared against the value argument. * @param {(string|number|Object|Array)} off - Value to be returned. * @returns {(string|number|Object|Array)} - The opposing value to the current. ======= * @param {(string|number)} value - Strictly compared against the on argument. * @param {(string|number)} on - Strictly compared against the value argument. * @param {(string|number)} off - Value to be returned. * @returns {(string|number)} - The on or off argument. >>>>>>> origin/master ======= * @returns {number} - Returns a unique id. >>>>>>> origin/master * * @example * uid(); * //=> 0 * * uid(); * //=> 1 * * uid.free(0); * //=> undefined * * uid(); * //=> 0 */ export const uid = () => { let result = uuidFree.shift(uuidFree); if (!hasValue(result)) { result = count; uuidClosed[result] = true; count++; } return result; }; /** * Frees an UID so that it may be recycled for later use. * * @function uid * @type {Function} * @param {number} uid - Number to freed. * @returns {undefined} - Nothing is returned. * * @example * uid(); * //=> 0 * * uid(); * //=> 1 * * uid.free(0); * //=> undefined * * uid(); * //=> 0 */ <<<<<<< HEAD export const toggle = (value, on, off) => { return (isEqual(on, value)) ? off : on; ======= uid.free = (id) => { uuidClosed[id] = null; uuidFree.push(id); >>>>>>> origin/master }; assign(acid, { uid, });
JavaScript
0.000001
@@ -81,144 +81,8 @@ t';%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0Aimport %7B isEqual %7D from './isEqual';%0A/**%0A * Performs a toggle between 2 values using a deep or strict comparison.%0A=======%0A impo @@ -301,38 +301,16 @@ reused.%0A -%3E%3E%3E%3E%3E%3E%3E origin/master%0A *%0A * @@ -348,689 +348,8 @@ on%7D%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A%3C%3C%3C%3C%3C%3C%3C HEAD%0A * @param %7B(string%7Cnumber%7CObject%7CArray)%7D value - Strictly compared against the on argument.%0A * @param %7B(string%7Cnumber%7CObject%7CArray)%7D on - Strictly compared against the value argument.%0A * @param %7B(string%7Cnumber%7CObject%7CArray)%7D off - Value to be returned.%0A * @returns %7B(string%7Cnumber%7CObject%7CArray)%7D - The opposing value to the current.%0A=======%0A * @param %7B(string%7Cnumber)%7D value - Strictly compared against the on argument.%0A * @param %7B(string%7Cnumber)%7D on - Strictly compared against the value argument.%0A * @param %7B(string%7Cnumber)%7D off - Value to be returned.%0A * @returns %7B(string%7Cnumber)%7D - The on or off argument.%0A%3E%3E%3E%3E%3E%3E%3E origin/master%0A=======%0A * @@ -389,38 +389,16 @@ que id.%0A -%3E%3E%3E%3E%3E%3E%3E origin/master%0A *%0A * @@ -1041,115 +1041,8 @@ %0A*/%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0Aexport const toggle = (value, on, off) =%3E %7B%0A return (isEqual(on, value)) ? off : on;%0A=======%0A uid. @@ -1083,16 +1083,16 @@ = null;%0A + uuidFr @@ -1108,30 +1108,8 @@ d);%0A -%3E%3E%3E%3E%3E%3E%3E origin/master%0A %7D;%0Aa
5f9014d18c91d7749135a8cedda4723cd72221d2
FIX exception on objectlink remove button
src/client/js/xpsui/directives/objectlink2-edit.js
src/client/js/xpsui/directives/objectlink2-edit.js
(function(angular) { 'use strict'; angular.module('xpsui:directives') .directive('xpsuiObjectlink2Edit', [ 'xpsui:logging', '$parse', 'xpsui:DropdownFactory', 'xpsui:Objectlink2Factory', 'xpsui:SelectDataFactory', 'xpsui:SchemaUtil', 'xpsui:RemoveButtonFactory', function(log, $parse, dropdownFactory, objectlink2Factory, dataFactory, schemaUtil, removeButtonFactory) { return { restrict: 'A', require: ['ngModel', '?^xpsuiFormControl', 'xpsuiObjectlink2Edit'], controller: function($scope, $element, $attrs) { this.setup = function(){ this.$input = angular.element('<div tabindex="0"></div>'); this.$input.addClass('x-input'); }; this.getInput = function(){ return this.$input; }; this.$input = null; this.setup(); }, link: function(scope, elm, attrs, ctrls) { log.group('ObjectLink2 edit Link'); var ngModel = ctrls[0], formControl = ctrls[1] || {}, selfControl = ctrls[2], input = selfControl.getInput(), parseSchemaFragment = $parse(attrs.xpsuiSchema), schemaFragment = parseSchemaFragment(scope) ; var removeButton = removeButtonFactory.create(elm,{ enabled: !!!schemaFragment.required, input: input, onClear: function(){ input.empty(); scope.$apply(function() { ngModel.$setModelValue( {} ); }); } }); elm.addClass('x-control'); elm.addClass('x-select-edit x-objectlink2-edit'); ngModel.$render = function() { if(!angular.equals({},ngModel.$viewValue)) { // get data from schema or model and render it render(dataFactory.getObjectLinkData( schemaFragment.objectLink2, ngModel.$modelValue )); } else { input.empty(); } }; function render(data) { input.empty(); if (data) { removeButton.show(); // get fields schema fragments schemaUtil.getFieldsSchemaFragment( schemaFragment.objectLink2.schema, schemaFragment.objectLink2.fields, function(fields) { objectlink2Factory.renderElement( input, fields, data ); } ); } } elm.append(input); elm.bind('focus', function(evt) { input[0].focus(); }); // dropdown var dropdown = dropdownFactory.create(elm, { titleTransCode: schemaFragment.transCode }); dropdown.setInput(selfControl.getInput()) .render() ; // selectobx var selectbox = objectlink2Factory.create(elm, { onSelected: function(value){ scope.$apply(function() { ngModel.$setViewValue( value ); }); render(value); console.log('onSelected'); console.log(arguments); } }); selectbox.setInput(selfControl.getInput()); selectbox.setDropdown(dropdown); // store var dataset = dataFactory.createObjectDataset(schemaFragment); selectbox.setDataset(dataset); log.groupEnd(); } }; }]); }(window.angular));
JavaScript
0
@@ -1335,12 +1335,9 @@ el.$ -setM +m odel @@ -1345,29 +1345,13 @@ alue -(%0A%09%09%09%09%09%09%09%09%7B%7D%0A%09%09%09%09%09%09%09) + = %7B%7D ;%0A%09%09
8bc4ef10c9341111e761ce9b2f321ee440638de9
Comment out segment so I don't get a million rollbar errors
src/html.js
src/html.js
import React from "react"; import PropTypes from "prop-types"; import BodyClassName from "react-body-classname"; import Helmet from "react-helmet"; import { siteMetadata as config } from "../gatsby-config"; const HTML = ({ color, favicon, body, headComponents, postBodyComponents }) => { let head = Helmet.rewind(); if (!color) { color = BodyClassName.rewind() || "green"; } let cssLink; if (process.env.NODE_ENV === "production") { cssLink = <link rel="stylesheet" href={"/styles.css"} />; } // Sorry, this is gross. let analytics = "!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error('Segment snippet included twice.');else{analytics.invoked=!0;analytics.methods=['trackSubmit','trackClick','trackLink','trackForm','pageview','identify','reset','group','track','ready','alias','page','once','off','on'];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement('script');e.type='text/javascript';e.async=!0;e.src=('https:'===document.location.protocol?'https://':'http://')+'cdn.segment.com/analytics.js/v1/'+t+'/analytics.min.js';var n=document.getElementsByTagName('script')[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION='3.1.0';"; analytics += `analytics.load("${config.segment}");`; analytics += "}}();"; const htmlAttrs = head.htmlAttributes.toComponent(); return ( <html {...htmlAttrs}> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0, viewport-fit=cover" /> {headComponents} {head.meta.toComponent()} {head.title.toComponent()} <link rel="shortcut icon" href={favicon} /> <script dangerouslySetInnerHTML={{ __html: analytics }} /> {cssLink} </head> <body className={color}> <div id="___gatsby" className="page-wrapper" dangerouslySetInnerHTML={{ __html: body }} /> {postBodyComponents} </body> </html> ); }; HTML.propTypes = { body: PropTypes.any, color: PropTypes.string, favicon: PropTypes.string, headComponents: PropTypes.any, postBodyComponents: PropTypes.any }; export default HTML;
JavaScript
0
@@ -2095,24 +2095,36 @@ favicon%7D /%3E%0A + %7B/*%0A %3Cscr @@ -2174,24 +2174,36 @@ ytics %7D%7D /%3E%0A + */%7D%0A %7Bcss
c33554e2d56a7266bad3ea507eea7238733c0ab9
change sakura element id
src/app/page/Sakura/Sakura.js
src/app/page/Sakura/Sakura.js
import React from 'react' import Button from 'material-ui/FloatingActionButton' import UpdateIcon from 'material-ui/svg-icons/action/update' function Sakura({doFetchSakuraData, sakuraLists}) { sakuraLists.map(list => list.discs).forEach(discs => { discs.sort((a, b) => a.this_rank - b.this_rank) }) const style = { position: 'fixed', bottom: '30px', right: '10px' } return ( <div id="home"> <Button style={style} onTouchTap={doFetchSakuraData}> <UpdateIcon/> </Button> {sakuraLists.map(sakuraList => ( <table key={sakuraList.name} border="1"> <caption>{sakuraList.title}</caption> <thead> <tr> <th>rank</th> <th>prev</th> <th>title</th> </tr> </thead> <tbody> {sakuraList.discs.map(disc => ( <tr key={disc.asin}> <td>{disc.this_rank}</td> <td>{disc.prev_rank}</td> <td>{disc.title}</td> </tr> ))} </tbody> </table> ))} </div> ) } export default Sakura
JavaScript
0.000381
@@ -412,12 +412,14 @@ id=%22 -home +sakura %22%3E%0A
9c14aa7b03bdc1310d64e77a7c069902873c16d3
update last bug fixed
request/handler.js
request/handler.js
const Promise = require('bluebird') const logger = require('log4js').getLogger() function promisify(func, params) { return new Promise((resolve, reject) => { func(params, (err, response) => { if (err) { reject(err) } else { resolve(response) } }) }) } function parseForm(str) { const form = {} const arr = str.split('&') arr.forEach(qs => { const i = qs.indexOf('=') const key = qs.slice(0, i) const value = decodeURIComponent(qs.slice(i + 1)) form[key] = value }) return form } function decodeURIForm(form) { const copyForm = {} const keys = Object.keys(form) keys.forEach(key => { copyForm[key] = decodeURIComponent(form[key]) }) return copyForm } function encodeURIForm(form) { const keys = Object.keys(form) return keys.map(key => { if (form[key]) { return `${key}=${encodeURIComponent(form[key])}` } else { return key } }).join('&') } exports.promisify = promisify exports.parseForm = parseForm exports.decodeURIForm = decodeURIForm exports.encodeURIForm = encodeURIForm
JavaScript
0
@@ -841,16 +841,25 @@ orm%5Bkey%5D + !== null ) %7B%0A
5aa2013bdadf4914af09d7fb0c2b935127ac39d8
Fix up comments and variable names in lib/subscribe.js.
lib/subscribe.js
lib/subscribe.js
/** * subscribe.js implements subscriptions to several observables at once. * * E.g. if we have some existing observables (which may be instances of `computed`), * we can subscribe to them explicitly: * let obs1 = observable(5), obs2 = observable(12); * subscribe(obs1, obs2, (use, v1, v2) => console.log(v1, v2)); * * or implicitly by using `use(obs)` function, which allows dynamic subscriptions: * subscribe(use => console.log(use(obs1), use(obs2))); * * In either case, if obs1 or obs2 is changed, the callbacks will get called automatically. * * Creating a subscription allows any number of dependencies to be specified explicitly, and their * values will be passed to the read() callback. These may be combined with automatic dependencies * detected using use(). Note that constructor dependencies have less overhead. * * subscribe(...deps, ((use, ...depValues) => READ_CALLBACK)); */ "use strict"; const fastMap = require('fast.js/map'); const _computed_queue = require('./_computed_queue.js'); const util = require('./util.js'); class Subscription { /** * Internal constructor for a Subscription. You should use subscribe() function instead. */ constructor(read, dependencies) { this._depItem = new _computed_queue.DepItem(this._evaluate, this); this._dependencies = dependencies || []; this._depListeners = fastMap(this._dependencies, obs => this._subscribeTo(obs)); this._dynDeps = new Map(); // Maps dependent observable to its Listener object. let useFunc = (obs => this._useDependency(obs)); this._readArgs = Array(this._dependencies.length + 1); this._readArgs[0] = useFunc; this._read = util.bindB(read, this._readArgs); this._evaluate(); } /** * @private * Gets called when the read() callback calls `use(obs)` for an observable. It creates a * subscription to `obs` if one doesn't yet exist. * @param {Observable} obs: The observable being used as a dependency. */ _useDependency(obs) { let listener = this._dynDeps.get(obs); if (!listener) { listener = this._subscribeTo(obs); this._dynDeps.set(obs, listener); } listener.inUse = true; this._depItem.useDep(obs._getDepItem()); return obs.get(); } /** * @private * Calls the read() callback with appropriate args, and updates subscriptions when it is done. * I.e. adds dynamic subscriptions created via `use(obs)`, and disposes those no longer used. */ _evaluate() { try { // Note that this is optimized for speed. for (let i = 0, len = this._dependencies.length; i < len; i++) { this._readArgs[i + 1] = this._dependencies[i].get(); this._depItem.useDep(this._dependencies[i]._getDepItem()); } return this._read(); } finally { this._dynDeps.forEach((listener, obs) => { if (listener.inUse) { listener.inUse = false; } else { this._dynDeps.delete(obs); listener.dispose(); } }); } } /** * @private * Subscribes this computed to another observable that it depends on. * @param {Observable} obs: The observable to subscribe to. * @returns {Listener} Listener object. */ _subscribeTo(obs) { return obs.addListener(this._enqueue, this); } /** * @private * Adds this item to the recompute queue. */ _enqueue() { this._depItem.enqueue(); } /** * Disposes the computed, unsubscribing it from all observables it depends on. */ dispose() { for (let lis of this._depListeners) { lis.dispose(); } for (let lis of this._dynDeps.values()) { lis.dispose(); } } } /** * Creates a new Subscription. * @param {Observable} ...observables: The initial params, of which there may be zero or more, are * observables on which this computed depends. When any of them change, the read() callback * will be called with the values of these observables as arguments. * @param {Function} read: Callback that will be called with arguments (use, ...values), i.e. the * `use` function and values for all of the ...observables that precede this argument. * This callback is called immediately, and whenever any dependency changes. * @returns {Subscription} The new subscription which may be disposed to unsubscribe. */ function subscribe(...args) { let read = args.pop(); return new Subscription(read, args); } module.exports = subscribe; module.exports.Subscription = Subscription;
JavaScript
0
@@ -689,31 +689,24 @@ assed to the - read() callback. T @@ -702,16 +702,18 @@ callback +() . These @@ -1195,20 +1195,24 @@ tructor( -read +callback , depend @@ -1682,20 +1682,24 @@ l.bindB( -read +callback , this._ @@ -1778,31 +1778,24 @@ led when the - read() callback ca @@ -2277,31 +2277,24 @@ * Calls the - read() callback wi @@ -2290,16 +2290,18 @@ callback +() with ap @@ -3863,15 +3863,8 @@ the - read() cal @@ -3868,16 +3868,18 @@ callback +() %0A * w @@ -3968,27 +3968,17 @@ on%7D -read: C +c allback - that +: wil @@ -4327,20 +4327,24 @@ %7B%0A let -read +callback = args. @@ -4376,20 +4376,24 @@ ription( -read +callback , args);
da630a6a9fdd8781d02d0aee6c381671ea99d262
Revert "add new logging output"
browscap.js
browscap.js
var jsonfile = './browscap.json'; exports.setJson = function (filename) { jsonfile = filename; }; exports.getBrowser = function (userAgent) { var patterns, re, patternReplaced; patterns = require(jsonfile); // Test user agent against each browser regex for (var pattern in patterns) { if (!patterns.hasOwnProperty(pattern)) { continue; } if ('GJK_Browscap_Version' === pattern || 'comments' === pattern) { continue; } patternReplaced = pattern.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\@]/g, "\\$&").replace(/\\\*/g, '.*').replace(/\\\?/g, '.'); re = new RegExp('^' + patternReplaced + '$', 'i'); if (re.test(userAgent)) { console.log('userAgent:' + userAgent); console.log('checking rule:' + pattern); console.log('checking parsed rule:' + patternReplaced); var browser = { browser_name: userAgent, browser_name_regex: pattern.toLowerCase().trim() }; var browserData = JSON.parse(patterns[pattern]); for (var property in browserData) { if (!browserData.hasOwnProperty(property)) { continue; } browser[property] = browserData[property]; console.log('added browser data:' + property + ' => ' + browserData[property]); } var browserParentData = browserData; while (browserParentData['Parent']) { console.log('detected Parent:' + browserParentData['Parent']); browserParentData = JSON.parse(patterns[browserParentData['Parent']]); for (var propertyParent in browserParentData) { if (!browserParentData.hasOwnProperty(propertyParent)) { continue; } if (browser.hasOwnProperty(propertyParent)) { continue; } browser[propertyParent] = browserParentData[propertyParent]; } } if (browser['Parent']) { browser['Parent'] = patterns[browser['Parent']]; } return browser; } } // return default return { Comment:"Default Browser", Browser:"Default Browser", Version:"0.0", MajorVer:"0", MinorVer:"0", Platform:"unknown", Platform_Version:"unknown", Alpha:false, Beta:false, Win16:false, Win32:false, Win64:false, Frames:false, IFrames:false, Tables:false, Cookies:false, BackgroundSounds:false, JavaScript:false, VBScript:false, JavaApplets:false, ActiveXControls:false, isMobileDevice:false, isTablet:false, isSyndicationReader:false, Crawler:false, CssVersion:"0", AolVersion:"0" }; };
JavaScript
0
@@ -678,53 +678,8 @@ ) %7B%0A - console.log('userAgent:' + userAgent);%0A @@ -959,16 +959,73 @@ ttern%5D); +%0A console.log('parsed browser data:' + browserData); %0A%0A @@ -1193,24 +1193,30 @@ roperty%5D;%0A + %7D%0A consol @@ -1249,59 +1249,17 @@ ' + -property + ' =%3E ' + browserData%5Bproperty%5D);%0A %7D +browser); %0A%0A @@ -1348,79 +1348,8 @@ ) %7B%0A - console.log('detected Parent:' + browserParentData%5B'Parent'%5D);%0A
b6ef46a1b589b42d764203cbf110e9e5444e6b06
Send concept id to LMS
src/scripts/app/play/sentences/controller.js
src/scripts/app/play/sentences/controller.js
'use strict'; module.exports = /*@ngInject*/ function SentencePlayCtrl ( $scope, $state, SentenceWritingService, RuleService, _, ConceptTagResult, ActivitySession, localStorageService, $analytics ) { $scope.$on('$locationChangeStart', function (event, next) { if (next.indexOf('gen-results') !== -1) { console.log('allow transition'); } else { console.log('not allowing'); event.preventDefault(); } }); $scope.$watch('currentRuleQuestion', function (crq) { if (_.isObject(crq)) { $scope.currentRule = $scope.swSet[crq.ruleIndex]; } }); $scope.partnerIframe = $state.params.partnerIframe; /* * This is some extra stuff for the partner integration * TODO move this out of here */ //Add in some custom images for the 3 stories we are showcasing $scope.pfImages = require('./../proofreadings/pfImages'); $scope.pfTitles = require('./../proofreadings/pfTitles'); if ($state.params.passageId) { $scope.passageImageUrl = $scope.pfImages[$state.params.passageId]; $scope.passageTitle = $scope.pfTitles[$state.params.passageId]; } $scope.number = 0; $scope.numAttempts = 2; $scope.$on('answerRuleQuestion', function (e, crq, answer, correct) { if (!answer || !crq) { throw new Error('We need a rule question and answer'); } if ($scope.sessionId) { //we only need to communicate with the LMS if there is a valid session ConceptTagResult.save($scope.sessionId, { concept_tag: crq.conceptTag, concept_class: crq.conceptClass, concept_category: crq.conceptCategory, answer: answer, correct: correct ? 1 : 0 }); } if (correct || crq.attempts >= $scope.numAttempts) { $scope.showNextQuestion = true; var passageId = $state.params.passageId; if (passageId) { var key = 'sw-temp-' + passageId; var rs = localStorageService.get(key); if (!rs) { rs = []; } rs.push({ conceptClass: crq.conceptCategory, correct: correct, answer: answer }); localStorageService.set(key, rs); } } }); //If we have a student param, then we have a valid session if ($state.params.student) { $scope.sessionId = $state.params.student; } /* * Function to map and send analytic information */ function sendSentenceWritingAnalytics(results, passageId) { var event = 'Sentence Writing Submitted'; var c = _.pluck(results, 'correct'); var attrs = { uid: passageId, answers: _.pluck(results, 'answer'), correct: c, conceptCategory: _.pluck(results, 'conceptClass'), total: results.length, numCorrect: c.length }; $analytics.eventTrack(event, attrs); } /* * Function to map temporary local results into */ function saveLocalResults() { var passageId = $state.params.passageId; if (passageId) { var tempKey = 'sw-temp-' + passageId; var trs = localStorageService.get(tempKey); sendSentenceWritingAnalytics(trs, passageId); var rs = _.chain(trs) .groupBy('conceptClass') .map(function (entries, cc) { return { conceptClass: cc, total: entries.length, correct: _.filter(entries, function (v) { return v.correct; }).length }; }) .value(); localStorageService.set('sw-' + passageId, rs); localStorageService.remove(tempKey); } } //This is what we need to do after a student has completed the set $scope.finish = function () { var sid = $scope.sessionId; var p = null; saveLocalResults(); if (sid) { //Do LMS logging if we have a sessionId p = ConceptTagResult.findAsJsonByActivitySessionId(sid) .then(function (list) { return ActivitySession.finish(sid, { concept_tag_results: list, percentage: 1, }); }) .then(function () { return ConceptTagResult.removeBySessionId(sid); }); } if (p) { p.then(function () { $state.go('.results', {student: sid}); }); } else { $state.go('.results', { partnerIframe: true, passageId: $state.params.passageId }); } }; $scope.nextQuestion = function () { $scope.showNextQuestion = false; var crq = $scope.currentRuleQuestion; var ncrq = $scope.questions[_.indexOf($scope.questions, crq) + 1]; if (!ncrq) { $scope.number = $scope.number + 1; $scope.finish(); return; } $scope.number = $scope.number + 1; $scope.currentRuleQuestion = ncrq; }; function errorStateChange() { $state.go('index'); } function retrieveNecessaryRules(ruleIds, quantities) { RuleService.getRules(ruleIds).then(function (resolvedRules) { $scope.swSet = _.chain(resolvedRules) .map(function (rr, i) { rr.selectedRuleQuestions = _.chain(rr.resolvedRuleQuestions) .sample(quantities[i]) .map(function (rrq) { rrq.ruleIndex = i; return rrq; }) .value(); return rr; }) .value(); $scope.questions = _.chain($scope.swSet) .pluck('selectedRuleQuestions') .flatten() .value(); $scope.currentRuleQuestion = $scope.questions[0]; $scope.showNextQuestion = false; $scope.showPreviousQuestion = false; }, function () { //errorStateChange(); }); } if ($state.params.uid) { SentenceWritingService.getSentenceWriting($state.params.uid).then(function (sw) { $scope.sentenceWriting = sw; var ruleIds = _.pluck(sw.rules, 'ruleId'); var quantities = _.pluck(sw.rules, 'quantity'); return retrieveNecessaryRules(ruleIds, quantities); }, errorStateChange); } else if ($state.params.ids) { var ids = _.uniq($state.params.ids.split(',')); var quantities = _.chain(ids) .map(function () { return 3; }) .value(); retrieveNecessaryRules(ids, quantities); } /* * Format Description */ $scope.formatDescription = function (des) { if (!des) { return; } var entries = des.split('.'); var phrases = []; var sentences = []; _.each(entries, function (e) { e = '<li>' + e + '.</li>'; if (e.indexOf(':') !== -1) { phrases.push(e); } else { sentences.push(e); } }); var html = '<ul>' + phrases.join('') + '</ul><hr/><ul>' + sentences.join('') + '</ul>'; return html; }; };
JavaScript
0
@@ -1594,32 +1594,67 @@ onceptCategory,%0A + concept_id: crq.conceptId,%0A answer:
3d47acdfe3c81385ca97a8f9410994924820ed6a
Update main.js
javascripts/main.js
javascripts/main.js
console.log (THis is cool-FireMiner99)
JavaScript
0.000001
@@ -11,9 +11,9 @@ g (T -H +h is i @@ -30,10 +30,34 @@ eMiner99 + I might add a game too. )%0A
d76a0373d2273d62bcfec473a0cbe27e9c8c0bf0
Check for scope.player.d to exist before destroy()
src/angular-youtube-embed.js
src/angular-youtube-embed.js
/* global YT */ angular.module('youtube-embed', ['ng']) .service ('youtubeEmbedUtils', ['$window', '$rootScope', function ($window, $rootScope) { var Service = {} // adapted from http://stackoverflow.com/a/5831191/1614967 var youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig; var timeRegexp = /t=(\d+)[ms]?(\d+)?s?/; function contains(str, substr) { return (str.indexOf(substr) > -1); } Service.getIdFromURL = function getIdFromURL(url) { var id = url.replace(youtubeRegexp, '$1'); if (contains(id, ';')) { var pieces = id.split(';'); if (contains(pieces[1], '%')) { // links like this: // "http://www.youtube.com/attribution_link?a=pxa6goHqzaA&amp;u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare" // have the real query string URI encoded behind a ';'. // at this point, `id is 'pxa6goHqzaA;u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare' var uriComponent = decodeURIComponent(id.split(';')[1]); id = ('http://youtube.com' + uriComponent) .replace(youtubeRegexp, '$1'); } else { // https://www.youtube.com/watch?v=VbNF9X1waSc&amp;feature=youtu.be // `id` looks like 'VbNF9X1waSc;feature=youtu.be' currently. // strip the ';feature=youtu.be' id = pieces[0]; } } else if (contains(id, '#')) { // id might look like '93LvTKF_jW0#t=1' // and we want '93LvTKF_jW0' id = id.split('#')[0]; } return id; }; Service.getTimeFromURL = function getTimeFromURL(url) { url = url || ''; // t=4m20s // returns ['t=4m20s', '4', '20'] // t=46s // returns ['t=46s', '46'] // t=46 // returns ['t=46', '46'] var times = url.match(timeRegexp); if (!times) { // zero seconds return 0; } // assume the first var full = times[0], minutes = times[1], seconds = times[2]; // t=4m20s if (typeof seconds !== 'undefined') { seconds = parseInt(seconds, 10); minutes = parseInt(minutes, 10); // t=4m } else if (contains(full, 'm')) { minutes = parseInt(minutes, 10); seconds = 0; // t=4s // t=4 } else { seconds = parseInt(minutes, 10); minutes = 0; } // in seconds return seconds + (minutes * 60); }; // Inject YouTube's iFrame API (function () { var validProtocols = ['http:', 'https:']; var url = '//www.youtube.com/iframe_api'; // We'd prefer a protocol relative url, but let's // fallback to `http:` for invalid protocols if (validProtocols.indexOf(window.location.protocol) < 0) { url = 'http:' + url; } var tag = document.createElement('script'); tag.src = url; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); }()); Service.ready = false; // Youtube callback when API is ready $window.onYouTubeIframeAPIReady = function () { $rootScope.$apply(function () { Service.ready = true; }); }; return Service; }]) .directive('youtubeVideo', ['youtubeEmbedUtils', function (youtubeEmbedUtils) { var uniqId = 1; // from YT.PlayerState var stateNames = { '-1': 'unstarted', 0: 'ended', 1: 'playing', 2: 'paused', 3: 'buffering', 5: 'queued' }; var eventPrefix = 'youtube.player.'; return { restrict: 'EA', scope: { videoId: '=?', videoUrl: '=?', player: '=?', playerVars: '=?', playerHeight: '=?', playerWidth: '=?' }, link: function (scope, element, attrs) { // allows us to $watch `ready` scope.utils = youtubeEmbedUtils; // player-id attr > id attr > directive-generated ID var playerId = attrs.playerId || element[0].id || 'unique-youtube-embed-id-' + uniqId++; element[0].id = playerId; // Attach to element scope.playerHeight = scope.playerHeight || 390; scope.playerWidth = scope.playerWidth || 640; scope.playerVars = scope.playerVars || {}; // YT calls callbacks outside of digest cycle function applyBroadcast () { var args = Array.prototype.slice.call(arguments); scope.$apply(function () { scope.$emit.apply(scope, args); }); } function onPlayerStateChange (event) { var state = stateNames[event.data]; if (typeof state !== 'undefined') { applyBroadcast(eventPrefix + state, scope.player, event); } scope.$apply(function () { scope.player.currentState = state; }); } function onPlayerReady (event) { applyBroadcast(eventPrefix + 'ready', scope.player, event); } function createPlayer () { var playerVars = angular.copy(scope.playerVars); playerVars.start = playerVars.start || scope.urlStartTime; var player = new YT.Player(playerId, { height: scope.playerHeight, width: scope.playerWidth, videoId: scope.videoId, playerVars: playerVars, events: { onReady: onPlayerReady, onStateChange: onPlayerStateChange } }); player.id = playerId; return player; } function loadPlayer () { if (playerId && scope.videoId) { if (scope.player && typeof scope.player.destroy === 'function') { scope.player.destroy(); } scope.player = createPlayer(); } }; var stopWatchingReady = scope.$watch( function () { return scope.utils.ready // Wait until one of them is defined... && (typeof scope.videoUrl !== 'undefined' || typeof scope.videoId !== 'undefined'); }, function (ready) { if (ready) { stopWatchingReady(); // use URL if you've got it if (typeof scope.videoUrl !== 'undefined') { scope.$watch('videoUrl', function (url) { scope.videoId = scope.utils.getIdFromURL(url); scope.urlStartTime = scope.utils.getTimeFromURL(url); loadPlayer(); }); // otherwise, watch the id } else { scope.$watch('videoId', function (id) { scope.urlStartTime = null; loadPlayer(); }); } } }); scope.$on('$destroy', function () { scope.player && scope.player.destroy(); }); } }; }]);
JavaScript
0
@@ -6343,16 +6343,58 @@ layer && + scope.player.d &&%0A typeof
850aec241df71ee36e2361ddcc5894dc5ecab1c1
add tachyfontreporter.js
run_time/src/gae_server/www/js/closure_deps.js
run_time/src/gae_server/www/js/closure_deps.js
/** * @license * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ goog.addDependency('../../../tachyfont/backendservice.js', ['tachyfont.BackendService', 'tachyfont.GoogleBackendService'], ['goog.Promise', 'goog.net.XhrIo', 'goog.events', 'goog.net.EventType']); goog.addDependency('../../../tachyfont/charcmapinfo.js', ['tachyfont.CharCmapInfo'], []); goog.addDependency('../../../tachyfont/demobackendservice.js', ['tachyfont.DemoBackendService'], ['goog.Promise', 'goog.net.XhrIo', 'goog.events', 'goog.net.EventType', 'tachyfont.BackendService' ]); goog.addDependency('../../../tachyfont/googlebackendservice.js', ['tachyfont.GoogleBackendService'], ['goog.Promise', 'tachyfont.BackendService']); goog.addDependency('../../../tachyfont/binaryfonteditor.js', ['tachyfont.BinaryFontEditor'], []); goog.addDependency('../../../tachyfont/glyphbundleresponse.js', ['tachyfont.GlyphBundleResponse'], []); goog.addDependency('../../../tachyfont/fontinfo.js', ['tachyfont.FontInfo'], []); goog.addDependency('../../../tachyfont/fontsinfo.js', ['tachyfont.FontsInfo'], ['tachyfont.FontInfo']); goog.addDependency('../../../tachyfont/incrementalfont.js', ['tachyfont.IncrementalFont', 'tachyfont.TachyFont'], ['goog.Promise', 'goog.log', 'tachyfont.DemoBackendService', 'tachyfont.GoogleBackendService', 'tachyfont.IncrementalFontUtils', 'tachyfont.promise', 'tachyfont.RLEDecoder' ]); goog.addDependency('../../../tachyfont/incrementalfontutils.js', ['tachyfont.IncrementalFontUtils'], ['goog.log', 'tachyfont.BinaryFontEditor']); goog.addDependency('../../../misc_utils.js', ['tachyfont_misc_utils'], []); goog.addDependency('../../../tachyfont/rledecoder.js', ['tachyfont.RLEDecoder'], []); goog.addDependency('../../../tachyfont/tachyfontpromise.js', ['tachyfont.promise', 'tachyfont.chainedPromises'], ['goog.Promise']); goog.addDependency('../../../tachyfont/tachyfontset.js', ['tachyfont.TachyFontSet'], ['goog.array', 'goog.Promise', 'goog.log', 'goog.style', 'tachyfont.IncrementalFontUtils', 'tachyfont.chainedPromises' ]); goog.addDependency('../../../tachyfont/webfonttailor.js', ['webfonttailor'], ['tachyfont.FontInfo', 'tachyfont.FontsInfo' ]); goog.addDependency('../../../tachyfont/webfonttailoralternate.js', ['webfonttailor.alternate'], ['tachyfont.FontInfo', 'tachyfont.FontsInfo' ]);
JavaScript
0.000001
@@ -2495,24 +2495,133 @@ Promise'%5D);%0A +goog.addDependency('../../../tachyfont/tachyfontreporter.js',%0A %5B'tachyfont.reporter'%5D,%0A %5B'goog.log'%5D);%0A goog.addDepe @@ -2825,32 +2825,141 @@ omises'%0A %5D);%0A +goog.addDependency('../../../tachyfont/tachyfontutils.js',%0A %5B'tachyfont.utils'%5D,%0A %5B'goog.crypt.Md5'%5D);%0A goog.addDependen
9e87b835e08aac17a4cd931c9d697bd47a5b7614
Fix transition to machines view after creating single server
src/mist/io/static/js/app/views/backend_add.js
src/mist/io/static/js/app/views/backend_add.js
define('app/views/backend_add', [ 'app/models/backend', 'text!app/templates/backend_add.html', 'ember'], /** * * Add Backend Dialog * * @returns Class */ function(Backend, backend_add_html) { return Ember.View.extend({ template: Ember.Handlebars.compile(backend_add_html), pendingCreation: false, pendingCreationObserver: function() { if (this.pendingCreation) { $('#create-backend-ok').addClass('ui-disabled'); } else { $('#create-backend-ok').removeClass('ui-disabled'); } }.observes('pendingCreation'), keyDown: function(event) { if (event.keyCode == 13) { // Enter if (event.preventDefault) { event.preventDefault(); } if (Mist.backendAddController.newBackendReady) { warn('yeay!'); this.addButtonClick(); } } else if (event.keyCode == 27) { // Esc this.backClicked(); } }, selectBackend: function(event) { if (event.target.title.indexOf("rackspace") != -1 || event.target.title.indexOf("linode") != -1 || event.target.title.indexOf("softlayer") !== -1) { $('#addBackendInfo').show(); $('#ApiKeylabel').text('2. Username:'); $('#ApiSecretlabel').text('3. API Key:'); $('#addBackendOpenstack').hide(); $('#addBackendBareMetal').hide(); } else if (event.target.title.indexOf("nephoscale") !== -1) { $('#addBackendInfo').show(); $('#ApiKeylabel').text('2. Username:'); $('#ApiSecretlabel').text('3. Password:'); $('#addBackendOpenstack').hide(); $('#addBackendBareMetal').hide(); } else if (event.target.title.indexOf("digitalocean") !== -1) { $('#addBackendInfo').show(); $('#ApiKeylabel').text('2. Client ID:'); $('#ApiSecretlabel').text('3. API Key:'); $('#addBackendOpenstack').hide(); $('#addBackendBareMetal').hide(); } else if (event.target.title.indexOf("openstack") != -1) { $('#addBackendInfo').show(); $('#ApiKeylabel').text('2. Username:'); $('#ApiSecretlabel').text('3. Password:'); $('#addBackendOpenstack').show(); $('#addBackendBareMetal').hide(); } else if (event.target.title.indexOf("bare_metal") != -1) { $('#addBackendInfo').hide(); $('#addBackendBareMetal').show(); $('#addBackendOpenstack').hide(); } else { $('#addBackendInfo').show(); $('#ApiKeylabel').text('2. API Key:'); $('#ApiSecretlabel').text('3. API Secret:'); $('#addBackendOpenstack').hide(); $('#addBackendBareMetal').hide(); } $('.select-backend-collapsible').collapsible('option','collapsedIcon','check'); $('.select-backend-collapsible span.ui-btn-text').text(event.target.text); Mist.backendAddController.set('newBackendProvider', {provider: $(event.target).attr('title'), title: event.target.text } ); $('.select-backend-collapsible').trigger('collapse'); Mist.backendAddController.set('newBackendKey', ''); Mist.backendAddController.set('newBackendSecret', ''); /* OpenStack support Mist.backendAddController.set('newBackendUrl', ''); Mist.backendAddController.set('newBackendTenant', ''); */ for (var b = 0; b < Mist.backendsController.content.length; b++) { var backend = Mist.backendsController.content[b]; if (event.target.title.split('_')[0] == 'ec2' && backend.provider.split('_')[0] == 'ec2') { //Autocomplete Mist.backendAddController.set('newBackendKey', backend.apikey); Mist.backendAddController.set('newBackendSecret', 'getsecretfromdb'); break; } else if (event.target.title.substr(0,9) == 'rackspace' && backend.provider.substr(0,9) == 'rackspace') { Mist.backendAddController.set('newBackendKey', backend.apikey); Mist.backendAddController.set('newBackendSecret', 'getsecretfromdb'); break; } } }, addBackend: function() { $('.select-listmenu li').on('click', this.selectBackend); $('#add-backend').panel('open'); }, addKey: function() { $('.select-key-listmenu li').on('click', this.selectKey); }, selectKey: function(key){ $('.select-key-collapsible').collapsible('option','collapsedIcon','check'); $('.select-key-collapsible span.ui-btn-text').text(key.name); Mist.backendAddController.set('newBareServerKey', key.name); $('.select-key-collapsible').trigger('collapse'); }, backClicked: function() { $("#add-backend").panel("close"); $('.select-listmenu li').off('click', this.selectBackend); Mist.backendAddController.newBackendClear(); }, addButtonClick: function() { var that = this; that.set('pendingCreation', true); var payload = { "title": Mist.backendAddController.newBackendProvider.title, "provider": Mist.backendAddController.newBackendProvider.provider, "apikey" : Mist.backendAddController.newBackendKey, "apisecret": Mist.backendAddController.newBackendSecret, "apiurl": Mist.backendAddController.newBackendUrl, "tenant_name": Mist.backendAddController.newBackendTenant, "machine_name": Mist.backendAddController.newBareServerName, "machine_ip_address": Mist.backendAddController.newBareServeIp, "machine_key": Mist.backendAddController.newBareServerKey, "machine_user": Mist.backendAddController.newBareServerUser }; $.ajax({ url: '/backends', type: "POST", contentType: "application/json", dataType: "json", headers: { "cache-control": "no-cache" }, data: JSON.stringify(payload), success: function(result) { that.set('pendingCreation', false); Mist.backendAddController.newBackendClear(); $("#add-backend").panel("close"); $('.select-listmenu li').off('click', this.selectBackend); info('added backend ' + result.id); if (result.provider == 'bare_metal') { if (!result.exists) { Mist.backendsController.pushObject(Backend.create(result)); } //add bare metal backend if it does not exist already var machines_url = window.location.href + "/machines"; window.location.href = machines_url; Mist.backendsController.getBackendById(result.id).machines.refresh(); } else { Mist.backendsController.pushObject(Backend.create(result)); } }, error: function(request){ that.set('pendingCreation', false); Mist.notificationController.notify(request.responseText); } }); }, createBareMetalKeyClicked: function() { $('#create-key-dialog').popup('open'); }, providerList: function() { return SUPPORTED_PROVIDERS; }.property('providerList') }); } );
JavaScript
0
@@ -7772,36 +7772,16 @@ false); - %0A @@ -8363,338 +8363,285 @@ -//add bare metal backend if it does not exist already %0A var machines_url = window.location.href + %22/machines%22; %0A window.location.href = machines_url; %0A Mist.backendsController.getBackendById(result.id).machines.refresh( +Ember.run.later(function() %7B%0A //Mist.backendsController.getBackendById(result.id).machines.refresh();%0A $('#home-menu li').eq(0).find('a').click(); // Manually click machines button%0A %7D, 500 );%0A
c92a61070d2cb936ac44444cfdd84b7c60bbb642
Change the ajax failure message
ecommerce/static/js/pages/checkout_payment.js
ecommerce/static/js/pages/checkout_payment.js
/** * Checkout payment page scripts. **/ require([ 'jquery', 'underscore', 'utils/utils', 'jquery-cookie' ], function ($, _, Utils) { 'use strict'; var redirectToPaymentProvider = function (data) { var $form = $('<form>', { action: data.payment_page_url, method: 'POST', 'accept-method': 'UTF-8' }); _.each(data.payment_form_data, function (value, key) { $('<input>').attr({ type: 'text', name: key, value: value }).appendTo($form); }); $form.submit(); }; $(document).ready(function () { var $paymentButtons = $('.payment-buttons'), basketId = $paymentButtons.data('basket-id'); $paymentButtons.find('.payment-button').click(function (e) { var $btn = $(e.target), deferred = new $.Deferred(), promise = deferred.promise(), paymentProcessor = $btn.val(), data = { basket_id: basketId, payment_processor: paymentProcessor }; Utils.disableElementWhileRunning($btn, function() { return promise; }); $.ajax({ url: '/api/v2/checkout/', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', headers: { 'X-CSRFToken': $.cookie('ecommerce_csrftoken') }, data: JSON.stringify(data) }).done(function (data) { redirectToPaymentProvider(data); }).fail(function(jqXHR, errorThrown) { $('#messages').empty().append( '<div class="error">' + jqXHR.status + errorThrown + ' occurred during checkout.</div>' ); }); }); }); } );
JavaScript
0.00001
@@ -1932,30 +1932,116 @@ tion -(jqXHR, errorThrown) %7B + () %7B%0A var message = gettext('Problem occurred during checkout. Please contact support'); %0A @@ -2140,64 +2140,19 @@ ' + -jqXHR.status + errorThrown + ' occurred during checkout. +message + ' %3C/di
a37a228e228489ab8a214b462f3d983f8d5c18a3
add icon in speed chart tooltip
src/scripts/services/ariaNgMonitorService.js
src/scripts/services/ariaNgMonitorService.js
(function () { 'use strict'; angular.module('ariaNg').factory('ariaNgMonitorService', ['$filter', '$translate', 'moment', 'ariaNgConstants', function ($filter, $translate, moment, ariaNgConstants) { var currentGlobalStat = {}; var storagesInMemory = {}; var globalStorageKey = 'global'; var getStorageCapacity = function (key) { if (key === globalStorageKey) { return ariaNgConstants.globalStatStorageCapacity; } else { return ariaNgConstants.taskStatStorageCapacity; } }; var initStorage = function (key) { var data = { legend: { show: false }, grid: { x: 50, y: 10, x2: 10, y2: 10 }, tooltip: { show: true, formatter: function (params) { if (params[0].name === '') { return '<div>' + $translate.instant('No Data') + '</div>'; } var time = moment(params[0].name, 'X').format('HH:mm:ss'); var uploadSpeed = $filter('readableVolume')(params[0].value) + '/s'; var downloadSpeed = $filter('readableVolume')(params[1].value) + '/s'; return '<div>' + time + '</div>' + '<div><i class="icon-download fa fa-arrow-down"></i> ' + downloadSpeed +'</div>' + '<div><i class="icon-upload fa fa-arrow-up"></i> ' + uploadSpeed + '</div>'; } }, xAxis: { data: [], type: 'category', boundaryGap: false, axisLabel: { show: false } }, yAxis: { type: 'value', axisLabel: { formatter: function (value) { return $filter('readableVolume')(value, 'auto'); } } }, series: [{ type: 'line', areaStyle: { normal: { opacity: 0.1 } }, smooth: true, symbolSize: 6, showAllSymbol: false, data: [] }, { type: 'line', areaStyle: { normal: { opacity: 0.1 } }, smooth: true, symbolSize: 6, showAllSymbol: false, data: [] }] }; var timeData = data.xAxis.data; var uploadData = data.series[0].data; var downloadData = data.series[1].data; for (var i = 0; i < getStorageCapacity(key); i++) { timeData.push(''); uploadData.push(''); downloadData.push(''); } storagesInMemory[key] = data; return data; }; var isStorageExist = function (key) { return angular.isDefined(storagesInMemory[key]); }; var pushToStorage = function (key, stat) { var storage = storagesInMemory[key]; var timeData = storage.xAxis.data; var uploadData = storage.series[0].data; var downloadData = storage.series[1].data; if (timeData.length >= getStorageCapacity(key)) { timeData.shift(); uploadData.shift(); downloadData.shift(); } timeData.push(stat.time); uploadData.push(stat.uploadSpeed); downloadData.push(stat.downloadSpeed); }; var getStorage = function (key) { return storagesInMemory[key]; }; var removeStorage = function (key) { delete storagesInMemory[key]; }; return { recordStat: function (key, stat) { if (!isStorageExist(key)) { initStorage(key); } stat.time = moment().format('X'); pushToStorage(key, stat); }, getStatsData: function (key) { if (!isStorageExist(key)) { initStorage(key); } return getStorage(key); }, getEmptyStatsData: function (key) { if (isStorageExist(key)) { removeStorage(key); } return this.getStatsData(key); }, recordGlobalStat: function (stat) { this.recordStat(globalStorageKey, stat); currentGlobalStat = stat; }, getGlobalStatsData: function () { return this.getStatsData(globalStorageKey); }, getCurrentGlobalStat: function () { return currentGlobalStat; } }; }]); }());
JavaScript
0
@@ -1464,24 +1464,54 @@ eturn '%3Cdiv%3E +%3Ci class=%22fa fa-clock-o%22%3E%3C/i%3E ' + time + '
1ec13c48785bbc0f3e4cabc5c26a7192ca759f39
Fix undefined function error.
assets/tools.js
assets/tools.js
/** * Magister Calendar v1.0.0 * https://git.io/magister * * Copyright 2015 Sander Laarhoven * Licensed under MIT (http://git.io/magister-calendar-license) */ var fs = require("fs"); module.exports = { validjson: function (string) { try { JSON.parse(string); } catch (e) { return false; } return true; }, log: function(status, text, error) { if (status == "error") { var prefix = "!"; } else { var prefix = "*"; } var date = new Date(); var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); var logtext = "[" + prefix + "] " + time + " " + text; if (error) { var logtext = logtext + " " + JSON.stringify(error); } console.log(logtext); }, loadJSONfile: function(path) { var file; try { file = fs.readFileSync(path, "utf8"); } catch (e) { if (e.code == "ENOENT") { module.exports.log("error", "Config file " + path + " not found.", e); process.exit(1); } else { module.exports.log("error", "An error occured when opening " + path + ".", e); throw e; } } if (!module.exports.validjson(file)) { module.exports.log("error", "File " + path + " contains bogus JSON."); process.exit(1); } return JSON.parse(file); } }
JavaScript
0.000027
@@ -1340,14 +1340,101 @@ (file);%0A + %7D,%0A sendPushMessage: function(appointment) %7B%0A // To be implemented..%0A return;%0A %7D%0A%7D%0A
de599537eca17f2ae897c33f8ad7f6d074c74958
Store EditableTable events in the instance
app/assets/javascripts/tables/editable_table.js
app/assets/javascripts/tables/editable_table.js
var EditableTable = (function(){ var selector, changeData, changeListener; EditableTable.prototype = { append: function(_changeListener, _changeData){ changeListener = (_changeListener || function(){}); changeData = (_changeData || function(){}); $(this.selector).on('change', changeListener.bind(this)); addClickListenersToAddRow.call(this); addClickListenersToDeleteRow.call(this); }, getData: function(){ return tableToProfile.call(this); } }; function tableToProfile(){ var self = this; return tableRows.call(this).map(function(tableRow){ return rowToTechnologyObject.call(self, tableRow); }); }; function rowToTechnologyObject(tableRow){ var tableData = {}; var self = this; $.each(tableRow, function(i, attribute){ var header = tableHeader.call(self, i); tableData[header] = attribute; changeData.call({ attribute: attribute, header: header, tableData: tableData }); }); return tableData; }; function tableHeader(index){ return $($(this.selector).find("thead th")[index]).data("header"); }; function tableRows(){ return $(this.selector).find("tbody tr").toArray().map(extractTextfromCells); }; function extractTextfromCells(row){ return $(row).find("td.editable").toArray().map(function(cell){ if($(cell).find("select:visible").length > 0){ return $.trim($(cell).find("select").val()); } else{ return $.trim($(cell).find("input").val()); } }); }; function addClickListenersToAddRow(){ $(this.selector).find("a.add-row").on("click", function(e){ e.preventDefault(); var row = $(this).parents("tr"); var clonedRow = row.clone(true, true); clonedRow.insertAfter(row); changeListener.call(); }); }; function addClickListenersToDeleteRow(){ $(this.selector).find("a.remove-row").on("click", function(e){ e.preventDefault(); $(this).parents("tr").remove(); changeListener.call(); }); }; function EditableTable(_selector){ this.selector = _selector; }; return EditableTable; })();
JavaScript
0
@@ -30,53 +30,8 @@ ()%7B%0A - var selector, changeData, changeListener;%0A%0A Ed @@ -110,24 +110,29 @@ ata)%7B%0A +this. changeListen @@ -169,32 +169,37 @@ ion()%7B%7D);%0A +this. changeData = (_c @@ -263,16 +263,21 @@ hange', +this. changeLi @@ -867,22 +867,28 @@ ribute;%0A +%0A +this. changeDa @@ -896,16 +896,24 @@ a.call(%7B +%0A attribu @@ -926,16 +926,24 @@ tribute, +%0A header: @@ -950,16 +950,24 @@ header, +%0A tableDa @@ -979,16 +979,22 @@ ableData +%0A %7D);%0A @@ -991,24 +991,35 @@ %7D);%0A %7D +.bind(this) );%0A retur @@ -1712,20 +1712,31 @@ row = $( -this +e.currentTarget ).parent @@ -1821,32 +1821,37 @@ ter(row);%0A +this. changeListener.c @@ -1840,37 +1840,32 @@ s.changeListener -.call ();%0A %7D);%0A %7D; @@ -1849,32 +1849,43 @@ istener();%0A %7D +.bind(this) );%0A %7D;%0A%0A funct @@ -2022,20 +2022,31 @@ $( -this +e.currentTarget ).parent @@ -2069,16 +2069,21 @@ ;%0A +this. changeLi @@ -2088,21 +2088,16 @@ Listener -.call ();%0A @@ -2089,32 +2089,43 @@ istener();%0A %7D +.bind(this) );%0A %7D;%0A%0A funct @@ -2184,16 +2184,95 @@ elector; +%0A%0A this.changeListener = function() %7B%7D;%0A this.changeData = function() %7B%7D; %0A %7D;%0A%0A
15891ab27fab1499afc58856b82c72c4e284cfa1
Apply the 'change' handler if provided
htdocs/components/00_jquery_speciesdropdown.js
htdocs/components/00_jquery_speciesdropdown.js
/* * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * speciesDropdown: Javascript counterpart for E::W::Form::Element::SpeciesDropdown * Extension of filterableDropdown to add species icons to the tags * Reserverd classname prefix: _sdd **/ (function ($) { $.fn.speciesDropdown = function (options) { /* * options: same as accepted by filterableDropdown, except 'change' key */ return this.each(function () { $.speciesDropdown($(this), options); }); }; $.speciesDropdown = function (el, options) { $.filterableDropdown(el, $.extend(options, { 'change': function() { $(this).find('._fd_tag').css('background-image', function() { return this.style.backgroundImage.replace(/[^\/]+\.png/, $($(this).data('input')).val() + '.png'); }); } })); }; })(jQuery);
JavaScript
0
@@ -984,30 +984,9 @@ down -, except 'change' key %0A + * @@ -1165,16 +1165,20 @@ .extend( +%7B%7D, options, @@ -1388,16 +1388,16 @@ .png');%0A - @@ -1400,16 +1400,116 @@ %7D);%0A + if (options && options.change) %7B%0A options.change.apply(this, arguments);%0A %7D%0A %7D%0A
b8725f3b2ad4a032a85b705ff56ae5e647c804bf
fix overriding styles, add size="" prop to set width/height
src/icon.js
src/icon.js
var element = require('magic-virtual-element') exports.render = function render (component) { var attrs = { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 24 24', style: { width: 24, height: 24 } } Object.keys(component.props).forEach(function (key) { if (key === 'style') { assign(attrs.style, component.props.style) } else if (key !== 'children') { attrs[key] = component.props[key] } }) return element('svg', attrs, component.props.children) }
JavaScript
0.000001
@@ -88,16 +88,93 @@ nent) %7B%0A + var props = component.props%0A var size = 'size' in props ? props.size : 24%0A var at @@ -263,49 +263,56 @@ le: -%7B%0A width: 24,%0A height: 24%0A %7D +'width: ' + size + 'px; height: ' + size + 'px;' %0A %7D @@ -326,26 +326,16 @@ ct.keys( -component. props).f @@ -395,15 +395,8 @@ -assign( attr @@ -402,28 +402,26 @@ rs.style -, component. + += ' ' + props.st @@ -423,17 +423,16 @@ ps.style -) %0A %7D e @@ -480,26 +480,16 @@ %5Bkey%5D = -component. props%5Bke @@ -533,26 +533,16 @@ attrs, -component. props.ch
9e15c9daa1eab9c0047b23542321e11097000e5e
Update production aws bucket in node dependencies
buildbug.js
buildbug.js
//------------------------------------------------------------------------------- // Requires //------------------------------------------------------------------------------- var buildbug = require("buildbug"); //------------------------------------------------------------------------------- // Simplify References //------------------------------------------------------------------------------- var buildProject = buildbug.buildProject; var buildProperties = buildbug.buildProperties; var buildTarget = buildbug.buildTarget; var enableModule = buildbug.enableModule; var series = buildbug.series; var targetTask = buildbug.targetTask; //------------------------------------------------------------------------------- // Enable Modules //------------------------------------------------------------------------------- var aws = enableModule("aws"); var bugpack = enableModule("bugpack"); var core = enableModule("core"); var nodejs = enableModule("nodejs"); //------------------------------------------------------------------------------- // Declare Properties //------------------------------------------------------------------------------- buildProperties({ packageJson: { name: "bugunit", version: "0.0.14", main: "./lib/bug-unit-cli-module.js", private: true, bin: "bin/bugunit", scripts: { start: "node ./scripts/bugunit-cli-start.js" }, dependencies: { npm: "1.2.x", tar: "0.1.x", bugpack: "https://s3.amazonaws.com/airbug/bugpack-0.0.5.tgz" } }, sourcePaths: [ "../bugjs/projects/bugjs/js/src", "../bugjs/projects/bugfs/js/src", "../bugjs/projects/bugflow/js/src", '../bugjs/projects/bugtrace/js/src', "./projects/bugunit-cli/js/src" ], scriptPaths: [ "./projects/bugunit-cli/js/scripts" ], binPaths: [ "./projects/bugunit-cli/bin" ] }); //------------------------------------------------------------------------------- // Declare Tasks //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- // Declare Flows //------------------------------------------------------------------------------- // Clean Flow //------------------------------------------------------------------------------- buildTarget("clean").buildFlow( targetTask("clean") ); // Local Flow //------------------------------------------------------------------------------- buildTarget("local").buildFlow( series([ // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that // old source files are removed. We should figure out a better way of doing that. targetTask("clean"), targetTask("createNodePackage", { properties: { packageJson: buildProject.getProperty("packageJson"), sourcePaths: buildProject.getProperty("sourcePaths"), binPaths: buildProject.getProperty("binPaths") } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("packageJson.name"), buildProject.getProperty("packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask("packNodePackage", { properties: { packageName: buildProject.getProperty("packageJson.name"), packageVersion: buildProject.getProperty("packageJson.version") } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"), buildProject.getProperty("packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: "public-read", encrypt: true } }); }, properties: { bucket: "{{local-bucket}}" } }) ]) ).makeDefault(); // Prod Flow //------------------------------------------------------------------------------- buildTarget("prod").buildFlow( series([ // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that // old source files are removed. We should figure out a better way of doing that. targetTask("clean"), targetTask("createNodePackage", { properties: { packageJson: buildProject.getProperty("packageJson"), sourcePaths: buildProject.getProperty("sourcePaths") } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("packageJson.name"), buildProject.getProperty("packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask("packNodePackage", { properties: { packageName: buildProject.getProperty("packageJson.name"), packageVersion: buildProject.getProperty("packageJson.version") } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"), buildProject.getProperty("packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: "public-read", encrypt: true } }); }, properties: { bucket: "{{prod-deploy-bucket}}" } }) ]) );
JavaScript
0
@@ -1661,16 +1661,23 @@ aws.com/ +deploy- airbug/b
589b510b8e97f55f8dd46336db5bd0ee0cb514c7
Fix accepted tooltip grammar (#129)
app/components/registration-status/component.js
app/components/registration-status/component.js
import Ember from 'ember'; const STATUS_HELP = { pending: function(registration) { return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!'; }, accepted: function(registration) { if (registration.directSource) { return registration.sourceName + ' have been approved as a source. Start pushing data!'; } return registration.sourceName + ' have been approved as a source but we have not started scraping it yet.'; }, implemented: function(registration) { return registration.sourceName + ' is now a source. Check it out!'; }, rejected: function(registration) { return registration.sourceName + ' has been rejected as a source. Contact [email protected] for additional information.'; }, }; export default Ember.Component.extend({ init() { this._super(...arguments); Ember.run.schedule('afterRender', this, function() { this.send('enablePopover'); }); }, colorClass: Ember.computed('registration.data.status', 'registration.data.sourceName', function() { return this.getStatusColor(this.get('registration.data')); }), helpText: Ember.computed('registration.data.status', function() { let registration = this.get('registration.data'); return STATUS_HELP[registration.status](registration); }), getStatusColor(registration) { if (registration.status === 'pending') { return 'bg-warning'; } else if (registration.directSource && registration.status === 'accepted') { return 'bg-success'; } else if (registration.status === 'accepted') { return 'bg-info'; } else if (registration.status === 'implemented') { return 'bg-success'; } return 'bg-danger'; }, actions: { enablePopover() { Ember.$('[data-toggle="popover"]').popover(); } } });
JavaScript
0
@@ -315,34 +315,33 @@ ourceName + ' ha -ve +s been approved a @@ -429,18 +429,17 @@ e + ' ha -ve +s been ap
719b97cba7aa54121d08601e62514b1818b601b8
make oldDashboard default page after login, again; #219
imports/startup/client/routes/Routes.Public.js
imports/startup/client/routes/Routes.Public.js
import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { Session } from 'meteor/session'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { wrs } from '/imports/framework/Functions/Async'; import { checkLanguage, logout } from '/imports/framework/Managers/RouteManager.Helpers'; FlowRouter.notFound = { action: () => { BlazeLayout.render('blankLayout', { content: 'notFound' }); } }; FlowRouter.route('/:language/welcome', { name: 'welcome', triggersEnter: [ checkLanguage ], action: () => { BlazeLayout.render('blankLayout', { content: 'landing' }); } }); FlowRouter.route('/:language/login', { name: 'login', triggersEnter: [ checkLanguage ], action: () => { Tracker.autorun((tracker) => { if (Meteor.userId()) { wrs(() => { FlowRouter.go('dashboard.details'); }); tracker.stop(); } else { BlazeLayout.render('blankLayout', { content: 'login' }); } }); } }); FlowRouter.route('/:language/forgot', { name: 'forgotPassword', triggersEnter: [ checkLanguage, logout ], action: () => { Session.set('parent', 'dashboard.details'); BlazeLayout.render('blankLayout', { content: 'forgotPassword' }); } }); FlowRouter.route('/:language/reset', { name: 'resetPassword', triggersEnter: [ checkLanguage, logout ], action: () => { Session.set('parent', 'dashboard.details'); BlazeLayout.render('blankLayout', { content: 'resetPassword' }); } }); FlowRouter.route('/:language/firstLogin', { name: 'firstLogin', triggersEnter: [ checkLanguage, logout ], action: () => { Session.set('parent', 'dashboard.details'); BlazeLayout.render('blankLayout', { content: 'firstLogin' }); } });
JavaScript
0
@@ -876,20 +876,8 @@ ) =%3E - %7B%0A Flo @@ -892,38 +892,14 @@ go(' -dashboard.details');%0A %7D +home') );%0A
4c8e7d377ab97ddded7c5bdc032be6d8f66583d1
Change CacheControl to no-cache for HTML
lib/templates.js
lib/templates.js
'use strict'; const pug = require('pug'); module.exports.updateIndex = (s3, config) => { const html = pug.renderFile('views/index.pug', config.podcast) return s3.putObject({ Bucket: config.bucket, Key: 'index.html', Body: html, ContentType: 'text/html; charset=utf-8', ACL: 'public-read', CacheControl: 'max-age=3600' }).promise() } module.exports.updateError = (s3, config) => { const html = pug.renderFile('views/error.pug', config.podcast) return s3.putObject({ Bucket: config.bucket, Key: 'error.html', Body: html, ContentType: 'text/html; charset=utf-8', ACL: 'public-read', CacheControl: 'max-age=3600' }).promise() } module.exports.updateFeed = (s3, config, episodes) => { const xml = pug.renderFile('views/feed.pug', { podcast: config.podcast, episodes }); return s3.putObject({ Bucket: config.bucket, Key: 'feed.xml', Body: xml, ContentType: 'text/xml; charset=utf-8', ACL: 'public-read', CacheControl: 'max-age=3600' }).promise() } module.exports.updatePublish = (s3, config, auth) => { const html = pug.renderFile('views/publish.pug', { config, auth }); return s3.putObject({ Bucket: config.bucket, Key: 'publish.html', Body: html, ContentType: 'text/html; charset=utf-8', ACL: 'public-read', CacheControl: 'max-age=3600' }).promise() }
JavaScript
0.000001
@@ -352,36 +352,32 @@ heControl: ' -max-age=3600 +no-cache '%0A %7D).promi @@ -699,36 +699,32 @@ heControl: ' -max-age=3600 +no-cache '%0A %7D).promi @@ -1055,36 +1055,32 @@ heControl: ' -max-age=3600 +no-cache '%0A %7D).promi
d736e641fdf568dfc66ba2693ddde070e4339b86
Change initial player positions
scripts/app/game.js
scripts/app/game.js
define([ "app/assetmanager", "app/audiomanager", "app/entitycreator", "app/ecs/world", "app/ecs/entity", "app/systems/animationsystem", "app/systems/collisionsystem", "app/systems/deathsystem", "app/systems/deterioratesystem", "app/systems/inputsystem", "app/systems/movementsystem", "app/systems/rendersystem" ], function(AssetManager, AudioManager, EntityCreator, World, Entity, AnimationSystem, CollisionSystem, DeathSystem, DeteriorateSystem, InputSystem, MovementSystem, RenderSystem) { "use strict"; const MANIFEST = "assets/configs/manifest.json"; const PLAYER_COLLISIONS_ENABLED = true; const TARGET_FPS = 60; const CACHE_LEVEL = true; var canvas, width, height; var world, assetManager, audioManager, entityCreator; function Game(canvasElement) { canvas = canvasElement; width = canvasElement.width; height = canvasElement.height; // Keep aspect ratio and in-game resolution on browser resize window.addEventListener("resize", resize, false); // Make sure the canvas is initially correct resize(); } Game.prototype.start = function() { world = new World(); assetManager = new AssetManager(MANIFEST); audioManager = new AudioManager(assetManager); entityCreator = new EntityCreator(world, audioManager); // Order is important! world.addSystem(new DeteriorateSystem()); world.addSystem(new DeathSystem(entityCreator)); world.addSystem(new InputSystem(entityCreator)); world.addSystem(new MovementSystem()); world.addSystem(new CollisionSystem(PLAYER_COLLISIONS_ENABLED)); world.addSystem(new AnimationSystem()); world.addSystem(new RenderSystem(canvas, tick, TARGET_FPS)); assetManager.load(function() { loadLevel(); loadEntities(); }); }; function loadLevel() { var level = assetManager.get("level"); entityCreator.createLevel(level, CACHE_LEVEL); } function loadEntities() { var controls = assetManager.get("controls"); loadPlayer("Player 1", "link", 0, 0, controls.keyBindings[0]); loadPlayer("Player 2", "alien", 100, 100, controls.keyBindings[1]); } function loadPlayer(name, assetId, posX, posY, keyBindings) { var spriteSheet = assetManager.get(assetId); entityCreator.createPlayer(name, posX, posY, spriteSheet, keyBindings); } function tick(event) { world.update(event.delta); } function resize() { var gameWidth = window.innerWidth; var gameHeight = window.innerHeight; var scaleToFitX = gameWidth / width; var scaleToFitY = gameHeight / height; var currentScreenRatio = gameWidth / gameHeight; var optimalRatio = Math.min(scaleToFitX, scaleToFitY); if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) { canvas.style.width = gameWidth + "px"; canvas.style.height = gameHeight + "px"; } else { canvas.style.width = width * optimalRatio + "px"; canvas.style.height = height * optimalRatio + "px"; } } return Game; });
JavaScript
0
@@ -2255,19 +2255,23 @@ %22link%22, +10 0, +50 0, contr @@ -2335,15 +2335,15 @@ n%22, -1 +9 00, -10 +35 0, c
ddc14a11c2d68f063c570a1cc52874db98451620
add POST /users object schema
server/users/userRoute.js
server/users/userRoute.js
const express = require('express'); const userCtrl = require('./userCtrl'); const userRoute = module.exports = express.Router(); userRoute.get('/', userCtrl.getUsers); userRoute.post('/');
JavaScript
0.000001
@@ -73,60 +73,433 @@ ');%0A -%0Aconst userRoute = module.exports = express.Router() +const Joi = require('joi');%0Aconst validate = require('../utils/validate');%0A%0Aconst userRoute = module.exports = express.Router();%0A%0Aconst createUserSchema = %7B%0A email: Joi.string().email().required(),%0A password: Joi.string().regex(/%5E%5Ba-zA-Z0-9%5D%7B3,30%7D$/).required(),%0A first_name: Joi.string().alphanum().min(3).max(30).required(),%0A last_name: Joi.string().alphanum().min(3).max(30).required(),%0A dob: Joi.date().required(),%0A%7D ;%0A%0Au @@ -554,11 +554,60 @@ post('/' +, validate(createUserSchema), userCtrl.createUser );%0A
6876301c04e048f66dad03bd7fc3edf14c2e7dbc
indent formatting
api/api.js
api/api.js
import express from 'express'; import session from 'express-session'; import bodyParser from 'body-parser'; import config from '../src/config'; import * as actions from './actions/index'; import { mapUrl } from 'utils/url.js'; import PrettyError from 'pretty-error'; import http from 'http'; const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); app.use(session({ secret: 'react and redux rule!!!!', resave: false, saveUninitialized: false, cookie: { maxAge: 60000 }, })); app.use(bodyParser.json()); app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const { action, params } = mapUrl(actions, splittedUrlPath); if (action) { action(req, params) .then((result) => { if (result instanceof Function) { result(res); } else { res.json(result); } }, (reason) => { if (reason && reason.redirect) { res.redirect(reason.redirect); } else { console.error('API ERROR:', pretty.render(reason)); res.status(reason.status || 500).json(reason); } }); } else { res.status(404).end('NOT FOUND'); } }); if (config.apiPort) { const runnable = app.listen(config.apiPort, (err) => { if (err) { console.error(err); } const green = '\x1b[34m'; const red = '\x1b[31m'; const dim = '\x1b[2m'; console.log('\n', dim, '==================| API Ready |=================\n'); console.log(green, `==> 🔮 API is running on port ${config.apiPort}`); console.log(green, '==> 💦 Send requests to', red, `http://${config.apiHost}:${config.apiPort}`); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
JavaScript
0.000002
@@ -761,23 +761,16 @@ params) -%0A .then((r @@ -777,24 +777,26 @@ esult) =%3E %7B%0A + if @@ -841,16 +841,18 @@ + result(r @@ -856,16 +856,18 @@ t(res);%0A + @@ -887,24 +887,26 @@ + res.json(res @@ -907,24 +907,26 @@ on(result);%0A + %7D%0A @@ -931,16 +931,18 @@ %7D%0A + %7D, (reas @@ -946,24 +946,26 @@ eason) =%3E %7B%0A + if @@ -1005,24 +1005,26 @@ + res.redirect @@ -1038,24 +1038,26 @@ .redirect);%0A + %7D @@ -1069,32 +1069,34 @@ %7B%0A + console.error('A @@ -1131,16 +1131,18 @@ ason));%0A + @@ -1200,26 +1200,30 @@ ;%0A -%7D%0A + %7D%0A %7D);%0A
9d06a8e670cbc67b87a1644d24e35b3edfddf64a
Add the filter to the init file.
src/init.js
src/init.js
(function (angular) { 'use strict'; angular.module('djangularRestFramework', [ 'drf-config', 'drf-provider' ]); }(window.angular));
JavaScript
0
@@ -125,16 +125,51 @@ rovider' +,%0A 'drf-display-name-filter' %0A %5D);
832aaabdda787b766cc6b5ac9fe9e2e0bf053380
add "name" arg to trailpack constructor
lib/trailpack.js
lib/trailpack.js
'use strict' const Trailpack = require('trailpack') module.exports = class SmokesignalsTrailpack extends Trailpack { constructor(app, config) { super(app, { pkg: { name: 'trailpack-smokesignals' }, config: config || { } }) } /** * Wait for some stuff so that the process does not exit. */ configure() { this.interval = setInterval(function () { }, Math.POSITIVE_INFINITY) } unload() { clearInterval(this.interval) } }
JavaScript
0.000001
@@ -137,16 +137,22 @@ , config +, name ) %7B%0A @@ -190,16 +190,24 @@ name: + name %7C%7C 'trailp
6058362b53330e8b50a6026e23b6642c7dc15939
Fix test setup in test-permissions.js
src/base1/test-permissions.js
src/base1/test-permissions.js
/* global cockpit, QUnit */ var root_user = { name: "weird-root", id: 0, groups: null }; var priv_user = { name: "user", id: 1000, groups: ["user", "agroup"] }; QUnit.module("Permission tests", { setup: function() { this.old_dbus = cockpit.dbus; this.old_is_superuser = cockpit._is_superuser; cockpit._is_superuser = false; }, teardown: function() { cockpit.dbus = this.old_dbus; cockpit._is_superuser = this.old_is_superuser; } }); QUnit.test("root-all-permissions", function (assert) { assert.expect(2); var p1 = cockpit.permission({ user: priv_user }); assert.equal(p1.allowed, false, "not root, not allowed"); var p2 = cockpit.permission({ user: root_user }); assert.equal(p2.allowed, true, "is root, allowed"); }); QUnit.test("group-permissions", function (assert) { assert.expect(4); var p1 = cockpit.permission({ user: priv_user, group: "badgroup" }); assert.equal(p1.allowed, false, "no group, not allowed"); var p2 = cockpit.permission({ user: priv_user, group: "agroup" }); assert.equal(p2.allowed, true, "has group, allowed"); var p3 = cockpit.permission({ user: root_user, group: "agroup" }); assert.equal(p3.allowed, true, "no group but root, allowed"); var p4 = cockpit.permission({ user: { id: 0, groups: ["other"] }, group: "agroup" }); assert.equal(p4.allowed, true, "no group match but root, allowed"); }); QUnit.test("admin-permissions", function (assert) { assert.expect(2); var p1 = cockpit.permission({ user: priv_user, _is_superuser: false, admin: true }); assert.equal(p1.allowed, false, "no superuser, admin not allowed"); var p2 = cockpit.permission({ user: priv_user, _is_superuser: true, admin: true }); assert.equal(p2.allowed, true, "superuser, admin allowed"); }); QUnit.start();
JavaScript
0.000407
@@ -224,25 +224,21 @@ -setup: function() +before: () =%3E %7B%0A @@ -383,28 +383,20 @@ -teardown: function() +after: () =%3E %7B%0A
1f153faa8e8432ccba6c88074eb61c445890a6ab
update files
lib/transform.js
lib/transform.js
/** * Created by nuintun on 2015/4/27. */ 'use strict'; var fs = require('fs'); var path = require('path'); var util = require('./util'); var through = require('@nuintun/through'); var gutil = require('@nuintun/gulp-util'); var join = path.join; var relative = path.relative; /** * include * * @param options * @returns {Stream} */ module.exports = function(options) { var initialized = false; var configure = util.initOptions(options); // stream return through({ objectMode: true }, function(vinyl, encoding, next) { // throw error if stream vinyl if (vinyl.isStream()) { return next(gutil.throwError('streaming not supported.')); } // hack old vinyl vinyl._isVinyl = true; // normalize vinyl base vinyl.base = relative(vinyl.cwd, vinyl.base); // return empty vinyl if (vinyl.isNull()) { return next(null, vinyl); } // when not initialized if (!initialized) { // debug util.debug('cwd: %p', gutil.normalize(gutil.cwd)); var base = join(vinyl.cwd, vinyl.base); // base out of bound of wwwroot if (gutil.isOutBound(base, configure.wwwroot)) { gutil.throwError( 'base: %s is out of bound of wwwroot: %s.', gutil.normalize(base), gutil.normalize(configure.wwwroot) ); } // rewrite ignore configure.ignore = util.initIgnore(vinyl, configure); // initialized initialized = true; } // catch error try { // stream var stream = this; // clone options options = gutil.extend({}, configure); // lock wwwroot gutil.readonlyProperty(options, 'wwwroot'); // lock plugins gutil.readonlyProperty(options, 'plugins'); // transport util.transport(vinyl, options, function(vinyl, options) { var pool = {}; var pkg = vinyl.package; var start = vinyl.clone(); var end = vinyl.clone(); var path = gutil.pathFromCwd(vinyl.path); // set start and end file status start.contents = gutil.BLANK_BUFFER; start.concat = gutil.CONCAT_STATUS.START; end.contents = gutil.BLANK_BUFFER; end.concat = gutil.CONCAT_STATUS.END; // clean vinyl delete start.package; delete end.package; // compute include options.include = gutil.isFunction(options.include) ? options.include(pkg.id || null, vinyl.path) : options.include; // debug util.debug('concat: %p start', path); // push start blank vinyl stream.push(start); // include dependencies files includeDeps.call(stream, vinyl, pool, options, function() { // push end blank vinyl stream.push(end); // free memory pool = null; // debug util.debug('concat: %p ...ok', path); next(); }); }); } catch (error) { // show error message util.print(gutil.colors.reset.red.bold(error.stack) + '\x07'); next(); } }); } /** * create a new vinyl * * @param path * @param cwd * @param base * @param done * @returns {void} */ function vinylFile(path, cwd, base, done) { if (!gutil.isString(path) || !gutil.isString(cwd) || !gutil.isString(base)) { return done(null); } // cache path var src = path; // print error function printError(error) { util.print( 'file: %s is %s', gutil.colors.reset.yellow(gutil.pathFromCwd(src)), error.code ); done(null); } // read file function readFile(path, stat) { fs.readFile(path, function(error, data) { if (error) return printError(error); done(new gutil.Vinyl({ path: path, cwd: cwd, base: base, stat: stat, contents: data })); }); } // read file use origin path fs.stat(path, function(error, stat) { if (error) { path = util.hideExt(path, true); // read file use hide extname path fs.stat(path, function(error, stat) { if (error) return printError(error); readFile(path, stat); }); } else { readFile(path, stat); } }); } /** * walk file * * @param vinyl * @param pool * @param options * @param done * @returns {void} */ function walk(vinyl, pool, options, done) { var stream = this; var status = pool[vinyl.path]; /** * transport dependence file * @param module * @param next */ function transform(module, next) { var path = module.path; if (options.ignore[path] || pool[path] || (options.include === 'relative' && !gutil.isRelative(module.id))) { return next(); } // create a vinyl file vinylFile(path, vinyl.cwd, vinyl.base, function(child) { // read file success if (child === null) return next(); // debug util.debug('include: %r', child.path); // transport file util.transport(child, options, function(child, options) { // cache next status.next = next; // add cache status pool[child.path] = { next: null, parent: status, included: false }; // walk walk.call(stream, child, pool, options, done); }); }); } /** * include current file and flush status * * @returns {void} */ function flush() { // push file to stream if (!status.included) { stream.push(vinyl); // change cache status status.next = null; status.included = true; } var parent = status.parent; // all file include if (parent === null || parent.next === null) { done(); } else { // run parent next dependencies parent.next(); // clean parent delete status.parent; } } var pkg = vinyl.package; // bootstrap if (status.included || !pkg) { flush(); } else { gutil.async.series(pkg.include, transform, flush); } } /** * include dependencies file * * @param vinyl * @param pool * @param options * @param done * @returns {void} */ function includeDeps(vinyl, pool, options, done) { // return if include not equal 'all' and 'relative' if (options.include !== 'all' && options.include !== 'relative') { // push file to stream this.push(vinyl); // free memory pool = null; return done(); } // set pool cache pool[vinyl.path] = { next: null, parent: null, included: false }; // bootstrap walk.call(this, vinyl, pool, options, function() { // free memory pool = null; // callback done(); }); }
JavaScript
0.000001
@@ -1535,16 +1535,162 @@ = this; +%0A var path = gutil.pathFromCwd(vinyl.path);%0A%0A // print process progress%0A util.print('process: %25s', gutil.colors.reset.green(path)); %0A%0A @@ -2107,58 +2107,8 @@ e(); -%0A var path = gutil.pathFromCwd(vinyl.path); %0A%0A
4dccc9d4df086999dca3ca67ded848bc612aaa7b
Fix super destroy in item
src/item.js
src/item.js
import { select } from 'd3'; import { Observer } from '@scola/d3-model'; import Button from './part/button'; import Icon from './part/icon'; import Icons from './part/icons'; import Scroller from './part/scroller'; import Space from './part/space'; import Switch from './part/switch'; import Input from './part/input'; import Text from './part/text'; import Textarea from './part/textarea'; import Texts from './part/texts'; export default class Item extends Observer { constructor() { super(); this._parts = []; this._disabled = false; this._first = false; this._visible = true; this._root = select('body') .append('div') .remove() .classed('scola item', true) .styles({ 'background': '#FFF', 'display': 'flex', 'flex-direction': 'row' }); this._padding = this._root .append('div') .classed('scola padding', true) .styles({ 'border-top': '1px solid transparent', 'width': '1em' }); this._bindRoot(); this.first(false); } destroy() { super.destroy(); this._unbindRoot(); this._parts.forEach((part) => { part.destroy(); }); this._parts = []; this._root.dispatch('destroy'); this._root.remove(); this._root = null; } root() { return this._root; } disabled(value = null) { if (value === null) { return this._disabled; } this._disabled = value; this._root.classed('disabled', value); this._parts.forEach((part) => { part.disabled(value); }); return this; } first(value = null) { if (value === null) { return this._first; } this._first = value; const color = value === true ? 'transparent' : '#CCC'; this._root.style('border-color', color); return this; } show(value = null) { if (value === null) { return this._visible; } this._visible = value; const display = value === true ? 'flex' : 'none'; this._root.style('display', display); return this; } order(part = null, value = -1) { if (part !== null) { this._move(part, value); } this._order(); } part(index) { return this._parts[index]; } button(value = null) { const button = new Button() .item(this); button.class(value); this._add(button); return button; } icon(value = null) { const icon = new Icon() .item(this); icon.class(value); this._add(icon); return icon; } icons() { const icon = new Icons() .item(this); this._add(icon); return icon; } input(value = null) { const input = new Input() .item(this); input.type(value); this._add(input); return input; } scroller() { const scroller = new Scroller() .item(this); this._add(scroller); return scroller; } space() { const space = new Space() .item(this); this._add(space); return space; } switch () { const part = new Switch() .item(this); this._add(part); return part; } text(value = null) { const text = new Text() .item(this); text.text(value); this._add(text); return text; } textarea() { const textarea = new Textarea() .item(this); this._add(textarea); return textarea; } texts() { const texts = new Texts() .item(this); this._add(texts); return texts; } _bindRoot() { this._root.on('click.scola-item', () => this._click()); } _unbindRoot() { this._root.on('click.scola-item', null); } _add(part) { this._parts.push(part); this._order(); } _move(part, value) { this._parts.splice(value, 0, this._parts.splice( this._parts.indexOf(part), 1).pop()); } _order() { this._parts.forEach((part, index) => { part.order(index + 2, false); this._root.append(() => part.root().node()); }); } _click() {} }
JavaScript
0
@@ -1074,29 +1074,8 @@ ) %7B%0A - super.destroy();%0A @@ -1268,16 +1268,38 @@ = null; +%0A%0A super.destroy(); %0A %7D%0A%0A
c21c0e1150092a461ff330947c9f3b909438d759
Add error to debug panel
src/components/views/settings/CrossSigningPanel.js
src/components/views/settings/CrossSigningPanel.js
/* Copyright 2019 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import MatrixClientPeg from '../../../MatrixClientPeg'; import { _t } from '../../../languageHandler'; import sdk from '../../../index'; import Modal from '../../../Modal'; export default class CrossSigningPanel extends React.PureComponent { constructor(props) { super(props); this.state = this._getUpdatedStatus(); } _getUpdatedStatus() { // XXX: Add public accessors if we keep this around in production const cli = MatrixClientPeg.get(); const crossSigning = cli._crypto._crossSigningInfo; const secretStorage = cli._crypto._secretStorage; const crossSigningPublicKeysOnDevice = crossSigning.getId(); const crossSigningPrivateKeysInStorage = crossSigning.isStoredInSecretStorage(secretStorage); const secretStorageKeyInAccount = secretStorage.hasKey(); return { crossSigningPublicKeysOnDevice, crossSigningPrivateKeysInStorage, secretStorageKeyInAccount, }; } _bootstrapSecureSecretStorage = async () => { try { const InteractiveAuthDialog = sdk.getComponent("dialogs.InteractiveAuthDialog"); await MatrixClientPeg.get().bootstrapSecretStorage({ authUploadDeviceSigningKeys: async (makeRequest) => { const { finished } = Modal.createTrackedDialog( 'Cross-signing keys dialog', '', InteractiveAuthDialog, { title: _t("Send cross-signing keys to homeserver"), matrixClient: MatrixClientPeg.get(), makeRequest, }, ); const [confirmed] = await finished; if (!confirmed) { throw new Error("Cross-signing key upload auth canceled"); } }, }); } catch (e) { console.error(e); } this.setState(this._getUpdatedStatus()); } render() { const AccessibleButton = sdk.getComponent("elements.AccessibleButton"); const { crossSigningPublicKeysOnDevice, crossSigningPrivateKeysInStorage, secretStorageKeyInAccount, } = this.state; return ( <div> <table className="mx_CrossSigningPanel_statusList"><tbody> <tr> <td>{_t("Cross-signing public keys:")}</td> <td>{crossSigningPublicKeysOnDevice ? _t("on device") : _t("not found")}</td> </tr> <tr> <td>{_t("Cross-signing private keys:")}</td> <td>{crossSigningPrivateKeysInStorage ? _t("in secret storage") : _t("not found")}</td> </tr> <tr> <td>{_t("Secret storage public key:")}</td> <td>{secretStorageKeyInAccount ? _t("in account data") : _t("not found")}</td> </tr> </tbody></table> <div className="mx_CrossSigningPanel_buttonRow"> <AccessibleButton kind="primary" onClick={this._bootstrapSecureSecretStorage}> {_t("Bootstrap Secure Secret Storage")} </AccessibleButton> </div> </div> ); } }
JavaScript
0
@@ -912,16 +912,58 @@ state = +%7B%0A error: null,%0A ... this._ge @@ -978,16 +978,27 @@ Status() +,%0A %7D ;%0A %7D%0A @@ -1707,24 +1707,64 @@ ync () =%3E %7B%0A + this.setState(%7B error: null %7D);%0A try @@ -2655,24 +2655,65 @@ catch (e) %7B%0A + this.setState(%7B error: e %7D);%0A @@ -2903,24 +2903,43 @@ const %7B%0A + error,%0A @@ -3080,16 +3080,150 @@ state;%0A%0A + let errorSection;%0A if (error) %7B%0A errorSection = %3Cdiv className=%22error%22%3E%7Berror.toString()%7D%3C/div%3E;%0A %7D%0A%0A @@ -4300,16 +4300,16 @@ Button%3E%0A - @@ -4315,32 +4315,63 @@ %3C/div%3E%0A + %7BerrorSection%7D%0A %3C/di
66ae77de174ed45ae58adf04b0b4faf94e7713a3
Modify payload format for kafka message
api/log.js
api/log.js
'use strict' const config = require('config') const logAPI = module.exports = {} logAPI.get = function *() { var token // TODO: Add support for session cookie authentication. token = this.token // Check necessary if fields are provided. if (!token._id) this.throw('User id is required.', 400) var log = this.query.log if (!log) this.throw('Log has no content.', 400) var payload = [{ topic: config.kafkaTopic, messages: log }] // Commit logs to kafka. yield this.kafkaClient.send(payload) this.body = { token: token, log: log } }
JavaScript
0.000003
@@ -306,35 +306,8 @@ 00)%0A - var log = this.query.log%0A if @@ -374,9 +374,8 @@ d = -%5B %7B%0A @@ -427,9 +427,8 @@ %0A %7D -%5D %0A%0A @@ -482,23 +482,25 @@ nt.send( +%5B payload +%5D )%0A%0A thi
5e04c005e3d35c1b3f7e7b31aa5c475debf01224
Allow fetchData in development mode
app/app.js
app/app.js
import 'babel/polyfill'; import './client/lib/index'; import $ from 'jquery'; import React from 'react'; import Router from 'react-router'; import app from 'app/client/components/main/app'; import routes from './routes'; import configureStore from './client/stores/index'; $(document).ready(() => { const appDOM = document.getElementById('app'); const store = configureStore(window.__data); Router.run(routes, Router.HistoryLocation, (Handler, routerState) => { React.render(app(store, Handler, routerState), appDOM); }); });
JavaScript
0.000001
@@ -397,79 +397,333 @@ %0A%0A -Router.run(routes, Router.HistoryLocation, (Handler, routerState) =%3E %7B%0A +if (process.env.NODE_ENV === 'development') %7B%0A const fetchData = require('./client/helpers/fetch-data');%0A let areFetchedData = false;%0A%0A Router.run(routes, Router.HistoryLocation, (Handler, routerState) =%3E %7B%0A if (!areFetchedData) %7B%0A fetchData(store, routerState);%0A areFetchedData = true;%0A %7D%0A @@ -782,14 +782,176 @@ M);%0A + %7D);%0A + %7D else %7B%0A Router.run(routes, Router.HistoryLocation, (Handler, routerState) =%3E %7B%0A React.render(app(store, Handler, routerState), appDOM);%0A %7D);%0A %7D%0A %7D);%0A
8d3c0cdde2fe97121bd45202589e9e537e0aafd2
Remove logging.
src/article/CellComponent.js
src/article/CellComponent.js
/* globals clearTimeout */ import { NodeComponent, FontAwesomeIcon, isEqual } from 'substance' import ValueComponent from '../shared/ValueComponent' import CodeEditor from '../shared/CodeEditor' import { getCellState, getError, getErrorMessage } from '../shared/cellHelpers' import { toString as stateToString, BROKEN, FAILED, OK } from '../engine/CellStates' import NodeMenu from './NodeMenu' const LANG_LABELS = { 'mini': 'Mini', 'js': 'JS', 'node': 'Node', 'sql': 'SQL', 'py': 'Py', 'r': 'R', } export default class CellComponent extends NodeComponent { constructor(...args) { super(...args) this.handleActions({ // triggered by CodeEditorComponent and MiniLangEditor 'execute': this._onExecute, 'break': this._onBreak }) } didMount() { this.context.editorSession.onRender('document', this._onNodeChange, this, { path: [this.props.node.id]}) } getInitialState() { return { hideCode: false, forceOutput: false } } _renderStatus($$) { const cellState = getCellState(this.props.node) let statusName = cellState ? stateToString(cellState.status) : 'unknown' return $$('div').addClass(`se-status sm-${statusName}`) } render($$) { const cell = this.props.node const cellState = getCellState(cell) let el = $$('div').addClass('sc-cell') el.attr('data-id', cell.id) if (!this.state.hideCode) { let source = cell.find('source-code') let cellEditorContainer = $$('div').addClass('se-cell-editor-container') cellEditorContainer.append( this._renderStatus($$), $$('div').addClass('se-expression').append( $$(CodeEditor, { path: source.getPath(), excludedCommands: this._getBlackListedCommands(), language: source.attributes.language, multiline: true }).ref('expressionEditor') .on('escape', this._onEscapeFromCodeEditor) ) ) el.append(cellEditorContainer) el.append( this._renderEllipsis($$) ) el.append( $$('div').addClass('se-language').append( LANG_LABELS[source.attributes.language] ) ) } else { // TODO: Create proper visual style el.append( $$('button').append( this._renderStatus($$), $$(FontAwesomeIcon, { icon: 'fa-code' }) ) .addClass('se-show-code') .attr('title', 'Show Code') .on('click', this._showCode) ) } if (cellState) { const status = cellState.status if(status === FAILED || status === BROKEN) { let errEl = $$('div').addClass('se-error').append( getErrorMessage(getError(cell)) ).ref('error') if (this._hideError) { errEl.setStyle('visibility', 'hidden') } el.append(errEl) } else if (status === OK) { if (this._showOutput()) { el.append( $$(ValueComponent, cellState.value).ref('value') ) } } else if (this.oldValue && this._showOutput()) { el.append( $$(ValueComponent, this.oldValue).ref('value') ).addClass('sm-pending') } } return el } /* Move this into an overlay, shown depending on app state */ _renderEllipsis($$) { let Button = this.getComponent('button') let el = $$('div').addClass('se-ellipsis') let configurator = this.context.editorSession.getConfigurator() let button = $$(Button, { icon: 'ellipsis', active: false, theme: 'light' }).on('click', this._toggleMenu) el.append(button) let sel = this.context.editorSession.getSelection() if (sel.isNodeSelection() && sel.getNodeId() === this.props.node.id) { el.append( $$(NodeMenu, { toolPanel: configurator.getToolPanel('node-menu') }).ref('menu') ) } return el } getExpression() { return this.refs.expressionEditor.getContent() } _renderMenu($$) { let menuEl = $$('div').addClass('se-menu') menuEl.append( this._renderToggleCode($$), this._renderToggleOutput($$) ) return menuEl } _getBlackListedCommands() { const commandGroups = this.context.commandGroups let result = [] ;['annotations', 'insert', 'prompt', 'text-types'].forEach((name) => { if (commandGroups[name]) { result = result.concat(commandGroups[name]) } }) return result } _showCode() { this.extendState({ hideCode: false }) } /* Generally output is shown when cell is not a definition, however it can be enforced */ _showOutput() { return !this._isDefinition() || this.state.forceOutput } _isDefinition() { const cellState = getCellState(this.props.node) return cellState && cellState.hasOutput() } _toggleMenu() { this.context.editorSession.setSelection({ type: 'node', containerId: 'body-content-1', surfaceId: 'bodyEditor', nodeId: this.props.node.id, }) } _onNodeChange() { const cell = this.props.node const cellState = getCellState(cell) const oldCellState = this._oldCellState if (cellState) { // 1. does the cell have an error? // 2. did the status or the errors change? let showError = true const status = cellState.status if(status === BROKEN || status === FAILED) { if (oldCellState) { showError = ( oldCellState.status !== status || !isEqual(oldCellState.errors.map(e => e.message), cellState.errors.map(e => e.message)) ) if (showError) { console.log('SHOW ERROR', oldCellState.status, status, oldCellState.errors.join(','), cellState.errors.join(',')) } } } clearTimeout(this.delayError) if (showError) { this._hideError = true this.delayError = setTimeout(() => { const errEl = this.refs.error if(errEl) { errEl.setStyle('visibility', 'visible') } this._hideError = false }, 500) } this._oldCellState = { status, errors: cellState.errors.slice() } // keep the last valid value to be able to reduce flickering in most of the cases if (status === OK) { this.oldValue = cellState.value } } this.rerender() } _onExecute() { this.context.cellEngine.recompute(this.props.node.id) } _onBreak() { this.context.editorSession.transaction((tx) => { tx.selection = this._afterNode() tx.insertBlockNode({ type: 'p' }) }) } _onEscapeFromCodeEditor(event) { event.stopPropagation() this.send('escape') } _afterNode() { // TODO: not too happy about how difficult it is to set the selection const node = this.props.node const isolatedNode = this.context.isolatedNodeComponent const parentSurface = isolatedNode.getParentSurface() return { type: 'node', nodeId: node.id, mode: 'after', containerId: parentSurface.getContainerId(), surfaceId: parentSurface.id } } } CellComponent.noBlocker = true
JavaScript
0
@@ -5650,173 +5650,8 @@ )%0A - if (showError) %7B%0A console.log('SHOW ERROR', oldCellState.status, status, oldCellState.errors.join(','), cellState.errors.join(','))%0A %7D%0A
13945ccf0e67f7d2b64e5b11735deaaf534b3bef
improve commenting
src/jump.js
src/jump.js
import easeInOutQuad from './easing' const jumper = () => { // globals let start // where scroll starts (px) let stop // where scroll stops (px) let offset // adjustment from the stop position (px) let easing // easing function let duration // scroll duration let distance // distance of scroll (px) let timeStart // time scroll started let timeElapsed // time scrolling thus far let next // next scroll position (px) let callback // fire when done scrolling function loop(timeCurrent) { if(!timeStart) { timeStart = timeCurrent } // determine time spent scrolling so far timeElapsed = timeCurrent - timeStart // calculate next scroll position next = easing(timeElapsed, start, distance, duration) // scroll to it window.scrollTo(0, next) // continue looping or end timeElapsed < duration ? requestAnimationFrame(loop) : end() } function end() { // account for rounding inaccuracies window.scrollTo(0, start + distance) // if it exists, fire the callback if(typeof callback === 'function') { callback() } // reset for next jump timeStart = undefined } function jump(target, options = {}) { // cache starting position start = window.scrollY || window.pageYOffset // resolve duration, the only required option // if its not a number, assume its a function duration = typeof options.duration === 'number' ? options.duration : options.duration(distance) // resolve offset offset = options.offset || 0 // resolve callback callback = options.callback // resolve easing easing = options.easing || easeInOutQuad // resolve target switch(typeof target) { // scroll from current position case 'number': stop = start + target break // scroll to element (node) case 'object': stop = target.getBoundingClientRect().top break // scroll to element (selector) case 'string': stop = document.querySelector(target).getBoundingClientRect().top break } // resolve distance distance = stop - start // start the loop requestAnimationFrame(loop) } return jump } // export singleton const singleton = jumper() export default singleton
JavaScript
0
@@ -569,24 +569,74 @@ eCurrent) %7B%0A + // store time started scrolling when starting%0A if(!time
fdd778c1392bf9a19e46e1d8ffebb3fde046e253
Add ESC key
src/keys.js
src/keys.js
export default { LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, ENTER: 13, SPACE: 32, };
JavaScript
0.000002
@@ -83,11 +83,22 @@ CE: 32,%0A + ESC: 27,%0A %7D;%0A
a931ad038002f53dfb90b9d4fb1f0cdd0ee65b4e
Remove socket connection on app load for security
app/app.js
app/app.js
'use strict'; // Declare app level module which depends on views, and components angular.module('collaborate', [ 'ui.router', 'ngAnimate', 'ui.bootstrap', 'home', 'login', 'services', 'directives' ]). config(['$urlRouterProvider','$httpProvider', function($urlRouterProvider, $httpProvider) { $httpProvider.interceptors.push('requestInterceptor'); $urlRouterProvider.otherwise('/login'); io.connect(window.__config.socketEndPoint); }]);
JavaScript
0
@@ -404,54 +404,8 @@ ');%0A - io.connect(window.__config.socketEndPoint);%0A %7D%5D);
97c5f7e647ecd659275db54c5f1519fa0ebec902
Add cleaning of generators
scripts/clean_up.js
scripts/clean_up.js
import craftai from '../src'; const craftToken = { token: process.env.CRAFT_TOKEN }; const JOB_ID = process.env.TRAVIS_JOB_ID || 'local'; const client = craftai(craftToken); console.log(client); client.listAgents() .then((agentNames) => { console.log('got', agentNames.length); agentNames.filter((agentName) => agentName.includes(JOB_ID)); return agentNames.reduce((acc, agentName) => acc.then((count) => client.deleteAgent(agentName) .then(() => { console.log('Deleted agent', agentName); return count += 1; })), Promise.resolve(0)); }) .then((nAgentDeleted) => { console.log(`${nAgentDeleted} agent(s) were deleted.`); process.exit(0); }) .catch(function(error) { console.error('Error!', error); process.exit(1); });
JavaScript
0
@@ -168,16 +168,17 @@ Token);%0A +%0A console. @@ -185,16 +185,65 @@ log( -client); +'Clearning up dangling agents and generators from tests') %0Acli @@ -669,24 +669,24 @@ leted) =%3E %7B%0A - console. @@ -733,16 +733,607 @@ ted.%60);%0A + return client.listGenerators%0A .then((generatorsName) =%3E %7B%0A console.log('got', agentNames.length);%0A generatorsName.filter((agentName) =%3E agentName.includes(JOB_ID));%0A return generatorsName.reduce((acc, agentName) =%3E%0A acc.then((count) =%3E client.deleteGenerator(agentName)%0A .then(() =%3E %7B%0A console.log('Deleted generators', agentName);%0A return count += 1;%0A %7D)),%0A Promise.resolve(0));%0A %7D)%0A %7D)%0A .then((nGeneratorDeleted) =%3E %7B%0A console.log(%60$%7BnGeneratorDeleted%7D generator(s) were deleted.%60);%0A proc
e17734aaac261ed3d88076bab8503bd594da2f5e
Fix show/hide editor
app/app.js
app/app.js
var Pastebin = Pastebin || {}; Pastebin = (function () { 'use strict'; // common RDF vocabs var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); var DCT = $rdf.Namespace("http://purl.org/dc/terms/"); var SIOC = $rdf.Namespace("http://rdfs.org/sioc/ns#"); var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/terms#"); // Bin structure var bin = { url: '', title: '', body: '' }; // Default publish location // ATTENTION: this variable must be set for the app to create new bins var defaultContainer = ''; function init() { if (queryVals['view'] && queryVals['view'].length > 0) { loadBin(queryVals['view']); } else if (queryVals['edit'] && queryVals['edit'].length > 0) { loadBin(queryVals['edit'], true); } else { document.getElementById('submit').setAttribute('onclick', 'Pastebin.publish()'); document.getElementById('edit').classList.remove('hidden'); } } function loadBin (url, showEditor) { Solid.web.get(url).then(function(g) { // set url bin.url = url; // add title var title = g.any($rdf.sym(url), DCT('title')); if (title) { bin.title = title.value; } // add body var body = g.any($rdf.sym(url), SIOC('content')); if (body) { bin.body = body.value; } if (showEditor) { document.getElementById('edit-title').value = bin.title; document.getElementById('edit-body').innerHTML = bin.body; document.getElementById('submit').setAttribute('onclick', 'Pastebin.update()'); document.getElementById('edit').classList.remove('hidden'); } else { document.getElementById('view-title').innerHTML = bin.title; document.getElementById('view-body').innerHTML = bin.body; document.getElementById('view').classList.remove('hidden'); document.getElementById('edit').classList.add('hidden'); } }).catch(function(err) { // do something with the error console.log(err); }); } function publish () { bin.title = document.getElementById('edit-title').value; bin.body = document.getElementById('edit-body').value; var g = new $rdf.graph(); g.add($rdf.sym(''), DCT('title'), bin.title); g.add($rdf.sym(''), SIOC('content'), bin.body); var data = new $rdf.Serializer(g).toN3(g); Solid.web.post(defaultContainer, undefined, data).then(function(meta) { // view window.location.search = "?view="+encodeURIComponent(meta.url); }).catch(function(err) { // do something with the error console.log(err); }); } function update () { bin.title = document.getElementById('edit-title').value; bin.body = document.getElementById('edit-body').value; var g = new $rdf.graph(); g.add($rdf.sym(''), DCT('title'), bin.title); g.add($rdf.sym(''), SIOC('content'), bin.body); var data = new $rdf.Serializer(g).toN3(g); Solid.web.put(bin.url, data).then(function(meta) { // view window.location.search = "?view="+encodeURIComponent(meta.url); }).catch(function(err) { // do something with the error console.log(err); }); } // Utility function to parse URL query string values var queryVals = (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('=', 2); if (p.length == 1) b[p[0]] = ""; else b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })(window.location.search.substr(1).split('&')); init(); // return public functions return { publish: publish, update: update }; }(this));
JavaScript
0
@@ -615,24 +615,155 @@ on init() %7B%0A + document.getElementById('edit').classList.add('hidden');%0A document.getElementById('view').classList.add('hidden');%0A%0A if ( @@ -823,35 +823,32 @@ load -Bin (queryVals%5B'view @@ -940,19 +940,16 @@ load -Bin (queryVa @@ -976,32 +976,68 @@ %7D else %7B%0A + console.log('showing');%0A docu @@ -1219,19 +1219,16 @@ ion load -Bin (url, s @@ -2268,81 +2268,8 @@ ');%0A - document.getElementById('edit').classList.add('hidden');%0A
0c748fc84a4dc332fc6dd8b8875d2fac89a092e7
fix controls bug where clicking in time box triggers event
scripts/controls.js
scripts/controls.js
/*jslint nomen: true, browser: true*/ /*global define*/ define([ 'jquery', 'underscore', 'backbone', 'text!../templates/controls.html' ], function ($, _, Backbone, controlsTmpl) { 'use strict'; var ControlsView; ControlsView = Backbone.View.extend({ template: _.template(controlsTmpl), className: 'globalControls', initialize: function () { this.reader = new FileReader(); this.render(); }, events: { 'change input#file': 'readFile', 'click #lifelineform > input': 'readTextArea', 'click #timecontrols > input': 'renderNewTimeLimits' }, renderNewTimeLimits: function (e) { var start, end; e.preventDefault(); start = this.$('#tree-start').val(); end = this.$('#tree-end').val(); this.model.set({ startTime: parseInt(start, 10), endTime: parseInt(end, 10) }); this.model.updateTimeLimits(); }, render: function () { this.$el.html(this.template(this.model.toJSON())); this.$('.error').hide(); return this; }, parse: function (text) { this.$('.error').hide(); try { this.model.parseShowtagsC(text); } catch (e) { this.$('.error').text(e.message).show(); } }, readTextArea: function (e) { e.preventDefault(); parse(this.$('#lifelineform > textarea').val()); }, readFile: function (ev) { var parentView, fileList; fileList = ev.currentTarget.files; parentView = this; this.reader.readAsText(fileList[0], 'UTF-8'); this.reader.onloadend = function () { var text; text = parentView.reader.result; parentView.parse(text); } } }); return ControlsView; });
JavaScript
0
@@ -572,24 +572,39 @@ form %3E input +%5Btype=%22submit%22%5D ': 'readText @@ -650,16 +650,31 @@ %3E input +%5Btype=%22submit%22%5D ': 'rend
14d049a5fbdc82f844f3bc477762d9ab7b092f15
Use fs.wrtieFile instead
lib/util/file.js
lib/util/file.js
var fs = require('graceful-fs'), path = require('path'), async = require('async'), _ = require('lodash'), EOL = require('os').EOL, EOLre = new RegExp(EOL, 'g'); if (!fs.exists || !fs.existsSync){ fs.exists = path.exists; fs.existsSync = path.existsSync; } var mkdir = exports.mkdir = function(destination, callback){ var parent = path.dirname(destination); fs.exists(parent, function(exist){ if (exist){ fs.mkdir(destination, callback); } else { mkdir(parent, function(){ fs.mkdir(destination, callback); }); } }); }; var writeFile = function(destination, content, callback) { fs.open(destination, "w", function(err, fd) { if (err) callback(err); fs.write(fd, content, 0, "utf8", function(err, written, buffer) { callback(err); }); }); }; var write = exports.write = function(destination, content, callback){ var parent = path.dirname(destination); fs.exists(parent, function(exist){ if (exist){ writeFile(destination, content, callback); } else { mkdir(parent, function(){ writeFile(destination, content, callback); }); } }); }; var copy = exports.copy = function(source, destination, callback){ var parent = path.dirname(destination); async.series([ function(next){ fs.exists(parent, function(exist){ if (exist) next(); else mkdir(parent, next); }); } ], function(){ var rs = fs.createReadStream(source), ws = fs.createWriteStream(destination); rs.pipe(ws) .on('error', function(err){ if (err) throw err; }); ws.on('close', callback) .on('error', function(err){ if (err) throw err; }); }); }; var dir = exports.dir = function(source, callback, parent){ fs.exists(source, function(exist){ if (exist){ fs.readdir(source, function(err, files){ if (err) throw err; var result = []; async.forEach(files, function(item, next){ fs.stat(source + '/' + item, function(err, stats){ if (err) throw err; if (stats.isDirectory()){ dir(source + '/' + item, function(children){ result = result.concat(children); next(); }, (parent ? parent + '/' : '') + item); } else { result.push((parent ? parent + '/' : '') + item); next(); } }); }, function(){ callback(result); }); }); } else { return []; } }); }; var textProcess = function(str){ // Transform EOL var str = EOL === '\n' ? str : str.replace(EOLre, '\n'); // Remove UTF BOM str = str.replace(/^\uFEFF/, ''); return str; }; var read = exports.read = function(source, callback){ fs.exists(source, function(exist){ if (exist){ fs.readFile(source, 'utf8', function(err, result){ if (err) return callback(err); callback(null, textProcess(result)); }); } else { callback(null); } }); }; var readSync = exports.readSync = function(source){ var result = fs.readFileSync(source, 'utf8'); if (result){ return textProcess(result); } }; var empty = exports.empty = function(target, exception, callback){ if (_.isFunction(exception)){ callback = exception; exception = []; } if (!Array.isArray(exception)) exception = []; if (target.substr(target.length - 1, 1) !== '/') target += '/'; var arr = [], exclude = {}; exception.forEach(function(item){ var split = item.split('/'), front = split.shift(); arr.push(front); if (!exclude[front]) exclude[front] = []; if (split.length) exclude[front].push(split.join('/')); }); fs.readdir(target, function(err, files){ if (err) throw err; files = _.filter(files, function(item){ return item.substr(0, 1) !== '.'; }); async.forEach(files, function(item, next){ var dest = target + item; fs.stat(dest, function(err, stats){ if (err) throw err; if (stats.isDirectory()){ empty(dest, exclude[item], function(){ fs.readdir(dest, function(err, files){ if (err) throw err; if (files.length === 0) fs.rmdir(dest, next); else next(); }); }); } else { if (arr.indexOf(item) === -1) fs.unlink(dest, next); else next(); } }); }, callback); }); };
JavaScript
0
@@ -985,24 +985,27 @@ ist)%7B%0A +fs. writeFile(de @@ -1088,16 +1088,19 @@ +fs. writeFil
6379557d7cf328f214a581fa5e781f9ec9d67573
Fix security token on settings page in Chrome
common/ui/inline/mvelo.js
common/ui/inline/mvelo.js
/** * Mailvelope - secure email with OpenPGP encryption for Webmail * Copyright (C) 2012 Thomas Oberndörfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ var mvelo = mvelo || {}; // chrome extension mvelo.crx = typeof chrome !== 'undefined'; // firefox addon mvelo.ffa = mvelo.ffa || typeof self !== 'undefined' && self.port || !mvelo.crx; // for fixfox, mvelo.extension is exposed from a content script mvelo.extension = mvelo.extension || mvelo.crx && chrome.runtime; // extension.connect shim for Firefox mvelo.extension.connect = mvelo.extension.connect || mvelo.ffa && function(obj) { mvelo.extension._connect(obj); obj.events = {}; var port = { postMessage: mvelo.extension.port.postMessage, disconnect: mvelo.extension.port.disconnect.bind(null, obj), onMessage: { addListener: mvelo.extension.port.addListener.bind(null, obj) } }; // page unload triggers port disconnect window.addEventListener('unload', port.disconnect); return port; }; // for fixfox, mvelo.l10n is exposed from a content script mvelo.l10n = mvelo.l10n || mvelo.crx && { getMessages: function(ids, callback) { var result = {}; ids.forEach(function(id) { result[id] = chrome.i18n.getMessage(id); }); callback(result); }, localizeHTML: function(l10n) { $('[data-l10n-id]').each(function() { var jqElement = $(this); var id = jqElement.data('l10n-id'); var text = l10n ? l10n[id] : chrome.i18n.getMessage(id); jqElement.text(text); }); } }; // min height for large frame mvelo.LARGE_FRAME = 600; // frame constants mvelo.FRAME_STATUS = 'stat'; // frame status mvelo.FRAME_ATTACHED = 'att'; mvelo.FRAME_DETACHED = 'det'; // key for reference to frame object mvelo.FRAME_OBJ = 'fra'; // marker for dynamically created iframes mvelo.DYN_IFRAME = 'dyn'; mvelo.IFRAME_OBJ = 'obj'; // armor header type mvelo.PGP_MESSAGE = 'msg'; mvelo.PGP_SIGNATURE = 'sig'; mvelo.PGP_PUBLIC_KEY = 'pub'; mvelo.PGP_PRIVATE_KEY = 'priv'; // editor mode mvelo.EDITOR_WEBMAIL = 'webmail'; mvelo.EDITOR_EXTERNAL = 'external'; mvelo.EDITOR_BOTH = 'both'; // display decrypted message mvelo.DISPLAY_INLINE = 'inline'; mvelo.DISPLAY_POPUP = 'popup'; // editor type mvelo.PLAIN_TEXT = 'plain'; mvelo.RICH_TEXT = 'rich'; // random hash generator mvelo.getHash = function() { return Math.random().toString(36).substr(2, 8); }; mvelo.encodeHTML = function(text) { return String(text) .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;") .replace(/\//g, "&#x2F;"); }; if (typeof exports !== 'undefined') { exports.mvelo = mvelo; }
JavaScript
0.000002
@@ -1073,33 +1073,26 @@ fox%0A +if ( mvelo. -extension.connect = +ffa) %7B%0A mve @@ -1116,23 +1116,9 @@ ect -%7C%7C mvelo.ffa && += fun @@ -1128,24 +1128,26 @@ on(obj) %7B%0A + + mvelo.extens @@ -1165,16 +1165,18 @@ t(obj);%0A + obj.ev @@ -1186,16 +1186,18 @@ s = %7B%7D;%0A + var po @@ -1207,16 +1207,18 @@ = %7B%0A + postMess @@ -1256,16 +1256,18 @@ essage,%0A + disc @@ -1327,16 +1327,18 @@ j),%0A + onMessag @@ -1342,16 +1342,18 @@ sage: %7B%0A + ad @@ -1420,17 +1420,23 @@ + %7D%0A + + %7D;%0A + + // p @@ -1471,16 +1471,18 @@ connect%0A + window @@ -1527,16 +1527,18 @@ nnect);%0A + return @@ -1544,18 +1544,22 @@ n port;%0A + %7D;%0A %7D -; %0A// for
4d78ad3c7fcd0ef6eaa41b045f9b86101b0a5076
add shape
src/cartesian/ReferenceDot.js
src/cartesian/ReferenceDot.js
/** * @fileOverview Reference Line */ import React, { Component, PropTypes } from 'react'; import pureRender from '../util/PureRender'; import Layer from '../container/Layer'; import Dot from '../shape/Dot'; import { PRESENTATION_ATTRIBUTES, getPresentationAttributes } from '../util/ReactUtils'; import { validateCoordinateInRange } from '../util/DataUtils'; import _ from 'lodash'; @pureRender class ReferenceDot extends Component { static displayName = 'ReferenceDot'; static propTypes = { ...PRESENTATION_ATTRIBUTES, r: PropTypes.number, label: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, PropTypes.func, PropTypes.element, ]), xAxisMap: PropTypes.object, yAxisMap: PropTypes.object, isFront: PropTypes.bool, alwaysShow: PropTypes.bool, x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), yAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), xAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; static defaultProps = { isFront: false, alwaysShow: false, xAxisId: 0, yAxisId: 0, r: 20, fill: '#fff', stroke: '#ccc', fillOpacity: 1, strokeWidth: 1, }; getCoordinate() { const { x, y, xAxisMap, yAxisMap, xAxisId, yAxisId } = this.props; const xScale = xAxisMap[xAxisId].scale; const yScale = yAxisMap[yAxisId].scale; const result = { cx: xScale(x), cy: yScale(y), }; if (validateCoordinateInRange(result.cx, xScale) && validateCoordinateInRange(result.cy, yScale)) { return result; } return null; } renderLabel(coordinate) { const { label, stroke } = this.props; const props = { ...getPresentationAttributes(label), stroke: 'none', fill: stroke, x: coordinate.cx, y: coordinate.cy, textAnchor: 'middle', }; if (React.isValidElement(label)) { return React.cloneElement(label, props); } else if (_.isFunction(label)) { return label(props); } else if (_.isString(label) || _.isNumber(label)) { return ( <g className="recharts-reference-dot-label"> <text {...props}>{label}</text> </g> ); } return null; } render() { const { x, y } = this.props; const isX = _.isNumber(x) || _.isString(x); const isY = _.isNumber(y) || _.isString(y); if (!isX || !isY) { return null; } const coordinate = this.getCoordinate(); if (!coordinate) { return null; } const props = getPresentationAttributes(this.props); return ( <Layer className="recharts-reference-dot"> <Dot {...props} r={this.props.r} className="recharts-reference-dot-dot" {...coordinate} /> {this.renderLabel(coordinate)} </Layer> ); } } export default ReferenceDot;
JavaScript
0
@@ -1075,16 +1075,85 @@ mber%5D),%0A + shape: PropTypes.oneOfType(%5BPropTypes.func, PropTypes.element%5D),%0A %7D;%0A%0A @@ -2376,32 +2376,340 @@ turn null;%0A %7D%0A%0A + renderDot(option, props) %7B%0A let dot;%0A%0A if (React.isValidElement(option)) %7B%0A dot = React.cloneElement(option, props);%0A %7D else if (_.isFunction(option)) %7B%0A dot = option(props);%0A %7D else %7B%0A dot = %3CDot %7B...props%7D className=%22recharts-reference-dot-dot%22 /%3E;%0A %7D%0A%0A return dot;%0A %7D%0A%0A render() %7B%0A @@ -2701,24 +2701,24 @@ render() %7B%0A - const %7B @@ -2952,32 +2952,69 @@ return null; %7D%0A%0A + const %7B shape, r %7D = this.props;%0A const props @@ -3129,121 +3129,43 @@ -%3CDot%0A %7B...props%7D%0A r=%7Bthis.props.r%7D%0A className=%22recharts-reference-dot-dot%22%0A %7B +%7Bthis.renderDot(shape, %7B ...props, ...c @@ -3177,20 +3177,12 @@ nate -%7D%0A /%3E + %7D)%7D %0A
f73cec06a8fc08b0c74a8e1e1976b6e1a96444ee
Update getstrokeweight.js
draw/colors/getstrokeweight.js
draw/colors/getstrokeweight.js
if(!Draw.getStrokeWeight) { Draw.getStrokeWeight = function() { if(!Canvas.configured) { console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!"); return; } return Canvas.context.lineWidth; }; }
JavaScript
0
@@ -21,16 +21,229 @@ ight) %7B%0A + /* Draw.getStrokeWeight%0A Draw.getStrokeWeight returns the canvas context's current stroke weight (or line width)%0A %0A @author TemporalFuzz%0A @version 1.0%0A @returns Number current stroke weight%0A */%0A Draw.g
a06b5f4d0715c3c503a7142b6104482674f72222
Fix gulp task
scripts/gulpfile.js
scripts/gulpfile.js
/* eslint no-console: ["error", { allow: ["log"] }] */ const gulp = require('gulp'); const connect = require('gulp-connect'); const gopen = require('gulp-open'); const runSequence = require('run-sequence'); const buildKsCore = require('./build-ks-core.js'); const buildKsVue = require('./build-ks-vue.js'); const buildKsReact = require('./build-ks-react.js'); const buildCoreJs = require('./build-core-js.js'); const buildCoreTypings = require('./build-core-typings.js'); const buildCoreLess = require('./build-core-less.js'); const buildCoreComponents = require('./build-core-components.js'); const buildCoreLazyComponents = require('./build-core-lazy-components.js'); const buildPhenome = require('./build-phenome.js'); const buildVue = require('./build-vue'); const buildVueTypings = require('./build-vue-typings.js'); const buildReact = require('./build-react'); const buildReactTypings = require('./build-react-typings.js'); const env = process.env.NODE_ENV || 'development'; // Tasks gulp.task('ks-core', buildKsCore); gulp.task('ks-vue', buildKsVue); gulp.task('ks-react', buildKsReact); gulp.task('core-js', buildCoreJs); gulp.task('core-typings', buildCoreTypings); gulp.task('core-less', buildCoreLess); gulp.task('core-components', buildCoreComponents); gulp.task('core-lazy-components', buildCoreLazyComponents); gulp.task('phenome', buildPhenome); gulp.task('react', buildReact); gulp.task('react-typings', buildReactTypings); gulp.task('vue', buildVue); gulp.task('vue-typings', buildVueTypings); // eslint-disable-next-line gulp.task('build-core', runSequence('core-js', 'core-components', 'core-typings', 'core-less', 'core-lazy-components')); gulp.task('build-react', () => runSequence('react', 'react-typings')); gulp.task('build-vue', () => runSequence('vue', 'vue-typings')); // Watchers const watch = { all() { gulp.watch(['./src/core/**/*.js'], () => runSequence( 'core-js', 'core-components', 'ks-react', 'ks-vue' )); gulp.watch(['./src/core/**/*.d.ts'], () => runSequence( 'core-typings' )); gulp.watch('./src/core/**/*.less', () => runSequence( 'core-less', 'core-components' )); gulp.watch(['./src/phenome/**/*.js', './src/phenome/**/*.jsx'], () => runSequence( 'phenome', 'build-react', 'build-vue', 'ks-react', 'ks-vue' )); gulp.watch(['./kitchen-sink/react/src/**/*.js', './kitchen-sink/react/src/**/*.jsx'], () => runSequence( 'ks-react' )); gulp.watch(['./kitchen-sink/vue/src/**/*.js', './kitchen-sink/vue/src/**/*.vue'], () => runSequence( 'ks-vue' )); }, core() { gulp.watch(['./src/core/**/*.js'], () => runSequence( 'core-js', 'core-components', 'core-lazy-components', )); gulp.watch(['./src/core/**/*.d.ts'], () => runSequence( 'core-typings' )); gulp.watch('./src/**/**/*.less', () => runSequence( 'core-less', 'core-components', 'core-lazy-components', )); }, react() { gulp.watch(['./src/core/**/*.js'], () => runSequence( 'core-js', 'core-components', 'ks-react' )); gulp.watch('./src/core/**/*.less', () => runSequence( 'core-less', 'core-components', )); gulp.watch(['./src/phenome/**/*.js', './src/phenome/**/*.jsx'], () => runSequence( 'phenome', 'build-react', 'ks-react' )); gulp.watch(['./kitchen-sink/react/src/**/*.js', './kitchen-sink/react/src/**/*.jsx'], [ 'ks-react', ]); }, vue() { gulp.watch(['./src/core/**/*.js'], () => runSequence( 'core-js', 'core-components', 'ks-vue' )); gulp.watch('./src/core/**/*.less', () => runSequence( 'core-less', 'core-components', )); gulp.watch(['./src/phenome/**/*.js', './src/phenome/**/*.jsx'], () => runSequence( 'phenome', 'build-vue', 'ks-vue' )); gulp.watch(['./kitchen-sink/vue/src/**/*.js', './kitchen-sink/vue/src/**/*.vue'], [ 'ks-vue', ]); }, }; // Server function server() { connect.server({ root: ['./'], livereload: false, port: '3000', }); } gulp.task('server', () => { if (env === 'development') watch.all(); server(); gulp.src('./kitchen-sink/core/index.html').pipe(gopen({ uri: 'http://localhost:3000/kitchen-sink/core/' })); }); gulp.task('server-core', () => { if (env === 'development') watch.core(); server(); gulp.src('./kitchen-sink/core/index.html').pipe(gopen({ uri: 'http://localhost:3000/kitchen-sink/core/' })); }); gulp.task('server-react', () => { if (env === 'development') watch.react(); server(); gulp.src('./kitchen-sink/react/index.html').pipe(gopen({ uri: 'http://localhost:3000/kitchen-sink/react/' })); }); gulp.task('server-vue', () => { if (env === 'development') watch.vue(); server(); gulp.src('./kitchen-sink/vue/index.html').pipe(gopen({ uri: 'http://localhost:3000/kitchen-sink/vue/' })); }); gulp.task('watch', () => { watch.all(); }); gulp.task('watch-core', () => { watch.core(); }); gulp.task('watch-react', () => { watch.react(); }); gulp.task('watch-vue', () => { watch.vue(); });
JavaScript
0.000208
@@ -1563,16 +1563,22 @@ d-core', + () =%3E runSequ
dd52dd3f817b4c421735fa30c3bab28a89d3b94f
Fix init loading
app/app.js
app/app.js
import Ember from 'ember'; import Resolver from 'ember/resolver'; import loadInitializers from 'ember/load-initializers'; import config from './config/environment'; import getAndInitNewEpisodes from "./lib/getAndInitNewEpisodes" var App; var ipc = nRequire("ipc"); Ember.MODEL_FACTORY_INJECTIONS = true; var notifier = nRequire('node-notifier'); var episodesToString = function(episodes){ var episode = episodes[0]; if(episodes.length == 1) { return episode.get("show") + " " + episode.get("what") + " was released"; } return episode.get("show") + " " + episode.get("what") + " and " + (episodes.length - 1) + " others"; } Ember.Application.initializer({ name: "fetchLoop", initialize: function(container, application) { var checkForEp = function(){ var store = container.lookup("store:main"); var epController = container.lookup('controller:episodes'); getAndInitNewEpisodes(store, function(episodes) { episodes.forEach(function(episode) { epController.get("episodes").unshiftObject(episode); episode.loading(); }); if(episodes.length > 0){ notifier.notify({ 'title': 'New episodes', 'message': episodesToString(episodes) }); ipc.sendSync('newBackgroundEpisodes', 1); } }); } setInterval(checkForEp, 1 * 60 * 60 * 1000); checkForEp(); } }); import User from "./lib/user"; Ember.Application.initializer({ name: "initUser", initialize: function(container, app) { app.register('service:user', User, { instantiate: true, singleton: true }); app.inject('controller', 'currentUser', "service:user"); app.inject('route', 'currentUser', "service:user"); } }); App = Ember.Application.extend({ modulePrefix: config.modulePrefix, podModulePrefix: config.podModulePrefix, Resolver: Resolver }); loadInitializers(App, config.modulePrefix); export default App;
JavaScript
0.000002
@@ -927,15 +927,46 @@ des( -store, +epController.currentUser, store).then( func @@ -1318,17 +1318,17 @@ endSync( -' +%22 newBackg @@ -1340,17 +1340,17 @@ Episodes -' +%22 , 1);%0A
131154fd4cd073ae62ba08a1324242c2a785540c
Fix linter error
app/app.js
app/app.js
var _ = require('lodash'); var React = require('react'); var createReactClass = require('create-react-class'); var request = require('browser-request'); var cx = require('classnames'); var { transform, formatError } = require('../lib/util'); var examples = require('./examples.json'); var exampleGrammar = examples[0].source; examples = examples.slice(1); var App = createReactClass({ formats: { pegjs: 'PEG.js', ebnf: 'EBNF', ohm: 'Ohm', }, handleChange(e) { const {name, value} = e.currentTarget; this.setState({[name]: value}); }, UNSAFE_componentWillMount() { this.updateGrammarDebounced = _.debounce(() => this.updateGrammar, 150); if (location.hash) { var hash = location.hash.replace(/^#/, ''); if (hash.match(/^https?:\/\/|\.\//)) { this.loadGrammar(hash); } else { this.updateGrammar(decodeURIComponent(hash)); } } else { this.updateGrammar(exampleGrammar); } }, getInitialState() { return { examples: examples, procesedGrammars: [], format: 'auto', detectedFormat: null }; }, render() { var { format, detectedFormat, syntaxError } = this.state; return ( <div> <div className="col-md-6"> <div className={cx('load-input', 'row', {'has-error': this.state.loadError})}> <form onSubmit={this.onLoadGrammar}> <div className="col-md-8 col-sm-8 col-xs-7"> <input className="form-control" type="text" name="link" value={this.state.link} onChange={this.handleChange} placeholder="e.g. http://server.com/grammar.pegjs" /> </div> <button className="btn btn-primary col-md-3 col-sm-3 col-xs-4" type="submit" disabled={this.state.loading}> {this.state.loading ? 'Loading...' : 'Load Grammar'} </button> </form> </div> <div className="load-examples row"> Format:{" "} <select value={format} onChange={this.onChangeFormat}> <option value="auto">Auto-detect</option> {Object.keys(this.formats).map(k => <option key={k} value={k}>{this.formats[k]}</option> )} </select> {format === 'auto' && !!detectedFormat && <span> Detected: {this.formats[detectedFormat]}</span>} </div> <div className="load-examples row"> <span>Try some examples:</span><br/> {this.state.examples.map((example, key) => <a key={key} href={'#'+example.link} onClick={() => this.onSwitchGrammar(example.link, example.format)}>{example.name}</a> )} </div> {this.state.loadError && <div className="row alert alert-danger"> {this.state.loadError} </div>} <div className={cx('row', {'has-error': syntaxError})}> <textarea className="form-control grammar-edit" value={this.state.grammar} onChange={this.onChangeGrammar} /> {syntaxError && <pre className="alert alert-danger"> {formatError(syntaxError)} </pre>} </div> </div> <div className="col-md-6"> {this.state.procesedGrammars.map(({ rules, references, name }, key) => <div key={key}> {!!name && <h2>{name}</h2>} {rules.map((rule, key) => <div key={key}> <h3 id={rule.name}>{rule.name}</h3> <div dangerouslySetInnerHTML={{__html: rule.diagram}} onClick={this.onClickDiagram} /> {references[rule.name] && references[rule.name].usedBy.length > 0 && <div> Used By: {references[rule.name].usedBy.map((rule, key) => <a key={key} href={'#' + rule}> {rule} </a> )} </div>} {references[rule.name] && references[rule.name].references.length > 0 && <div> References: {references[rule.name].references.map((rule, key) => <a key={key} href={'#' + rule}> {rule} </a> )} </div>} </div> )} </div> )} </div> </div> ); }, onChangeGrammar(ev) { this.setState({grammar: ev.target.value}); this.updateGrammarDebounced(ev.target.value); }, onSwitchGrammar(link, format /* , ev */) { this.loadGrammar(link, format); }, onLoadGrammar(ev) { ev.preventDefault(); this.loadGrammar(this.state.link); }, onClickDiagram(ev) { // if the node was clicked then go to rule definition if (ev.target.tagName === 'text') { location.hash = ev.target.textContent; } }, onChangeFormat(ev) { this.updateGrammar(this.state.grammar, ev.target.value); }, updateGrammar(grammar, format) { format = format || this.state.format; var state = { grammar: grammar, syntaxError: null, format, detectedFormat: null }; try { state = Object.assign(state, transform(grammar, format)); } catch (e) { state.syntaxError = e; state.procesedGrammars = []; } this.setState(state); }, loadGrammar(link, format) { format = format || 'auto'; link = link.trim().replace(/^https?:\/\/github.com\/([^\/]+)\/([^\/]+)\/blob\//, 'https://raw.githubusercontent.com/$1/$2/'); location.hash = link; this.setState({ link: link, grammar: '', procesedGrammars: [], loading: true, loadError: null, format, detectedFormat: null }); request(link, (er, response, body) => { this.setState({loading: false}) if (er || response.status !== 200) { this.setState({loadError: '' + (er || body)}); } else { this.updateGrammar(body, format); } }) } }); module.exports = App;
JavaScript
0.000004
@@ -5380,25 +5380,24 @@ hub.com%5C/(%5B%5E -%5C /%5D+)%5C/(%5B%5E%5C/%5D @@ -5393,17 +5393,16 @@ %5D+)%5C/(%5B%5E -%5C /%5D+)%5C/bl
817e5f4a52143c3c93dcab460e23da440f5b9e69
add link to home
src/client/components/Main.js
src/client/components/Main.js
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { bindActions, mapStateToProps } from '../stores'; import * as actions from '../actions/main'; import Page from './Page'; import SideMenu from './SideMenu'; import PageContent from './PageContent'; // eslint-disable-next-line class Main extends React.PureComponent { render() { const menu = [{ to: { pathname: '/about' }, label: 'About this repo', }, { to: '/libraries', label: 'Libraries', }, { to: '/extend', label: 'How to extend from this repo', }, { to: '/contact', label: 'Contact', }]; return ( <Page> <SideMenu menu={menu} /> <PageContent>{this.props.children}</PageContent> </Page> ); } } Main.defaultProps = { children: null, }; Main.propTypes = { // eslint-disable-next-line actions: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types // eslint-disable-next-line store: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types children: PropTypes.oneOfType([ PropTypes.object, PropTypes.array, ]), // eslint-disable-line react/forbid-prop-types }; export default connect(mapStateToProps('main'), bindActions(actions))(Main);
JavaScript
0
@@ -403,16 +403,75 @@ nu = %5B%7B%0A + to: %7B pathname: '/' %7D,%0A label: 'Home',%0A %7D, %7B%0A to
2a5a9f86f485a91b6b1315cb577beb3a362f2faa
remove dev.js from cli args
app/dev.js
app/dev.js
/** * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. * * Camunda licenses this file to you under the MIT; you may not use this file * except in compliance with the MIT License. */ const log = require('./lib/log')('app:dev'); const { default: installExtension, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer'); const getAppVersion = require('./util/get-version'); // enable development perks process.env.NODE_ENV = 'development'; // monkey-patch package version to indicate DEV mode in application const pkg = require('./package'); pkg.version = getAppVersion(pkg, { nightly: 'dev' }); const app = require('./lib'); // make sure the app quits and does not hang app.on('before-quit', function() { app.exit(0); }); app.on('app:window-created', async () => { try { const name = await installExtension(REACT_DEVELOPER_TOOLS); log.info('added extension <%s>', name); } catch (err) { log.error('failed to add extension', err); } }); try { require('electron-reloader')(module); } catch (err) { // ignore it }
JavaScript
0.000002
@@ -798,16 +798,146 @@ v'%0A%7D);%0A%0A +// monkey-patch cli args to not open this file in application%0Aprocess.argv = process.argv.filter(arg =%3E !arg.includes('dev.js'));%0A %0Aconst a
f51484adeaea13dd46104bf4314a2296a3663078
Update jquery.slideshow.js
jquery.slideshow.js
jquery.slideshow.js
$.fn.Slideshow = function(args){ var self = this; this.currentSlide = 0; var playState=true; var slides = getSlides(this,args['slides']['selectorType'],args['slides']['selector']); var controls = buildControls(this, args); autoPlay(); function buildControls(sliderShow, args){ if(typeof(args["controls"])!==undefined){ var cnt = $("."+args['controls']['selector']); var prvBtn = $(args['controls']['prvBtn']).appendTo(cnt); prvBtn.click(function(){ self.prev() }); var nextBtn = $(args['controls']['nextBtn']).appendTo(cnt); nextBtn.click(function(){ self.next(); }); var paganator = $(document.createElement('nav')); paganator.appendTo(cnt); slides.each(function(index){ if(index==0){ var typeT = "active"; }else{ var typeT = "hidden"; } var pager = $(args['controls']['pager']['elm']); pager.addClass(args['controls']['pager']["class"][typeT]); pager.attr("index",index); pager.click(function(){ setTo($(this).attr("index")); }); paganator.append(pager); }); return cnt; } return undefined; } function autoPlay(){ if(typeof(args['playInterval'])!==undefined){ play(args['playInterval']); }else{ play(8000); } } function setTo(i){ console.log(self.currentSlide+" -> "+i); changePager(i); changeSlide(i); self.currentSlide=parseInt(i); } function play(interval){ self.next(); setTimeout(function(){ play(interval); }, interval); } this.next = function(){ var sn=parseInt(self.currentSlide)+1; if(sn>slides.length-1){ sn=0; } setTo(sn); } this.prev = function(){ var s=parseInt(self.currentSlide)-1; if(s<0){ s=slides.length-1; } setTo(s); } function changeSlide(selected){ if(self.currentSlide != selected){ $(slides.get(self.currentSlide)).fadeOut("slow"); $(slides.get(selected)).fadeIn("slow"); } } function changePager(selected){ var pagers = controls.children("nav").children("i"); pagers.each(function(){ if($(this).hasClass(args['controls']['pager']["class"]["active"])){ self.currentSlide = $(this).attr("index"); $(this).removeClass(args['controls']['pager']['class']['active']).addClass(args['controls']['pager']['class']['hidden']); } }); $(pagers.get(selected)).removeClass(args['controls']['pager']['class']['hidden']).addClass(args['controls']['pager']['class']['active']); } function getPaganator(controls_element){ var p = document.createElement('nav'); controls_element.append(p); return $(p); } function getControls(slideShow,selType,sel){ var results; results = slideShow.children(sel); return results; } function getSlides(slideShow,selType,sel){ var results; results = slideShow.children(sel); return results; } };
JavaScript
0
@@ -1259,51 +1259,8 @@ i)%7B%0A -%09%09console.log(self.currentSlide+%22 -%3E %22+i);%0A %09%09ch
090d653033e15d8174d9c475d704e8f91f31e4cc
Fix event handler
scripts/explore/ExploreDiscussionController.js
scripts/explore/ExploreDiscussionController.js
/** * ExploreDiscussionController * Concrete view controller to display a Discussion. * @constructor */ let ExploreDiscussionController = ConversationController.createComponent("ExploreDiscussionController"); ExploreDiscussionController.createViewFragment = function createViewFragment() { return cloneTemplate("#template-explore-discussion"); }; ExploreDiscussionController.defineAlias("model", "discussion"); (function (ExploreDiscussionController) { ExploreDiscussionController.defineMethod("initView", function initView() { if (!this.view) return; // Init click to display full article this.view.addEventListener("click", viewOnClick); setElementProperty(this.view, "discussion-id", this.discussion.discussionId); }); ExploreDiscussionController.defineMethod("updateView", function updateView() { if (!this.view) return; // Update display metadata this.view.querySelectorAll("[data-ica-discussion]").forEach(function (element) { element.textContent = this.discussion[getElementProperty(element, "discussion")]["0"] || ""; }.bind(this)); // Display order this.view.style.order = -this.discussion.discussionId; }); ExploreDiscussionController.defineMethod("uninitView", function uninitView() { if (!this.view) return; // Uninit click to display full article this.view.removeEventListener("click", viewOnClick); removeElementProperty(this.view, "discussion-id"); }); // Shared functions function viewOnClick() { e.preventDefault(); e.stopPropagation(); let fragment = MapArticleDiscussionController.createViewFragment(); let element = fragment.querySelector(".article-container"); document.body.querySelector(".app-view").appendChild(fragment); new MapArticleDiscussionController(this.controller.discussion, element); } })(ExploreDiscussionController);
JavaScript
0.000042
@@ -1506,16 +1506,21 @@ OnClick( +event ) %7B%0A @@ -1520,16 +1520,20 @@ %7B%0A e +vent .prevent @@ -1548,16 +1548,20 @@ );%0A e +vent .stopPro
7ca2d233cc7274a8b8c21510f369b0715b0a4ce5
Fix for Synapse backbone integration
js/application/synapse/hooks/backbone-model.js
js/application/synapse/hooks/backbone-model.js
(function(root, factory) { if (typeof exports !== 'undefined') { return factory(root, exports, require('synapse/core'), require('backbone')); } else if (typeof define === 'function' && define.amd) { return define('synapse/hooks/backbone-model', ['synapse/core', 'backbone', 'exports'], function(core, Backbone, exports) { return factory(root, exports, core, Backbone); }); } else { return root.BackboneModelHook = factory(root, {}, root.SynapseCore, root.Backbone); } })(this, function(root, BackboneModelHook, core) { return { typeName: 'Backbone Model', checkObjectType: function(object) { return object instanceof Backbone.Model; }, getHandler: function(object, key) { if (core.isFunction(object[key])) { return object[key](); } else { return object.get(key); } }, setHandler: function(object, key, value) { var attrs; if (core.isFunction(object[key])) { return object[key](value); } else { attrs = {}; attrs[key] = value; return object.set(attrs); } }, onEventHandler: function(object, event, handler) { return object.bind(event, handler); }, offEventHandler: function(object, event, handler) { return object.unbind(event, handler); }, triggerEventHandler: function(object, event) { return object.trigger(event); }, detectEvent: function(object, interface) { if (interface && !object[interface]) return "change:" + interface; return 'change'; } }; });
JavaScript
0
@@ -540,16 +540,26 @@ ok, core +, Backbone ) %7B%0A re
18aa55888b45eb683c216b887e04e062fa6a85f6
Improve electron process webpack plugin
scripts/webpack/ManageElectronProcessPlugin.js
scripts/webpack/ManageElectronProcessPlugin.js
const { exec } = require('child_process'); class ManageElectronProcessPlugin { apply(compiler) { if (compiler.options.watch) { let electron = null; compiler.hooks.done.tap( 'RestartElectronPlugin', () => { if (electron === null) { electron = exec("yarn electron ."); electron.once('close', () => { electron = null; }); } else { electron.kill(); electron = exec("yarn electron ."); } } ); } } } module.exports = ManageElectronProcessPlugin;
JavaScript
0
@@ -138,39 +138,97 @@ let electron - = null +MainProcess = null;%0A let isMainProcessBeingRestarted = false ;%0A compiler @@ -315,16 +315,27 @@ electron +MainProcess === nul @@ -351,32 +351,43 @@ electron +MainProcess = exec(%22yarn el @@ -418,16 +418,27 @@ electron +MainProcess .once('c @@ -474,16 +474,27 @@ electron +MainProcess = null; @@ -510,105 +510,331 @@ -%7D);%0A %7D else %7B%0A electron.kill();%0A electron = exec(%22yarn electron .%22 + if (isMainProcessBeingRestarted) %7B%0A electronMainProcess = exec(%22yarn electron .%22);%0A isMainProcessBeingRestarted = false;%0A %7D%0A %7D);%0A %7D else if (!isMainProcessBeingRestarted) %7B%0A isMainProcessBeingRestarted = true;%0A electronMainProcess.kill( );%0A
dbc7e260ad53ffec5c318efeee425804132debb2
Reorder routes to trigger rebuild.
src/main.js
src/main.js
import './main.sass' import 'babel-core/polyfill' import React from 'react' import ReactDOM from 'react-dom' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import createBrowserHistory from 'history/lib/createBrowserHistory' import { compose, createStore, applyMiddleware } from 'redux' import { reduxReactRouter, routerStateReducer, ReduxRouter } from 'redux-router' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' import { persistStore, autoRehydrate } from 'redux-persist' import './vendor/embetter' import './vendor/time_ago_in_words' // TODO: move this somewhere else? window.embetter.activeServices = [ window.embetter.services.youtube, window.embetter.services.vimeo, window.embetter.services.soundcloud, window.embetter.services.dailymotion, window.embetter.services.mixcloud, window.embetter.services.codepen, window.embetter.services.bandcamp, window.embetter.services.ustream, ] window.embetter.reloadPlayers = (el = document.body) => { window.embetter.utils.disposeDetachedPlayers() window.embetter.utils.initMediaPlayers(el, window.embetter.activeServices) } window.embetter.stopPlayers = (el = document.body) => { window.embetter.utils.unembedPlayers(el) window.embetter.utils.disposeDetachedPlayers() } window.embetter.removePlayers = (el = document.body) => { window.embetter.stopPlayers(el) for (const ready of el.querySelectorAll('.embetter-ready')) { ready.classList.remove('embetter-ready') } for (const statix of el.querySelectorAll('.embetter-static')) { statix.classList.remove('embetter-static') } } window.embetter.reloadPlayers() function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const routes = [ createRedirect('/', '/following'), { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/discover'), require('./routes/following'), require('./routes/onboarding'), require('./routes/post_detail'), require('./routes/search'), require('./routes/starred'), require('./routes/user_detail'), ], }, ] const logger = createLogger({ collapsed: true }) function reducer(state = {}, action) { return { json: reducers.json(state.json, action, state.router), devtools: reducers.devtools(state.devtools, action), modals: reducers.modals(state.modals, action), profile: reducers.profile(state.profile, action), router: routerStateReducer(state.router, action), stream: reducers.stream(state.stream, action), } } const store = compose( autoRehydrate(), applyMiddleware(thunk, uploader, requester, analytics, logger), reduxReactRouter({routes: routes, createHistory: createBrowserHistory}) )(createStore)(reducer) const element = ( <Provider store={store}> <ReduxRouter /> </Provider> ) persistStore(store, { blacklist: ['router'] }, () => { ReactDOM.render(element, document.getElementById('root')) })
JavaScript
0
@@ -2018,71 +2018,8 @@ -createRedirect('onboarding', '/onboarding/communities'),%0A requ @@ -2073,24 +2073,87 @@ es/following +'),%0A createRedirect('onboarding', '/onboarding/communities '),%0A re