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 |
|---|---|---|---|---|---|---|---|
ae013ec01874f9c7095801082b68dfee7d55dc88 | Fix "Unknown property: autoClear" message | www/local-notification-util.js | www/local-notification-util.js | /*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
var exec = require('cordova/exec'),
channel = require('cordova/channel');
/***********
* MEMBERS *
***********/
// Default values
exports._defaults = {
text: '',
title: '',
sound: 'res://platform_default',
badge: 0,
id: "0",
data: undefined,
every: undefined,
at: undefined
};
// listener
exports._listener = {};
/********
* UTIL *
********/
/**
* Merge platform specific properties into the default ones.
*
* @return {Object}
* The default properties for the platform
*/
exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults;
switch (device.platform) {
case 'Android':
defaults.icon = 'res://icon';
defaults.smallIcon = 'res://ic_popup_reminder';
defaults.ongoing = false;
defaults.autoClear = true;
defaults.led = 'FFFFFF';
break;
}
return defaults;
};
/**
* Merge custom properties with the default values.
*
* @param {Object} options
* Set of custom values
*
* @retrun {Object}
* The merged property list
*/
exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults();
options.at = this.getValueFor(options, 'at', 'firstAt', 'date');
options.text = this.getValueFor(options, 'text', 'message');
options.data = this.getValueFor(options, 'data', 'json');
options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
if (options.autoClear !== true && options.ongoing) {
options.autoClear = false;
}
if (options.at === undefined || options.at === null) {
options.at = new Date();
}
for (var key in defaults) {
if (options[key] === null || options[key] === undefined) {
if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
options[key] = undefined;
} else {
options[key] = defaults[key];
}
}
}
for (key in options) {
if (!defaults.hasOwnProperty(key)) {
delete options[key];
console.warn('Unknown property: ' + key);
}
}
return options;
};
/**
* Convert the passed values to their required type.
*
* @param {Object} options
* Set of custom values
*
* @retrun {Object}
* The converted property list
*/
exports.convertProperties = function (options) {
if (options.id) {
if (isNaN(options.id)) {
options.id = this.getDefaults().id;
} else {
options.id = options.id.toString();
}
}
if (options.title) {
options.title = options.title.toString();
}
if (options.text) {
options.text = options.text.toString();
}
if (options.badge) {
if (isNaN(options.badge)) {
options.badge = this.getDefaults().badge;
} else {
options.badge = Number(options.badge);
}
}
if (typeof options.at == 'object') {
options.at = options.at.getTime();
}
options.at = Math.round(options.at/1000);
if (typeof options.data == 'object') {
options.data = JSON.stringify(options.data);
}
return options;
};
/**
* Create callback, which will be executed within a specific scope.
*
* @param {Function} callbackFn
* The callback function
* @param {Object} scope
* The scope for the function
*
* @return {Function}
* The new callback function
*/
exports.createCallbackFn = function (callbackFn, scope) {
if (typeof callbackFn != 'function')
return;
return function () {
callbackFn.apply(scope || this, arguments);
};
};
/**
* Convert the IDs to Strings.
*
* @param {String/Number[]} ids
*
* @return Array of Strings
*/
exports.convertIds = function (ids) {
var convertedIds = [];
for (var i = 0; i < ids.length; i++) {
convertedIds.push(ids[i].toString());
}
return convertedIds;
};
/**
* First found value for the given keys.
*
* @param {Object} options
* Object with key-value properties
* @param {String[]} keys*
* Key list
*/
exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (options.hasOwnProperty(key)) {
return options[key];
}
}
};
/**
* Fire event with given arguments.
*
* @param {String} event
* The event's name
* @param {args*}
* The callback's arguments
*/
exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1),
listener = this._listener[event];
if (!listener)
return;
for (var i = 0; i < listener.length; i++) {
var fn = listener[i][0],
scope = listener[i][1];
fn.apply(scope, args);
}
};
/**
* Execute the native counterpart.
*
* @param {String} action
* The name of the action
* @param args[]
* Array of arguments
* @param {Function} callback
* The callback function
* @param {Object} scope
* The scope for the function
*/
exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope),
params = [];
if (Array.isArray(args)) {
params = args;
} else if (args) {
params.push(args);
}
exec(fn, null, 'LocalNotification', action, params);
};
/*********
* HOOKS *
*********/
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered
// and all queued events can be executed.
exec(null, null, 'LocalNotification', 'deviceready', []);
});
// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
// Device plugin is ready now
channel.onCordovaInfoReady.subscribe(function () {
// Merge platform specifics into defaults
exports.applyPlatformSpecificOptions();
});
});
| JavaScript | 0.000004 | @@ -2363,24 +2363,76 @@
, 'json');%0A%0A
+ if (defaults.hasOwnProperty('autoClear')) %7B%0A
options.
@@ -2496,16 +2496,22 @@
ancel');
+%0A %7D
%0A%0A if
|
c3ee12c91801ce56caf8ecfd0c37224ef1719ce5 | Change awaitingresponse.js to be the opposite of the original and show emails the user has not responded to, add some comments | awaitingresponse.js | awaitingresponse.js | /*
* This script goes through your Gmail Inbox and finds recent emails where you
* were the last respondent. It applies a nice label to them, so you can
* see them in Priority Inbox or do something else.
*
* To remove and ignore an email thread, just remove the unrespondedLabel and
* apply the ignoreLabel.
*
* This is most effective when paired with a time-based script trigger.
*
* For installation instructions, read this blog post:
* http://jonathan-kim.com/2013/Gmail-No-Response/
*/
// Edit these to your liking.
var unrespondedLabel = 'No Response',
ignoreLabel = 'Ignore No Response',
minDays = 5,
maxDays = 14;
function main() {
processUnresponded();
cleanUp();
}
function processUnresponded() {
var threads = GmailApp.search('is:sent from:me -in:chats older_than:' + minDays + 'd newer_than:' + maxDays + 'd'),
numUpdated = 0,
minDaysAgo = new Date();
minDaysAgo.setDate(minDaysAgo.getDate() - minDays);
// Filter threads where I was the last respondent.
for (var i = 0; i < threads.length; i++) {
var thread = threads[i],
messages = thread.getMessages(),
lastMessage = messages[messages.length - 1],
lastFrom = lastMessage.getFrom(),
lastMessageIsOld = lastMessage.getDate().getTime() < minDaysAgo.getTime();
if (isFromMe(lastFrom) && lastMessageIsOld && !threadHasLabel(thread, ignoreLabel)) {
markUnresponded(thread);
numUpdated++;
}
}
Logger.log('Updated ' + numUpdated + ' messages.');
}
function isFromMe(fromAddress) {
var addresses = getEmailAddresses();
for (i = 0; i < addresses.length; i++) {
var address = addresses[i],
r = RegExp(address, 'i');
if (r.test(fromAddress)) {
return true;
}
}
return false;
}
function getEmailAddresses() {
var me = Session.getActiveUser().getEmail(),
emails = GmailApp.getAliases();
emails.push(me);
return emails;
}
function threadHasLabel(thread, labelName) {
var labels = thread.getLabels();
for (i = 0; i < labels.length; i++) {
var label = labels[i];
if (label.getName() == labelName) {
return true;
}
}
return false;
}
function markUnresponded(thread) {
var label = getLabel(unrespondedLabel);
label.addToThread(thread);
}
function getLabel(labelName) {
var label = GmailApp.getUserLabelByName(labelName);
if (label) {
Logger.log('Label exists.');
} else {
Logger.log('Label does not exist. Creating it.');
label = GmailApp.createLabel(labelName);
}
return label;
}
function cleanUp() {
var label = getLabel(unrespondedLabel),
iLabel = getLabel(ignoreLabel),
threads = label.getThreads(),
numExpired = 0,
twoWeeksAgo = new Date();
twoWeeksAgo.setDate(twoWeeksAgo.getDate() - maxDays);
if (!threads.length) {
Logger.log('No threads with that label');
return;
} else {
Logger.log('Processing ' + threads.length + ' threads.');
}
for (i = 0; i < threads.length; i++) {
var thread = threads[i],
lastMessageDate = thread.getLastMessageDate();
// Remove all labels from expired threads.
if (lastMessageDate.getTime() < twoWeeksAgo.getTime()) {
numExpired++;
Logger.log('Thread expired');
label.removeFromThread(thread);
iLabel.removeFromThread(thread);
} else {
Logger.log('Thread not expired');
}
}
Logger.log(numExpired + ' unresponded messages expired.');
}
| JavaScript | 0 | @@ -65,16 +65,31 @@
emails
+sent%0A * to you
where yo
@@ -93,16 +93,16 @@
you
-%0A * were
+ are not
the
@@ -118,16 +118,69 @@
pondent.
+ These may be emails that%0A * are awaiting your reply.
It appl
@@ -189,13 +189,8 @@
s a
-nice
labe
@@ -214,60 +214,36 @@
can
-%0A * see them in Priority Inbox or do something else.
+ search%0A* for them easily.
%0A *%0A
@@ -299,16 +299,50 @@
ove the
+email from inbox%0A * or remove the
unrespon
@@ -353,19 +353,16 @@
abel and
-%0A *
apply t
@@ -567,79 +567,525 @@
/%0A *
-/%0A%0A%0A// Edit these to your liking.%0Avar unrespondedLabel = 'No R
+ %0A * This script is based on and is nearly identical to:%0A * http://jonathan-kim.com/2013/Gmail-No-Response/%0A * which does the same but for messages that you sent but haven't been%0A * responded to. Thank you to @hijonathan for putting his work in %0A * the public domain%0A * %0A */%0A%0A%0A// Edit these to your liking.%0Avar searchLabel = 'inbox', // which label to look in, %0A // switch to 'important' to check priority only%0A unrespondedLabel = 'AR', // label for messages that may be awaiting r
esponse
-',
%0A
@@ -1111,56 +1111,188 @@
ore
-No Response',%0A minDays = 5,%0A maxDays = 14;
+AR', // label to use for messages for the script to ignore%0A minDays = 3, // minimum number of days of age email to look for%0A maxDays = 5; // maximum number of days to look at
%0A%0Afu
@@ -1416,16 +1416,39 @@
ch('
-is:sent
+label:'+ searchLabel +' to:me -
from
@@ -1984,16 +1984,17 @@
if (
+!
isFromMe
|
bd3db9510636400fd9de6ba5b88d14b2625f10ba | update webpack loader config | app/templates/_webpack.config.js | app/templates/_webpack.config.js | var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: __dirname+'/scripts/pages',
entry: require('./app-entry'),
output: {
path: __dirname + '/build',
publicPath: '/build',
filename: '[name].js',
sourceMapFilename: '[file].map'
},
devServer: {
contentBase: '.',
colors: true,
port: 1024,
host: '0.0.0.0'
},
debug: true,
devtool: 'eval',
module: {
loaders: [
{ test: /\.coffee$/, loader: "coffee-loader" },
{ test: /\.(coffee\.md|litcoffee)$/, loader: "coffee-loader?literate" },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader','css-loader!autoprefixer-loader') },
{ test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") },
{ test: /(\.scss)|(\.sass)$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader?sourceMap") },
{ test: /(\.woff)|(\.ttf)|(\.eot)|(\.svg)|(\.png)|(\.jpg)|(\.gif)/, loader: "file-loader"},
]
},
resolve:{
root: [__dirname],
alias: {
styles: __dirname+'/stylesheets',
images: __dirname+'/images',
plugins: __dirname+'/plugins'
}
},
plugins: [
new ExtractTextPlugin("[name].css"),
new webpack.optimize.CommonsChunkPlugin({
name: 'bundle',
filename: 'bundle.js',
minChunks: 3
})
]
}
| JavaScript | 0.000001 | @@ -843,20 +843,16 @@
t: /
-(
%5C.
+(
scss
-)%7C(%5C.
+%7C
sass
@@ -964,60 +964,41 @@
t: /
-(
%5C.
+(
woff
-)%7C(%5C.ttf)%7C(%5C.eot)%7C(%5C.svg)%7C(%5C.png)%7C(%5C.jpg)%7C(%5C.
+%7Cttf%7Ceot%7Csvg%7Cpng%7Cjpg%7Cjpeg%7C
gif)
|
d8e3df79bca39e091c61a5600b673b3230001ef5 | remove extra space | Contents/Sketch/colors.js | Contents/Sketch/colors.js | var applyColors = function (newColors, docData) {
var app = NSApplication.sharedApplication();
var appController = app.delegate();
var colors = [];
for(var i=0; i<newColors.length; i++) {
var color = MSColor.colorWithSVGString("#" + newColors[i].Rgb);
color.alpha = newColors[i] .Opacity;
colors.push(color);
}
colors = MSArray.dataArrayWithArray(colors);
appController.globalAssets().setPrimitiveColors(colors);
appController.globalAssets().objectDidChange();
}
| JavaScript | 0.002319 | @@ -287,17 +287,16 @@
olors%5Bi%5D
-
.Opacity
|
c70b2dbc4dea4ab13763279281064af2e7030e86 | fix jshint | app/src/routes/api/v1/umdLossGainRouter.js | app/src/routes/api/v1/umdLossGainRouter.js | 'use strict';
var Router = require('koa-router');
var logger = require('logger');
var CartoDBService = require('services/cartoDBService');
var GEEService = require('services/geeService');
var NotFound = require('errors/notFound');
var UMDIFLSerializer = require('serializers/umdIflSerializer');
var UMDSerializer = require('serializers/umdSerializer');
var UseSerializer = require('serializers/useSerializer');
var router = new Router({
prefix: '/umd-loss-gain'
});
class UMDLossGainRouter {
static * getIFLNational(){
logger.info('Obtaining ifl national data');
this.assert(this.query.thresh, 400, 'thresh param required');
let data = yield CartoDBService.getIFLNational(this.params.iso, this.query.thresh);
this.body = UMDIFLSerializer.serialize(data);
}
static * getIFLSubnational(){
logger.info('Obtaining ifl subnational data');
this.assert(this.query.thresh, 400, 'thresh param required');
let data = yield CartoDBService.getIFLSubnational(this.params.iso, this.params.id1, this.query.thresh);
this.body = UMDIFLSerializer.serialize(data);
}
static * getNational(){
logger.info('Obtaining national data');
this.assert(this.query.thresh, 400, 'thresh param required');
let data = yield CartoDBService.getNational(this.params.iso, this.query.thresh, this.query.period);
logger.debug('Data final', data),
this.body = UMDSerializer.serialize(data);
}
static * getSubnational(){
logger.info('Obtaining subnational data');
this.assert(this.query.thresh, 400, 'thresh param required');
let data = yield CartoDBService.getSubnational(this.params.iso, this.params.id1, this.query.thresh, this.query.period);
this.body = UMDSerializer.serialize(data);
}
static * use(){
logger.info('Obtaining use data with name %s and id %s', this.params.name, this.params.id);
let useTable = null;
switch (this.params.name) {
case 'mining':
useTable = 'gfw_mining';
break;
case 'oilpalm':
useTable = 'gfw_oil_palm';
break;
case 'fiber':
useTable = 'gfw_wood_fiber';
break;
case 'logging':
useTable = 'gfw_logging';
break;
default:
this.throw(400, 'Name param invalid');
}
if(!useTable){
this.throw(404, 'Name not found');
}
try{
let data = yield GEEService.getUse(useTable, this.params.id, this.query.period, this.query.thresh);
this.body = UseSerializer.serialize(data);
} catch (err){
logger.error(err);
if(err instanceof NotFound){
this.throw(404, 'WDPA not found');
return;
}
throw err;
}
}
static * wdpa(){
logger.info('Obtaining wpda data with id %s', this.params.id);
try{
let data = yield GEEService.getWdpa(this.params.id, this.query.period, this.query.thresh);
this.body = UseSerializer.serialize(data);
} catch(err){
logger.error(err);
if(err instanceof NotFound){
this.throw(404, 'WDPA not found');
return;
}
throw err;
}
}
static * world(){
logger.info('Obtaining world data');
this.assert(this.query.geostore, 400, 'geostore param required');
let data = yield GEEService.getWorld(this.query.geostore, this.query.period, this.query.thresh);
this.body = UseSerializer.serialize(data);
}
}
var isCached = function *(next){
if (yield this.cashed()) {
return;
}
yield next;
};
router.get('/admin/ifl/:iso', isCached, UMDLossGainRouter.getIFLNational);
router.get('/admin/ifl/:iso/:id1', isCached, UMDLossGainRouter.getIFLSubnational);
router.get('/admin/:iso', isCached, UMDLossGainRouter.getNational);
router.get('/admin/:iso/:id1', isCached, UMDLossGainRouter.getSubnational);
router.get('/use/:name/:id', isCached, UMDLossGainRouter.use);
router.get('/wdpa/:id', isCached, UMDLossGainRouter.wdpa);
router.get('/', isCached, UMDLossGainRouter.world);
module.exports = router;
| JavaScript | 0.000002 | @@ -1392,50 +1392,8 @@
d);%0A
- logger.debug('Data final', data),%0A
|
283cedfd8187496f2c4aeb0d2c55f002442af00d | Connect to www not beta (which no longer exists) | public/js/app.controller.js | public/js/app.controller.js | "use strict";
var BaobabControllers; //globals
BaobabControllers
.controller('AppCtrl', ['$scope', '$me', '$inbox', '$auth', '$location', '$cookieStore', '$sce', function($scope, $me, $inbox, $auth, $location, $cookieStore, $sce) {
var self = this;
window.AppCtrl = this;
this.inboxAuthURL = $sce.trustAsResourceUrl('https://beta.inboxapp.com/oauth/authorize');
this.inboxClientID = $inbox.appId();
this.inboxRedirectURL = window.location.protocol + "//" + window.location.host + "/";
this.loginHint = '';
this.clearToken = $auth.clearToken;
this.token = function() {
return $auth.token;
};
this.namespace = function() {
return $me._namespace;
};
this.theme = $cookieStore.get('baobab_theme') || 'light';
this.setTheme = function(theme) {
self.theme = theme;
$cookieStore.put('baobab_theme', theme);
};
this.cssForTab = function(path) {
return ($location.path().indexOf(path) != -1) ? 'active' : '';
};
}]); | JavaScript | 0 | @@ -330,12 +330,11 @@
s://
-beta
+www
.inb
|
f3e0421b46cb02556c449f234f56eb618c3a3caa | Handle clicks to open links in a new tab correctly | public/js/routing/router.js | public/js/routing/router.js | /**
* Copyright 2015-2016, Google, Inc.
* 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.
*/
/* eslint-env browser */
export default class Router {
constructor(window, shell, container) {
this._routes = [];
this._shell = shell;
this._window = window;
this._container = container;
// Update UI when back is pressed.
this._window.addEventListener('popstate', this._updateContent.bind(this));
this._takeOverAnchorLinks(this._window.document);
}
findRoute(url) {
return this._routes.find(route => route.matches(url));
}
_updateContent() {
const location = this._window.document.location.href;
const page = this.findRoute(location);
if (!page) {
console.error('Url did not match any router: ', location);
// TODO: navigate to 404?
return;
}
page.transitionOut(this._container);
page.retrieveContent(location)
.then(content => {
this._container.innerHTML = content;
this._shell.afterAttach(page);
this._window.scrollTo(0, 0);
page.transitionIn(this._container);
this._takeOverAnchorLinks(this._container);
})
.catch(err => {
console.error('Error getting page content for: ', location, ' Error: ', err);
});
}
addRoute(route) {
this._routes.push(route);
}
navigate(url) {
console.log('Navigating To: ', url);
this._window.history.pushState(null, null, url);
this._updateContent();
}
_takeOverAnchorLinks(root) {
root.querySelectorAll('a').forEach(element => {
element.addEventListener('click', e => {
// Link does not have an url.
if (!e.currentTarget.href) {
return true;
}
// Never catch links to external websites.
if (!e.currentTarget.href.startsWith(this._window.location.origin)) {
return true;
}
// Check if there's a route for this url.
const page = this.findRoute(e.currentTarget.href);
if (!page) {
return true;
}
e.preventDefault();
this.navigate(e.currentTarget.href);
return false;
});
});
}
}
| JavaScript | 0 | @@ -2092,24 +2092,140 @@
ck', e =%3E %7B%0A
+ if (e.button !== 0 %7C%7C e.ctrlKey %7C%7C e.metaKey %7C%7C e.shiftKey %7C%7C e.altKey) %7B%0A return true;%0A %7D%0A%0A
// L
|
a695dd2c4c5a8d4e6fadb5ca4bae725350b5bae6 | Update collider() test helper | test/collider.js | test/collider.js | // matter.js
//
'use strict';
var fs = require('fs');
var os = require('os');
var path = require('path');
var spawnSync = require('child_process').spawnSync;
var expect = require('chai').expect;
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var uuid = require('node-uuid');
var TempDir = {
tmpLocation: null,
prepare: function () {
mkdirp.sync(this.tmpLocation);
},
clean: function () {
rimraf.sync(this.tmpLocation);
},
getPath: function (path) {
return path.join(this.tmpLocation, path);
},
read: function (path) {
return fs.readFileSync(this.getPath(path), 'utf8');
},
readJson: function (path) {
return JSON.parse(this.read(path));
},
exists: function (path) {
return fs.accessSync(path.join(this.tmpLocation, path), fs.F_OK);
},
collider: function () {
var args = Array.prototype.slice.call(arguments);
return spawnSync('collider', args, { cwd: this.tmpLocation });
},
};
// Set a unique temporary location.
TempDir.tmpLocation = path.join(os.tmpdir(), 'collider-cli-tests', uuid.v4());
// TESTS
//
before('prepare', function () {
TempDir.prepare();
});
describe('collider-cli', function () {
it('should return a usage string', function () {
});
describe('run', function () {
it('should run an existing project', function () {
});
it('should throw an error when run from a non-existent project', function () {
});
});
});
after('clean', function () {
TempDir.clean();
});
| JavaScript | 0 | @@ -828,24 +828,28 @@
nction (
+args
) %7B%0A
var args
@@ -844,56 +844,25 @@
-var
args =
-Array.prototype.slice.call(arguments)
+args %7C%7C %5B%5D
;%0A
|
d53812f545ca183de482cd30eb04073fff0df4e4 | fix logging only on dev | back/app.js | back/app.js | /**
* Fondi
* Open courses platform.
*
* @author Theodore Keloglou
* @file Main application boot file.
*/
var path = require('path');
var express = require('express');
// var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('config');
var routes = require('./routes/index');
var listeners = require('./util/listeners');
var models = require('./models/index');
var authMidd = require('./middleware/auth.midd');
var app = express();
app.set('views', path.join(__dirname, '../front/views'));
app.set('view engine', 'pug');
// Enable CORS
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// app.use(favicon(path.join(__dirname, '../front/static', 'favicon.ico')));
// app.use(logger('dev')); // FIXME
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: config.webserver.sessionSecret,
resave: false,
saveUninitialized: false,
store: new SequelizeStore({
db: models.sequelize,
}),
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
}, function (username, password, done) {
models.User.findOne({
where: {
username: username,
},
}).then(function (user) {
if (!user) {
return done(null, false, {
message: 'Incorrect username.',
});
}
return user.validPassword(password)
.then(function (isMatch) {
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {
message: 'Incorrect password.',
});
}
});
});
}));
passport.serializeUser(function (user, done) {
done(null, user.username);
});
passport.deserializeUser(function (username, done) {
models.User.findOne({
where: {
username: username,
},
}).then(function (user) {
done(null, user);
});
});
app.use(express.static(path.join(__dirname, '../front/static')));
app.use(authMidd.check);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler, will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
});
});
}
app.use(function (err, req, res) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {},
});
});
var port = config.webserver.port;
if (process.env.PORT) {
port = process.env.PORT;
}
app.set('port', port);
// models.sequelize.sync({ force: true })
models.sequelize.sync()
.then(function () {
app.listen(port);
app.on('error', listeners.onError);
app.on('listening', listeners.onListening);
console.log('Server running on http://localhost:' + port + '/');
});
module.exports = app;
| JavaScript | 0 | @@ -208,24 +208,56 @@
-favicon');%0A
+var logger = require('morgan');%0A
var cookiePa
@@ -1148,18 +1148,62 @@
co')));%0A
-//
+if (process.env.NDOE_ENV !== 'production') %7B%0A
app.use
@@ -1222,17 +1222,10 @@
'));
- // FIXME
+%0A%7D
%0A%0Aap
|
cb041cdd996f4bf11960988396b9269c2d250a36 | Increase limit when getting Content Types | example/mirror-content-model.js | example/mirror-content-model.js | #!/usr/bin/env node
'use strict';
var argv = require('optimist')
.usage('$0 access_token src_space_id dest_space_id')
.demand(3)
.argv;
var Promise = require('bluebird');
var contentful = require('../index');
var accessToken = argv._[0];
var srcSpaceId = argv._[1];
var destSpaceId = argv._[2];
var client = contentful.createClient({
accessToken: accessToken
});
var log = console.log.bind(log);
Promise.all([
client.getSpace(srcSpaceId).catch(function(error) {
console.log('Could not find source Space %s using access token %s', srcSpaceId, accessToken);
return error;
}),
client.getSpace(destSpaceId).catch(function(error) {
console.log('Could not find destination Space %s using access token %s', destSpaceId, accessToken);
return error;
})
]).spread(function(srcSpace, destSpace) {
srcSpace.getContentTypes().map(function(contentType) {
destSpace.createContentType(contentType).then(function() {
console.log('Duplicated Content Type %s from %s to %s',
contentType.sys.id, srcSpaceId, destSpaceId);
}).catch(function(error) {
var errorType = JSON.parse(error.body).sys.id;
return errorType === 'VersionMismatch';
}, function() {
console.log('Content Type %s already exists in %s', contentType.sys.id, destSpaceId);
}).catch(function(error) {
console.log('Could not duplicate Content Type %s from %s to %s',
contentType.sys.id, srcSpaceId, destSpaceId);
return error;
});
});
});
| JavaScript | 0 | @@ -843,16 +843,29 @@
ntTypes(
+%7Blimit: 1000%7D
).map(fu
|
d494ef1c15e7ee587cfd73002a77dcd400700ff6 | remove log | pkg/interface/src/views/landscape/components/Home/Post/PostItem/PostItem.js | pkg/interface/src/views/landscape/components/Home/Post/PostItem/PostItem.js | import React from 'react';
import { Box, Col, Row, Text } from '@tlon/indigo-react';
import { PostHeader } from './PostHeader';
import { PostContent } from './PostContent';
import { PostFooter } from './PostFooter';
import { PostInput } from '../PostInput';
import { Mention } from "~/views/components/MentionText";
import withState from '~/logic/lib/withState';
import { useHovering } from '~/logic/lib/util';
import { resourceFromPath, isWriter } from '~/logic/lib/group';
class PostItem extends React.Component {
constructor(props) {
super(props);
this.state = { inReplyMode: false };
this.toggleReplyMode = this.toggleReplyMode.bind(this);
this.navigateToReplies = this.navigateToReplies.bind(this);
this.submitCallback = this.submitCallback.bind(this);
}
canWrite() {
const {
group,
association,
vip,
index
} = this.props;
console.log(index);
if (vip === '') {
return true;
}
if (index && index.length > 0) {
return true;
}
return isWriter(group, association.resource);
}
toggleReplyMode() {
this.setState({ inReplyMode: !this.state.inReplyMode });
}
navigateToReplies() {
const { history, baseUrl, index, isParent } = this.props;
if (isParent) { return; }
let indexString = '';
index.forEach((i) => {
indexString = indexString + '/' + i.toString();
});
history.push(`${baseUrl}/feed${indexString}`);
}
submitCallback() {
this.toggleReplyMode();
}
render() {
const {
node,
api,
graphPath,
association,
index,
innerRef,
isParent,
isReply,
isRelativeTime,
parentPost,
vip,
group,
hovering,
bind
} = this.props;
const graphResource = resourceFromPath(graphPath);
let indexString = '';
index.forEach((i) => {
indexString = indexString + '/' + i.toString();
});
const { inReplyMode } = this.state;
const canComment = this.canWrite();
return (
<Col
ref={innerRef}
pl="1"
pr="1"
mb="3"
width="100%"
alignItems="center">
<Col
pt="2"
border={1}
borderColor={ isParent ? "gray" : "lightGray" }
borderRadius="2"
width="100%"
maxWidth="600px"
backgroundColor={ hovering ? 'washedGray' : 'transparent' }
onClick={this.navigateToReplies}
cursor={isParent ? "default": "pointer"}
{...bind}>
<PostHeader
post={node.post}
api={api}
association={association}
showTimestamp={isRelativeTime}
isReply={isReply} />
{ isReply ? (
<Row width="100%" alignItems="center" mb="2" pl="2" pr="2">
<Text color="gray" pr="1">Replying to</Text>
<Mention ship={parentPost.author} />
</Row>
) : null }
<PostContent
post={node.post}
isParent={isParent}
isReply={isReply}
api={api} />
<PostFooter
timeSent={node.post['time-sent']}
replyCount={node.children.size}
showTimestamp={!isRelativeTime}
isParent={isParent}
canComment={canComment}
toggleReplyMode={this.toggleReplyMode} />
</Col>
{ inReplyMode ? (
<Col width="100%" maxWidth="600px">
<Box
ml="3"
height="16px"
borderLeft={1}
borderLeftColor="lightGray"></Box>
<PostInput
api={api}
graphPath={graphPath}
group={group}
association={association}
vip={vip}
index={indexString}
submitCallback={this.submitCallback} />
</Col>
) : null }
</Col>
);
}
}
export default withState(PostItem, [
[useHovering, ['hovering', 'bind']],
]);
| JavaScript | 0.000003 | @@ -889,32 +889,8 @@
ops;
-%0A console.log(index);
%0A%0A
|
a26a301387889683e4796458a7723ec9d4ffc0c4 | Fix display of poi title in the gadget arround me. | app/Resources/packages/Gadget-keosu-around-me/core.js | app/Resources/packages/Gadget-keosu-around-me/core.js | /************************************************************************
Keosu is an open source CMS for mobile app
Copyright (C) 2013 Vincent Le Borgne
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
//Main controller
app.controller('keosu-around-meController', function ($scope, $http, $sce, usSpinnerService, cacheManagerService) {
//Functions
$scope.parts=function(isList, isMap, $scope) {
$scope.isList = isList;
$scope.isMap = isMap;
}
//Init google gadget
$scope.initialize=function() {
var mapOptions = {
center: new google.maps.LatLng(47.21677,-1.553307),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$('#map_canvas').html('');
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
return map;
}
$scope.open = function (page) {
usSpinnerService.spin('spinner'); // While loading, there will be a spinner
cacheManagerService.get($scope.param.host + 'service/gadget/aroundme/view/'
+ page.id + '/json').success(function (data){
usSpinnerService.stop('spinner');
$scope.myMap = data[0];
$scope.myMap.description = $sce.trustAsHtml(decodedContent(data[0].description));
$scope.myMap.nom = $('<div/>').html(data[0].nom).text();
var map=$scope.initialize();
google.maps.event.trigger($("#map_canvas")[0], 'resize');
var latitudeAndLongitude = new google.maps.LatLng(data[0].lat,data[0].lng);
map.setCenter(latitudeAndLongitude);
markerOne = new google.maps.Marker({
position: latitudeAndLongitude,
map: map
});
window.setTimeout(function(){
google.maps.event.trigger($("#map_canvas")[0], 'resize');
map.setCenter(latitudeAndLongitude);
},100);
$scope.parts(false, true, $scope);
});
};
$scope.close = function () {
$scope.parts(true, false, $scope);
};
$scope.init = function (params) {
$scope.parts(true, false, $scope);
usSpinnerService.spin('spinner'); // While loading, there will be a spinner
$scope.param = params;
var onGpsSuccess = function(position) {
cacheManagerService.get($scope.param.host + 'service/gadget/aroundme/' + $scope.param.gadgetId +'/'
+ position.coords.latitude + '/'
+ position.coords.longitude + '/0/' + '10' + '/json').success(function (data) {
usSpinnerService.stop('spinner');
$tmp = [];
for (i = 0; i < data.data.length; i++) {
$tmp[i] = data.data[i];
$tmp[i].title = decodedContent(data.data[i].title);
}
$scope.pages = $tmp;
usSpinnerService.stop('spinner');
});
};
function onGpsError(error) {
alert('Impossible de vous localiser.');
}
cacheManagerService.getLocation($scope.param.host + 'service/gadget/aroundme/'+$scope.param.gadgetId+'/location')
.success(function (position) {
onGpsSuccess(position);
});
}
});
| JavaScript | 0 | @@ -3209,30 +3209,32 @@
title =
-decodedContent
+$('%3Cdiv/%3E').html
(data.da
@@ -3245,16 +3245,23 @@
%5D.title)
+.text()
;%0A%09%09%09%09%09%09
|
e476ecc6b9d002b158276dd06f10bb0bc8acc8d0 | Fix bug related to loader and empty list | app/assets/javascripts/components/members_list.es6.js | app/assets/javascripts/components/members_list.es6.js | // Require React
React = require('react/addons');
var $ = require('jquery-browserify');
var Loader = require('react-loader');
// import material UI
import mui from 'material-ui';
let List = mui.List;
let Colors = mui.Styles.Colors;
let ThemeManager = mui.Styles.ThemeManager;
let LightRawTheme = mui.Styles.LightRawTheme;
// Dependent component
import Member from './member.es6.js'
import Search from './search.es6.js'
import NoContent from './no_content.es6.js'
import Pagination from './pagination.es6.js'
import EmptyList from './empty_list.es6.js'
// Define component
const MembersList = React.createClass({
getInitialState () {
return {
members: [],
rels: [],
path: this.props.path,
featured: this.props.featured,
loaded: false,
muiTheme: ThemeManager.getMuiTheme(LightRawTheme)
};
},
childContextTypes: {
muiTheme: React.PropTypes.object
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentDidMount() {
if(this.isMounted()){
var query = decodeURIComponent(document.location.search.replace('?', ''));
var path = !query? this.state.path : this.state.path + '?' + query
this._fetchMembers(path, {});
}
},
setChecked(e, checked) {
this.setState({loaded: false});
this._fetchMembers(this.state.path, {hireable: checked});
},
render() {
let containerStyle = {
paddingTop: '50px'
};
let subHeaderStyles = {
fontSize: '25px',
marginBottom: '20px',
padding: '0',
display: 'inline-block',
marginRight: '30px'
};
let checkboxStyles = {
display: 'inline-block',
width: 'auto',
marginRight: '20px',
marginTop: '5px',
height: '20px',
width: '50%'
};
console.log(this.state.members.length === 0);
return (
<div className="members-list p-b-100">
<div className="container">
<div className="members-list members--small sm-pull-reset">
<Search action={"/members"} />
</div>
</div>
{this.state.members.length > 0 ?
<List subheader={this.state.featured? 'Featured members' : 'Result'} subheaderStyle={subHeaderStyles} className="container" style={containerStyle}>
<Loader loaded={this.state.loaded}>
{this.state.members.map(member => (
<Member member={member} key={member.id} meta={this.props.meta} />
))}
</Loader>
</List> : <EmptyList />
}
{this.state.rels.length > 0 && this.state.members.length > 0 ?
<Pagination links={this.state.rels} />
: <NoContent />
}
</div>
);
},
_fetchMembers(path, params) {
// Setup cache false
$.ajaxSetup({
cache: false
});
// Get initial members
$.getJSON(path, params, function(json, textStatus) {
this.setState({
members: json.members,
rels: json.rels,
loaded: true
});
// Pre fetch paginations
setTimeout(function(){
json.rels.map(function(link) {
$.get('?' + decodeURIComponent(link.url), function(data) {
}, "html");
}.bind(this));
}.bind(this), 1000);
}.bind(this));
}
});
module.exports = MembersList;
| JavaScript | 0 | @@ -1996,58 +1996,8 @@
%7D;%0A%0A
- console.log(this.state.members.length === 0);%0A
@@ -2005,16 +2005,16 @@
eturn (%0A
+
%3Cd
@@ -2231,33 +2231,100 @@
%3C/div%3E%0A
-%7B
+%3CLoader loaded=%7Bthis.state.loaded%7D%3E%0A %7Bthis.state.loaded &&
this.state.membe
@@ -2331,32 +2331,34 @@
rs.length %3E 0 ?%0A
+
%3CList
@@ -2503,58 +2503,8 @@
e%7D%3E%0A
- %3CLoader loaded=%7Bthis.state.loaded%7D%3E%0A
@@ -2547,18 +2547,16 @@
er =%3E (%0A
-
@@ -2643,36 +2643,12 @@
-
))%7D%0A
- %3C/Loader%3E%0A
@@ -2672,24 +2672,25 @@
EmptyList /%3E
+%7D
%0A %7D%0A
@@ -2682,25 +2682,34 @@
/%3E%7D%0A
-%7D
+%3C/Loader%3E%0A
%0A %7Bth
|
a5aa20278cc4ac08e9aead2ed6228af67607cf45 | Remove unneeded class | app/assets/javascripts/controllers/user_controller.js | app/assets/javascripts/controllers/user_controller.js | HB.UserController = Ember.ObjectController.extend(HB.HasCurrentUser, {
coverUpload: Ember.Object.create(),
coverUrl: Ember.computed.any('coverUpload.croppedImage', 'model.coverImageUrl'),
coverImageStyle: function () {
return "background-image: url(" + this.get('coverUrl') + ")";
}.property('coverUrl'),
coverImageOverlayStyle: function () {
return "background-image: url(" + this.get('coverUrl') + "); mask: url(#blur-fade); filter: url(#blur)";
}.property('coverUrl'),
showEditMenu: false,
viewingSelf: function () {
return this.get('model.id') === this.get('currentUser.id');
}.property('model.id'),
forumProfile: function () {
return "https://forums.hummingbird.me/users/" + this.get('model.username');
}.property('model.username'),
// Legacy URLs
feedURL: function () {
return "/users/" + this.get('model.username') + "/feed";
}.property('model.username'),
libraryURL: function () {
return "/users/" + this.get('model.username') + "/watchlist";
}.property('model.username'),
actions: {
toggleEditMenu: function(){
this.toggleProperty('showEditMenu');
},
saveEditMenu: function(){
this.toggleProperty('showEditMenu');
this.get('model').set('miniBio', this.get('truncatedBio'));
this.get('content').save();
},
coverSelected: function (file) {
var self = this;
var reader = new FileReader();
reader.onload = function (e) {
self.set('coverUpload.originalImage', e.target.result);
return self.send('openModal', 'crop-cover', self.get('coverUpload'));
};
return reader.readAsDataURL(file);
},
avatarSelected: function (file) {
var self = this;
var data = new FormData();
data.append('avatar', file);
return ic.ajax({
url: '/users/' + this.get('model.username') + '/avatar.json',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'PUT'
}).then(function (response) {
// Update both the user and current_user, should kind of work
response['user'] = response['current_user'];
self.store.pushPayload(response);
});
}
}
});
| JavaScript | 0.000007 | @@ -315,184 +315,8 @@
),%0A%0A
- coverImageOverlayStyle: function () %7B%0A return %22background-image: url(%22 + this.get('coverUrl') + %22); mask: url(#blur-fade); filter: url(#blur)%22;%0A %7D.property('coverUrl'),%0A%0A
sh
|
ccf590512b46e7456e27c80d5041533b590241f2 | Add basic tooltip functionality to scatter plot | app/assets/javascripts/d3/scatter-plot/scatterPlot.js | app/assets/javascripts/d3/scatter-plot/scatterPlot.js | function drawApprovalScatterPlot() {
var plot = d3.select("#approval-scatter");
var WIDTH = 1000;
var HEIGHT = 600;
var MARGINS = {
top: 40,
right: 40,
bottom: 60,
left: 80
};
// KMEANS_DATA is defined in kmeans_training_results.js
var data = KMEANS_DATA;
var xScale = d3.scale.linear()
.range([MARGINS.left, WIDTH - MARGINS.right])
.domain([d3.min(data.map(function(d) {
return parseFloat(d.stockPrice);
})), d3.max(data.map(function(d) {
return parseFloat(d.stockPrice);
}))]);
var yScale = d3.scale.linear()
.range([HEIGHT - MARGINS.top, MARGINS.bottom])
.domain([d3.min(data.map(function(d) {
return parseFloat(d.unemployment);
})) - 0.5, d3.max(data.map(function(d) {
return parseFloat(d.unemployment);
}))]);
var colorScale = d3.scale.linear()
.domain([d3.min(data.map(function(d) {
return parseInt(d.approval);
})), d3.max(data.map(function(d) {
return parseInt(d.approval);
}))])
.range(["red", "green"]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
var chartTitle = plot.append("text")
.attr("class", "scatter-plot-title")
.attr("text-anchor", "middle")
.attr("transform", "translate(" + (WIDTH / 2) + "," + ((MARGINS.top / 2) + (MARGINS.top / 6)) + ")")
.text("Obama's Approval Rating vs. Unemployment and S&P 500 Price");
var yAxisLabel = plot.append("text")
.attr("class", "scatter-axis-label")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90), translate(-" + (HEIGHT / 2) + ", 30)")
.text("Unemployment Rate (%)");
var xAxisLabel = plot.append("text")
.attr("class", "scatter-axis-label")
.attr("text-anchor", "middle")
.attr("transform", "translate(" + (WIDTH / 2) + "," + (HEIGHT - (MARGINS.bottom / 4)) + ")")
.text("S&P 500 Close Price");
plot.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
plot.append("g")
.attr("class", "y-axis")
.attr("transform", "translate(" + MARGINS.left + ",0)")
.call(yAxis);
var yaxiscords = d3.range(MARGINS.top, HEIGHT - MARGINS.bottom + 1, 20);
var xaxiscords = d3.range(MARGINS.left, WIDTH - MARGINS.right + 1, 20);
plot.selectAll("line.vertical") // grid for x axis
.data(xaxiscords)
.enter().append("svg:line")
.attr("x1", function(d) {return d;})
.attr("y1", MARGINS.top)
.attr("x2", function(d) {return d;})
.attr("y2", HEIGHT - MARGINS.bottom)
.style("stroke", "rgb(192,192,192)")
.style("opacity", 0.3)
.style("stroke-width", 2);
plot.selectAll("line.horizontal") // grid for y axis
.data(yaxiscords)
.enter().append("svg:line")
.attr("x1", MARGINS.left)
.attr("y1", function(d) {return d;})
.attr("x2", WIDTH - MARGINS.right)
.attr("y2", function(d) {return d;})
.style("stroke", "rgb(192,192,192)")
.style("opacity", 0.3)
.style("stroke-width", 2);
var pointGroups = plot.selectAll(".point-group")
.data(data)
.enter()
.append("g")
.attr("class", "point-group");
var plotPoints = pointGroups.append("circle")
.attr("class", "plot-point")
.attr("r", function(d) {
return 10 * Math.pow((d.approval / 50), 2);
})
.attr("cx", WIDTH / 2)
.attr("cy", HEIGHT / 2)
.attr("fill", function(d) {
return colorScale(parseInt(d.approval));
});
plotPoints.transition()
.duration(1500)
.attr("cx", function(d) {
return xScale(parseFloat(d.stockPrice));
})
.attr("cy", function(d) {
return yScale(parseFloat(d.unemployment));
});
}
| JavaScript | 0 | @@ -4577,10 +4577,736 @@
%7D);%0A
+%0A plotPoints.on(%22mousemove%22, function(d) %7B%0A d3.selectAll(%22.scatter-plot-tooltip%22).remove();%0A var toolTipX = d3.mouse(this)%5B0%5D + 10;%0A var toolTipY = d3.mouse(this)%5B1%5D - 5;%0A var toolTip = d3.select(this.parentElement)%0A .append(%22g%22)%0A .attr(%22class%22, %22scatter-plot-tooltip%22)%0A .attr(%22transform%22, %22translate(%22 + toolTipX + %22,%22 + toolTipY + %22)%22)%0A toolTip.append(%22rect%22)%0A .attr(%22width%22, 25)%0A .attr(%22height%22, 25)%0A .attr(%22fill%22, %22#bbb%22)%0A .attr(%22transform%22, %22translate(0, -15)%22);%0A toolTip.append(%22text%22)%0A .text(d.approval);%0A %7D);%0A%0A plotPoints.on(%22mouseout%22, function() %7B%0A d3.selectAll(%22.scatter-plot-tooltip%22).remove();%0A %7D);%0A%0A
%7D%0A
|
46493a5fe31ae3c139dcee00370d8a423235b1ec | fix in breaking float after activating an accordion and displaying a scrollbar | media/js/Layout.js | media/js/Layout.js | var Sidebar = new Class({
Implements: [Options, Class.Occlude],
options: {
DOM: ''
},
initialize: function (options) {
this.setOptions(options);
if ($(this.options.DOM)) {
this.element = $(this.options.DOM);
this.resize();
Layout.addEvents({
'resize': this.resize.bind(this)
});
window.addEvents({
'scroll': this.resize.bind(this)
});
this.element.getFirst('.toggler').addClass('active');
this.accordion = new Fx.Accordion('#' + this.options.DOM + ' .toggler', '#' + this.options.DOM + ' .element');
this.accordion.addEvent('active', function(toggler, element) {
toggler.addClass('active').getSiblings('.toggler').removeClass('active');
});
}
},
resize: function () {
this.element.setStyle('min-height',window.getSize().y - this.element.getPosition().y - 8)
}
});
var Layout = {
start: function () {
this.sidebar = new Sidebar({DOM: 'sidebar'});
window.addEvents({
'resize': function() {
this.resize();
}.bind(this),
});
var results = $$('#result')
var result = ($type(results) == 'array') ? results[0] : false;
$$('.editor_label').setStyle('opacity',0.8);
if (result) {
result.getElement('.editor_label').setStyle('opacity', 0.3);
this.result = result.getElement('iframe');
}
this.resize();
this.fireEvent('ready');
},
resize: function(e) {
if (this.js_edit) this.js_edit.element.hide();
if (this.result) this.result.hide();
var window_size = window.getSize();
var full_width = window_size.x - $('content').getPosition().x;
var width = Math.floor(full_width / 2) - 10; // width + border
$$('fieldset p').setStyle('width', width + 10);
if (this.js_edit) {
this.js_edit.element.show();
var top = this.js_edit.element.getPosition().y;
var height = window_size.y - top - 10; // height + border
this.js_edit.element.setStyles({
'height': height,
'width': width
});
}
if (this.result) {
this.result.show();
if (!this.js_edit) {
var top = this.result.getPosition().y;
var height = window_size.y - top - 10;
}
this.result.setStyles({
'height': height,
'width': width
});
}
if (this.css_edit) this.css_edit.element.setStyle('width', width);
if (this.html_edit) this.html_edit.element.setStyle('width', width);
this.fireEvent('resize');
}
}
$extend(Layout, new Events())
| JavaScript | 0 | @@ -679,17 +679,21 @@
ctive');
+%09%09%09%09
%0A
-
%09%09%09%7D);%0A%09
@@ -913,39 +913,49 @@
;%0A%09%09
-window.addEvents(%7B%0A%09%09%09'resize':
+this.sidebar.accordion.addEvent('active',
fun
@@ -965,33 +965,81 @@
on()
-
%7B%0A%09%09%09
-%09this.resize();
+var self = this%0A%09%09%09return (function() %7Bself.resize()%7D.delay(700))
%0A%09%09
-%09
%7D.bi
@@ -1050,15 +1050,62 @@
his)
-,%0A%09%09%7D);
+);%0A%09%09window.addEvent('resize', this.resize.bind(this))
%0A%09%09v
@@ -1595,24 +1595,8 @@
th =
- window_size.x -
$('
@@ -1608,24 +1608,20 @@
nt').get
-Position
+Size
().x;%0A%09%09
@@ -1683,16 +1683,22 @@
border%0A
+%09%09%0A%09%09%0A
%09%09$$('fi
|
3d5ea6aacb33eda0e972fda2b3f6f349d2176e32 | Handle errors in reduce. | accumulator.js | accumulator.js | /* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
forin: true latedef: false globalstrict: true */
'use strict';
var Name = require('name')
var Method = require('method')
var Box = require('./box')
var core = require('./core'),
accumulate = core.accumulate, end = core.end, error = core.error,
convert = core.convert, map = core.map
var eventuals = require('eventual/eventual'),
defer = eventuals.defer, deliver = eventuals.deliver, when = eventuals.when
function reduce(source, f, state) {
var promise = defer()
accumulate(source, function(value) {
if (value && value.isBoxed) {
if (value.is === end) deliver(promise, state)
if (value.is === error) deliver(promise, value.value)
return value
} else {
state = f(state, value)
return state
}
}, state)
return when(promise)
}
exports.reduce = reduce
function reducible(source, f) {
return convert(source, function(source, next, initial) {
var result = f(source, function forward(result, value) {
return next(value, result)
}, initial)
when(result, function(value) { next(end(), value) })
})
}
// console.log(into(join([ 1, 2 ], [ 3 ], [ 3, 5 ])))
function flatten(source) {
/**
Flattens given `reducible` collection of `reducible`s
to a `reducible` with items of nested `reducibles`.
**/
return reducible(source, function(_, next, initial) {
return reduce(source, function(result, nested) {
return reduce(nested, function(result, value) {
return next(result, value)
}, result)
}, initial)
})
}
exports.flatten = flatten
// console.log(into(flatten([ [1, 2], [ 3, 4 ], [], [ 7, 8 ] ])))
function expand(source, f) {
return flatten(map(source, f))
}
exports.expand = expand
/*
console.log(into(expand(function(x) {
return [ x, x * x ]
}, [ 1, 2, 3 ])))
*/
function into(source, buffer) {
/**
Adds items of given `reducible` into
given `array` or a new empty one if omitted.
**/
return reduce(source, function(result, value) {
result.push(value)
return result
}, buffer || [])
}
exports.into = into
| JavaScript | 0.000002 | @@ -1170,16 +1170,22 @@
value) %7B
+%0A
next(en
@@ -1195,16 +1195,62 @@
, value)
+%0A %7D, function(e) %7B%0A next(error(e))%0A
%7D)%0A %7D)
|
65583a0fcc733ee2b5c50180362cf9d1b4f4cd85 | add array.from | webpack.config.production.js | webpack.config.production.js | /* eslint-disable no-var */
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: ['./src/index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: path.resolve(__dirname),
alias: {
'appConfig': 'src/prod-config.js'
},
extensions: ['', '.js']
},
devtool: 'source-map',
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new ExtractTextPlugin('style.css', {
allChunks: true
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
'Map': 'core-js/fn/map',
'Symbol': 'core-js/fn/symbol',
'Promise': 'core-js/fn/promise',
'Object.assign': 'core-js/fn/object/assign'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
"style",
"css?minimize!sass"
)
},
{
test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,
loader: 'file'
}
]
}
};
| JavaScript | 0.000027 | @@ -1097,16 +1097,63 @@
/assign'
+,%0A 'Array.from': 'core-js/fn/array/from'
%0A %7D)%0A
|
d791be4e0801f85c2d0efb613fa882a550d63b6f | fix linter | webpack.config.production.js | webpack.config.production.js | 'use strict';
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const banner = require('./dev/banner');
const VERSION = require('./package.json').version;
function getConfig(options) {
const optimize = options.optimize || false;
const minimize = optimize ? 'minimize' : '-minimize';
const ENV_VAR = {
'process.env': {
'VERSION': JSON.stringify(VERSION),
'process.env.NODE_ENV': JSON.stringify('production')
}
};
const config = {
context: __dirname,
entry: {
'availity-uikit': './js/index.js'
},
resolve: {
extensions: ['.js']
},
output: {
path: 'dist',
filename: optimize ? 'js/[name].min.js' : 'js/[name].js',
library: 'availity-uikit',
libraryTarget: 'umd',
umdNamedDefine: true
},
externals: {
'jquery': 'jQuery'
},
devtool: 'source-map',
stats: {
colors: true,
reasons: true,
hash: true,
version: true,
timings: true,
chunks: true,
chunkModules: true,
cached: true,
cachedAssets: true
},
module: {
loaders: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /(bower_components|node_modules)/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
`css-loader?sourceMap&${minimize}?limit=32768?name=images/[name].[ext]`,
'postcss-loader'
],
publicPath: '../'
})
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
`css-loader?sourceMap&${minimize}?limit=32768?name=images/[name].[ext]`,
'postcss-loader',
'sass-loader?sourceMap'
],
publicPath: '../'
})
},
{
// test should match the following:
//
// '../fonts/availity-font.eot?18704236'
// '../fonts/availity-font.eot'
//
test: /\.(otf|ttf|woff2?|eot|svg)(\?.*)?$/,
use: [
'file-loader?name=fonts/[name].[ext]'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
'url-loader?name=images/[name].[ext]&limit=10000'
]
}
]
},
plugins: [
new webpack.BannerPlugin({
banner: banner(),
exclude: ['vendor']
}),
new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
new ExtractTextPlugin('css/[name].css'),
new webpack.DefinePlugin(ENV_VAR),
new webpack.LoaderOptionsPlugin(
{
test: /\.s?css$/,
debug: false,
options: {
postcss: [
autoprefixer(
{
browsers: [
'last 5 versions',
'Firefox ESR',
'not ie < 9'
]
}
)
],
context: __dirname,
output: { path: '/build' }
}
}
)
]
};
if (optimize) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
minimize: true,
mangle: false,
output: {
comments: false
},
compressor: {
screw_ie8: true,
warnings: false
}
})
);
}
return config;
}
module.exports = getConfig;
| JavaScript | 0.000002 | @@ -249,18 +249,16 @@
rsion;%0A%0A
-%0A%0A
function
|
a04a5e0daa2d4dec99846c5d8cc6427b7e6ed4c3 | fix eslint errors for xod-client-chrome (add chrome to globals) | xod-client-chrome/.eslintrc.js | xod-client-chrome/.eslintrc.js | module.exports = {
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
plugins: [
'react',
'import',
],
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/react',
'plugin:react/recommended',
'airbnb',
],
};
| JavaScript | 0 | @@ -347,12 +347,48 @@
b',%0A %5D,
+%0A%0A globals: %7B%0A chrome: true,%0A %7D
%0A%7D;%0A
|
9885fce1e3f535bef3ce3b2747f91222adfbb717 | Fix comment path slashes | rollup-examples.config.js | rollup-examples.config.js | var path = require( 'path' );
var fs = require( 'fs' );
// Creates a rollup config object for the given file to
// be converted to umd
function createOutput( file ) {
var inputPath = path.resolve( file );
var outputPath = inputPath.replace( /[\\\/]examples[\\\/]jsm[\\\/]/, '/examples/js/' );
// Every import is marked as external so the output is 1-to-1. We
// assume that that global object should be the THREE object so we
// replicate the existing behavior.
return {
input: inputPath,
treeshake: false,
external: p => p !== inputPath,
plugins: [{
generateBundle: function(options, bundle) {
for ( var key in bundle ) {
bundle[ key ].code = bundle[ key ].code.replace( /three_module_js/g, 'THREE' );
}
}
}],
output: {
format: 'umd',
name: 'THREE',
file: outputPath,
globals: () => 'THREE',
paths: p => /three\.module\.js$/.test( p ) ? 'three' : p,
extend: true,
banner:
'/**\n' +
` * Generated from '${ path.relative( '.', inputPath.replace( /\\/, '/' ) ) }'\n` +
' */\n',
esModule: false
}
};
}
// Walk the file structure starting at the given directory and fire
// the callback for every js file.
function walk( dir, cb ) {
var files = fs.readdirSync( dir );
files.forEach( f => {
var p = path.join( dir, f );
var stats = fs.statSync( p );
if ( stats.isDirectory() ) {
walk( p, cb );
} else if ( f.endsWith( '.js' ) ) {
cb( p );
}
} );
}
// Gather up all the files
var files = [];
walk( 'examples/jsm/', p => files.push( p ) );
// Create a rollup config for each module.js file
export default files.map( p => createOutput( p ) );
| JavaScript | 0.000247 | @@ -1001,32 +1001,34 @@
( '.', inputPath
+ )
.replace( /%5C%5C/,
@@ -1029,17 +1029,16 @@
/%5C%5C/
+g
, '/' )
- )
%7D'%5C
|
fe08585eb629c4a4e1bd6ba803bcc03d26d14000 | Remove logging | portal/js/router.js | portal/js/router.js | App.Router.map(function () {
this.resource('projects', {path: '/'}, function() {
this.resource('user-welcome');
this.resource('project', {path: '/:project_id'}, function() {
this.resource('investigation', {path: '/:investigation_id'}, function() {
this.resource('chart', {path: '/:chart_id'});
});
});
});
});
App.Router.reopen({
rootURL: '/portal'
});
App.ApplicationRoute = Ember.Route.extend({
model: function () {
var self = this;
return this.store.find('user').then(function(result){
return result.get('firstObject');
}, function(error){
self.render('user/error');
throw new Error('failed to get user');
});
},
afterModel: function(user, transition) {
if (!user.get('isDeveloper')) {
console.log("transitioning");
this.transitionTo('user-welcome');
}
}
})
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
renderTemplate: function() {
this.render('project');
this.render('project-title', {
outlet: 'title'
});
}
}); | JavaScript | 0.000001 | @@ -776,44 +776,8 @@
) %7B%0A
- console.log(%22transitioning%22);%0A
|
3e59c8a5c5de047056055cabef4454914159ffd5 | Fix relative url for zeroclipboard swf | app/scripts/timetable_builder/views/UrlSharingView.js | app/scripts/timetable_builder/views/UrlSharingView.js | define(['backbone.marionette', 'zeroclipboard', 'hbs!../templates/url_sharing'],
function(Marionette, ZeroClipboard, template) {
'use strict';
return Marionette.ItemView.extend({
template: template,
initialize: function() {
ZeroClipboard.config({
swfPath: 'bower_components/ZeroClipboard/dist/ZeroClipboard.swf'
});
var copyToClipboard = $('#copy-to-clipboard'),
clip = new ZeroClipboard(copyToClipboard),
shortURLInput = $('#short-url');
function getShortURL(callback) {
var shortURL = shortURLInput.val();
if (shortURL) {
callback(shortURL);
} else {
$.getJSON('short_url.php', {
url: location.href
}, function(data) {
shortURL = data.shorturl;
if (shortURL) {
shortURLInput.val(shortURL);
callback(shortURL);
}
});
}
}
shortURLInput.on('cut keydown', function (event) {
// Prevent default actions on cut and keydown to simulate readOnly
// behavior on input, as the readOnly attribute does not allow selection
// on some mobile platforms.
event.preventDefault();
}).focus(function() {
getShortURL(function() {
// shortURLInput.select() does not work on iOS
shortURLInput[0].setSelectionRange(0, 99);
});
}).mouseup(function (event) {
// Prevent the mouseup event from unselecting the selection
event.preventDefault();
});
var CLIPBOARD_TOOLTIP = 'Copy to Clipboard';
copyToClipboard.qtip({
content: CLIPBOARD_TOOLTIP,
events: {
hidden: function() {
// Set to original text when hidden as text may have been changed.
copyToClipboard.qtip('option', 'content.text', CLIPBOARD_TOOLTIP);
}
}
});
copyToClipboard.on('mouseover', function() {
getShortURL(function(shortURL) {
clip.setText(shortURL);
});
});
clip.on('aftercopy', function() {
copyToClipboard.qtip('option', 'content.text', 'Copied!');
});
$('#share-email').click(function() {
getShortURL(function(shortURL) {
window.location.href = 'mailto:?subject=My%20NUSMods.com%20Timetable&' +
'body=' + encodeURIComponent(shortURL);
});
}).qtip({
content: 'Share via Email'
});
$('#share-facebook').click(function() {
getShortURL(function(shortURL) {
window.open('http://www.facebook.com/sharer.php?u=' +
encodeURIComponent(shortURL), '', 'width=660,height=350');
});
}).qtip({
content: 'Share via Facebook'
});
$('#share-twitter').click(function() {
getShortURL(function(shortURL) {
window.open('http://twitter.com/intent/tweet?url=' +
encodeURIComponent(shortURL), '', 'width=660,height=350');
});
}).qtip({
content: 'Share via Twitter'
});
}
});
});
| JavaScript | 0.000004 | @@ -280,16 +280,17 @@
fPath: '
+/
bower_co
|
8a22e35e413efa8296b33845e723e349ea5e00ff | Add Glimmer 2 support Glimmer 2 changes the default second argument of the helper to an EmptyObject which: - doesn't provide `toString` - doesn't allow extending (See https://github.com/emberjs/ember.js/issues/14189) | addon/utils.js | addon/utils.js | import { currency } from "./settings";
/**
* Extends an object with a defaults object, similar to underscore's _.defaults
*
* Used for abstracting parameter handling from API methods
*/
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
// Iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasOwnProperty(key)) {
// Replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) {
object[key] = defs[key];
}
}
}
return object;
}
/**
* Check and normalise the value of precision (must be positive integer)
*/
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val)? base : val;
}
/**
* Tests whether supplied parameter is a true object
*/
function isObject(obj) {
return obj && obj.toString() === '[object Object]';
}
/**
* Parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* Either string or format.pos must contain "%v" (value) to be valid
*/
function checkCurrencyFormat(format) {
var defaults = currency.format;
// Allow function as format parameter (should return string or object):
if ( typeof format === "function" ) {
format = format();
}
// Format can be a string, in which case `value` ("%v") must be present:
if ( typeof format === "string" && format.match("%v") ) {
// Create and return positive, negative and zero formats:
return {
pos : format,
neg : format.replace("-", "").replace("%v", "-%v"),
zero : format
};
// If no format, or object is missing valid positive value, use defaults:
} else if ( !format || !format.pos || !format.pos.match("%v") ) {
// If defaults is a string, casts it to an object for faster checking next time:
if (typeof defaults !== "string") {
return defaults;
} else {
return currency.format = {
pos : defaults,
neg : defaults.replace("%v", "-%v"),
zero : defaults
};
}
}
// Otherwise, assume format was fine:
return format;
}
export {
defaults,
checkPrecision,
isObject,
checkCurrencyFormat
};
export default {
defaults: defaults,
checkPrecision: checkPrecision,
isObject: isObject,
checkCurrencyFormat: checkCurrencyFormat,
};
| JavaScript | 0.000001 | @@ -32,16 +32,87 @@
tings%22;%0A
+import Ember from 'ember';%0A%0Avar assign = Ember.assign %7C%7C Ember.merge;%0A%0A
/**%0A * E
@@ -314,20 +314,26 @@
t =
-object %7C%7C %7B%7D
+assign(%7B%7D, object)
;%0A
@@ -832,24 +832,247 @@
e : val;%0A%7D%0A%0A
+/**%0A * Returns the toString representation of an object even when the object %0A * does not support %60toString%60 out of the box, i.e. %60EmptyObject%60.%0A */%0Afunction toString(obj) %7B%0A return Object.prototype.toString.call(obj);%0A%7D%0A%0A
/**%0A * Tests
@@ -1165,12 +1165,8 @@
&&
-obj.
toSt
@@ -1170,16 +1170,19 @@
oString(
+obj
) === '%5B
|
43304385b518ae24cbd62d3d67b8ff2da27dae44 | test new range | CNN/tester/GSheets_tester.js | CNN/tester/GSheets_tester.js | export { tester };
import * as GSheets from "../util/GSheets.js";
import * as ValueMax from "../util/ValueMax.js";
/*
class TestCase {
constructor( spreadsheetId, range, apiKey ) {
this.source = source;
this.skipLineCount = skipLineCount;
this.result = result;
this.suspendByteCount = suspendByteCount;
this.note = note;
}
}
let testCases = [
new TestCase( tEncoder.encode(base64EncodedStrings_extra[ 0]), 1, emptyUint8Array, undefined, "Empty. Not enough lines." ),
*/
/**
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The
* created progressToAdvance will be increased when every time advanced. The
* progressParent.root_get() will be returned when every time yield.
*
*/
async function* tester( progressParent ) {
console.log( "GSheet download testing..." );
let progress1 = progressParent.child_add(
ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );
let progress2 = progressParent.child_add(
ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );
let spreadsheetId = "18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M";
let range = "A:A";
let apiKey = "AIzaSyDQpdX3Z7297fkZ7M_jWdq7zjv_IIxpArU";
// Without API key.
let tester1 = GSheets.UrlComposer.Pool.get_or_create_by( spreadsheetId, range );
let fetcher1 = tester1.fetcher_JSON_ColumnMajorArrayArray( progress1 );
let result1 = yield* fetcher1;
// With API key.
let tester2 = GSheets.UrlComposer.Pool.get_or_create_by( spreadsheetId, range, apiKey );
let fetcher2 = tester2.fetcher_JSON_ColumnMajorArrayArray( progress2 );
let result2 = yield* fetcher2;
// Compare results: should the same.
{
if ( result1.toString() != result2.toString() )
throw Error( ` ${result1} != ${result2}` );
}
tester2.disposeResources_and_recycleToPool();
tester2 = null;
tester1.disposeResources_and_recycleToPool();
tester1 = null;
console.log( "GSheet download testing... Done." );
}
| JavaScript | 0 | @@ -1002,17 +1002,231 @@
progress
-2
+11 = progressParent.child_add(%0A ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );%0A%0A let progress2 = progressParent.child_add(%0A ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );%0A%0A let progress21
= progr
@@ -2039,16 +2039,495 @@
);%0A %7D%0A%0A
+ // Test change range.%0A %7B%0A let newRange = result1%5B 0 %5D%5B 0 %5D;%0A tester1.range_set( newRange );%0A let fetcher11 = tester1.fetcher_JSON_ColumnMajorArrayArray( progress11 );%0A let result11 = yield* fetcher11;%0A%0A tester2.range_set( newRange );%0A let fetcher21 = tester2.fetcher_JSON_ColumnMajorArrayArray( progress21 );%0A let result21 = yield* fetcher21;%0A%0A if ( result11.toString() != result21.toString() )%0A throw Error( %60 $%7Bresult11%7D != $%7Bresult21%7D%60 );%0A %7D%0A%0A
tester
|
ddeda7c103112048b05756f09dde4faa07701d53 | Fix URLs with special characters | packages/example-forum/lib/server/posts/out.js | packages/example-forum/lib/server/posts/out.js | import { runCallbacksAsync } from 'meteor/vulcan:core';
import escapeStringRegexp from 'escape-string-regexp';
import { Picker } from 'meteor/meteorhacks:picker';
import { Posts } from '../../modules/posts/index.js';
Picker.route('/out', ({ query}, req, res, next) => {
if(query.url){ // for some reason, query.url doesn't need to be decoded
/*
If the URL passed to ?url= is in plain text, any hash fragment
will get stripped out.
So we search for any post whose URL contains the current URL to get a match
even without the hash
*/
try {
// decode url just in case
const decodedUrl = decodeURIComponent(query.url);
const post = Posts.findOne({url: {$regex: escapeStringRegexp(decodedUrl)}}, {sort: {postedAt: -1, createdAt: -1}});
if (post) {
const ip = req.headers && req.headers['x-forwarded-for'] || req.connection.remoteAddress;
runCallbacksAsync('posts.click.async', post, ip);
res.writeHead(301, {'Location': query.url});
res.end();
} else {
// don't redirect if we can't find a post for that link
res.end(`Invalid URL: ${query.url}`);
}
} catch (error) {
// eslint-disable-next-line no-console
console.log('// /out error');
// eslint-disable-next-line no-console
console.log(error);
// eslint-disable-next-line no-console
console.log(query);
}
} else {
res.end("Please provide a URL");
}
});
| JavaScript | 0.999799 | @@ -598,24 +598,27 @@
n case%0A
+ //
const decod
@@ -629,27 +629,8 @@
l =
-decodeURIComponent(
quer
@@ -634,17 +634,16 @@
uery.url
-)
;%0A%0A
@@ -704,24 +704,23 @@
gRegexp(
-decodedU
+query.u
rl)%7D%7D, %7B
|
2cb4aeb78fad04a4c87c517d5f039a16578cbab6 | use default for transition and allow to hide control buttons | addon/index.js | addon/index.js | import Ember from 'ember';
import WidgetModel from 'ember-eureka/widget-model';
export default WidgetModel.extend({
/** if false, display the save button
*/
isEmbedded: false,
model: Ember.computed.alias('routeModel'),
fieldNames: Ember.computed.alias('config.fields'),
/** display only the fields specified in `config.fields`
* If `config.fields` doesn't exists, display all model's fields
*/
fields: function() {
var fieldNames = this.get('fieldNames');
var fields, field;
if (fieldNames) {
var model = this.get('model');
fields = Ember.A();
fieldNames.forEach(function(fieldName) {
field = model.get(fieldName+'Field');
fields.pushObject(field);
});
} else {
fields = this.get('model._fields');
}
return fields;
}.property('fieldNames.[]', 'model._fields'),
label: Ember.computed.alias('config.label'),
actions: {
save: function() {
var model = this.get('model');
var that = this;
var routePath = this.get('config.actions.save.transitionTo');
model.save().then(function(m) {
var payload = {model: m, routePath: routePath};
that.sendAction('toControllerAction', {name: 'refreshModel'});
that.sendAction('toControllerAction', {name: 'transitionTo', payload: payload});
});
},
cancel: function() {
var model = this.get('model');
model.rollback();
var routePath = this.get('config.actions.cancel.transitionTo');
var payload = {model: model, routePath: routePath};
this.sendAction('toControllerAction', {name: 'transitionTo', payload: payload});
}
},
_focusOnFirstElement: function() {
this.$('input:eq(0)').focus();
}.on('didInsertElement'),
_focusOnNextElement: function() {
// XXX check li
this.$().closest('li').next().find('input').focus();
}.on('willDestroyElement')
});
| JavaScript | 0 | @@ -177,21 +177,64 @@
bedded:
-false
+Ember.computed.bool('config.hideControlButtons')
,%0A mo
@@ -1178,32 +1178,43 @@
ePath = this.get
+WithDefault
('config.actions
@@ -1224,32 +1224,70 @@
ve.transitionTo'
+, model.get('meta.modelIndexViewPath')
);%0A m
@@ -1758,24 +1758,296 @@
sitionTo');%0A
+ if (!routePath) %7B%0A if (model.get('_id')) %7B%0A routePath = model.get('meta.modelIndexViewPath');%0A %7D else %7B%0A routePath = model.get('meta.collectionIndexViewPath');%0A %7D%0A %7D%0A
|
b1b5c14aa21577913972a5ae1f47e6ab468774b5 | Update index.js | admin/index.js | admin/index.js |
var fs = require('fs-extra'),
marked = require('marked'),
path = require('path'),
ImportUbb = {
admin: {
menu: function(custom_header) {
custom_header.plugins.push({
"route": '/plugins/import-ubb',
"icon": 'icon-edit',
"name": 'ImportUbb'
});
return custom_header;
},
route: function(custom_routes, callback) {
fs.readFile(path.join(__dirname, '../README.md'), function(err, tpl) {
marked(tpl.toString(), function(err, content){
if (err) throw err;
custom_routes.routes.push({
route: '/plugins/import-ubb',
method: "get",
options: function(req, res, callback) {
callback({
req: req,
res: res,
route: '/plugins/import-ubb',
name: ImportUbb,
content: content
});
}
});
callback(null, custom_routes);
});
});
}
}
};
module.exports = ImportUbb; | JavaScript | 0.000002 | @@ -82,19 +82,133 @@
'),%0A
-%0A%09ImportUbb
+%09pkg = fs.readJsonSync(path.join(__dirname + '../package.json')),%0A nbbId = pkg.name.replace(/nodebb-plugin-/, ''),%0A%09Plugin
= %7B
@@ -307,35 +307,33 @@
: '/plugins/
-import-ubb'
+' + nbbId
,%0A%09%09%09%09%09%22icon
@@ -365,19 +365,13 @@
e%22:
-'ImportUbb'
+nbbId
%0A%09%09%09
@@ -662,35 +662,33 @@
: '/plugins/
-import-ubb'
+' + nbbId
,%0A%09%09%09%09%09%09%09met
@@ -833,19 +833,17 @@
ins/
-import-ubb'
+' + nbbId
,%0A%09%09
@@ -855,25 +855,22 @@
%09%09name:
-ImportUbb
+Plugin
,%0A%09%09%09%09%09%09
@@ -1010,14 +1010,12 @@
s =
-ImportUbb;
+Plugin;%0A
|
16e450fc95b0f2279e60ec71551e723f5a3d95c2 | store the selected layout in the URL | webapps/client/scripts/navigation/directives/cam-layout-switcher.js | webapps/client/scripts/navigation/directives/cam-layout-switcher.js | define([
'angular',
'text!./cam-layout-switcher.html'
], function(
angular,
template
) {
'use strict';
var $bdy = angular.element('body');
var layouts = [
{
label: 'task',
css: 'layout-focus-task'
},
{
label: 'list',
css: 'layout-focus-list'
},
{
label: 'standard'
}
];
var layoutClasses = layouts.map(function(layout) {
return layout.css || '';
}).join(' ');
return [function() {
return {
restrict: 'EAC',
link: function(scope) {
scope.activeLayout = parseInt(localStorage.hasOwnProperty('tasklistLayout') ?
localStorage.tasklistLayout :
(layouts.length - 1), 10);
scope.activeLayoutInfo = layouts[scope.activeLayout];
scope.layouts = layouts;
scope.switchLayout = function(delta) {
localStorage.tasklistLayout = delta;
var layout = layouts[delta];
scope.activeLayout = delta;
scope.activeLayoutInfo = layout;
$bdy
.removeClass(layoutClasses)
.addClass(layout.css)
;
};
scope.switchLayout(scope.activeLayout);
},
template: template
};
}];
});
| JavaScript | 0 | @@ -188,44 +188,16 @@
l: '
-task',%0A css: 'layout-focus-task
+standard
'%0A
@@ -282,32 +282,60 @@
label: '
-s
ta
-ndard
+sk',%0A css: 'layout-focus-task
'%0A %7D%0A %5D;
@@ -445,25 +445,88 @@
return %5B
-function(
+%0A '$location',%0A 'search',%0A function(%0A $location,%0A search%0A
) %7B%0A
@@ -600,85 +600,247 @@
-scope.activeLayout = parseInt(localStorage.hasOwnProperty('tasklistLayout') ?
+function applyLayout(delta) %7B%0A var layout = layouts%5Bdelta%5D;%0A scope.activeLayout = delta;%0A scope.activeLayoutInfo = layout;%0A%0A $bdy%0A .removeClass(layoutClasses)%0A .addClass(layout.css)
%0A
@@ -842,32 +842,34 @@
)%0A
+;%0A
@@ -852,32 +852,35 @@
;%0A
+%7D%0A%0A
@@ -871,72 +871,187 @@
- localStorage.tasklistLayout :%0A
+function applyRouteLayout() %7B%0A var state = $location.search();%0A var delta = parseInt(state.layout ? state.layout : 0, 10);%0A applyLayout(delta);%0A
@@ -1042,32 +1042,35 @@
a);%0A
+%7D%0A%0A
(lay
@@ -1061,43 +1061,83 @@
- (layouts.length - 1), 10
+applyRouteLayout();%0A scope.$on('$routeChanged', applyRouteLayout
);%0A
+%0A
@@ -1229,16 +1229,17 @@
youts;%0A%0A
+%0A
@@ -1291,83 +1291,38 @@
-localStorage.tasklistLayout = delta;%0A%0A var layout = layouts%5Bdelta%5D
+var state = $location.search()
;%0A
@@ -1326,36 +1326,30 @@
%0A s
-cope.activeL
+tate.l
ayout = delt
@@ -1366,200 +1366,76 @@
s
-cope.activeLayoutInfo = layout;%0A%0A $bdy%0A .removeClass(layoutClasses)%0A .addClass(layout.css)%0A ;%0A %7D;%0A%0A scope.switchLayout(scope.activeLayout)
+earch.updateSilently(state);%0A applyLayout(delta);%0A %7D
;%0A
|
e3558b9df3639427a3f0177c23bcc4e8a55ab752 | implement a small part of fstat() | runtime/js/modules/_fs.js | runtime/js/modules/_fs.js | // Copyright (c) 2015 Tzvetan Mikov.
// Licensed under the Apache License v2.0. See LICENSE in the project
// root for complete license information.
var _jsc = require("./_jsc");
exports.FSInitialize = function FSInitialize (stats) {
console.error("process.binding.fs.FSInitialize() is not implemented");
};
exports.open = function open (path, flags, mode)
{
var hnd = __asm__({},["res"],[["path", String(path)], ["flags", flags | 0], ["mode", mode | 0]], [],
"%[res] = js::makeNumberValue(" +
"::open(%[path].raw.sval->getStr()," +
"(int)%[flags].raw.nval," +
"(int)%[mode].raw.nval" +
"));"
);
if (hnd === -1)
_jsc.throwIOError("open", path);
return hnd;
};
exports.close = function close(fd) {
console.error("process.binding.fs.close() is not implemented");
};
exports.fstat = function fstat(fd) {
console.error("process.binding.fs.fstat() is not implemented");
return {size: 0};
};
exports.read = function read(fd, buffer, offset, length, position) {
console.error("process.binding.fs.read() is not implemented");
return 0;
};
| JavaScript | 0.000277 | @@ -173,16 +173,55 @@
jsc%22);%0A%0A
+__asmh__(%7B%7D,%22#include %3Csys/stat.h%3E%22);%0A%0A
exports.
@@ -879,24 +879,25 @@
ented%22);%0A%7D;%0A
+%0A
exports.fsta
@@ -918,83 +918,426 @@
stat
+
(fd)
-
+%0A
%7B%0A
-console.error(%22process.binding.fs.fstat() is not implemented
+var size;%0A if (__asm__(%7B%7D,%5B%22res%22%5D,%5B%5B%22fd%22, fd%7C0%5D, %5B%22size%22, size%5D%5D,%5B%5D,%0A %22struct stat buf;%5Cn%22 +%0A %22int res;%5Cn%22 +%0A %22%25%5Bres%5D = js::makeNumberValue(res = ::fstat((int)%25%5Bfd%5D.raw.nval, &buf));%5Cn%22 +%0A %22if (res != -1) %7B%5Cn%22 +%0A %22 %25%5Bsize%5D = js::makeNumberValue(buf.st_size);%5Cn%22 +%0A %22%7D%22%0A ) === -1)%0A %7B%0A _jsc.throwIOError(%22fstat
%22);%0A
+ %7D%0A%0A
@@ -1348,21 +1348,27 @@
rn %7B
+
size:
-0
+size
%7D;%0A%7D;%0A
+%0A
expo
|
38986fd2554f9f075736dfdc0b13de06a00597f5 | Fix flatten two dimensional array | src/Symbologies/Code39.js | src/Symbologies/Code39.js | // @flow
import type { Barcode } from "../Core/Barcode"
import type { DiscreteSymbologySymbol } from "../Core/Characters"
import { NARROW_BAR, NARROW_SPACE, WIDE_BAR, WIDE_SPACE } from "../Core/Characters"
// See https://en.wikipedia.org/wiki/Code_39
export const Mapping: { [key: string]: DiscreteSymbologySymbol[] } = {}
const BaseMapping = {}
const Bars = [
[
// 1
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
],
[
// 2
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
],
[
// 3
WIDE_BAR,
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
NARROW_BAR,
],
[
// 4
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
WIDE_BAR,
],
[
// 5
WIDE_BAR,
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
],
[
// 6
NARROW_BAR,
WIDE_BAR,
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
],
[
// 7
NARROW_BAR,
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
WIDE_BAR,
],
[
// 8
WIDE_BAR,
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
],
[
// 9
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
WIDE_BAR,
NARROW_BAR,
],
[
// 10
NARROW_BAR,
NARROW_BAR,
WIDE_BAR,
WIDE_BAR,
NARROW_BAR,
],
]
const Spaces = [
[
// +0
NARROW_SPACE,
WIDE_SPACE,
NARROW_SPACE,
NARROW_SPACE,
],
[
// +10
NARROW_SPACE,
NARROW_SPACE,
WIDE_SPACE,
NARROW_SPACE,
],
[
// +20
NARROW_SPACE,
NARROW_SPACE,
NARROW_SPACE,
WIDE_SPACE,
],
[
// +30
WIDE_SPACE,
NARROW_SPACE,
NARROW_SPACE,
NARROW_SPACE,
],
]
function populate() {
// Numbers
for (let i = 1; i <= 9; i++) {
BaseMapping[i.toString()] = [i - 1, 0]
}
BaseMapping["0"] = [9, 0]
// A-J
for (let i = "A".charCodeAt(0); i <= "J".charCodeAt(0); i++) {
BaseMapping[String.fromCharCode(i)] = [i - "A".charCodeAt(0), 1]
}
// K-T
for (let i = "K".charCodeAt(0); i <= "T".charCodeAt(0); i++) {
BaseMapping[String.fromCharCode(i)] = [i - "K".charCodeAt(0), 2]
}
// U-Z
for (let i = "U".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
BaseMapping[String.fromCharCode(i)] = [i - "U".charCodeAt(0), 3]
}
BaseMapping["-"] = [6, 3]
BaseMapping["."] = [7, 3]
BaseMapping[" "] = [8, 3]
BaseMapping["*"] = [9, 3]
}
function map() {
for (const key of Object.keys(BaseMapping)) {
const bar = BaseMapping[key][0]
const space = BaseMapping[key][1]
const reduction = []
for (let i = 0; i < Spaces[space].length; i++) {
reduction.push(Bars[bar][i])
reduction.push(Spaces[space][i])
}
reduction.push(Bars[bar][Bars[bar].length - 1])
Mapping[key] = reduction
}
}
populate()
map()
Mapping["+"] = [
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
NARROW_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
]
Mapping["/"] = [
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
NARROW_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
]
Mapping["$"] = [
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
NARROW_SPACE,
NARROW_BAR,
]
Mapping["%"] = [
NARROW_BAR,
NARROW_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
WIDE_SPACE,
NARROW_BAR,
]
function _encodeContent(text: string, fallbackChar: string): DiscreteSymbologySymbol[] {
const encodedCharacters: DiscreteSymbologySymbol[] = text
.toUpperCase()
.split("")
.map(character => (Mapping[character] ? Mapping[character] : Mapping[fallbackChar]))
const flattenedIncludingSeparators: DiscreteSymbologySymbol[] = encodedCharacters.map(encodedCharacter => [
...encodedCharacter,
NARROW_SPACE,
])
return flattenedIncludingSeparators
}
export function encodeCode39(text: string, fallbackChar: string = "-"): Barcode<DiscreteSymbologySymbol> {
if (!Mapping.hasOwnProperty(fallbackChar)) {
fallbackChar = "-"
}
const encodedContent: DiscreteSymbologySymbol[] = _encodeContent(text, fallbackChar)
const encoded: DiscreteSymbologySymbol[] = [...Mapping["*"], NARROW_SPACE, ...encodedContent, ...Mapping["*"]]
return {
encoded,
plainTextContent: text,
}
}
| JavaScript | 0.999986 | @@ -3245,16 +3245,18 @@
Symbol%5B%5D
+%5B%5D
= text%0A
@@ -3380,23 +3380,21 @@
%0A%09const
-flatten
+encod
edInclud
@@ -3433,16 +3433,18 @@
Symbol%5B%5D
+%5B%5D
= encod
@@ -3531,22 +3531,91 @@
)%0A%0A%09
-return flatten
+const flattened: DiscreteSymbologySymbol%5B%5D = Array.prototype.concat.apply(%5B%5D, encod
edIn
@@ -3631,16 +3631,36 @@
parators
+)%0A%0A%09return flattened
%0A%7D%0A%0Aexpo
|
b8f9682fd532151fe421647caaf5a0d7c59d89dc | create user before system_user | controller/register.js | controller/register.js | "use strict";
/* eslint camelcase: 0 */
var clientData = require("../components").clientData;
var crypto = require("crypto");
var commons = require("./commons");
var config = require("../components").config;
var pusher = require("commons/pusher")(config.pusher);
var errors = require("./errors");
function sendVerifyEmail(user, systemUser) {
return pusher.sendEmail({
template: "confirm_email",
to: user.email,
from: config.email_from,
params: {
name: `${user.name.given} ${user.name.family}`,
verifyToken: systemUser.verify_token
}
})
.catch(error => {
throw new errors.SendEmailError(error.message);
});
}
exports.register = function(req) {
var email = req.params.email;
var password = req.params.password;
var firstName = req.params.first_name;
var lastName = req.params.last_name;
var dateOfBirth = req.params.date_of_birth;
if (!email) {
throw new errors.MissingParameter("email");
}
if (!password) {
throw new errors.MissingParameter("password");
}
if (!firstName) {
throw new errors.MissingParameter("first_name");
}
if (!lastName) {
throw new errors.MissingParameter("last_name");
}
if (!dateOfBirth) {
throw new errors.MissingParameter("date_of_birth");
}
var salt = crypto.randomBytes(64).toString("hex");
var passwordHash = commons.getPasswordHash(password, salt);
var verifyToken = crypto.randomBytes(44).toString("hex");
return Promise.resolve().then(() => {
return clientData.createObject({
object_type: "system_user",
salt,
password_hash: passwordHash
})
.then(systemUser =>
clientData.createObject({
object_type: "user",
name: {
given: firstName,
family: lastName
},
email: email,
date_of_birth: dateOfBirth,
system: systemUser.id
})
.then(user => {
verifyToken = user.id + "|" + verifyToken;
return clientData.updateObject(systemUser.id, {verify_token: verifyToken})
.then(systemUser => [user, systemUser]);
})
)
.then(res => {
var user = res[0];
var systemUser = res[1];
return sendVerifyEmail(user, systemUser)
.then(() => user);
})
.then(user => commons.createSession(user.id))
.then(session => ({type: "Bearer", token: session.token}));
});
};
| JavaScript | 0.000009 | @@ -1647,198 +1647,15 @@
e: %22
-system_
user%22,%0A
- salt,%0A password_hash: passwordHash%0A %7D)%0A .then(systemUser =%3E%0A clientData.createObject(%7B%0A object_type: %22user%22,%0A
@@ -1666,28 +1666,24 @@
name: %7B%0A
-
@@ -1720,20 +1720,16 @@
-
family:
@@ -1749,20 +1749,16 @@
-
%7D,%0A
@@ -1764,20 +1764,16 @@
-
email: e
@@ -1774,28 +1774,24 @@
ail: email,%0A
-
@@ -1816,17 +1816,16 @@
eOfBirth
-,
%0A
@@ -1829,37 +1829,105 @@
- system
+%7D).then(user =%3E%0A clientData.createObject(%7B%0A object_type
:
+%22
system
-User.id
+_user%22,
%0A
@@ -1927,34 +1927,41 @@
r%22,%0A
-%7D)
+ salt,
%0A .th
@@ -1961,23 +1961,40 @@
-.then(user =%3E %7B
+ password_hash: passwordHash,
%0A
@@ -2012,23 +2012,23 @@
verify
-T
+_t
oken
- =
+:
user.id
@@ -2047,17 +2047,16 @@
ifyToken
-;
%0A
@@ -2056,34 +2056,61 @@
- return
+%7D).then(systemUser =%3E%0A
clientData.
@@ -2122,23 +2122,17 @@
eObject(
-systemU
+u
ser.id,
@@ -2136,33 +2136,29 @@
d, %7B
-verify_token: verifyToken
+system: systemUser.id
%7D)%0A
@@ -2178,31 +2178,25 @@
.then(
-systemU
+u
ser =%3E %5Buser
@@ -2209,17 +2209,16 @@
emUser%5D)
-;
%0A
@@ -2214,33 +2214,32 @@
r%5D)%0A
-%7D
)%0A )%0A
|
4bb386d04af10f788d86aae1e587821029d01c82 | add missing semicolon | controllers/catalog.js | controllers/catalog.js | var _ = require("lodash");
var Catalog = require("../models/catalog");
/**
* 保存知乎日报列表至数据库。如果已存在,则更新。
* @param {Object} p_catalog 知乎日报列表。
* @param {Function(err, doc)} [p_callback]
*/
exports.saveCatalog = function (p_catalog, p_callback)
{
if (_.isEmpty(p_catalog) || !_.isObject(p_catalog))
{
if (_.isFunction(p_callback))
{
p_callback(new Error("p_catalog must be a non-empty Object."))
}
}
else
{
Catalog.findOneAndUpdate(
{ date: p_catalog.date },
p_catalog,
{ new: true, upsert: true },
p_callback
);
}
};
/**
* 从数据库中查找指定日期的知乎日报列表。
* @param {String} p_date 日期(知乎格式,例如:"20130519")。
* @param {Function(err, doc)} [p_callback]
*/
exports.findCatalogByDate = function (p_date, p_callback)
{
if (_.isFunction(p_callback))
{
Catalog.findOne({ date: p_date }, p_callback);
}
};
/**
* 从数据库中查找最近日期的知乎日报列表(缓存的最近日期)。
* @param {Function(err, doc)} [p_callback]
*/
exports.findLatestCatalog = function (p_callback)
{
if (_.isFunction(p_callback))
{
Catalog.findOne({}, {}, { sort: { "date": -1 } }, p_callback);
}
};
/**
* 从数据库中查找满足条件的记录。
* @param {Object} p_conditions 指定的查询条件。
* @param {Object} [p_projection]
* @param {Object} [p_options]
* @param {Function(err, docs)} [p_callback]
*/
exports.query = function (p_conditions, p_projection, p_options, p_callback)
{
Catalog.find(p_conditions, p_projection, p_options, p_callback);
};
| JavaScript | 0.999999 | @@ -437,16 +437,17 @@
ject.%22))
+;
%0D%0A
|
7908c7c2abc1da4a2ad3c6589204e63b29d4490c | fix status | controllers/default.js | controllers/default.js | var Mailgun = require('mailgun-js');
var models = require('../models');
//Your api key, from Mailgun’s Control Panel
var apiKey = process.env.MAILGUN_KEY;
//Your domain, from the Mailgun Control Panel
var domain = process.env.MAILGUN_DOMAIN;
var limit = 5;
module.exports = function(req, res) {
// find customer
models.customers.findById(req.params.id, function(err, customer) {
if (err) {
res.json({error:{message:err}});
}
else {
if (customer) {
var now = new Date();
// get count log by client_id, ip address and date
models.logs.count({
'client_id': req.params.id,
'ip': req.heroku.ip,
'created_at': {
$lte: now
}
}, function(err, count) {
if (err) {
res.json({error:{message:err}});
}
else if (count <= limit) {
var from = req.body.from;
var to = customer.to;
var subject = req.body.subject;
var message = req.body.message;
var mailgun = new Mailgun({apiKey: apiKey, domain: domain});
var data = {
from: from,
to: to,
subject: subject,
html: message
};
mailgun.messages().send(data, function(err, body) {
var log = new models.logs;
log.from = from;
log.subject = subject;
log.message = message;
log.status = (err) ? true : false;
log.ip = req.heroku.ip;
log.save(function(error) {
if (error) {
res.json({error:{message:error.message}});
}
else if (err) {
res.json({error:{message:err.message}});
}
else {
res.json({response:'Mensaje enviado'});
}
});
});
}
else {
res.json({error:{message:'No puedes enviar más de ' + limit + ' mensajes por día.'}});
}
});
}
else {
res.json({error:{message:'El usuario no existe'}});
}
}
});
};
| JavaScript | 0.000001 | @@ -1501,19 +1501,19 @@
) ?
-true : fals
+false : tru
e;%0A
|
55dc9dfe22fe67c7a3e0204b7515f263580f1aaf | Update gulpfile.js | test/gulpfile.js | test/gulpfile.js | /***************************** EXTERNAL IMPORTS ******************************/
var gulp = require('gulp');
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var babel = require('gulp-babel');
var gutil = require('gulp-util');
var Mocha = require('mocha');
/************************** GULP MODULE CONSTANTS ****************************/
var TMP_FOLDER = '.compiled-tests';
var LIB_SRC_FOLDER = 'src';
var LIB_FOLDER = 'lib';
/************************** GULP MODULE DEFINITION ***************************/
gulp.task('clean', function() {
rimraf.sync(path.join(__dirname, TMP_FOLDER));
rimraf.sync(path.join(__dirname, LIB_FOLDER));
});
gulp.task('compile:lib', function(done) {
gulp.src(path.join(__dirname, '..', LIB_SRC_FOLDER, '**', '*'))
.pipe(babel())
.pipe(gulp.dest(path.join(__dirname, '..', LIB_FOLDER)))
.on('end', function() {
done();
});
});
gulp.task('compile:tests', ['compile:lib'], function(done) {
gulp.src(path.join(__dirname, '*.test.js'))
.pipe(babel())
.pipe(gulp.dest(path.join(__dirname, TMP_FOLDER)))
.on('end', function() {
done();
});
});
gulp.task('test', ['compile:tests'], function(done) {
var mocha = new Mocha();
// Load the tests from the filesystem
fs.readdir(path.join(__dirname, TMP_FOLDER), function(err, files) {
if (err) {
done(err);
} else {
files.filter(function(file) {
return (file.indexOf('.test.js') === (file.length - 8));
}).forEach(function(testFile, i, testFiles) {
// Add the file to mocha context
mocha.addFile(path.join(__dirname, TMP_FOLDER, testFile));
gutil.log('Found test file:\t', gutil.colors.blue(testFile));
// Wait for the last last file to be loaded
if (i >= (testFiles.length - 1)) {
gutil.log('Now running the tests...');
// Run the mocha tests
mocha.run(function(failures) {
if (failures > 0) {
gutil.log(gutil.colors.red('✗ The tests didn\'t execute successfully.'));
process.exit(1);
} else {
gutil.log(gutil.colors.green('✓ All tests executed successfully!'));
}
// Finish up
done();
});
}
});
}
});
});
gulp.task('default', ['clean', 'test']);
| JavaScript | 0.000001 | @@ -2506,46 +2506,28 @@
-%7D%0A
- // Finish up
+process.exit(0);
%0A
@@ -2539,39 +2539,33 @@
-done();
+%7D
%0A
|
a2a7e2922f02ba661c765fd08bc0820472622c7b | Remove redundant code in script_config.js | Server/static/js/script_config.js | Server/static/js/script_config.js | var loadData;
$.getJSON("/api/config", function(data) {
loadData = data;
for (var key in data.config) {
if (key === "alerts") {
for (var keycode in data.config[key]) {
var sel = "#" + keycode + "";
$(sel).val(data.config[key][keycode]);
}
} else if (key === "arduino") {
for (var keycode in data.config[key]) {
var sel = "#" + keycode + "";
$(sel).val(data.config[key][keycode]);
}
} else if (key === "db") {
for (var keycode in data.config[key]) {
var sel = "#" + keycode + "";
$(sel).val(data.config[key][keycode]);
}
} else if (key === "forecast") {
for (var keycode in data.config[key]) {
var sel = "#" + keycode + "";
$(sel).val(data.config[key][keycode]);
}
}
}
});
$("#submit").on("click", function() {
for (var key in loadData.config) {
for (var keycode in loadData.config[key]) {
var sel = "#" + keycode + "";
var value = $(sel).val();
if(!isNaN(value)){
value = Number(value);
}
loadData.config[key][keycode] = value;
}
}
$.ajax({
type: "POST",
url: "/api/config",
data: JSON.stringify(loadData, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
}
});
});
| JavaScript | 0.001021 | @@ -106,38 +106,8 @@
) %7B%0A
- if (key === %22alerts%22) %7B%0A
@@ -138,34 +138,32 @@
.config%5Bkey%5D) %7B%0A
-
var sel =
@@ -180,34 +180,32 @@
ode + %22%22;%0A
-
$(sel).val(data.
@@ -231,537 +231,8 @@
%5D);%0A
- %7D%0A %7D else if (key === %22arduino%22) %7B%0A for (var keycode in data.config%5Bkey%5D) %7B%0A var sel = %22#%22 + keycode + %22%22;%0A $(sel).val(data.config%5Bkey%5D%5Bkeycode%5D);%0A %7D%0A %7D else if (key === %22db%22) %7B%0A for (var keycode in data.config%5Bkey%5D) %7B%0A var sel = %22#%22 + keycode + %22%22;%0A $(sel).val(data.config%5Bkey%5D%5Bkeycode%5D);%0A %7D%0A %7D else if (key === %22forecast%22) %7B%0A for (var keycode in data.config%5Bkey%5D) %7B%0A var sel = %22#%22 + keycode + %22%22;%0A $(sel).val(data.config%5Bkey%5D%5Bkeycode%5D);%0A %7D%0A
|
ccea2d9d33686dafdb210eb5c02f31c41314b9bb | clarify git checkout - tip | episodes/2015-12-30/index.js | episodes/2015-12-30/index.js | /* eslint max-len:0 */
export default {
title: `Functional and Immutable Design Patterns in JavaScript`,
guests: [
{
name: 'Dan Abramov',
twitter: 'dan_abramov',
imgSrc: '/resources/panelists/dan_abramov.png',
picks: [
`[A General Theory of Reactivity](https://github.com/kriskowal/gtor)`,
`[The Future of JavaScript MVC Frameworks](http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/)`,
`[Programming in the 21st Century] (http://prog21.dadgum.com/archives.html)`,
`[Redux Saga](https://github.com/yelouafi/redux-saga)`,
],
},
{
name: 'Brian Lonsdorf',
twitter: 'drboolean',
imgSrc: '/resources/panelists/drboolean.png',
links: [
`[A Modern Architecture for FP](http://degoes.net/articles/modern-fp/)`,
`[Crazy FP words tweet](https://twitter.com/drboolean/status/682059953708773377)`,
],
tips: [
`Watch [Dan's](https://twitter.com/dan_abramov) [Redux videos](https://egghead.io/series/getting-started-with-redux)`,
`Experiment with [ramda](http://ramdajs.com), [immutable.js](https://facebook.github.io/immutable-js/), and the Maybe Functor`,
`If you want to read the white papers, checkout [The Haskell Road to Logic, Maths and Programming](http://www.amazon.com/Haskell-Programming-Second-Edition-Computing/dp/0954300696)`,
],
picks: [
`[ForwardJS](http://forwardjs.com/) Feb 10th @Regency Ballroom SF`,
],
},
],
description: `
Functional programming have been greatly facilitated with ES6.
We're going to talk about the how and why of functional
programming and immutable design patterns in JavaScript.
`,
hangoutId: 'c6gcf8f0nirc5t83homjb5trquc',
youTubeId: '82M9fKe7hiw',
podbeanId: '',
past: true,
host: {
tips: ['Try a standing desk'],
picks: [
`[Lowes](http://www.lowes.com/)`,
`[The ES2016 Pipe Operator](https://github.com/mindeavor/es-pipeline-operator)`,
`[Learn JavaScript Arrays in Depth](https://egghead.io/playlists/learn-javascript-arrays-in-depth-dbe40331)`,
],
},
panelists: [
{
twitter: 'getify',
tips: [
`[Rediscover devtools in Firefox, you’ll be pleasantly surprised ](http://www.smashingmagazine.com/2015/12/revisiting-firefox-devtools/) -- specifically WebIDE/Valence and CSS Transforms Previewer`,
],
picks: [
`[JavaScript Allongé (book)](https://leanpub.com/javascriptallongesix) by [@raganwald](http://twitter.com/raganwald)`,
`Kris Jenkins’ blog posts on FP: [Part 1] (http://blog.jenkster.com/2015/12/what-is-functional-programming.html), [Part 2] (http://blog.jenkster.com/2015/12/which-programming-languages-are-functional.html)`,
`[The FP side of async programming](https://medium.com/@yelouafi/from-callback-to-future-functor-monad-6c86d9c16cb5)`,
`[Concurrency’s future on the web](https://medium.com/@cramforce/2016-will-be-the-year-of-concurrency-on-the-web-c39b1e99b30f)`,
],
},
{
twitter: 'linclark',
tips: [
`git checkout - takes you back to the branch you were last on`,
`[hub](https://github.com/github/hub) makes it easier to work with github on the command line. [Tab completion](https://github.com/github/hub#shell-tab-completion) is especially helpful`,
`[fetch all PRs](https://gist.github.com/piscisaureus/3342247) if you do a lot of PR reviews, this can be really helpful. It downloads all new PRs as branches whenever you fetch`,
],
picks: [
`[Jessica Kerr - Functional Principles In React](https://www.youtube.com/watch?v=1uRC3hmKQnM)`,
],
},
{
twitter: 'tylermcginnis33',
picks: [
`[Starters and Maintainers](http://jlongster.com/Starters-and-Maintainers)`,
`[Classroom Coding with Prof. Frisby](https://www.youtube.com/watch?v=h_tkIpwbsxY&list=PLK_hdtAJ4KqX0JOs_KMAmUNTNMRYhWEaC)`,
],
},
],
}
| JavaScript | 0.000004 | @@ -3112,16 +3112,70 @@
%60
+When running git checkout, using '-' as the argument (
git chec
@@ -3180,16 +3180,17 @@
eckout -
+)
takes y
|
1809efd0c6b2181e4e7e32d3c192ec83c2d2eb73 | Fix hidden property | controllers/regions.js | controllers/regions.js | 'use strict';
var mongoose = require('mongoose'),
Promise = require('bluebird'),
restifyErrors = require('restify-errors'),
rHandler = require('../lib/util/response-handlers'),
CommonController = require('./common');
class RegionsController extends CommonController {
constructor() {
super();
this.coroutines.findResource.main = Promise.coroutine(function* (req, res, next, config) {
let limit = parseInt(req.query.limit || 0),
skip = parseInt(req.query.skip || 0),
lat = req.params.lat || req.query.lat,
lon = req.params.lon || req.query.lon,
isAdmin = req.api_key && req.api_key.scopes && (
req.api_key.scopes.indexOf("admin") > -1 ||
req.api_key.scopes.indexOf("region-" + req.params.uuid) > -1
);
if (lat && lon) {
let q = mongoose.model("Region").where("lonlat");
q.near({
center: {coordinates: [lon, lat], type: 'Point'}
});
q = config.select ? q.select(config.select) : q;
if (req.query.sort) {
q = q.sort(req.query.sort);
}
if (req.query.limit) {
q = q.limit(limit);
}
if (req.query.skip) {
q = q.skip(skip);
}
let data = {page: Math.floor(skip / limit), pagesize: limit};
data.results = yield q.exec();
data.total = yield mongoose.model(config.resource).count(q._conditions);
rHandler.handleDataResponse(data, 200, res, next);
} else {
var results = yield mongoose.model("Location").mapReduce({
map: function () {
if (!this.hide) {
emit(this.region_uuid, 1); // jshint ignore:line
}
},
reduce: function (k, v) {
return Array.sum(v);
}
});
var output = [];
yield Promise.map(results, function (item) {
var hideParamter = isAdmin ? {uuid: item._id} : {uuid: item._id, hide:false};
return mongoose.model("Region").findOne(hideParamter)
.then(function (region) {
if (region) {
var out = region.toObject();
out.locations = item.value;
output.push(out);
}
});
}, {concurrency: 1});
if (req.query.sort) {
// function lifted from http://stackoverflow.com/a/4760279/578963
// FIXME: and apparently is not working too well...?
output.sort(function sortOn(property) {
var sortOrder = 1;
if (req.query.sort[0] === "-") {
sortOrder = -1;
req.query.sort = req.query.sort.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
};
});
}
let total = output.length,
data = {page: Math.floor(skip / limit), pagesize: limit};
data.total = total;
data.results = output.slice(skip, limit || total);
rHandler.handleDataResponse(data, 200, res, next);
}
});
this.coroutines.getResource.main = Promise.coroutine(function* (req, res, next, config) {
let isAdmin = req.api_key && req.api_key.scopes && (
req.api_key.scopes.indexOf("admin") > -1 ||
req.api_key.scopes.indexOf("region-" + req.params.uuid) > -1
);
let query = {$or: [{uuid: req.params.uuid}, {slug: req.params.uuid.toLowerCase()}]};
if(!isAdmin) {
query = {$and: [{hide: false}, {$or: [{uuid: req.params.uuid}, {slug: req.params.uuid.toLowerCase()}]}]};
}
let q = mongoose.model(config.resource).findOne(query);
q = config.select ? q.select(config.select) : q;
let result = yield q.exec();
if (!result) {
return rHandler.handleErrorResponse(new restifyErrors.NotFoundError(), res, next);
}
result = result.toObject();
rHandler.handleDataResponse(result, 200, res, next);
});
}
}
module.exports = RegionsController;
| JavaScript | 0.000001 | @@ -1904,17 +1904,19 @@
this.hid
-e
+den
) %7B%0A
|
32dc3e221e364daf0e1638747857590aad1fc302 | bump darn version in about -.- | sample/src/about/about.js | sample/src/about/about.js | export class About {
actors = [
{
'name': 'Bryan Cranston',
'episodes': 62,
'description': 'Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle.',
'image': 'bryan-cranston.jpg'
}, {
'name': 'Aaron Paul',
'episodes': 62,
'description': 'Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie.',
'image': 'aaron-paul.jpg'
}, {
'name': 'Bob Odenkirk',
'episodes': 62,
'description': 'Bob Odenkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul".',
'image': 'bob-odenkirk.jpg'
}
];
attached() {
// let bridge = System.get(System.normalizeSync('aurelia-materialize-bridge'));
// this.version = bridge.version;
this.version = '0.20.6';
}
onSelectionChanged(e) {
let selected = this.list.getSelected();
let names = selected.map(i => i.name);
this.logger.log('selection changed: ' + names.join(', '));
// this.logger.log(`selection changed ${e.detail.item.name}`);
}
}
| JavaScript | 0 | @@ -928,11 +928,11 @@
'0.2
-0.6
+1.0
';%0A
|
b93498d6269e44357e3f56b4f29e1a49a39bca1c | increase version | sample/src/about/about.js | sample/src/about/about.js | export class About {
actors = [
{
'name': 'Bryan Cranston',
'episodes': 62,
'description': 'Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle.',
'image': 'bryan-cranston.jpg'
}, {
'name': 'Aaron Paul',
'episodes': 62,
'description': 'Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie.',
'image': 'aaron-paul.jpg'
}, {
'name': 'Bob Odenkirk',
'episodes': 62,
'description': 'Bob Odenkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul".',
'image': 'bob-odenkirk.jpg'
}
];
attached() {
// let bridge = System.get(System.normalizeSync('aurelia-materialize-bridge'));
// this.version = bridge.version;
this.version = '0.6.1';
}
onSelectionChanged(e) {
let selected = this.list.getSelected();
let names = selected.map(i => i.name);
this.logger.log('selection changed: ' + names.join(', '));
// this.logger.log(`selection changed ${e.detail.item.name}`);
}
}
| JavaScript | 0.000004 | @@ -929,9 +929,9 @@
0.6.
-1
+2
';%0A
|
08dd7bb6d7afefe443a0919ef636ae633722f14e | Modify typo | walk-in-interview/src/main/webapp/account/log-in/applicant/script.js | walk-in-interview/src/main/webapp/account/log-in/applicant/script.js | /**
* This file is specific to log-in/applicant/index.html.
* It renders the fields on the page dynamically.
*/
// TODO(issue/21): get the language from the browser
const CurrentLocale = 'en';
/**
* Import statements are static so its parameters cannot be dynamic.
* TODO(issue/22): figure out how to use dynamic imports
*/
import {AppStrings} from '../../../strings.en.js';
import {Auth} from '../../firebase-auth.js';
import {setErrorMessage} from '../../../common-functions.js';
const COMMONG_STRINGS = AppStrings['log-in'];
const STRINGS = AppStrings['applicant-log-in'];
const LOGIN_HOMEPAGE_PATH = '../index.html';
const HOMEPAGE_PATH = '../../../index.html';
window.onload = () => {
renderPageElements();
};
/** Adds all the text to the fields on this page. */
function renderPageElements() {
Auth.signIntoBusinessAccount('phone-auth', HOMEPAGE_PATH, STRINGS['new-user-info'])
.catch((error) => {
setErrorMessage(/* errorMessageElementId= */'error-message',
/* msg= */ COMMONG_STRINGS['error-message'],
/* includesDefault= */false);
console.error(error.message);
// Back to home page
window.location.href = HOMEPAGE_PATH;
});
const backButton = document.getElementById('back');
backButton.innerText = COMMONG_STRINGS['back'];
}
const backButton = document.getElementById('back');
backButton.addEventListener('click', (_) => {
window.location.href = LOGIN_HOMEPAGE_PATH;
});
| JavaScript | 0.00155 | @@ -825,16 +825,17 @@
Into
-Business
+Applicant
Acco
|
9abe6ef083eb82fe8ae139480c75b02893c7f767 | Add an example of a compound conditional statement with && | examples/composit_statements.js | examples/composit_statements.js | import Local
import Global
"Global.x:" <input data=Global.x dataType="number" style={ display:'block' }/>
"Global.y:" <input data=Global.y dataType="number" style={ display:'block' }/>
let five = 5,
two = 2,
greeting = "hello ",
name = "world"
<table>
<tr>
<th>"Global.x + Global.y"</th>
Global.x + Global.y
</tr><tr>
<th>"Global.x * Global.y + Global.x * five"</th>
Global.x * Global.y + Global.x * five
</tr><tr>
<th>"five + 2 * Global.x"</th>
five + 2 * Global.x
</tr><tr>
<th>"two - 3 / Global.y"</th>
two - 3 / Global.y
</tr><tr>
<th>"greeting + name"</th>
greeting + name
</tr>
</table>
<br />"Numbers: "
<input data=Local.x dataType="number" /> "+" <input data=Local.y dataType="number" /> "=" Local.x + Local.y
<br />"Strings: "
<input data=Local.foo /> "+" <input data=Local.bar /> "=" Local.foo + Local.bar
if (Global.x < 10) {
<br />"Global.x < 10"
}
if (Global.x * Global.y > 100) {
<br />"Global.x * Global.y > 100"
} else {
<br />"Global.x * Global.y <= 100"
}
if (Global.x * Global.y + Global.x * five > 200) {
<br />"Global.x * Global.y + Global.x * five > 200"
}
| JavaScript | 0.999918 | @@ -19,16 +19,29 @@
t Global
+%0Aimport Mouse
%0A%0A%22Globa
@@ -1124,12 +1124,86 @@
ve %3E 200%22%0A%7D%0A
+%0Aif (Mouse.x %3E 100 && Mouse.y %3E 100) %7B%0A%09%22Mouse.x %3E 100 && Mouse.y %3E 100%22%0A%7D
|
118cf4edec9a96ee3cf7927070f3145fe9ce9897 | Modify encoding for URL fragment so Firefox doesn't decode it automatically | zephyr/static/js/hashchange.js | zephyr/static/js/hashchange.js | var hashchange = (function () {
var exports = {};
var expected_hash = false;
exports.changehash = function (newhash) {
expected_hash = newhash;
// Some browsers reset scrollTop when changing the hash to "",
// so we save and restore it.
// http://stackoverflow.com/questions/4715073/window-location-hash-prevent-scrolling-to-the-top
var scrolltop = viewport.scrollTop();
window.location.hash = newhash;
util.reset_favicon();
if (newhash === "" || newhash === "#") {
viewport.scrollTop(scrolltop);
}
};
exports.save_narrow = function (operators) {
if (operators === undefined) {
exports.changehash('#');
} else {
var new_hash = '#narrow';
$.each(operators, function (idx, elem) {
new_hash += '/' + encodeURIComponent(elem[0])
+ '/' + encodeURIComponent(elem[1]);
});
exports.changehash(new_hash);
}
};
function parse_narrow(hash) {
var i, operators = [];
for (i=1; i<hash.length; i+=2) {
// We don't construct URLs with an odd number of components,
// but the user might write one.
var operator = decodeURIComponent(hash[i]);
var operand = decodeURIComponent(hash[i+1] || '');
operators.push([operator, operand]);
}
var new_selection;
if (current_msg_list.selected_id() !== -1) {
new_selection = current_msg_list.selected_id();
} else {
new_selection = initial_pointer;
}
narrow.activate(operators, {
then_select_id: new_selection,
change_hash: false // already set
});
}
// Returns true if this function performed a narrow
function hashchanged() {
// If window.location.hash changed because our app explicitly
// changed it, then we don't need to do anything.
// (This function only neds to jump into action if it changed
// because e.g. the back button was pressed by the user)
if (window.location.hash === expected_hash) {
return false;
}
var hash = window.location.hash.split("/");
switch (hash[0]) {
case "#narrow":
ui.change_tab_to("#home");
parse_narrow(hash);
ui.update_floating_recipient_bar();
return true;
case "":
case "#":
ui.change_tab_to("#home");
narrow.deactivate();
ui.update_floating_recipient_bar();
break;
case "#subscriptions":
ui.change_tab_to("#subscriptions");
break;
case "#settings":
ui.change_tab_to("#settings");
break;
}
return false;
}
exports.initialize = function () {
window.onhashchange = hashchanged;
if (hashchanged()) {
load_more_messages(current_msg_list);
}
};
return exports;
}());
| JavaScript | 0 | @@ -73,16 +73,398 @@
false;%0A%0A
+// Some browsers zealously URI-decode the contents of%0A// window.location.hash. So we hide our URI-encoding%0A// by replacing %25 with . (like MediaWiki).%0A%0Afunction encodeHashComponent(str) %7B%0A return encodeURIComponent(str)%0A .replace(/%5C./g, '%252E')%0A .replace(/%25/g, '.');%0A%7D%0A%0Afunction decodeHashComponent(str) %7B%0A return decodeURIComponent(str.replace(/%5C./g, '%25'));%0A%7D%0A%0A
exports.
@@ -1162,35 +1162,36 @@
+= '/' + encode
-URI
+Hash
Component(elem%5B0
@@ -1225,27 +1225,28 @@
'/' + encode
-URI
+Hash
Component(el
@@ -1538,35 +1538,36 @@
perator = decode
-URI
+Hash
Component(hash%5Bi
@@ -1595,27 +1595,28 @@
nd = decode
-URI
+Hash
Component(ha
@@ -2402,16 +2402,160 @@
%0A %7D%0A%0A
+ // NB: In Firefox, window.location.hash is URI-decoded.%0A // Even if the URL bar says #%2541%2542%2543%2544, the value here will%0A // be #ABCD.%0A
var
|
c7f555cf5e830238acf9c8b9bd9bdc652ce93595 | remove pageable mixin | imports/pages/music/index.js | imports/pages/music/index.js | import { Component, PropTypes } from "react";
import ReactMixin from "react-mixin";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import ApollosPullToRefresh from "../../components/pullToRefresh";
import { FeedItemSkeleton } from "../../components/loading";
import FeedItem from "../../components/cards/cards.FeedItem";
import Headerable from "../../mixins/mixins.Header";
import Pageable from "../../mixins/mixins.Pageable";
import infiniteScroll from "../../decorators/infiniteScroll";
import { nav as navActions } from "../../store";
import Album from "./music.Album";
const ALBUMS_QUERY = gql`
query getAlbums($limit: Int!, $skip: Int!) {
content(channel: "newspring_albums", limit: $limit, skip: $skip) {
id
entryId: id
title
status
channelName
meta {
urlTitle
siteId
date
channelId
}
content {
images(sizes: ["large"]) {
fileName
fileType
fileLabel
url
}
tracks {
file: s3
}
}
}
}
`;
const withAlbums = graphql(ALBUMS_QUERY, {
options: { variables: { limit: 20, skip: 0 } },
props: ({ data }) => ({
data,
loading: data.loading,
fetchMore: () => data.fetchMore({
variables: { ...data.variables, skip: data.content.length },
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult.data) return previousResult;
return { content: [...previousResult.content, ...fetchMoreResult.data.content] };
},
}),
}),
});
const mapStateToProps = state => ({ paging: state.paging });
@connect(mapStateToProps)
@withAlbums
@infiniteScroll()
@ReactMixin.decorate(Pageable)
@ReactMixin.decorate(Headerable)
class Template extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
data: PropTypes.object.isRequired,
}
componentWillMount() {
this.props.dispatch(navActions.setLevel("TOP"));
this.headerAction({ title: "All Music" });
}
handleRefresh = (resolve, reject) => {
this.props.data.refetch()
.then(resolve)
.catch(reject);
}
renderItems = () => {
const { content } = this.props.data;
let loading = true;
let items = [1, 2, 3, 4, 5];
if (content) {
loading = false;
items = _.filter(content, item => (
_.any(item.content.tracks, track => !!track.file)
));
}
return items.map((item, i) => (
<div
className={
"grid__item one-half@palm-wide one-third@portable one-quarter@anchored " +
"flush-bottom@handheld push-bottom@portable push-bottom@anchored"
}
key={i}
>
{(() => {
if (loading) return <FeedItemSkeleton />;
return <FeedItem item={item} />;
})()}
</div>
));
}
render() {
return (
<ApollosPullToRefresh handleRefresh={this.handleRefresh}>
<div className="background--light-secondary">
<section className="soft-half">
<div className="grid">
{this.renderItems()}
</div>
</section>
</div>
</ApollosPullToRefresh>
);
}
}
const Routes = [
{ path: "music", component: Template },
{ path: "music/:id", component: Album },
];
export default {
Template,
Routes,
};
| JavaScript | 0 | @@ -436,61 +436,8 @@
r%22;%0A
-import Pageable from %22../../mixins/mixins.Pageable%22;%0A
impo
@@ -1701,39 +1701,8 @@
l()%0A
-@ReactMixin.decorate(Pageable)%0A
@Rea
|
7c623274ce8292518c07b7e59e1dd55ba6b44ddc | Remove .highlightClass | angular/app.js | angular/app.js | var app = angular.module('testApp', ['ngMaterial']);
// Config
app.config(function ($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('green')
.accentPalette('purple');
console.info('Successfully initialized!');
});
app.controller('MainController', function ($scope, $mdSidenav, $mdDialog, $mdToast) {
$scope.openLeftMenu = function () {
$mdSidenav('left').toggle();
};
$scope.oriFeedback = {
name: "",
email: "",
sendFeedback: ""
};
// Declare a variable called oriFeedback
var oriFeedback = angular.copy($scope.oriFeedback);
// On initial, set feedback to original
$scope.feedback = angular.copy(oriFeedback);
// Reset form
$scope.reset = function () {
$scope.feedback = angular.copy(oriFeedback);
// Reset form
$scope.feedbackbeta.$setPristine();
// Reset validation errors
$scope.feedbackbeta.$setUntouched();
};
// Feedback Form ($mdToast)
var last = {
bottom: false,
top: true,
left: false,
right: true
};
$scope.toastPosition = angular.extend({}, last);
$scope.getToastPosition = function () {
sanitizePosition();
return Object.keys($scope.toastPosition)
.filter(function (pos) { return $scope.toastPosition[pos]; })
.join(' ');
};
function sanitizePosition() {
var current = $scope.toastPosition;
if (current.bottom && last.top) current.top = false;
if (current.top && last.bottom) current.bottom = false;
if (current.right && last.left) current.left = false;
if (current.left && last.right) current.right = false;
last = angular.extend({}, current);
}
$scope.submitForm = function() {
var pinTo = $scope.getToastPosition();
var toast = $mdToast.simple()
.textContent('Form submitted')
.action('UNDO')
.highlightAction(true)
.highlightClass('md-accent')// Accent is used by default, this just demonstrates the usage.
.position(pinTo);
$mdToast.show(toast).then(function(response) {
if ( response == 'ok' ) {
console.info('User clicked Undo.');
}
});
};
$scope.resetForm = function() {
var pinTo = $scope.getToastPosition();
var toast = $mdToast.simple()
.textContent('Form reset')
.action('UNDO')
.highlightAction(true)
.highlightClass('md-accent')// Accent is used by default, this just demonstrates the usage.
.position(pinTo);
$mdToast.show(toast).then(function(response) {
if ( response == 'ok' ) {
alert('You clicked the \'UNDO\' action.');
console.info('User clicked Undo.');
}
});
};
// More menu
var originatorEv;
$scope.openMenu = function ($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
// Initialize switches
$scope.switch = {
form_debug: false,
};
// $mdDialog (start)
$scope.whats_new = function (ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'whats_new_tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
});
};
$scope.settings = function (ev) {
$mdDialog.show({
controller: DialogController,
teplateUrl: 'settings_tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
});
};
// $mdDialog (end)
$scope.about_site = function () {
window.location.href = "https://chan4077.github.io/about#angular";
};
function DialogController($scope, $mdDialog) {
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
};
});
app.controller('SideNavController', function ($scope) {
$scope.top = [
{ url: 'https://chan4077.github.io', title: 'Main', icon: 'home', class: 'material-icons' },
{ url: 'https://chan4077.github.io/about', title: 'About Me', icon: 'account_box', class: 'material-icons' },
{ url: 'https://chan4077.github.io/blog', title: 'Blog', icon: '', class: '' },
{ url: 'https://chan4077.github.io/media', title: 'Social Media', icon: 'group', class: 'material-icons' },
{ url: 'https://chan4077.github.io/angular', title: 'Angular', icon: '' },
];
$scope.other = [
{ url: 'https://github.com/Chan4077/chan4077.github.io', title: 'Project Page', icon: '' },
{ url: 'https://chan4077.github.io/preferences', title: 'Preferences', icon: 'settings', class: 'material-icons' },
{ url: '', title: 'Submit Feedback', icon: 'feedback' },
{ url: '', title: 'Get Help', icon: 'help' }
]
}); | JavaScript | 0.000002 | @@ -1979,106 +1979,8 @@
ue)%0A
- .highlightClass('md-accent')// Accent is used by default, this just demonstrates the usage.%0A
@@ -1991,32 +1991,32 @@
osition(pinTo);%0A
+
%0A $mdToast.sh
@@ -2119,32 +2119,76 @@
licked Undo.');%0A
+ console.log('Successfully undone');%0A
%7D%0A %7D);%0A
@@ -2390,106 +2390,8 @@
ue)%0A
- .highlightClass('md-accent')// Accent is used by default, this just demonstrates the usage.%0A
@@ -2506,46 +2506,39 @@
-alert('You clicked the %5C'UNDO%5C' action
+console.info('User clicked Undo
.');
@@ -2558,32 +2558,32 @@
ole.
-info('User clicked Undo.
+log('Successfully undone
');%0A
|
c0116c40aef744d06edfba7a5525f5e1957cb2ff | update shell reference extensions | packages/remark-lint-no-shell-dollars/index.js | packages/remark-lint-no-shell-dollars/index.js | /**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module no-shell-dollars
* @fileoverview
* Warn when shell code is prefixed by `$` (dollar sign) characters.
*
* Ignores indented code blocks and fenced code blocks without language flag.
*
* @example {"name": "valid.md"}
*
* ```sh
* echo a
* echo a > file
* ```
*
* ```zsh
* $ echo a
* a
* $ echo a > file
* ```
*
* Some empty code:
*
* ```command
* ```
*
* It’s fine to use dollars in non-shell code.
*
* ```js
* $('div').remove();
* ```
*
* @example {"name": "invalid.md", "label": "input"}
*
* ```bash
* $ echo a
* $ echo a > file
* ```
*
* @example {"name": "invalid.md", "label": "output"}
*
* 1:1-4:4: Do not use dollar signs before shell-commands
*/
'use strict'
var rule = require('unified-lint-rule')
var visit = require('unist-util-visit')
var generated = require('unist-util-generated')
module.exports = rule('remark-lint:no-shell-dollars', noShellDollars)
var reason = 'Do not use dollar signs before shell-commands'
// List of shell script file extensions (also used as code flags for syntax
// highlighting on GitHub):
// See: <https://github.com/github/linguist/blob/5bf8cf5/lib/linguist/languages.yml#L3002>
var flags = [
'sh',
'bash',
'bats',
'cgi',
'command',
'fcgi',
'ksh',
'tmux',
'tool',
'zsh'
]
function noShellDollars(tree, file) {
visit(tree, 'code', visitor)
function visitor(node) {
var lines
var line
var length
var index
// Check both known shell code and unknown code.
if (!generated(node) && node.lang && flags.indexOf(node.lang) !== -1) {
lines = node.value.split('\n')
length = lines.length
index = -1
if (length <= 1) {
return
}
while (++index < length) {
line = lines[index]
if (line.trim() && !line.match(/^\s*\$\s*/)) {
return
}
}
file.message(reason, node)
}
}
}
| JavaScript | 0.000019 | @@ -1250,15 +1250,15 @@
lob/
-5bf8cf5
+001ca52
/lib
@@ -1286,10 +1286,10 @@
ml#L
-30
+47
02%3E%0A
|
6ba6527ef705b120b8095f2ffe55fb2de73219bb | fix jsdoc tag, no functional change | lib/OpenLayers/Filter/FeatureId.js | lib/OpenLayers/Filter/FeatureId.js | /* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Filter.js
*/
/**
* Class: OpenLayers.Filter.FeatureId
* This class represents a ogc:FeatureId Filter, as being used for rule-based SLD
* styling
*
* Inherits from
* - <OpenLayers.Filter>
*/
OpenLayers.Filter.FeatureId = OpenLayers.Class(OpenLayers.Filter, {
/**
* APIProperty: fids
* {Array(String)} Feature Ids to evaluate this rule against. To be passed
* To be passed inside the params object.
*/
fids: null,
/**
* Property: type
* {String} Type to identify this filter.
*/
type: "FID",
/**
* Constructor: OpenLayers.Filter.FeatureId
* Creates an ogc:FeatureId rule.
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* rule
*
* Returns:
* {<OpenLayers.Filter.FeatureId>}
*/
initialize: function(options) {
this.fids = [];
OpenLayers.Filter.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: evaluate
* evaluates this rule for a specific feature
*
* Parameters:
* feature - {<OpenLayers.Feature>} feature to apply the rule to.
* For vector features, the check is run against the fid,
* for plain features against the id.
*
* Returns:
* {Boolean} true if the rule applies, false if it does not
*/
evaluate: function(feature) {
for (var i=0, len=this.fids.length; i<len; i++) {
var fid = feature.fid || feature.id;
if (fid == this.fids[i]) {
return true;
}
}
return false;
},
/**
* APIMethod: clone
* Clones this filter.
*
* Returns:
* {<OpenLayers.Filter.FeatureId>} Clone of this filter.
*/
clone: function() {
var filter = new OpenLayers.Filter.FeatureId();
OpenLayers.Util.extend(filter, this);
filter.fids = this.fids.slice();
return filter;
},
CLASS_NAME: "OpenLayers.Filter.FeatureId"
});
| JavaScript | 0.000002 | @@ -646,27 +646,19 @@
st.
-To be passed
%0A *
+
To
|
318ee5df7dcf95d925e76124344ca613f01cb6f6 | Move timestamp updating to an exported function for testing purposes | zephyr/static/js/timerender.js | zephyr/static/js/timerender.js | var timerender = (function () {
var exports = {};
// If this is 5, then times from up to 5 days before the current
// day will be formatted as weekday names:
//
// 1/10 1/11 1/12
// Sun Mon Tue Wed Thu 1/18 1/19
// ^ today
var MAX_AGE_FOR_WEEKDAY = 5;
var next_timerender_id = 0;
var set_to_start_of_day = function (time) {
return time.setMilliseconds(0).setSeconds(0).setMinutes(0).setHours(0);
};
function now() { return (new XDate()); }
// Given an XDate object 'time', return a two-element list containing
// - a string for the current human-formatted version
// - a string like "2013-01-20" representing the day the format
// needs to change, or undefined if it will never need to change.
function render_now(time) {
var start_of_today = set_to_start_of_day(now());
var start_of_other_day = set_to_start_of_day(time.clone());
// How many days old is 'time'? 0 = today, 1 = yesterday, 7 = a
// week ago, -1 = tomorrow, etc.
// Presumably the result of diffDays will be an integer in this
// case, but round it to be sure before comparing to integer
// constants.
var days_old = Math.round(start_of_other_day.diffDays(start_of_today));
if (days_old >= 0 && days_old <= MAX_AGE_FOR_WEEKDAY)
// "\xa0" is U+00A0 NO-BREAK SPACE.
// Can't use as that represents the literal string " ".
return [time.toString("ddd") + "\xa0" + time.toString("HH:mm"),
start_of_other_day.addDays(MAX_AGE_FOR_WEEKDAY+1)
.toString("yyyy-MM-dd")];
else {
// For now, if we get a message from tomorrow, we don't bother
// rewriting the timestamp when it gets to be tomorrow.
return [time.toString("MMM dd") + "\xa0\xa0" + time.toString("HH:mm"),
undefined];
}
}
// This table associates to each day (represented as a yyyy-MM-dd
// string) a list of timestamps that need to be updated on that day.
// Each timestamp is represented as a list of length 2:
// [id of the span element, XDate representing the time]
// This is an efficient data structure because we only need to update
// timestamps at the start of each day. If timestamp update times were
// arbitrary, a priority queue would be more sensible.
var update_table = {};
// The day that elements are currently up-to-date with respect to.
// Represented as an XDate with hour, minute, second, millisecond 0.
var last_updated = set_to_start_of_day(now());
function maybe_add_update_table_entry(update_date, id, time) {
if (update_date === undefined)
return;
if (update_table[update_date] === undefined)
update_table[update_date] = [];
update_table[update_date].push([id, time]);
}
// Given an XDate object 'time', return a DOM node that initially
// displays the human-formatted time, and is updated automatically as
// necessary (e.g. changing "Mon 11:21" to "Jan 14 11:21" after a week
// or so).
// (What's actually spliced into the message template is the contents
// of this DOM node as HTML, so effectively a copy of the node. That's
// okay since to update the time later we look up the node by its id.)
exports.render_time = function (time) {
var id = "timerender" + next_timerender_id;
next_timerender_id++;
var rendered_now = render_now(time);
var node = $("<span />").attr('id', id).text(rendered_now[0]);
maybe_add_update_table_entry(rendered_now[1], id, time);
return node;
};
setInterval(function () {
var start_of_today = set_to_start_of_day(now());
var new_date;
// This loop won't do anything unless the day changed since the
// last time it ran.
for (new_date = last_updated.clone().addDays(1);
new_date <= start_of_today;
new_date.addDays(1)) {
var update_date = new_date.toString("yyyy-MM-dd");
if (update_table[update_date] !== undefined)
{
var to_process = update_table[update_date];
var i;
update_table[update_date] = [];
$.each(to_process, function (idx, elem) {
var id = elem[0];
var element = document.getElementById(id);
// The element might not exist any more (because it
// was in the zfilt table, or because we added
// messages above it and re-collapsed).
if (element !== null) {
var time = elem[1];
var new_rendered = render_now(time);
$(document.getElementById(id)).text(new_rendered[0]);
maybe_add_update_table_entry(new_rendered[1], id, time);
}
});
}
}
last_updated = start_of_today;
}, 60 * 1000);
return exports;
}());
| JavaScript | 0 | @@ -3498,20 +3498,124 @@
%7D;%0A%0A
-setInterval(
+// This isn't expected to be called externally except manually for%0A// testing purposes.%0Aexports.update_timestamps =
func
@@ -4860,16 +4860,56 @@
today;%0A%7D
+;%0A%0AsetInterval(exports.update_timestamps
, 60 * 1
|
eedbdb6ddcd8b0d9b48a1cf3fd04f80a6dae0fbb | Fix caret position after image update | wcfsetup/install/files/js/3rdParty/redactor2/plugins/WoltLabImage.js | wcfsetup/install/files/js/3rdParty/redactor2/plugins/WoltLabImage.js | $.Redactor.prototype.WoltLabImage = function() {
"use strict";
return {
init: function() {
var button = this.button.add('woltlabImage', '');
this.button.addCallback(button, this.WoltLabImage.add);
// add support for image source when editing
var mpShowEdit = this.image.showEdit;
this.image.showEdit = (function($image) {
var image = $image[0];
if (image.classList.contains('smiley')) {
// smilies cannot be edited
return;
}
mpShowEdit($image);
// enforce title and button labels
this.modal.setTitle(WCF.Language.get('wcf.editor.image.edit'));
this.modal.getActionButton().text(WCF.Language.get('wcf.global.button.save'));
this.modal.getDeleteButton().text(WCF.Language.get('wcf.global.button.delete'));
elById('redactor-image-source').value = image.src;
var float = elById('redactor-image-float');
if (image.classList.contains('messageFloatObjectLeft')) float.value = 'left';
else if (image.classList.contains('messageFloatObjectRight')) float.value = 'right';
// hide source if image is an attachment
if (image.classList.contains('woltlabAttachment')) {
elRemove(elById('redactor-image-source-container'));
}
}).bind(this);
var mpUpdate = this.image.update;
this.image.update = (function() {
var image = this.observe.image[0];
var sourceInput = elById('redactor-image-source');
var showError = function(inputElement, message) {
$('<small class="innerError" />').text(message).insertAfter(inputElement);
};
if (!image.classList.contains('woltlabAttachment')) {
// check if source is valid
var source = sourceInput.value.trim();
if (source === '') {
return showError(sourceInput, WCF.Language.get('wcf.global.form.error.empty'));
}
else if (!source.match(this.opts.regexps.url)) {
return showError(sourceInput, WCF.Language.get('wcf.editor.image.source.error.invalid'));
}
// update image source
image.src = source;
}
// remove old float classes
image.classList.remove('messageFloatObjectLeft');
image.classList.remove('messageFloatObjectRight');
// set float behavior
var float = elById('redactor-image-float').value;
if (float === 'left' || float === 'right') {
image.classList.add('messageFloatObject' + WCF.String.ucfirst(float));
}
mpUpdate();
// remove alt/title attribute again (not supported)
image.removeAttribute('alt');
image.removeAttribute('title');
}).bind(this);
// overwrite modal template
this.opts.modal['image-edit'] = '<div class="section">'
+ '<dl id="redactor-image-source-container">'
+ '<dt><label for="redactor-image-source">' + WCF.Language.get('wcf.editor.image.source') + '</label></dt>'
+ '<dd><input type="text" id="redactor-image-source" class="long"></dd>'
+ '</dl>'
+ '<dl>'
+ '<dt><label for="redactor-image-link">' + WCF.Language.get('wcf.editor.image.link') + '</label></dt>'
+ '<dd><input type="text" id="redactor-image-link" class="long"></dd>'
+ '</dl>'
+ '<dl>'
+ '<dt><label for="redactor-image-float">' + WCF.Language.get('wcf.editor.image.float') + '</label></dt>'
+ '<dd>'
+ '<select id="redactor-image-float">'
+ '<option value="none">' + WCF.Language.get('wcf.global.noSelection') + '</option>'
+ '<option value="left">' + WCF.Language.get('wcf.editor.image.float.left') + '</option>'
+ '<option value="right">' + WCF.Language.get('wcf.editor.image.float.right') + '</option>'
+ '</select>'
+ '</dd>'
+ '</dl>'
+ '<input id="redactor-image-title" style="display: none">' /* dummy because redactor expects it to be present */
+ '<input id="redactor-image-caption" style="display: none">' /* dummy because redactor expects it to be present */
+ '<div class="formSubmit">'
+ '<button id="redactor-modal-button-action" class="buttonPrimary">Insert</button>'
+ '<button id="redactor-modal-button-delete" class="redactor-modal-button-offset">Delete</button>'
+ '</div>'
+ '</div>';
},
add: function() {
this.modal.load('image-edit', WCF.Language.get('wcf.editor.image.insert'));
this.modal.show();
this.modal.getDeleteButton().hide();
var button = this.modal.getActionButton()[0];
button.addEventListener(WCF_CLICK_EVENT, this.WoltLabImage.insert);
button.textContent = WCF.Language.get('wcf.global.button.insert');
this.WoltLabModal.rebuild();
},
insert: function(event) {
event.preventDefault();
// remove any existing error messages first
this.modal.getModal().find('.innerError').remove();
var sourceInput = elById('redactor-image-source');
var showError = function(inputElement, message) {
$('<small class="innerError" />').text(message).insertAfter(inputElement);
};
// check if source is valid
var source = sourceInput.value.trim();
if (source === '') {
return showError(sourceInput, WCF.Language.get('wcf.global.form.error.empty'));
}
else if (!source.match(this.opts.regexps.url)) {
return showError(sourceInput, WCF.Language.get('wcf.editor.image.source.error.invalid'));
}
// check if link is valid
var linkInput = elById('redactor-image-link');
var link = linkInput.value.trim();
if (link !== '' && !link.match(this.opts.regexps.url)) {
return showError(linkInput, WCF.Language.get('wcf.editor.image.link.error.invalid'));
}
var float = elById('redactor-image-float').value, className = '';
if (float === 'left' || float === 'right') {
className = 'messageFloatObject' + WCF.String.ucfirst(float);
}
var html = '<img src="' + WCF.String.escapeHTML(source) + '"' + (className ? ' class="' + className + '"' : '') + '>';
if (link) {
html = '<a href="' + WCF.String.escapeHTML(link) + '">' + html + '</a>';
}
this.modal.close();
this.buffer.set();
this.insert.html(html);
}
};
}; | JavaScript | 0 | @@ -2425,17 +2425,26 @@
mpUpdate
-(
+.call(this
);%0A%09%09%09%09%0A
@@ -2569,16 +2569,50 @@
itle');%0A
+%09%09%09%09%0A%09%09%09%09this.caret.after(image);%0A
%09%09%09%7D).bi
|
3041dbb5a06a57b5e1e197dae1652dd5cc6748b4 | Fix applyDefaults objects mutation | core/services/build.js | core/services/build.js | 'use strict';
const { eachSeries } = require('async');
const { get, assignWith, cloneDeep, isNil } = require('lodash');
module.exports = (callCIDriver, localConfig) => {
return (branch, jobs, deployConfig, cb) => {
const ciJobsConfig = deployConfig.ciJobs;
const ciServicesConfig = deployConfig.ciServices;
eachSeries(jobs, (job, nextJob) => {
// TODO: ensure we check for ci jobs, services and drivers references in the preview step
const ciJobConfig = get(ciJobsConfig, job.name);
if (!ciJobConfig) return nextJob();
const settings = combineSettings(ciJobConfig.ciService, ciServicesConfig, localConfig);
const params = combineParams(job, ciJobConfig, branch);
callCIDriver(ciJobConfig.ciService, settings, params, nextJob);
// TODO: return job execution result
}, cb);
}
function combineSettings(ciService, ciServicesConfig, localConfig) {
const repoSettings = get(ciServicesConfig, `${ciService}.settings`);
const localSettings = get(localConfig, `deploy.ciServices.${ciService}.settings`);
const settings = applyDefaults(repoSettings, localSettings);
return settings;
}
function combineParams(job, ciJobConfig, branch) {
// TODO: combine default params with monorail config
const params = applyDefaults(job.params, ciJobConfig.defaultParams);
if (ciJobConfig.servicesParam) {
params[ciJobConfig.servicesParam.paramName] = job.deployTo.join(ciJobConfig.servicesParam.separator);
}
if (ciJobConfig.sourceVersionParam) {
params[ciJobConfig.sourceVersionParam.paramName] = branch;
}
return params
}
function applyDefaults(originalObj, defaultObj) {
const finalObj = cloneDeep(originalObj);
return assignWith(defaultObj, finalObj, (defaultProp, originalProp) => {
return isNil(originalProp) ? defaultProp : originalProp;
});
}
}
| JavaScript | 0 | @@ -1715,24 +1715,23 @@
oneDeep(
-original
+default
Obj);%0A
@@ -1754,21 +1754,22 @@
ith(
-default
+final
Obj,
-f
+orig
inal
|
a4d572343628113192da7104412b30ffeee0eceb | Set default values | src/angular-punchchart.js | src/angular-punchchart.js | (function () {
'use strict';
var module = angular.module('pygmalios.punchchart', []);
module.directive('punchChart', ['$window', function($window) {
var getMaxValue = function(data) {
var max = 1;
data.forEach(function(xValues){
xValues.forEach(function(value){
if (max < value) {
max = value;
}
});
});
return max;
};
return {
restrict: 'EA',
scope: {
chartData: '=',
xlabels: '=',
ylabels: '=',
options: '='
},
template: '<svg width="100%" height="100%" viewBox="0 0 800 300" preserveAspectRatio="xMaxYMax"></svg>',
link: function(scope, elem, attrs){
var VIEWPORT_WIDTH = 800;
var VIEWPORT_HEIGHT = 300;
var PADDING_TOP = 10;
var LABEL_LEFT = 30;
var LABEL_BOTTOM = 30;
var LINE_SIZE_X = 30;
var LINE_SIZE_Y = 30;
var MAX_RADIUS = 12;
var PUNCT_COLOR;
var LABEL_COLOR;
var LINE_COLOR;
var FONT_SIZE;
var FONT_WEIGHT;
var d3 = $window.d3;
var rawSvg = elem.find('svg');
var svg = d3.select(rawSvg[0]);
var maxValue;
var valueScaleFactor;
var yAxisLength;
var xAxisLength;
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0]);
svg.call(tip);
var init = function() {
maxValue = getMaxValue(scope.chartData);
yAxisLength = scope.chartData.length;
xAxisLength = scope.chartData[0] ? scope.chartData[0].length : 1;
LINE_SIZE_Y = (VIEWPORT_HEIGHT - PADDING_TOP - LABEL_BOTTOM) / (scope.ylabels.length + 1);
LINE_SIZE_X = (VIEWPORT_WIDTH - LABEL_BOTTOM) / (scope.xlabels.length + 1);
MAX_RADIUS = LINE_SIZE_X < LINE_SIZE_Y ? Math.floor(LINE_SIZE_X * 9 / 20) : Math.floor(LINE_SIZE_Y * 9 / 20);
valueScaleFactor = maxValue / MAX_RADIUS;
scope.options = scope.options || {};
PUNCT_COLOR = scope.options.PUNCT_COLOR || '#62BFCE';
LABEL_COLOR = scope.options.LABEL_COLOR || '#7F7F7F';
LINE_COLOR = scope.options.LINE_COLOR || '#D0D0D0';
FONT_SIZE = scope.options.FONT_SIZE || 10;
FONT_WEIGHT = scope.options.FONT_WEIGHT || 100;
};
var drawLabels = function() {
for (var y=0; y<scope.ylabels.length; y++) {
svg.append('svg:text')
.attr('class', 'ylabel')
.attr('x', LABEL_LEFT)
.attr('y', (y + 1) * LINE_SIZE_Y + PADDING_TOP)
.attr('dy', '0.25em')
.attr('text-anchor', 'end')
.style('font-family', 'Helvetica')
.style('font-size', FONT_SIZE)
.style('font-weight', FONT_WEIGHT)
.style('fill', LABEL_COLOR)
.text(scope.ylabels[y]);
svg.append('svg:line')
.attr('class', 'line')
.attr('x1', (1) * LABEL_LEFT + 0.25 * LABEL_LEFT)
.attr('y1', (y + 1) * LINE_SIZE_Y + PADDING_TOP)
.attr('x2', (1 + scope.xlabels.length) * LINE_SIZE_X + 0.75 * LINE_SIZE_X)
.attr('y2', (y + 1) * LINE_SIZE_Y + PADDING_TOP)
.style('stroke', LINE_COLOR)
.style('stroke-width', 0.5);
}
for (var x=0; x<scope.xlabels.length; x++) {
svg.append('svg:text')
.attr('class', 'xlabel')
.attr('x', (x + 1) * LINE_SIZE_X + LABEL_LEFT)
.attr('y', (scope.ylabels.length + 1) * LINE_SIZE_Y + PADDING_TOP)
.attr('text-anchor', 'middle')
.style('font-family', 'Helvetica')
.style('font-size', FONT_SIZE)
.style('font-weight', FONT_WEIGHT)
.style('fill', LABEL_COLOR)
.text(scope.xlabels[x]);
svg.append('svg:line')
.attr('class', 'line')
.attr('x1', (x + 1) * LINE_SIZE_X + LABEL_LEFT)
.attr('y1', (1) * LINE_SIZE_Y + PADDING_TOP - 0.75 * LINE_SIZE_Y)
.attr('x2', (x + 1) * LINE_SIZE_X + LABEL_LEFT)
.attr('y2', (1 + scope.ylabels.length) * LINE_SIZE_Y + PADDING_TOP - 0.25 * LINE_SIZE_Y)
.style('stroke', LINE_COLOR)
.style('stroke-width', 0.5);
}
};
var drawContent = function() {
for (var y=0; y<yAxisLength && y<scope.ylabels.length; y++) {
for (var x=0; x<xAxisLength && x<scope.xlabels.length; x++) {
svg.append('svg:circle')
.attr('class', 'circle')
.attr('cx', (x + 1) * LINE_SIZE_X + LABEL_LEFT)
.attr('cy', (y + 1) * LINE_SIZE_Y + PADDING_TOP)
.attr('r', scope.chartData[y][x] / valueScaleFactor)
.attr('data', scope.chartData[y][x])
.attr('fill', PUNCT_COLOR)
.on('mouseover', function(){
tip.html(d3.select(this).attr('data'));
tip.show();
})
.on('mouseout', tip.hide);
}
}
};
var redraw = function() {
svg.selectAll('*').remove();
init();
drawLabels();
drawContent();
};
scope.$watch('chartData', function(value, old) {
if (value !== old) {
redraw();
}
});
scope.$watch('xlabels', function(value, old) {
if (value !== old) {
redraw();
}
});
scope.$watch('ylabels', function(value, old) {
if (value !== old) {
redraw();
}
});
scope.$watch('options', function(value, old) {
if (value !== old) {
redraw();
}
});
redraw();
}
};
}]);
})(); | JavaScript | 0.000005 | @@ -202,17 +202,17 @@
r max =
-1
+0
;%0A
@@ -1592,32 +1592,90 @@
= function() %7B%0A
+ scope.chartData = scope.chartData %7C%7C %5B%5D;%0A%0A
@@ -1849,17 +1849,17 @@
ength :
-1
+0
;%0A%0A
@@ -2213,16 +2213,17 @@
actor =
+(
maxValue
@@ -2235,16 +2235,22 @@
X_RADIUS
+) %7C%7C 1
;%0A%0A
|
20e893379ea14283bb9c1fa058b358f3e8981cbc | fix babel-jest config? | scripts/utils/babelTransform.js | scripts/utils/babelTransform.js | const babelJest = require('babel-jest');
const config = require('../../config/webpack.defaults.js');
module.exports = babelJest.createTransformer({
passPerPreset: true,
presets: [
'babel-preset-react',
'babel-preset-env',
'babel-preset-stage-0',
],
plugins: [
'babel-plugin-transform-runtime',
],
});
| JavaScript | 0 | @@ -259,16 +259,37 @@
-0',%0A %5D
+.map(require.resolve)
,%0A plug
@@ -336,14 +336,35 @@
me',%0A %5D
+.map(require.resolve)
,%0A%7D);%0A
|
b8fe9f8e9124c73a0cad9932c368b89d591905e8 | Update flow.js | examples/listen_to_this/flow.js | examples/listen_to_this/flow.js | const datafire = require('datafire');
const flow = module.exports = new datafire.Flow("Create a Spotify playlist from r/listenToThis", "Create a new playlist every day using suggestions from Reddit");
const spotify = datafire.Integration.new('spotify').as('default');
const reddit = datafire.Integration.new('reddit');
flow.step('spotify', {
do: spotify.get("/me"),
params: (data) => {
return {}
}
})
flow.step('reddit', {
do: reddit.subreddit(),
params: () => {
return {subreddit: 'listentothis'}
}
})
flow.step('spotify1', {
do: spotify.get("/search"),
params: (data) => {
var tracks = data.reddit.feed.entries.slice(0, 10);
return tracks.map(function(entry) {
return {
type: "track",
q: entry.title.replace(/\[.*\]/g, '').replace(/\(.*\)/g, ''),
}
})
}
})
flow.step('spotify2', {
do: spotify.post("/users/{user_id}/playlists"),
params: (data) => {
return {
user_id: data.spotify.id,
body: {
name: "r/listentothis for " + new Date().toISOString().slice(0,10),
}
}
}
})
flow.step('spotify3', {
do: spotify.post("/users/{user_id}/playlists/{playlist_id}/tracks"),
params: (data) => {
return {
user_id: data.spotify.id,
playlist_id: data.spotify2.id,
uris: data.spotify1.filter(function(searchResults) {
return searchResults.tracks.items.length;
}).map(function(searchResults) {
return searchResults.tracks.items[0].uri;
})
.join(',')
}
}
})
| JavaScript | 0.000001 | @@ -331,21 +331,26 @@
'spotify
+_user
', %7B%0A
-
do: sp
@@ -535,24 +535,22 @@
w.step('
-spotify1
+tracks
', %7B%0A d
@@ -844,24 +844,28 @@
w.step('
-spotify2
+add_playlist
', %7B%0A d
@@ -965,32 +965,37 @@
id: data.spotify
+_user
.id,%0A body:
@@ -1110,16 +1110,18 @@
ep('
-spotify3
+add_tracks
', %7B
@@ -1254,16 +1254,21 @@
.spotify
+_user
.id,%0A
@@ -1292,16 +1292,20 @@
ata.
-spotify2
+add_playlist
.id,
@@ -1326,16 +1326,14 @@
ata.
-spotify1
+tracks
.fil
|
3240bad466fb157ad539fb9a2ef8868cd04f0c28 | Fix layouts to use leaf counts if no value field is provided. (#1863) | packages/vega-hierarchy/src/HierarchyLayout.js | packages/vega-hierarchy/src/HierarchyLayout.js | import {Transform} from 'vega-dataflow';
import {error, inherits, one} from 'vega-util';
/**
* Abstract class for tree layout.
* @constructor
* @param {object} params - The parameters for this operator.
*/
export default function HierarchyLayout(params) {
Transform.call(this, null, params);
}
var prototype = inherits(HierarchyLayout, Transform);
prototype.transform = function(_, pulse) {
if (!pulse.source || !pulse.source.root) {
error(this.constructor.name
+ ' transform requires a backing tree data source.');
}
var layout = this.layout(_.method),
fields = this.fields,
root = pulse.source.root,
as = _.as || fields;
if (_.field) root.sum(_.field);
if (_.sort) root.sort(_.sort);
setParams(layout, this.params, _);
if (layout.separation) {
layout.separation(_.separation !== false ? defaultSeparation : one);
}
try {
this.value = layout(root);
} catch (err) {
error(err);
}
root.each(function(node) { setFields(node, fields, as); });
return pulse.reflow(_.modified()).modifies(as).modifies('leaf');
};
function setParams(layout, params, _) {
for (var p, i=0, n=params.length; i<n; ++i) {
p = params[i];
if (p in _) layout[p](_[p]);
}
}
function setFields(node, fields, as) {
var t = node.data;
for (var i=0, n=fields.length-1; i<n; ++i) {
t[as[i]] = node[fields[i]];
}
t[as[n]] = node.children ? node.children.length : 0;
}
function defaultSeparation(a, b) {
return a.parent === b.parent ? 1 : 2;
}
| JavaScript | 0 | @@ -694,16 +694,35 @@
.field);
+ else root.count();
%0A if (_
|
0182ca7d4668f62ef2d3f52a2a1096a919a9e870 | Add viewNodeMetadataURL helper. | src/api/user/urlHelper.js | src/api/user/urlHelper.js | import "user";
import "../node/urlHelper";
import "../../config/config";
import "../../util/util";
sn.api.user.registerUrlHelperFunction = sn_api_user_registerUrlHelperFunction;
var sn_api_user_urlHelperFunctions;
function sn_api_user_baseURL(urlHelper) {
return (urlHelper.hostURL()
+(sn.config && sn.config.solarUserPath ? sn.config.solarUserPath : '/solaruser')
+'/api/v1/sec');
}
/**
* An active user-specific URL utility object. This object does not require
* any specific user ID to be configured, as all requests are assumed to apply
* to the active user credentials.
*
* @class
* @constructor
* @param {Object} configuration The configuration options to use.
* @returns {sn.api.user.userUrlHelper}
* @preserve
*/
sn.api.user.userUrlHelper = function(configuration) {
var self = {
version : '1.0.0'
};
var config = sn.util.copy(configuration, {
host : 'data.solarnetwork.net',
tls : true,
path : '/solaruser',
secureQuery : true
});
/**
* Get a URL for just the SolarNet host, without any path.
*
* @returns {String} the URL to the SolarNet host
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function hostURL() {
return ('http' +(config.tls === true ? 's' : '') +'://' +config.host);
}
/**
* Get a URL for the SolarNet host and the base API path, e.g. <code>/solaruser/api/v1/sec</code>.
*
* @returns {String} the URL to the SolarUser base API path
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function baseURL() {
return (hostURL() +config.path +'/api/v1/' +(config.secureQuery === true ? 'sec' : 'pub'));
}
/**
* Get a description of this helper object.
*
* @return {String} The description of this object.
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function keyDescription() {
return 'user';
}
/**
* Generate a SolarUser {@code /nodes} URL.
*
* @return {String} the URL to access the active user's nodes
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function viewNodesURL() {
var url = (baseURL() + '/nodes');
return url;
}
// setup core properties
Object.defineProperties(self, {
keyDescription : { value : keyDescription },
hostURL : { value : hostURL },
baseURL : { value : baseURL },
viewNodesURL : { value : viewNodesURL }
});
// allow plug-ins to supply URL helper methods, as long as they don't override built-in ones
(function() {
if ( Array.isArray(sn_api_user_urlHelperFunctions) ) {
sn_api_user_urlHelperFunctions.forEach(function(helper) {
if ( self.hasOwnProperty(helper.name) === false ) {
Object.defineProperty(self, helper.name, { value : function() {
return helper.func.apply(self, arguments);
} });
}
});
}
}());
return self;
};
/**
* Register a custom function to generate URLs with {@link sn.api.user.userUrlHelper}.
*
* @param {String} name The name to give the custom function. By convention the function
* names should end with 'URL'.
* @param {Function} func The function to add to sn.api.user.userUrlHelper instances.
* @preserve
*/
function sn_api_user_registerUrlHelperFunction(name, func) {
if ( typeof func !== 'function' ) {
return;
}
if ( sn_api_user_urlHelperFunctions === undefined ) {
sn_api_user_urlHelperFunctions = [];
}
name = name.replace(/[^0-9a-zA-Z_]/, '');
sn_api_user_urlHelperFunctions.push({name : name, func : func});
}
/*
* Node URL helper functions
*/
sn_api_node_registerUrlHelperFunction('viewInstruction', sn_api_user_viewInstruction);
sn_api_node_registerUrlHelperFunction('viewActiveInstructionsURL', sn_api_user_viewActiveInstructionsURL);
sn_api_node_registerUrlHelperFunction('viewPendingInstructionsURL', sn_api_user_viewPendingInstructionsURL);
sn_api_node_registerUrlHelperFunction('updateInstructionStateURL', sn_api_user_updateInstructionStateURL);
sn_api_node_registerUrlHelperFunction('queueInstructionURL', sn_api_user_queueInstructionURL);
function sn_api_user_viewInstruction(instructionID) {
return (sn_api_user_baseURL(this) +'/instr/view?id=' +encodeURIComponent(instructionID));
}
function sn_api_user_viewActiveInstructionsURL() {
return (sn_api_user_baseURL(this) +'/instr/viewActive?nodeId=' +this.nodeId);
}
function sn_api_user_viewPendingInstructionsURL() {
return (sn_api_user_baseURL(this) +'/instr/viewPending?nodeId=' +this.nodeId);
}
function sn_api_user_updateInstructionStateURL(instructionID, state) {
return (sn_api_user_baseURL(this)
+'/instr/updateState?id=' +encodeURIComponent(instructionID)
+'&state=' +encodeURIComponent(state));
}
/**
* Generate a URL for posting an instruction request.
*
* @param {String} topic - The instruction topic.
* @param {Array} parameters - An array of parameter objects in the form <code>{name:n1, value:v1}</code>.
* @preserve
*/
function sn_api_user_queueInstructionURL(topic, parameters) {
var url = (sn_api_user_baseURL(this)
+'/instr/add?nodeId=' +this.nodeId
+'&topic=' +encodeURIComponent(topic));
if ( Array.isArray(parameters) ) {
var i, len;
for ( i = 0, len = parameters.length; i < len; i++ ) {
url += '&' +encodeURIComponent('parameters['+i+'].name') +'=' +encodeURIComponent(parameters[i].name)
+ '&' +encodeURIComponent('parameters['+i+'].value') +'=' +encodeURIComponent(parameters[i].value);
}
}
return url;
}
| JavaScript | 0 | @@ -5350,12 +5350,388 @@
turn url;%0A%7D%0A
+%0Asn_api_node_registerUrlHelperFunction('viewNodeMetadataURL', sn_api_user_viewNodeMetadataURL);%0A%0A/**%0A * Generate a URL for viewing the configured node's metadata.%0A *%0A * The configured %3Ccode%3EnodeId%3C/code%3E property will be used.%0A *%0A * @returns %7BString%7D the URL%0A */%0Afunction sn_api_user_viewNodeMetadataURL() %7B%0A%09return (sn_api_user_baseURL(this) +'/nodes/meta/' +this.nodeId);%0A%7D%0A
|
e3448b42aceb1874c86bb2a973a9d82622fe9373 | add two reported phishing url's | src/app/utils/Phishing.js | src/app/utils/Phishing.js | const domains = [
'steewit.com',
'śteemit.com',
'ŝteemit.com',
'şteemit.com',
'šteemit.com',
'sţeemit.com',
'sťeemit.com',
'șteemit.com',
'sleemit.com',
'aba.ae',
'autobidbot.cf',
'autobidbot.ga',
'autobidbot.gq',
'autobotsteem.cf',
'autobotsteem.ga',
'autobotsteem.gq',
'autobotsteem.ml',
'autosteem.info',
'autosteembot.cf',
'autosteembot.ga',
'autosteembot.gq',
'autosteembot.ml',
'autosteemit.wapka.mobi',
'boostbot.ga',
'boostbot.gq',
'boostwhaleup.cf',
'cutt.us',
'dereferer.me',
'eb2a.com',
'lordlinkers.tk',
'nullrefer.com',
'steeemit.ml',
'steeemitt.aba.ae',
'steemart.ga',
'steemautobot.bid',
'steemautobot.cf',
'steemautobot.trade',
'steemers.aba.ae',
'steemiit.cf',
'steemiit.ga',
'steemij.tk',
'steemik.ga',
'steemik.tk',
'steemil.com',
'steemil.ml',
'steemir.tk',
'steemitou.co.nf',
'steemitservices.ga',
'steemitservices.gq',
'steemiz.tk',
'steemnow.cf',
'steemnow.ga',
'steemnow.gq',
'steemnow.ml',
'steempostupper.win',
'steemrewards.ml',
'steemrobot.ga',
'steemrobot.ml',
'steemupgot.cf',
'steemupgot.ga',
'steemupgot.gq',
'steemupper.cf',
'steemupper.ga',
'steemupper.gq',
'steemupper.ml',
'steenit.cf',
'stemit.com',
'stssmater.aba.ae',
'uppervotes.ga',
'uppervotes.gq',
'upperwhaleplus.cf',
'upperwhaleplus.ga',
'upperwhaleplus.gq',
'upvoteme.cf',
'upvoteme.ga',
'upvoteme.gq',
'upvoteme.ml',
'url.rw',
'us.aba.ae',
'whaleboostup.ga',
'whaleboostup.ml',
];
/**
* Does this URL look like a phishing attempt?
*
* @param {string} questionableUrl
* @returns {boolean}
*/
export const looksPhishy = questionableUrl => {
for (let domain of domains) {
if (questionableUrl.toLocaleLowerCase().indexOf(domain) > -1)
return true;
}
return false;
};
| JavaScript | 0.000007 | @@ -1692,16 +1692,67 @@
up.ml',%0A
+ 'steemboostup.icu',%0A 'proservices.website',%0A
%5D;%0A%0A/**%0A
|
1425017a46d83a7263cf110d04ce4723930e7d7b | Exit with code 1 when got errored tasks | bin/gulp.js | bin/gulp.js | #!/usr/bin/env node
var path = require('path');
var argv = require('optimist').argv;
var completion = require('../lib/completion');
if (argv.completion) { return completion(argv.completion); }
var resolve = require('resolve');
var findup = require('findup-sync');
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
var tasks = argv._;
var cliPkg = require('../package.json');
var localBaseDir = process.cwd();
loadRequires(argv.require, localBaseDir);
var gulpFile = getGulpFile(localBaseDir);
// find the local gulp
var localGulp = findLocalGulp(gulpFile);
var localPkg = findLocalGulpPackage(gulpFile);
// print some versions and shit
if (argv.v || argv.version) {
gutil.log('CLI version', cliPkg.version);
if (localGulp) {
gutil.log('Local version', localPkg.version);
}
process.exit(0);
}
if (!localGulp) {
gutil.log(gutil.colors.red('No local gulp install found in'), getLocalBase(gulpFile));
gutil.log(gutil.colors.red('You need to npm install it first'));
process.exit(1);
}
if (!gulpFile) {
gutil.log(gutil.colors.red('No Gulpfile found'));
process.exit(1);
}
// Wire up logging for tasks
// on local gulp singleton
logEvents(localGulp);
// Load their gulpfile and run it
gutil.log('Using file', gutil.colors.magenta(gulpFile));
loadGulpFile(localGulp, gulpFile, tasks);
function loadRequires(requires, baseDir) {
if (typeof requires === 'undefined') requires = [];
if (!Array.isArray(requires)) requires = [requires];
return requires.map(function(modName){
gutil.log('Requiring external module', gutil.colors.magenta(modName));
var mod = findLocalModule(modName, baseDir);
if (typeof mod === 'undefined') {
gutil.log('Failed to load external module', gutil.colors.magenta(modName));
}
});
}
function getLocalBase(gulpFile) {
return path.resolve(path.dirname(gulpFile));
}
function findLocalGulp(gulpFile){
var baseDir = getLocalBase(gulpFile);
return findLocalModule('gulp', baseDir);
}
function findLocalModule(modName, baseDir){
try {
return require(resolve.sync(modName, {basedir: baseDir}));
} catch(e) {}
return;
}
function findLocalGulpPackage(gulpFile){
var baseDir = getLocalBase(gulpFile);
var packageBase;
try {
packageBase = path.dirname(resolve.sync('gulp', {basedir: baseDir}));
return require(path.join(packageBase, 'package.json'));
} catch(e) {}
return;
}
function loadGulpFile(localGulp, gulpFile, tasks){
var gulpFileCwd = path.dirname(gulpFile);
process.chdir(gulpFileCwd);
gutil.log('Working directory changed to', gutil.colors.magenta(gulpFileCwd));
var theGulpfile = require(gulpFile);
// just for good measure
process.nextTick(function(){
localGulp.run.apply(localGulp, tasks);
});
return theGulpfile;
}
function getGulpFile(baseDir) {
var extensions;
if (require.extensions) {
extensions = Object.keys(require.extensions).join(',');
} else {
extensions = ['.js','.coffee'];
}
var gulpFile = findup('Gulpfile{'+extensions+'}', {nocase: true});
return gulpFile;
}
// format orchestrator errors
function formatError (e) {
if (!e.err) return e.message;
if (e.err.message) return e.err.message;
return JSON.stringify(e.err);
}
// wire up logging events
function logEvents(gulp) {
gulp.on('task_start', function(e){
gutil.log('Running', "'"+gutil.colors.cyan(e.task)+"'...");
});
gulp.on('task_stop', function(e){
var time = prettyTime(e.hrDuration);
gutil.log('Finished', "'"+gutil.colors.cyan(e.task)+"'", 'in', gutil.colors.magenta(time));
});
gulp.on('task_err', function(e){
var msg = formatError(e);
var time = prettyTime(e.hrDuration);
gutil.log('Errored', "'"+gutil.colors.cyan(e.task)+"'", 'in', gutil.colors.magenta(time), gutil.colors.red(msg));
});
gulp.on('task_not_found', function(err){
gutil.log(gutil.colors.red("Task '"+err.task+"' was not defined in your gulpfile but you tried to run it."));
gutil.log('Please check the documentation for proper gulpfile formatting.');
process.exit(1);
});
}
| JavaScript | 0 | @@ -2712,16 +2712,158 @@
tion()%7B%0A
+ if (typeof tasks%5Btasks.length%5D !== 'function') %7B%0A tasks.push(function(err) %7B%0A if (err) %7B process.exit(1); %7D%0A %7D);%0A %7D%0A
loca
|
fd9f3661afd4f8d2d0fedf8aff390d87c5d9af33 | add variable discovery functions | bin/unit.js | bin/unit.js | var make = exports.make = function(obj) {
var stream = '';
var cmd;
var i;
for(i in obj) {
cmd = obj[i].command.split(' ')[0];
if(exports[cmd] && cmd !== 'make') {
stream += exports[cmd](obj[i], function(children) {
var s = '';
var j;
if(children !== null) {
for(j in children) {
s += this.variables(children[j]);
}
}
s += this.make(children);
return s;
}.bind(this));
}
}
return stream;
};
exports.variables = function(obj) {
var s = '';
var i;
var rx = /\{([^}]+)\}/gim;
var matches;
while((matches = rx.exec(obj.command)) !== null) {
s += 'var ' + matches[1] + ';\n\n';
}
return s;
};
exports.describe = function(obj, cb) {
var s;
s = 'describe(\'' + obj.command + '\', function() {\n\n';
s += cb(obj.children);
s += '});\n\n';
return s;
};
exports.it = function(obj, cb) {
var s;
s = 'it(\'' + obj.command + '\', function() {\n\n';
s += cb(obj.children);
s += '});\n\n';
return s;
};
// describe(obj, function(children) {
// var s = '';
// var i;
// s += make(children);
// return s;
// }); | JavaScript | 0.000001 | @@ -1,12 +1,44 @@
+var _ = require('underscore');%0A%0A
var make = e
@@ -489,17 +489,20 @@
exports.
-v
+getV
ariables
@@ -524,29 +524,8 @@
) %7B%0A
-%09var s = '';%0A%09var i;%0A
%09var
@@ -548,10 +548,8 @@
%5C%7D/g
-im
;%0A%09v
@@ -556,18 +556,30 @@
ar match
-es
+, matches = %5B%5D
;%0A%0A%09whil
@@ -586,18 +586,16 @@
e((match
-es
= rx.ex
@@ -623,16 +623,237 @@
null) %7B%0A
+%09%09matches.push(match%5B1%5D);%0A%09%7D%0A%0A%09return matches;%0A%7D;%0A%0Aexports.variables = function(obj) %7B%0A%09var s = '';%0A%09var i;%0A%0A%09var variables = this.getVariables(obj);%0A%09variables = _.unique(variables);%0A%0A%09for(i = variables.length; i--; ) %7B%0A
%09%09s += '
@@ -864,17 +864,19 @@
' +
-matches%5B1
+variables%5Bi
%5D +
@@ -1215,16 +1215,436 @@
s;%0A%7D;%0A%0A
+exports.require = function(obj, cb) %7B%0A%09var s;%0A%09var i;%0A%09var variables = this.getVariables(obj);%0A%09if(variables.length !== 2) %7B%0A%09%09s = 'var ' + variables%5B0%5D + ' = require(%5C'' + variables%5B1%5D + '%5C');';%0A%09%7D%0A%09else if(variables.length === 1) %7B%0A%09%09s = 'var ' + variables%5B0%5D + ' = require(%5C'' + variables%5B0%5D + '%5C');';%0A%09%7D%0A%09else %7B%0A%09%09throw 'Require statement for ' + obj.command + ' must have one or two variables.';%0A%09%7D%0A%0A%09return s;%0A%7D;%0A%0A
%0A%0A// des
|
423b21f12c735d70f976ad656080a65571f5c3a2 | fix create user bug introduced during flow refactor | lib/admin/components/CreateUser.js | lib/admin/components/CreateUser.js | // @flow
import Icon from '@conveyal/woonerf/components/icon'
import React, {Component} from 'react'
import {Button, Modal, FormControl, ControlLabel, FormGroup} from 'react-bootstrap'
import UserSettings from './UserSettings'
import UserPermissions from '../../common/user/UserPermissions'
import {getComponentMessages, getMessage} from '../../common/util/config'
import type {UserState} from '../../manager/reducers/user'
import type {Organization, Project} from '../../types'
type Props = {
createUser: ({email: string, password: string, permissions: UserPermissions}) => void,
fetchProjectFeeds: string => void,
projects: Array<Project>,
creatingUser: UserState,
organizations: Array<Organization>
}
type State = {
email: string,
password: string,
showModal: boolean
}
export default class CreateUser extends Component<Props, State> {
state = {
email: '',
password: '',
showModal: false
}
save = (e: any) => {
e.preventDefault()
if (!e.target.checkValidity()) {
console.warn('Form inputs are invalid!')
return
}
this.setState({showModal: false})
const {email, password} = this.state
this.props.createUser({
email,
password,
permissions: this.refs.userSettings.getSettings()
})
}
cancel () {
this.setState({
showModal: false
})
}
open = () => {
this.setState({
showModal: true
})
}
render () {
const messages = getComponentMessages('CreateUser')
const {
creatingUser,
organizations,
projects,
fetchProjectFeeds
} = this.props
return (
<div>
<Button
bsStyle='primary'
onClick={this.open}
className='pull-right'>
<Icon type='plus' />{' '}
Create User
</Button>
<Modal show={this.state.showModal} onHide={this.cancel.bind(this)}>
<Modal.Header closeButton>
<Modal.Title>Create User</Modal.Title>
</Modal.Header>
<form onSubmit={this.save}>
<Modal.Body>
<FormGroup controlId='formControlsEmail'>
<ControlLabel>Email Address</ControlLabel>
<FormControl
ref='email'
autoFocus
value={this.state.email}
autoComplete='username email'
type='email'
placeholder='Enter email' />
</FormGroup>
<FormGroup controlId='formControlsPassword'>
<ControlLabel>Password</ControlLabel>
<FormControl
ref='password'
value={this.state.password}
minLength='8'
type='password'
placeholder='Enter password for new user'
autoComplete='new-password' />
</FormGroup>
<UserSettings
projects={projects}
organizations={organizations}
fetchProjectFeeds={fetchProjectFeeds}
creatingUser={creatingUser}
permissions={new UserPermissions()}
isCreating
ref='userSettings' />
</Modal.Body>
<Modal.Footer>
<Button type='submit'>{getMessage(messages, 'new')}</Button>
</Modal.Footer>
</form>
</Modal>
</div>
)
}
}
| JavaScript | 0.000002 | @@ -788,16 +788,91 @@
lean%0A%7D%0A%0A
+const DEFAULT_STATE = %7B%0A email: '',%0A password: '',%0A showModal: false%0A%7D%0A%0A
export d
@@ -943,85 +943,73 @@
e =
-%7B%0A email: '',%0A password: '',%0A showModal: false%0A %7D%0A%0A save = (e: any
+DEFAULT_STATE%0A%0A save = (e: SyntheticInputEvent%3CHTMLInputElement%3E
) =%3E
@@ -1141,46 +1141,8 @@
%7D%0A
- this.setState(%7BshowModal: false%7D)%0A
@@ -1304,72 +1304,165 @@
)%0A
-%7D%0A%0A cancel () %7B%0A this.setState(%7B%0A showModal: false%0A
+ this.setState(DEFAULT_STATE)%0A %7D%0A%0A _updateField = (evt: SyntheticInputEvent%3CHTMLInputElement%3E) =%3E %7B%0A this.setState(%7B%5Bevt.target.name%5D: evt.target.value
%7D)%0A
@@ -1471,20 +1471,22 @@
%0A%0A
-open
+cancel
= () =%3E
%7B%0A
@@ -1477,30 +1477,24 @@
ncel = () =%3E
- %7B%0A
this.setSta
@@ -1496,24 +1496,62 @@
etState(
-%7B%0A
+DEFAULT_STATE)%0A%0A open = () =%3E this.setState(%7B
showModa
@@ -1561,19 +1561,10 @@
true
-%0A %7D)%0A
%7D
+)
%0A%0A
@@ -1743,16 +1743,68 @@
s.props%0A
+ const %7Bemail, password, showModal%7D = this.state%0A
retu
@@ -2022,36 +2022,45 @@
odal
- show=%7Bthis.state.showModal%7D
+%0A show=%7BshowModal%7D%0A
onH
@@ -2079,19 +2079,8 @@
ncel
-.bind(this)
%7D%3E%0A
@@ -2417,19 +2417,20 @@
-ref
+name
='email'
@@ -2472,36 +2472,39 @@
-valu
+onChang
e=%7Bthis.
state.email%7D
@@ -2491,22 +2491,55 @@
e=%7Bthis.
-state.
+_updateField%7D%0A value=%7B
email%7D%0A
@@ -2850,19 +2850,20 @@
-ref
+name
='passwo
@@ -2888,20 +2888,23 @@
-valu
+onChang
e=%7Bthis.
stat
@@ -2903,14 +2903,47 @@
his.
-state.
+_updateField%7D%0A value=%7B
pass
|
0417757de95778f230fc548c427b70b56989c723 | add '.' in name strategy regex | lib/helpers/findElementStrategy.js | lib/helpers/findElementStrategy.js | import { ProtocolError } from '../utils/ErrorHandler'
const DEFAULT_SELECTOR = 'css selector'
let findStrategy = function (...args) {
let value = args[0]
let relative = (args.length > 1 ? args[1] : false)
let xpathPrefix = relative ? './' : '//'
/**
* set default selector
*/
let using = DEFAULT_SELECTOR
if (typeof value !== 'string') {
throw new ProtocolError('selector needs to be typeof `string`')
}
if (args.length === 3) {
return {
using: args[0],
value: args[1]
}
}
// check value type
// use id strategy if value starts with # and doesnt contain any other CSS selector-relevant character
if (value.indexOf('#') === 0 && value.search(/(\s|>|\.|[|])/) === -1) {
using = 'id'
value = value.slice(1)
// use xPath strategy if value starts with //
} else if (value.indexOf('/') === 0 || value.indexOf('(') === 0 ||
value.indexOf('../') === 0 || value.indexOf('./') === 0 ||
value.indexOf('*/') === 0) {
using = 'xpath'
// use link text startegy if value startes with =
} else if (value.indexOf('=') === 0) {
using = 'link text'
value = value.slice(1)
// use partial link text startegy if value startes with *=
} else if (value.indexOf('*=') === 0) {
using = 'partial link text'
value = value.slice(2)
// recursive element search using the UiAutomator library (Android only)
} else if (value.indexOf('android=') === 0) {
using = '-android uiautomator'
value = value.slice(8)
// recursive element search using the UIAutomation library (iOS-only)
} else if (value.indexOf('ios=') === 0) {
using = '-ios uiautomation'
value = value.slice(4)
// recursive element search using accessibility id
} else if (value.indexOf('~') === 0) {
using = 'accessibility id'
value = value.slice(1)
// use tag name strategy if value contains a tag
// e.g. "<div>" or "<div />"
} else if (value.search(/<[a-zA-Z\-]+( \/)*>/g) >= 0) {
using = 'tag name'
value = value.replace(/<|>|\/|\s/g, '')
// use name strategy if value queries elements with name attributes
// e.g. "[name='myName']" or '[name="myName"]'
} else if (value.search(/^\[name=("|')([a-zA-z0-9\-_ ]+)("|')\]$/) >= 0) {
using = 'name'
value = value.match(/^\[name=("|')([a-zA-z0-9\-_ ]+)("|')\]$/)[2]
// any element with given text e.g. h1=Welcome
} else if (value.search(/^[a-z0-9]*=(.)+$/) >= 0) {
let query = value.split(/=/)
let tag = query.shift()
using = 'xpath'
value = `${xpathPrefix}${tag.length ? tag : '*'}[normalize-space() = "${query.join('=')}"]`
// any element containing given text
} else if (value.search(/^[a-z0-9]*\*=(.)+$/) >= 0) {
let query = value.split(/\*=/)
let tag = query.shift()
using = 'xpath'
value = `${xpathPrefix}${tag.length ? tag : '*'}[contains(., "${query.join('*=')}")]`
// any element with certian class or id + given content
} else if (value.search(/^[a-z0-9]*(\.|#)-?[_a-zA-Z]+[_a-zA-Z0-9-]*=(.)+$/) >= 0) {
let query = value.split(/=/)
let tag = query.shift()
let classOrId = tag.substr(tag.search(/(\.|#)/), 1) === '#' ? 'id' : 'class'
let classOrIdName = tag.slice(tag.search(/(\.|#)/) + 1)
tag = tag.substr(0, tag.search(/(\.|#)/))
using = 'xpath'
value = `${xpathPrefix}${tag.length ? tag : '*'}[contains(@${classOrId}, "${classOrIdName}") and normalize-space() = "${query.join('=')}"]`
// any element with certian class or id + has certain content
} else if (value.search(/^[a-z0-9]*(\.|#)-?[_a-zA-Z]+[_a-zA-Z0-9-]*\*=(.)+$/) >= 0) {
let query = value.split(/\*=/)
let tag = query.shift()
let classOrId = tag.substr(tag.search(/(\.|#)/), 1) === '#' ? 'id' : 'class'
let classOrIdName = tag.slice(tag.search(/(\.|#)/) + 1)
tag = tag.substr(0, tag.search(/(\.|#)/))
using = 'xpath'
value = xpathPrefix + (tag.length ? tag : '*') + '[contains(@' + classOrId + ', "' + classOrIdName + '") and contains(., "' + query.join('*=') + '")]'
value = `${xpathPrefix}${tag.length ? tag : '*'}[contains(@${classOrId}, "${classOrIdName}") and contains(., "${query.join('*=')}")]`
// allow to move up to the parent or select current element
} else if (value === '..' || value === '.') {
using = 'xpath'
}
return {
using: using,
value: value
}
}
export default findStrategy
| JavaScript | 0.999999 | @@ -2366,32 +2366,33 @@
')(%5Ba-zA-z0-9%5C-_
+.
%5D+)(%22%7C')%5C%5D$/) %3E
@@ -2477,16 +2477,17 @@
-z0-9%5C-_
+.
%5D+)(%22%7C'
|
efc4bb39c0a8e4ac92d11aa5b9b5ebf25318376c | test for argument of function in matching | test/registers/match.spec.js | test/registers/match.spec.js | 'use strict';
const {check} = require('../util');
const bee = require('../../src/index');
describe('[match register]', () => {
it('multi type match', function () {
let ori = {
foo: 1,
bar: 2,
1: 3
};
let beeOptions = {
[bee.match(/foo/, 1, 'bar')]: (value) => {
return String(value) + '!?';
}
};
check(ori, beeOptions, {
foo: '1!?',
bar: '2!?',
1: '3!?'
});
});
describe('string match', function () {
it('normal', () => {
let ori = {
name: null,
age: 12,
privacy: {
location: 'china',
occupation: 'front-end'
},
detail: null
};
let beeOptions = {
[bee.match('detail', 'age')] () {
return 'foo';
}
};
check(ori, beeOptions, {
name: null,
age: 'foo',
privacy: {
location: 'china',
occupation: 'front-end'
},
detail: 'foo'
});
});
it('in deep', () => {
let ori = {
node: {
info: {
data: {
name: 'foo'
}
}
}
};
let beeOptions = {
node: {
info: {
data: {
[bee.match('name')]: bee.remove()
}
}
}
};
check(ori, beeOptions, {
node: {
info: {
data: {}
}
}
});
});
it('unknown key', () => {
let ori = {
foo: 'bar'
};
let beeOptions = {
[bee.match('unknownKey')] () {
return 111;
}
};
check(ori, beeOptions, {
foo: 'bar'
});
});
it('ensure', () => {
let ori = {
name: []
};
let beeOptions = {
[bee.match('unknowKey')]: bee.ensure()
};
check(ori, beeOptions, {
name: []
});
});
it('has origin bee', function () {
let ori = {
info: {
name: 'bee',
career: 'front-end'
}
};
let beeOptions = {
info: {
[bee.match('name', 'career')]: (value) => {
return value + '!!';
},
name: (value) => {
return value + '!!';
}
}
};
check(ori, beeOptions, {
info: {
name: 'bee!!!!',
career: 'front-end!!'
}
});
});
});
describe('regExp match', function () {
it('normal', () => {
let ori = {
abc12345: 1,
abc123: 'foo'
};
let beeOptions = {
[bee.match(/^abc\d+$/)] () {
return 'bar';
}
};
check(ori, beeOptions, {
abc12345: 'bar',
abc123: 'bar'
});
});
it('in deep', () => {
let ori = {
node: {
info: {
data: {
name: 'foo'
}
}
}
};
let beeOptions = {
node: {
info: {
data: {
[bee.match(/^name$/)]: bee.remove()
}
}
}
};
check(ori, beeOptions, {
node: {
info: {
data: {}
}
}
});
});
it('rename', () => {
let ori = {
foo: 'bar'
};
let beeOptions = {
[bee.match(/foo/)]: bee.rename('bar')
};
check(ori, beeOptions, {
bar: 'bar'
});
});
it('unknown key', () => {
let ori = {
foo: 'bar'
};
let beeOptions = {
[bee.match(/abc/)] () {
return 111;
}
};
check(ori, beeOptions, {
foo: 'bar'
});
});
it('ensure unknown key', () => {
let ori = {
name: []
};
let beeOptions = {
[bee.match('unknownKey')]: bee.ensure()
};
check(ori, beeOptions, {
name: []
});
});
it('has origin bee', function () {
let ori = {
info: {
name: 'bee',
career: 'front-end'
}
};
let beeOptions = {
info: {
name: (value) => {
return value + '!!';
},
[bee.match(/^name|career$/)]: (value) => {
return value + '!!';
}
}
};
check(ori, beeOptions, {
info: {
name: 'bee!!!!',
career: 'front-end!!'
}
});
});
it('multi reg match', function () {
let ori = {
info: {
name: 'bee',
career: 'front-end'
}
};
let beeOptions = {
info: {
[bee.match(/^name$/, /^career$/)]: (value) => {
return value + '!!';
}
}
};
check(ori, beeOptions, {
info: {
name: 'bee!!',
career: 'front-end!!'
}
});
});
it('origin bee and rename', function () {
let ori = {
name: 'bee'
};
let beeOptions = {
[bee.match(/name/)]: bee.rename('foo'),
name: [bee.rename('bar'), () => {
return 123;
}]
};
check(ori, beeOptions, {
bar: 123
});
});
});
});
| JavaScript | 0.000001 | @@ -83,16 +83,50 @@
index');
+%0Aconst assert = require('assert');
%0A%0Adescri
@@ -554,32 +554,396 @@
%7D);%0A %7D);%0A%0A
+ it('match and function', function () %7B%0A let ori = %7B%0A foo: 1%0A %7D;%0A%0A let beeOptions = %7B%0A %5Bbee.match('foo')%5D: (value, key) =%3E %7B%0A assert.strictEqual(value, 1);%0A assert.strictEqual(key, 'foo');%0A %7D%0A %7D;%0A%0A check(ori, beeOptions, %7B%0A foo: 1%0A %7D);%0A %7D);%0A%0A
describe('st
|
743bc142aa4c8cd11f16ebda2a1b153114af4b92 | Add tests for proposition display. | test/unit/PropositionTest.js | test/unit/PropositionTest.js |
define(
[
'chai',
'sinon',
'fixtures',
'argumenta/widgets/Proposition',
'argumenta/widgets/Base'
],
function(chai, undefined, fixtures, Proposition, Base) {
var assert = chai.assert;
describe('Proposition', function() {
it('should be a function', function() {
assert.isFunction(Proposition);
});
it('should include a moduleID', function() {
assert.equal(Proposition.prototype.moduleID, 'Proposition');
});
describe('new Proposition( options, element )', function() {
it('should return a new Proposition widget', function() {
var data = fixtures.validPropositionData();
var proposition = new Proposition(data);
assert.instanceOf(
proposition, Base,
'Proposition widgets inherit from Base.'
);
assert.instanceOf(
proposition, Proposition,
'Proposition widgets are instances of Proposition.'
);
});
});
});
});
| JavaScript | 0 | @@ -1083,24 +1083,1528 @@
%7D);
+%0A%0A it('should display the proposition index', function() %7B%0A var data = fixtures.validPropositionData();%0A var proposition = new Proposition(data);%0A var $span = proposition.element.find('span.index');%0A var html = $span.html();%0A assert.include(%0A html, 'P.',%0A 'Check index.'%0A );%0A %7D);%0A%0A it('should display the proposition text', function() %7B%0A var data = fixtures.validPropositionData();%0A var proposition = new Proposition(data);%0A var $span = proposition.element.find('span.text');%0A var html = $span.html();%0A assert.include(%0A html, data.text,%0A 'Check text.'%0A );%0A %7D);%0A%0A it('should display the proposition SHA-1', function() %7B%0A var data = fixtures.validPropositionData();%0A var proposition = new Proposition(data);%0A var $link = proposition.element.find('span.sha1 a');%0A var href = $link.prop('href');%0A var sha1 = $link.html();%0A assert.include(%0A href, '/propositions/' + data.sha1,%0A 'Check object link.'%0A );%0A assert.include(%0A sha1, data.sha1.substr(0, 20),%0A 'Check SHA-1.'%0A );%0A %7D);
%0A %7D);
|
01970fa6f0b53de83adc1039ede365ce192a7b3f | Update test/unit/util_task-queue.js | test/unit/util_task-queue.js | test/unit/util_task-queue.js | const test = require('tap').test;
const TaskQueue = require('../../src/util/task-queue');
const testCompare = require('../fixtures/test-compare');
test('constructor', t => {
// Max tokens = 1000, refill 1000 tokens per second (1 per millisecond), and start with 0 tokens
const bukkit = new TaskQueue(1000, 1000, 0);
// Simulate time passing with a stubbed timer
const simulatedTimeStart = Date.now();
bukkit._timer = {timeElapsed: () => Date.now() - simulatedTimeStart};
const taskResults = [];
const promises = [];
const goodCancelMessage = 'Task was canceled correctly';
bukkit.do(() => taskResults.push('nope'), 999).then(
() => {
t.fail('Task should have been canceled');
},
() => {
taskResults.push(goodCancelMessage);
}
);
bukkit.cancelAll();
promises.push(
bukkit.do(() => taskResults.push('a'), 50).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait')
),
bukkit.do(() => taskResults.push('b'), 10).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial')
),
bukkit.do(() => taskResults.push('c'), 1).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '<', 80, 'Cheap task should run soon')
)
);
return Promise.all(promises).then(() => {
t.deepEqual(taskResults, [goodCancelMessage, 'a', 'b', 'c'], 'All tasks must run in correct order');
});
});
| JavaScript | 0 | @@ -21,20 +21,20 @@
('tap').
-test
+skip
;%0A%0Aconst
|
d5f5d4a55d625ec64fc0fcda19d18d149b1c5186 | Fix tooltip issue | lib/shared/addon/mixins/tooltip.js | lib/shared/addon/mixins/tooltip.js | import { scheduleOnce } from '@ember/runloop';
import { get, set, observer } from '@ember/object';
import { on } from '@ember/object/evented';
import $ from 'jquery';
import { inject as service } from '@ember/service';
import Mixin from '@ember/object/mixin';
import ThrottledResize from 'shared/mixins/throttled-resize';
export default Mixin.create(ThrottledResize, {
tooltipContent: null,
originalNode: null,
router: service(),
currentRoute: null,
tooltipService: service('tooltip'),
didInsertElement() {
let $el = $(get(this, 'element'));
let markup = `<div class ='tooltip-caret'></div>`;
$(markup).appendTo($el);
},
mouseEnter() {
get(this, 'tooltipService').cancelTimer();
},
mouseLeave() {
this.destroyTooltip();
},
routeObserver: on('init', observer('router.currentRouteName', function() {
// On init
if (!get(this, 'currentRoute')) {
set(this, 'currentRoute', get(this, 'router.currentRouteName'));
}
// if we change routes tear down the tooltip
if (get(this, 'currentRoute') !== get(this, 'router.currentRouteName')) {
this.destroyTooltip();
}
})),
tooltipConstructor: on('init', observer('tooltipService.tooltipOpts', function() {
scheduleOnce('afterRender', this, function() {
if (get(this, 'tooltipService.tooltipOpts')) {
this.constructTooltip();
}
});
})),
constructTooltip() {
let tts = get(this, 'tooltipService');
let node = $(this.element);
let eventPosition = tts.get('tooltipOpts.eventPosition');
let position = this.positionTooltip(node, $().extend({}, eventPosition));
let css = { visibility: 'visible' };
let classes = position.placement;
if ( tts.get('tooltipOpts.isCopyTo') ) {
css.width = position.width + 1;
}
if (tts.tooltipOpts.baseClass) {
classes += ` ${ tts.tooltipOpts.baseClass }`;
}
node.offset(position).addClass(classes).css(css);
if (position.caret) {
node.find('.tooltip-caret').css('left', position.caret);
}
},
destroyTooltip() {
get(this, 'tooltipService').startTimer();
},
positionTooltip(tooltipNode, position) {
let windowWidth = window.innerWidth;
let eventNode = get(this, 'tooltipService.tooltipOpts.originalNode');
let eventNodeWidth = eventNode.outerWidth();
let eventNodeHeight = eventNode.outerHeight();
let tooltipNodeHeight = tooltipNode.outerHeight();
let tooltipNodeWidth = tooltipNode.outerWidth();
let overridePlacement = get(this, 'tooltipService.tooltipOpts.placement');
let self = this;
if ( overridePlacement ) {
position.placement = overridePlacement;
} else if (tooltipNodeWidth >= position.left) {
position.placement = 'left';
} else if (tooltipNodeWidth >= (windowWidth - position.left)) {
position.placement = 'right';
} else if (tooltipNodeHeight >= position.top) {
position.placement = 'bottom';
} else {
position.placement = 'top';
}
switch ( position.placement ) {
case 'left':
position.left = horizontalViewport(position.left + eventNodeWidth + 7, position);
position.top = position.top + (eventNodeHeight / 2) - (tooltipNodeHeight / 2);
break;
case 'right':
position.left = horizontalViewport(position.left - tooltipNodeWidth - 7, position);
position.top = position.top + (eventNodeHeight / 2) - (tooltipNodeHeight / 2);
break;
case 'bottom':
position.left = horizontalViewport(position.left + (eventNodeWidth / 2) - (tooltipNodeWidth / 2), position);
position.top = position.top + eventNodeHeight + 7;
break;
default:
position.left = horizontalViewport(position.left + (eventNodeWidth / 2) - (tooltipNodeWidth / 2), position);
position.top = position.top - (tooltipNodeHeight + 7);
break;
}
function horizontalViewport(leftEdge2CenterPoint, position) {
if (leftEdge2CenterPoint < (tooltipNodeWidth / 2)) {
let centerOfDot = self.get('tooltipService.tooltipOpts.originalNode').offset().left + (eventNodeWidth / 2);
let widthOfEvent = eventNodeWidth;
let pushFromLeft = 10;
leftEdge2CenterPoint = Math.max(0, leftEdge2CenterPoint) + pushFromLeft;
position.caret = centerOfDot - pushFromLeft - widthOfEvent / 2;
}
return leftEdge2CenterPoint;
}
position.width = tooltipNodeWidth;
return position;
},
});
| JavaScript | 0.00008 | @@ -2642,42 +2642,8 @@
t');
-%0A let self = this;
%0A%0A
@@ -4085,176 +4085,8 @@
) %7B%0A
- let centerOfDot = self.get('tooltipService.tooltipOpts.originalNode').offset().left + (eventNodeWidth / 2);%0A let widthOfEvent = eventNodeWidth;%0A
@@ -4116,16 +4116,16 @@
= 10;%0A
+
%0A
@@ -4233,53 +4233,44 @@
=
-centerOfDot - pushFromLeft - widthOfEvent / 2
+position.left - leftEdge2CenterPoint
;%0A
|
a5f08b90fc7f72a8e82b452f667452be76bbafc9 | Fix flash messages | libcrowds_analyst/static/notify.js | libcrowds_analyst/static/notify.js | function notify(msg){
let html = $(`<div class="alert alert-${category} fade">
<a class="close" data-dismiss="alert" href="#">×</a>${msg}
</div>`);
$('#alert-messages').append(html);
window.setTimeout(function () {
html.addClass("in");
}, 300);
} | JavaScript | 0.000043 | @@ -12,16 +12,26 @@
tify(msg
+, category
)%7B%0A l
|
148af6c6fef05fe25f3f3c26ae9b9c5a7d7a1125 | Fix error when no configurations for creating a new one | views/dialog.js | views/dialog.js | define([
"text!templates/dialog.html",
"less!stylesheets/dialog.less"
], function(templateFile) {
var DialogView = codebox.require("views/dialogs/base");
var dialogs = codebox.require("utils/dialogs");
var loading = codebox.require("utils/loading");
var _ = codebox.require("underscore");
var rpc = codebox.require("core/backends/rpc");
var ConfigurationDialog = DialogView.extend({
className: "addon-launchconf-dialog modal fade",
templateLoader: "text",
template: templateFile,
events: _.extend({}, DialogView.prototype.events,{
"click #launchconf-add" : "createConfiguration",
"click #launchconf-del" : "removeConfiguration",
"click #launchconf-save" : "saveConfiguration",
"change #launchconf-select" : "loadConfiguration",
"focus #launchconf-select" : "onFocusSelect"
}),
defaults: _.extend({}, DialogView.prototype.defaults, {
keyboardEnter: false
}),
/**
* Helper to render the template and select the appropriate configuration.
*/
_renderAndSelect: function(conf_name) {
var that = this;
that.render().then(function(ok) {
if(!conf_name || conf_name === null) {
that.$("#launchconf-select").change();
}
else {
that.$("#launchconf-select").val(conf_name).change();
}
});
},
/**
* Save the current configuration in the manager cache.
*/
_saveCurrentConfigurationInCache: function() {
var conf_name = this.$("#launchconf-select option:selected").val();
var conf_cmds = this.$("#launchconf-commands").val().split('\n');
if(conf_name.length === 0) {
return;
}
this.manager.setCommands(conf_name, conf_cmds);
},
/**
* Upon initialization, load all configuration names.
*/
initialize: function(options) {
var that = this;
ConfigurationDialog.__super__.initialize.apply(this, arguments);
this.previous_conf_name = null;
this.manager = options.manager;
this.manager.getAll().then(function(data) {
that._renderAndSelect();
});
return this;
},
/**
* Needed to pass variables to the template context.
*/
templateContext: function() {
return {
confs: this.manager.getCache()
};
},
/**
* Refuses to render this dialog if the confs is not defined
* (ie. when still not loaded via RPC).
*/
render: function() {
if (!this.manager.getCache()) return this;
return ConfigurationDialog.__super__.render.apply(this, arguments);
},
/**
* Create a new configuration.
*/
createConfiguration: function(e) {
if (e) e.preventDefault();
var that = this;
var old_conf = this.previous_conf_name;
this._saveCurrentConfigurationInCache();
this.previous_conf_name = null;
dialogs.prompt( "Configuration name",
"Enter the name of the new launch configuration.")
.then(function(name) {
that.manager.create(name);
that._renderAndSelect(name);
}, function(err) {
that._renderAndSelect(old_conf);
});
},
/**
* Load a configuration (when the selection has changed).
*/
loadConfiguration: function(e) {
// Save the previous value in the cache
if(this.previous_conf_name !== null
&& this.previous_conf_name.length > 0) {
this.manager.setCommands(
this.previous_conf_name,
this.$("#launchconf-commands").val().split('\n')
);
}
// And load commands for the new value
var conf_name = e.currentTarget.value;
if(conf_name.length === 0) {
return;
}
this.previous_conf_name = conf_name;
this.$("#launchconf-commands").val(this.manager.getCommands(conf_name).join('\n'));
},
/**
* Store the current configuration name.
*/
onFocusSelect: function(e) {
this.previous_conf_name = this.$("#launchconf-select").val();
},
/**
* Save the configuration.
*/
saveConfiguration: function(e) {
if (e) e.preventDefault();
var that = this;
// Save the current configuration
this._saveCurrentConfigurationInCache();
// And this one will save all the cache file to the server
loading.show(this.manager.save(), "Saving configuration").fin(function() {
that.close();
});
},
/**
* Remove an existing configuration.
*/
removeConfiguration: function(e) {
if (e) e.preventDefault();
var that = this;
var conf_name = this.$("#launchconf-select option:selected").val();
if(conf_name.length === 0) {
return;
}
this._saveCurrentConfigurationInCache();
this.previous_conf_name = null;
dialogs.confirm("Remove configuration", "Do you really want to delete " + _.escape(conf_name) + "?")
.then(function(ok) {
that.manager.delete(conf_name);
that._renderAndSelect();
}, function(err) {
// User cancelled
that._renderAndSelect(conf_name);
});
}
});
return ConfigurationDialog;
}); | JavaScript | 0.000006 | @@ -1913,32 +1913,33 @@
%0A if(
+!
conf_name.length
@@ -1927,37 +1927,24 @@
f(!conf_name
-.length === 0
) %7B%0A
@@ -4519,32 +4519,33 @@
%0A if(
+!
conf_name.length
@@ -4533,37 +4533,24 @@
f(!conf_name
-.length === 0
) %7B%0A
|
8604c68f9ec423e02dd082e1417c8cac90e84d88 | remove npm check on modified | tooling/modified-packages.js | tooling/modified-packages.js | /*!
* Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
*/
const _ = require('lodash');
const yargs = require('yargs');
const {listDependents} = require('./lib/dependencies');
const {last} = require('./lib/version');
const {diff} = require('./lib/git');
const fileToPackage = (d) => {
if (d.startsWith('packages/node_modules/')) {
d = d.replace('packages/node_modules/', '');
d = d.split('/');
if (d[0].startsWith('@')) {
return d.slice(0, 2).join('/');
}
return d[0];
}
if (d.startsWith('docs') || d.startsWith('documentation') || d.startsWith('.github') || d.endsWith('.md')) {
return 'docs';
}
return 'tooling';
};
/**
* Lists all of the updated packages in the repo
* @param {Object} options
* @param {boolean=} options.dependents if true, also includes dependents of
* updated packages
* @param {boolean=} options.npm if true, compares to the last tag published to
* npm instead of upstream/master
* @returns {Promise<Array<string>>}
*/
const updated = async ({dependents, npm}) => {
const tag = npm ? await last() : 'upstream/master';
const changedPackages = _(await diff(tag))
.map((d) => d.path)
.filter()
.map(fileToPackage)
.uniq()
.value();
if (dependents) {
let transitive = new Set([...changedPackages]);
for (const packageName of changedPackages) {
transitive = new Set([...transitive, ...await listDependents(packageName, {includeTransitive: true})]);
}
return Array.from(transitive);
}
return changedPackages;
};
const modified = async (argv) => {
let changedPackages = argv.integration ?
await updated({dependents: true, npm: !!process.env.CI}) :
await updated({npm: !!process.env.CI});
changedPackages = changedPackages
.filter((packageName) => !packageName.includes('samples'))
.filter((packageName) => !packageName.includes('tooling'))
.filter((packageName) => !packageName.includes('bin-'))
.filter((packageName) => !packageName.includes('test-helper-'))
.filter((packageName) => !packageName.includes('eslint-config'))
.filter((packageName) => !packageName.includes('xunit-with-logs'))
.filter((packageName) => !packageName.includes('docs'));
console.log(argv.glob ?
`packages/node_modules/{${changedPackages}}` :
`${changedPackages.join(argv.singleLine ? ' ' : '\n')}`);
};
modified(
yargs
.options('i', {
alias: 'integration',
describe: 'Grab packages for integration environment',
default: false,
type: 'boolean'
})
.options('g', {
alias: 'glob',
describe: 'Modify reponse for CircleCI split testing',
default: false,
type: 'boolean'
})
.options('single-line', {
alias: 'singleLine',
describe: 'Log results in a single line',
default: false,
type: 'boolean'
})
.argv
);
| JavaScript | 0.000001 | @@ -1044,16 +1044,21 @@
ts, npm%7D
+ = %7B%7D
) =%3E %7B%0A
@@ -1670,77 +1670,31 @@
true
-, npm: !!process.env.CI%7D) :%0A await updated(%7Bnpm: !!process.env.CI%7D
+%7D) :%0A await updated(
);%0A%0A
|
274d5c0ae9191798b36dc6a298dcda62656d5d76 | Test IE6 | tools/browser_test_runner.js | tools/browser_test_runner.js | var path = require("path");
var build = require("./build.js");
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var baseDir = path.join(__dirname, "..", "test", "browser");
var browsers = [
["Windows XP", "internet explorer", "7"],
["Windows XP", "internet explorer", "8"],
["Windows 7", "internet explorer", "9"],
["Windows 7", "internet explorer", "10"],
["Windows 8.1", "internet explorer", "11"],
["Windows 7", "firefox", "3.5"],
["Windows 7", "firefox", "4"],
["Windows 7", "firefox", "25"],
["Windows 7", "firefox", "33"],
["Windows 7", "chrome", "beta"],
["Windows 7", "safari", "5"],
["OS X 10.9", "iphone", "8.1"],
["OS X 10.8", "safari", "6"],
["OS X 10.9", "safari", "7"]
];
var saucelabsOptions = {
urls: ["http://127.0.0.1:9999/index.html"],
tunnelTimeout: 30,
build: process.env.TRAVIS_JOB_ID,
maxPollRetries: 3,
throttled: 3,
browsers: browsers,
testname: "mocha tests",
tags: ["master"]
};
module.exports = function(options) {
var Promise = require("bluebird");
var ret = Promise.resolve();
function createServer() {
var http = require("http");
var serve = require("serve-static")(baseDir, {'index': ['index.html']});
var bodyParser = require("body-parser").urlencoded({
limit: "100mb",
extended: false
});
var server = http.createServer(function(req, res) {
serve(req, res, function() {
if (options.cover &&
req.url.indexOf("coverdata") >= 0 &&
req.method.toLowerCase() === "post") {
bodyParser(req, res, function() {
try {
var json = JSON.parse(req.body.json);
} catch (e) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404\n');
return;
}
var browser = (req.body.browser + "").replace(/[^a-zA-Z0-9]/g, "");
var fileName = path.join(build.dirs.coverage, "coverage-" + browser + ".json");
fs.writeFileAsync(fileName, JSON.stringify(json), "utf8").then(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Success\n');
});
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404\n');
}
});
});
return Promise.promisify(server.listen, server)(options.port)
}
if (options.saucelabs) {
var saucelabsRunner = require("./saucelabs_runner.js");
ret = createServer().then(function() {
return saucelabsRunner(saucelabsOptions);
}).then(function() {
process.exit(0);
});
} else {
var open = require("open");
ret = createServer().then(function() {
var url = "http://localhost:" + options.port;
console.log("Test can be run at " + url);
if (options.openBrowser && !options.cover) {
return Promise.promisify(open)(url);
}
});
}
return ret;
};
| JavaScript | 0 | @@ -215,16 +215,62 @@
ers = %5B%0A
+ %5B%22Windows XP%22, %22internet explorer%22, %226%22%5D,%0A
%5B%22Wi
|
b06d6d98630ec8a61b075e1b0037ede27d0d1881 | resolve merge conflicts | Components/Widgets/Button.js | Components/Widgets/Button.js | /* @flow */
'use strict';
import React, { Text, View, TouchableOpacity } from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import button from '../Styles/button';
import _ from 'lodash';
import computeProps from '../../Utils/computeProps';
import Icon from 'react-native-vector-icons/Ionicons';
export default class Button extends NativeBaseComponent {
getInitialStyle() {
return {
button: {
padding: 10,
justifyContent: 'space-around',
flexDirection: 'row',
marginBottom: 10,
alignSelf: 'flex-start',
backgroundColor: this.getTheme().btnPrimaryBg,
}
}
}
prepareRootProps() {
var type = { backgroundColor: (this.props.primary) ? this.getTheme().btnPrimaryBg :
((this.props.transparent) || (this.props.bordered)) ? 'rgba(0,0,0,0)' :
(this.props.success) ? this.getTheme().btnSuccessBg :
(this.props.danger) ? this.getTheme().btnDangerBg :
(this.props.warning) ? this.getTheme().btnWarningBg :
(this.props.info) ? this.getTheme().btnInfoBg :
(this.props.backgroundColor) ? this.props.backgroundColor :
this.getInitialStyle().button.backgroundColor,
borderRadius: (this.props.rounded) ? this.getTheme().borderRadiusLarge : this.getTheme().borderRadiusBase,
borderWidth: (this.props.bordered) ? 1 : 0,
borderColor: (this.props.primary) ? this.getTheme().primary :
(this.props.success) ? this.getTheme().btnSuccessBg :
(this.props.danger) ? this.getTheme().btnDangerBg :
(this.props.warning) ? this.getTheme().btnWarningBg :
(this.props.info) ? this.getTheme().btnInfoBg :
this.getInitialStyle().button.backgroundColor,
height: (this.props.large) ? 60 : (this.props.small) ? 35 : 45,
alignSelf: (this.props.block) ? 'stretch' : 'flex-start',
}
var addedProps = _.merge(this.getInitialStyle().button,type);
var defaultProps = {
style: addedProps
}
return computeProps(this.props, defaultProps);
}
getTextStyle() {
var mergedStyle = {};
var btnType = {
color: ((this.props.bordered) && (this.props.primary)) ? this.getTheme().btnPrimaryBg :
((this.props.bordered) && (this.props.success)) ? this.getTheme().btnSuccessBg :
((this.props.bordered) && (this.props.danger)) ? this.getTheme().btnDangerBg :
((this.props.bordered) && (this.props.warning)) ? this.getTheme().btnWarningBg :
((this.props.bordered) && (this.props.info)) ? this.getTheme().btnInfoBg :
this.getTheme().inverseTextColor,
fontSize: (this.props.large) ? this.getTheme().btnTextSizeLarge : (this.props.small) ? this.getTheme().btnTextSizeSmall : this.getTheme().btnTextSize,
lineHeight: (this.props.large) ? 32 : (this.props.small) ? 15 : 22
}
var addedBtnProps = _.merge(this.getInitialStyle().buttonText,btnType);
return _.merge(mergedStyle, addedBtnProps, this.props.textStyle);
}
renderChildren() {
if(typeof this.props.children == undefined || typeof this.props.children == "string") {
return <TouchableOpacity {...this.prepareRootProps()} >
<<<<<<< HEAD
<Text style={this.getTextStyle()}>{this.props.children}</Text>
=======
<Text style={this.getTextStyle()}>{this.props.children}</Text>
>>>>>>> 1d9203dff8b3adf7b8ddc62749f10db5cdf07eed
</TouchableOpacity>
}
else if(Array.isArray(this.props.children)) {
if(this.props.children[0] && (typeof this.props.children[0] == "string" || this.props.children[0].type == undefined))
return <TouchableOpacity {...this.prepareRootProps()} >
<Text style={this.getTextStyle()}>{this.props.children[0]}</Text>
<Text>
{this.props.children[1]}
</Text>
</TouchableOpacity>
else if(this.props.children[1] && (typeof this.props.children[1] == "string" || this.props.children[1].type == undefined))
return <TouchableOpacity {...this.prepareRootProps()} >
<Text>
{this.props.children[0]}
</Text>
<Text style={this.getTextStyle()}>{this.props.children[1]}</Text>
</TouchableOpacity>
else
return <TouchableOpacity {...this.prepareRootProps()} >
<Text>
{this.props.children[0]}
</Text>
<Text>
{this.props.children[1]}
</Text>
</TouchableOpacity>
}
else
return <TouchableOpacity {...this.prepareRootProps()} >
{this.props.children}
</TouchableOpacity>
}
render() {
return(this.renderChildren());
}
}
| JavaScript | 0.000001 | @@ -3602,21 +3602,8 @@
%3E%0A
-%3C%3C%3C%3C%3C%3C%3C HEAD%0A
@@ -3683,147 +3683,8 @@
xt%3E%0A
-=======%0A %3CText style=%7Bthis.getTextStyle()%7D%3E%7Bthis.props.children%7D%3C/Text%3E%0A%3E%3E%3E%3E%3E%3E%3E 1d9203dff8b3adf7b8ddc62749f10db5cdf07eed%0A
|
9b691c527aa5c96fd0a4cd0d40750a89310cce32 | update symbol species test | misc/scratchpad.js | misc/scratchpad.js | let sym = Symbol;
let spec = sym.species;
class A extends Array {
static [spec] = Array;
}
let typeA = A.from([1, 2, 3]);
let typeAArray = A.from([1, 2, 3]) // return type: A
.map((x) => x + 1); // return type: Array
console.log(typeA, typeAArray);
class B extends Array {
static [Symbol.species] = Array;
}
let typeB = A.from([1, 2, 3]);
let typeBArray = A.from([1, 2, 3]) // return type: A
.map((x) => x + 1); // return type: Array
console.log(typeB, typeBArray);
| JavaScript | 0 | @@ -73,24 +73,41 @@
tic
+get
%5Bspec%5D
- =
+() %7B%0A return
Array;%0A
%7D%0A%0Al
@@ -94,32 +94,36 @@
return Array;%0A
+ %7D%0A
%7D%0A%0Alet typeA = A
@@ -255,16 +255,61 @@
og(typeA
+ instanceof A, typeA, typeAArray instanceof A
, typeAA
@@ -349,16 +349,20 @@
static
+get
%5BSymbol.
@@ -373,18 +373,31 @@
ies%5D
- =
+() %7B%0A return
Array;%0A
%7D%0A%0Al
@@ -392,16 +392,20 @@
Array;%0A
+ %7D%0A
%7D%0A%0Alet t
@@ -411,17 +411,17 @@
typeB =
-A
+B
.from(%5B1
@@ -440,33 +440,33 @@
et typeBArray =
-A
+B
.from(%5B1, 2, 3%5D)
@@ -549,15 +549,289 @@
ypeB
-, typeB
+ instanceof B, typeB, typeBArray instanceof B, typeBArray);%0A%0Aclass C extends Array %7B%7D%0A%0Alet typeC = C.from(%5B1, 2, 3%5D);%0A%0Alet typeCArray = C.from(%5B1, 2, 3%5D) // return type: C%0A .map((x) =%3E x + 1); // return type: C%0Aconsole.log(typeC instanceof C, typeC, typeCArray instanceof C, typeC
Arra
|
54488995aba55221af97e1c3c46b39f6d09141aa | Remove /api prefix from routes. | processes/server.js | processes/server.js | var gateway = require(__dirname + '/../');
process.env.DATABASE_URL = gateway.config.get('DATABASE_URL');
var express = require('express');
var fs = require('fs');
var https = require('https');
var sequelize = require(__dirname+'/../node_modules/ripple-gateway-data-sequelize/lib/sequelize.js');
var restful = require('sequelize-restful');
var userCtrl = require(__dirname + '/../lib/http_json/controllers/users');
var publicCtrl = require(__dirname + '/../lib/http_json/controllers/public');
var ApiRouter = require(__dirname+'/../lib/http_json/routers/api_router.js');
var passportAuth = require(__dirname + '/../lib/http_json/passport_auth');
var passport = require('passport');
passport.use(passportAuth.adminBasic);
passport.use(passportAuth.userBasic);
var apiRouter = new ApiRouter({
passport: passport,
authName: 'adminBasic'
});
app = express();
app.use("/", express.static(__dirname + "/../node_modules/ripple-gateway-webapp-example/"));
app.use(express.json());
app.use(express.urlencoded());
app.use(restful(sequelize));
// PUBLIC
app.get('/ripple.txt', publicCtrl.rippleTxt);
app.get('/app', publicCtrl.webapp);
// USER
function userAuth() {
return passport.authenticate('userBasic', {session: false });
}
app.post('/api/v1/users/register', publicCtrl.registerUser);
app.post('/api/v1/users/login', publicCtrl.loginUser);
app.get('/api/v1/users/:id/external_accounts', userAuth(), userCtrl.externalAccounts);
app.get('/api/v1/users/:id/external_transactions', userAuth(), userCtrl.externalTransactions);
app.get('/api/v1/users/:id/ripple_addresses', userAuth(), userCtrl.rippleAddresses);
app.get('/api/v1/users/:id/ripple_transactions', userAuth(), userCtrl.rippleTransactions);
// ADMIN
function adminAuth() {
return passport.authenticate('adminBasic', {session: false });
}
apiRouter.bind(app);
var ssl = (gateway.config.get('SSL') && (gateway.config.get('SSL') != 'false'));
if (ssl) {
app = https.createServer({
key: fs.readFileSync(gateway.config.get('SSL_KEY_PATH')),
cert: fs.readFileSync(gateway.config.get('SSL_CERTIFICATE_PATH'))
}, app);
console.log('SSL enabled');
}
var host = gateway.config.get('HOST');
var port = gateway.config.get('PORT');
var protocol = ssl ? 'https' : 'http';
app.listen(port, host);
console.log('Serving REST API and Angular WebApp at '+protocol+'://'+host+':'+port);
| JavaScript | 0 | @@ -1233,36 +1233,32 @@
;%0A%7D%0A%0Aapp.post('/
-api/
v1/users/registe
@@ -1294,28 +1294,24 @@
%0Aapp.post('/
-api/
v1/users/log
@@ -1340,36 +1340,32 @@
ser);%0Aapp.get('/
-api/
v1/users/:id/ext
@@ -1423,36 +1423,32 @@
nts);%0Aapp.get('/
-api/
v1/users/:id/ext
@@ -1514,36 +1514,32 @@
ons);%0Aapp.get('/
-api/
v1/users/:id/rip
@@ -1607,12 +1607,8 @@
t('/
-api/
v1/u
@@ -2221,16 +2221,17 @@
http';%0A%0A
+%0A
app.list
|
d986a18c567f27c329d7d15d34579081287c7183 | Fix comments, add reject example | scratchpad.js | scratchpad.js | // Plugins are just a class
class IssuesPlugin {
// plugins can be initialized with state that is available in any of the methods
constructor(state) {
this.state = state;
}
// All defined methods become available in the api.
// each method takes a `context` argument that has access to the context it was called in.
comment(context, message) {
// Methods that make network calls should return a promise
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("comment:", message, this.state, context);
resolve();
}, 1000);
});
}
close(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("close");
resolve();
}, 1000);
});
}
}
PLUGINS = [
new IssuesPlugin("state")
];
class Workflow {
constructor() {
this.stack = [];
this.api = {};
PLUGINS.forEach(plugin => {
// Get all the property names of the plugin
for(let method of Object.getOwnPropertyNames(plugin.constructor.prototype)) {
if(method !== 'constructor') {
// Define a new function in the API for this plugin method, forcing
// the binding to this to prevent any tampering.
this.api[method] = this.proxy(plugin, method).bind(this);
}
}
});
}
proxy(plugin, method) {
return (...args) => {
// When this method is called, push new function on the stack that
this.stack.push((context) => {
return plugin[method].call(plugin, context, ...args);
});
// Return the API to allow methods to be chained.
return this.api;
}
}
// Execute the stack for this workflow with the given context
execute(context) {
this.stack.reduce((promise, func) => {
return promise.then(func.bind(func, context));
}, Promise.resolve(context));
}
}
workflow = new Workflow();
// workflow.api would be passed into a sandbox
workflow.api.comment("Hello").close();
// Execute the workflow with the given context
w.execute({name: 'Brandon'});
| JavaScript | 0 | @@ -528,16 +528,24 @@
message,
+ %7Bstate:
this.st
@@ -556,16 +556,17 @@
context
+%7D
);%0A
@@ -725,16 +725,27 @@
(%22close%22
+, %7Bcontext%7D
);%0A
@@ -781,24 +781,113 @@
%0A %7D);%0A %7D
+%0A%0A fail(context) %7B%0A return Promise.reject(%22Rejecting a promise stops the chain%22);%0A %7D
%0A%7D%0A%0APLUGINS
@@ -1461,24 +1461,81 @@
, method) %7B%0A
+ // This function is what gets exposed to the sandbox%0A
return (
@@ -1561,37 +1561,9 @@
//
-When this method is called, p
+P
ush
@@ -1592,16 +1592,56 @@
ack that
+ calls the plugin method with a context.
%0A t
@@ -1839,46 +1839,86 @@
%0A%0A
-// E
+e
xecute
- the stack for this workflow
+(context) %7B%0A // Reduce the stack to a chain of promises, each called
wit
@@ -1937,37 +1937,16 @@
context%0A
- execute(context) %7B%0A
this
@@ -2056,23 +2056,16 @@
resolve(
-context
));%0A %7D%0A
@@ -2179,16 +2179,56 @@
.close()
+.fail().comment(%22this won't get called%22)
;%0A%0A// Ex
@@ -2269,16 +2269,23 @@
context%0A
+workflo
w.execut
|
27a56fd3e660b51c6fc47594baf079a3474a1d77 | Fix jsdoc comment | HelloWorld/lib/myPanel.js | HelloWorld/lib/myPanel.js | /* See license.txt for terms of usage */
"use strict";
const self = require("sdk/self");
const { Cu, Ci } = require("chrome");
const { Panel } = require("dev/panel.js");
const { Class } = require("sdk/core/heritage");
const { Tool } = require("dev/toolbox");
/**
* This object represents a new {@Toolbox} panel
*/
const MyPanel = Class(
/** @lends BasePanel */
{
extends: Panel,
label: "My Panel",
tooltip: "My panel tooltip",
icon: "./icon-16.png",
url: "./myPanel.html",
/**
* Executed by the framework when an instance of this panel is created.
* There is one instance of this panel per {@Toolbox}. The panel is
* instantiated when selected in the toolbox for the first time.
*/
initialize: function(options) {
},
/**
* Executed by the framework when the panel is destroyed.
*/
dispose: function() {
},
/**
* Executed by the framework when the panel content iframe is
* constructed. Allows e.g to connect the backend through
* `debuggee` object
*/
setup: function(options) {
// TODO: connect to backend using options.debuggee
},
});
const myTool = new Tool({
name: "MyTool",
panels: {
myPanel: MyPanel
}
});
| JavaScript | 0.000001 | @@ -351,12 +351,10 @@
nds
-Base
+My
Pane
|
e06ff48e3f45f8ce5800984504189aa1dfa6542e | Fix title/subtitle for people activity graph. | dashboard/js/graphs.js | dashboard/js/graphs.js | function makeLink(url, text) {
var link = $('<a />', {
href: url,
text: text,
});
return $('<div />').append(link).html();
}
function makeList(container, options) {
$.getJSON(API_BASE + options.endpoint)
.done(function (json) {
$container = $(container);
$container.append($('<h3 />').text(options.title).addClass('text-center'));
$list = $('<ul />');
data = json.data;
data.forEach(function (e) {
$item = $('<li />');
if (typeof options.keyName === 'function') {
$item.html(options.keyName(e));
} else {
$item.html(e[options.keyName]);
}
$list.append($item);
});
$container.append($list);
})
.fail(displayFailMessage);
}
function makeXYGraph(container, options) {
$.getJSON(API_BASE + options.endpoint)
.done(function (json) {
data = json.data;
$(container).highcharts({
chart: {
type: options.type
},
title: {
text: options.title
},
subtitle: {
text: options.subtitle
},
xAxis: {
categories: data.map(function (e) {
if (typeof options.keyName === 'function') {
return options.keyName(e);
}
return e[options.keyName];
})
},
yAxis: {
min: 0,
title: {
text: options.yTitle
}
},
legend: {
enabled: false
},
series: [{
name: options.label,
data: data.map(function (e) {
if (typeof options.valueName === 'function') {
return options.valueName(e);
}
return e[options.valueName];
})
}]
});
})
.fail(displayFailMessage);
}
/*
* Populate the User Issues card
*/
function getUserIssues () {
$this = $('.js-handler--github-username');
$this.data('timeout-id', '');
var username = $this.val().trim();
if (username) {
$.get(API_BASE + username +'/issues_assigned')
.success(function (data) {
var source = $("#user-issues").html();
var template = Handlebars.compile(source);
var issues = data.data.length ? data.data.join('') : 'No issues assigned to this user';
var context = {user: username, list: issues}
var html = template(context);
$('.template-user-issues').empty().append(html);
})
.fail(function (data) {
$('.template-user-issues').empty().text('Failed to retrieve data');
});
}
}
function makeStackedSeries(data, valueKey) {
// find all the series
var seriesNames = [];
for (var i = 0; i < data.length; ++i) {
var values = data[i][valueKey];
var keys = Object.keys(values);
for (var j = 0; j < keys.length; ++j) {
var category = keys[j];
if (seriesNames.indexOf(category) === -1) {
seriesNames.push(category);
}
}
}
// get the actual values
var series = [];
for (var i = 0; i < seriesNames.length; ++i) {
var s = {
name: seriesNames[i],
data: []
};
for (var j = 0; j < data.length; ++j) {
var d = data[j][valueKey];
if (d[s.name]) {
s.data.push(d[s.name]);
} else {
s.data.push(0);
}
}
series.push(s);
}
return series;
}
function makeStackedGraph(container, options) {
var graph = {
chart: {
type: options.type
},
title: {
text: options.title
},
subtitle: {
text: options.subtitle
},
xAxis: {
categories: options.categories,
title: {
enabled: true
}
},
yAxis: {
title: {
text: options.yTitle
},
min: 0
},
legend: {
labelFormatter: options.legendFormatter
},
tooltip: {
shared: true,
valueSuffix: ' ' + options.suffix,
formatter: options.tooltipFormatter
},
plotOptions: {},
series: options.series
};
graph.plotOptions[options.type] = {
stacking: 'normal',
fillOpacity: 1,
lineColor: '#666666',
lineWidth: 1,
marker: {
enabled: false
}
};
$(container).highcharts(graph);
}
function drawActivityGraph() {
$.getJSON(API_BASE + '/total_events_monthly')
.done(function(data) {
var series = makeStackedSeries(data.data, 'value');
var categories = data.data.map(function (e) {
return e.month;
});
var options = {
type: 'column',
title: "Activity",
subtitle: "Total monthly events",
yTitle: 'Events',
suffix: 'events',
series: series,
categories: categories,
legendFormatter: function () {
var label = this.name;
var idx = label.indexOf("event");
return label.substr(0, idx);
}
};
makeStackedGraph('#total-events-monthly', options);
})
.fail(displayFailMessage);
}
function drawActivePeopleGraph() {
$.getJSON(API_BASE + '/most_active_people')
.done(function(data) {
var series = makeStackedSeries(data.data, 'events');
var categories = data.data.map(function (e) {
return e.login;
});
var options = {
type: 'bar',
title: "Activity",
subtitle: "Total monthly events",
yTitle: 'Events',
suffix: 'events',
series: series,
categories: categories,
legendFormatter: function () {
var label = this.name;
var idx = label.indexOf("event");
return label.substr(0, idx);
}
};
makeStackedGraph('#most-active-people', options);
})
.fail(displayFailMessage);
}
function drawGraphs() {
drawActivePeopleGraph();
drawActivityGraph();
makeXYGraph('#most-active-issues', {
endpoint: '/most_active_issues',
type: 'bar',
title: "Most active issues",
keyName: function (e) {
return makeLink('http://github.com/' + REPO + '/issues/' + e.term,
"#" + e.term);
},
valueName: 'count',
yTitle: 'Events',
label: 'events'
});
/*
makeList('#issues-without-comments', {
endpoint: 'gabrielfalcao/lettuce/issues_without_comments',
title: "Issues without comments",
keyName: function (e) {
return makeLink("http://github.com/gabrielfalcao/lettuce/issues/" + e,
"#" + e);
}
});
*/
/*
* Listen for keyup events and fetch data for specified user
* has a 200ms delay between keyup and actual GET request
* to prevent firing a cascade of requests
*/
/*
$('.js-handler--github-username').off('keyup');
$('.js-handler--github-username').on('keyup', function () {
var timeout_id = parseInt($(this).data('timeout-id'), 10) || null;
if (timeout_id) clearTimeout(timeout_id);
timeout_id = setTimeout(getUserIssues, 200);
$(this).data('timeout-id', timeout_id);
});
*/
}
| JavaScript | 0 | @@ -6423,32 +6423,42 @@
title: %22
-Activity
+Most active people
%22,%0A
@@ -6471,37 +6471,36 @@
subtitle: %22
-Total monthly
+By number of
events%22,%0A
|
b2f2a8a384dab64d13e775f9491559b81ee59e08 | Add sass dependency to buildfiles in gulpfile | MSPSpain.Web/Content/gulpfile.js | MSPSpain.Web/Content/gulpfile.js | var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var files = {
build: 'build/**/*.*',
buildJS: 'build/code.js',
buildCSS: 'build/styles.css',
css: 'css/**/*.css',
filePaths: ['css/**/*.css', 'ts/Services/*.js', 'ts/Models/*.js', 'ts/Interfaces/*.js', 'ts/Controllers/*.js', 'ts/App.js'],
index: '../Views/Home/Index.cshtml',
indexBkp: '../Views/Home/Index.cshtml.bkp',
js: 'js/**/*.js',
scss: 'scss/*.scss',
scssAll: 'scss/**/*.scss'
};
var paths = {
general: '../',
build: 'build',
css: 'css',
project: '../Views/Home/',
scss: 'scss',
js: 'js'
};
// Compile Sass
gulp.task('sass', function(){
return gulp.src(files.scss)
.pipe(plugins.sass())
.pipe(plugins.autoprefixer({
browsers: ['last 2 version']
}))
.pipe(gulp.dest(paths.css));
});
// Inject JS & CSS Files
gulp.task('inject', ['clear', 'sass'], function() {
return gulp.src(files.index)
.pipe(plugins.inject(
gulp.src(files.filePaths, { read: false }),
{
transform: function (filepath) {
if (filepath.indexOf('.js') > -1) {
return '<script src="Content/' + filepath.slice(1) + '"></script>'
}
// Css
return ' <link rel="stylesheet" href="Content' + filepath + '">'
}
}
))
.pipe(gulp.dest(paths.project));
});
// Celan specific folders
gulp.task('clear', function () {
// If exist indexBkp replace normal index and delete this
gulp.src(files.indexBkp)
.pipe(plugins.rename('Index.cshtml'))
.pipe(gulp.dest(paths.project));
//return gulp.src(files.build, { read: false })
// .pipe(plugins.clean({ force: true }));
});
// Build Files
gulp.task('buildFiles', function() {
// Save index
gulp.src(files.index)
.pipe(plugins.clone())
.pipe(plugins.rename('Index.cshtml.bkp'))
.pipe(gulp.dest(paths.project));
// Build files
return gulp.src(files.index)
.pipe(plugins.usemin(
{
css: [plugins.minifyCss()],
js: /*[plugins.uglify()]*/[]
}
))
.pipe(gulp.dest(paths.general));
});
//relocate index
gulp.task('relocateIndex',['buildFiles'], function () {
gulp.src(paths.general + '/Index.cshtml').pipe(gulp.dest(paths.project));
return gulp.src(paths.general + '/Index.cshtml').pipe(plugins.clean({ force: true }));
});
// Init watch
gulp.task('watch', function () {
gulp.watch(files.js, ['inject']);
gulp.watch(files.scssAll, ['sass', 'inject']);
});
gulp.task('default', ['clear', 'inject', 'sass']);
gulp.task('build', ['default', 'buildFiles', 'relocateIndex']);
| JavaScript | 0.000001 | @@ -1639,16 +1639,26 @@
dFiles',
+ %5B'sass'%5D,
functio
@@ -1654,24 +1654,25 @@
'%5D, function
+
() %7B%0A%09// Sav
|
6c59b221d967743460038c28592392420bcc51e5 | fix complete callback | example/sprites/js/sprite.js | example/sprites/js/sprite.js |
function Sprite(sprite_data)
{
var position,
halfWidth,
halfHeight,
properties = {
x: sprite_data.x,
y: sprite_data.y,
facing: sprite_data.facing,
start: 0,
sprite_data: sprite_data,
object: null
};
var animation_class = null;
var moving = false;
var manager = null;
this.setManager = function(my_manager) {
manager = my_manager;
};
this.init = function(target) {
return this.initView(target)
.registerEvents()
.update();
};
/**
* set player status of sprite
*
* @return {Sprite}
*/
this.setPlayer = function(isPlayer) {
properties.sprite_data.player = isPlayer;
if (isPlayer) {
properties.object.addClass('player');
} else {
properties.object.removeClass('player');
}
return this;
};
/**
* get player status of sprite
*
* @return {boolean}
*/
this.isPlayer = function() {
return properties.sprite_data.player;
}
this.setAnimationClass = function() {
properties.object.removeClass(animation_class);
animation_class = properties.facing + '_' + pad(properties.start + '', 2);
properties.object.addClass(animation_class);
};
this.initView = function(target) {
properties.start = 0;
properties.object = $('<div class="sprite '+properties.sprite_data.type+' '+(properties.sprite_data.player ? 'player' : '')+'"></div>')
.appendTo($(target));
$(properties.object).css({
top: properties.y + 'px',
left: properties.x + 'px',
zIndex : properties.sprite_data.zIndex++
});
position = $(properties.object).position();
halfWidth = $(properties.object).width() / 2;
halfHeight = $(properties.object).height() / 2;
this.setAnimationClass();
return this;
};
this.registerEvents = function() {
var self = this;
$(properties.object).bind('move', function(eventObject, eventData) {
if (properties.sprite_data.player) {
self.move(eventData.x, eventData.y);
}
});
$(properties.object).bind('click', function(eventObject) {
manager.setPlayer(self);
eventObject.stopPropagation();
});
return this;
};
/**
* initialite sprite movement to given coordinates
*
* @return {Sprite}
*/
this.move = function(x, y) {
// source center
var position_x = position.left + halfWidth,
position_y = position.top + halfHeight,
position_x2 = x - halfWidth,
position_y2 = y - halfHeight,
angle = calculateFacingAngle(x, y, position_x, position_y),
animation_duration = 4000,
distance = Math.sqrt((position_x2-position_x)*(position_x2-position_x)+(position_y2-position_y)*(position_y2-position_y));
properties.facing = calculateFacing(angle);
if (Math.abs(distance) < 200) {
animation_duration = 1500;
}
moving = true;
$(properties.object).clearQueue().animate({
top : position_y2 + 'px',
left : position_x2 + 'px'
}, {duration: animation_duration, queue: true}, 'swing', function() {
moving = false;
});
return this;
};
/**
* update sprite
*
* @return {Sprite}
*/
this.update = function() {
var self = this;
properties.start += moving ? 2 : 1;
if (properties.start >= properties.sprite_data.maxFrame)
properties.start = properties.sprite_data.minFrame;
position = $(properties.object).position();
self.setAnimationClass();
return this;
};
}
| JavaScript | 0.000001 | @@ -2801,16 +2801,20 @@
'%0A%09%09%7D, %7B
+%0A%09%09%09
duration
@@ -2834,17 +2834,20 @@
uration,
-
+%0A%09%09%09
queue: t
@@ -2853,33 +2853,93 @@
true
-%7D, 'swing', function() %7B%0A
+,%0A%09%09%09easing: 'swing',%0A%09%09%09step: function() %7B%0A%0A%09%09%09%7D,%0A%09%09%09complete: function(now, fx) %7B%0A%09
%09%09%09m
@@ -2953,16 +2953,21 @@
false;%0A
+%09%09%09%7D%0A
%09%09%7D);%0A%0A%09
|
294fd5d7e068597387deb11346d813f7b687d08e | clarify to use response.set() | 06-content-negotiation/index.js | 06-content-negotiation/index.js |
var koa = require('koa');
/**
* This is a promisified version of zlib's gzip function,
* allowing you to simply `yield` it without "thunkifying" it.
*
* this.response.body = yield gzip('something');
*/
var gzip = require('mz/zlib').gzip;
var app = module.exports = koa();
app.use(function* () {
})
| JavaScript | 0.000002 | @@ -151,16 +151,104 @@
t.%0A *%0A *
+ app.use(function* (next) %7B%0A * this.response.set('Content-Encoding', 'gzip');%0A *
this.
@@ -288,16 +288,24 @@
hing');%0A
+ * %7D)%0A
*/%0Avar
|
02e513159c99eb1de29fcc8c00d6ef476572e993 | fix a bug | models/dc_model.js | models/dc_model.js | var mongodb = require('./mongodb');
var Schema = mongodb.mongoose.Schema;
var DCSchema = new Schema({
no: String,
r1: Number,
r2: Number,
r3: Number,
r4: Number,
r5: Number,
r6: Number,
b1: Number,
date: Date
});
var DCModel = mongodb.mongoose.model('dc', DCSchema);
var DCDAO = function () { };
DCDAO.prototype.save = function (obj, cb) {
var instance = new DCModel(obj);
instance.save(cb);
};
DCDAO.prototype.getData = function (limitnum,query, opts, callback) {
if (limitnum != null) {
DCModel.find(query, '', opts, callback).limit(limitnum).sort({ 'no': -1 });
}
else {
DCModel.find(query, '', opts, callback).limit(limitnum).sort({ 'no': -1 });
}
};
module.exports = new DCDAO();
| JavaScript | 0.000016 | @@ -592,86 +592,8 @@
e %7B%0A
-%09%09DCModel.find(query, '', opts, callback).limit(limitnum).sort(%7B 'no': -1 %7D);%0A
%09%7D%0A%7D
|
779e529feaab70c57f361892ff2591c86f316c10 | comment (support _method (PUT in forms etc)) | server/app.js | server/app.js | /**
* Point d'entrée du programme
*/
if (typeof define !== 'function') {
var define = (require('amdefine'))(module);
}
define([
'express.io',
'./config/boot'
], function (express, boot) {
var app = express().http().io();
// settings
// define a custom res.message() method
// which stores messages in the session
app.response.message = function(msg){
// reference `req.session` via the `this.req` reference
var sess = this.req.session;
// simply add the msg to an array for later
sess.messages = sess.messages || [];
sess.messages.push(msg);
return this;
};
// log
if (!module.parent) app.use(express.logger('dev'));
// serve static files
app.use(express.static(__dirname + '/../client/app'));
// session support
app.use(express.cookieParser('79vm86SUm34c3ZSxtc3aSPnn8DReU9Q4'));
app.use(express.session());
// parse request bodies (req.body)
app.use(express.bodyParser());
// support _method (PUT in forms etc)
app.use(express.methodOverride());
// expose the "messages" local variable when views are rendered
app.use(function(req, res, next){
var msgs = req.session.messages || [];
// expose "messages" local variable
res.locals.messages = msgs;
// expose "hasMessages"
res.locals.hasMessages = !! msgs.length;
/* This is equivalent:
res.locals({
messages: msgs,
hasMessages: !! msgs.length
});
*/
next();
// empty or "flush" the messages so they
// don't build up
req.session.messages = [];
});
// load controllers and sockets
boot.route(app, { verbose: !module.parent });
// assume "not found" in the error msgs
// is a 404. this is somewhat silly, but
// valid, you can do whatever you like, set
// properties, use instanceof etc.
app.use(function(err, req, res, next){
// treat as 404
if (~err.message.indexOf('not found')) return next();
// log it
console.error(err.stack);
// error page
res.status(500).render('5xx');
});
// assume 404 since no middleware responded
app.use(function(req, res, next){
res.status(404).render('404', { url: req.originalUrl });
});
if (!module.parent) {
app.listen(3000);
console.log('\n listening on port 3000\n');
}
}); | JavaScript | 0 | @@ -1037,24 +1037,27 @@
rms etc)%0A
+ //
app.use(exp
|
1574986ee853e0e589be8ef57860aa2d8caaf44a | fix a bug | server/app.js | server/app.js | const path = require("path");
const helmet = require("helmet");
const express = require("express");
const favicon = require("serve-favicon");
const bodyParser = require("body-parser");
const compression = require("compression");
const isDevMode = app.get("env") !== "production";
const viewsPath = path.resolve(__dirname, "./views");
const publicPath = path.resolve(__dirname, "../dist/public");
const faviconPath = path.join(publicPath, "favicon.png");
const assetsPath = path.join(publicPath, "assets", "assets.json");
const routes = require("./routes");
// init express.
const app = express();
// view engine setup.
app.set("views", viewsPath);
app.set("view engine", "pug");
// security setup.
app.use(helmet());
// gzip setup.
app.use(compression());
// favicon setup.
app.use(favicon(faviconPath));
// body parser setup.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// static file setup.
app.use(express.static(publicPath));
if (isDevMode)
{
// development: logger & HMR setup.
const { blue } = require("chalk");
console.log(blue("Current Environment:", "development"));
const logger = require("morgan");
app.use(logger("dev"));
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const webpackDevConfig = require("../webpack.dev.config");
const compiler = webpack(webpackDevConfig);
const webpackDevMiddlewareInstance = webpackDevMiddleware(
compiler,
{
stats:
{
chunks: false,
colors: true
},
publicPath: webpackDevConfig.output.publicPath
}
);
webpackDevMiddlewareInstance.waitUntilValid(() =>
{
// assets map setup.
app.locals.map = require(assetsPath);
});
app.use(webpackDevMiddlewareInstance);
app.use(webpackHotMiddleware(compiler));
}
else
{
// production: assets map setup.
app.locals.map = require(assetsPath);
}
// router setup.
app.use("/", routes);
// catch 404 and forward to global error handler.
app.use((req, res, next) =>
{
const err = new Error("404 Not Found");
err.status = 404;
next(err);
});
// global error handler.
app.use((err, req, res, next) =>
{
const status = err.status | 500;
if (isDevMode)
{
res.status(status).send(err);
}
else
{
res.status(status).send(`Error ${status}.`);
}
});
module.exports = app;
| JavaScript | 0.000016 | @@ -228,59 +228,8 @@
);%0A%0A
-const isDevMode = app.get(%22env%22) !== %22production%22;%0A
cons
@@ -542,16 +542,67 @@
press();
+%0Aconst isDevMode = app.get(%22env%22) !== %22production%22;
%0A%0A// vie
|
763033d7f91bae894150c6d060ea43bb40f8d332 | Update commain.js | yangfan01/scripts/commain.js | yangfan01/scripts/commain.js | var button=$("button:eq(0)"),p=$("p");button.click(function(a){$("div").addClass("divHide");time=totalTime;goldCaught=0;unactivation();activation();main();timeInterval=setInterval(tick,1E3)});function tick(){time--;0>=time&&(clearInterval(timeInterval),cancelAnimationFrame(mainFrame),$("div").removeClass(),goldCaught>max&&(max=goldCaught),$("b:eq(0)").html(goldCaught),$("b:eq(1)").html(max),$("button:eq(0)").html("\u518d\u73a9\u4e00\u6b21"))}var canvas=document.createElement("canvas");
canvas.width=$(window).get(0).innerWidth;canvas.height=$(window).get(0).innerHeight-10;var ctx=canvas.getContext("2d");$("body").append(canvas);var catReady=!1,catImage=new Image;catImage.onload=function(){catReady=!0};catImage.src="cat.png";var goldReady=!1,goldImage=new Image;goldImage.onload=function(){goldReady=!0};goldImage.src="gold.png";var cat={speed:600,x:canvas.width/2},goldCaught=0,keysDown={};
addEventListener("touchstart",function(a){1==a.touches.length&&(a.touches[0].clientX>cat.x?keysDown.right=!0:keysDown.left=!0);startX=a.touches[0].clientX},!1);addEventListener("touchend",function(a){delete keysDown.left;delete keysDown.right;delete keysDown.moveR;delete keysDown.moveL},!1);addEventListener("touchmove",function(a){a.preventDefault();endX=a.touches[0].clientX;moveX=endX-startX;0<moveX?keysDown.moveR=!0:keysDown.moveL=!0},!1);
addEventListener("keydown",function(a){keysDown[a.keyCode]=!0},!1);addEventListener("keyup",function(a){delete keysDown[a.keyCode]},!1);function rnd(a,b){return a+parseInt(Math.random()*(b-a))}
var update=function(a){37 in keysDown&&(cat.x-=cat.speed*a);39 in keysDown&&(cat.x+=cat.speed*a);"moveR"in keysDown&&(cat.x+=cat.speed*a);"moveL"in keysDown&&(cat.x-=cat.speed*a);for(a=0;a<poll.length;a++)poll[a].inUse&&(poll[a].move(),poll[a].isOut());for(a=0;a<size;a++)poll[a].inUse&&cat.x<=poll[a].x+32&&poll[a].x<=cat.x+50&&100>=canvas.height-poll[a].y&&poll[a].y<=canvas.height&&(goldCaught++,poll[a].clear())},render=function(){ctx.fillStyle="#ff9588";ctx.fillRect(0,0,canvas.width,canvas.height);
if(goldReady)for(var a=0;a<poll.length;a++)poll[a].inUse&&ctx.drawImage(goldImage,poll[a].x,poll[a].y);0>cat.x?cat.x=0:cat.x>canvas.width-75&&(cat.x=canvas.width-75);catReady&&ctx.drawImage(catImage,cat.x,canvas.height-100);ctx.fillStyle="black";ctx.font="24px Helvetica";ctx.textAlign="left";ctx.textBaseline="top";ctx.fillText("\u5f97\u5206",32,32);ctx.fillText("\u65f6\u95f4",canvas.width-132,32);ctx.fillStyle="white";ctx.font="40px Helvetica";ctx.fillText(goldCaught,85,25);0>time?ctx.fillText(0,
canvas.width-75,25):ctx.fillText(time,canvas.width-75,25)},main=function(){var a=Date.now();update((a-then)/1E3);render();then=a;mainFrame=requestAnimationFrame(main)};function Gold(){this.inUse=!1;this.x=rnd(0,canvas.width-50);this.y=-20;this.move=function(){this.y+=6};this.isOut=function(){return this.y>=canvas.height?(this.clear(),!0):!1};this.clear=function(){this.x=rnd(0,canvas.width-50);this.y=-20;this.inUse=!1}}
function createGold(){for(var a=0;poll.length<size;a++){var b=new Gold;poll.push(b)}}function activation(){var a=rnd(0,10);poll[a].inUse||(poll[a].inUse=!0);setTimeout(activation,800)}function unactivation(){for(var a=0;a<poll.length;a++)poll[a].clear()}var w=window;requestAnimationFrame=w.requestAnimationFrame||w.webkitRequestAnimationFrame||w.msRequestAnimationFrame||w.mozRequestAnimationFrame;
var then=Date.now(),poll=[],size=10,totalTime=30,time=totalTime,timeInterval,mainFrame,max=0,startX=0,endX=0,moveX=0,inUseNumber=0;createGold();
| JavaScript | 0.000001 | @@ -717,16 +717,23 @@
ge.src=%22
+images/
cat.png%22
@@ -827,16 +827,23 @@
ge.src=%22
+images/
gold.png
|
8eb58ae508824bcae517f30d75bc1d87664860fc | Update reverseTransaction, #8423 | arches/app/media/js/views/components/plugins/etl-manager.js | arches/app/media/js/views/components/plugins/etl-manager.js | define([
'jquery',
'knockout',
'arches',
], function($, ko, arches) {
return ko.components.register('etl-manager', {
viewModel: function(params) {
const self = this;
this.loading = params.loading;
this.alert = params.alert;
this.loading(true);
this.selectedModule = ko.observable();
this.activeTab = ko.observable();
this.isImport = ko.observable(true);
this.loadEvents = ko.observable();
this.selectedLoadEvent = ko.observable();
this.validated = ko.observable();
this.validationError = ko.observableArray();
this.selectedLoadEvent.subscribe(function(val){
self.fetchValidation(val.loadid);
});
this.moduleSearchString = ko.observable('');
this.taskSearchString = ko.observable('');
this.tabs = [
{id: 'start', title: 'Start'},
{id: 'details', title: 'Task Details'},
{id: 'import', title: 'Import Tasks'},
{id: 'export', title: 'Export Tasks'},
];
this.selectModule = function(etlmodule) {
self.selectedModule(etlmodule);
self.activeTab("details");
};
this.activeTab.subscribe(val => {
if (val == "import") {
self.fetchLoadEvent();
}
});
this.fetchLoadEvent = function(){
const url = arches.urls.etl_manager + "?action=loadEvent";
window.fetch(url).then(function(response){
if(response.ok){
return response.json();
}
}).then(function(data){
data.sort((a,b) => Date.parse(b.load_start_time) - Date.parse(a.load_start_time));
self.loadEvents(data);
self.selectedLoadEvent(data[0]);
});
};
this.cleanLoadEvent = function(loadid) {
const url = arches.urls.etl_manager + "?action=cleanEvent&loadid="+loadid;
window.fetch(url).then(function(response){
if(response.ok){
return response.json();
}
}).then(function(data){
console.log(data);
self.init();
self.activeTab("import");
});
};
this.reverseTransactions = function(loadid) {
self.loading(true);
window.fetch(arches.urls.transaction_reverse(loadid),{
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
}).then(function(response) {
return response.json();
}).then(function() {
self.loading(false);
});
};
this.formatUserName = function(event){
if (event.first_name || event.last_name) {
return [event.first_name, event.last_name].join(" ");
} else {
return event.username;
}
};
this.fetchStagedData = function(loadid){
const url = arches.urls.etl_manager + "?action=stagedData&loadid="+loadid;
window.fetch(url).then(function(response){
if(response.ok){
return response.json();
}
}).then(function(data){
console.log(data);
});
};
this.fetchValidation = function(loadid){
const url = arches.urls.etl_manager + "?action=validate&loadid="+loadid;
window.fetch(url).then(function(response){
if(response.ok){
return response.json();
}
}).then(function(data){
self.validated(true);
self.validationError(data.data);
});
};
this.formatTime = function(timeString){
if (timeString){
const timeObject = new Date(timeString);
return timeObject.toLocaleString();
} else {
return null;
}
};
this.timeDifference = function(endTime, startTime){
let timeDiff = new Date(endTime) - new Date(startTime);
const hours = Math.floor(timeDiff / 3600000);
timeDiff -= hours * 3600000;
const minutes = Math.floor(timeDiff / 60000);
timeDiff -= minutes * 60000;
const seconds = Math.floor(timeDiff / 1000);
return `${hours}:${('0' + minutes).slice(-2)}:${('0' + seconds).slice(-2)}`;
};
this.init = function(){
const url = arches.urls.etl_manager + "?action=modules";
window.fetch(url).then(function(response){
if(response.ok){
return response.json();
}
}).then(function(data){
self.etlModules = data.map(function(etl){
etl.alert = self.alert;
require([etl.component]);
return etl;
});
self.loading(false);
});
this.activeTab("start");
};
this.init();
},
template: { require: 'text!templates/views/components/plugins/etl-manager.htm' }
});
});
| JavaScript | 0 | @@ -32,16 +32,33 @@
ckout',%0A
+ 'js-cookie',%0A
'arc
@@ -81,16 +81,25 @@
n($, ko,
+ Cookies,
arches)
@@ -2872,42 +2872,47 @@
-'Content-Type': 'application/jso
+%22X-CSRFToken%22: Cookies.get('csrftoke
n'
+)
%0A
|
3797a36cc083a0a4566d54e999ac80b6ebdc4278 | Create algorithm to calculate text color by background colour | src/Oro/Bundle/CalendarBundle/Resources/public/js/calendar/color-manager.js | src/Oro/Bundle/CalendarBundle/Resources/public/js/calendar/color-manager.js | /*jslint nomen:true*/
/*global define*/
define(['underscore'], function (_) {
'use strict';
/**
* @export orocalendar/js/calendar/color-manager
* @class orocalendar.calendar.colorManager
*/
var ColorManager = {
/**
* A list of text/background colors are used to determine colors of events of connected calendars
* @property {Array}
*/
colors: [
'AC725E', 'D06B64', 'F83A22', 'FA573C', 'FF7537', 'FFAD46', '42D692', '16A765',
'7BD148', 'B3DC6C', 'FBE983', 'FAD165', '92E1C0', '9FE1E7', '9FC6E7', '4986E7',
'9A9CFF', 'B99AFF', 'C2C2C2', 'CABDBF', 'CCA6AC', 'F691B2', 'CD74E6', 'A47AE2'
],
/** @property {String} */
defaultColor: null,
/** @property {Object} */
calendarColors: null,
initialize: function () {
this.defaultColor = this.findColors('4986E7');
this.calendarColors = {};
},
setCalendarColors: function (calendarId, backgroundColor) {
this.calendarColors[calendarId] = {
color: '#' + this.getColor(backgroundColor),
backgroundColor: '#' + backgroundColor
};
},
removeCalendarColors: function (calendarId) {
if (!_.isUndefined(this.calendarColors[calendarId])) {
delete this.calendarColors[calendarId];
}
},
getCalendarColors: function (calendarId) {
return this.calendarColors[calendarId];
},
applyColors: function (obj, getLastBackgroundColor) {
if (_.isEmpty(obj.color) && _.isEmpty(obj.backgroundColor)) {
var colors = this.findNextColors(getLastBackgroundColor());
obj.backgroundColor = colors;
} else if (_.isEmpty(obj.backgroundColor)) {
obj.backgroundColor = this.defaultColor;
}
obj.color = this.getColor(obj.backgroundColor);
},
findColors: function (bgColor) {
if (_.isEmpty(bgColor)) {
return this.findColors(this.defaultColor);
}
bgColor = bgColor.toUpperCase();
var result = _.find(this.colors, function (item) { return item === bgColor; });
if (_.isUndefined(result)) {
result = this.findColors(this.defaultColor);
}
return result;
},
findNextColors: function (bgColor) {
if (_.isEmpty(bgColor)) {
return this.findColors(this.defaultColor);
}
bgColor = bgColor.toUpperCase();
var i = -1;
_.each(this.colors, function (item, index) {
if (item === bgColor) {
i = index;
}
});
if (i === -1) {
return this.findColors(this.defaultColor);
}
if ((i + 1) === _.size(this.colors)) {
return _.first(this.colors);
}
return this.colors[i + 1];
},
hex2rgb: function (hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
},
rgb2hex: function (r, g, b) {
var filter = function(dec) {
var hex = dec.toString(16).toUpperCase();
return hex.length == 1 ? '0' + hex : hex;
}
return filter(r) + filter(g) + filter(b)
},
/**
* Calculates contrast color
* @see http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
*
* @param backgroundColor {string} The background color in sixdigit hexadecimal form.
* @returns {string|null} Calculated sufficient contrast color, currently black or white.
*/
getColor: function(backgroundColor) {
var color = this.hex2rgb(backgroundColor);
if (color) {
var d = 0;
var a = 1 - (0.299 * color.r + 0.587 * color.g + 0.114 * color.b) / 255;
if (a < 0.5) {
d = 0;
} else {
d = 255;
}
return this.rgb2hex(d, d, d);
}
}
};
return function () {
var obj = _.extend({}, ColorManager);
obj.initialize();
return obj;
};
});
| JavaScript | 0 | @@ -272,13 +272,8 @@
of
-text/
back
@@ -1117,24 +1117,32 @@
+ this.getCo
+ntrastCo
lor(backgrou
@@ -1971,16 +1971,24 @@
is.getCo
+ntrastCo
lor(obj.
@@ -3490,16 +3490,17 @@
function
+
(dec) %7B%0A
@@ -3593,16 +3593,17 @@
ength ==
+=
1 ? '0'
@@ -3621,32 +3621,33 @@
x;%0A %7D
+;
%0A ret
@@ -3683,16 +3683,17 @@
ilter(b)
+;
%0A
@@ -3844,47 +3844,24 @@
ram
-backgroundColor %7Bstring%7D The background
+%7Bstring%7D color A
col
@@ -4001,26 +4001,24 @@
*
-/%0A
getColor
@@ -4013,152 +4013,189 @@
-getColor: function(backgroundColor) %7B%0A var color = this.hex2rgb(backgroundColor);%0A if (color) %7B%0A var d = 0;
+ If the given color is invalid or cannot be parsed, returns black.%0A */%0A getContrastColor: function (color) %7B%0A var rgb = this.hex2rgb(color),
%0A
@@ -4211,80 +4211,77 @@
-var a = 1 - (0.
+yiq = rgb ? ((
299 *
-color
+rgb
.r +
-0.
587 *
-color
+rgb
.g +
-0.
114 *
-color.b) /
+rgb.b) / 1000) :
255
-;
+,
%0A
@@ -4297,181 +4297,153 @@
-if (a %3C 0.5) %7B%0A d = 0;%0A %7D else %7B%0A d = 255;%0A %7D%0A return this.rgb2hex(d, d, d);%0A %7D
+clrDiff = rgb ? (rgb.r + rgb.g + rgb.b) : 0;%0A return yiq %3E 125 && clrDiff %3E 500 ? this.rgb2hex(0, 0, 0) : this.rgb2hex(255, 255, 255);
%0A
|
c88adb0c96b694bf240595f2ceb13469f5e223f7 | Bump commit. | assets/js/components/surveys/CurrentSurvey.stories.js | assets/js/components/surveys/CurrentSurvey.stories.js | /**
* CurrentSurvey Component Stories.
*
* Site Kit by Google, Copyright 2021 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
import { provideSiteInfo } from '../../../../tests/js/test-utils';
import WithRegistrySetup from '../../../../tests/js/WithRegistrySetup';
import CurrentSurvey from './CurrentSurvey';
const Template = ( args ) => <CurrentSurvey { ...args } />;
export const CurrentSurveyStory = Template.bind( {} );
CurrentSurveyStory.storyName = 'CurrentSurvey';
export default {
title: 'Components/Surveys',
decorators: [
( Story ) => {
const triggerID = 'test-survey';
const survey = {
survey_payload: 'foo',
session: 'bar',
};
const setupRegistry = async ( registry ) => {
provideSiteInfo( registry );
registry.dispatch( CORE_USER ).receiveTriggerSurvey( survey, { triggerID } );
await registry.dispatch( CORE_USER ).triggerSurvey( triggerID, { ttl: 1 } );
};
return (
<WithRegistrySetup func={ setupRegistry }>
<Story />
</WithRegistrySetup>
);
},
],
};
| JavaScript | 0 | @@ -1372,24 +1372,25 @@
registry );%0A
+%0A
%09%09%09%09registry
|
1e9b2a8aaa001a0a1abb06bc924d41eea8e48e12 | Fix broken tests. | assets/js/googlesitekit/datastore/site/errors.test.js | assets/js/googlesitekit/datastore/site/errors.test.js | /**
* `core/site` data store: Errors tests.
*
* Site Kit by Google, Copyright 2021 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import { STORE_NAME } from './constants';
import { createTestRegistry } from '../../../../../tests/js/utils';
describe( 'core/site errors', () => {
const internalServerError = {
id: `module-setup-error`,
title: 'Internal Server Error',
description: 'Test error message',
format: 'small',
type: 'win-error',
};
let registry;
let store;
beforeEach( () => {
registry = createTestRegistry();
store = registry.stores[ STORE_NAME ].store;
} );
describe( 'actions', () => {
describe( 'setInternalServerError', () => {
it( 'should require the internalServerError param', () => {
expect( () => {
registry.dispatch( STORE_NAME ).setInternalServerError();
} ).toThrow( 'internalServerError is required.' );
} );
it( 'adds error to the state', () => {
registry.dispatch( STORE_NAME ).setInternalServerError( internalServerError );
expect( store.getState() ).toMatchObject( { internalServerError } );
} );
} );
describe( 'clearInternalServerError', () => {
it( 'clears the error', () => {
registry.dispatch( STORE_NAME ).setInternalServerError( internalServerError );
expect( store.getState() ).toMatchObject( { internalServerError } );
registry.dispatch( STORE_NAME ).clearInternalServerError();
expect( store.getState().internalServerError ).toBeNull();
} );
} );
} );
describe( 'selectors', () => {
describe( 'getInternalServerError', () => {
it( 'should return the internal server error once set', () => {
registry.dispatch( STORE_NAME ).setInternalServerError( internalServerError );
expect( registry.select( STORE_NAME ).getInternalServerError() ).toEqual( internalServerError );
} );
it( 'should return an empty object when no internal server error is set', () => {
expect( registry.select( STORE_NAME ).getInternalServerError() ).toEqual( {} );
} );
} );
} );
} );
| JavaScript | 0.000004 | @@ -1277,16 +1277,37 @@
or param
+ to be a plain object
', () =%3E
@@ -1468,12 +1468,22 @@
t( '
-adds
+should set the
err
@@ -1619,35 +1619,47 @@
tState()
- ).toMatchObject( %7B
+.internalServerError ).toEqual(
interna
@@ -1666,26 +1666,24 @@
lServerError
- %7D
);%0A%09%09%09%7D );%0A
@@ -1750,24 +1750,46 @@
t( '
-clears the error
+should remove the error from the store
', (
@@ -1910,27 +1910,39 @@
te()
- ).toMatchObject( %7B
+.internalServerError ).toEqual(
int
@@ -1961,14 +1961,13 @@
rror
- %7D
);%0A
+%0A
%09%09%09%09
@@ -2085,12 +2085,17 @@
toBe
-Null
+Undefined
();%0A
@@ -2345,31 +2345,37 @@
ror );%0A%0A%09%09%09%09
-expect(
+const error =
registry.se
@@ -2409,32 +2409,51 @@
nalServerError()
+;%0A%09%09%09%09expect( error
).toEqual( inte
@@ -2506,23 +2506,17 @@
urn
-an empty object
+undefined
whe
@@ -2544,24 +2544,28 @@
error is set
+ yet
', () =%3E %7B%0A%09
@@ -2567,23 +2567,29 @@
%3E %7B%0A%09%09%09%09
-expect(
+const error =
registr
@@ -2639,23 +2639,44 @@
or()
- ).toEqual( %7B%7D
+;%0A%09%09%09%09expect( error ).toBeUndefined(
);%0A%09
|
5665684a5e15cce31299783f95b232c07f0ac927 | Tweak chroma.js sed args to work on the build system (#53) | examples/chroma.js/config.js | examples/chroma.js/config.js | export default {
cloneUrl: 'https://github.com/gka/chroma.js.git',
forkUrl: 'git@github.com:decaffeinate-examples/chroma.js.git',
useDefaultConfig: true,
extraDependencies: [
'grunt-cli',
],
expectConversionSuccess: true,
expectTestSuccess: true,
testCommand: `
set -e
find src -name '*.js' | xargs sed -i '' -e 's/\\/\\/ @require\\(.*\\)$/\\/* @require\\1 *\\//g'
git commit -a -m 'Change catty dependencies to have the proper format'
npm run build
git commit -a -m 'Rebuild chroma.js'
npm test
`,
};
| JavaScript | 0 | @@ -330,11 +330,8 @@
d -i
- ''
-e
|
355f8d3f6b289a6f2774fbb32b1997be6f2e27ef | Update tester16.js | test/tester16.js | test/tester16.js | "use strict";
const request = require("request-promise-native");
const http = require("http");
const pino = require("pino")();
const Pool = require("pg-pool");
const parseString = require("xml2js").parseString;
const debug = require("debug")("tester16");
const moment = require("moment");
const pool = new Pool({
max: 30, //set pool max size to 20
min: 10, //set min pool size to 4
idleTimeoutMillis: 10000 //close idle clie
});
setInterval(() => pino.info(controller.statistik(), "statistik"), 5000).unref();
process.on("unhandledRejection", (reason, p) => {
pino.error(reason, "Unhandled Rejection at: Promise", p);
// application specific logging, throwing an error, or other logic here
});
const agent = new http.Agent({
// keepAlive: true,
// maxFreeSockets: 500
});
const superrequest = request.defaults({
agent,
// timeout: 6000,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1" //"Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36"
}
});
//Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1
const differ = (obj) => Promise.resolve()
.then(() => {
obj.ende = moment.now("X");
obj.diff = obj.ende - obj.start;
if (obj.res) {
obj.len = obj.res.length;
} else {
obj.len = null;
}
parseString(obj.res, {
explicitArray: true
}, (err, result) => {
//debug("hier",err,result);
});
// debug(obj);
})
.then(() => pool.query(`insert into weblog
( start, ende, url , message ,len,data )
values($1,$2,$3,$4,$5,$6 )`, [obj.start, obj.ende, obj.url, obj.message || "", obj.len, obj.res || ""]))
.then(() => {
if (obj.message) {
throw new Error("Fehler:" + obj.message);
} else {
delete obj.res;
return obj;
}
});
const crawler =
(obj) => Promise.resolve(obj)
.then(() => pool.query("select 'http://'||url as url from weburl where id = $1", [obj.id]))
.then((res) => {
if (res.rows.length === 1) {
Object.assign(obj, res.rows[0]);
}
return obj;
})
.then((obj) => pool.query("select count(*) anz,max(ende-start) maxer,min(ende-start) miner from weblog where url = $1 group by url", [obj.url]))
.then((res) => {
if (res.rows.length === 1) {
Object.assign(obj, res.rows[0]);
}
obj.start = moment.now("X");
obj.message = null;
return obj;
})
.then((obj) => superrequest({
uri: obj.url
}))
.then((res) => Object.assign(obj, {
res
}))
.catch((err) => Object.assign(obj, {
message: err.message
}))
.then(differ);
//pino.info("vor start %d", webber.length);
pool.on("error", (error, client) => {
// handle this in the same way you would treat process.on('uncaughtException')
// it is supplied the error as well as the idle client which received the error
pino.error(error, "pg-pool", client);
});
const Controller = require("./controller2.js");
const controller = new Controller({
parallel: 40,
limit: 30000,
//limit : 100,
fun: crawler
});
Promise.resolve()
.then(() => pool.query("select id from weburl order by id"))
.then((res) => controller.runner(res.rows))
.then((x) => {
pino.info(x, "finished");
pool.end();
})
.catch((err) => {
pool.end();
pino.error(err[0], "exit with errors: %d", err.length);
});
| JavaScript | 0.000001 | @@ -1391,16 +1391,56 @@
%7D%0A%0A
+ return new Promise((resolve, reject) =%3E
parseSt
@@ -1517,41 +1517,109 @@
-//debug(%22hier%22,err,result
+if (err) %7B%0A //reject(err);%0A resolve();%0A %7D else %7B%0A resolve(
);%0A
+
-%7D
+ %7D%0A %7D)
);%0A
|
ba4a9b34329268a60d73e049779f9f2180c06ae6 | Fix masonry. | assets/themes/sangria/js/main.js | assets/themes/sangria/js/main.js | $(document).ready(function() {
// instagram feed
var feed = new Instafeed({
clientId: 'babb8453913c4c7f87f210172eed1166',
accessToken: '4044782518.babb845.cdfe6f09843d4f0f885c2882b9c161d5',
get: 'user',
userId: '4044782518',
limit: 7,
resolution: 'thumbnail',
template: '<div class="footer-instagram-el tn-col-7">' +
'<a class="footer-instagram-link cursor-zoom" href="{{link}}" target="_blank">' +
'<img alt="{{post.title}}" '+ 'src="{{image}}"></a>'+
'</div>'
});
feed.run();
$('#tn-button-mobile-menu-open').click(function() {
$('body').toggleClass('open-menu-mobile');
});
$('.main-content-inner').masonry({
// options
itemSelector: '.masonry-el',
columnWidth: 300,
transitionDuration: '0.2s'
});
}); | JavaScript | 0.000001 | @@ -686,12 +686,12 @@
$('.
-main
+ruby
-con
@@ -699,13 +699,12 @@
ent-
-inner
+wrap
').m
|
d5ec31123e8824902550c60200c798cc0a9fecbe | Document lastActivityResultParser middleware. | lib/junction/middleware/lastActivityResultParser.js | lib/junction/middleware/lastActivityResultParser.js | module.exports = function lastActivityResultParser(options) {
options = options || {};
return function lastActivityResultParser(stanza, next) {
if (!stanza.is('iq')) { return next(); }
if (stanza.type != 'result') { return next(); }
var query = stanza.getChild('query', 'jabber:iq:last');
if (!query) { return next(); }
stanza.lastActivity = query.attrs.seconds;
stanza.lastStatus = query.getText();
next();
}
}
| JavaScript | 0 | @@ -1,92 +1,596 @@
-module.exports = function lastActivityResultParser(options) %7B%0A options = options %7C%7C %7B%7D;
+/**%0A * Parse information about the last activity associated with an XMPP entity.%0A *%0A * This middleware parses last activity information contained within IQ-result%0A * stanzas. %60stanza.lastActivity%60 indicates the time of last activity of the%0A * entity, in seconds. %60stanza.lastStatus%60 indicates last status of the entity.%0A *%0A * Examples:%0A *%0A * connection.use(junction.lastActivityResultParser());%0A *%0A * References:%0A * - %5BXEP-0012: Last Activity%5D(http://xmpp.org/extensions/xep-0012.html)%0A *%0A * @return %7BFunction%7D%0A * @api public%0A */%0A%0Amodule.exports = function lastActivityResultParser() %7B
%0A %0A
|
cd002bfa5a5283f5f16744ee4e2b87219e342d97 | fix panels | app/assets/javascripts/scripts/plugins/panel/element/panel.element.js | app/assets/javascripts/scripts/plugins/panel/element/panel.element.js | /**
* Created with JetBrains RubyMine.
* User: teamco
* Date: 5/9/13
* Time: 11:48 AM
*/
/**
* @constant PluginElement
* @type {module.PluginElement}
*/
const PluginElement = require('../../plugin.element.js');
/**
* Define Panel Element
* @class PanelElement
* @extends PluginElement
*/
module.exports = class PanelElement extends PluginElement {
/**
* @param {PanelView} view
* @param opts
* @constructor
*/
constructor(view, opts) {
super('PanelElement', view, false);
this._config(view, opts, $(this.getTemplate())).build(opts);
/**
* Fetch panel header
* @property PanelElement
*/
this.header = this.view.scope.model.getConfig('header');
this.addCSS('panel');
this.setPanelHeader();
return this;
}
/**
* Define template
* @memberOf PanelElement
* @returns {string}
*/
getTemplate() {
return [
'<nav class="navbar-default navbar-static-side" role="navigation">',
'<div class="sidebar-collapse">',
'<ul></ul></div></nav>'
].join('');
}
/**
* Define content container
* @memberOf PanelElement
* @returns {*}
*/
getContentContainer() {
return this.$.find('ul:first');
}
/**
* Toggle open/close
* @param {string} resource
* @memberOf PanelElement
* @returns {boolean}
*/
toggleModule(resource) {
// Define locals
var view = this.view,
scope = view.scope;
scope.observer.publish(
scope.eventManager.eventList.showContent,
resource
);
}
/**
* Define header wrapper
* @memberOf PanelElement
*/
setPanelHeader() {
const $tpl = $('<li class="nav-header" />'),
header = this.header;
if (header && this.view.utils.setBoolean(header.visible, true)) {
$tpl.appendTo(this.$.find('ul:first'));
this.setLongHeader();
this.setShortHeader();
this.$.removeClass('no-title');
} else {
this.$.addClass('no-title');
}
}
/**
* Define long header wrapper
* @memberOf PanelElement
*/
getLongHeaderWrapper() {
const $tpl = $('<div class="profile-element text-center"><h1 class="logo-element"></h1></div>'),
title = this.header.title;
if (title && title.long) {
$tpl.find('.logo-element').text(title.long);
$tpl.appendTo(this.$.find('.nav-header'));
}
}
/**
* Define short header wrapper
* @memberOf PanelElement
*/
getShortHeaderWrapper() {
const $tpl = $('<div class="logo-element" />'),
title = this.header.title;
if (title && title.short) {
$tpl.find('.logo-element').text(title.short);
$tpl.appendTo(this.$.find('.nav-header'));
}
}
/**
* Hide Active module
* @memberOf PanelElement
*/
hideActiveModule() {
this.view.elements.items[this.getContentItemIndex()].hide();
}
/**
* Show Active module
* @memberOf PanelElement
*/
showActiveModule() {
this.view.elements.items[this.getContentItemIndex()].show();
}
/**
* Get item index
* @memberOf PanelElement
* @returns {string}
*/
getContentItemIndex() {
return ['$', this.view.controller.getActiveResource(), '-content'].join('');
}
}; | JavaScript | 0.000001 | @@ -2052,17 +2052,17 @@
*/%0A
-g
+s
etLongHe
@@ -2061,31 +2061,24 @@
etLongHeader
-Wrapper
() %7B%0A%0A co
@@ -2425,17 +2425,17 @@
*/%0A
-g
+s
etShortH
@@ -2443,15 +2443,8 @@
ader
-Wrapper
() %7B
|
2ff1def4549d14c9cb2d93db5857767978eecb35 | Change run radius to 0.2 miles for physical test | client/app/services/services.js | client/app/services/services.js | angular.module('bolt.services', [])
.factory('Geo', function () {
var mainMap;
var currentLocMarker;
var destinationMarker;
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var route;
var makeInitialMap = function($scope) {
navigator.geolocation.getCurrentPosition(function(position) {
makeMap({lat: position.coords.latitude, lng: position.coords.longitude}, $scope);
}, function(err) {
console.error(err);
});
var makeMap = function(currentLatLngObj, $scope) {
var destinationCoordinates = randomCoordsAlongCircumference(currentLatLngObj, 1);
$scope.destination = destinationCoordinates;
mainMap = new google.maps.Map(document.getElementById('map'), {
center: currentLatLngObj,
zoom: 13
});
directionsRenderer.setMap(mainMap);
currentLocMarker = new google.maps.Marker({
position: currentLatLngObj,
map: mainMap,
animation: google.maps.Animation.DROP,
icon: '/assets/bolt.png'
});
destinationMarker = new google.maps.Marker({
position: destinationCoordinates,
map: mainMap,
animation: google.maps.Animation.DROP,
icon: '/assets/finish-line.png' // change to finish line image
});
var startOfRoute = new google.maps.LatLng(currentLocMarker.position.lat(), currentLocMarker.position.lng());
var endOfRoute = new google.maps.LatLng(destinationMarker.position.lat(), destinationMarker.position.lng());
route = directionsService.route({
origin: startOfRoute,
destination: endOfRoute,
travelMode: google.maps.TravelMode.WALKING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: false
}, function(response, status) {
directionsRenderer.setDirections(response);
console.log('response:');
console.log(response);
var totalDistance = 0;
for (var i = 0; i < response.routes[0].legs.length; i++) {
totalDistance += response.routes[0].legs[i].distance.text;
}
console.log('total distance: ', totalDistance);
});
};
};
var updateCurrentPosition = function($scope) {
console.log($scope);
navigator.geolocation.getCurrentPosition(function(position) {
currentLocMarker.setPosition({lat: position.coords.latitude, lng: position.coords.longitude});
if ($scope) {
$scope.userLocation= {lat: position.coords.latitude, lng: position.coords.longitude};
}
console.log(currentLocMarker);
}, function(err) {
console.error(err);
});
};
function randomCoordsAlongCircumference (originObj, radius) {
var randomTheta = Math.random() * 2 * Math.PI;
console.log('randomTheta');
return {
lat: originObj.lat + (radius / 69 * Math.cos(randomTheta)),
lng: originObj.lng + (radius / 69 * Math.sin(randomTheta))
};
};
return {
makeInitialMap: makeInitialMap,
updateCurrentPosition: updateCurrentPosition
};
})
.factory('Run', function(){
// Kyle's code here
// Kyle's code here
// Kyle's code here
// Kyle's code here
})
.factory('Auth', function ($http, $location, $window) {
// Don't touch this Auth service!!!
// it is responsible for authenticating our user
// by exchanging the user's username and password
// for a JWT from the server
// that JWT is then stored in localStorage as 'com.bolt'
// after you signin/signup open devtools, click resources,
// then localStorage and you'll see your token from the server
var signin = function (user) {
return $http({
method: 'POST',
url: '/api/users/signin',
data: user
})
.then(function (resp) {
return resp.data.token;
});
};
var signup = function (user) {
return $http({
method: 'POST',
url: '/api/users/signup',
data: user
})
.then(function (resp) {
return resp.data.token;
});
};
var isAuth = function () {
return !!$window.localStorage.getItem('com.bolt');
};
var signout = function () {
$window.localStorage.removeItem('com.bolt');
$location.path('/signin');
};
return {
signin: signin,
signup: signup,
isAuth: isAuth,
signout: signout
};
});
| JavaScript | 0 | @@ -659,17 +659,19 @@
LngObj,
-1
+0.2
);%0A
|
6d319f9f31a6e62b48dd9c40c7565039317a9098 | update the fetch code script | scripts/fetch-question.js | scripts/fetch-question.js | const { writeFileSync, closeSync, openSync, existsSync } = require('fs');
const { resolve } = require('path');
const { get } = require('request');
const { load } = require('cheerio');
const { prompt } = require('inquirer');
const { info } = require('better-console');
const { clearConsole, traverseNode, unicodeToChar, createFiles } = require('./util.js');
const ALGORITHM_URL = `https://leetcode.com/api/problems/algorithms/`;
const QUESTION_URL = slug => `https://leetcode.com/problems/${slug}/`;
const PROGRAM_URL = slug => resolve(__dirname, `../programs/${slug}.js`);
const FETCH_JS_RE = /{\'value\': \'javascript\'[\w\W\s]+?\},/;
const FETCH_CODE_RE = /\/\*\*[\w\W\s]+?\};/;
const difficultyMap = { 1: 'Easy', 2: 'Medium', 3: 'Hard' };
const questionTitle = question => {
let { difficulty, paid_only, stat } = question;
let { question_id, question__title, total_acs, total_submitted } = stat;
let { level } = question.difficulty;
return `${question_id}\t${difficultyMap[level]}\t${(total_acs / total_submitted * 100).toString().slice(0, 4)}%\t${question__title}`;
};
const questionOption = question => {
let { paid_only, stat } = question;
let { question__article__slug, question__title_slug } = stat;
let slug = question__title_slug || question__article__slug;
let solved = existsSync(PROGRAM_URL(slug));
if (paid_only) {
return { name: questionTitle(question), disabled: 'Paid only' };
} else if (solved) {
return { name: questionTitle(question), disabled: 'Solved'};
} else {
return questionTitle(question);
}
};
const mapTitleToQuestion = questions => questions.reduce((pre, curr) => {
pre[questionTitle(curr)] = curr;
return pre;
}, {});
const getQuestions = url => new Promise((resolve, reject) => {
get(url).on('response', res => {
res.setEncoding('utf8');
let chunk = '';
res.on('data', data => chunk += data);
res.on('error', err => reject(err));
res.on('end', () => resolve(JSON.parse(chunk).stat_status_pairs));
});
});
const showQuestionSelection = questions => {
titleQuestionMap = mapTitleToQuestion(questions);
return prompt({
type : 'list',
name : 'title',
message : 'Which problem do you want to solve?',
choices : questions.map(questionOption)
});
};
const getQuestionContent = title => new Promise((resolve, reject) => {
let question = titleQuestionMap[title];
let { question__article__slug, question__title_slug } = question.stat;
let selectedQuestionSlug = question__title_slug || question__article__slug;
get(QUESTION_URL(selectedQuestionSlug)).on('response', res => {
let chunk = '';
res.on('data', data => chunk += data);
res.on('error', err => reject(err));
res.on('end', () => {
const $ = load(chunk);
resolve({
slug : selectedQuestionSlug,
code : unicodeToChar($('.container[ng-app=app]')[0].attribs['ng-init']).match(FETCH_JS_RE)[0].match(FETCH_CODE_RE)[0],
description : $('meta[name=description]')[0].attribs['content'],
});
});
});
});
const actionToQuestion = question => {
let { slug, code, description } = question;
info(`\n${description}`);
prompt({
type : 'list',
name : 'action',
message : 'Do you want to solve the problem?',
choices : ['Yes', 'No']
}).then(answer => {
switch (answer.action) {
case 'Yes':
createFiles(slug, code);
return;
case 'No':
SelectAndSolve();
return;
default:
return;
}
});
};
const SelectAndSolve = () => {
clearConsole();
getQuestions(ALGORITHM_URL).then(
questions => showQuestionSelection(questions),
err => Promise.reject(err)
).then(
answer => getQuestionContent(answer.title),
err => Promise.reject(err)
).then(
question => actionToQuestion(question)
);
};
SelectAndSolve();
| JavaScript | 0.000001 | @@ -2267,24 +2267,434 @@
)%0A %7D);%0A%7D;%0A%0A
+const getInfosFromPagedata = $ =%3E %7B%0A eval($('script').toArray().find(elem =%3E %7B%0A return elem.children.length && elem.children%5B0%5D.data.includes('pageData');%0A %7D).children%5B0%5D.data);%0A%0A return %7B%0A slug: pageData.questionTitleSlug,%0A code: pageData.codeDefinition.find(definition =%3E 'javascript' === definition.value).defaultCode,%0A description: $('meta%5Bname=description%5D')%5B0%5D.attribs%5B'content'%5D%0A %7D;%0A%7D;%0A%0A
const getQue
@@ -3151,305 +3151,49 @@
-const $ = load(chunk);%0A resolve(%7B%0A slug : selectedQuestionSlug,%0A code : unicodeToChar($('.container%5Bng-app=app%5D')%5B0%5D.attribs%5B'ng-init'%5D).match(FETCH_JS_RE)%5B0%5D.match(FETCH_CODE_RE)%5B0%5D,%0A description : $('meta%5Bname=description%5D')%5B0%5D.attribs%5B'content'%5D,%0A %7D
+resolve(getInfosFromPagedata(load(chunk))
);%0A
|
d10344f39364a4db39b221aeb1532b71cb7aefc4 | replace d3 sort / each | client/route-card-view/index.js | client/route-card-view/index.js | var analytics = require('analytics');
var d3 = require('d3');
var convert = require('convert');
var Feedback = require('feedback-modal');
var mouseenter = require('mouseenter');
var mouseleave = require('mouseleave');
var Calculator = require('route-cost-calculator');
var RouteDirections = require('route-directions-table');
var RouteModal = require('route-modal');
var routeSummarySegments = require('route-summary-segments');
var routeResource = require('route-resource');
var session = require('session');
//var transitive = require('transitive');
var view = require('view');
var showMapView = require('map-view');
/**
* Expose `View`
*/
var View = module.exports = view(require('./template.html'), function(view, model) {
mouseenter(view.el, function() {
var itineration = JSON.parse(localStorage.getItem('itineration'));
for (var i=0; i<itineration.length;i++) {
var r3 = d3.selectAll(".iteration-"+i);
if (i!=model.index){
r3.transition().duration(600).style("stroke", "#E0E0E0");
r3.attr("data-show","0");
var rec2 = d3.selectAll(".circle-fade-"+i);
- rec2.attr('class', 'leaflet-marker-icon leaflet-div-icon2 circle-fade-'+i+ ' leaflet-zoom-hide');
}else {
r3.attr("data-show","1");
}
}
d3.selectAll(".iteration-200").each(function(e){
var element = d3.select(this);
var parent = d3.select(element.node().parentNode);
parent.attr("class", "g-element");
if (Boolean(parseInt(element.attr("data-show")))) {
parent.attr("data-show", "1");
}else {
parent.attr("data-show", "0");
}
});
d3.selectAll(".g-element")[0].sort(function(a,b){
if (Boolean(parseInt(d3.select(a).attr("data-show")))) {
d3.select(a).node().parentNode.appendChild(a);
}
});
});
mouseleave(view.el, function() {
showMapView.cleanPolyline();
showMapView.cleanMarkerpoint();
showMapView.cleanMarkerCollision();
showMapView.marker_collision_group = [];
var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
sesion_plan = sesion_plan.plan;
var itineraries = sesion_plan.itineraries;
for (var i= 0; i < itineraries.length; i++) {
for (var j=0; j < itineraries[i].legs.length; j++) {
showMapView.drawRouteAmigo(itineraries[i].legs[j], itineraries[i].legs[j].mode, i);
}
}
showMapView.drawMakerCollision();
});
});
View.prototype.calculator = function() {
return new Calculator(this.model);
};
View.prototype.directions = function() {
return new RouteDirections(this.model);
};
View.prototype.segments = function() {
return routeSummarySegments(this.model);
};
View.prototype.costSavings = function() {
return convert.roundNumberToString(this.model.costSavings());
};
View.prototype.timeSavingsAndNoCostSavings = function() {
return this.model.timeSavings() && !this.model.costSavings();
};
/**
* Show/hide
*/
View.prototype.showDetails = function(e) {
e.preventDefault();
var el = this.el;
var expanded = document.querySelector('.option.expanded');
if (expanded) expanded.classList.remove('expanded');
el.classList.add('expanded');
analytics.track('Expanded Route Details', {
plan: session.plan().generateQuery(),
route: {
modes: this.model.modes(),
summary: this.model.summary()
}
});
var scrollable = document.querySelector('.scrollable');
scrollable.scrollTop = el.offsetTop - 52;
};
View.prototype.hideDetails = function(e) {
e.preventDefault();
var list = this.el.classList;
if (list.contains('expanded')) {
list.remove('expanded');
}
};
/**
* Get the option number for display purposes (1-based)
*/
View.prototype.optionNumber = function() {
return this.model.index + 1;
};
/**
* View
*/
View.prototype.feedback = function(e) {
e.preventDefault();
Feedback(this.model).show();
};
/**
* Select this option
*/
View.prototype.selectOption = function() {
var route = this.model;
var plan = session.plan();
var tags = route.tags(plan);
analytics.send_ga({
category: 'route-card',
action: 'select route',
label: JSON.stringify(tags),
value: 1
});
routeResource.findByTags(tags, function(err, resources) {
var routeModal = new RouteModal(route, null, {
context: 'route-card',
resources: resources
});
routeModal.show();
routeModal.on('next', function() {
routeModal.hide();
});
});
};
| JavaScript | 0.000082 | @@ -1783,16 +1783,13 @@
nt%22)
-%5B0%5D.sort
+.each
(fun
@@ -1843,17 +1843,20 @@
.select(
-a
+this
).attr(%22
@@ -1898,17 +1898,20 @@
.select(
-a
+this
).node()
@@ -1934,17 +1934,20 @@
ndChild(
-a
+this
);%0A
|
273127f22166c690d97bfb1d0ee3396117857116 | Add missing semi-colons. | website/app/application/core/projects/dataedit/reviews/review-controller.js | website/app/application/core/projects/dataedit/reviews/review-controller.js | Application.Controllers.controller('projectsDataEditCreateReview',
["$scope", "mcapi", "User", "$stateParams", "alertService", "pubsub", "$state","dateGenerate", "$filter",
function ($scope, mcapi, User, $stateParams, alertService, pubsub, $state, dateGenerate, $filter) {
$scope.addReview = function () {
$scope.review = {messages: []}
$scope.review.item_id = $scope.doc.id;
$scope.review.item_type = 'datafile';
$scope.review.item_name = $scope.doc.name;
$scope.review.author = User.u();
$scope.review.assigned_to = $scope.model.assigned_to;
$scope.review.status = 'open';
$scope.review.title = $scope.model.title;
$scope.review.messages.push({'message': $scope.model.new_review, 'who': User.u(), 'date': dateGenerate.new_date()});
$scope.saveData();
};
$scope.saveData = function () {
mcapi('/reviews')
.success(function (data) {
$state.go('projects.dataedit.editreviews', {'review_id': data.id})
$scope.model.new_review = "";
}).post($scope.review);
};
$scope.viewReview = function(review){
$state.go('projects.dataedit.editreviews', {'review_id': review.id})
}
$scope.showReviews = function(status){
$scope.status = status;
if(status === 'open'){
$scope.list_reviews = $scope.open_reviews;
}
else if(status === 'close'){
$scope.list_reviews = $scope.closed_reviews;
}
}
$scope.loadReviews = function(id){
mcapi('/datafiles/%/reviews', $stateParams.data_id)
.success(function (reviews) {
$scope.open_reviews = $filter('reviewFilter')(reviews, 'open');
$scope.closed_reviews = $filter('reviewFilter')(reviews, 'close');
$scope.list_reviews = $scope.open_reviews;
$scope.status = 'open'
pubsub.send('open_reviews.change')
}).jsonp();
}
function init() {
$scope.list_reviews = [];
$scope.loadReviews();
mcapi('/datafile/%', $stateParams.data_id)
.success(function (data) {
$scope.datafile = data;
}).jsonp();
$scope.model = {
new_review: "",
assigned_to: "",
title: ""
};
mcapi('/selected_users')
.success(function (data) {
$scope.users = data;
}).jsonp();
}
init();
}]); | JavaScript | 0.003646 | @@ -369,17 +369,18 @@
ges: %5B%5D%7D
+;
%0A
-
@@ -1158,24 +1158,25 @@
': data.id%7D)
+;
%0A
@@ -1411,16 +1411,17 @@
iew.id%7D)
+;
%0A
@@ -1418,32 +1418,33 @@
);%0A %7D
+;
%0A $sc
@@ -1772,32 +1772,33 @@
%7D%0A %7D
+;
%0A $sc
@@ -2240,16 +2240,17 @@
= 'open'
+;
%0A
@@ -2300,16 +2300,17 @@
change')
+;
%0A
@@ -2339,32 +2339,33 @@
);%0A %7D
+;
%0A fun
@@ -2999,24 +2999,24 @@
init();%0A%0A
-
%7D%5D);
@@ -3015,8 +3015,9 @@
%7D%5D);
+%0A
|
3d1ba11cbb1b728dd4b7b71d32a2d723cfd22b83 | rename getComponent argument location to nextState | chapter-10/react_router_chunked/src/Routes.js | chapter-10/react_router_chunked/src/Routes.js | import React from 'react';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import {Provider} from 'react-redux';
import {syncHistoryWithStore} from 'react-router-redux';
import App from './pages/App.js';
//import Home from './pages/Home.js';
//import About from './pages/About.js';
//import NotFound from './pages/NotFound.js';
import store from './Store.js';
const createElement = (Component, props) => {
return (
<Provider store={store}>
<Component {...props} />
</Provider>
);
};
const getHomePage = (location, callback) => {
require.ensure([], function(require) {
callback(null, require('./pages/Home.js').default);
}, 'home');
};
const getAboutPage = (location, callback) => {
require.ensure([], function(require) {
callback(null, require('./pages/About.js').default);
}, 'about');
};
const getNotFoundPage = (location, callback) => {
require.ensure([], function(require) {
callback(null, require('./pages/NotFound.js').default);
}, '404');
};
const history = syncHistoryWithStore(browserHistory, store);
//const history = browserHistory;
const Routes = () => (
<Router history={history} createElement={createElement}>
<Route path="/" component={App}>
<IndexRoute getComponent={getHomePage} />
<Route path="home" getComponent={getHomePage} />
<Route path="about" getComponent={getAboutPage} />
<Route path="*" getComponent={getNotFoundPage} />
</Route>
</Router>
);
export default Routes;
| JavaScript | 0.000001 | @@ -539,32 +539,33 @@
HomePage = (
-location
+nextState
, callback)
@@ -702,32 +702,33 @@
boutPage = (
-location
+nextState
, callback)
@@ -878,16 +878,17 @@
= (
-location
+nextState
, ca
|
c76e2d59f47d3f4a7e96dc3ef6f4fd506d865463 | hyphenate shouldnt lowercase | tests/helpers.js | tests/helpers.js | import test from 'tape'
import * as helpers from '../app/utils/helpers'
test('capitalise', t => {
const exp = 'Hello World, How Are You?'
const act = helpers.capitalise('hello world, how are you?')
t.equal(exp, act, 'Capitalise should capitalise')
t.end()
})
test('hyphenate', t => {
const exp = 'the-name-of-my-component'
const act = helpers.hyphenate('The name of my Component')
t.equal(exp, act, 'Hyphenate should hyphenate')
t.end()
})
| JavaScript | 0.99859 | @@ -303,17 +303,17 @@
exp = '
-t
+T
he-name-
@@ -318,17 +318,17 @@
e-of-my-
-c
+C
omponent
|
295f4eea3578daf7b921946aae1919224eb7ce36 | comment un-necessary stmts | tests/inf_cli.js | tests/inf_cli.js | /* informix cli using nodejs-db-informix */
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
/*
* Connection configurations
*/
// var settings = JSON.parse(require('fs').readFileSync('./tests/db_conf.json','utf8'));
var settings = {
"host": ""
, "user": ""
, "password": ""
, "database": "sysmaster"
, "charset": ""
// , "port": ""
// , "compress": ""
// , "initCommand": ""
// , "readTimeout": ""
// , "reconnect": ""
// , "socket": ""
// , "sslVerifyServer": ""
// , "timeout": ""
// , "writeTimeout": ""
};
/*
* Create a new Informix database bindings. Setup event callbacks. Connect to
* the database.
* c - connection
*/
function connect(settings) {
if (!settings || typeof(settings) !== 'object') {
throw new Error("No settings provided");
}
/*
* Create an Informix database nodejs object
*/
var bindings = require("../nodejs-db-informix");
console.log(bindings);
var c = new bindings.Informix(settings);
c.on('error', function(error) {
console.log("Error: ");
console.log(error);
}).on('ready', function(server) {
console.log("Connection ready to ");
console.log(server);
}).connect(function(err) {
if (err) {
throw new Error('Could not connect to DB');
}
console.log('Connected to db with ');
console.log(settings);
console.log("isConnected() == " + c.isConnected());
this
.on('each', function(e, idx, more) {
console.log('each');
console.log(arguments);
})
.on('success', function() {
console.log('success');
console.log(arguments);
});
/*
var rs = this.query("select first 10 * from systables", function(s,r) {
console.log(s);
console.log(r);
}).execute();
*/
var rs = this
.query(
"SELECT FIRST 10 * FROM systables"
, []
, function (status, results) {
console.log('CALLBACK:');
// console.log(arguments);
console.log("status:" + status);
console.log(results);
}
, {
start: function(q) {
console.log('Query:');
console.log(q);
}
, finish: function(f) {
console.log('Finish:');
console.log(f);
}
, async: true
, cast: true
}
)
.execute();
/*
var rs = this
.query(
""
, []
, function (status, results) {
console.log('CALLBACK:');
// console.log(arguments);
console.log("status:" + status);
console.log(results);
}
, {
start: function(q) {
console.log('Query:');
console.log(q);
}
, finish: function(f) {
console.log('Finish:');
console.log(f);
}
, async: true
, cast: true
}
)
.select("*")
.first(10)
.from("systables", false)
.execute();
*/
});
return c;
}
function execQuery(conn,qry) {
if (!conn || conn == undefined || conn == null) {
throw Error("_main: connection is not valid");
}
var rs = conn
.query(
qry
, []
, function (status, results) {
console.log('CALLBACK:');
// console.log(arguments);
console.log("status:" + status);
console.log(results);
}
, {
start: function(q) {
console.log('Query:');
console.log(q);
}
, finish: function(f) {
console.log('Finish:');
console.log(f);
}
, async: true
, cast: true
}
)
.execute();
return rs;
}
function _main () {
var conn = connect(settings);
if (!conn || conn == undefined || conn == null) {
throw Error("_main: connection is not valid");
}
console.log('connection:');
console.log(conn);
rl.setPrompt('inf> ');
rl.prompt();
rl.on('line', function(line) {
var cmd = line.trim();
if (cmd == '' || cmd == undefined || cmd == null) {
rl.prompt();
return;
}
var c_reg = /^\s*connect\s+(\w+)/;
if (c_reg.test(cmd)) {
var m = cmd.match(c_reg);
var db = m[1];
if (db == null || db == undefined || db.trim() == '') {
console.log("Invalid command: " + cmd);
rl.prompt();
return;
}
conn.disconnect();
settings.database = db;
conn = connect(settings);
} else {
execQuery(conn, cmd);
}
rl.prompt();
}).on('close', function() {
console.log('Exit.');
});
}
_main();
| JavaScript | 0.000001 | @@ -1968,24 +1968,35 @@
*/%0A%0A
+ /*%0A
var
@@ -2886,24 +2886,35 @@
.execute();
+%0A */
%0A%0A /*
|
7be9bf2a5a181b859f02c72e2c72bbc4b819b4ec | remove unused helper namespace | browserDetection.js | browserDetection.js | var rb = rb || {};
(function(ns){
var sUndetectedName = "undetected";
function getBrowserName(sUserAgent){
var retVal = sUndetectedName,
aBrowserNames = [
{detectedName:'Firefox' , contain:'Firefox\/' , notContain:'Seamonkey\/'},
{detectedName:'Seamonkey' , contain:'Seamonkey\/' , notContain:''},
{detectedName:'Chrome' , contain:'Chrome\/' , notContain:'Chromium\/'},
{detectedName:'Chromium' , contain:'Chromium\/' , notContain:''},
{detectedName:'Safari' , contain:'Safari\/' , notContain:'Chrome\/|Chrome\/'},
{detectedName:'Opera' , contain:'OPR\/|Opera\/' , notContain:''},
{detectedName:'Internet Explorer' , contain:'MSIE' , notContain:''}
];
if(sUserAgent){
for(var i=0,nLen=aBrowserNames.length; i<nLen; i++){
var browser = aBrowserNames[i];
if(sUserAgent.match(new RegExp(browser.contain),"g")&& !sUserAgent.match(new RegExp(browser.notContain,"ig"))){
retVal = browser.detectedName;
}
}
}
return retVal;
};
function getBrowserVersion(sUserAgent){
var retVal = sUndetectedName;
if(sUserAgent){
var results = sUserAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i);
if(results.length>=3){
retVal = results[2];
}
}
return retVal;
};
function getRenderEngine(sUserAgent){
var retVal = sUndetectedName;
if(sUserAgent){
var results = sUserAgent.match(/(Presto|WebKit|Gecko|Trident|Mosaic|Netscape|KTHML|Tasman|Robin|Blink|Servo|Lynx|Links)/i);
if(results.length>=2){
retVal = results[1];
}
}
return retVal;
};
function getRenderEngineVersion(sUserAgent){
var retVal = sUndetectedName;
if(sUserAgent){
var results = sUserAgent.match(/(Presto|WebKit|Gecko|Trident|Mosaic|Netscape|KTHML|Tasman|Robin|Blink|Servo|Lynx|Links(?=\/))\/?\s*([\d\.]+)/i);
if(results.length>=3){
retVal = results[2];
}
}
return retVal;
};
function getOs(sUserAgent){
var retVal = sUndetectedName;
if(sUserAgent){
if (/Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/.test(sUserAgent)){
if (RegExp["$1"] == "NT"){
switch(RegExp["$2"]){
case "5.0":
retVal = "Windows 2000";
break;
case "5.1":
retVal = "Windows XP";
break;
case "6.0":
retVal = "Windows Vista";
break;
default:
retVal = "Windows NT";
break;
}
} else if (RegExp["$1"] == "9x"){
retVal = "Windows ME";
} else {
retVal = RegExp["$1"];
}
}
var result = sUserAgent.match(/(Linux|Debian|Ubuntu|Solaris|Unix|UnixWare|SmartOS|Sinix|SCO|IRIX|HP-UX|Dynix|BSD|Sun|MacOS|Mac|BeOS|Haiku|NewOS|X11|Android|bada|blackberry|palm|symbian|meego|iOS)+/ig);
if( result ){
retVal = result.join("/");
}
}
return retVal;
};
function getBit(sUserAgent){
var retVal = 32;
if(sUserAgent){
var results = sUserAgent.match(/(x86_64|win64|wow64)/i);
if( results ){
retVal = 64;
}
}
return retVal;
};
function getMobile(sUserAgent){
var retVal = false;
if(sUserAgent){
var results = sUserAgent.match(/(mobile)/i);
if( results ){
retVal = true;
}
}
return retVal;
};
function getTablet(sUserAgent){
var retVal = false;
if(sUserAgent){
var results = sUserAgent.match(/(tablet)/i);
if( results ){
retVal = true;
}
}
return retVal;
};
ns.browserDetection = function(sUserAgent){
return {
browserName : getBrowserName(sUserAgent),
browserVersion : getBrowserVersion(sUserAgent),
renderEngine : getRenderEngine(sUserAgent),
renderEngineVersion : getRenderEngineVersion(sUserAgent),
os : getOs(sUserAgent),
bit : getBit(sUserAgent),
mobile : getMobile(sUserAgent),
tablet : getTablet(sUserAgent),
fullAgent : sUserAgent,
helper : {
}
};
};
})(rb);
| JavaScript | 0.000001 | @@ -4201,31 +4201,8 @@
gent
-,%0A%09%09%09helper%09%09%09%09: %7B%0A%09%09%09%7D
%0A%09%09%7D
|
ffac78c1eb3eb123b7ddb1574ac51fbd708293c6 | Improve validation around instance names. Fixes #35. | modules/filters.js | modules/filters.js | var utils = require('./utils');
exports.findMatchingInstances = function (name, args) {
args.instances = utils.findMatchingInstances(name);
if (args.instances.length === 0) {
utils.dieWithList('No instances found matching "' + name + '".');
return false;
}
};
exports.findFirstMatchingInstance = function (name, args) {
args.instance = utils.findFirstMatchingInstance(name);
if (!args.instance) {
utils.dieWithList('No instance found matching "' + name + '".');
return false;
}
};
exports.findMatchingCluster = function (name, args) {
var clusters = utils.getClusters();
args.cluster = clusters[name];
if (!args.cluster) {
utils.dieWithList('No clusters found matching "' + name + '".');
return false;
}
};
exports.shouldBeNewCluster = function (name, args) {
var clusters = utils.getClusters();
if (clusters[name]) {
utils.grey('The cluster "' + name + '" already exists, no action taken.');
return false;
}
};
exports.shouldBeNewInstance = function (name, args) {
var clusters = utils.getClusters();
if (!args.cluster) {
utils.grey('Using "default" cluster.');
args.cluster = 'default';
}
if (clusters[args.cluster] && clusters[args.cluster].instances[name]) {
utils.die('Instance "' + name + '" already exists.');
return false;
}
};
exports.shouldBeNewKey = function (name, args) {
if (utils.keyExists(name)) {
utils.grey('The key "' + name + '" already exists, no action taken.');
return false;
}
};
exports.shouldBeExistingKey = function (name, args) {
if (!utils.keyExists(name)) {
utils.grey('The key "' + name + '" was not found, no action taken.');
return false;
}
};
exports.shouldBeAWS = function (name, args) {
if (!args.instance || !args.instance.aws) {
utils.die('This instance has no AWS metadata attached.');
return false;
}
};
exports.shouldBeDigitalOcean = function (name, args) {
if (!args.instance || !args.instance.digitalocean) {
utils.red('This instance has no DigitalOcean metadata attached.');
utils.red('Run this command and then try again:');
utils.die('overcast digitalocean sync "' + args.instance.name + '"');
return false;
}
};
exports.shouldBeVirtualbox = function (name, args) {
if (!args.instance || !args.instance.virtualbox) {
utils.die('This instance has no Virtualbox metadata attached.');
return false;
}
};
exports.shouldBeLinode = function (name, args) {
if (!args.instance || !args.instance.linode) {
utils.red('This instance has no Linode metadata attached.');
utils.red('Run this command and then try again:');
utils.die('overcast linode sync "' + args.instance.name + '"');
return false;
}
};
| JavaScript | 0 | @@ -1186,63 +1186,438 @@
ers%5B
-args.cluster%5D && clusters%5Bargs.cluster%5D.instances%5Bname%5D
+name%5D) %7B%0A utils.die('%22' + name + '%22 is already in use as a cluster name.');%0A return false;%0A %7D else if (name === 'all') %7B%0A utils.die('%22all%22 is a special keyword that cannot be used for instance names.');%0A return false;%0A %7D else if (name.indexOf('*') !== -1) %7B%0A utils.die('Instance names cannot include asterisk characters.');%0A return false;%0A %7D else if (utils.findMatchingInstancesByInstanceName(name).length %3E 0
) %7B%0A
|
3c958f1b9c2328b7fda36c11ef76afd98202cabd | Remove login button when already authenticated | client/src/components/NavBar.js | client/src/components/NavBar.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import { format } from 'date-fns';
import {
Toolbar,
ToolbarGroup,
ToolbarTitle
} from 'material-ui/Toolbar';
import FlatButton from 'material-ui/FlatButton';
import { white } from 'material-ui/styles/colors';
import { logoutUser } from '../../redux/actions';
import FlatButtonLink from './FlatButtonLink';
class NavBar extends Component {
static defaultProps = {
currentMonth: format(new Date(), 'MMMM')
};
render () {
const {
currentMonth,
isAuthenticated,
location: { pathname },
logoutUser
} = this.props;
return (
<Toolbar>
<Link to="/" style={{ textDecoration: 'none' }}>
<ToolbarTitle text="Presence" style={{
color: white
}} />
</Link>
<ToolbarGroup>
{ isAuthenticated && [
<FlatButtonLink
key="stopwatch"
label="Stopwatch"
to="/stopwatch"
/>,
<FlatButtonLink
key="history"
label={ currentMonth }
to={ `/history/${currentMonth}` }
/>,
<FlatButton
key="logout"
label="Logout"
onClick={ logoutUser }
style={{
marginLeft: '0px',
marginRight: '0px'
}}
/>
]}
{ !isAuthenticated &&
<FlatButtonLink
key="signup"
label="Signup"
to="/signup"
/>
}
{ pathname !== '/login' &&
<FlatButtonLink
key="login"
label="Login"
to="/login"
/>
}
</ToolbarGroup>
</Toolbar>
);
}
}
export default withRouter(connect(
({ root }) => ({ isAuthenticated: root.isAuthenticated }),
{ logoutUser }
)(NavBar));
| JavaScript | 0 | @@ -2186,16 +2186,36 @@
ogin' &&
+ !isAuthenticated &&
%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.