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
|
---|---|---|---|---|---|---|---|
8a14f9edf982a9994e6cb5c7d213370db28c9aef | Optimize output if selected task was not found | src/run.js | src/run.js | "use strict";
const chalk = require("chalk");
const tildify = require("tildify");
const prettyTime = require("pretty-time");
const path = require("path");
var timers = {};
/**
*
* @param {LiftoffEnvironment} env
* @param argv
*/
module.exports = function (env, argv)
{
const VERBOSE = argv.v;
const DEBUG = !!argv.debug || !!argv.dev || !!argv.d;
console.log("");
console.log(" " + chalk.black(chalk.bgYellow(" ~~~~~~ ")));
console.log(" " + chalk.black(chalk.bgYellow(" kaba ")));
console.log(" " + chalk.black(chalk.bgYellow(" ~~~~~~ ")));
console.log("");
// check for local kaba installation
if (!env.modulePath)
{
console.log(
chalk.red("Local kaba not found in "),
tildify(env.cwd)
);
process.exit(1);
}
// if no config file, return with an error
if (!env.configPath)
{
console.log(chalk.red("No kabafile found."));
process.exit(1);
}
// print path to the used kaba file
printUsedKabaFile(env);
console.log("");
// set current dir to the dir of the kabafile
process.chdir(env.cwd);
// get kaba instance
let kaba = require(env.modulePath);
kaba.on("start", (taskDetails) => timers[taskDetails.id] = process.hrtime());
kaba.on("end", (taskDetails) => {
if (timers[taskDetails.id])
{
let diff = process.hrtime(timers[taskDetails.id]);
console.log("Task " + chalk.yellow(taskDetails.task) + " finished after " + chalk.blue(prettyTime(diff)));
delete timers[taskDetails.id];
}
});
try
{
// run kabafile
require(env.configPath);
}
catch (e)
{
let message = e instanceof Error ? e.message : e;
printUsage(kaba, `The loaded kaba file has thrown an error: ${message}`);
// rethrow error, if verbose mode is set
if (VERBOSE)
{
throw e;
}
return;
}
// get selected task name
let selectedTaskName;
switch (argv._.length)
{
// if no task name is given, use the default task name
case 0:
selectedTaskName = kaba.DEFAULT_TASK_NAME;
break;
case 1:
selectedTaskName = argv._[0];
break;
// if more than one task is given: abort
default:
printUsage(kaba, "Please select a single task.");
return;
}
let selectedTask = kaba.task(selectedTaskName);
if (!selectedTask)
{
printUsage(kaba, "The task " + chalk.yellow(argv._[0]) + " is not registered.");
}
else
{
try
{
var noop = () => {};
selectedTask(noop, DEBUG);
}
catch (e)
{
let message = e instanceof Error ? e.message : e;
console.log(chalk.red(`The task has thrown an error: ${message}`));
if (VERBOSE)
{
throw e;
}
}
}
};
/**
* Prints the path to the used kaba file
*
* @param {LiftoffEnvironment} env
*/
function printUsedKabaFile (env)
{
let kabaFilePath = path.relative(process.cwd(), env.configPath);
// if it is a relative path in one of the parent directories
if (0 === kabaFilePath.indexOf(".."))
{
kabaFilePath = tildify(env.configPath);
}
console.log(chalk.blue("Using kabafile: ") + kabaFilePath);
}
/**
* Prints the usage information with an additional, optional error message
*
* @param {Kaba} kaba
* @param {string|null} message
*/
function printUsage (kaba, message = null)
{
console.log("Registered tasks:");
kaba.listTasks().forEach(
function (taskName)
{
let formattedTaskName = (kaba.DEFAULT_TASK_NAME === taskName) ?
chalk.yellow.bold("default task") + " (run without parameter)" :
chalk.yellow(taskName);
console.log(` - ${formattedTaskName}`);
}
);
console.log("");
if (message)
{
console.log(chalk.red(message));
}
console.log("Please run a task with: " + chalk.cyan("kaba task"));
}
| JavaScript | 0.000017 | @@ -2551,32 +2551,103 @@
ctedTask)%0A %7B%0A
+ if (kaba.DEFAULT_TASK_NAME !== selectedTaskName)%0A %7B%0A
printUsa
@@ -2682,25 +2682,32 @@
.yellow(
-argv._%5B0%5D
+selectedTaskName
) + %22 is
@@ -2722,24 +2722,128 @@
istered.%22);%0A
+ %7D%0A else%0A %7B%0A printUsage(kaba, %22No default task registered.%22);%0A %7D%0A
%7D%0A el
|
6fb1f05949e8ca5e1d9e692348535c7bf1f0186e | words plugin: links inherit color. default link color is annoying | plugins/popcorn.words.js | plugins/popcorn.words.js | // PLUGIN: words
(function (Popcorn) {
"use strict";
var styleSheet;
Popcorn.basePlugin( 'words' , function(options, base) {
var popcorn,
video,
classes,
container,
textContainer,
text, node, i;
if (!base.target || !options.text) {
return;
}
popcorn = this;
video = popcorn.media;
//todo: add stylesheet with basePlugin
if (!styleSheet) {
styleSheet = document.createElement('style');
styleSheet.setAttribute('type', 'text/css');
styleSheet.appendChild(
document.createTextNode(
'.popcorn-words { display: none; }\n' +
'.popcorn-words.active { display: block; }\n'
));
document.head.appendChild(styleSheet);
}
container = base.makeContainer();
container.style.cssText = options.style || '';
//todo: do all of this positioning stuff with basePlugin
i = options.top;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.top = i;
container.style.position = 'absolute';
}
i = options.left;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.left = i;
container.style.position = 'absolute';
}
i = options.right;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.right = i;
container.style.position = 'absolute';
}
i = options.bottom;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.bottom = i;
container.style.position = 'absolute';
}
base.animate('top', function(val) {
container.style.top = val;
});
base.animate('left', function(val) {
container.style.left = val;
});
base.animate('right', function(val) {
container.style.right = val;
});
base.animate('bottom', function(val) {
container.style.bottom = val;
});
if (options.align) {
container.style.textAlign = options.align;
}
if (options.classes) {
base.addClass(container, options.classes);
}
if (options.link) {
//todo: localize link
textContainer = document.createElement('a');
textContainer.setAttribute('href', options.link);
if (options.linkTarget) {
textContainer.setAttribute('target', options.linkTarget);
} else {
textContainer.setAttribute('target', '_new');
}
//pause video when link is clicked
textContainer.addEventListener('click', function() {
video.pause();
}, false);
container.appendChild(textContainer);
} else {
textContainer = container;
}
//todo: localize
text = base.toArray(options.text, /[\n\r]/);
for (i = 0; i < text.length; i++) {
if (i) {
textContainer.appendChild(document.createElement('br'));
}
textContainer.appendChild(document.createTextNode(text[i]));
}
if (typeof options.onLoad === 'function') {
options.onLoad(options);
}
return {
start: function( event, options ) {
base.addClass(base.container, 'active');
},
end: function( event, options ) {
base.removeClass(base.container, 'active');
}
};
});
}( Popcorn ));
| JavaScript | 0.999987 | @@ -573,16 +573,66 @@
%7D%5Cn' +%0A
+%09%09%09%09%09'.popcorn-words %3E a %7B color: inherit; %7D%5Cn' +%0A
%09%09%09%09%09'.p
|
b2dc6e68c29703182c048654ed19c4d9e66d51e0 | Add "say" command. | extension.js | extension.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var axon = require('axon');
var rpc = require('axon-rpc');
var req = axon.socket('req');
var subSock = axon.socket('sub');
var rpcClient = new rpc.Client(req);
var equal = require('deep-equal');
module.exports = function(nodecg) {
if (!nodecg.bundleConfig || !Object.keys(nodecg.bundleConfig).length) {
throw new Error('[lfg-siphon] No config found in cfg/lfg-siphon.json, aborting!');
}
var self = new EventEmitter();
var channels = nodecg.bundleConfig.channels;
var SUB_PORT = nodecg.bundleConfig.subPort || 9455;
var RPC_PORT = nodecg.bundleConfig.rpcPort || 9456;
nodecg.listenFor('getChannels', function(data, cb) {
cb(channels);
});
subSock.connect(SUB_PORT, '127.0.0.1');
req.connect(RPC_PORT, '127.0.0.1');
subSock.on('connect', function() {
nodecg.log.info('Connected to Streen');
channels.forEach(function(channel) {
rpcClient.call('join', channel, function(err, alreadyJoined) {
if (err) {
nodecg.log.error(err.stack);
return;
}
if (alreadyJoined) {
nodecg.log.info('Streen already in channel:', alreadyJoined);
} else {
nodecg.log.info('Joined channel:', channel);
nodecg.sendMessage('join', channel);
self.emit('join', channel);
}
});
});
});
subSock.on('disconnect', function() {
nodecg.log.warn('Disconnected from Streen');
self.emit('disconnect');
nodecg.sendMessage('disconnect');
});
var lastSub;
subSock.on('message', function(msg) {
var channel, data;
switch (msg.toString()) {
case 'connected':
nodecg.log.info('Streen connected to Twitch Chat');
break;
case 'disconnected':
nodecg.log.info('Streen disconnected from Twitch Chat');
break;
case 'chat':
data = {
channel: arguments[1],
user: arguments[2],
message: arguments[3],
self: arguments[4]
};
if (channels.indexOf(data.channel) < 0) return;
nodecg.sendMessage('chat', data);
self.emit('chat', data);
break;
case 'timeout':
data = {channel: arguments[1], username: arguments[2]};
if (channels.indexOf(data.channel) < 0) return;
nodecg.sendMessage('timeout', data);
self.emit('timeout', data);
break;
case 'clearchat':
channel = arguments[1];
if (channels.indexOf(channel) < 0) return;
nodecg.sendMessage('clearchat', channel);
self.emit('clearchat', channel);
break;
case 'subscription':
data = arguments[1];
if (channels.indexOf(data.channel) < 0) return;
if (equal(lastSub, data)) return;
lastSub = data;
// 10-30-2015: Streen now ensures that "months" is an integer.
// The below line can be removed soon.
if (data.months) data.months = parseInt(data.months);
nodecg.sendMessage('subscription', data);
self.emit('subscription', data);
break;
}
});
var heartbeatTimeout = setTimeout(heartbeat, 5000);
function heartbeat() {
rpcClient.call('heartbeat', channels, function(err, interval) {
if (err) {
nodecg.log.error(err.stack);
}
heartbeatTimeout = setTimeout(heartbeat, interval);
});
}
self.timeout = function(channel, username, seconds) {
rpcClient.call('timeout', channel, username, seconds, function(err){
if (err) nodecg.log.error(err.stack);
});
};
return self;
};
| JavaScript | 0.046462 | @@ -3717,16 +3717,54 @@
5000);%0A
+ var lastHeartbeatInterval = 5000;%0A
func
@@ -3778,24 +3778,24 @@
artbeat() %7B%0A
-
rpcC
@@ -3998,16 +3998,217 @@
interval
+ %7C%7C lastHeartbeatInterval);%0A %7D);%0A %7D%0A%0A self.say = function(channel, message) %7B%0A rpcClient.call('say', channel, message, function(err)%7B%0A if (err) nodecg.log.error(err.stack
);%0A
@@ -4206,37 +4206,38 @@
k);%0A %7D);%0A
-
%7D
+;
%0A%0A self.timeo
|
6abb2cb92edc1edaefea7e37cd46a6c866239c27 | fix sharing nested galleries | apps/gallery/js/album_cover.js | apps/gallery/js/album_cover.js | var actual_cover;
var paths = [];
var crumbCount = 0;
$(document).ready(returnToElement(0));
function returnToElement(num) {
while (crumbCount != num) {
$('#g-album-navigation .last').remove();
$('#g-album-navigation .crumb :last').parent().addClass('last');
crumbCount--;
paths.pop();
}
var p='';
for (var i in paths) p += paths[i]+'/';
$('#g-album-loading').show();
$.getJSON(OC.filePath('gallery','ajax','galleryOp.php'), {operation: 'get_gallery', path: p }, albumClickHandler);
}
function albumClick(title) {
paths.push(title);
crumbCount++;
var p = '';
for (var i in paths) p += paths[i]+'/';
$('#g-album-loading').show();
$.getJSON(OC.filePath('gallery','ajax','galleryOp.php'), {operation: 'get_gallery', path: p }, function(r) {
albumClickHandler(r);
if ($('#g-album-navigation :last-child'))
$('#g-album-navigation :last-child').removeClass('last');
$('#g-album-navigation').append('<div class="crumb last real" style="background-image:url(\''+OC.imagePath('core','breadcrumb')+'\')"><a href=\"javascript:returnToElement('+crumbCount+');\">'+decodeURIComponent(escape(title))+'</a></div>');
});
}
function constructSharingPath() {
return document.location.protocol + '//' + document.location.host + OC.linkTo('gallery', 'sharing.php') + '?token=' + Albums.token;
}
function shareGallery() {
var existing_token = '';
if (Albums.token)
existing_token = constructSharingPath();
var form_fields = [{text: 'Share', name: 'share', type: 'checkbox', value: Albums.shared},
{text: 'Share recursive', name: 'recursive', type: 'checkbox', value: Albums.recursive},
{text: 'Shared gallery address', name: 'address', type: 'text', value: existing_token}];
OC.dialogs.form(form_fields, t('gallery', 'Share gallery'), function(values){
var p = '';
for (var i in paths) p += '/'+paths[i];
if (p == '') p = '/';
$.getJSON(OC.filePath('gallery', 'ajax', 'galleryOp.php'), {operation: 'share', path: p, share: values[0].value, recursive: values[1].value}, function(r) {
if (r.status == 'success') {
Albums.shared = r.sharing;
if (Albums.shared) {
Albums.token = r.token;
Albums.recursive = r.recursive;
} else {
Albums.token = '';
Albums.recursive = false;
}
var actual_addr = '';
if (Albums.token)
actual_addr = constructSharingPath();
$('input[name="address"]').val(actual_addr);
} else {
OC.dialogs.alert(t('gallery', 'Error: ') + r.cause, t('gallery', 'Internal error'));
}
});
});
}
function albumClickHandler(r) {
Albums.photos = [];
Albums.albums = [];
if (r.status == 'success') {
for (var i in r.albums) {
var a = r.albums[i];
Albums.add(a.name, a.numOfItems, a.path, a.shared, a.recursive, a.token);
}
for (var i in r.photos) {
Albums.photos.push(r.photos[i]);
}
Albums.shared = r.shared;
if (Albums.shared) {
Albums.recursive = r.recursive;
Albums.token = r.token;
} else {
Albums.recursive = false;
Albums.token = '';
}
var targetDiv = document.getElementById('gallery_list');
if (targetDiv) {
$(targetDiv).html('');
Albums.display(targetDiv);
//$('#gallery_list').sortable({revert:true});
$('.album').each(function(i, el) {
$(el).click(albumClick.bind(null,$(el).attr('title')));
//$(el).draggable({connectToSortable: '#gallery_list', handle: '.dummy'});
});
} else {
OC.dialogs.alert(t('gallery', 'Error: no such layer `gallery_list`'), t('gallery', 'Internal error'));
}
} else {
OC.dialogs.alert(t('gallery', 'Error: ') + r.cause, t('gallery', 'Internal error'));
}
$('#g-album-loading').hide();
}
var albumCounter = 0;
var totalAlbums = 0;
function scanForAlbums(cleanup) {
Scanner.scanAlbums();
return;
}
function settings() {
$( '#g-dialog-settings' ).dialog({
height: 180,
width: 350,
modal: false,
buttons: [
{
text: t('gallery', 'Apply'),
click: function() {
var scanning_root = $('#g-scanning-root').val();
var disp_order = $('#g-display-order option:selected').val();
if (scanning_root == '') {
alert('Scanning root cannot be empty');
return;
}
$.getJSON(OC.filePath('gallery','ajax','galleryOp.php'), {operation: 'store_settings', root: scanning_root, order: disp_order}, function(r) {
if (r.status == 'success') {
if (r.rescan == 'yes') {
$('#g-dialog-settings').dialog('close');
Albums.clear(document.getElementById('gallery_list'));
scanForAlbums(true);
return;
}
} else {
alert('Error: ' + r.cause);
return;
}
$('#g-dialog-settings').dialog('close');
});
}
},
{
text: t('gallery', 'Cancel'),
click: function() {
$(this).dialog('close');
}
}
],
});
}
| JavaScript | 0 | @@ -1864,20 +1864,16 @@
+=
-'/'+
paths%5Bi%5D
;%0A
@@ -1868,16 +1868,20 @@
paths%5Bi%5D
++'/'
;%0A if
@@ -1896,24 +1896,38 @@
') p = '/';%0A
+ alert(p);%0A
$.getJSO
|
01761e0d9f10362d2a681b2bcb1c51c78b39d2d9 | increase test timeout | index.test.js | index.test.js | const execa = require('execa');
const fs = require('fs');
afterEach(done => {
fs.access('sitemap.xml', err => {
if (!err) {
fs.unlink('sitemap.xml', done);
}
});
});
test('should create sitemap file', () => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
]).then(() => {
expect(() => fs.accessSync('sitemap.xml')).not.toThrow();
});
});
test('should write to stdout in verbose mode', () => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
'--verbose',
]).then(result => {
expect(result.stdout).not.toBe('');
});
});
| JavaScript | 0.000002 | @@ -176,32 +176,35 @@
%7D);%0A%7D);%0A%0Atest(
+%0A
'should create s
@@ -216,16 +216,18 @@
p file',
+%0A
() =%3E %7B
@@ -219,32 +219,34 @@
ile',%0A () =%3E %7B%0A
+
expect.asserti
@@ -246,32 +246,34 @@
assertions(1);%0A%0A
+
return execa('
@@ -277,32 +277,34 @@
a('node', %5B%0A
+
'index.js',%0A
@@ -291,32 +291,34 @@
'index.js',%0A
+
'https://lar
@@ -329,32 +329,34 @@
ubner.com',%0A
+
'sitemap.xml',%0A
@@ -354,16 +354,18 @@
p.xml',%0A
+
%5D).the
@@ -374,24 +374,26 @@
() =%3E %7B%0A
+
expect(() =%3E
@@ -438,23 +438,37 @@
hrow();%0A
+
%7D);%0A
-%7D
+ %7D,%0A 20000%0A
);%0A%0Atest
@@ -468,16 +468,19 @@
;%0A%0Atest(
+%0A
'should
@@ -512,16 +512,18 @@
e mode',
+%0A
() =%3E %7B
@@ -525,16 +525,18 @@
=%3E %7B%0A
+
+
expect.a
@@ -552,16 +552,18 @@
(1);%0A%0A
+
+
return e
@@ -577,24 +577,26 @@
ode', %5B%0A
+
+
'index.js',%0A
@@ -591,24 +591,26 @@
'index.js',%0A
+
'https:/
@@ -629,24 +629,26 @@
r.com',%0A
+
+
'sitemap.xml
@@ -654,16 +654,18 @@
l',%0A
+
'--verbo
@@ -671,16 +671,18 @@
ose',%0A
+
+
%5D).then(
@@ -689,24 +689,26 @@
result =%3E %7B%0A
+
expect(r
@@ -735,18 +735,32 @@
Be('');%0A
+
%7D);%0A
-%7D
+ %7D,%0A 20000%0A
);%0A
|
f3ea100dedd0ffd3ed102ddaa5bd0f1e5e0007a0 | Fix Assist async and force calls settings | apps/spark/static/js/assist.js | apps/spark/static/js/assist.js | // Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var Assist = function (options) {
var self = this;
function hasExpired(timestamp) {
if (!timestamp) {
return true;
}
var TIME_TO_LIVE_IN_MILLIS = 86400000; // 1 day
return (new Date()).getTime() - timestamp > TIME_TO_LIVE_IN_MILLIS;
}
function getTotalStoragePrefix() {
var _app = "";
if (typeof options.app != "undefined") {
_app = options.app;
}
if (typeof options.user != "undefined") {
return _app + "_" + options.user + "_";
}
return (_app != "" ? _app + "_" : "");
}
function jsonCalls() {
if (typeof options.baseURL == "undefined" || options.baseURL == null) {
console.error("Assist should always have a baseURL set to work fine.");
return null;
}
var _url = options.baseURL;
if (options.firstLevel != null) {
_url += options.firstLevel;
}
if (options.secondLevel != null) {
_url += "/" + options.secondLevel;
}
var _cachePath = getTotalStoragePrefix() + _url;
var _cached = $.totalStorage(_cachePath);
var _returnCached = false;
if (_cached != null && !hasExpired(_cached.timestamp) && typeof options.forceReload == "undefined") {
options.onDataReceived(_cached.data);
_returnCached = true;
}
if (options.onError) {
$.ajaxSetup({
error: function(x, e) {
if (x.status == 500) {
self.hasErrors(true);
options.onError(e);
}
}
});
}
$.ajax({
type: "GET",
url: _url + "?" + Math.random(),
success: function (data) {
if (data.error){
if (typeof options.failsSilentlyOn == "undefined" || (data.code != null && options.failsSilentlyOn.indexOf(data.code) == -1)){
$.jHueNotify.error(data.error);
}
}
else {
var _obj = {
data: data,
timestamp: (new Date()).getTime()
}
$.totalStorage(_cachePath, _obj);
if (!_returnCached) {
options.onDataReceived($.totalStorage(_cachePath).data);
}
}
},
error: function (error) {
$(document).trigger('error', error);
},
async: options.sync == "undefined"
});
}
self.options = options;
self.getData = function (path, force) {
self.path(path);
self.options.firstLevel = null;
self.options.secondLevel = null;
if (path) {
if (path.indexOf("/") > -1) {
self.options.firstLevel = path.split("/")[0];
self.options.secondLevel = path.split("/")[1];
}
else {
self.options.firstLevel = path;
}
}
jsonCalls(force);
}
// ko observables
self.isLoading = ko.observable(true);
self.hasErrors = ko.observable(false);
self.path = ko.observable();
self.selectedMainObject = ko.observable();
self.mainObjects = ko.observableArray([]);
self.firstLevelObjects = ko.observable({});
self.filter = ko.observable("");
self.filter.extend({ rateLimit: 150 });
self.filteredFirstLevelObjects = ko.computed(function(){
return ko.utils.arrayFilter(Object.keys(self.firstLevelObjects()), function(item) {
return item.toLowerCase().indexOf(self.filter()) > -1;
});
});
} | JavaScript | 0 | @@ -1344,16 +1344,21 @@
onCalls(
+force
) %7B%0A
@@ -1932,27 +1932,13 @@
eof
-options.forceReload
+force
==
@@ -2974,16 +2974,23 @@
async:
+ typeof
options
@@ -2994,14 +2994,15 @@
ons.
+a
sync
-=
+!
= %22u
@@ -3010,16 +3010,32 @@
defined%22
+ && optons.async
%0A %7D);
|
e27fb513a6887b400b8a6089f7fa2059a6fac528 | Fix require bug | app/lib/backgroundLoader.js | app/lib/backgroundLoader.js | import getAndInitNewEpisodes from "./getAndInitNewEpisodes";
import forEach from "./forEach";
import episodesToString from "./episodesToString";
var ipc = require("ipc");
export default function(controller) {
var store = controller.get("store");
var checkForEp = function(){
if(controller.get("isUpdating")) { return; }
controller.set("isUpdating", true);
getAndInitNewEpisodes(controller.currentUser, store).then(function(episodes) {
controller.model.unshiftObjects(episodes);
forEach(episodes.toArray(), function(episode, next) {
episode.loading(next, next);
}, function(){
controller.set("isUpdating", false);
if(episodes.get("length")){
new Notification("New episodes", {
body: episodesToString(episodes)
});
ipc.send("newBackgroundEpisodes", 1);
}
});
}).catch(function(err){
console.info("err1", err)
controller.currentUser.logout();
controller.transitionToRoute("login");
}).finally(function(){
controller.set("isUpdating", false);
});
}
var deleteOld = function() {
var deleteOnTerm = function(term) {
store.query("episode", term).then(function(episodes) {
episodes.forEach(function(episode) {
if(episode.isOlderThenDays(30)){
episode.destroyRecord();
}
});
});
}
deleteOnTerm({ removed: true });
deleteOnTerm({ seen: true });
};
var checkForNewMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false,
magnet: null
}).then(function(episodes) {
forEach(episodes.toArray(), function(episode, next){
episode.loading(next, next);
}, function() {
// Remove all episodes which doesn't have a magnet link
var filteredEps = episodes.reject(function(episode) {
return ! episode.get("magnet");
});
if(filteredEps.length){
new Notification("New magnet links", {
body: episodesToString(filteredEps)
});
ipc.send("newBackgroundEpisodes", 1);
}
controller.set("isReloading", false);
}, function() {
controller.set("isReloading", false);
});
}, function(err) {
controller.set("isReloading", false);
});
}
var updateMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false
}).then(function(episodes) {
forEach(episodes.toArray().reverse(), function(episode, next){
episode.loading(next, next);
}, function(){
controller.set("isReloading", false);
});
});
}
var minute = 1000 * 60;
var ids = []
// Update releases every 60 min
ids.push(setInterval(checkForEp, 60 * minute));
// Find new magnets every 30 min
ids.push(setInterval(checkForNewMagnets, 30 * minute));
// Update magnets every 40 min
ids.push(setInterval(updateMagnets, 40 * minute));
// Delete old episodes once every hour
ids.push(setInterval(deleteOld, 60 * minute));
var check = function() {
checkForEp();
checkForNewMagnets();
updateMagnets();
deleteOld();
};
var online = function() {
// Wait 5 sec to ensure connectivity
setTimeout(check, 5000);
}
var down = function() {
window.removeEventListener("online", online);
ids.forEach(function(id) {
clearInterval(id);
});
};
// Check when online
window.addEventListener("online", online);
// Check all on start up
check();
return down;
}; | JavaScript | 0.000001 | @@ -148,17 +148,18 @@
r ipc =
-r
+nR
equire(%22
|
72817bdb9f571075b2d0020ccba95bef68f9758e | use separate escape/non-escape toString functions for fragments - easier for browsers to optimise | src/virtualdom/Fragment/prototype/toString.js | src/virtualdom/Fragment/prototype/toString.js | export default function Fragment$toString ( escape ) {
if ( !this.items ) {
return '';
}
return this.items.map( function ( item ) {
return item.toString( escape );
}).join( '' );
}
| JavaScript | 0 | @@ -111,24 +111,86 @@
ms.map(
-function
+escape ? toEscapedString : toString ).join( '' );%0A%7D%0A%0Afunction toString
( item
@@ -189,25 +189,24 @@
( item ) %7B%0A
-%09
%09return item
@@ -219,33 +219,78 @@
ing(
- escape );%0A%09%7D).jo
+);%0A%7D%0A%0Afunction toEscapedString ( item ) %7B%0A%09return item.toStr
in
+g
(
-''
+true
);%0A%7D
-%0A
|
ec375d715289fc0726efcf2c34c97ad3b6e89e3a | Complete sensors list | sensors.js | sensors.js | const gpio = require('pi-gpio');
const client = require('prom-client');
const Promise = require('bluebird');
Promise.promisifyAll(gpio);
const sensors = [{
gpioPin: 0,
sensorId: '',
sensorDescription: '',
}];
const airTempGauge = new client.Gauge('air_temperature', 'Air Temperature in a room', ['sensorId', 'sensorDescription']);
const relHumidityGauge = new client.Gauge('humidity_relative', 'Relative humidity in a room', ['sensorId', 'sensorDescription']);
function readSensorData(sensor) {
gpio.readAsync(sensor.gpioPin)
.then((value) => {
console.log(value);
//tempGauge.set(parseFloat(data));
});
}
Promise.map(sensors, (sensor) => gpio.openAsync(sensor.gpioPin, 'input'))
.then(() => Promise.map(sensors, (sensor) => readSensor(sensor));
| JavaScript | 0.000005 | @@ -166,24 +166,336 @@
in:
-0,%0A sensorId: '
+11,%0A sensorId: '0',%0A sensorDescription: '',%0A%7D, %7B%0A gpioPin: 12,%0A sensorId: '1',%0A sensorDescription: '',%0A%7D, %7B%0A gpioPin: 13,%0A sensorId: '2',%0A sensorDescription: '',%0A%7D, %7B%0A gpioPin: 15,%0A sensorId: '3',%0A sensorDescription: '',%0A%7D, %7B%0A gpioPin: 16,%0A sensorId: '4',%0A sensorDescription: '',%0A%7D, %7B%0A gpioPin: 18,%0A sensorId: '5
',%0A
@@ -810,17 +810,16 @@
nsor) %7B%0A
-%0A
gpio.r
@@ -880,21 +880,38 @@
ole.log(
+%60$%7BsensorId%7D $%7B
value
+%7D%60
);%0A /
@@ -985,16 +985,27 @@
nsor) =%3E
+ %7B%0A return
gpio.op
@@ -1040,16 +1040,19 @@
ut')
+;%0A%7D
)%0A.then(
() =
@@ -1051,14 +1051,8 @@
hen(
-() =%3E
Prom
@@ -1079,16 +1079,27 @@
nsor) =%3E
+ %7B%0A return
readSen
@@ -1101,19 +1101,23 @@
adSensor
+Data
(sensor)
);%0A
@@ -1113,11 +1113,14 @@
(sensor)
+;%0A%7D
);%0A
|
4c4b1a4d20640c3597bb8143f64a81f4227e1606 | Remove console log | app/assets/javascripts/components/search.es6.js | app/assets/javascripts/components/search.es6.js | // Require React
React = require('react/addons');
var TagsInput = require('react-tagsinput');
// Material UI
import mui from 'material-ui';
let RaisedButton = mui.RaisedButton;
let Colors = mui.Styles.Colors;
let ThemeManager = mui.Styles.ThemeManager;
let Snackbar = mui.Snackbar;
let LightRawTheme = mui.Styles.LightRawTheme;
// Define component
const Search = React.createClass({
mixins: [React.addons.LinkedStateMixin],
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
error: false,
tags: []
};
},
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()) {
this._populate_form();
}
},
render() {
let textFieldStyles = {
marginRight: '20px',
marginTop: '10px',
marginBottom: '20px',
width: '400px'
}
return (
<form ref="search" method="GET" action={this.props.action} onKeyDown={this._handleKeyDown}>
<div className="search-box">
<TagsInput style={textFieldStyles} ref='tags' name="q" transform={this._formatTag} valueLink={this.linkState("tags")} validate={this._validateTag} onTagAdd={this._addTag} placeholder="Type a filter(ex: location:london) and click find" />
<RaisedButton className="search-box search-box--button"label="Find" primary={true} onClick={this._handleSubmit} />
</div>
<Snackbar
ref="snackbar_error"
message="Search can't be empty"
action="error"
autoHideDuration={5000} />
<Snackbar
ref="snackbar_hint"
message="Now click find or enter key to search"
action="hint"
autoHideDuration={5000} />
<Snackbar
ref="snackbar_uniqueness_error"
message="Keyword already added"
action="error"
autoHideDuration={5000} />
<Snackbar
ref="snackbar_invalid_keyword"
message="Not a valid keyword! Allowed: language, location, created, repos, followers"
action="error"
autoHideDuration={10000} />
<Snackbar
ref="snackbar_invalid_format"
message="Not a valid format! See demo tags and format correctly ex: location:london"
action="error"
autoHideDuration={10000} />
</form>
);
},
_validateTag(tag, done) {
var keywords = ["location", "followers", "repos", "created", "language", "keyword"];
var unique = this.state.tags.indexOf(tag) === -1;
if (!unique) {
this.setState({error: true});
this.refs.snackbar_uniqueness_error.show(); return done(false);
}
// Split the term
var terms = tag.split(':');
// Check if number of terms are === 2
if(terms.length != 2){
this.setState({error: true});
this.refs.snackbar_invalid_format.show();
return done(false);
}
// Check if search keyword exists in keywords
if(keywords.indexOf(terms[0]) === -1) {
this.setState({error: true});
this.refs.snackbar_invalid_keyword.show();
return done(false);
}
// All passes then return valid true
this.setState({error: false});
done(true);
},
_formatTag(tag) {
return tag.trim().toLowerCase();
},
_addTag() {
this._preFetchPage();
},
_getFormData() {
console.log(this.state.tags.join('+'))
// finally submit the form
return this.state.tags.join('+');
},
_preFetchPage() {
// Pre-fetch the page to warm up cache
$.get('/members?q=' + decodeURIComponent(this._getFormData()), function(data) {
}, "html");
},
_handleKeyDown(event) {
// Dont' submit form on enter
if(event.keyCode === 13) {
$(event.target.closest('form')).submit(function(){
return false;
});
}
},
_handleSubmit(event) {
event.preventDefault();
// Only submit if there are any tags
if (this.refs.tags.getTags().join(', ').length > 0) {
// Don't submit empty form fields
Turbolinks.visit('/members?q=' + decodeURIComponent(this._getFormData()));
} else {
// Empty stop submit event and show error
event.stopPropagation();
this.refs.snackbar_error.show();
}
},
_populate_form(){
//grab the entire query string
var query_params = decodeURIComponent(document.location.search.replace('?', ''));
if(query_params) {
//first get the query fragments
var fragments = query_params.split('q=');
// Split query from other params
var query = fragments[1].split('&');
//Split query params
var field = query[0].split("+");
//loop query params and push it to tags
field.map(function(elem, i) {
if(elem.indexOf("+") > -1) {
this.state.tags.push(elem.replace('+', ''))
} else {
this.state.tags.push(elem)
}
}.bind(this));
}
}
});
module.exports = Search;
| JavaScript | 0.000002 | @@ -3691,51 +3691,8 @@
) %7B%0A
- console.log(this.state.tags.join('+'))%0A
|
1708171858ce97ec2e5e7f7681e5b8cf2c6ca901 | Move the directive link function to a function definition. | app/common/directives/bubble-chart.directive.js | app/common/directives/bubble-chart.directive.js | (function () {
'use strict';
angular
.module('gmailHistogramApp')
.directive('d3BubbleChart', d3BubbleChartDirective);
d3BubbleChartDirective.$inject = ['$window'];
function d3BubbleChartDirective($window) {
return {
restrict: 'EA',
scope: {
data: '='
},
link: function (scope, element, attrs) {
var diameter = 450;
var svg = d3.select(element[0]).append('svg');
svg.attr({
'width': diameter,
'height': diameter,
'class': 'bubble'
});
$window.onresize = function () {
scope.$apply();
};
scope.$watch(
function () {
return angular.element($window)[0].innerWidth;
},
function () {
draw(svg, diameter, scope.data);
});
scope.$watch('data',
function () {
draw(svg, diameter, scope.data);
});
}
};
};
function flattenData(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function (child) { recurse(node.name, child); });
else classes.push({ packageName: name, className: node.name, value: node.size });
}
recurse(null, root);
return { children: classes };
};
function draw(svg, diameter, inputData) {
var format = d3.format(",d");
var color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var flatData = bubble.nodes(flattenData(inputData)).filter(function (d) { return !d.children; });
var node = svg.selectAll("g").data(flatData);
var appendedNode = node.enter().append("g").attr("class", "node");
appendedNode.append("circle");
appendedNode.append("text").attr("dy", ".3em").style("text-anchor", "middle");
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
node.select("circle")
.attr("r", function (d) { return d.r; })
.style("fill", function (d) { return color(d.packageName); });
node.select("text").text(function (d) { return d.className.toUpperCase(); });
node.exit().remove();
};
} ()); | JavaScript | 0 | @@ -129,20 +129,16 @@
ctive);%0A
-
%0A d3B
@@ -352,16 +352,41 @@
link:
+ link%0A %7D;%0A%0A
functio
@@ -387,16 +387,20 @@
unction
+link
(scope,
@@ -425,28 +425,24 @@
-
-
var diameter
@@ -449,20 +449,16 @@
= 450;%0A
-
@@ -521,20 +521,16 @@
-
-
svg.attr
@@ -532,20 +532,16 @@
.attr(%7B%0A
-
@@ -583,20 +583,16 @@
-
-
'height'
@@ -619,20 +619,16 @@
-
'class':
@@ -645,37 +645,29 @@
-
-
%7D);%0A%0A
-
@@ -711,28 +711,24 @@
-
-
scope.$apply
@@ -739,28 +739,24 @@
-
%7D;%0A%0A
@@ -751,36 +751,32 @@
%7D;%0A%0A
-
-
scope.$watch(%0A
@@ -773,20 +773,16 @@
$watch(%0A
-
@@ -819,28 +819,24 @@
-
-
return angul
@@ -882,34 +882,27 @@
- %7D,%0A
+%7D,%0A
@@ -897,33 +897,32 @@
-
function () %7B%0A
@@ -911,36 +911,32 @@
function () %7B%0A
-
@@ -984,37 +984,29 @@
-
-
%7D);%0A%0A
-
@@ -1034,36 +1034,32 @@
-
-
function () %7B%0A
@@ -1048,36 +1048,32 @@
function () %7B%0A
-
@@ -1129,30 +1129,12 @@
-
-
%7D);%0A
- %7D%0A
@@ -1147,20 +1147,16 @@
%0A %7D;%0A
-
%0A fun
|
4327db9cd4d507c15dfb4afe66d81653d1dadef6 | Set theme field to full size | app/components/forms/settings/base/component.js | app/components/forms/settings/base/component.js | import React from 'react';
import { RaisedButton, MenuItem } from 'material-ui';
import {
TextField,
SelectField
} from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';
import BaseComponent from 'lex/libs/base/component';
import BaseContainer from 'lex/libs/container';
import { I18n } from 'react-redux-i18n';
import { connect } from 'react-redux';
import { pullData } from 'lex/actions/form-setup';
import fillData from 'lex/utils/object-fill-from-data';
import themes from 'lex/constants/menu-themes';
const validate = values => {
const errors = {};
const { hitSize } = values;
if (!hitSize) {
errors.hitSize = I18n.t('components.forms.required');
} else if (isNaN(Number(hitSize))) {
errors.hitSize = I18n.t('components.forms.mustBeNumber');
} else if (Number(hitSize) <= 0) {
errors.hitSize = I18n.t('components.forms.mustBeGreaterZero');
}
return errors;
};
const ThemeSelect = () => {
const items = themes.map((item, index) => {
return (
<MenuItem
primaryText={item.label}
value={item.code}
key={index}
/>
);
});
return (
<Field
name="theme"
component={SelectField}
hintText="Theme"
floatingLabelText="Theme"
>
{items}
</Field>
);
};
class SettingsBaseForm extends BaseComponent {
componentDidMount() {
const { data, load, form } = this.props;
if (form, data) {
const fields = fillData(data);
Object.keys(fields).forEach((item) => {
const value = fields[item];
if (value) {
load('settings-base', item, value);
}
});
}
}
render() {
this.decorateStyle();
const { handleSubmit, invalid } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>
<Field
placeholder={I18n.t('components.forms.settings.placeholders.hitSize')}
component={TextField}
fullWidth={true}
name="hitSize"
/>
</div>
<div>
<ThemeSelect />
</div>
<div>
<RaisedButton
disabled={invalid}
label='Save'
secondary={true}
type="submit"
/>
</div>
</form>
);
}
}
SettingsBaseForm = reduxForm({
form: 'settings-base',
validate,
})(SettingsBaseForm);
SettingsBaseForm = connect(null, {
load: pullData
})(SettingsBaseForm);
export default BaseContainer(SettingsBaseForm);
| JavaScript | 0 | @@ -1149,15 +1149,28 @@
-name=%22t
+floatingLabelText=%22T
heme
@@ -1231,35 +1231,45 @@
%0A f
-loatingLabelText=%22T
+ullWidth=%7Btrue%7D%0A name=%22t
heme%22%0A
|
e85b1a2f3f73a975b6570e0dd2a8a93735e30f24 | fix c boolean formatter | app/components/logic/lib/formatter/c-boolean.js | app/components/logic/lib/formatter/c-boolean.js | const operators = {
AND: '&&',
OR: '||',
NOT: '!',
XOR: '^',
};
const tryFetch = (map, key) =>
map[key] || key
;
const whitspace = new RegExp('\s+', 'g');
const sanitizeName = (name) =>
name.replace(whitspace, '_');
const formatter = {
name: "C Boolean",
formatBinary: (op, lhs, rhs/*, depth*/) => {
return formatter.formatBinaryChain(op, lhs, rhs);
},
formatBinaryChain: (op, ...operands) => {
return `(${operands.join(` ${tryFetch(operators, op)} `)})`;
},
formatUnary: (op, content/*, depth*/) => {
return `(${formatter.formatUnarySimple(op, content)})`;
},
formatUnarySimple: (op, content/*, depth*/) => {
return `${tryFetch(operators, op)}${content}`;
},
formatGroup: (content/*, depth*/) => {
return content;
},
formatName: (name) => {
return sanitizeName(name);
},
formatValue: (value) => {
if (value === true) {
return 'true';
} else if (value === false) {
return 'false';
} else {
return 'void';
}
},
formatVector: (identifiers, values) => {
return `<${
identifiers.map((i) => i.name).join(',')
}:${
values.map(formatter.formatVectorValue).join('')
}>`;
},
formatVectorValue: (value) => {
if (value === true) {
return '1';
} else if (value === false) {
return '0';
} else {
return '*';
}
},
formatLabel: (name, body) => {
return `${name}=${body}`;
},
formatExpressions: (expressions) => {
return expressions.join(', ');
},
};
export default formatter;
| JavaScript | 0.999246 | @@ -62,9 +62,10 @@
R: '
-%5E
+!=
',%0A%7D
|
400e1b221d277175d8d3656f7e5f146ce20f0a6e | refresh based on notifications | app/controllers/facebook-realtime-controller.js | app/controllers/facebook-realtime-controller.js | var User = mongoose.model("User")
, ImageList = mongoose.model("ImageList")
, util = require('util')
, PuSHHelper = require('node-push-helper').PuSHHelper;
module.exports = function (app) {
// a GET request will be a challenge query
app.get('/facebook/realtime', function(req, res){
PuSHHelper.handshake(req, res);
});
// this is where Instagram will send updates (using POST)
app.post('/facebook/realtime', PuSHHelper.check_signature, function(req, res){
console.log("Data is " + util.inspect(req.body, false, null));
res.send({meta: 200, message: "Received and understood."}, 200);
});
}
| JavaScript | 0.000002 | @@ -98,16 +98,46 @@
'util')%0A
+ , _ = require('underscore')%0A
, PuSH
@@ -571,16 +571,1603 @@
null));%0A
+ %0A var notifications = req.body;%0A %0A if (notifications%5B'object'%5D == 'user') %7B%0A var seen_in_this_batch = %7B%7D;%0A var entries = notifications.entry;%0A for (var i=0; i %3C entries.length; i++) %7B%0A var message = entries%5Bi%5D;%0A // check if we already processed this user in this batch%0A // since we're just pulling the latest batch of public photos,%0A // we don't need to do this multiple times in one notification%0A // push.%0A if (seen_in_this_batch%5Bmessage.uid%5D === undefined) %7B%0A seen_in_this_batch%5Bmessage.uid%5D = true;%0A User.findOne(%7B%22tokens.facebook.account_id%22: message%5B%22uid%22%5D%7D, function(err, user)%7B%0A if (err == null) %7B%0A if (user !== null) %7B%0A ImageList.refreshFeedForUserProvider(user, %22facebook%22, function(err, imageList) %7B%0A if (err) %7B%0A console.log(%22ERROR: Flickr notification had an error refreshing the feed: %22 + err);%0A %7D else %7B%0A console.log(%22SUCCESS: Flickr notification successfully refreshed feed. New timestamp is: %22 + moment(imageList.updated_at).format('MM/DD/YYYY h:mm:ss a'));%0A %7D%0A %7D); %0A %7D else %7B%0A console.log(%22ERROR: facebook uid from realtime notification not found: %22 + message%5B%22uid%22%5D);%0A %7D%0A %7D else %7B%0A // failed%0A console.log(%22ERROR handling notification: %22 + err);%0A %7D%0A %7D);%0A %7D%0A %7D;%0A %7D%0A %0A // don't wait for refreshes to finish.%0A
res.
|
b544e1f33c824b6fe2f60143d503df1bd606ba73 | declare connectGaiaHub in proptypes | app/js/welcome/components/ConnectStorageView.js | app/js/welcome/components/ConnectStorageView.js | import React, { PropTypes } from 'react'
const ConnectStorageView = (props) =>
(
<div>
<h3 className="modal-heading m-t-15 p-b-20">
Connect a storage provider to store app data in a place you control
</h3>
<img
role="presentation"
src="/images/blockstack-logo-vertical.svg"
className="m-b-20"
style={{ width: '210px', display: 'block', marginRight: 'auto', marginLeft: 'auto' }}
/>
<div className="m-t-40">
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectGaiaHub}>
Connect Gaia Hub
</button>
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectDropbox}>
Connect Dropbox
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect IPFS
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect Self-hosted Drive
</button>
</div>
</div>
)
ConnectStorageView.propTypes = {
connectDropbox: PropTypes.func.isRequired
}
export default ConnectStorageView
| JavaScript | 0.000001 | @@ -1059,16 +1059,61 @@
Dropbox:
+ PropTypes.func.isRequired,%0A connectGaiaHub:
PropTyp
|
f6d88915fdbbc270fa40043c66fd46e897f804de | break general intersection test | src/set_core_test.js | src/set_core_test.js | require("steal-qunit");
var set = require('./set-core');
var ignoreProp = function(){ return true; };
QUnit.module("set core");
test('set.equal', function(){
ok(set.equal({
type: 'FOLDER'
}, {
type: 'FOLDER',
count: 5
}, {
count: ignoreProp
}), 'count ignored');
ok(set.equal({
type: 'folder'
}, {
type: 'FOLDER'
}, {
type: function (a, b) {
return ('' + a)
.toLowerCase() === ('' + b)
.toLowerCase();
}
}), 'folder case ignored');
// Issue #773
ok(!set.equal(
{foo: null},
{foo: new Date()}
), 'nulls and Dates are not considered the same. (#773)');
ok(!set.equal(
{foo: null},
{foo: {}}
), 'nulls and empty objects are not considered the same. (#773)');
});
test('set.subset', function(){
ok(set.subset({
type: 'FOLDER'
}, {
type: 'FOLDER'
}), 'equal sets');
ok(set.subset({
type: 'FOLDER',
parentId: 5
}, {
type: 'FOLDER'
}), 'sub set');
ok(!set.subset({
type: 'FOLDER'
}, {
type: 'FOLDER',
parentId: 5
}), 'wrong way');
ok(!set.subset({
type: 'FOLDER',
parentId: 7
}, {
type: 'FOLDER',
parentId: 5
}), 'different values');
ok(set.subset({
type: 'FOLDER',
count: 5
}, {
type: 'FOLDER'
}, {
count: ignoreProp
}), 'count ignored');
ok(set.subset({
type: 'FOLDER',
kind: 'tree'
}, {
type: 'FOLDER',
foo: true,
bar: true
}, {
foo: ignoreProp,
bar: ignoreProp
}), 'understands a subset');
ok(set.subset({
type: 'FOLDER',
foo: true,
bar: true
}, {
type: 'FOLDER',
kind: 'tree'
}, {
foo: ignoreProp,
bar: ignoreProp,
kind: ignoreProp
}), 'ignores nulls');
});
test('set.properSubset', function(){
equal( set.properSubset({foo: "bar"},{}), true );
equal( set.properSubset({},{}), false );
equal( set.properSubset({},{foo: "bar"}), false );
});
test('set.difference', function(){
var res = set.difference({}, { completed: true });
ok(res === true, "diff should be true");
res = set.difference({ completed: true }, { completed: true });
equal(res, false);
res = set.difference({ completed: true }, {});
equal(res, false);
res = set.difference({ completed: true }, { foo: 'bar' });
equal(res, false);
});
test('set.difference({ function })', function() {
var res = set.difference({ colors: ['red','blue'] }, { colors: ['blue'] }, {
colors: function() {
return {
// can’t always be privided … but COULD if we were gods
difference: ['red' ],
intersection: ['blue']
};
}
});
deepEqual(res, { colors: [ 'red' ] });
});
test('set.union', function(){
// set / subset
/*var res = set.union({}, { completed: true });
deepEqual(res , {}, "set / subset");
res = set.union({ completed: true }, {});
deepEqual(res , {}, "subset / set");
res = set.union({foo: "bar"},{foo: "bar"});
deepEqual(res, {foo: "bar"}, "equal");
res = set.union({foo: "bar"},{foo: "zed"});
ok(!res, "values not equal");*/
var res = set.union({foo: "bar"},{name: "A"});
ok(!res, "values not equal");
});
test('set.union Array', function(){
// set / subset
var res = set.union({foo: ["a","b"]}, { foo: ["a","c"] });
deepEqual(res , {foo: ["a","b","c"]}, "set / subset");
});
test('set.count', function(){
ok( set.count({}) === Infinity, "defaults to infinity");
ok( set.count({foo: "bar"},{}) === Infinity, "defaults to infinity");
equal( set.count({foo: "bar"}, {
foo: function(){
return {
count: 100
};
}
}), 100, "works with a single value" );
});
test('set.intersection', function(){
var res = set.intersection({}, { completed: true });
deepEqual(res , { completed: true }, "set / subset");
res = set.intersection({ completed: true }, {});
deepEqual(res , { completed: true }, "subset / set");
res = set.intersection({foo: "bar"},{foo: "bar"});
deepEqual(res, {foo: "bar"}, "equal");
res = set.intersection({foo: "bar"},{foo: "zed"});
ok(!res, "values not equal");
});
test('set.intersection Array', function(){
// set / subset
var res = set.intersection({foo: ["a","b"]}, { foo: ["a","c"] });
deepEqual(res , {foo: ["a"]}, "intersection");
}); | JavaScript | 0 | @@ -3896,32 +3896,181 @@
ues not equal%22);
+%0A%0A%09res = set.intersection(%7Bfoo: 'bar'%7D,%7Bcompleted: true%7D);%0A%09deepEqual(res, %7Bfoo: 'bar', completed: true%7D, 'intersection should combine definitions');
%0A%7D);%0A%0Atest('set.
|
0af482b4e11e885956f8ee32eb0dad2df0f9e8fb | Update zh_cn.js | vendor/assets/javascripts/redactor-rails/langs/zh_cn.js | vendor/assets/javascripts/redactor-rails/langs/zh_cn.js | //@chen1706@gmail.com
(function ($) {
$.Redactor.opts.langs['zh_cn'] = {
html: 'HTML代码',
video: '视频',
image: '图片',
table: '表格',
link: '链接',
link_insert: '插入链接',
unlink: '取消链接',
formatting: '样式',
paragraph: '段落',
quote: '引用',
code: '代码',
header1: '一级标题',
header2: '二级标题',
header3: '三级标题',
header4: '四级标题',
bold: '粗体',
italic: '斜体',
fontcolor: '字体颜色',
backcolor: '背景颜色',
unorderedlist: '项目编号',
orderedlist: '数字编号',
outdent: '减少缩进',
indent: '增加缩进',
cancel: '取消',
insert: '插入',
save: '保存',
_delete: '删除',
insert_table: '插入表格',
insert_row_above: '在上方插入',
insert_row_below: '在下方插入',
insert_column_left: '在左侧插入',
insert_column_right: '在右侧插入',
delete_column: '删除整列',
delete_row: '删除整行',
delete_table: '删除表格',
rows: '行',
columns: '列',
add_head: '添加标题',
delete_head: '删除标题',
title: '标题',
image_position: '位置',
none: '无',
left: '左',
right: '右',
image_web_link: '图片网页链接',
text: '文本',
mailto: '邮箱',
web: '网址',
video_html_code: '视频嵌入代码',
file: '文件',
upload: '上传',
download: '下载',
choose: '选择',
or_choose: '或选择',
drop_file_here: '将文件拖拽至此区域',
align_left: '左对齐',
align_center: '居中',
align_right: '右对齐',
align_justify: '两端对齐',
horizontalrule: '水平线',
fullscreen: '全屏',
deleted: '删除',
anchor: '锚点',
link_new_tab: '在新窗口打开',
underline: '下划线',
alignment: '对齐方式'
};
})( jQuery ); | JavaScript | 0.000005 | @@ -160,16 +160,36 @@
'%E6%8F%92%E5%85%A5%E9%93%BE%E6%8E%A5',%0A
+%09link_edit: '%E7%BC%96%E8%BE%91%E9%93%BE%E6%8E%A5',%0A
%09unlink:
@@ -333,16 +333,33 @@
'%E5%9B%9B%E7%BA%A7%E6%A0%87%E9%A2%98',%0A
+%09header5: '%E4%BA%94%E7%BA%A7%E6%A0%87%E9%A2%98'%0A
%09bold:
@@ -1371,16 +1371,52 @@
: '%E5%AF%B9%E9%BD%90%E6%96%B9%E5%BC%8F'
+,%0A%09filename: '%E6%96%87%E4%BB%B6%E5%90%8D (%E5%8F%AF%E9%80%89)',%0A%09edit: '%E7%BC%96%E8%BE%91'
%0A%7D;%0A%7D)(
@@ -1424,8 +1424,9 @@
Query );
+%0A
|
954ab95f680a2b1cd2dc30b189a0a0e03234a7e4 | Add getVersions | src/spm.js | src/spm.js | import co from "co";
import { EventEmitter } from "events";
import Config from "./config";
import { getJSON } from "./utils";
import Package from "./package";
class SPM extends EventEmitter {
constructor () {
super();
this.config = new Config;
this._currentPackage = null;
}
// Public methods
get currentPackage () {
if (this._currentPackage === null)
throw Error("No package loaded");
else
return this._currentPackage.toJSON();
}
load (rootUrl="") {
return co(
this._loadPackage.bind(this, rootUrl)
).then(
pkg => {
this._setPackage(pkg);
this.emit("load", pkg);
}
).catch(
this.emit.bind(this, "error")
);
}
// Public methods
_setPackage (pkg) {
this._currentPackage = new Package(pkg);
}
*_loadPackage (rootUrl) {
let
{CONFIG_FILE} = this.config,
url = `${ rootUrl }/${ CONFIG_FILE }`,
pkg = yield getJSON(url);
return pkg;
}
}
export default SPM;
| JavaScript | 0 | @@ -52,16 +52,105 @@
events%22;
+%0Aimport map from %22lodash/collection/map%22;%0Aimport zipObject from %22lodash/array/zipObject%22;
%0A%0Aimport
@@ -190,16 +190,29 @@
getJSON
+, getJSONProp
%7D from
@@ -304,16 +304,25 @@
ructor (
+config=%7B%7D
) %7B%0A
@@ -359,16 +359,24 @@
w Config
+(config)
;%0A th
@@ -408,37 +408,40 @@
;%0A %7D%0A%0A //
-Public method
+Getters & setter
s%0A get curr
@@ -594,16 +594,251 @@
);%0A %7D%0A%0A
+ // Public methods%0A getVersions (pkgName) %7B%0A if (!pkgName)%0A throw new Error(%22No package name passed%22);%0A%0A return co(%0A this._getVersions.bind(this, pkgName)%0A%0A ).catch(%0A this.emit.bind(this, %22error%22)%0A );%0A %7D%0A%0A
load (
@@ -1069,37 +1069,38 @@
);%0A %7D%0A%0A // P
-ublic
+rivate
methods%0A _setP
@@ -1098,32 +1098,38 @@
s%0A
-_setPackage
+*_getVersions
(pkg
+Name
) %7B%0A
this
@@ -1128,46 +1128,220 @@
-this._currentPackage = new Package(pkg
+let%0A %7Bregistries%7D = this.config,%0A versions = map(registries, registry =%3E %7B%0A return getJSONProp(%60$%7B registry %7D/$%7B pkgName %7D%60, %22versions%22)%0A %7D);%0A%0A return yield zipObject(registries, versions
);%0A
@@ -1512,16 +1512,88 @@
pkg;%0A %7D
+%0A%0A _setPackage (pkg) %7B%0A this._currentPackage = new Package(pkg);%0A %7D
%0A%7D%0A%0Aexpo
|
1c445ca6378aa1725dd16a074963229ec5c5f17f | add chrome API check | plugins/sidebar/index.js | plugins/sidebar/index.js | 'use strict';
const React = require('react');
const ListItem = require('react-material/components/ListItem');
const Sidebar = require('./sidebar');
const FileList = require('./file-list');
const File = require('./file');
const FileOperations = require('./file-operations');
const ProjectOperations = require('./project-operations');
const deviceStore = require('../../src/stores/device');
const fileStore = require('../../src/stores/file');
const transmissionStore = require('../../src/stores/transmission');
const { loadFile } = require('../../src/actions/file');
function sidebar(app, opts, done){
const space = app.workspace;
const userConfig = app.userConfig;
const getBoard = app.getBoard.bind(app);
const scanBoards = app.scanBoards.bind(app);
// TODO: move into frylord?
chrome.syncFileSystem.onFileStatusChanged.addListener(function(detail){
if(detail.direction === 'remote_to_local'){
space.refreshDirectory();
}
});
chrome.syncFileSystem.onServiceStatusChanged.addListener(function(){
space.refreshDirectory();
});
app.view('sidebar', function(el, cb){
console.log('sidebar render');
const { cwd, directory } = space.getState();
var Component = (
<Sidebar>
<ProjectOperations />
<FileList workspace={space} loadFile={loadFile}>
<ListItem icon="folder" disableRipple>{cwd}</ListItem>
{directory.map(({ name, temp }) => <File key={name} filename={name} temp={temp} loadFile={loadFile} />)}
</FileList>
<FileOperations />
</Sidebar>
);
React.render(Component, el, cb);
});
space.subscribe(() => {
app.render();
});
// Store bindings
deviceStore.workspace = space;
deviceStore.getBoard = getBoard;
deviceStore.scanBoards = scanBoards;
fileStore.workspace = space;
fileStore.userConfig = userConfig;
transmissionStore.getBoard = getBoard;
done();
}
module.exports = sidebar;
| JavaScript | 0 | @@ -788,16 +788,103 @@
rylord?%0A
+ if(typeof chrome !== 'undefined' && typeof chrome.syncFileSystem !== 'undefined')%7B%0A
chrome
@@ -949,16 +949,18 @@
etail)%7B%0A
+
if(d
@@ -1001,24 +1001,26 @@
al')%7B%0A
+
space.refres
@@ -1041,16 +1041,22 @@
+
+
%7D%0A
+
%7D);%0A
+
ch
@@ -1122,24 +1122,26 @@
tion()%7B%0A
+
space.refres
@@ -1150,29 +1150,35 @@
irectory();%0A
+
%7D);
+%0A %7D
%0A%0A app.view
|
3896605bec916d4cf00d586d64aede700481dfbd | fix typo | createjson.js | createjson.js | const fs = require('fs');
const path = require('path');
const codelabsPath = '_posts/codelabs/';
const indexJson = [];
function readDir(lolPath) {
fs.readdir(lolPath, (err, files) => {
if (err) {
console.log(err);
throw err;
}
files
.map((file) => {
if (fs.statSync(path.join(lolPath, file)).isDirectory()) {
readDir(path.join(lolPath, file));
}
return path.join(lolPath, file);
})
.filter((file) => fs.statSync(file).isFile())
.forEach((file) => {
if (path.extname(file) === '.json' && file !== '_posts/codelabs/index.json') {
const obj = JSON.parse(fs.readFileSync(file, 'utf8'));
indexJson.push(obj);
const json = JSON.stringify(indexJson);
fs.writeFileSync('_posts/codelabs/index.json', json, 'utf8');
}
});
});
}
readDir(codelabsPath);
| JavaScript | 0.999991 | @@ -131,19 +131,19 @@
readDir(
-lol
+dir
Path) %7B%0A
@@ -155,19 +155,19 @@
readdir(
-lol
+dir
Path, (e
@@ -304,35 +304,35 @@
tSync(path.join(
-lol
+dir
Path, file)).isD
@@ -365,35 +365,35 @@
adDir(path.join(
-lol
+dir
Path, file));%0A
@@ -430,11 +430,11 @@
oin(
-lol
+dir
Path
|
53ecc46ba16a163edfa6219143ac4a6344b70426 | remove extra buffer creation | credential.js | credential.js | /**
* credential
*
* Easy password hashing and verification in Node.
* Protects against brute force, rainbow tables, and
* timing attacks.
*
* Cryptographically secure per-password salts prevent
* rainbow table attacks.
*
* Key stretching prevents brute force.
*
* Constant time verification prevents hang man timing
* attacks.
*
* Created by Eric Elliott for the book,
* "Programming JavaScript Applications" (O'Reilly)
*
* MIT license http://opensource.org/licenses/MIT
*/
'use strict';
var crypto = require('crypto'),
mixIn = require('mout/object/mixIn'),
pify = require('pify'),
P = require('pinkie-promise'),
constantTimeCompare = require('./constantTimeCompare'),
msPerDay = 24 * 60 * 60 * 1000,
msPerYear = 365.242199 * msPerDay,
y2k = new Date(2000, 0, 1),
minimalMsSinceEpoch = (2016 - 1970) * msPerYear,
defaultOptions = {
keyLength: 66,
work: 1,
hashMethod: 'pbkdf2'
},
/**
* pdkdf(password, salt, iterations,
* keyLength, callback) callback(err, hash)
*
* A standard to employ hashing and key stretching to
* prevent rainbow table and brute-force attacks, even
* if an attacker steals your password database.
*
* This function is a thin wrapper around Node's built-in
* crypto.pbkdf2().
*
* See Internet Engineering Task Force RFC 2898
*
* @param {String} password
* @param {String} salt
* @param {Number} iterations
* @param {Number} keyLength
* @param {Function} callback
* @return {undefined}
*/
pbkdf2 = function pbkdf2 (password, salt, iterations,
keyLength, callback) {
crypto.pbkdf2(password, salt,
iterations, keyLength, function (err, hash) {
if (err) {
return callback(err);
}
callback(null, new Buffer(hash).toString('base64'));
});
},
hashMethods = {
pbkdf2: pbkdf2
},
dateNow = function dateNow () {
var date = Date.now();
if (minimalMsSinceEpoch < date) {
return date;
}
return minimalMsSinceEpoch;
},
/**
* createSalt(keylength, callback) callback(err, salt)
*
* Generates a cryptographically secure random string for
* use as a password salt using Node's built-in
* crypto.randomBytes().
*
* @param {Number} keyLength
* @param {Function} callback
* @return {undefined}
*/
createSalt = function createSalt (keyLength, callback) {
crypto.randomBytes(keyLength, function (err, buff) {
if (err) {
return callback(err);
}
callback(null, buff.toString('base64'));
});
},
/**
* iterations(work)
*
* Computes iterations based on current year and a shifting
* factor.
*
* @param {Number} work
* @return {Number} iterations
*/
iterations = function iterations (work, base) {
var years = ((base || dateNow()) - y2k) / msPerYear;
return Math.floor(1000 * Math.pow(2, years / 2) * work);
},
/**
* isExpired(hash, days, work)
*
* Checks if a hash is older than the amount of days.
*
* @param {Number} hash
* @param {Number} days
* @param {Number} work
* @return {bool}
*/
isExpired = function isExpired (hash, days, work){
var base = dateNow() - (days || 90) * msPerDay;
var minIterations = iterations(work, base);
return JSON.parse(hash).iterations < minIterations;
},
/**
* toHash(password, hashMethod, keyLength, work, callback) callback(err, hash)
*
* Takes a new password and creates a unique hash. Passes
* a JSON encoded object to the callback.
*
* @param {[type]} password
* @param {String} hashMethod
* @param {Number} keyLength
* @param {Number} work
* @param {Function} callback
*/
/**
* callback
* @param {Error} Error Error or null
* @param {String} hashObject JSON string
* @param {String} hashObject.hash
* @param {String} hashObject.salt
* @param {Number} hashObject.keyLength
* @param {String} hashObject.hashMethod
* @param {Number} hashObject.iterations
* @return {undefined}
*/
toHash = function toHash (password, hashMethod, keyLength, work, callback) {
var n = iterations(work);
if (typeof (password) !== 'string' || password.length === 0) {
return callback(new Error('Password must be a ' +
' non-empty string.'));
}
// Create the salt
createSalt(keyLength, function (err, salt) {
if (err) {
return callback(err);
}
// Then create the hash
hashMethods[hashMethod](password, salt,
n, keyLength,
function (err, hash) {
if (err) {
return callback(err);
}
callback(null, JSON.stringify({
hash: hash,
salt: salt,
keyLength: keyLength,
hashMethod: hashMethod,
iterations: n
}));
});
});
},
parseHash = function parseHash (encodedHash) {
try {
return JSON.parse(encodedHash);
} catch (err) {
return err;
}
},
/**
* verifyHash(hash, input, callback) callback(err, isValid)
*
* Takes a stored hash, password input from the user,
* and a callback, and determines whether or not the
* user's input matches the stored password.
*
* @param {String} hash stored JSON object
* @param {String} input user's password input
* @param {Function} callback(err, isValid)
*/
verifyHash = function verifyHash (hash, input, callback) {
var storedHash = parseHash(hash);
if (!hashMethods[storedHash.hashMethod]) {
return callback(new Error('Couldn\'t parse stored ' +
'hash.'));
} else if (typeof (input) !== 'string' || input.length === 0) {
return callback(new Error('Input password must ' +
' be a non-empty string.'));
}
var n = storedHash.iterations;
hashMethods[storedHash.hashMethod](input, storedHash.salt,
n, storedHash.keyLength,
function (err, newHash) {
if (err) {
return callback(err);
}
callback(null, constantTimeCompare(newHash, storedHash.hash));
});
};
module.exports = function credential (opts) {
var options = mixIn({}, defaultOptions, opts);
return {
verify: function (hash, input, callback) {
if (!callback) {
return pify(verifyHash, P)(hash, input);
}
verifyHash(hash, input, callback);
},
iterations: iterations,
hash: function (password, callback) {
if (!callback) {
return pify(toHash, P)(password, options.hashMethod, options.keyLength, options.work);
}
toHash(password, options.hashMethod, options.keyLength, options.work, callback);
},
expired: function (hash, days) {
return isExpired(hash, days, options.work);
}
};
};
| JavaScript | 0.000001 | @@ -1790,24 +1790,12 @@
ll,
-new Buffer(
hash
-)
.toS
|
401c7b04ace9311ca51264f2a68c9fc09560224c | Remove bar timer | src/js/round/clock/view.js | src/js/round/clock/view.js | var m = require('mithril');
var classSet = require('chessground').util.classSet;
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
function bold(x) {
return '<b>' + x + '</b>';
}
function formatClockTime(ctrl, time) {
var date = new Date(time);
var minutes = prefixInteger(date.getUTCMinutes(), 2);
var seconds = prefixInteger(date.getSeconds(), 2);
var tenths;
if (ctrl.data.showTenths && time < 10000) {
tenths = Math.floor(date.getMilliseconds() / 100);
return bold(minutes) + ':' + bold(seconds) + '<span>.' + bold(tenths) + '</span>';
} else if (time >= 3600000) {
var hours = prefixInteger(date.getUTCHours(), 2);
return bold(hours) + ':' + bold(minutes) + ':' + bold(seconds);
} else {
return bold(minutes) + ':' + bold(seconds);
}
}
module.exports = function(ctrl, color, runningColor) {
var time = ctrl.data[color];
return m('div', {
class: 'clock clock_' + color + ' ' + classSet({
'outoftime': !time,
'running': runningColor === color,
'emerg': time < ctrl.data.emerg
})
}, [
m('div.timer.before', {
style: {
width: Math.max(0, Math.min(100, (time / ctrl.data.initial) * 100)) + '%'
}
}),
m('div.time', m.trust(formatClockTime(ctrl, time * 1000)))
]);
};
| JavaScript | 0.000001 | @@ -1113,149 +1113,8 @@
, %5B%0A
- m('div.timer.before', %7B%0A style: %7B%0A width: Math.max(0, Math.min(100, (time / ctrl.data.initial) * 100)) + '%25'%0A %7D%0A %7D),%0A
|
94def5257c300501c74502951d28979cf7a24d21 | replace $server global var with call to wptServer() | filmstrip.js | filmstrip.js | <?php
/*
Copyright 2010 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.
*/
require_once("utils.inc");
$gPageid = getParam('pageid');
$query = "select url, wptid, wptrun, onLoad, renderStart from $gPagesTable where pageid='$gPageid';";
$result = doQuery($query);
$row = mysql_fetch_assoc($result);
$url = $row['url'];
$wptid = $row['wptid'];
$wptrun = $row['wptrun'];
$onLoad = $row['onLoad'];
$interval = ( $gbMobile ? 1000 : ( $onLoad > 15000 ? 5000 : ( $onLoad > 4000 ? 1000 : ( $onLoad > 1000 ? 500 : 100 ) ) ) );
$renderStart = $row['renderStart'];
$xmlurl = "{$server}xmlResult.php?test=$wptid";
$xmlstr = file_get_contents($xmlurl);
$xml = new SimpleXMLElement($xmlstr);
$frames = $xml->data->run[($wptrun - 1)]->firstView->videoFrames;
$aTimes = array();
foreach($frames->frame as $frame) {
$time = floatval($frame->time) * 1000;
$aTimes[$time] = true;
}
$sTh = "";
$sTd = "";
$aMatches = array();
$url = "";
$pattern = '/([0-9][0-9])([0-9][0-9])([0-9][0-9])_(.*)/';
if ( preg_match($pattern, $wptid, $aMatches) ) {
$url = "{$server}results/" . $aMatches[1] . "/" . $aMatches[2] . "/" . $aMatches[3] . "/" . str_replace('_', '/', $aMatches[4]) . "/video_$wptrun/frame_";
}
$lastFrameTime = 0;
for ( $i = 0; $i < ($onLoad+100); $i += 100 ) {
$sTh .= "<th id=th$i style='display: none;'>" . ($i/1000) . "s</th> ";
//$border = "";
$class = "thumb";
if ( array_key_exists($i, $aTimes) ) {
$lastFrameTime = $i;
//$border = "style='border: 3px solid #FEB301;'";
$class = "thumb changed";
}
$f = "0000" . ($lastFrameTime/100);
$f = substr($f, strlen($f)-4);
if ( $gbMobile && "0000" == $f ) {
// There's a bug in Blaze's WPT that calls the "0.0s" image "frame_0010.jpg" instead of "frame_0000.jpg".
$f = "0010";
}
$sTd .= "<td id=td$i class='$class' style='display: none;'><a target='_blank' href='$url$f.jpg'><img width=" .
( $gbMobile ? "93" : "200" ) .
" height=140 id='{$server}thumbnail.php?test=$wptid&width=200&file=video_$wptrun/frame_$f.jpg'></a></td>";
}
?>
var sTh = "<?php echo $sTh ?>";
var sTd = "<?php echo $sTd ?>";
document.getElementById('videoDiv').innerHTML = "<table id='video'><tr>" + sTh + "</tr><tr>" + sTd + "</tr></table>";
showInterval(<?php echo $interval ?>);
| JavaScript | 0.000007 | @@ -618,17 +618,42 @@
geid');%0A
+$wptServer = wptServer();
%0A
-
$query =
@@ -1075,25 +1075,28 @@
xmlurl = %22%7B$
-s
+wptS
erver%7DxmlRes
@@ -1554,17 +1554,20 @@
rl = %22%7B$
-s
+wptS
erver%7Dre
@@ -2424,17 +2424,20 @@
0 id='%7B$
-s
+wptS
erver%7Dth
|
762a8d35db181f2f1c58415675b8f1c32eb61567 | Fix docs link | app/pages/HomePage/index.js | app/pages/HomePage/index.js | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import shouldPureComponentUpdate from 'react-pure-render/function';
import Button from 'Button';
import GettingStarted from 'GettingStarted';
import Features from 'Features';
import Contribute from 'Contribute';
import Logo from './react-boilerplate-logo.svg'
import styles from './styles.css';
export class HomePage extends React.Component {
shouldComponentUpdate = shouldPureComponentUpdate;
/**
* Changes the route
*
* @param {string} route The route we want to go to
*/
openRoute = (route) => {
this.props.changeRoute(route);
};
render() {
return (
<main className={ styles.homePage }>
<nav className={ styles.nav } >
<Button icon="download" outlined collapsable href="https://github.com/mxstbr/react-boilerplate/archive/master.zip">Download</Button>
<Button icon="book">Docs</Button>
<Button icon="github-logo" outlined collapsable href="https://github.com/mxstbr/react-boilerplate">Source</Button>
</nav>
<header className={ styles.header }>
<Logo className={ styles.logo }/>
<p>Quick setup for new performance orientated, offline–first React.js applications</p>
</header>
<article className={ styles.content }>
<GettingStarted />
<Features />
</article>
<Contribute />
</main>
);
}
}
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url)),
dispatch,
};
}
// Wrap the component to inject dispatch and state into it
export default connect(null, mapDispatchToProps)(HomePage);
| JavaScript | 0 | @@ -1035,16 +1035,84 @@
n=%22book%22
+ href=%22https://github.com/mxstbr/react-boilerplate/tree/master/docs%22
%3EDocs%3C/B
|
da9fe41e74a64eff77134979745b2081fd22155a | Clean up lint errors for ProSignup | client/src/components/Signup/ProSignup.js | client/src/components/Signup/ProSignup.js | import React, { Component } from 'react';
import { Button, Form, Grid, Header, Icon } from 'semantic-ui-react';
export default class ProSignup extends Component {
constructor() {
super()
}
render() {
return(
<div>
<div className="signup-buttons">
<Header textAlign='center'><Icon name="travel"/>Professional Signup</Header>
</div>
<Grid width={16}>
<Grid.Column width={5}>
</Grid.Column>
<Grid.Column width={11}>
<Form>
<Form.Field width="8">
<label>First Name</label>
<input placeholder='First Name' />
</Form.Field>
<Form.Field width="8">
<label>Last Name</label>
<input placeholder='Last Name' />
</Form.Field>
<Form.Field width="8">
<label>Email</label>
<input placeholder='Email' />
</Form.Field>
<Form.Field width="8">
<label>Password</label>
<input placeholder='Password' />
</Form.Field>
<Form.Field width="8">
<label>Confirm Password</label>
<input placeholder='Confirm Password' />
</Form.Field>
<Form.Field width="8">
<Button type='submit'>Sign Up</Button>
</Form.Field>
</Form>
</Grid.Column>
</Grid>
</div>
)
}
}
| JavaScript | 0 | @@ -186,16 +186,17 @@
super()
+;
%0A %7D%0A%0A
@@ -216,16 +216,17 @@
return
+
(%0A
@@ -304,16 +304,16 @@
ign=
-'
+%22
center
-'
+%22
%3E%3CIc
@@ -328,16 +328,17 @@
%22travel%22
+
/%3EProfes
@@ -437,33 +437,10 @@
=%7B5%7D
-%3E%0A %3C/Grid.Column
+ /
%3E%0A
@@ -550,16 +550,35 @@
%3Clabel
+ htmlFor=%22password%22
%3EFirst N
@@ -624,17 +624,17 @@
eholder=
-'
+%22
First Na
@@ -631,25 +631,25 @@
=%22First Name
-'
+%22
/%3E%0A
@@ -727,16 +727,35 @@
%3Clabel
+ htmlFor=%22password%22
%3ELast Na
@@ -800,17 +800,17 @@
eholder=
-'
+%22
Last Nam
@@ -810,17 +810,17 @@
ast Name
-'
+%22
/%3E%0A
@@ -902,16 +902,35 @@
%3Clabel
+ htmlFor=%22password%22
%3EEmail%3C/
@@ -975,15 +975,15 @@
der=
-'
+%22
Email
-'
+%22
/%3E%0A
@@ -1069,16 +1069,35 @@
%3Clabel
+ htmlFor=%22password%22
%3EPasswor
@@ -1145,17 +1145,17 @@
der=
-'
+%22
Password
' /%3E
@@ -1142,33 +1142,33 @@
holder=%22Password
-'
+%22
/%3E%0A
@@ -1242,16 +1242,35 @@
%3Clabel
+ htmlFor=%22password%22
%3EConfirm
@@ -1322,17 +1322,17 @@
eholder=
-'
+%22
Confirm
@@ -1339,17 +1339,17 @@
Password
-'
+%22
/%3E%0A
@@ -1442,16 +1442,16 @@
ype=
-'
+%22
submit
-'
+%22
%3ESig
@@ -1571,15 +1571,16 @@
v%3E%0A )
+;
%0A %7D%0A%7D%0A
|
1aa2c7437f8571870cfcfdcc46f8582d25a0e963 | Replace bootstrap modal in Groups Component | client/src/js/groups/components/Groups.js | client/src/js/groups/components/Groups.js | import { push } from "connected-react-router";
import { find, get, includes, map, sortBy } from "lodash-es";
import React from "react";
import { InputGroup } from "react-bootstrap";
import { connect } from "react-redux";
import styled from "styled-components";
import {
BoxGroup,
Button,
InputError,
LoadingPlaceholder,
Icon,
DialogBody,
ModalDialog,
DialogHeader
} from "../../base";
import { clearError } from "../../errors/actions";
import { routerLocationHasState } from "../../utils/utils";
import { createGroup, removeGroup, setGroupPermission } from "../actions";
import { GroupDetail } from "./Detail";
import Group from "./Group";
const GroupsModalBody = styled(DialogBody)`
display: grid;
grid-template-columns: 2fr 3fr;
grid-column-gap: 15px;
`;
class Groups extends React.Component {
constructor(props) {
super(props);
this.state = {
createGroupId: "",
spaceError: false,
submitted: false,
error: ""
};
}
handleModalExited = () => {
this.setState({
createGroupId: "",
spaceError: false,
submitted: false,
error: ""
});
if (this.props.error) {
this.props.onClearError("CREATE_GROUP_ERROR");
}
};
handleChange = e => {
this.setState({
createGroupId: e.target.value,
spaceError: this.state.spaceError && includes(e.target.value, " "),
submitted: false,
error: ""
});
if (this.props.error) {
this.props.onClearError("CREATE_GROUP_ERROR");
}
};
handleSubmit = e => {
e.preventDefault();
if (this.state.createGroupId === "") {
this.setState({
error: "Group id missing"
});
} else if (includes(this.state.createGroupId, " ")) {
this.setState({
spaceError: true
});
} else {
this.setState(
{
spaceError: false,
submitted: true,
error: ""
},
() => this.props.onCreate(this.state.createGroupId)
);
}
};
render() {
if (this.props.groups === null || this.props.users === null) {
return <LoadingPlaceholder margin="130px" />;
}
const groupComponents = map(sortBy(this.props.groups, "id"), group => <Group key={group.id} {...group} />);
const activeGroup = find(this.props.groups, { id: this.props.activeId });
let error;
if (this.state.submitted && this.props.error) {
error = this.props.error;
}
if (this.state.spaceError) {
error = "Group names may not contain spaces";
}
return (
<ModalDialog
label="group"
size="lg"
show={this.props.show}
onHide={this.props.onHide}
onExited={this.handleModalExited}
>
<DialogHeader>
Groups
<Icon name="times" onClick={this.handleHide} style={{ color: "grey" }} />
</DialogHeader>
<GroupsModalBody>
<div>
<InputGroup>
<InputError
type="text"
value={this.state.createGroupId}
onChange={this.handleChange}
placeholder="Group name"
error={error || this.state.error}
/>
<InputGroup.Button style={{ verticalAlign: "top", zIndex: "0" }}>
<Button type="button" icon="plus-square" bsStyle="primary" onClick={this.handleSubmit}>
Add
</Button>
</InputGroup.Button>
</InputGroup>
<br />
<BoxGroup>{groupComponents}</BoxGroup>
</div>
<GroupDetail
group={activeGroup}
pending={this.props.pending}
users={this.props.users}
onRemove={this.props.onRemove}
onSetPermission={this.props.onSetPermission}
/>
</GroupsModalBody>
</ModalDialog>
);
}
}
const mapStateToProps = state => {
return {
show: routerLocationHasState(state, "groups"),
users: state.users.documents,
groups: state.groups.documents,
pending: state.groups.pending,
activeId: state.groups.activeId,
error: get(state, "errors.CREATE_GROUP_ERROR.message", "")
};
};
const mapDispatchToProps = dispatch => ({
onCreate: groupId => {
dispatch(createGroup(groupId));
},
onHide: () => {
dispatch(push({ ...window.location, state: { groups: false } }));
},
onRemove: groupId => {
dispatch(removeGroup(groupId));
},
onSetPermission: (groupId, permission, value) => {
dispatch(setGroupPermission(groupId, permission, value));
},
onClearError: error => {
dispatch(clearError(error));
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Groups);
| JavaScript | 0.000003 | @@ -263,20 +263,16 @@
import %7B
-%0A
BoxGrou
@@ -277,20 +277,16 @@
oup,
-%0A
Button,
%0A
@@ -281,20 +281,16 @@
Button,
-%0A
InputEr
@@ -293,20 +293,16 @@
utError,
-%0A
Loading
@@ -317,22 +317,8 @@
der,
-%0A Icon,%0A
Dia
@@ -325,20 +325,16 @@
logBody,
-%0A
ModalDi
@@ -341,27 +341,9 @@
alog
-,%0A DialogHeader%0A
+
%7D fr
@@ -3072,195 +3072,46 @@
- %3E%0A
- %3CDialogHeader%3E%0A Groups%0A %3CIcon name=%22times%22 onClick=%7Bthis.handleHide%7D style=%7B%7B color: %22grey%22 %7D%7D /%3E%0A %3C/DialogHeader%3E%0A
+headerText=%22Groups%22%0A %3E
%0A
|
3ef8e6f1c4374320a25d9a3da5dbccc5a7d7f0d3 | Call initialize on original L.Map instead | src/leaflet.dataoptions.js | src/leaflet.dataoptions.js | //
// leaflet.dataoptions
//
// A Leaflet plugin that makes it easy to configure a Leaflet map using data
// attributes on the map's DOM element.
//
(function () {
function defineDataOptions(L) {
L.Map = L.Map.extend({
// Override the default constructor to get options from data
// attributes
initialize: function (id, options) {
// Get the data prefix for attribute names
var prefix = 'data-l-';
if (options !== undefined && options.dataOptionsPrefix !== undefined) {
prefix = options.dataOptionsPrefix;
}
// Find options given by data attribute, add to existing options
var dataAttributeOptions = this.loadDataAttributeOptions(id, prefix);
options = L.extend(dataAttributeOptions, options);
// Carry on as usual
L.Map.__super__.initialize.call(this, id, options);
},
loadDataAttributeOptions: function (id, prefix) {
var element = L.DomUtil.get(id),
attributes = element.attributes,
length = attributes.length,
newOptions = {};
for (var i = 0; i < length; i++) {
var attribute = attributes[i];
if (attribute.name.search(prefix) === 0) {
var name = attribute.name.slice(prefix.length),
camelCaseName = this.camelCaseDataAttributeName(name),
value = this.parseDataAttributeValue(attribute.value);
newOptions[camelCaseName] = newOptions[name] = value;
}
}
return newOptions;
},
camelCaseDataAttributeName: function (name) {
var nameParts = name.split('-'),
camelCaseName = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
camelCaseName += nameParts[i][0].toUpperCase();
camelCaseName += nameParts[i].slice(1);
}
return camelCaseName;
},
parseDataAttributeValue: function (value) {
try {
return JSON.parse(value);
}
catch (e) {
// If parsing as JSON fails, return original string
return value;
}
}
});
}
if (typeof define === 'function' && define.amd) {
// Try to add dataoptions to Leaflet using AMD
define(['leaflet'], function (L) {
defineDataOptions(L);
});
}
else {
// Else use the global L
defineDataOptions(L);
}
})();
| JavaScript | 0 | @@ -200,16 +200,47 @@
s(L) %7B%0A%0A
+ var LMapOrig = L.Map;%0A%0A
@@ -967,22 +967,25 @@
L
-.
Map
-.__super__
+Orig.prototype
.ini
|
e769dbab4fd867d8b76f6bdf5061600f964e0db9 | Fix myCounterparts tests | client/tests/webdriver/pages/home.page.js | client/tests/webdriver/pages/home.page.js | import Page from "./page"
class Home extends Page {
get topbar() {
return browser.$("#topbar")
}
get ie11BannerText() {
const ieBanner = browser.$("#ieBanner")
ieBanner.waitForExist()
ieBanner.waitForDisplayed()
return browser.$("#ieBanner > div:nth-child(2)").getText()
}
get securityBanner() {
const banner = browser.$("#topbar .banner")
banner.waitForExist()
banner.waitForDisplayed()
return banner
}
get searchBar() {
return browser.$("#searchBarInput")
}
get homeTilesContainer() {
return browser.$("fieldset.home-tile-row")
}
get pendingMyApprovalOfCount() {
return browser
.$('//button[contains(text(), "Reports pending my approval")]')
.$("h1")
}
get submitSearch() {
return browser.$("#topbar #searchBarSubmit")
}
get linksMenuButton() {
return browser.$("#nav-links-button")
}
get myOrgLink() {
return browser.$("#my-organization")
}
get myTasksLink() {
return browser.$("#my-tasks-nav")
}
get myCounterpartsLink() {
return browser.$("#my-counterparts-nav")
}
get myCounterpartsNotifications() {
return this.myCounterpartsLink.$("span:last-child")
}
get myTasksNotifications() {
return this.myTasksLink.$("span:last-child")
}
get onboardingPopover() {
return browser.$(".hopscotch-bubble-container")
}
waitForSecurityBannerValue(value) {
this.securityBanner.waitForExist()
this.securityBanner.waitForDisplayed()
return browser.waitUntil(
() => {
return this.securityBanner.getText() === value
},
{ timeout: 5000, timeoutMsg: "Expected different banner text after 5s" }
)
}
}
export default new Home()
| JavaScript | 0 | @@ -867,27 +867,31 @@
r.$(
-%22#nav-links-button%22
+'//a%5Btext()=%22My Work%22%5D'
)%0A
@@ -1078,14 +1078,31 @@
r.$(
-%22#my-c
+'//a//span%5Btext()=%22My C
ount
@@ -1108,21 +1108,19 @@
terparts
--nav%22
+%22%5D'
)%0A %7D%0A%0A
|
482b18bc542a2bb593492f1b7a7dcae62fb228e3 | Add additional tests in API tester. | external/api_tester/api_test.js | external/api_tester/api_test.js | /**
* Copyright 2018 The Lovefield Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const chai = require('chai');
const lf = require('lovefield-ts');
const assert = chai.assert;
function assertMethods(obj, methodNames, target) {
methodNames.forEach((methodName) => {
const hasMethod = typeof obj[methodName] === 'function';
if (!hasMethod) {
throw new Error(`Missing ${methodName} from ${target}`);
}
});
}
function assertAttributes(obj, attributeNames, target) {
attributeNames.forEach((attributeName) => {
if (!Object.prototype.hasOwnProperty.call(obj, attributeName)) {
throw new Error(`Missing ${attributeName} from ${target}`);
}
});
}
describe('ApiTester', async () => {
let builder;
let tableBuilder;
before(() => {
builder = lf.schema.create('apiCheck', 1);
tableBuilder = builder
.createTable('DummyTable')
.addColumn('number', lf.Type.NUMBER)
.addColumn('dateTime', lf.Type.DATE_TIME)
.addColumn('string', lf.Type.STRING)
.addColumn('boolean', lf.Type.BOOLEAN)
.addColumn('arrayBuffer', lf.Type.ARRAY_BUFFER)
.addColumn('object', lf.Type.OBJECT);
});
it('hasAttributes', () => {
assertAttributes(
lf,
[
// enums
'ConstraintAction',
'ConstraintTiming',
'Order',
'TransactionType',
'Type',
// classes
'fn',
'op',
'schema',
],
'lf',
);
assertMethods(lf, ['bind'], 'lf');
});
it('enumType', () => {
assertAttributes(
lf.Type,
[
'ARRAY_BUFFER',
'BOOLEAN',
'DATE_TIME',
'INTEGER',
'NUMBER',
'STRING',
'OBJECT',
],
'lf.Type',
);
});
it('enumOrder', () => {
assertAttributes(lf.Order, ['ASC', 'DESC'], 'lf.Order');
});
it('enumTransactionType', () => {
assertAttributes(
lf.TransactionType,
['READ_ONLY', 'READ_WRITE'],
'lf.TransactionType',
);
});
it('enumDataStoreType', () => {
assertAttributes(
lf.DataStoreType,
['INDEXED_DB', 'MEMORY', 'LOCAL_STORAGE', 'WEB_SQL'],
'lf.DataStoreType',
);
});
it('enumConstraintAction', () => {
assertAttributes(
lf.ConstraintAction,
['RESTRICT', 'CASCADE'],
'lf.ConstraintAction',
);
});
it('enumConstraintTiming', () => {
assertAttributes(
lf.ConstraintTiming,
['IMMEDIATE', 'DEFERRABLE'],
'lf.ConstraintTiming',
);
});
it('apiFn', () => {
assertMethods(
lf.fn,
['avg', 'count', 'distinct', 'max', 'min', 'stddev', 'sum', 'geomean'],
'lf.fn',
);
});
it('apiOp', () => {
assertMethods(lf.op, ['and', 'or', 'not'], 'lf.op');
});
it('apiSchemaBuilder', () => {
assertMethods(lf.schema, ['create'], 'lf.schema');
assertMethods(
builder,
['createTable', 'connect', 'setPragma', 'getSchema'],
'schemaBuilder',
);
assertMethods(
tableBuilder,
[
'addColumn',
'addPrimaryKey',
'addForeignKey',
'addUnique',
'addNullable',
'addIndex',
'persistentIndex',
],
'tableBuilder',
);
});
it('Capability', () => {
const cap = lf.Capability.get();
assert.isDefined(cap);
assert.isNotNull(cap);
assertAttributes(
cap,
['supported', 'indexedDb', 'localStorage', 'webSql'],
'Capability',
);
});
});
| JavaScript | 0 | @@ -1301,16 +1301,40 @@
Builder;
+%0A let db;%0A let schema;
%0A%0A befo
@@ -1742,16 +1742,168 @@
BJECT);%0A
+ return builder.connect(%7B%0A DataStoreType: lf.DataStoreType.MEMORY%0A %7D).then(conn =%3E %7B%0A db = conn;%0A schema = db.getSchema();%0A %7D);%0A
%7D);%0A%0A
@@ -4320,13 +4320,832 @@
);%0A %7D);
+%0A%0A it('connection', () =%3E %7B%0A assertMethods(%0A db,%0A %5B%0A 'getSchema',%0A 'select',%0A 'insert',%0A 'insertOrReplace',%0A 'update',%0A 'delete',%0A 'observe',%0A 'unobserve',%0A 'createTransaction',%0A 'close',%0A 'export',%0A 'import',%0A 'isOpen',%0A %5D,%0A 'db',%0A );%0A %7D);%0A%0A it('DBSchema', () =%3E %7B%0A assertMethods(%0A schema,%0A %5B%0A 'name',%0A 'version',%0A 'tables',%0A 'info',%0A 'table',%0A 'pragma',%0A %5D,%0A 'schema',%0A );%0A %7D);%0A%0A it('TableSchema', () =%3E %7B%0A const table = schema.table('DummyTable');%0A assert.isNotNull(table);%0A assertMethods(%0A table,%0A %5B'as', 'createRow'%5D,%0A 'table',%0A );%0A %7D);
%0A%7D);%0A
|
a09eae7d085e53a5e0e9f60e6becbcf3e3e45515 | combine routing reducer | app/store/configureStore.js | app/store/configureStore.js | import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
import DevTools from '../components/DevTools' // make it NODE_ENV-dependent
const finalCreateStore = getCreateStoreModifier()(createStore)
export default (initialState) => finalCreateStore(rootReducer, initialState)
function getCreateStoreModifier () {
if (process.env.NODE_ENV === 'development') {
return compose(
applyMiddleware(thunk),
DevTools.instrument()
)
} else {
return applyMiddleware(thunk)
}
}
| JavaScript | 0.000001 | @@ -1,16 +1,33 @@
import %7B
+ combineReducers,
createS
@@ -104,16 +104,68 @@
-thunk'%0A
+import %7B routeReducer %7D from 'redux-simple-router'%0A%0A
import r
@@ -271,16 +271,145 @@
endent%0A%0A
+// let redux store the current URL%0Aconst reducer = combineReducers(Object.assign(%7B%7D, rootReducer, %7B%0A routing: routeReducer%0A%7D))%0A%0A
const fi
@@ -515,20 +515,16 @@
eStore(r
-ootR
educer,
|
dfcafb7b0037abc6bb4cbff5639bdb836c6a62d0 | update analytics code | public/javascripts/analytics_lib.js | public/javascripts/analytics_lib.js | /*------------------------------------------------------------------+
| Utilizes event tracking in Google Analytics to track |
| clicks on outbound, document, and email links. |
| Requires jQuery |
+-------------------------------------------------------------------*/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31505617-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
_trackClickEventWithGA = function (category, action, label) {
if (typeof(_gaq) != 'undefined')
_gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);
_gaq.push(['_trackEvent', category, action, label]);
};
jQuery(function () {
jQuery('a').click(function () {
var $a = jQuery(this);
var href = $a.attr("href");
//links going to outside sites
if (href.match(/^http/i) && !href.match(document.domain)) {
_trackClickEventWithGA("Outgoing", "Click", href);
}
//direct links to files
if (href.match(/\.(avi|css|doc|docx|exe|gif|js|jpg|mov|mp3|pdf|png|ppt|pptx|rar|txt|vsd|vxd|wma|wmv|xls|xlsx|zip)$/i)) {
_trackClickEventWithGA("Downloads", "Click", href);
}
//email links
if (href.match(/^mailto:/i)) {
_trackClickEventWithGA("Emails", "Click", href);
}
});
});
| JavaScript | 0 | @@ -918,16 +918,16 @@
'UA-
-xxxxxxxx
+31505617
-1'%5D
|
df21ff82b5e2c460cc71571a1cfaf7487c8c5e28 | add new line | dashboard/test/unit/test_refresh.js | dashboard/test/unit/test_refresh.js | /*
* Copyright 2015 Telefónica I+D
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
'use strict';
var assert = require('assert'),
sinon = require('sinon'),
http = require('http'),
common = require('../../lib/routes/common'),
refresh = require('../../lib/routes/refresh');
/* jshint multistr: true */
suite('refresh', function () {
test('test_get_refresh', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = "Admin";
var request_stub = sinon.stub();
var http_stub = sinon.stub(http, 'request').returns(request_stub);
request_stub.on = sinon.stub();
request_stub.write = sinon.stub();
request_stub.end = sinon.stub();
//when
refresh.get_refresh(req, res);
//then
assert(request_stub.on.calledOnce);
assert(request_stub.write.calledOnce);
assert(request_stub.end.calledOnce);
http_stub.restore();
});
test('test_get_refresh_with_undefined_role', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = undefined;
var common_stub = sinon.stub(common, 'notAuthorized');
//when
refresh.get_refresh(req, res);
//then
assert(common_stub.calledOnce);
common_stub.restore();
});
});
| JavaScript | 0.002414 | @@ -2111,12 +2111,13 @@
%7D);%0A%7D);%0A
+%0A
|
69f21295477743d5be7b191c4bae5e15db081315 | Remove the toLowerCase function call as it doesn't work on this object, and it's going to be lower case anyway | generators/aws/lib/s3.js | generators/aws/lib/s3.js | const fs = require('fs');
const FILE_EXTENSION = '.original';
const S3_STANDARD_REGION = 'us-east-1';
let Progressbar;
const S3 = module.exports = function S3(Aws, generator) {
this.Aws = Aws;
try {
Progressbar = require('progress'); // eslint-disable-line
} catch (e) {
generator.error(`Something went wrong while running jhipster:aws:\n${e}`);
}
};
S3.prototype.createBucket = function createBucket(params, callback) {
const bucket = params.bucket;
const region = this.Aws.config.region;
const s3Params = {
Bucket: bucket,
CreateBucketConfiguration: { LocationConstraint: region }
};
if (region.toLowerCase() === S3_STANDARD_REGION) {
s3Params.CreateBucketConfiguration = undefined;
}
const s3 = new this.Aws.S3({
params: s3Params,
signatureVersion: 'v4'
});
s3.headBucket((err) => {
if (err && err.statusCode === 404) {
s3.createBucket((err) => {
if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} created successfully`, callback);
}
});
} else if (err && err.statusCode === 301) {
error(`Bucket ${bucket} is already in use`, callback);
} else if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} already exists`, callback);
}
});
};
S3.prototype.uploadWar = function uploadWar(params, callback) {
const bucket = params.bucket;
const buildTool = params.buildTool;
let buildFolder;
if (buildTool === 'gradle') {
buildFolder = 'build/libs/';
} else {
buildFolder = 'target/';
}
findWarFilename(buildFolder, (err, warFilename) => {
if (err) {
error(err, callback);
} else {
const warKey = warFilename.slice(0, -FILE_EXTENSION.length);
const s3 = new this.Aws.S3({
params: {
Bucket: bucket,
Key: warKey
},
signatureVersion: 'v4',
httpOptions: { timeout: 600000 }
});
const filePath = buildFolder + warFilename;
const body = fs.createReadStream(filePath);
uploadToS3(s3, body, (err, message) => {
if (err) {
error(err.message, callback);
} else {
callback(null, { message, warKey });
}
});
}
});
};
function findWarFilename(buildFolder, callback) {
let warFilename = '';
fs.readdir(buildFolder, (err, files) => {
if (err) {
error(err, callback);
}
files
.filter(file => file.substr(-FILE_EXTENSION.length) === FILE_EXTENSION)
.forEach((file) => {
warFilename = file;
});
callback(null, warFilename);
});
}
function uploadToS3(s3, body, callback) {
let bar;
s3.waitFor('bucketExists', (err) => {
if (err) {
callback(err, null);
} else {
s3.upload({ Body: body }).on('httpUploadProgress', (evt) => {
if (bar === undefined && evt.total) {
const total = evt.total / 1000000;
bar = new Progressbar('uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 20,
total,
clear: true
});
}
const curr = evt.loaded / 1000000;
bar.tick(curr - bar.curr);
}).send((err) => {
if (err) {
callback(err, null);
} else {
callback(null, 'War uploaded successful');
}
});
}
});
}
function success(message, callback) {
callback(null, { message });
}
function error(message, callback) {
callback({ message }, null);
}
| JavaScript | 0.000008 | @@ -667,22 +667,8 @@
gion
-.toLowerCase()
===
|
ebbbb7a7721f62bfa9580199ce4af29c41d91daa | Add jsdoc. | common/models/member.js | common/models/member.js | var loopback = require('loopback');
var path = require('path');
var debug = require('debug')('freecoder:member');
module.exports = function (Member) {
// send verification email after registration
// refer to http://docs.strongloop.com/display/public/LB/Remote+hooks
Member.afterRemote('create', function (context, member, next) {
debug('> Member.afterRemote("create") triggered');
var options = {
type: 'email',
to: member.email,
from: 'support@freecoder.net', //TODO: read from configuration
subject: 'Thanks for registering.',
template: path.resolve(__dirname, '../../server/email_templates/registration_verify.ejs'),
redirect: encodeURIComponent('/#/dashboard')
};
member.verify(options, function (err, response) {
if (err) {
next(err);
return;
}
debug('>> verification email sent:', response);
next();
});
});
Member.changePassword = function (access_token, options, cb) {
debug('> Member.changePassword().', access_token, options);
Member.validatePassword(options.oldPass);
Member.validatePassword(options.newPass);
//if (!options.oldPass || !options.newPass) {
// var msg = 'oldPass or newPass is invalid.';
// debug(msg);
// cb(msg)
//}
var ctx = loopback.getCurrentContext();
var accessToken = ctx.get('accessToken');
var userId = accessToken.userId;
this.findById(userId, function (err, user) {
if (err) {
cb(err);
}
debug(">> get User:", user);
user.hasPassword(options.oldPass, function (err, isMatch) {
if (err) {
debug('>> verify old password failed: ', err);
cb(err);
}
if (isMatch) {
user.password = Member.hashPassword(options.newPass);
user.save(function (err) {
if (err) {
cb(err);
} else {
debug('>> change password successful.');
cb();
}
});
} else {
cb('Invalid password.');
}
});
});
};
Member.remoteMethod('changePassword', {
description: "Change password by verify current password.",
http: {verb: 'post', path: '/changePassword'},
accepts: [
{
arg: 'access_token', type: 'string', required: true, http: function (ctx) {
var req = ctx && ctx.req;
var accessToken = req && req.accessToken;
var tokenID = accessToken && accessToken.id;
return tokenID;
}
},
{arg: 'options', type: 'object', required: true, http: {source: 'body'}}
],
returns: {}
})
};
| JavaScript | 0 | @@ -914,16 +914,144 @@
%0A %7D);%0A%0A
+ /**%0A * Change user password by verify old password first.%0A * @param access_token%0A * @param options%0A * @param cb%0A */%0A
Member
@@ -1267,154 +1267,8 @@
ss);
-%0A //if (!options.oldPass %7C%7C !options.newPass) %7B%0A // var msg = 'oldPass or newPass is invalid.';%0A // debug(msg);%0A // cb(msg)%0A //%7D
%0A%0A
@@ -2069,16 +2069,70 @@
;%0A %7D;%0A%0A
+ /**%0A * Define REST API for change password.%0A */%0A
Member
|
8585bda908d0e675841c992686be2dd1ab63e415 | Update items.js | data/items.js | data/items.js | items =
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
"35.179436",
"31.763183"
]
},
"type": "Feature",
"properties": {
"text": "פרג זיפני",
"image": "data/photos/1.JPG"
}
},
]
} | JavaScript | 0.000001 | @@ -323,10 +323,281 @@
%7D,%0A
+ %0A%7B%0A %22geometry%22: %7B%0A %22type%22: %22Point%22,%0A %22coordinates%22: %5B%0A %2235.178672%22,%0A %2231.765298%22%0A %5D%0A %7D,%0A %22type%22: %22Feature%22,%0A %22properties%22: %7B%0A %22text%22: %22%D7%96%D7%A2%D7%97%D7%9F %D7%A4%D7%A8%D7%97%D7%95%D7%A0%D7%99%22,%0A %22image%22: %22data/photos/2.JPG%22%0A %7D%0A %7D,
%0A %5D%0A%7D
+%0A
|
ca5eb976d37fe3870dd2cfbdea33ef05e70b0f13 | handle synchronous exceptions in indexedDB openDatabase method | src/lib/store/indexedDb.js | src/lib/store/indexedDb.js | define(['../util', './pending'], function(util, pendingAdapter) {
var DB_NAME = 'remoteStorage';
var DB_VERSION = 1;
var OBJECT_STORE_NAME = 'nodes';
var logger = util.getLogger('store::indexed_db');
var adapter = function(indexedDB) {
if(! indexedDB) {
throw new Error("Not supported: indexedDB not found");
}
var DB = undefined;
function removeDatabase() {
return util.makePromise(function(promise) {
if(DB) {
try {
DB.close();
} catch(exc) {
// ignored.
};
DB = undefined;
}
var request = indexedDB.deleteDatabase(DB_NAME);
request.onsuccess = function() {
promise.fulfill();
};
request.onerror = function() {
promise.fail();
};
});
}
function openDatabase() {
logger.info("Opening database " + DB_NAME + '@' + DB_VERSION);
return util.makePromise(function(promise) {
var dbRequest = indexedDB.open(DB_NAME, DB_VERSION);
function upgrade(db) {
db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'key' });
}
dbRequest.onupgradeneeded = function(event) {
upgrade(event.target.result);
};
dbRequest.onsuccess = function(event) {
var database = event.target.result;
if(typeof(database.setVersion) === 'function') {
if(database.version != DB_VERSION) {
var versionRequest = database.setVersion(DB_VERSION);
versionRequest.onsuccess = function(event) {
upgrade(database);
event.target.transaction.oncomplete = function() {
promise.fulfill(database);
};
};
} else {
promise.fulfill(database);
}
} else {
// assume onupgradeneeded is supported.
promise.fulfill(database);
}
};
dbRequest.onerror = function(event) {
logger.error("indexedDB.open failed: ", event);
promise.fail(new Error("Failed to open database!"));
};
});
}
function storeRequest(methodName) {
var args = Array.prototype.slice.call(arguments, 1);
return util.makePromise(function(promise) {
var store = DB.transaction(OBJECT_STORE_NAME, 'readwrite').
objectStore(OBJECT_STORE_NAME);
var request = store[methodName].apply(store, args);
request.onsuccess = function() {
promise.fulfill(request.result);
};
request.onerror = function(event) {
promise.fail(event.error);
};
});
}
var indexedDbStore = {
on: function(eventName, handler) {
logger.debug("WARNING: indexedDB event handling not implemented");
},
get: function(key) {
logger.debug("GET " + key);
return storeRequest('get', key);
},
set: function(key, value) {
logger.debug("SET " + key);
var node = value;
node.key = key;
return storeRequest('put', node);
},
remove: function(key) {
logger.debug("REMOVE " + key);
return storeRequest('delete', key);
},
forgetAll: function() {
logger.debug("FORGET ALL");
return removeDatabase().then(doOpenDatabase);
}
};
var tempStore = pendingAdapter();
function replaceAdapter() {
if(tempStore.flush) {
tempStore.flush(indexedDbStore);
util.extend(tempStore, indexedDbStore);
}
}
function doOpenDatabase() {
openDatabase().
then(function(db) {
logger.info("Database opened.");
DB = db;
replaceAdapter();
});
}
doOpenDatabase();
return tempStore;
};
adapter.detect = function() {
var indexedDB = undefined;
if(typeof(window) !== 'undefined') {
indexedDB = (window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.msIndexedDB);
}
return indexedDB;
}
return adapter;
});
| JavaScript | 0.000001 | @@ -1305,32 +1305,50 @@
nction(event) %7B%0A
+ try %7B%0A
var da
@@ -1383,24 +1383,26 @@
;%0A
+
+
if(typeof(da
@@ -1450,16 +1450,18 @@
+
if(datab
@@ -1499,24 +1499,26 @@
+
+
var versionR
@@ -1573,16 +1573,18 @@
+
versionR
@@ -1628,32 +1628,34 @@
+
+
upgrade(database
@@ -1649,32 +1649,34 @@
rade(database);%0A
+
@@ -1736,32 +1736,34 @@
+
promise.fulfill(
@@ -1781,35 +1781,39 @@
+
%7D;%0A
+
%7D;
@@ -1805,32 +1805,34 @@
%7D;%0A
+
%7D el
@@ -1842,32 +1842,34 @@
%7B%0A
+
promise.fulfill(
@@ -1883,34 +1883,38 @@
e);%0A
-%7D%0A
+ %7D%0A
%7D else
@@ -1928,16 +1928,18 @@
+
+
// assum
@@ -1974,32 +1974,34 @@
ed.%0A
+
promise.fulfill(
@@ -2013,33 +2013,104 @@
ase);%0A
-%7D
+ %7D%0A %7D catch(exc) %7B%0A promise.fail(exc);%0A %7D;
%0A %7D;%0A%0A
|
cc9a2a0f6a48c2b97dd199d9d879921b26708ce4 | update watch task for html closes #24 | app/templates/_gruntfile.js | app/templates/_gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
options: {
livereload: true,
spawn: false
},
// Styling
scss: {
files: 'components/**/*.scss',
tasks: ['imagemin', 'sync', 'compass:development', 'csslint']
},
// Scripting
js: {
files: ['components/*.js', 'components/app/**/*.js', '!components/app/_deferred/**/*.js'],
tasks: ['requirejs:development', 'jshint'],
},
js_deferred: {
files: ['components/app/_deferred/**/*.js'],
tasks: ['uglify:deferred', 'jshint'],
},
js_bower: {
files: ['components/bower/**/*.js'],
tasks: ['uglify:external', 'requirejs:development'],
},
// HTML
html: {
files: ['**/*.html', '!components/bower/**/*.html', '!build/**/*.html'],
tasks: ['replace:development'],
},
// Images
img_content: {
files: 'img/**/*.{png,gif,jpg,svg}',
tasks: ['imagemin:content'],
},
img_background: {
files: 'components/**/*.{png,gif,jpg,svg}',
tasks: ['clean:css', 'imagemin:backgrounds' , 'compass:development', 'clean:development', 'csslint'],
}
},
compass: {
options: {
// banner: "/* <%= pkg.author %>, Version: <%= pkg.version %> */",
// httpPath: "/build",
// imagesPath: 'assets/img',
// specify: '*.scss'
asset_cache_buster: false,
cssDir: 'build/assets/css',
httpImagesPath: '/assets/img',
imagesDir: 'build/assets/img',
noLineComments: true,
sassDir: 'components'
},
development: {
options: {
environment: 'development'
}
},
production: {
options: {
httpPath: "/", // . = relative
environment: 'production'
}
}
},
replace: {
modules: {
options: {
patterns: [
{
match: /{app:{(.+)}}/g,
replacement: function (match, placeholder) {
return grunt.file.read('components/app/' + placeholder + '/' + placeholder + '.html');
}
},
{
match: /{deferred:{(.+)}}/g,
replacement: function (match, placeholder) {
return grunt.file.read('components/app/_deferred/' + placeholder + '/' + placeholder + '.html');
}
}
]
},
files: [
{
expand: true,
flatten: true,
src: ['*.html'],
dest: 'build/'
}
]
}
},
requirejs: {
development: {
options: {
// baseUrl: "modules",
useStrict: true,
mainConfigFile: "components/<%= _.slugify(ProjectName) %>.js",
name: "<%= _.slugify(ProjectName) %>",
optimize: 'none',
out: "build/assets/js/<%= _.slugify(ProjectName) %>.js"
}
}
},
uglify: {
deferred: {
options: {
beautify: true
},
files: [{
expand: true,
flatten: true,
cwd: 'components/app/_deferred',
src: ['**/*.js'],
dest: 'build/assets/js/deferred'
}]
},
external: {
options: {
beautify: true
},
files: {
<% if (includeModernizr) { %>'build/assets/js/libs/modernizr.js': ['components/bower/modernizr-shim/modernizr.min.js'],<% } %>
'build/assets/js/libs/require.js': ['components/bower/requirejs/require.js']
}
}
},
imagemin: {
content: {
files: [{
flatten: true,
expand: true,
cwd: 'img',
src: ['**/*.{png,jpg,gif,svg}'],
dest: 'build/img'
}]
},
backgrounds: {
files: [{
flatten: true,
expand: true,
cwd: 'components/app',
src: ['**/*.{jpg,gif,png,svg}'],
dest: 'build/assets/img'
}]
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: ['components/app/**/*.js']
},
csslint: {
options: {
csslintrc: '.csslintrc',
import: false
},
lax: {
src: ['build/assets/css/**/*.css']
}
},
accessibility: {
options : {
accessibilityLevel: 'WCAG2<%= WCAG2 %>',
outputFormat: 'txt',
domElement: true
},
development : {
files: [{
expand : true,
cwd : 'build/',
src : ['*.html'],
dest : 'build/WCAG2-reports/',
ext : '-report.txt'
}]
}
},
clean: {
development: {
src: ["build/assets/img/**/*.svg"]
},
css: {
src: ["build/assets/css/**/*.css"]
}
},
sync: {
webfonts: {
files: [{
flatten: true,
expand: true,
cwd: 'components/app',
src: ['**/*.{ttf,eot,woff}'],
dest: 'build/assets/font'
}],
verbose: true
}
}
});
grunt.loadNpmTasks('grunt-accessibility');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-replace');
grunt.loadNpmTasks('grunt-sync');
grunt.registerTask('default', ['replace', 'imagemin','sync', 'compass:development', 'requirejs:development', 'uglify', 'clean:development', 'csslint', 'jshint', 'accessibility:development']);
};
| JavaScript | 0 | @@ -830,24 +830,49 @@
files: %5B'*
+.html', 'components/app/*
*/*.html', '
@@ -864,24 +864,25 @@
p/**/*.html'
+
, '!componen
@@ -947,28 +947,33 @@
'replace
-:development
+', 'accessibility
'%5D,%0A
|
d403669be0f6cf25ee198e3dfc34b7182dea8470 | Update index.js | projects/acc/js/index.js | projects/acc/js/index.js | if ('Accelerometer' in window && 'Gyroscope' in window) {
//document.getElementById('moApi').innerHTML = 'Generic Sensor API';
let accelerometer = new Accelerometer();
accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
accelerometer.start();
let accelerometerWithGravity = new Accelerometer({includeGravity: true});
accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
accelerometerWithGravity.start();
let gyroscope = new Gyroscope();
gyroscope.addEventListener('reading', e => rotationHandler({
alpha: gyroscope.x,
beta: gyroscope.y,
gamma: gyroscope.z
}));
gyroscope.start();
intervalHandler('Not available in Generic Sensor API');
} else if ('DeviceMotionEvent' in window) {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'Device Motion API';
window.addEventListener('devicemotion', function (eventData) {
accelerationHandler(eventData.acceleration, 'moAccel');
MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
rotationHandler(eventData.rotationRate);
intervalHandler(eventData.interval);
}, false);
} else {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}
function accelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
//document.getElementById(targetId).innerHTML = info;
}
function MaccelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
var zz = (acceleration.z && acceleration.z.toFixed(3));
if (zz>10) {
x = 1;
var timer = setInterval(function change() {
if (x === 1) {
color = "#ffffff";
x = 2;
} else {
color = "#000000";
x = 1;
}
document.body.style.background = color;
}, 50);
setTimeout(function() {
clearInterval(timer);
}, 1000);
document.body.style.background = #000000;
}
}
function rotationHandler(rotation) {
var info, xyz = "[X, Y, Z]";
//info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
//info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
//info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
var xx = (rotation.alpha && rotation.alpha.toFixed(3));
var yy = (rotation.beta && rotation.beta.toFixed(3));
var zz = (rotation.gamma && rotation.gamma.toFixed(3));
var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
//document.getElementById("mean").innerHTML = mean;
//document.getElementById("moRotation").innerHTML = info;
}
function intervalHandler(interval) {
//document.getElementById("moInterval").innerHTML = interval;
}
if (location.href.indexOf('debug') !== -1) {
//document.getElementById('alert').style.display = 'none';
}
| JavaScript | 0.000002 | @@ -2410,60 +2410,8 @@
); %0A
- document.body.style.background = #000000;%0A
%7D%0A
|
96acf76612545d56504a9ba9aa04853d6495e8dd | Fix #413 - children with the same key | public/js/components/SourcesTree.js | public/js/components/SourcesTree.js | const React = require("react");
const { DOM: dom, PropTypes } = React;
const {
nodeHasChildren, createParentMap, addToTree,
collapseTree, createTree
} = require("../utils/sources-tree.js");
const classnames = require("classnames");
const ImPropTypes = require("react-immutable-proptypes");
const Arrow = React.createFactory(require("./utils/Arrow"));
const { Set } = require("immutable");
const ManagedTree = React.createFactory(require("./utils/ManagedTree"));
const FolderIcon = React.createFactory(require("./utils/Icons").FolderIcon);
const DomainIcon = React.createFactory(require("./utils/Icons").DomainIcon);
const FileIcon = React.createFactory(require("./utils/Icons").FileIcon);
const WorkerIcon = React.createFactory(require("./utils/Icons").WorkerIcon);
let SourcesTree = React.createClass({
propTypes: {
sources: ImPropTypes.map.isRequired,
selectSource: PropTypes.func.isRequired
},
displayName: "SourcesTree",
getInitialState() {
return createTree(this.props.sources);
},
componentWillReceiveProps(nextProps) {
if (nextProps.sources !== this.props.sources) {
if (nextProps.sources.size === 0) {
this.setState(createTree(nextProps.sources));
return;
}
const next = Set(nextProps.sources.valueSeq());
const prev = Set(this.props.sources.valueSeq());
const newSet = next.subtract(prev);
const uncollapsedTree = this.state.uncollapsedTree;
for (let source of newSet) {
addToTree(uncollapsedTree, source);
}
// TODO: recreating the tree every time messes with the expanded
// state of ManagedTree, because it depends on item instances
// being the same. The result is that if a source is added at a
// later time, all expanded state is lost.
const sourceTree = newSet.size > 0
? collapseTree(uncollapsedTree)
: this.state.sourceTree;
this.setState({ uncollapsedTree,
sourceTree,
parentMap: createParentMap(sourceTree) });
}
},
focusItem(item) {
this.setState({ focusedItem: item });
},
selectItem(item) {
if (!nodeHasChildren(item)) {
this.props.selectSource(item.contents.get("id"));
}
},
renderItem(item, depth, focused, _, expanded, { setExpanded }) {
const arrow = Arrow({
className: classnames(
{ expanded: expanded,
hidden: !nodeHasChildren(item) }
),
onClick: e => {
e.stopPropagation();
setExpanded(item, !expanded);
}
});
const folder = FolderIcon({
className: classnames(
"folder"
)
});
const domain = DomainIcon({
className: classnames(
"domain"
)
});
const file = FileIcon({
className: classnames(
"file"
)
});
const worker = WorkerIcon({
className: classnames(
"worker"
)
});
let icon = worker;
if (depth === 0) {
icon = domain;
} else if (!nodeHasChildren(item)) {
icon = file;
} else {
icon = folder;
}
return dom.div(
{ className: classnames("node", { focused }),
style: { paddingLeft: depth * 15 + "px" },
onClick: () => this.selectItem(item),
onDoubleClick: e => {
setExpanded(item, !expanded);
} },
dom.div(null, arrow, icon, item.name)
);
},
render: function() {
const { focusedItem, sourceTree, parentMap } = this.state;
const tree = ManagedTree({
getParent: item => {
return parentMap.get(item);
},
getChildren: item => {
if (nodeHasChildren(item)) {
return item.contents;
}
return [];
},
getRoots: () => sourceTree.contents,
getKey: (item, i) => item.path,
itemHeight: 30,
autoExpandDepth: 2,
onFocus: this.focusItem,
renderItem: this.renderItem
});
return dom.div({
className: "sources-list",
onKeyDown: e => {
if (e.keyCode === 13 && focusedItem) {
this.selectItem(focusedItem);
}
}
}, tree);
}
});
module.exports = SourcesTree;
| JavaScript | 0 | @@ -3127,16 +3127,24 @@
%0A %7B
+%0A
classNa
@@ -3180,16 +3180,16 @@
sed %7D),%0A
-
@@ -3227,24 +3227,48 @@
5 + %22px%22 %7D,%0A
+ key: item.path,%0A
onCl
@@ -3328,28 +3328,16 @@
ck: e =%3E
- %7B%0A
setExpa
@@ -3357,27 +3357,22 @@
xpanded)
-;
%0A
- %7D
%7D,%0A
|
ae7402422a690d9e34ae9fb07eb1b42f95b77c03 | remove e2e files in karma | app/templates/karma.conf.js | app/templates/karma.conf.js | 'use strict';
module.exports = function (config) {
config.set({
basePath: 'client',
frameworks: ['jasmine'],
preprocessors: {
'**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/',
moduleName: 'templates'
},
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',<% if (filters.ngAnimate) { %>
'bower_components/angular-animate/angular-animate.js',<% } if (filters.ngSanitize) { %>
'bower_components/angular-sanitize/angular-sanitize.js',<% } if (filters.ngCookies) { %>
'bower_components/angular-cookies/angular-cookies.js',<% } if (filters.ngResource) { %>
'bower_components/angular-resource/angular-resource.js',<% } if (filters.sockets) { %>
'bower_components/angular-socket-io/socket.min.js',<% } %>
'app.js',
'views/**/*.js',
'services/**/*.js',
'directives/**/*.js',
'directives/**/*.html',
'filters/**/*.js'
],<% if (filters.sockets) { %>
exclude: [
'services/socket/socket.service.js',
],<% } %>
reporters: ['progress'],
port: 9876,
colors: true,
// possible values:
// config.LOG_DISABLE
// config.LOG_ERROR
// config.LOG_WARN
// config.LOG_INFO
// config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
| JavaScript | 0 | @@ -1190,16 +1190,58 @@
'%0A %5D,
+%0A%0A exclude: %5B%0A 'views/**/*.e2e.js'
%3C%25 if (f
@@ -1260,32 +1260,17 @@
ts) %7B %25%3E
-%0A%0A exclude: %5B
+,
%0A '
@@ -1307,23 +1307,22 @@
.js'
-,%0A %5D,
%3C%25 %7D %25%3E
+%0A %5D,
%0A%0A
|
0c5e03f8245ff12f8e81d7f784083f75062aa734 | call to Places Details API working; need to incorporate it into map initialization and remove calls to Geocoding API | public/scripts/models/google_map.js | public/scripts/models/google_map.js | 'use strict';
const GOOGLE_GEOCODE_API_KEY = 'AIzaSyB3ds8lw9KjCDvLxfBCj5EpU52-5nGUe_Q';
const GOOGLE_PLACES_API_KEY = 'AIzaSyABR5dsVE6XNT0UOAKI_qmSC4_p0jPShQM';
const locations = [
{
title: 'Fly Awake Tea'
},
{
title: 'Tao of Tea'
},
{
title: 'Heavens Tea, School of Tea Arts'
}
];
//this is how we ping the google geocode API with a shop name and it returns the latLng
function geocodeUrl(title) {
return `https://maps.googleapis.com/maps/api/geocode/json?address=${title}&key=${GOOGLE_GEOCODE_API_KEY}`;
}
function placesUrl(title) {
return `https://maps.googleapis.com/maps/api/place/textsearch/xml?query=${title}&key=${GOOGLE_PLACES_API_KEY}`
}
function initMap() {
//initialize map and center it
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 45.549863, lng: -122.675790},
scrollwheel: false
});
//loop through locations array and convert title to latLng
for (let i = 0; i < locations.length; i++) {
let url = geocodeUrl(locations[i].title);
//set marker for each shop
$.get(url).done(function (response) {
//create marker for shop
let marker = new google.maps.Marker({
position: response.results[0].geometry.location,
map: map,
});
//create info window for marker
let infoWindow = new google.maps.InfoWindow({
content: `<p>${locations[i].title}</p>
<p>${response.results[0].formatted_address}</p>`,
maxWidth: 120
});
//click handler to open info windows
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
});
}
//re-center map upon window resize
google.maps.event.addDomListener(window, 'resize', function() {
const center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
let place = placesUrl(locations[0].title);
$.get(place).done(function(response) {
console.log(response);
});
}
| JavaScript | 0 | @@ -626,11 +626,12 @@
rch/
-xml
+json
?que
@@ -671,24 +671,168 @@
PI_KEY%7D%60%0A%7D%0A%0A
+function placeDetailsUrl(id) %7B%0A return %60https://maps.googleapis.com/maps/api/place/details/json?placeid=$%7Bid%7D&key=$%7BGOOGLE_PLACES_API_KEY%7D%60%0A%7D%0A%0A
function ini
@@ -1255,24 +1255,78 @@
response) %7B%0A
+ // console.log('Geocode response: ', response);%0A
//crea
@@ -2079,16 +2079,104 @@
%0A %7D);%0A%0A
+%0A%0A //working, now need to incorporate this into the for loop and replace geocoding API%0A
let pl
@@ -2212,24 +2212,25 @@
title);%0A
+%0A
$.get(
place).d
@@ -2221,21 +2221,49 @@
$.get(
+%60https://crossorigin.me/$%7B
place
+%7D%60
).done(f
@@ -2290,28 +2290,237 @@
-console.log(response
+let placeId = response.results%5B0%5D.place_id;%0A let placeIdUrl = placeDetailsUrl(placeId);%0A $.get(%60https://crossorigin.me/$%7BplaceIdUrl%7D%60).done(function(response) %7B%0A console.log('Place Details response: ', response);%0A %7D
);%0A
|
8dd3dc991f5895d3cc511d2db4f88e44cddd8b62 | add special variable test cases for rename.js | rename.js | rename.js | "use strict";
class Env {
constructor(outer, k, v) {
this.outer = outer;
this.k = k;
this.v = v;
}
get(key) {
return (key == this.k) ? this.v : this.outer.get(key);
}
static empty() { return new Env(new Map()); }
}
class NextVar {
constructor() { this.nextVar = 0; }
next() { return "_" + (this.nextVar++); }
}
function rename0(exp, env, nextVar) {
if (exp[0] == "var") {
var v = env.get(exp[1]);
return ["var", (v == undefined) ? nextVar.next() : v];
} else if (exp[0] == "lam") {
var v = nextVar.next();
var newEnv = new Env(env, exp[1], v);
return ["lam", v, rename0(exp[2], newEnv, nextVar)];
} else if (exp[0] == "app") {
return ["app", rename0(exp[1], env, nextVar), rename0(exp[2], env, nextVar)];
}
}
function rename(exp) { return rename0(exp, Env.empty(), new NextVar()); }
// TODO: es6 import
exports.rename = rename;
/*
var _parse = require("./parse.js"),
parse = _parse.parse, unparse = _parse.unparse;
var testData = [
//["x", "_0"],
//["y", "_0"],
//["(λv u)", "(λ_0 _1)"],
// what about (v v) ?!
["(λv v)", "(λ_0 _0)"],
["(λv (v v))", "(λ_0 (_0 _0))"],
["(λv (λv v))", "(λ_0 (λ_1 _1))"],
["((λv v) (λv v))", "((λ_0 _0) (λ_1 _1))"],
["((λy y) (λx x))", "((λ_0 _0) (λ_1 _1))"],
];
for (let [orig, expected] of testData) {
const actualExp = rename(parse(orig));
const actual = unparse(actualExp);
console.assert(actual == expected, `\nactual: ${actual}\nexpected: ${expected}`);
}
*/
| JavaScript | 0.000001 | @@ -919,17 +919,16 @@
ename;%0A%0A
-%0A
/*%0Avar _
@@ -1319,24 +1319,146 @@
%CE%BB_1 _1))%22%5D,%0A
+ %5B%22(%CE%BB_1 (_1 _1))%22, %22(%CE%BB_0 (_0 _0))%22%5D,%0A %5B%22(%CE%BB_0 (_0 _0))%22, %22(%CE%BB_0 (_0 _0))%22%5D,%0A %5B%22(%CE%BB_1 (%CE%BB_0 _0))%22, %22(%CE%BB_0 (%CE%BB_1 _1))%22%5D,%0A
%5D;%0Afor (
|
608215c5bca4a64b667970968c8344c54e7a78f2 | update get new notifications logic | files/public/we.notification.js | files/public/we.notification.js | /**
* Notifications client side lib
*/
(function (we) {
we.notification = {
count: 0,
countDisplay: null,
link: null,
init: function() {
this.countDisplay = $('.main-menu-link-notification-count');
this.link = $('.main-menu-notification-link');
// only start if both elements is found
if (this.countDisplay && this.link) this.registerNewCheck();
},
notificationsCountCheckDelay: 60000,// check every 1 min
lastCheckData: null,
registerNewCheck: function registerNewCheck() {
setTimeout(
this.getNewNotificationCount.bind(this),
this.notificationsCountCheckDelay
);
},
getNewNotificationCount: function getNewNotificationCount() {
var self = this;
$.ajax({
url: '/api/v1/current-user/notification-count'
}).then(function (data){
self.count = Number(data.count);
self.updateNotificationsDisplay();
// update last check time
self.lastCheckData = new Date().toISOString();
}).fail(function (err) {
console.error('we.post.js:error in getNewsPosts:', err);
}).always(function () {
self.registerNewCheck();
});
},
updateNotificationsDisplay: function updateNotificationsDisplay() {
if (this.count) {
this.countDisplay.text(this.count);
this.link.addClass('have-notifications');
} else {
this.countDisplay.text('');
this.link.removeClass('have-notifications');
}
}
};
we.notification.init();
})(window.we); | JavaScript | 0 | @@ -348,32 +348,39 @@
k) this.
-registerNewCheck
+getNewNotificationCount
();%0A %7D,
@@ -1033,12 +1033,20 @@
'we.
-post
+notification
.js:
@@ -1064,14 +1064,25 @@
tNew
-sPosts
+NotificationCount
:',
|
19af6710d339b3d156971fa3a3a95607de161b55 | fix remaining cases on reduce | special.js | special.js | var u = require('./util')
var compare = require('typewiselite')
var search = require('binary-search')
function is$ (obj) {
for(var k in obj)
if(k[0] === '$') return true
return false
}
//rawpaths, reducedpaths, reduce
function arrayGroup (set, get, reduce) {
//we can use a different lookup path on the right hand object
//is always the "needle"
function _compare (hay, needle) {
for(var i in set) {
var x = u.get(hay, set[i]), y = needle[i]
if(x !== y) return compare(x, y)
}
return 0
}
return function (a, b) {
if(a && !Array.isArray(a)) a = reduce([], a)
var A = a = a || []
var i = search(A, get.map(function (fn) { return fn(b) }), _compare)
if(i >= 0) A[i] = reduce(A[i], b)
else A.splice(~i, 0, reduce(undefined, b))
return a
}
}
module.exports = function (make) {
return {
filter: function makeFilter (rule) {
if(u.isContainer(rule) && !is$(rule)) {
rule = u.map(rule, makeFilter)
return function (value) {
if(value == null) return false
for(var k in rule)
if(!rule[k](value[k])) return false
return true
}
}
if(u.isBasic(rule))
return function (v) { return rule === v }
//now only values at the end...
return make(rule)
},
map: function makeMap (rule) {
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeMap)
return function (value) {
if(value == null) return undefined
var keys = 0
var ret = u.map(rules, function (fn, key) {
if(rule[key] === true) {
keys ++
return value && value[key]
}
keys ++
return fn(value)
})
return keys ? ret : undefined
}
}
return make(rule)
},
reduce: function (rule) {
function makeReduce (rule) {
if(u.isObject(rule) && !is$(rule) && !u.isArray(rule))
return u.map(rule, makeReduce)
return make(rule)
}
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeReduce)
var getPaths = []
var setPaths = u.paths(rules, function (maybeMap) {
if(u.isFunction(maybeMap) && maybeMap.length === 1) {
return getPaths.push(maybeMap), true
}
})
function reduce (a, b) {
return u.map(rules, function (reduce, key) {
//handle maps as reduces (skip aggregator arg)
return reduce.length === 1 ? reduce(b) : reduce(a && a[key], b)
})
}
if(getPaths.length) return arrayGroup(setPaths, getPaths, reduce)
return reduce
}
return make(rule)
}
}
}
| JavaScript | 0.000002 | @@ -1891,24 +1891,109 @@
on (rule) %7B%0A
+ //this traverses the rule THREE TIMES!%0A //surely I can do this in one go.%0A
functi
@@ -2111,33 +2111,32 @@
le, makeReduce)%0A
-%0A
return m
@@ -2470,24 +2470,38 @@
%7D)%0A%0A
+var reduce = (
function red
@@ -2501,213 +2501,473 @@
ion
+c
re
-duce (a, b) %7B%0A return u.map(rules, function (reduce, key) %7B%0A //handle maps as reduces (skip aggregator arg)%0A return reduce.length === 1 ? reduce(b) : reduce(a && a%5Bkey%5D, b)
+ateReduce(rule) %7B%0A if(u.isObject(rule)) %7B%0A var rules = u.map(rule, createReduce)%0A return function (a, b) %7B%0A if(!a) a = %7B%7D%0A return u.map(rules, function (reduce, key) %7B%0A return a%5Bkey%5D = reduce(a%5Bkey%5D, b)%0A %7D)%0A %7D%0A %7D%0A else if(u.isFunction(rule)) %7B%0A if(rule.length === 2) return rule%0A else return function (a, b) %7B return rule(b) %7D
%0A
@@ -2966,33 +2966,32 @@
b) %7D%0A %7D
-)
%0A %7D%0A%0A
@@ -2979,26 +2979,30 @@
%7D%0A
-%7D%0A
+ else
%0A if(
@@ -2998,19 +2998,113 @@
-if(
+ throw new Error('could not process:'+JSON.stringify(rule))%0A %7D)(rules)%0A%0A return
getPaths
@@ -3110,24 +3110,28 @@
s.length
-) return
+%0A ?
arrayGr
@@ -3161,32 +3161,18 @@
reduce)
-%0A%0A return
+ :
reduce%0A
@@ -3216,10 +3216,8 @@
%0A %7D%0A%7D%0A%0A
-%0A%0A
|
14150f7825c78a6caaf50fb659a7f2c99267f2e5 | comment line so that build passes | src/App.js | src/App.js | import React from 'react';
import { Time, WeekDate, Event, EventOption, TimeInterval } from './suppClasses'
import { makeDomain, search } from './cSearch'
import { Schedule , scheduleEvaluation } from './schedule'
import { miect4 } from './data/miect4';
import { miect2 } from './data/miect2';
import logo from './logo.svg';
import './App.css';
import { Events } from './ui/Events'
import { Constraints } from './ui/Constraints'
import { Preferences } from './ui/Preferences'
import { Calendar } from './ui/Calendar'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
events: [],
constraints: [],
preferences: {
'Contiguous, unfragmented events': 0,
'Free afternoons': 0,
'Free mornings': 0,
'Long lunch breaks': 0,
'Longer weekends': 0,
'Free days': 0,
'Free friday morning for hangovers': 0,
},
schedules: [],
}
}
handleEventAdd(name, option, day, start, end) {
const instance = new TimeInterval(
new WeekDate(day, new Time(start.hours(), start.minutes())), new WeekDate(day, new Time(end.hours(), end.minutes()))
)
const events = this.state.events.slice()
const foundEvent = events.find(e => e.event.name === name && e.option === option)
if (foundEvent) {
foundEvent.instances = [...foundEvent.instances, instance]
this.setState({
events: events
})
} else {
this.setState(prevState => ({
events: [...prevState.events, new EventOption(new Event(name), option, [instance])]
}))
}
}
handleOptionDelete(index) {
this.setState({
events: [...this.state.events.slice(0, index), ...this.state.events.slice(index+1)]
})
}
handleConstraintAdd(day, start, end) {
const instance = new TimeInterval(
new WeekDate(day, new Time(start.hours(), start.minutes())),
new WeekDate(day, new Time(end.hours(), end.minutes()))
)
const event = new EventOption(new Event('Constraint', true), this.state.constraints.length+1, [instance])
this.setState(prevState => ({
events: [...prevState.events, event],
constraints: [...prevState.constraints, event]
}))
}
handlePreferenceChange(e, p) {
const preferences = this.state.preferences
preferences[p] = e.target.value
this.setState({ preferences })
}
handleGenerate() {
// Compute solutions
let domain = makeDomain(this.state.events)
let solutions = search(domain)
let schedules = solutions.map(solution => new Schedule(solution))
// Sort by preferences
let weights = Object.values(this.state.preferences)
schedules = schedules.sort((s1, s2) => scheduleEvaluation(s2, ...weights) - scheduleEvaluation(s1, ...weights))
// Set the events of the first 10 schedules
this.setState({
schedules: schedules.slice(0, 10).map(s => s.events)
})
alert("Done")
}
handleImport() {
this.setState(prevState => ({
events: miect2
}))
}
render() {
return (
<div className="container">
<div className="App-logo-wrapper">
<img src={logo} className="App-logo" alt="Dhroraryus" />
<span className="align-top">beta</span>
</div>
<Events
events={this.state.events}
handleAdd={(name, option, day, start, end) => this.handleEventAdd(name, option, day, start, end)}
handleDelete={(index) => this.handleOptionDelete(index)}
handleImport={() => this.handleImport()}
/>
<div className="row">
<div className="col-sm">
<Constraints
constraints={this.state.constraints}
handleAdd={(day, start, end) => this.handleConstraintAdd(day, start, end)}
/>
</div>
<div className="col-sm">
<Preferences
preferences={this.state.preferences}
handleChange={(e, p) => this.handlePreferenceChange(e, p)}
/>
</div>
</div>
<button type="button" className="mb-3 btn btn-primary btn-lg btn-block" disabled={this.state.events.length === 0} onClick={() => this.handleGenerate()}>
Generate
</button>
{this.state.schedules.map((schedule, index) => (
<div className="card mb-3">
<h5 className="card-header">Schedule #{index+1}</h5>
<div className="card-body">
<Calendar
key={index}
events={schedule}
/>
</div>
</div>
))}
</div>
);
}
}
export default App;
| JavaScript | 0 | @@ -208,16 +208,18 @@
hedule'%0A
+//
import %7B
|
dd471a697d821b88245e9d7d0a3259becba5f484 | Add userGuess() | src/App.js | src/App.js | import React, { Component } from 'react';
import './App.css';
import ReactSVG from 'react-svg'
class App extends Component {
constructor(){
this.alphabet = []
this.word = []
this.guessesLeft = 8
}
function newGame() {
newGameView()
this.alphabet =
["A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
this.word = ["c", "a", "t"]
this.guessesLeft = 8
setBlanks( "___" )
}
render() {
return (
<div className="App">
<div className="header">
<h2>Hangman Game</h2>
</div>
<div className="intro">
<p>To get started, edit <code>src/App.js</code> and save to reload.</p>
<p>There are some placeholder elements setup that need implementation.</p>
</div>
<div className="main">
<ReactSVG path="hangman.svg"/>
<div className="game-controls">
<button onClick={this.newGame}>New Game</button>
<div className="remaining-alphabet">{this.alphabet}</div>
<div className="guess-left">{this.guessesLeft}</div>
<input type="text" onChange={this.userGuess} placeholder="Guess a letter..."/>
<div className="puzzle-word">_ _ _ _ _ _ _ _ _ _</div>
</div>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0.000001 | @@ -521,16 +521,647 @@
)%0A %7D%0A%0A
+ userGuess( event ) %7B%0A letter = event.value%0A if(!this.alphabet.includes(letter.toUpperCase)) %7B%0A // You already guessed that! Do nothing (no penalty).%0A Console.log(%22You already guessed that!%22)%0A return%0A %7D%0A else %7B%0A this.guessesLeft--%0A if (this.word.includes(letter)) %7B%0A for (i = 0; i %3C this.word.length; i ++) %7B%0A if ( this.hint%5Bi%5D === %22_%22 && this.word.charAt(i) === letter)%0A this.hint%5Bi%5D === letter.toUpperCase()%0A %7D%0A %7D%0A else %7B%0A // add to hangman%0A %7D%0A this.alphabet.splice(this.alphabet.indexOf(letter.toUpperCase()), 1)%0A %7D%0A %0A %7D%0A%0A
render
|
d6a7f211850f9b1b6c6a3a0ab17d72dfce38568a | Substitute static content with the state object | src/App.js | src/App.js | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>React Todos</h2>
</div>
<div className="Todo-App">
<form>
<input type="text" />
</form>
<div className="Todo-List">
<ul>
<li><input type="checkbox" />Learn React</li>
<li><input type="checkbox" />Build a React App</li>
<li><input type="checkbox" />Evaluate the end result</li>
</ul>
</div>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0.000084 | @@ -117,16 +117,331 @@
onent %7B%0A
+%0A constructor() %7B%0A super()%0A this.state = %7B%0A //list of todos in state object%0A todos: %5B%0A %7B id: 1, name: 'Learn React', isComplete: true %7D,%0A %7B id: 2, name: 'Build a React App', isComplete: false %7D,%0A %7B id: 3, name: 'Evaluate the end result', isComplete: false %7D%0A %5D%0A %7D%0A %7D%0A%0A
render
@@ -807,120 +807,77 @@
-%3Cli%3E%3Cinput type=%22checkbox%22 /%3ELearn React%3C/li%3E%0A %3Cli%3E%3Cinput type=%22checkbox%22 /%3EBuild a React App%3C/li%3E%0A
+%7Bthis.state.todos.map(todo =%3E%0A %3Cli key=%7Btodo.id%7D%3E%0A
@@ -890,12 +890,8 @@
-%3Cli%3E
%3Cinp
@@ -913,38 +913,93 @@
ox%22
-/%3EEvaluate the end result%3C/li%3E
+defaultChecked=%7Btodo.isComplete%7D /%3E%7Btodo.name%7D%0A %3C/li%3E%0A )%7D
%0A
|
7028afe0153202364f428eb1761968a5f747c724 | Add more locations. | src/App.js | src/App.js | import React, { Component } from 'react';
import './App.css';
import ErrorMsg from './ErrorMsg.js';
import LoadingMsg from './LoadingMsg.js';
import TimeTable from './TimeTable.js';
import UserLocation from './UserLocation.js';
import MapView from './MapView.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
var self = this;
var currentURL = window.location.href;
if (/niemi/.exec(currentURL)) {
self.setState({
//lat:60.183692, lon:24.827744
lat:60.186269 ,lon:24.830909, maxDistance:1000
});
} else if (/kara/.exec(currentURL)) {
self.setState({
lat:[60.224655, 60.215923],
lon:[24.759257, 24.753498],
maxDistance:[300, 100]
});
}
//if (/location/.exec(currentURL)) {
else {
UserLocation.getUserLocation((loc) => {
self.setState({
lat:loc.coords.latitude, lon:loc.coords.longitude
});
}, (e) => {
this.setState({error: {
name: 'User location not available.',
message: e.toString()
}});
});
}
}
render() {
if (this.state.hasOwnProperty('error')) {
return (
<div className='app'>
<ErrorMsg name={this.state.error.name} message={this.state.error.message}/>
</div>
);
}
if ((!this.state.hasOwnProperty('lat') || !this.state.hasOwnProperty('lon')) && !this.state.hasOwnProperty('stopCode')) {
return (
<div className='app'>
<LoadingMsg name='User location' message={UserLocation.waitingForUserLocation}/>
</div>
);
}
//<TimeTable stopCode='E2036' />;
//Alvarin aukio 60.186269, 24.830909
return (
<div className='app'>
<div className='foreground'>
<TimeTable lat={this.state.lat} lon={this.state.lon} maxDistance={this.state.maxDistance} maxResults={15}/>
</div>
<div className='background'>
<MapView
lat={Array.isArray(this.state.lat) ? this.state.lat[0] : this.state.lat}
lon={Array.isArray(this.state.lon) ? this.state.lon[0] : this.state.lon}
/>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0 | @@ -573,16 +573,38 @@
nce:1000
+, filterOut:'Otaniemi'
%0A%09%09%09%7D);%0A
@@ -756,24 +756,451 @@
100%5D%0A%09%09%09%7D);%0A
+%09%09%7D else if (/sello/.exec(currentURL)) %7B%0A%09%09%09self.setState(%7B%0A%09%09%09%09lat:60.219378, lon:24.815121, maxDistance:325, filterOut:'Lepp%C3%A4vaara'%0A%09%09%09%7D);%0A%09%09%7D else if (/keskusta/.exec(currentURL)) %7B%0A%09%09%09self.setState(%7B%0A%09%09%09%09lat:60.170508, lon:24.941104, maxDistance:300, filterOut:'Lepp%C3%A4vaara'%0A%09%09%09%7D);%0A%09%09%7D else if (/kamppi/.exec(currentURL)) %7B%0A%09%09%09self.setState(%7B%0A%09%09%09%09lat:60.169038, lon:24.932908, maxDistance:100, filterOut:'Lepp%C3%A4vaara'%0A%09%09%09%7D);%0A
%09%09%7D%0A%09%09//if (
@@ -1278,24 +1278,108 @@
((loc) =%3E %7B%0A
+%09%09%09%09console.log(String(loc.coords.latitude) + ', ' + String(loc.coords.longitude));%0A
%09%09%09%09self.set
@@ -1440,16 +1440,33 @@
ongitude
+, maxDistance:500
%0A%09%09%09%09%7D);
@@ -2143,16 +2143,141 @@
.830909%0A
+%09%09//console.log('render: ' + String(this.state.lat) + ', ' + String(this.state.lon) + ', ' + String(this.state.maxDistance))%0A
%09%09return
@@ -2447,16 +2447,49 @@
lts=%7B15%7D
+ filterOut=%7Bthis.state.filterOut%7D
/%3E%0A%09%09%09%09%3C
|
0988c6e3d216f019a08bc9cfdf864a9e4af5caa2 | Update order of lessons. | src/App.js | src/App.js | import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { withRouter } from 'react-router'
import { Panel, ListGroup, ListGroupItem, Navbar, Col, Clearfix } from 'react-bootstrap'
import * as Lessons from './lessons/index.js'
const lessons = [
{ key: 'StateAsProps', displayName: 'State as props' },
{ key: 'PureRenderFunctions', displayName: 'Pure render functions' },
{ key: 'RenderStates', displayName: 'Render states' },
]
const LessonRoute = ({ lessonKey, lessonName, incr }) => (
<ListGroupItem>
<Col sm={10}>
<span>{incr + 1}. {lessonName}</span>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/exercise`}>Exercise</Link>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/solution`}>Solution</Link>
</Col>
<Clearfix />
</ListGroupItem>
)
const Routes = () => (
<div className="container">
{lessons.map(lesson => (
<div key={lesson.key}>
<Route path={`/${lesson.key}/exercise`} component={Lessons[`${lesson.key}Exercise`]} />
<Route path={`/${lesson.key}/solution`} component={Lessons[`${lesson.key}Solution`]} />
</div>
))}
</div>
)
const Home = () => (
<main>
<Panel header="Workshop lessons">
<ListGroup fill>
{lessons.map((lesson, key) => (
<LessonRoute
key={lesson.key}
lessonKey={lesson.key}
lessonName={lesson.displayName}
incr={key}
/>
))}
</ListGroup>
</Panel>
</main>
)
const Header = withRouter(({ location }) => (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Learning Recompose</Link>
</Navbar.Brand>
</Navbar.Header>
{location.pathname !== '/' &&
<span>
{location.pathname.includes('solution') &&
<Navbar.Text pullRight>
<Link to={`./exercise`}>Got to exercise</Link>
</Navbar.Text>}
{location.pathname.includes('exercise') &&
<Navbar.Text pullRight>
<Link to={`./solution`}>Go to solution</Link>
</Navbar.Text>}
</span>}
</Navbar>
))
const App = () => (
<Router>
<div className="app">
<Header />
<Routes />
<div className="container">
<Route path="/" exact component={Home} />
</div>
</div>
</Router>
)
export default App
| JavaScript | 0 | @@ -359,26 +359,19 @@
y: '
-Pure
Render
-Function
+State
s',
@@ -388,28 +388,20 @@
e: '
-Pure render function
+Render state
s' %7D
@@ -408,35 +408,42 @@
,%0A %7B key: '
+Pure
Render
-State
+Function
s', displayN
@@ -444,36 +444,44 @@
splayName: '
-Render state
+Pure render function
s' %7D,%0A%5D%0A%0Acon
|
f6f4d331233f9b4fb886e39acae232512b63c833 | make years the default time bin | src/VIS.js | src/VIS.js | /*global d3, utils */
"use strict";
// declaration of global object (modified by browser().load())
var VIS = {
ready: { }, // which viz already generated?
last: { // which subviews last shown?
bib: { }
},
files: { // what data files to request
info: "data/info.json",
meta: "data/meta.csv.zip", // remove .zip to use uncompressed data
dt: "data/dt.json.zip", // (name the actual file accordingly)
tw: "data/tw.json",
topic_scaled: "data/topic_scaled.csv"
},
aliases: { // simple aliasing in URLs:
yearly: "conditional" // #/model/yearly/... -> #/model/conditional/...
},
default_view: "/model", // specify the part after the #
metadata: {
type: "dfr", // use "base" if meta.csv has a header
spec: {
extra_fields: [ ],// (dfr type only) names for extra columns
date_field: "date"// (base type only) name of date field
}
},
condition: { // metadata variable to condition topics on
type: "time", // alternatives: "category" and "continuous"
spec: {
field: "date", // name of metadata field
unit: "month", // unit of time bins
n: 1 // width of time bins
// format: "%Y-%m" // can optionally specify key format (strftime)
}
},
overview_words: 15, // may need adjustment
model_view: {
w: 500, // px: the minimum svg width
aspect: 1.3333, // for calculating height
words: 4, // maximum: may need adjustment
size_range: [7, 18], // points. may need adjustment
name_size: 18, // points
stroke_range: 6, // max. perimeter thickness
conditional: {
w: 500, // px: the minimum svg width
aspect: 1.333,
m: {
left: 20,
right: 20,
top: 20,
bottom: 30
},
label_threshold: 40, // px
words: 4,
label_words: 2, // should be <= words
streamgraph: true, // streamgraph or stack areas from x-axis?
ordinal: { // ordinal variable: stacked bars, not areas
bar: 0.4 // bar width as proportion
}
},
list: {
spark: { // same form as topic_view plot parameters below
w: 70,
h: 20,
m: {
left: 2,
right: 2,
top: 2,
bottom: 2
},
time: {
bar: {
unit: "day",
w: 300
}
},
ordinal: {
bar: {
w: 0.25
}
},
continuous: {
bar: {
w: 0.25
}
}
}
}
},
topic_view: {
words: 50,
docs: 20,
w: 400, // minimum in px
aspect: 3,
m: {
left: 40,
right: 20,
top: 20,
bottom: 30
},
time: { // conditional plot x-axis settings: time variable
bar: { // width of bars
unit: "day", // unit is used as d3.time[unit].utc
w: 90
},
ticks: {
unit: "year",
n: 10
}
},
continuous: { // continuous variable: step is calculated automatically
bar: {
w: 0.25, // proportion: how much x-axis bar takes up
},
ticks: 10
},
ordinal: { // categorical variable: step is calculated automatically
bar: {
w: 0.25 // proportion
},
ticks: 10
},
ticks_y: 10, // y axis ticks
tx_duration: 1000 // animated transition time in ms (where applicable)
},
word_view: {
n_min: 10, // words per topic
topic_label_padding: 8, // pt
topic_label_leading: 14, // pt
row_height: 80, // pt
svg_rows: 10, // * row_height gives min. height for svg element
w: 700, // px: minimum width
m: {
left: 100,
right: 40,
top: 20,
bottom: 0
}
},
bib: {
// default if no author delimiter supplied, but note that
// 2014 JSTOR metadata format uses ", " instead
author_delimiter: "\t",
// "et al" is better for real bibliography, but it's
// actually worth being able to search all the multiple authors
et_al: Infinity,
anon: "[Anon]",
},
bib_view: {
window_lines: 100,
major: "year",
minor: "authortitle",
dir: "up"
},
tooltip: { // tooltip div parameters
offset: {
x: 10, // px
y: 0
}
},
percent_format: d3.format(".1%"),
resize_refresh_delay: 100, // ms
hidden_topics: [], // list of 1-based topic numbers to suppress
show_hidden_topics: false,
annotes: [], // list of CSS classes annotating the current view
update: function (x) {
return utils.deep_replace(this, x);
}
};
| JavaScript | 0.000066 | @@ -1229,15 +1229,15 @@
t: %22
-month
+year
%22,
+
//
|
701503a5d205d22145597390b492992c17244925 | Make jshint pass | tasks/aglio.js | tasks/aglio.js | 'use strict';
var path = require('path');
var when = require('when');
module.exports = function (grunt) {
var _ = require('underscore');
var aglio = require('aglio');
grunt.registerMultiTask('aglio', 'Grunt plugin to generate aglio documentation', function () {
var done = this.async();
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
separator: "",
theme: "default",
filter: function (src) {
return src;
}
});
var files = this.files;
if (options.theme === "default") {
// gracefully handle incorrect themeVariables value for detault theme.
// see https://github.com/danielgtaylor/aglio/tree/olio-theme#theme-options
// and https://github.com/danielgtaylor/aglio/tree/olio-theme/styles
if (options.themeVariables && !_.contains(['default', 'flatly', 'slate', 'cyborg'], options.themeVariables)) {
grunt.log.warn("Unrecognized theme variables '" + options.themeVariables + "'. Using 'default'.");
options.themeVariables = "default";
}
grunt.verbose.writeln("Using olio (default) theme with theme variables '" + options.themeVariables + "'.");
} else {
// catch theme (module) require before aglio catches it; fall back to
// default theme. incorrectly styled docs are beter than no docs at all.
try {
require('aglio-theme-' + options.theme);
} catch(e) {
options.theme = 'default';
grunt.log.warn("Aglio custom theme '" + options.theme + "' not found. Using default theme ('oglio'). Hint: 'npm install --save aglio-theme-" + options.theme + "'");
}
grunt.verbose.writeln("Using custom theme '" + options.theme + "' with theme variables '" + options.themeVariables + "'.");
}
var getLineNo = function(input, err) {
if (err.location && err.location.length) {
return input.substr(0, err.location[0].index).split('\n').length;
}
};
var logWarnings = function(warnings) {
var lineNo, warning, _i, _len, _ref, _results;
_ref = warnings || [];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
warning = _ref[_i];
lineNo = getLineNo(warnings.input, warning) || 0;
_results.push(grunt.log.error("Line " + lineNo + ": " + warning.message + " (warning code " + warning.code + ")"));
}
return _results;
};
compile();
function compile() {
return when.all(when.map(files, function (f) {
var concattedSrc = f.src.filter(function (path) {
if (!grunt.file.exists(path)) {
grunt.log.warn(path + " does not exist");
return false;
} else {
return true;
}
}).map(function (path) {
return grunt.file.read(path);
}).join(options.separator);
return when.promise(function (resolve, reject) {
aglio.render(options.filter(concattedSrc), options, function (err, html, warnings) {
var lineNo;
if (err) {
lineNo = getLineNo(err.input, err);
if (lineNo != null) {
grunt.log.error("Line " + lineNo + ": " + err.message + " (error code " + err.code + ")");
} else {
grunt.log.error(JSON.stringify(err));
}
return done(err);
}
logWarnings(warnings);
if (typeof html == 'string') {
grunt.file.write(f.dest, html);
grunt.log.ok("Written to " + f.dest);
resolve(true);
} else {
reject({ error: err, warnings: warnings });
}
});
});
})).then(done) // Don't call done until ALL the files have completed rendering
.catch(function (err) {
grunt.fail.fatal("Code:" + err.code + '\n' + "Message:" + err.err, err.warnings);
});
}
});
};
| JavaScript | 0.994966 | @@ -2455,24 +2455,8 @@
%7D;%0A%0A
- compile();%0A%0A
@@ -3473,16 +3473,17 @@
html ==
+=
'string
@@ -3959,16 +3959,32 @@
);%0A %7D
+%0A%0A compile();
%0A %7D);%0A%7D
|
7ce48514893ffdaed2a7cb8d5c553ca723a7b193 | Enable smart typographic punctuation in markdown plugin. | tasks/build.js | tasks/build.js | var gulp = require('gulp');
var Metalsmith = require('metalsmith');
var collections = require('metalsmith-collections');
var ignore = require('metalsmith-ignore');
var permalinks = require('metalsmith-permalinks');
// Content
var fileMetadata = require('metalsmith-filemetadata');
var metadata = require('metalsmith-metadata');
var markdown = require('metalsmith-markdown');
var templates = require('metalsmith-templates');
// CSS
var less = require('metalsmith-less');
var fingerprint = require('metalsmith-fingerprint');
var autoprefixer = require('metalsmith-autoprefixer');
var Handlebars = require('handlebars');
var moment = require('handlebars-helper-moment')();
Handlebars.registerHelper('moment', moment.moment);
Handlebars.registerHelper('log', function(content) {
console.log(content);
});
gulp.task('build', function(callback) {
Metalsmith('./')
// CSS
.use(less({
pattern: '**/main.less'
}))
.use(autoprefixer())
.use(fingerprint({
pattern: '**/*.css'
}))
.use(ignore([
'**/*.less',
'**/main.css',
'**/.DS_Store'
]))
// Content
.use(metadata({
site: 'site.yaml'
}))
.use(fileMetadata([
{
pattern: '**/*.md',
metadata: {
template: 'default.html'
},
preserve: true
}
]))
.use(collections({
pages: {
pattern: '*.md',
sortBy: 'order'
},
articles: {
pattern: 'articles/*.md',
sortBy: 'date',
reverse: true
}
}))
.use(markdown())
.use(permalinks({
relative: false
}))
.use(templates('handlebars'))
.build(function(err, files) {
if (err) {
return callback(err);
}
callback();
});
});
| JavaScript | 0 | @@ -1556,16 +1556,47 @@
arkdown(
+%7B%0A smartypants: true%0A %7D
))%0A .
|
81df5c6a7b5126e888fcbe9962185e683ace8821 | Implement click transition for now | front/scripts/modules/reader.js | front/scripts/modules/reader.js | 'use strict';
const electron = require('electron');
const remote = electron.remote;
const webFrame = electron.webFrame;
const app = remote.app;
const co = require('co');
const View = require('./view');
const util = require('./util');
const keycodes = require('./keycodes');
let current = null;
class Reader extends View {
constructor(id) {
super(id);
this.inner = this.el.querySelector('#readerInner');
this.left = this.el.querySelector('#readerLeft');
this.right = this.el.querySelector('#readerRight');
this.bindKeyHandler = _bindKeyHandler.bind(this);
this.swipeHandler = _swipeHandler.call(this);
}
set() {
const leftPath = 'file://' + current.pages[current.state.currentPage + 1];
const rightPath = 'file://' + current.pages[current.state.currentPage];
this.left.style.cssText = `background-image: url(${leftPath});`
this.right.style.cssText = `background-image: url(${rightPath});`
}
next() {
(function(c) {
if (c.state.currentPage + 2 < c.pages.length - 1) {
c.state.currentPage += 2;
} else if (c.state.currentPage + 1 < c.pages.length - 1) {
c.state.currentPage += 1;
}
})(current);
this.set();
}
prev() {
(function(c) {
if (c.state.currentPage - 2 > -1) {
c.state.currentPage -= 2;
} else if (c.state.currentpage - 1 > -1) {
c.state.currentPage -= 1;
}
})(current);
this.set();
}
startEvent() {
document.addEventListener('keydown', this.bindKeyHandler);
window.addEventListener('wheel', this.swipeHandler);
}
endEvent() {
document.removeEventListener('keydown', this.bindKeyHandler);
window.removeEventListener('wheel', this.swipeHandler);
}
start(manga, reset) {
const self = this;
if (reset) {
manga.state.currentPage = 1;
}
current = manga;
co(function* () {
current.pages = yield util.getFilePaths(manga.dirPath);
self.set();
self.startEvent();
self.visible();
});
}
end() {
this.endEvent();
this.hidden();
this.emit('end');
}
}
module.exports = Reader;
function _bindKeyHandler(e) {
if (
keycodes[e.keyCode] === 'right'
|| keycodes[e.keyCode] === 'k'
|| (keycodes[e.keyCode] === 'n' && e.ctrlKey)
) {
this.prev();
return;
}
if (
keycodes[e.keyCode] === 'left'
|| keycodes[e.keyCode] === 'space'
|| keycodes[e.keyCode] === 'j'
|| (keycodes[e.keyCode] === 'p' && e.ctrlKey)
) {
this.next();
return;
}
if (keycodes[e.keyCode] === 'esc') {
this.end();
return;
}
}
function _swipeHandler() {
const isZoom = () => {
return innerHeight === document.body.clientHeight;
};
let executed = false;
let scale = 100;
let swipe = _.throttle((e) => {
if (Math.abs(e.deltaX) < 20) {
executed = false;
} else if (!executed) {
if (e.deltaX < -60) {
executed = true;
this.next();
} else if (e.deltaX > 60) {
executed = true;
this.prev();
}
}
}, 80);
let timeout = null;
const fn = (e) => {
if (isZoom()) {
swipe(e);
}
// if (e.ctrlKey) {
// scale += e.deltaY / 10;
// if (scale < 100) scale = 100;
// this.el.style.cssText = `width: ${scale}vw; height: ${scale}vh`;
// console.log(this.el.clientHeight);
// const width = this.el.clientWidth / 4;
// const height = this.el.clientHeight / 4;
// console.log(width, height);
// scroll(width, height);
// }
}
return fn;
}
function zoomHandler() {
}
| JavaScript | 0 | @@ -286,16 +286,36 @@
= null;
+%0Aconst _events = %7B%7D;
%0A%0Aclass
@@ -641,16 +641,99 @@
(this);%0A
+ _events.left = this.next.bind(this);%0A _events.right = this.prev.bind(this);%0A
%7D%0A%0A s
@@ -1672,24 +1672,136 @@
peHandler);%0A
+ this.left.addEventListener('click', _events.left);%0A this.right.addEventListener('click', _events.right);%0A
%7D%0A%0A endEv
@@ -1934,16 +1934,134 @@
ndler);%0A
+ this.left.removeEventListener('click', _events.left);%0A this.right.removeEventListener('click', _events.right);%0A
%7D%0A%0A s
|
ed6abbc49f74022e7ac2a93012509ee02fe85598 | Increase maxBuffer to 1000 * 1024, was having problems with the `xcodebuild archive` exceeding buffer | tasks/xcode.js | tasks/xcode.js | /*
* grunt-xcode
* https://github.com/matiassingers/grunt-xcode
*
* Copyright (c) 2014 Matias Singers
* Licensed under the MIT license.
*/
'use strict';
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
var temporary = require('temporary');
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
formatted = formatted.replace(
RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
}
return formatted;
};
module.exports = function(grunt) {
function executeCommand(command){
grunt.verbose.writeln('Running command: {0}'.format(command));
return exec(command)
.catch(handleCommandError);
}
function handleCommandError(error){
if (error){
grunt.warn(error);
}
}
grunt.registerMultiTask('xcode', 'Build and export Xcode projects with Grunt', function() {
var done = this.async();
var options = this.options({
clean: true,
export: true,
project: '',
scheme: '',
archivePath: '',
exportPath: process.cwd(),
exportFilename: 'export.ipa'
});
if(!options.project){
throw new Error('`options.project` is required');
}
if(!options.archivePath){
var temporaryDirectory = new temporary.Dir();
options.archivePath = temporaryDirectory.path;
}
runCleanCommand()
.then(runArchiveCommand)
.then(runExportCommand)
.finally(cleanUp);
function runCleanCommand(){
if(!options.clean){
return Promise.resolve();
}
var command = 'xcodebuild clean -project "{0}"'.format(options.project);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild clean` was successful');
});
}
function runArchiveCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild archive';
command += ' -project "{0}"'.format(options.project);
command += ' -scheme "{0}"'.format(options.scheme);
command += ' -archivePath "{0}"'.format(options.archivePath);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild archive` was successful');
});
}
function runExportCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild';
command += ' -exportArchive';
command += ' -exportFormat ipa';
command += ' -project "{0}"'.format(options.project);
command += ' -archivePath "{0}.xcarchive"'.format(options.archivePath);
command += ' -exportPath "{0}/{1}"'.format(options.exportPath, options.exportFilename);
command += ' -exportWithOriginalSigningIdentity';
executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild export` was successful');
});
}
function cleanUp(){
if(temporaryDirectory){
temporaryDirectory.rmdir();
}
if(options.export){
grunt.log.ok('Built and exported product to: {0}/{1}'.format(options.exportPath, options.exportFilename));
}
done();
}
});
};
| JavaScript | 0.000001 | @@ -685,32 +685,56 @@
urn exec(command
+, %7BmaxBuffer: 1000*1024%7D
)%0A .catch(h
|
d590014bb6377979afaf738b23ce5d4895903c43 | load correctly lowercased findone.js blueprint | blueprints/find.js | blueprints/find.js | /**
* Module dependencies
*/
var util = require( 'util' ),
actionUtil = require( './_util/actionUtil' ),
pluralize = require( 'pluralize' );
/**
* Find Records
*
* get /:modelIdentity
* * /:modelIdentity/find
*
* An API call to find and return model instances from the data adapter
* using the specified criteria. If an id was specified, just the instance
* with that unique id will be returned.
*
* Optional:
* @param {Object} where - the find criteria (passed directly to the ORM)
* @param {Integer} limit - the maximum number of records to send back (useful for pagination)
* @param {Integer} skip - the number of records to skip (useful for pagination)
* @param {String} sort - the order of returned records, e.g. `name ASC` or `age DESC`
* @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
*/
module.exports = function findRecords( req, res ) {
// Look up the model
var Model = actionUtil.parseModel( req );
// root level element in JSON api
var documentIdentifier = pluralize( Model.identity );
// We could use the JSON API URL shorthand template style, if the client supported it
// var documentLinks = actionUtil.asyncAssociationToplevelLinks( documentIdentifier, Model, req.options.associations );
// If an `id` param was specified, use the findOne blueprint action
// to grab the particular instance with its primary key === the value
// of the `id` param. (mainly here for compatibility for 0.9, where
// there was no separate `findOne` action)
if ( actionUtil.parsePk( req ) ) {
return require( './findOne' )( req, res );
}
// Lookup for records that match the specified criteria
var query = Model.find()
.where( actionUtil.parseCriteria( req ) )
.limit( actionUtil.parseLimit( req ) )
.skip( actionUtil.parseSkip( req ) )
.sort( actionUtil.parseSort( req ) );
// TODO: .populateEach(req.options);
query = actionUtil.populateEach( query, req.options );
query.exec( function found( err, matchingRecords ) {
if ( err ) return res.serverError( err );
// Only `.watch()` for new instances of the model if
// `autoWatch` is enabled.
if ( req._sails.hooks.pubsub && req.isSocket ) {
Model.subscribe( req, matchingRecords );
if ( req.options.autoWatch ) {
Model.watch( req );
}
// Also subscribe to instances of all associated models
_.each( matchingRecords, function ( record ) {
actionUtil.subscribeDeep( req, record );
} );
}
matchingRecords = actionUtil.asyncAssociationLinks( Model, matchingRecords, req.options.associations );
var jsonAPI = {};
jsonAPI[ documentIdentifier ] = matchingRecords;
// jsonAPI = actionUtil.sideloadAssociations( jsonAPI, documentIdentifier, req.options.associations );
// res.set( 'Content-Type', 'application/vnd.api+json' );
res.ok( jsonAPI );
} );
};
| JavaScript | 0.00004 | @@ -1646,17 +1646,17 @@
'./find
-O
+o
ne' )( r
|
fbea2335c0a71d71dc27788281ed97a28e3855e8 | Fix time lost if opponent was disconnected. | frontend/js/controllers/play.js | frontend/js/controllers/play.js | /**
* Created by stas on 30.01.16.
*/
'use strict';
playzoneControllers.controller('PlayCtrl', function ($scope, $rootScope, $routeParams, GameRest, WebRTCService, WebsocketService, $interval, dateFilter) {
$scope.boardConfig = {
pieceType: 'leipzig'
};
$scope.gameConfig = {
zeitnotLimit: 28000
};
$scope.game = GameRest.get(
{
id: $routeParams.gameId
}
);
$scope.game.$promise.then(
function () {
if ($scope.game.color === 'b') {
$scope.my_move = $rootScope.user.id === $scope.game.user_to_move.id;
} else {
$scope.my_move = $scope.game.user_white.id === $scope.game.user_to_move.id;
}
$scope.my_time = $scope.game.color === 'w' ? $scope.game.time_white : $scope.game.time_black;
$scope.opponent_time = $scope.game.color === 'b' ? $scope.game.time_white : $scope.game.time_black;
switch ($scope.game.color) {
case 'w':
WebRTCService.createGameRoom($scope.game.id);
break;
case 'b':
WebRTCService.joinGameRoom($scope.game.id);
WebRTCService.addCallBackLeaveRoom($scope.game.id, function () {
$scope.game.$savePgn();
});
break;
default:
WebsocketService.subscribeToGame($scope.game.id);
}
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
$scope.timer = $interval(function() {
$scope.game.status != 'play' && $interval.cancel($scope.timer);
if ($scope.my_move) {
$scope.my_time -= 100;
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.my_time <= 0 && $interval.cancel($scope.timer) && $scope.timeLost();
} else {
$scope.opponent_time -= 100;
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
if ($scope.opponent_time <= 0) {
$interval.cancel($scope.timer);
$scope.savePgnAndTime();
}
}
}, 100);
}
);
$scope.resign = function () {
$scope.game.$resign().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.timeLost = function () {
$scope.game.$timeLost().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.savePgnAndTime = function () {
$scope.game.time_white = $scope.game.color === 'w' ? $scope.my_time : $scope.opponent_time;
$scope.game.time_black = $scope.game.color === 'b' ? $scope.my_time : $scope.opponent_time;
$scope.game.$savePgn();
};
}); | JavaScript | 0 | @@ -3415,24 +3415,150 @@
me.$savePgn(
+).then(%0A function () %7B%0A WebsocketService.sendGameToObservers($scope.game.id);%0A %7D%0A
);%0A %7D;%0A%7D)
|
7178296aa07088e152e38e852cda00e7ce85f0c6 | Update rest_api.js | app/assets/javascripts/codelation_ui/std/interfaces/rest_api.js | app/assets/javascripts/codelation_ui/std/interfaces/rest_api.js | (function(){
"use strict";
// Config options
App.vue.config.rest_api = {
'options': {},
'version': null
};
function url() {
if (App.vue.config.rest_api.version === null) {
return '/api';
}else{
return '/api/v' + App.vue.config.rest_api.version;
}
}
function toPath(model) {
var pluralModel = App.vue.interfaces.string.methods._pluralize(model);
var modelPath = App.vue.interfaces.string.methods._dasherize(pluralModel);
return url() + '/' + modelPath;
}
function queryStringFromOptions(options_arg, defaultOptions_arg) {
var queries = [];
var options = options_arg || {};
var defaultOptions = defaultOptions_arg || {};
Object.keys(options).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + options[key]);
});
Object.keys(defaultOptions).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + defaultOptions[key]);
});
if (queries.length > 0) {
return '?'+queries.join('&');
} else {
return '';
}
}
App.vue.interfaces.rest_api = {
methods: {
_sendRequest: function(url, method, data) {
return $.ajax({
url: url,
type: method || 'GET',
data: data || {}
});
},
_restfulGet: function(model, id, options) {
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
return this.RestfulGetAll(model, options);
}else{
var url = toPath(model);
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulGetAll: function(model, options) {
var requestUrl = toPath(model) + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulCreate: function(model, id, data, options) {
var url = toPath(model);
var path = url;
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'POST', data);
},
_restfulUpdate: function(model, id, data, options) {
var url = toPath(model);
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
var path = url + '/';
}else{
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'PATCH', data);
},
_restfulDelete: function(model, id, options) {
var url = toPath(model);
var path = url + '/' + id;
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'DELETE');
}
}
}
})();
| JavaScript | 0.000001 | @@ -2794,32 +2794,159 @@
toPath(model);%0A
+ if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) %7B%0A var path = url + '/';%0A %7Delse%7B%0A
var path
@@ -2956,32 +2956,42 @@
url + '/' + id;%0A
+ %7D%0A
var requ
|
3f854bd6a0d4d0e5e363e1fc38dbdf6ba6693b2c | edit playground | src/app.js | src/app.js | document.write('Hello Frontend Masters!')
var React = require('react')
var Hello = React.createClass({
render: function() {
return <div>Hello, {this.props.name}</div>
}
})
React.render(<Hello name="dian"/>, document.body) | JavaScript | 0.000001 | @@ -1,47 +1,4 @@
-document.write('Hello Frontend Masters!')%0A%0A
var
@@ -182,8 +182,9 @@
nt.body)
+%0A
|
96064ca82c38e6248a5f5f851b9046fc40776444 | fix cart | app/assets/javascripts/controllers/trade/my/carts/show-ready.js | app/assets/javascripts/controllers/trade/my/carts/show-ready.js | class CartController extends Stimulus.Controller {
//static targets = [ 'number' ];
connect() {
console.log(this.numberTarget.value)
}
update() {
var data = new FormData();
data.set(this.numberTarget.name, this.numberTarget.value);
Rails.ajax({ url: this.numberTarget.dataset.url, type: 'PATCH', dataType: 'script', data: data })
}
increase() {
this.numberTarget.value = this.numberTarget.valueAsNumber + 1;
this.update()
}
decrease() {
this.numberTarget.value = this.numberTarget.valueAsNumber - 1;
this.update()
}
}
application.register('cart', CartController);
| JavaScript | 0.000001 | @@ -1,8 +1,47 @@
+import %7B Controller %7D from 'stimulus'%0A%0A
class Ca
@@ -65,17 +65,8 @@
nds
-Stimulus.
Cont
@@ -80,10 +80,8 @@
%7B%0A
-//
stat
|
37f2ced956641f948101ebdd4fb0b26a63113c2b | Edit the verification base url to avoid strange anchor behavior and separate path and token | frontend/views/provider-form.js | frontend/views/provider-form.js | var Backbone = require('backbone'),
template = require("../templates/provider-form.hbs"),
i18n = require('i18next-client');
var config = require('../config');
module.exports = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function() {
var $el = this.$el;
$el.html(template({
}));
config.load('providertypes', function(e, data) {
$typeSel = $el.find('select[name=type]');
$.each(data, function() {
$option = $('<option></option>');
$option.attr({
value: this.url,
});
$option.text(this['name_' + config.get('lang')]);
$typeSel.append($option)
})
console.log($typeSel);
})
console.log($el);
},
events: {
"click .form-btn-submit": function() {
var data = {};
var $el = this.$el;
$el.find('[name]').each(function() {
var $field = $(this);
var value = $field.val();
var name = $field.attr('name');
var ml = typeof $field.data('i18n-field')==="undefined" ? false : true;
if (ml) {
var cur_lang = localStorage['lang'];
name = name + '_' + cur_lang;
}
data[name] = value;
// console.log(name + ': ' + value);
});
$el.find('.error').text('');
var errors = {};
// Password Handling
if (data['password1'].length === 0) {
errors['password1'] = ["Password must not be blank"];
}
if (data['password2'].length === 0) {
errors['password2'] = ["Password must be repeated"];
} else if (data['password1'] != data['password2']) {
errors['password2'] = ["Passwords must match"];
}
if (!errors['password1'] && !errors['password2']) {
data['password'] = data['password1'];
delete data.password1;
delete data.password2;
}
// Base Activation Link
data["base_activation_link"] = location.protocol+'//'+location.host+location.pathname+'#/register/verify';
$.ajax('//localhost:4005/api/providers/create_provider/', {
method: 'POST',
data: data,
error: function(e) {
$.extend(errors, e.responseJSON);
$.each(errors, function(k) {
console.log(k + ' (error): ' + this[0]);
var $error = $el.find('[for='+k+'] .error');
if ($error) {
$error.text(this[0]);
}
})
},
success: function(data) {
window.location = '#/register/confirm';
},
});
return false;
},
"click .form-btn-clear": function() {
this.$el.find('[name]').each(function() {
var $field = $(this);
$field.val('');
});
return false;
},
},
})
| JavaScript | 0 | @@ -2331,16 +2331,17 @@
thname+'
+?
#/regist
@@ -2349,16 +2349,17 @@
r/verify
+/
';%0A%0A
|
0230a79eb937ed562c42124cdeaa6da25c874394 | add docstring to app.js | src/app.js | src/app.js | define('app',
['vent', 'db', 'util', 'template'],
function( vent, db, util, tmpl ){
'use strict';
var app = window.app = {};
app.vent = vent;
app.db = db;
app.util = util;
app.tmpl = tmpl;
return app;
});
| JavaScript | 0.000001 | @@ -1,8 +1,228 @@
+/**%0A * app.js%0A *%0A * This module is somewhat superfluous at the moment, its only being used to%0A * expose certain interfaces for debugging purposes. Perhaps it will evolve down%0A * the road to a more useful construct.%0A */%0A%0A
define('
|
aed3dae46a21f1c4200af6b3c3d8184ce6d09c05 | Update test to reflect PerDistrict | app/assets/javascripts/student_profile/LightProfilePage.test.js | app/assets/javascripts/student_profile/LightProfilePage.test.js | import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import {toMoment, toMomentFromTimestamp} from '../helpers/toMoment';
import {withDefaultNowContext} from '../testing/NowContainer';
import LightProfilePage, {latestStar, countEventsSince} from './LightProfilePage';
import {
testPropsForPlutoPoppins,
testPropsForOlafWhite,
testPropsForAladdinMouse
} from './profileTestProps.fixture';
function testingTabTextLines(el) {
const leafEls = $(el).find('.LightProfileTab:eq(2) *:not(:has(*))').toArray(); // magic selector from https://stackoverflow.com/questions/4602431/what-is-the-most-efficient-way-to-get-leaf-nodes-with-jquery#4602476
return leafEls.map(el => $(el).text());
}
function testRender(props) {
const el = document.createElement('div');
ReactDOM.render(<LightProfilePage {...props} />, el);
return el;
}
it('renders without crashing', () => {
testRender(testPropsForPlutoPoppins());
});
describe('snapshots', () => {
function expectSnapshot(props) {
const tree = renderer
.create(withDefaultNowContext(<LightProfilePage {...props} />))
.toJSON();
expect(tree).toMatchSnapshot();
}
it('works for olaf notes', () => expectSnapshot(testPropsForOlafWhite({selectedColumnKey: 'notes'})));
it('works for olaf reading', () => expectSnapshot(testPropsForOlafWhite({selectedColumnKey: 'reading'})));
it('works for olaf math', () => expectSnapshot(testPropsForOlafWhite({selectedColumnKey: 'math'})));
it('works for pluto notes', () => expectSnapshot(testPropsForPlutoPoppins({selectedColumnKey: 'notes'})));
it('works for pluto attendance', () => expectSnapshot(testPropsForPlutoPoppins({selectedColumnKey: 'attendance'})));
it('works for pluto behavior', () => expectSnapshot(testPropsForPlutoPoppins({selectedColumnKey: 'behavior'})));
it('works for aladdin notes', () => expectSnapshot(testPropsForAladdinMouse({selectedColumnKey: 'notes'})));
it('works for aladdin grades', () => expectSnapshot(testPropsForAladdinMouse({selectedColumnKey: 'grades'})));
it('works for aladdin testing', () => expectSnapshot(testPropsForAladdinMouse({selectedColumnKey: 'testing'})));
});
describe('HS testing tab', () => {
it('works when missing', () => {
const props = testPropsForAladdinMouse();
const el = testRender(props);
expect(testingTabTextLines(el)).toEqual([
'Testing',
'-',
'ELA and Math MCAS',
'not yet taken'
]);
});
it('takes next gen when there are both', () => {
const aladdinProps = testPropsForAladdinMouse();
const props = {
...aladdinProps,
chartData: {
...aladdinProps.chartData,
"next_gen_mcas_mathematics_scaled": [[2014,5,15,537]],
"next_gen_mcas_ela_scaled": [[2015,5,15,536]],
"mcas_series_math_scaled": [[2015,5,15,225]],
"mcas_series_ela_scaled": [[2015,5,15,225]]
}
};
const el = testRender(props);
expect(testingTabTextLines(el)).toEqual([
'Testing',
'M',
'ELA and Math MCAS',
'9 months ago / 2 years ago'
]);
});
it('falls back to old MCAS when no next gen', () => {
const aladdinProps = testPropsForAladdinMouse();
const props = {
...aladdinProps,
chartData: {
...aladdinProps.chartData,
"next_gen_mcas_mathematics_scaled": [],
"next_gen_mcas_ela_scaled": [],
"mcas_series_math_scaled": [[2015,5,15,225]],
"mcas_series_ela_scaled": [[2015,5,15,225]]
}
};
const el = testRender(props);
expect(testingTabTextLines(el)).toEqual([
'Testing',
'NI',
'ELA and Math MCAS',
'9 months ago'
]);
});
});
it('#latestStar works regardless of initial sort order', () => {
const nowMoment = toMomentFromTimestamp('2018-08-13T11:03:06.123Z');
const starSeriesReadingPercentile = [
{"percentile_rank":98,"total_time":1134,"grade_equivalent":"6.90","date_taken":"2017-04-23T06:00:00.000Z"},
{"percentile_rank":94,"total_time":1022,"grade_equivalent":"4.80","date_taken":"2017-01-07T02:00:00.000Z"}
];
expect(latestStar(starSeriesReadingPercentile, nowMoment)).toEqual({
nDaysText: 'a year ago',
percentileText: '98th'
});
expect(latestStar(starSeriesReadingPercentile.reverse(), nowMoment)).toEqual({
nDaysText: 'a year ago',
percentileText: '98th'
});
});
it('#countEventsSince works', () => {
const absences = [
{id: 217, occurred_at: "2018-07-23", student_id:42},
{id: 219, occurred_at: "2018-05-12", student_id:42},
{id: 216, occurred_at: "2018-05-11", student_id:42}
];
expect(countEventsSince(toMoment('8/28/2018'), absences, 45)).toEqual(1);
});
describe('inactive overlay', () => {
it('is shown for inactive students', () => {
const defaultProps = testPropsForOlafWhite();
const el = testRender({
...defaultProps,
student: {
...defaultProps.student,
enrollment_status: 'Withdrawn'
}
});
expect($(el).find('.LightProfilePage-inactive-overlay').length).toEqual(1);
expect($(el).text()).toContain('no longer actively enrolled');
});
it('is shown for students missing from export', () => {
const defaultProps = testPropsForOlafWhite();
const el = testRender({
...defaultProps,
student: {
...defaultProps.student,
missing_from_last_export: true
}
});
expect($(el).find('.LightProfilePage-inactive-overlay').length).toEqual(1);
expect($(el).text()).toContain('no longer actively enrolled');
});
});
| JavaScript | 0 | @@ -4886,32 +4886,65 @@
..defaultProps,%0A
+ districtKey: 'somerville',%0A
student: %7B
@@ -5341,24 +5341,58 @@
faultProps,%0A
+ districtKey: 'new-bedford',%0A
studen
|
e70a56c0d2b642bb7ab1cbc58e6a7486b8c04231 | fix typo | src/renderer/js/component/form.js | src/renderer/js/component/form.js | import React from "react";
import PropTypes from "prop-types";
import FormField from "component/formField";
import { Icon } from "component/common.js";
let formFieldCounter = 0;
export const formFieldNestedLabelTypes = ["radio", "checkbox"];
export function formFieldId() {
return "form-field-" + ++formFieldCounter;
}
export class Form extends React.PureComponent {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
}
handleSubmit(event) {
event.preventDefault();
this.props.onSubmit();
}
render() {
return (
<form onSubmit={event => this.handleSubmit(event)}>
{this.props.children}
</form>
);
}
}
export class FormRow extends React.PureComponent {
spropTypes = {
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
errorMessage: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
// helper: PropTypes.html,
};
static defaultProps = {
isFocus: false,
};
constructor(props) {
super(props);
this._field = null;
this._fieldRequiredText = __("This field is required");
this.state = this.getStateFromProps(props);
}
componentWillReceiveProps(nextProps) {
this.setState(this.getStateFromProps(nextProps));
}
getStateFromProps(props) {
return {
isError: !!props.errorMessage,
errorMessage:
typeof props.errorMessage === "string"
? props.errorMessage
: props.errorMessage instanceof Error
? props.errorMessage.toString()
: "",
};
}
showError(text) {
this.setState({
isError: true,
errorMessage: text,
});
}
showRequiredError() {
this.showError(this._fieldRequiredText);
}
clearError(text) {
this.setState({
isError: false,
errorMessage: "",
});
}
getValue() {
return this._field.getValue();
}
getSelectedElement() {
return this._field.getSelectedElement();
}
getOptions() {
return this._field.getOptions();
}
focus() {
this._field.focus();
}
onFocus() {
this.setState({ isFocus: true });
}
onBlur() {
this.setState({ isFocus: false });
}
render() {
const fieldProps = Object.assign({}, this.props),
elementId = formFieldId(),
renderLabelInFormField = formFieldNestedLabelTypes.includes(
this.props.type
);
if (!renderLabelInFormField) {
delete fieldProps.label;
}
delete fieldProps.helper;
delete fieldProps.errorMessage;
delete fieldProps.isFocus;
return (
<div
className={"form-row" + (this.state.isFocus ? " form-row--focus" : "")}
>
{this.props.label && !renderLabelInFormField ? (
<div
className={
"form-row__label-row " +
(this.props.labelPrefix ? "form-row__label-row--prefix" : "")
}
>
<label
htmlFor={elementId}
className={
"form-field__label " +
(this.state.isError ? "form-field__label--error" : " ")
}
>
{this.props.label}
</label>
</div>
) : (
""
)}
<FormField
ref={ref => {
this._field = ref ? ref.getWrappedInstance() : null;
}}
hasError={this.state.isError}
onFocus={this.onFocus.bind(this)}
onBlur={this.onBlur.bind(this)}
{...fieldProps}
/>
{!this.state.isError && this.props.helper ? (
<div className="form-field__helper">{this.props.helper}</div>
) : (
""
)}
{this.state.isError ? (
<div className="form-field__error">{this.state.errorMessage}</div>
) : (
""
)}
</div>
);
}
}
export const Submit = props => {
const { title, label, icon, disabled } = props;
const className =
"button-block" +
" button-primary" +
" button-set-item" +
" button--submit" +
(disabled ? " disabled" : "");
const content = (
<span className="button__content">
{"icon" in props ? <Icon icon={icon} fixed={true} /> : null}
{label ? <span className="button-label">{label}</span> : null}
</span>
);
return (
<button type="submit" className={className} title={title}>
{content}
</button>
);
};
| JavaScript | 0.999991 | @@ -761,17 +761,16 @@
ent %7B%0A
-s
propType
|
532558b47ba9055c04301e69a201faef765d96dd | Refactor email page to use new textarea | app/scripts/Widget/plugins/PressureWidget/settings/EmailPage.js | app/scripts/Widget/plugins/PressureWidget/settings/EmailPage.js | import React, { Component, PropTypes } from 'react'
import { reduxForm } from 'redux-form'
import * as WidgetActions from '../../../actions'
import { FormFooter, InputTag } from '../../../components'
import {
FormRedux,
FormGroup,
ControlLabel,
FormControl
} from '../../../../Dashboard/Forms'
import { Base as PressureBase } from '../components/settings'
// Regex to validate Target (Ex.: Igor Santos <igor@nossascidades.org>)
const patternTarget = /[\w]+[ ]*<(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>/
class EmailPage extends Component {
constructor(props) {
super(props)
this.state = { targets: this.getTargetList() || [] }
}
getTargetString() {
const { targets } = this.state
return targets.join(';')
}
getTargetList() {
const { targets } = this.props
return targets && targets.split(';')
}
handleSubmit(values, dispatch) {
const { widget, credentials, editWidget, ...props } = this.props
const targets = this.getTargetString()
const settings = widget.settings || {}
const data = { ...widget, settings: { ...settings, ...values, targets } }
const params = { credentials, mobilization_id: props.mobilization.id }
return dispatch(editWidget(data, params))
}
render() {
const { fields: { pressure_subject, pressure_body }, ...props } = this.props
return (
<PressureBase location={props.location} mobilization={props.mobilization} widget={props.widget}>
<FormRedux onSubmit={::this.handleSubmit} {...props}>
<InputTag
label="Alvos"
values={this.state.targets}
onInsertTag={value => this.setState({ targets: [...this.state.targets, value] })}
onRemoveTag={value => this.setState({ targets: this.state.targets.filter(tag => tag !== value) })}
validate={value => {
const errors = { valid: true }
if (!value.match(patternTarget)) {
errors.valid = false
errors.message = 'Alvo fora do formato padrão. Ex.: Nome do alvo <alvo@provedor.com>'
}
return errors
}}
/>
<FormGroup controlId="email-subject-id" {...pressure_subject}>
<ControlLabel>Assunto do email</ControlLabel>
<FormControl type="text" />
</FormGroup>
<FormGroup controlId="email-body-id" {...pressure_body}>
<ControlLabel>Corpo do email que será enviado</ControlLabel>
<FormControl type="text" style={{height: '20rem'}} componentClass="textarea" />
</FormGroup>
</FormRedux>
</PressureBase>
)
}
}
EmailPage.propTypes = {
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
credentials: PropTypes.object.isRequired,
editWidget: PropTypes.func.isRequired,
// Redux form
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired
}
const fields = ['pressure_subject', 'pressure_body', 'targets']
const validate = values => {
const errors = {}
if (!values.pressure_subject) {
errors.pressure_subject = 'Preenchimento obrigatório'
}
if (!values.pressure_body) {
errors.pressure_body = 'Preenchimento obrigatório'
}
return errors
}
const parseTargetList = (targets = '') => targets.split(';')
export default reduxForm({
form: 'widgetForm',
fields,
validate
},
(state, ownProps) => ({
initialValues: {
...ownProps.widget.settings || {},
targets: parseTargetList(ownProps.widget.settings && ownProps.widget.settings.targets)
},
credentials: state.auth.credentials,
}), { ...WidgetActions })(EmailPage)
| JavaScript | 0 | @@ -2621,34 +2621,8 @@
ext%22
- style=%7B%7Bheight: '20rem'%7D%7D
com
|
6019c287f3db0a415a0a7290df3a8f8308e7c8c7 | change preview photo number | javascript.js | javascript.js | function initialize_webiopi(){
// apply style.css after initialize webiopi
applyCustomCss('styles.css');
// set touch area
var touchArea = $("#touchArea")[0];
// add touch event listener
touchArea.addEventListener("touchstart", touchEvent, false);
touchArea.addEventListener("touchmove", touchEvent, false);
touchArea.addEventListener("touchend", touchEndEvent, false);
// add click event listener
touchArea.addEventListener("click", clickEvent, false);
webiopi().refreshGPIO(false);
imageSetup();
}
var commandID = 0;
var mCount = 0;
var mCanvas;
var mCtx;
var mImg1;
var mImg2;
var mImgShutter;
var mImgArrow;
var mWidth = 640;
var mHeight = 480;
var viewScale = 0.90;
var URL1, URL2;
var cameraMode = 0; //0:auto 1:preview 2:manual
var photoNumb = 0;
function imageSetup(){
getData('./photo/camera.set').then(function(data) {
photoNumb = data;
});
var host = location.host;
var hostname = host.split(":")[0];
var port_mjpeg = 9000;
var port_webiopi = 8000;
URL_MJPEG = 'http://' + hostname + ':' + port_mjpeg + '/?action=snapshot';
URL_SHUTTER = 'http://' + hostname + ':' + port_webiopi + '/raspicam_wifi/img/shutter.png';
URL_PREVIEW = 'http://' + hostname + ':' + port_webiopi + '/raspicam_wifi/photo/';
URL_ARROW = 'http://' + hostname + ':' + port_webiopi + '/raspicam_wifi/img/arrow.png';
mCanvas = document.getElementById("canvas");
mCtx = mCanvas.getContext('2d');
mWidth = viewScale*document.getElementById("touchArea").offsetWidth;
mHeight= mWidth*3/4;
mCanvas.width = mWidth;
mCanvas.height = mHeight;
mImg1 = new Image();
mImg2 = new Image();
mImgShutter = new Image();
mImgArrow = new Image();
mImg1.src = URL_MJPEG +'&'+(mCount++);
mImgShutter.src = URL_SHUTTER;
mImgArrow.src = URL_ARROW;
mImg1.onload = function() {
if(cameraMode == 0 || cameraMode == 2){
mImg2.src = URL_MJPEG + '&' + (mCount++);
mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
mCtx.drawImage(mImgShutter, 0, 0, mWidth, mHeight);
}
if(cameraMode == 1){
mImg2.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
}
};
mImg2.onload = function() {
if(cameraMode == 0 || cameraMode == 2){
mImg1.src =URL_MJPEG + '&' + (mCount++);
mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
mCtx.drawImage(mImgShutter, 0, 0, mWidth, mHeight);
}
if(cameraMode == 1){
mImg1.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
}
};
}
function getData(url) {
return $.ajax({
type: 'get',
url: url
});
}
// touch event for smartphone
function touchEvent(e){
e.preventDefault();
var touch = e.touches[0];
var width = viewScale*document.getElementById("touchArea").offsetWidth;
var height = width*3/4;
if(touch.pageX<width/3){ // left
if(cameraMode == 1){
photoNumb--;
}
}else if(touch.pageX<2*width/3){ // middle
if(touch.pageY<height/2){ // upper
}else{ // lower
if(cameraMode == 0 || cameraMode == 2){
ActionShutter();
}
}
}else if(touch.pageX<width){ // right
if(cameraMode == 1){
photoNumb++;
}
}
}
// touch end event
function touchEndEvent(e){
e.preventDefault();
}
// click event for PC
function clickEvent(e){
var width = viewScale*document.getElementById("touchArea").offsetWidth;
var height = width*3/4;
if(e.pageX<width/3){ // left
if(cameraMode == 1){
photoNumb--;
}
}else if(e.pageX<2*width/3){ // middle
if(e.pageY>=2*height/5 && e.pageY<3*height/5){
}else if(e.pageY<height/2){
if(cameraMode == 0 || cameraMode == 2){
ActionShutter();
}
}else{
}
}else if(e.pageX<width){ // right
if(cameraMode == 1){
photoNumb++;
}
}
}
function applyCustomCss(custom_css){
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('link');
style.rel = "stylesheet";
style.type = 'text/css';
style.href = custom_css;
head.appendChild(style);
}
function getZeroDigit(num,digit) {
var n,m,s;
if (isNaN(num)) {
s = num;
} else {
s = num.toString();
}
m = digit - s.length;
for (n=0;n<m;n++) {
s = "0" + s;
}
return s;
}
function ChangeMode(){
cameraMode++;
if(cameraMode > 2){
cameraMode = 0;
}
}
function ActionShutter(){
webiopi().callMacro("shutterCamera", [0]);
getData('./photo/camera.set').then(function(data) {
photoNumb = data;
});
setTimeout("imageSetup()", 5000);
}
function ActionShutdown(){
webiopi().callMacro("shutdownCamera", [0]);
}
| JavaScript | 0 | @@ -4553,84 +4553,8 @@
%0A%09%09%7D
-%0A%7D%0A%0Afunction ActionShutter()%7B%0A webiopi().callMacro(%22shutterCamera%22, %5B0%5D);
%0A%0A%09%09
@@ -4625,24 +4625,28 @@
b = data
+ - 1
;%0A%09%09%7D);%0A
%09%0A%09%09setT
@@ -4637,17 +4637,92 @@
;%0A%09%09%7D);%0A
-%09
+%7D%0A%0Afunction ActionShutter()%7B%0A webiopi().callMacro(%22shutterCamera%22, %5B0%5D);%0A
%0A%09%09setTi
|
c7761e26070c3e4bcd8d6a7016f0bdc18257a39b | clean up naming | analysis/test/js/spec/directives/sumaCsvHourly.js | analysis/test/js/spec/directives/sumaCsvHourly.js | 'use strict';
describe('Directive: sumaCsvHourly', function () {
// load the directive's module
beforeEach(module('sumaAnalysis'));
beforeEach(module('csvHourlyMock'));
// load the directive's template
beforeEach(module('views/directives/csv.html'));
var element,
scope,
testLink,
Ctrlscope;
beforeEach(inject(function ($rootScope, $compile, mockData, mockLink) {
element = angular.element('<span data-suma-csv-hourly data-data="data"></span>');
testLink = mockLink;
scope = $rootScope.$new();
scope.data = mockData;
element = $compile(element)(scope);
scope.$digest();
Ctrlscope = element.isolateScope();
}));
it('should attach a data url to the element', function () {
Ctrlscope.download(scope.data);
expect(Ctrlscope.href).to.equal(testLink);
});
});
| JavaScript | 0.003219 | @@ -289,28 +289,28 @@
cope,%0A
-test
+Mock
Link,%0A
@@ -485,20 +485,20 @@
');%0A
-test
+Mock
Link = m
@@ -814,12 +814,12 @@
ual(
-test
+Mock
Link
|
1d7ea9c960b3d914158142a25cebfb76dd7f0473 | Remove VariablesAreInputTypesRule | packages/relay-compiler/core/RelayValidator.js | packages/relay-compiler/core/RelayValidator.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const Profiler = require('./GraphQLCompilerProfiler');
const util = require('util');
const {
NoUnusedVariablesRule,
PossibleFragmentSpreadsRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
VariablesAreInputTypesRule,
formatError,
} = require('graphql');
import type {Schema} from './Schema';
import type {
DocumentNode,
FieldNode,
ValidationRule,
ValidationContext,
} from 'graphql';
function validateOrThrow(
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
): void {
const validationErrors = schema.DEPRECATED__validate(document, rules);
if (validationErrors && validationErrors.length > 0) {
const formattedErrors = validationErrors.map(formatError);
const errorMessages = validationErrors.map(e => e.toString());
const error = new Error(
util.format(
'You supplied a GraphQL document with validation errors:\n%s',
errorMessages.join('\n'),
),
);
(error: $FlowFixMe).validationErrors = formattedErrors;
throw error;
}
}
function DisallowIdAsAliasValidationRule(
context: ValidationContext,
): $TEMPORARY$object<{|Field: (field: FieldNode) => void|}> {
return {
Field(field: FieldNode): void {
if (
field.alias &&
field.alias.value === 'id' &&
field.name.value !== 'id'
) {
throw new Error(
'RelayValidator: Relay does not allow aliasing fields to `id`. ' +
'This name is reserved for the globally unique `id` field on ' +
'`Node`.',
);
}
},
};
}
module.exports = {
GLOBAL_RULES: [
/* Some rules are not enabled (potentially non-exhaustive)
*
* - KnownFragmentNamesRule: RelayClassic generates fragments at runtime,
* so RelayCompat queries might reference fragments unknown in build time.
* - NoFragmentCyclesRule: Because of @argumentDefinitions, this validation
* incorrectly flags a subset of fragments using @include/@skip as
* recursive.
* - NoUndefinedVariablesRule: Because of @argumentDefinitions, this
* validation incorrectly marks some fragment variables as undefined.
* - NoUnusedFragmentsRule: Queries generated dynamically with RelayCompat
* might use unused fragments.
* - OverlappingFieldsCanBeMergedRule: RelayClassic auto-resolves
* overlapping fields by generating aliases.
*/
NoUnusedVariablesRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
],
LOCAL_RULES: [
/*
* GraphQL built-in rules: a subset of these rules are enabled, some of the
* default rules conflict with Relays-specific features:
* - FieldsOnCorrectTypeRule: is not aware of @fixme_fat_interface.
* - KnownDirectivesRule: doesn't pass with @arguments and other Relay
* directives.
* - ScalarLeafsRule: is violated by the @match directive since these rules
* run before any transform steps.
* - VariablesInAllowedPositionRule: violated by the @arguments directive,
* since @arguments is not defined in the schema. relay-compiler does its
* own type-checking for variable/argument usage that is aware of fragment
* variables.
*/
PossibleFragmentSpreadsRule,
VariablesAreInputTypesRule,
// Relay-specific validation
DisallowIdAsAliasValidationRule,
],
validate: (Profiler.instrument(validateOrThrow, 'RelayValidator.validate'): (
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
) => void),
};
| JavaScript | 0 | @@ -466,38 +466,8 @@
le,%0A
- VariablesAreInputTypesRule,%0A
fo
@@ -3521,40 +3521,8 @@
ule,
-%0A VariablesAreInputTypesRule,
%0A%0A
|
884c167fc7f8d98788652579d8959047544628c8 | Support graphql in resolve-scripts (#171) | packages/resolve-scripts/src/server/express.js | packages/resolve-scripts/src/server/express.js | import bodyParser from 'body-parser';
import express from 'express';
import path from 'path';
import query from 'resolve-query';
import commandHandler from 'resolve-command';
import request from 'request';
import ssr from './render';
import eventStore from './event_store';
import config from '../configs/server.config.js';
const STATIC_PATH = '/static';
const rootDirectory = process.env.ROOT_DIR || '';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const executeQuery = query({
eventStore,
readModels: config.queries
});
const executeCommand = commandHandler({
eventStore,
aggregates: config.aggregates
});
if (config.gateways) {
config.gateways.forEach(gateway => gateway({ executeQuery, executeCommand, eventStore }));
}
app.use((req, res, next) => {
req.resolve = {
executeQuery,
executeCommand,
eventStore
};
next();
});
try {
config.extendExpress(app);
} catch (err) {}
app.get(`${rootDirectory}/api/queries/:queryName`, (req, res) => {
executeQuery(req.params.queryName).then(state => res.status(200).json(state)).catch((err) => {
res.status(500).end('Query error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
app.post(`${rootDirectory}/api/commands`, (req, res) => {
executeCommand(req.body).then(() => res.status(200).send('ok')).catch((err) => {
res.status(500).end('Command error:' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
const staticMiddleware = process.env.NODE_ENV === 'production'
? express.static(path.join(__dirname, '../../dist/static'))
: (req, res) => {
var newurl = 'http://localhost:3001' + req.path;
request(newurl).pipe(res);
};
app.use(`${rootDirectory}${STATIC_PATH}`, staticMiddleware);
app.get([`${rootDirectory}/*`, `${rootDirectory || '/'}`], async (req, res) => {
try {
const state = await config.initialState(executeQuery, {
cookies: req.cookies,
hostname: req.hostname,
originalUrl: req.originalUrl,
body: req.body
});
ssr(state, { req, res });
} catch (err) {
res.status(500).end('SSR error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
}
});
export default app;
| JavaScript | 0 | @@ -1059,32 +1059,174 @@
q, res) =%3E %7B%0A
+ const gqlQuery = req.query && req.query.graphql;%0A const result = gqlQuery%0A ? executeQuery(req.params.queryName, gqlQuery)%0A :
executeQuery(re
@@ -1244,16 +1244,29 @@
eryName)
+;%0A%0A result
.then(st
|
6e9777f51758400cd30641a85a2740563cf89c61 | add table to theme-data storybook docs | packages/theme-data/src/__stories__/stories.js | packages/theme-data/src/__stories__/stories.js | import baseTheme from "../baseTheme";
import basicsReadme from "../basics/README.md";
import densityReadme from "./DENSITY_README.md";
import colorSchemeReadme from "./COLOR_SCHEME_README.md";
function filterMatchByKey(o, keyFragment) {
return Object.keys(o).reduce((acc, key) => {
if (key.match(keyFragment)) {
return { ...acc, [key]: o[key] };
}
return acc;
}, {});
}
export default [
{
description: "Basics - Border radii",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.borderRadii"),
readme: basicsReadme
},
{
description: "Basics - Border widths",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.borderWidths"),
readme: basicsReadme
},
{
description: "Basics - Colors",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.colors"),
readme: basicsReadme
},
{
description: "Basics - Font families",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.fontFamilies"),
readme: basicsReadme
},
{
description: "Basics - Font sizes",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.fontSizes"),
readme: basicsReadme
},
{
description: "Basics - Font weights",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.fontWeights"),
readme: basicsReadme
},
{
description: "Basics - Line heights",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.lineHeights"),
readme: basicsReadme
},
{
description: "Basics - Shadows",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.shadows"),
readme: basicsReadme
},
{
description: "Basics - Spacings",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "basics.spacings"),
readme: basicsReadme
},
{
description: "Color scheme",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "colorScheme"),
readme: colorSchemeReadme
},
{
description: "Density",
schema: filterMatchByKey(baseTheme.unresolvedRoles, "density"),
readme: densityReadme
},
{
description: "Component",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^component./),
readme: undefined
},
{
description: "Component - Accordion",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^accordion./),
readme: undefined
},
{
description: "Component - Avatar",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^avatar./),
readme: undefined
},
{
description: "Component - Banner",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^banner./),
readme: undefined
},
{
description: "Component - Button",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^button./),
readme: undefined
},
{
description: "Component - Checkbox",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^checkbox./),
readme: undefined
},
{
description: "Component - Divider",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^divider./),
readme: undefined
},
{
description: "Component - Flyout",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^flyout./),
readme: undefined
},
{
description: "Component - Form field",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^formField./),
readme: undefined
},
{
description: "Component - Input",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^input./),
readme: undefined
},
{
description: "Component - Label",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^label./),
readme: undefined
},
{
description: "Component - Menu",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^menu./),
readme: undefined
},
{
description: "Component - Modal",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^modal./),
readme: undefined
},
{
description: "Component - Progress bar",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^progressBar./),
readme: undefined
},
{
description: "Component - Progress ring",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^progressRing./),
readme: undefined
},
{
description: "Component - Skeleton item",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^skeletonItem./),
readme: undefined
},
{
description: "Component - Slider",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^slider./),
readme: undefined
},
{
description: "Component - Tabs",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^tabs./),
readme: undefined
},
{
description: "Component - Text area",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^textArea./),
readme: undefined
},
{
description: "Component - Text link",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^textLink./),
readme: undefined
},
{
description: "Component - Tooltip",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^tooltip./),
readme: undefined
},
{
description: "Component - Typography",
schema: filterMatchByKey(baseTheme.unresolvedRoles, /^typography./),
readme: undefined
}
];
| JavaScript | 0.000002 | @@ -4446,32 +4446,169 @@
efined%0A %7D,%0A %7B%0A
+ description: %22Component - Table%22,%0A schema: filterMatchByKey(baseTheme.unresolvedRoles, /%5Etable./),%0A readme: undefined%0A %7D,%0A %7B%0A
description:
|
3734a5389404e56c89467093ec96c487d6450094 | Fix listener tests | packages/transport-commons/test/client.test.js | packages/transport-commons/test/client.test.js | const assert = require('assert');
const { EventEmitter } = require('events');
const errors = require('@feathersjs/errors');
const Service = require('../lib/client');
describe('client', () => {
let connection, testData, service;
beforeEach(() => {
connection = new EventEmitter();
testData = { data: 'testing ' };
service = new Service({
events: [ 'created' ],
name: 'todos',
method: 'emit',
timeout: 50,
connection
});
});
it('sets `events` property on service', () => {
assert.ok(service.events);
});
it('throws an error when the emitter does not have the method', () => {
const service = new Service({
name: 'todos',
method: 'emit',
timeout: 50,
connection: {}
});
try {
service.eventNames();
assert.ok(false, 'Should never get here');
} catch (e) {
assert.equal(e.message, 'Can not call \'eventNames\' on the client service connection');
}
try {
service.on();
assert.ok(false, 'Should never get here');
} catch (e) {
assert.equal(e.message, 'Can not call \'on\' on the client service connection');
}
});
it('allows chaining event listeners', () => {
assert.equal(service, service.on('thing', () => {}));
assert.equal(service, service.once('other thing', () => {}));
});
it('initializes and emits namespaced events', done => {
connection.once('todos test', data => {
assert.deepEqual(data, testData);
done();
});
service.emit('test', testData);
});
it('has other emitter methods', () => {
assert.ok(service.eventNames());
});
it('can receive pathed events', done => {
service.once('thing', data => {
assert.deepEqual(data, testData);
done();
});
connection.emit('todos thing', testData);
});
it('sends all service methods with acknowledgement', () => {
const idCb = (path, id, params, callback) =>
callback(null, { id });
const idDataCb = (path, id, data, params, callback) =>
callback(null, data);
connection.once('create', (path, data, params, callback) => {
data.created = true;
callback(null, data);
});
return service.create(testData)
.then(result => assert.ok(result.created))
.then(() => {
connection.once('get', idCb);
return service.get(1)
.then(res => assert.deepEqual(res, { id: 1 }));
})
.then(() => {
connection.once('remove', idCb);
return service.remove(12)
.then(res => assert.deepEqual(res, { id: 12 }));
})
.then(() => {
connection.once('update', idDataCb);
return service.update(12, testData)
.then(res => assert.deepEqual(res, testData));
})
.then(() => {
connection.once('patch', idDataCb);
return service.patch(12, testData)
.then(res => assert.deepEqual(res, testData));
})
.then(() => {
connection.once('find', (path, params, callback) =>
callback(null, { params })
);
return service.find({ query: { test: true } }).then(res =>
assert.deepEqual(res, {
params: { test: true }
})
);
});
});
it('times out on undefined methods', () => {
return service.remove(10).then(() => {
throw new Error('Should never get here');
}).catch(error =>
assert.equal(error.message, 'Timeout of 50ms exceeded calling remove on todos')
);
});
it('throws a Timeout error when send times out waiting for a response', () => {
return service.remove(10).then(() => {
throw new Error('Should never get here');
}).catch(error =>
assert.equal(error.name, 'Timeout')
);
});
it('converts to feathers-errors (#19)', () => {
connection.once('create', (path, data, params, callback) =>
callback(new errors.NotAuthenticated('Test', { hi: 'me' }).toJSON())
);
return service.create(testData).catch(error => {
assert.ok(error instanceof errors.NotAuthenticated);
assert.equal(error.name, 'NotAuthenticated');
assert.equal(error.message, 'Test');
assert.equal(error.code, 401);
assert.deepEqual(error.data, { hi: 'me' });
});
});
it('converts other errors (#19)', () => {
connection.once('create', (path, data, params, callback) =>
callback('Something went wrong') // eslint-disable-line
);
return service.create(testData).catch(error => {
assert.ok(error instanceof Error);
assert.equal(error.message, 'Something went wrong');
});
});
it('has all EventEmitter methods', done => {
const testData = { hello: 'world' };
const callback = data => {
assert.deepEqual(data, testData);
assert.equal(service.listenerCount('test'), 1);
service.removeListener('test', callback);
assert.equal(service.listenerCount('test'), 0);
done();
};
service.addListener('test', callback);
connection.emit('todos test', testData);
});
it('properly handles on/off methods', done => {
const testData = { hello: 'world' };
const callback1 = data => {
assert.deepEqual(data, testData);
assert.equal(service.listenerCount('test'), 3);
service.off('test', callback1);
assert.equal(service.listenerCount('test'), 2);
service.off('test');
assert.equal(service.listenerCount('test'), 0);
done();
};
const callback2 = () => {
// noop
};
service.on('test', callback1);
service.on('test', callback2);
service.on('test', callback2);
connection.emit('todos test', testData);
});
it('forwards namespaced call to .off', done => {
// Use it's own connection and service so off method gets detected
const connection = new EventEmitter();
connection.off = name => {
assert.equal(name, 'todos test');
done();
};
const service = new Service({
name: 'todos',
method: 'emit',
timeout: 50,
connection
});
service.off('test');
});
});
| JavaScript | 0.000011 | @@ -5365,35 +5365,50 @@
;%0A service.
-off
+removeAllListeners
('test');%0A
|
cee1bc36ab83de27ce8e4809efd2c1f23b93195b | Update browser versions | protractor-remote.conf.js | protractor-remote.conf.js | "use strict";
var request = require("request");
exports.config = {
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
allScriptsTimeout: 11000,
specs: [
"e2e-tests/*.js"
],
multiCapabilities: [
addCommon({browserName: "chrome", version: 46}),
addCommon({browserName: "firefox", version: 42}),
addCommon({browserName: "internet explorer", version: 11}),
addCommon({browserName: "safari", version: "9.0", platform: "OS X 10.11"}),
],
baseUrl: "http://localhost:9090",
onPrepare: function() {
// Disable animations so e2e tests run more quickly
browser.addMockModule("disableNgAnimate", function() {
angular.module("disableNgAnimate", []).run(["$animate", function($animate) {
$animate.enabled(false);
}]);
});
var defer = protractor.promise.defer();
request(browser.baseUrl + "/test_is_integration", function(error, response, body) {
if (!error && response.statusCode === 418 && body === "true") {
defer.fulfill(body);
} else {
defer.reject("Not running against integration!");
}
});
return defer.promise;
},
framework: "jasmine2",
jasmineNodeOpts: {
defaultTimeoutInterval: 60000
}
};
function addCommon(capabilities) {
var buildLabel = "TRAVIS #" + process.env.TRAVIS_BUILD_NUMBER + " (" + process.env.TRAVIS_BUILD_ID + ")";
if (process.env.TRAVIS) {
return {
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER,
"name": "CCJ16 Registration (e2e)",
"build": buildLabel,
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
} else {
return {
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
}
}
| JavaScript | 0 | @@ -277,10 +277,16 @@
on:
-46
+%22latest%22
%7D),%0A
@@ -335,10 +335,16 @@
on:
-42
+%22latest%22
%7D),%0A
@@ -399,18 +399,24 @@
ersion:
-11
+%22latest%22
%7D),%0A%09%09ad
|
7eb9a1111b42e55044d551cee8502dbff6ae95fa | Remove geolocation caching | geolocate.js | geolocate.js | /* global map */
(function () {
'use strict'
var latitude
var longitude
if (!map) return false
var getCurrentLocation = function (success, error) {
var geolocator = window.navigator.geolocation;
var options = {
enableHighAccuracy: true,
maximumAge: 10000
};
if (geolocator) {
// Fixes an infinite loop bug with Safari
// https://stackoverflow.com/questions/27150465/geolocation-api-in-safari-8-and-7-1-keeps-asking-permission/28436277#28436277
window.setTimeout(function () {
geolocator.getCurrentPosition(success, error, options);
}, 0);
} else {
document.getElementById('geolocator').style.display = 'none';
console.log('Browser does not support geolocation');
}
}
var cacheCurrentLocation = function () {
var onSuccess = function (position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
}
// Do nothing if we are unable to do geolocation
// No error callback
getCurrentLocation(onSuccess)
}
var onGeolocateSuccess = function (position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
/* global map */
map.setView([latitude, longitude], 17);
resetGeolocateButton();
}
var onGeolocateError = function (err) {
console.log(err);
alert('Unable to retrieve current position. Geolocation may be disabled on this browser or unavailable on this system.');
resetGeolocateButton();
}
var resetGeolocateButton = function () {
var button = document.getElementById('geolocator').querySelector('.geolocate-icon');
button.classList.remove('geolocating');
}
document.getElementById('geolocator').querySelector('.geolocate-icon').addEventListener('click', function (e) {
if (e.target.classList.contains('geolocating')) {
return false;
}
e.target.classList.add('geolocating');
getCurrentLocation(onGeolocateSuccess, onGeolocateError);
});
// Requests browser's permission to use
// geolocator upon page load, if necessary
cacheCurrentLocation()
})()
| JavaScript | 0.000001 | @@ -760,300 +760,8 @@
%7D%0A%0A
- var cacheCurrentLocation = function () %7B%0A var onSuccess = function (position) %7B%0A latitude = position.coords.latitude%0A longitude = position.coords.longitude%0A %7D%0A%0A // Do nothing if we are unable to do geolocation%0A // No error callback%0A%0A getCurrentLocation(onSuccess)%0A %7D%0A%0A
va
@@ -1700,121 +1700,8 @@
%7D);
-%0A%0A // Requests browser's permission to use%0A // geolocator upon page load, if necessary%0A cacheCurrentLocation()
%0A%7D)(
|
332a3df24e66bc7fee91f5cc0256feff045e431e | Reverting state to 3adfae7e5b3b70310dae64de0ae8a1b8b5471f5f | src/routes/yelpSearch.js | src/routes/yelpSearch.js | var express = require('express'),
yelp = require('yelp-fusion');
var router = express.Router();
var client;
const token = yelp.accessToken(process.env.YELP_KEY, process.env.YELP_SECRET).then(response =>{
client = yelp.client(response.jsonBody.access_token);
}).catch(e => {
console.log(e);
});
function randomGenerator (numBus) {
return Math.floor(Math.random() * numBus);
}
function yelpSearch(query, lat, lon, rad) {
}
router.post('/yelpSearch', (req, res) => {
let query = req.body.data.query;
let coords = req.body.data.coords.split(',');
// Splits the coordinates into latitude and longitude values
let lat = coords[0], lon = coords[1];
// Radius of search in meters
let rad = 9000;
// If stay, shows radius of 1 mile, otherwise 6 miles
if (req.body.data.stay) {
rad = 500;
} else {
rad = 9000;
}
console.log("HI");
//TODO: Increase search radius if nothing found
//TODO: Probably put search in own function, put into a while loop
//TODO: Return 404 on errors, alert on page of error
// Check to make sure query and coords got passed through
if (query || coords === undefined) {
client.search({
term: query,
latitude: lat ,
longitude: lon ,
radius: rad,
categories: ("coffee"),
limit: 50
}).then(response => {
const resJson = response.jsonBody
// Variable to check when response value found
let resVal;
// Generates a random business number upto 50
let count = resJson.businesses.length;
let randBus = randomGenerator(count);
while (resVal === undefined) {
let randBusiness = resJson.businesses[randBus]
// Only marks cafes with a 4 or higher rating
if (randBusiness.rating >= 4) {
// Returns the selected business name
return res.status(200).json(resJson.businesses[randBus]);
resVal = resJson.businesses[randBus].name;
} else {
// Loops with another randomly generated business number
randBus = randomGenerator(count);
}
}
}).catch(e => {
return res.status(404).json({data: "Failed to find :("});
console.log(e);
});
}
})
module.exports = router;
| JavaScript | 0.999651 | @@ -399,56 +399,8 @@
%0A%7D%0A%0A
-function yelpSearch(query, lat, lon, rad) %7B%0A%0A%7D%0A%0A
rout
@@ -768,16 +768,17 @@
rad =
+1
500;%0A %7D
@@ -809,203 +809,8 @@
%7D%0A
- console.log(%22HI%22);%0A //TODO: Increase search radius if nothing found%0A //TODO: Probably put search in own function, put into a while loop%0A //TODO: Return 404 on errors, alert on page of error%0A
//
@@ -1573,31 +1573,24 @@
e%0A
-return
res.status(2
@@ -1823,24 +1823,24 @@
%7D%0A %7D%0A
+
%7D).catch
@@ -1851,72 +1851,8 @@
%3E %7B%0A
- return res.status(404).json(%7Bdata: %22Failed to find :(%22%7D);%0A
|
e5ae43e30821ce2b3caefef328318e46c2fa10f2 | clean up working directory between install:arch tests | packages/xod-cli/test-func/installArch.spec.js | packages/xod-cli/test-func/installArch.spec.js | import { test } from '@oclif/test';
import { assert } from 'chai';
import path from 'path';
import process from 'process';
import fs from 'fs-extra';
import { createWorkingDirectory } from './helpers';
// save process.exit for unmocking
const exit = process.exit;
// save tty status
const isTTY = process.stdout.isTTY;
const its = wd => {
const myWSPath = path.resolve(wd, 'workspace');
const stdMock = test.stdout().stderr();
stdMock
.command(['install:arch', `--workspace=${myWSPath}`, 'adfkjasdfkjasdf'])
.it(
`print error on nonexistent board, creates workspace, stdout is empty, stderr with error, non-zero exit code`,
async ctx => {
assert.isOk(
await fs.pathExists(path.resolve(myWSPath, '.xodworkspace')),
'workspace should be created'
);
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.include(
ctx.stderr,
'Error: invalid item',
'stderr must contain error'
);
assert.notEqual(process.exitCode, 0, 'exit code must be non-zero');
}
);
stdMock
.env({ XOD_WORKSPACE: myWSPath })
.command(['install:arch', '--quiet', 'adfkjasdfkjasdf'])
.it(
`quiet fails on nonexistent board, creates workspace, stdout is empty, stderr with error, non-zero exit code`,
async ctx => {
assert.isOk(
await fs.pathExists(path.resolve(myWSPath, '.xodworkspace')),
'workspace should be created'
);
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.equal(ctx.stderr, '', 'stderr must be empty');
assert.notEqual(process.exitCode, 0, 'exit code must be non-zero');
}
);
stdMock
.env({ XOD_WORKSPACE: myWSPath })
.command(['install:arch', 'emoro:avr'])
.it(
`installs board, creates workspace, stdout is empty, stderr with messages, zero exit code`,
async ctx => {
assert.isOk(
await fs.pathExists(path.resolve(myWSPath, '.xodworkspace')),
'workspace should be created'
);
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.include(
ctx.stderr,
'Installing',
'stderr with install messages'
);
assert.equal(process.exitCode, 0, 'exit code must be zero');
}
);
stdMock
.env({ XOD_WORKSPACE: myWSPath })
.command(['install:arch', '--quiet', 'emoro:avr'])
.it(
`silently installs board, creates workspace, stdout is empty, stderr is empty, zero exit code`,
async ctx => {
assert.isOk(
await fs.pathExists(path.resolve(myWSPath, '.xodworkspace')),
'workspace should be created'
);
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.equal(ctx.stderr, '', 'stderr must be empty');
assert.equal(process.exitCode, 0, 'exit code must be zero');
}
);
stdMock
.env({ XOD_WORKSPACE: myWSPath })
.env({ XOD_ARDUINO_CLI: '/nonexistent' })
.command(['install:arch', 'emoro:avr'])
.it(
`arduino-cli not found, stdout is empty, stderr with error, non-zero exit code`,
async ctx => {
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.include(
ctx.stderr,
'arduino-cli not found',
'stderr with error'
);
assert.notEqual(process.exitCode, 0, 'exit code must be non-zero');
}
);
stdMock
.env({ XOD_WORKSPACE: myWSPath })
.env({ XOD_ARDUINO_CLI: '/nonexistent' })
.command(['install:arch', '-q', 'emoro:avr'])
.it(
`arduino-cli not found, quiet flag, stdout is empty, stderr is empty, non-zero exit code`,
async ctx => {
assert.equal(ctx.stdout, '', 'stdout must be empty');
assert.equal(ctx.stderr, '', 'stderr must be empty');
assert.notEqual(process.exitCode, 0, 'exit code must be non-zero');
}
);
};
describe('xodc install:arch', () => {
// working directory, workspace, src project path
const wd = createWorkingDirectory('installArch');
// create working directory
before(() => fs.ensureDir(wd));
// remove working directory
// unmock TTY status
after(() => {
process.stdout.isTTY = isTTY;
process.stderr.isTTY = isTTY;
fs.removeSync(wd);
});
describe('common', () => {
// mock process.exit
beforeEach(() => {
process.exit = code => {
process.exitCode = code;
};
});
// unmock process.exit
afterEach(() => {
process.exit = exit;
});
test
.stdout()
.stderr()
.command(['install:arch', '--help'])
.catch(/EEXIT: 0/)
.it(
`shows help in stdout, doesn't print to stderr, exits with 0`,
ctx => {
assert.include(ctx.stdout, '--version', '--version flag not found');
assert.include(ctx.stdout, '--help', '--help flag not found');
assert.include(ctx.stdout, '--quiet', '--quiet flag not found');
assert.include(
ctx.stdout,
'--workspace',
'--workspace flag not found'
);
assert.equal(ctx.stderr, '', 'stderr should be emply');
}
);
test
.stdout()
.stderr()
.command(['install:arch', '--version'])
.catch(/EEXIT: 0/)
.it(
`shows version in stdout, doesn't print to stderr and exits with 0`,
ctx => {
assert.include(ctx.stdout, 'xod-cli', 'version string not found');
assert.equal(ctx.stderr, '', 'stderr should be emply');
}
);
});
describe('TTY', () => {
before(() => {
process.stdout.isTTY = true;
process.stderr.isTTY = true;
});
// mock process.exit
beforeEach(() => {
process.exit = code => {
process.exitCode = code;
};
});
// unmock process.exit
afterEach(() => {
process.exit = exit;
});
its(wd);
});
describe('no TTY', () => {
before(() => {
process.stdout.isTTY = false;
process.stderr.isTTY = false;
});
// mock process.exit
beforeEach(() => {
process.exit = code => {
process.exitCode = code;
};
});
// unmock process.exit
afterEach(() => {
process.exit = exit;
});
its(wd);
});
});
| JavaScript | 0 | @@ -5935,32 +5935,84 @@
exit;%0A %7D);%0A%0A
+ after(() =%3E %7B%0A fs.removeSync(wd);%0A %7D);%0A%0A
its(wd);%0A %7D
@@ -6351,32 +6351,84 @@
exit;%0A %7D);%0A%0A
+ after(() =%3E %7B%0A fs.removeSync(wd);%0A %7D);%0A%0A
its(wd);%0A %7D
|
cbc464000d03364d67e5b6c89e0bd22ef7de5f27 | Attach event listeners also to dynamically inserted elements. Fixes #150 | pari/article/static/article/js/media_player.js | pari/article/static/article/js/media_player.js | $(function(){
$(".media-popup").on("shown.bs.modal", function () {
if($(this).data('video')) {
var youtube_url = "http://www.youtube.com/embed/" + $(this).data('video') + "?autoplay=1";
$('.video-container', this).html('<iframe src="' + youtube_url + '" frameborder="0" allowfullscreen></iframe>');
} else {
var soundcloud_url = "https://w.soundcloud.com/player/?url=http://api.soundcloud.com/tracks/" + $(this).data('audio');
$('.audio-container', this).html('<iframe width="100%" height="166" scrolling="no" frameborder="no" src="' + soundcloud_url + '" frameborder="0"></iframe>');
}
});
$(".media-popup").on('hidden.bs.modal', function () {
$('.video-container', this).html('');
$('.audio-container', this).html('');
});
}); | JavaScript | 0 | @@ -10,36 +10,28 @@
n()%7B%0A $(%22
-.media-popup
+body
%22).on(%22shown
@@ -41,16 +41,33 @@
.modal%22,
+ %22.media-popup%22,
functio
@@ -682,28 +682,20 @@
%0A $(%22
-.media-popup
+body
%22).on('h
@@ -710,16 +710,32 @@
.modal',
+ %22.media-popup%22,
functio
|
b8f3f7b57ac0fbde9c1bdd1f3b3ccb931a131c43 | fix localforage error | src/app.js | src/app.js | import feathers from 'feathers/client';
import hooks from 'feathers-hooks';
import rest from 'feathers-rest/client';
import socketio from 'feathers-socketio/client';
import authentication from 'feathers-authentication-client';
import io from 'socket.io-client';
import superagent from 'superagent';
import localForage from 'localforage';
import config from './config';
const storage = __SERVER__ ? require('localstorage-memory') : localForage;
const host = clientUrl => (__SERVER__ ? `http://${config.apiHost}:${config.apiPort}` : clientUrl);
const configureApp = transport => feathers()
.configure(transport)
.configure(hooks())
.configure(authentication({ storage }));
export const socket = io('', { path: host('/ws'), autoConnect: false });
const app = configureApp(socketio(socket));
export default app;
export const restApp = configureApp(rest(host('/api')).superagent(superagent));
export function exposeInitialRequest(req) {
restApp.defaultService = null;
restApp.configure(rest(host('/api')).superagent(superagent, {
headers: {
Cookie: req.get('cookie'),
authorization: req.header('authorization')
}
}));
const accessToken = req.header('authorization') || (req.cookies && req.cookies['feathers-jwt']);
restApp.set('accessToken', accessToken);
}
| JavaScript | 0.000001 | @@ -296,47 +296,8 @@
t';%0A
-import localForage from 'localforage';%0A
impo
@@ -390,19 +390,30 @@
) :
+require('
local
-F
+f
orage
+')
;%0A%0Ac
|
1f2de197d30e05141d9a6418c2b4a973ecfab6b1 | Fix bugs in AST module | src/AST.js | src/AST.js | /*
NOTE: We forego using classes and class-based inheritance because at this time
super() tends to be slow in transpiled code. Instead, we use regular constructor
functions and give them a common prototype property.
*/
import * as Nodes from './Nodes.js';
export * from './Nodes.js';
function isNode(x) {
return x !== null && typeof x === 'object' && typeof x.type === 'string';
}
class AstNode {
children() {
let keys = Object.keys(this);
let list = [];
for (let i = 0; i < keys.length; ++i) {
if (keys[i] === 'parent')
break;
let value = this[keys[i]];
if (Array.isArray(value)) {
for (var j = 0; j < value.length; ++j) {
if (isNode(value[j]))
list.push(value[j]);
}
} else if (isNode(value)) {
list.push(value);
}
}
return list;
}
}
Object.keys(Nodes).forEach(k => Nodes[k].prototype = AstNode.prototype);
| JavaScript | 0.000001 | @@ -555,13 +555,16 @@
-break
+continue
;%0A%0A
@@ -648,11 +648,11 @@
or (
-var
+let
j =
|
e1dc65cc8b1a270e07f8d1dbbb08692204d187e4 | Implement unwrapConsole, to show line numbers when using remote inspector | www/main.js | www/main.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
'use strict';
/******************************************************************************/
function getMode(callback) {
var mode = localStorage.getItem('cdvtests-mode') || 'main';
callback(mode);
}
function setMode(mode) {
var handlers = {
'main': runMain,
'auto': runAutoTests,
'manual': runManualTests
}
if (!handlers.hasOwnProperty(mode)) {
console.error("Unsupported mode: " + mode);
console.error("Defaulting to 'main'");
mode = 'main';
}
localStorage.setItem('cdvtests-mode', mode);
clearContent();
handlers[mode]();
}
/******************************************************************************/
function clearContent() {
var content = document.getElementById('content');
content.innerHTML = '';
var log = document.getElementById('log--content');
log.innerHTML = '';
var buttons = document.getElementById('buttons');
buttons.innerHTML = '';
setLogVisibility(false);
}
/******************************************************************************/
function setTitle(title) {
var el = document.getElementById('title');
el.textContent = title;
}
/******************************************************************************/
function setLogVisibility(visible) {
if (visible) {
document.getElementById('log').classList.add('expanded');
} else {
document.getElementById('log').classList.remove('expanded');
}
}
function toggleLogVisibility() {
var log = document.getElementById('log');
if (log.classList.contains('expanded')) {
log.classList.remove('expanded');
} else {
log.classList.add('expanded');
}
}
/******************************************************************************/
function attachEvents() {
document.getElementById('log--title').addEventListener('click', toggleLogVisibility);
}
/******************************************************************************/
function wrapConsole() {
var origConsole = window.console;
function appendToOnscreenLog(type, args) {
var el = document.getElementById('log--content');
var div = document.createElement('div');
div.classList.add('log--content--line');
div.classList.add('log--content--line--' + type);
div.textContent = Array.prototype.slice.apply(args).map(function(arg) {
return (typeof arg === 'string') ? arg : JSON.stringify(arg);
}).join(' ');
el.appendChild(div);
// scroll to bottom
el.scrollTop = el.scrollHeight;
}
function createCustomLogger(type) {
var medic = require('org.apache.cordova.test-framework.medic');
return function() {
origConsole[type].apply(origConsole, arguments);
// TODO: encode log type somehow for medic logs?
medic.log.apply(medic, arguments);
appendToOnscreenLog(type, arguments);
setLogVisibility(true);
}
}
window.console = {
log: createCustomLogger('log'),
warn: createCustomLogger('warn'),
error: createCustomLogger('error'),
}
}
/******************************************************************************/
function createActionButton(title, callback, appendTo) {
appendTo = appendTo ? appendTo : 'buttons';
var buttons = document.getElementById(appendTo);
var div = document.createElement('div');
var button = document.createElement('a');
button.textContent = title;
button.onclick = function(e) {
e.preventDefault();
callback();
};
button.classList.add('topcoat-button');
div.appendChild(button);
buttons.appendChild(div);
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
function runAutoTests() {
setTitle('Auto Tests');
createActionButton('Again', setMode.bind(null, 'auto'));
createActionButton('Reset App', location.reload.bind(location));
createActionButton('Back', setMode.bind(null, 'main'));
var cdvtests = cordova.require('org.apache.cordova.test-framework.cdvtests');
cdvtests.defineAutoTests();
// Run the tests!
var jasmineEnv = window.jasmine.getEnv();
jasmineEnv.execute();
}
/******************************************************************************/
function runManualTests() {
setTitle('Manual Tests');
createActionButton('Reset App', location.reload.bind(location));
createActionButton('Back', setMode.bind(null, 'main'));
var contentEl = document.getElementById('content');
var beforeEach = function(title) {
clearContent();
setTitle(title || 'Manual Tests');
createActionButton('Reset App', location.reload.bind(location));
createActionButton('Back', setMode.bind(null, 'manual'));
}
var cdvtests = cordova.require('org.apache.cordova.test-framework.cdvtests');
cdvtests.defineManualTests(contentEl, beforeEach, createActionButton);
}
/******************************************************************************/
function runMain() {
setTitle('Cordova Tests');
createActionButton('Auto Tests', setMode.bind(null, 'auto'));
createActionButton('Manual Tests', setMode.bind(null, 'manual'));
createActionButton('Reset App', location.reload.bind(location));
if (/showBack/.exec(location.search)) {
createActionButton('Back', function() {
history.go(-1);
});
}
}
/******************************************************************************/
exports.init = function() {
// TODO: have a way to opt-out of console wrapping in case line numbers are important.
// ...Or find a custom way to print line numbers using stack or something.
// make sure to always wrap when using medic.
attachEvents();
wrapConsole();
var medic = require('org.apache.cordova.test-framework.medic');
medic.load(function() {
if (medic.enabled) {
setMode('auto');
} else {
getMode(setMode);
}
});
};
/******************************************************************************/
| JavaScript | 0 | @@ -2715,35 +2715,8 @@
*/%0A%0A
-function wrapConsole() %7B%0A
var
@@ -2746,16 +2746,51 @@
nsole;%0A%0A
+exports.wrapConsole = function() %7B%0A
functi
@@ -3782,24 +3782,98 @@
ror'),%0A %7D%0A%7D
+;%0A%0Aexports.unwrapConsole = function() %7B%0A window.console = origConsole;%0A%7D;
%0A%0A/*********
@@ -6590,16 +6590,24 @@
ts();%0A
+exports.
wrapCons
|
9d01caa76766dd6ceb5fea4031643288f088daaa | Remove only | test/bigtest/tests/settings-transfers-test.js | test/bigtest/tests/settings-transfers-test.js | import { expect } from 'chai';
import {
beforeEach,
describe,
it,
} from '@bigtest/mocha';
import TransferInteractor from '../interactors/settings-transfers';
import setupApplication from '../helpers/setup-application';
describe.only('Settings transfers', () => {
setupApplication({ scenarios: ['settings-feefine'] });
beforeEach(async function () {
this.visit('/settings/users/transfers');
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.whenLoaded();
});
it('renders proper amount of rows', () => {
expect(TransferInteractor.list.rowCount).to.equal(2);
});
it('renders proper amount of columns', () => {
expect(TransferInteractor.list.rows(0).cellCount).to.equal(4);
});
it('renders proper values for the first row', () => {
const firstRow = TransferInteractor.list.rows(0);
expect(firstRow.cells(0).text).to.equal('USA Bank0');
expect(firstRow.cells(1).text).to.equal('Transfer place0');
});
describe('is visible', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.list.rows(0).deleteButton.click();
});
it('when delete button is clicked', () => {
expect(TransferInteractor.confirmationModal.isPresent).to.be.true;
});
});
describe('confirmation modal disappears', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.list.rows(0).deleteButton.click();
await TransferInteractor.confirmationModal.cancelButton.click();
});
it('when cancel button is clicked ', () => {
expect(TransferInteractor.confirmationModal.isPresent).to.be.false;
});
});
describe('upon click on confirm button initiates the deletion process', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.list.rows(0).deleteButton.click();
await TransferInteractor.confirmationModal.confirmButton.click();
await TransferInteractor.whenLoaded();
});
it('confirmation modal disappears', () => {
expect(TransferInteractor.confirmationModal.isPresent).to.be.false;
});
it('the successful toast appears', () => {
expect(TransferInteractor.callout.successCalloutIsPresent).to.be.true;
});
it('renders empty message', () => {
expect(TransferInteractor.list.rowCount).to.equal(1);
});
});
describe('cancel edit transfers', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.list.rows(0).editButton.click();
await TransferInteractor.list.rows(0).fillTransferName.fillAndBlur('USA Bank3');
await TransferInteractor.list.rows(0).description.fillAndBlur('Transfer place3');
await TransferInteractor.list.rows(0).cancelButton.click();
await TransferInteractor.whenLoaded();
});
it('renders proper values after cancel', () => {
const firstRow = TransferInteractor.list.rows(0);
expect(firstRow.cells(0).text).to.equal('USA Bank0');
expect(firstRow.cells(1).text).to.equal('Transfer place0');
});
});
describe('edit transfers', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.list.rows(0).editButton.click();
await TransferInteractor.list.rows(0).fillTransferName.fillAndBlur('USA Bank11');
await TransferInteractor.list.rows(0).description.fillAndBlur('Transfer place11');
await TransferInteractor.list.rows(0).saveButton.click();
await TransferInteractor.whenLoaded();
});
it('renders proper values after edit', () => {
const firstRow = TransferInteractor.list.rows(0);
expect(firstRow.cells(0).text).to.equal('USA Bank11');
expect(firstRow.cells(1).text).to.equal('Transfer place11');
});
});
describe('add a transfers', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin2');
await TransferInteractor.newTransfersButton.click();
await TransferInteractor.list.rows(0).fillTransferName.fillAndBlur('USA Bank10');
await TransferInteractor.list.rows(0).description.fillAndBlur('Transfer place10');
await TransferInteractor.list.rows(0).saveButton.click();
await TransferInteractor.whenLoaded();
});
it('renders proper values after add', () => {
const firstRow = TransferInteractor.list.rows(3);
expect(firstRow.cells(0).text).to.equal('USA Bank10');
expect(firstRow.cells(1).text).to.equal('Transfer place10');
});
});
describe('add an exist transfer', () => {
beforeEach(async () => {
await TransferInteractor.activeSelector('Main Admin1');
await TransferInteractor.whenLoaded();
await TransferInteractor.newTransfersButton.click();
await TransferInteractor.list.rows(0).fillTransferName.fillAndBlur('USA Bank0');
await TransferInteractor.list.rows(0).description.fillAndBlur('Transfer place0');
await TransferInteractor.list.rows(0).cancelButton.click();
});
it('renders proper amount of rows', () => {
expect(TransferInteractor.list.rowCount).to.equal(2);
});
});
});
| JavaScript | 0 | @@ -234,13 +234,8 @@
ribe
-.only
('Se
|
699d473ac92ab61a7abf32002c500150633cfc08 | enable advpng test (#13) | test/advpng.js | test/advpng.js | import test from 'ava'
import { readFile, writeFile, find, rm } from 'fildes-extra'
import { join } from 'path'
import imagemin from 'imagemin'
import imageminAdvpng from 'imagemin-advpng'
const images = join(__dirname, 'images')
const build = join(__dirname, 'build')
test.before(() => {
return find(join(build, '**/advpng.*.png'))
.then(files => files.map(file => rm(file)))
})
const advpng = files => {
return Promise.all(files.map(file => {
return readFile(join(images, file))
.then(buffer => imagemin.buffer(buffer, {
plugins: [imageminAdvpng({
// optimizationLevel: 3
})]
}))
.then(buffer => writeFile(join(build, file, 'advpng.default.png'), buffer))
}))
}
// https://github.com/imagemin/imagemin-advpng/issues/3
test.skip('advpng', t => {
return find('*.png', { cwd: images })
.then(advpng)
.then(() => find(join(build, '**/advpng.*.png')))
.then(imgs => t.truthy(imgs.length, `found ${imgs.length} advpng's`))
})
| JavaScript | 0 | @@ -709,73 +709,12 @@
%0A%7D%0A%0A
-// https://github.com/imagemin/imagemin-advpng/issues/3%0Atest.skip
+test
('ad
|
de1ce519cab94308b05e76c8d2e9436e9fedb5a6 | Update push.js | www/push.js | www/push.js | /* global cordova:false */
/* globals window */
/*!
* Module dependencies.
*/
var exec = cordova.require('cordova/exec');
/**
* PushNotification constructor.
*
* @param {Object} options to initiate Push Notifications.
* @return {PushNotification} instance that can be monitored and cancelled.
*/
var PushNotification = function(options) {
this._handlers = {
'registration': [],
'notification': [],
'error': []
};
// require options parameter
if (typeof options === 'undefined') {
throw new Error('The options argument is required.');
}
// store the options to this object instance
this.options = options;
// triggered on registration and notification
var that = this;
var success = function(result) {
if (result && typeof result.registrationId !== 'undefined') {
that.emit('registration', result);
} else if (result && result.additionalData && typeof result.additionalData.callback !== 'undefined') {
var executeFunctionByName = function(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split('.');
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
};
executeFunctionByName(result.additionalData.callback, window, result);
} else if (result) {
that.emit('notification', result);
}
};
// triggered on error
var fail = function(msg) {
var e = (typeof msg === 'string') ? new Error(msg) : msg;
that.emit('error', e);
};
// wait at least one process tick to allow event subscriptions
setTimeout(function() {
exec(success, fail, 'PushNotification', 'init', [options]);
}, 10);
};
/**
* Unregister from push notifications
*/
PushNotification.prototype.unregister = function(successCallback, errorCallback, options) {
if (!errorCallback) { errorCallback = function() {}; }
if (typeof errorCallback !== 'function') {
console.log('PushNotification.unregister failure: failure parameter not a function');
return;
}
if (typeof successCallback !== 'function') {
console.log('PushNotification.unregister failure: success callback parameter must be a function');
return;
}
var that = this;
var cleanHandlersAndPassThrough = function() {
if (!options) {
that._handlers = {
'registration': [],
'notification': [],
'error': []
};
}
successCallback();
};
exec(cleanHandlersAndPassThrough, errorCallback, 'PushNotification', 'unregister', [options]);
};
/**
* Call this to set the application icon badge
*/
PushNotification.prototype.setApplicationIconBadgeNumber = function(successCallback, errorCallback, badge) {
if (!errorCallback) { errorCallback = function() {}; }
if (typeof errorCallback !== 'function') {
console.log('PushNotification.setApplicationIconBadgeNumber failure: failure parameter not a function');
return;
}
if (typeof successCallback !== 'function') {
console.log('PushNotification.setApplicationIconBadgeNumber failure: success callback parameter must be a function');
return;
}
exec(successCallback, errorCallback, 'PushNotification', 'setApplicationIconBadgeNumber', [{badge: badge}]);
};
PushNotification.prototype.getApplicationIconBadgeNumber = function(successCallback, errorCallback) {
if (!errorCallback) { errorCallback = function() {}; }
if (typeof errorCallback !== 'function') {
console.log('PushNotification.getApplicationIconBadgeNumber failure: failure parameter not a function');
return;
}
if (typeof successCallback !== 'function') {
console.log('PushNotification.getApplicationIconBadgeNumber failure: success callback parameter must be a function');
return;
}
exec(successCallback, errorCallback, 'PushNotification', 'getApplicationIconBadgeNumber', []);
};
/**
* Get the application icon badge
*/
PushNotification.prototype.select = function(successCallback, errorCallback, data) {
if (!errorCallback) { errorCallback = function() {}; }
if (typeof errorCallback !== 'function') {
console.log('PushNotification.select failure: failure parameter not a function');
return;
}
if (typeof successCallback !== 'function') {
console.log('PushNotification.select failure: success callback parameter must be a function');
return;
}
exec(successCallback, errorCallback, 'PushNotification', 'select', [{data:data}]);
};
/**
* Listen for an event.
*
* The following events are supported:
*
* - registration
* - notification
* - error
*
* @param {String} eventName to subscribe to.
* @param {Function} callback triggered on the event.
*/
PushNotification.prototype.on = function(eventName, callback) {
if (this._handlers.hasOwnProperty(eventName)) {
this._handlers[eventName].push(callback);
}
};
/**
* Remove event listener.
*
* @param {String} eventName to match subscription.
* @param {Function} handle function associated with event.
*/
PushNotification.prototype.off = function (eventName, handle) {
if (this._handlers.hasOwnProperty(eventName)) {
var handleIndex = this._handlers[eventName].indexOf(handle);
if (handleIndex >= 0) {
this._handlers[eventName].splice(handleIndex, 1);
}
}
};
/**
* Emit an event.
*
* This is intended for internal use only.
*
* @param {String} eventName is the event to trigger.
* @param {*} all arguments are passed to the event listeners.
*
* @return {Boolean} is true when the event is triggered otherwise false.
*/
PushNotification.prototype.emit = function() {
var args = Array.prototype.slice.call(arguments);
var eventName = args.shift();
if (!this._handlers.hasOwnProperty(eventName)) {
return false;
}
for (var i = 0, length = this._handlers[eventName].length; i < length; i++) {
this._handlers[eventName][i].apply(undefined,args);
}
return true;
};
PushNotification.prototype.finish = function(successCallback, errorCallback) {
if (!successCallback) { successCallback = function() {}; }
if (!errorCallback) { errorCallback = function() {}; }
if (typeof successCallback !== 'function') {
console.log('finish failure: success callback parameter must be a function');
return;
}
if (typeof errorCallback !== 'function') {
console.log('finish failure: failure parameter not a function');
return;
}
exec(successCallback, errorCallback, 'PushNotification', 'finish', []);
};
/*!
* Push Notification Plugin.
*/
module.exports = {
/**
* Register for Push Notifications.
*
* This method will instantiate a new copy of the PushNotification object
* and start the registration process.
*
* @param {Object} options
* @return {PushNotification} instance
*/
init: function(options) {
return new PushNotification(options);
},
hasPermission: function(successCallback, errorCallback) {
exec(successCallback, errorCallback, 'PushNotification', 'hasPermission', []);
},
/**
* PushNotification Object.
*
* Expose the PushNotification object for direct use
* and testing. Typically, you should use the
* .init helper method.
*/
PushNotification: PushNotification
};
| JavaScript | 0.000001 | @@ -4420,14 +4420,8 @@
back
-, data
) %7B%0A
@@ -4890,21 +4890,9 @@
ct',
- %5B%7Bdata:data%7D
+%5B
%5D);%0A
|
a1c1af255e0fdfd4318493bdf412acf9645d110b | Split disabled and sale logic. | src/App.js | src/App.js | import config from './config.js';
import React, { Component } from 'react';
import Select from './components/Select.js';
import RentSelect from './components/RentSelect.js';
import moment from 'moment';
import DatePicker from 'react-datepicker';
export default class App extends Component {
constructor () {
super();
this.prepareParam = this.prepareParam.bind(this);
this.changeFormActionUrl = this.changeFormActionUrl.bind(this);
this.redirectSearchExtend = this.redirectSearchExtend.bind(this);
this.state = {
formActionUrl: config.formActionUrls.rentShort,
paramGetPrefix: config.paramGetPrefixRent,
sale: false
};
}
redirectSearchExtend () {
window.location.href = config.host + config.searchPathExternal;
}
prepareParam (name) {
return this.state.paramGetPrefix + '[' + name +']';
}
changeFormActionUrl (selectValue) {
let newUrl = config.searchPathExternal;
let newPrefix = config.paramGetPrefixRent;
let sale = false;
switch (selectValue) {
case 'short_rent':
newUrl = config.formActionUrls.rentShort;
newPrefix = config.paramGetPrefixRent;
break;
case 'long_rent':
newUrl = config.formActionUrls.rentLong;
newPrefix = config.paramGetPrefixRent;
break;
case 'sale':
newUrl = config.formActionUrls.sale;
newPrefix = config.paramGetPrefixSale;
sale = true;
break;
};
this.setState({
formActionUrl: newUrl,
paramGetPrefix: newPrefix,
sale: sale
});
}
render() {
let realtyTypes = config.getParams.realtyType.values;
if (this.state.sale) {
realtyTypes = realtyTypes.concat(config.getParams.realtyType.valuesSale);
}
return (
<div className='kipr-widget'>
<form
className='kipr-widget__form'
method='get'
action={config.host + this.state.formActionUrl} >
<h6 className='kipr-widget__header'>Поиск</h6>
<div className='kipr-widget__row kipr-widget__row--type-flex'>
<div className='kipr-widget__column'>
<RentSelect
name={this.prepareParam(config.getParams.duration.name)}
sale={this.state.sale}
title={config.getParams.duration.title}
options={config.getParams.duration.values}
onChange={this.changeFormActionUrl}
/>
</div>
<div className='kipr-widget__column'>
<Select
name={this.prepareParam(config.getParams.realtyType.name)}
title={config.getParams.realtyType.title}
options={realtyTypes}
/>
</div>
</div>
<div className='kipr-widget__row'>
<Select
name={this.prepareParam(config.getParams.region.name)}
title={config.getParams.region.title}
options={config.getParams.region.values}
/>
</div>
<div className='kipr-widget__row kipr-widget__row--type-flex'>
<div className='kipr-widget__column'>
<Select
name={this.prepareParam(config.getParams.bedrooms.name)}
title={config.getParams.bedrooms.title}
options={config.getParams.bedrooms.values}
/>
</div>
<div className='kipr-widget__column'>
<Select
disabled={this.state.sale}
name={this.prepareParam(config.getParams.beds.name)}
title={config.getParams.beds.title}
options={config.getParams.beds.values}
/>
</div>
</div>
<div className='kipr-widget__row kipr-widget__row--type-flex'>
<div className='kipr-widget__column'>
<div className='kipr-widget__formControl kipr-widget__formControl--type-date'>
<label className='kipr-widget__label'>{config.getParams.checkInDate.title}:</label>
<DatePicker
disabled={this.state.sale}
className='kipr-widget__input'
dateFormat="DD.MM.YYYY"
minDate={moment()}
placeholder={moment()}
name={this.prepareParam(config.getParams.checkInDate.name)}
placeholderText='ДД.ММ.ГГГГ'
locale="ru"
/>
</div>
</div>
<div className='kipr-widget__column'>
<Select
disabled={this.state.sale}
name={this.prepareParam(config.getParams.daysCount.name)}
title={config.getParams.daysCount.title}
options={config.getParams.daysCount.values}
/>
</div>
</div>
<div className='kipr-widget__formActions'>
<a className='kipr-widget__extendSearchLink' onClick={this.redirectSearchExtend}>Расширенный поиск</a>
<button className='kipr-widget__button' type='submit'>Найти</button>
</div>
</form>
</div>
);
}
}
| JavaScript | 0 | @@ -635,16 +635,50 @@
ixRent,%0A
+ rentOptionsDisabled: false,%0A
sa
@@ -687,16 +687,16 @@
: false%0A
-
%7D;%0A
@@ -1010,24 +1010,61 @@
PrefixRent;%0A
+ let rentOptionsDisabled = false;%0A
let sale
@@ -1350,32 +1350,68 @@
mGetPrefixRent;%0A
+ rentOptionsDisabled = true;%0A
break;%0A
@@ -1516,24 +1516,60 @@
PrefixSale;%0A
+ rentOptionsDisabled = true;%0A
sale
@@ -1682,16 +1682,64 @@
Prefix,%0A
+ rentOptionsDisabled: rentOptionsDisabled,%0A
sa
@@ -3711,36 +3711,51 @@
led=%7Bthis.state.
+rentOptionsDi
sa
+b
le
+d
%7D%0A
@@ -4347,36 +4347,51 @@
led=%7Bthis.state.
+rentOptionsDi
sa
+b
le
+d
%7D%0A
@@ -4863,36 +4863,51 @@
led=%7Bthis.state.
+rentOptionsDi
sa
+b
le
+d
%7D%0A
|
6a0d0d68853cf7757ebcf92cd685f1093dbdfd39 | Fix cookie domain generator | public/javascript/core.js | public/javascript/core.js | //Reusable functions
var Alphagov = {
cookie_domain: function() {
host_parts = document.location.host.split('.');
return '.' + host_parts.slice(-3, 3).join('.');
},
read_cookie: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
delete_cookie: function(name) {
if (document.cookie && document.cookie != '') {
var date = new Date();
date.setTime(date.getTime()-(24*60*60*1000)); // 1 day ago
document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
},
write_permanent_cookie: function(name, value) {
var date = new Date(2021, 12, 31);
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
}
//General page setup
jQuery(document).ready(function() {
//Setup annotator links
$('a.annotation').each(function(index) {
$(this).linkAnnotator();
});
var has_no_tour_cookie = function() {
return Alphagov.read_cookie('been_on_tour') == null;
}
var write_tour_coookie = function() {
Alphagov.write_permanent_cookie('been_on_tour', 'true');
}
var launch_tour = function() {
$('<div id="splash-back" class="popover-mask"></div>').appendTo($('body'));
$('#splash-back').hide();
$('#splash-back').load('/tour.html #splash', function() {
$(document).trigger('tour-ready');
$('#tour-close').click(close_tour);
$('#splash-back').fadeIn();
});
return false;
}
var close_tour = function() {
$('#splash-back').fadeOut().remove();
return false;
}
//setup tour click event
$('#tour-launcher').click(launch_tour);
//set initial cookie ?
if (has_no_tour_cookie()) {
write_tour_coookie();
launch_tour();
}
});
//Tour setup
$(document).bind('tour-ready', function () {
var $panels = $('#slider .scrollContainer > div');
var $container = $('#slider .scrollContainer');
// if false, we'll float all the panels left and fix the width
// of the container
var horizontal = true;
// collect the scroll object, at the same time apply the hidden overflow
// to remove the default scrollbars that will appear
var $scroll = $('#slider .scroll').css('overflow', 'hidden');
// handle nav selection
function selectNav() {
var nav_li = $(this);
nav_li.parents('ul:first').find('a').removeClass('selected');
nav_li.addClass('selected');
}
$('#slider .navigation').find('a').click(selectNav);
// go find the navigation link that has this target and select the nav
function trigger(data) {
var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
selectNav.call(el);
}
//setup scroll optioons
var scrollOptions = {
target: $scroll, // the element that has the overflow
items: $panels,
navigation: '.navigation a',
axis: 'xy',
onAfter: trigger, // our final callback
offset: 0,
duration: 500,
};
//set first item selected and then setup scroll
$('ul.navigation a:first').click();
$.localScroll(scrollOptions);
}); | JavaScript | 0.000003 | @@ -107,24 +107,34 @@
t.split('.')
+.reverse()
;%0A return
@@ -161,15 +161,24 @@
ice(
--3
+0
, 3).
+reverse().
join
|
b5ed0a6789436063620749aaede1a94ddfb3cce5 | use FileStore for demo | demo/index.js | demo/index.js | const express = require('express');
const http = require("http");
const swig = require('swig');
const Wechat = require('../lib');
const path = require("path");
const debug = require('debug')('wechat');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const MongoStore = Wechat.MongoStore;
const FileStore = Wechat.FileStore;
const wx = new Wechat({
"wechatToken": "6mwdIm9p@Wg7$Oup",
"appId": "wxfc9c5237ebf480aa",
"appSecret": "2038576336804a90992b8dbe46cd5948",
"wechatRedirectUrl": "http://127.0.0.1/oauth",
store: new MongoStore({limit: 5}),
// store: new FileStore({interval: 1000 * 60 * 3}),
});
const app = express();
swig.setDefaults({
cache: false,
});
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname));
app.use(cookieParser());
app.use(session({name: "sid", secret: 'wechat-app', saveUninitialized: true, resave: true}));
app.get('/', function (req, res) {
//also you can generate one at runtime:
//const oauthUrl = wx.oauth.generateOAuthUrl(customRedirectUrl, scope, state);
res.render('index', {oauthUrl: wx.oauth.snsUserInfoUrl});
});
app.get('/api/wechat', function (req, res) {
if(wx.jssdk.verifySignature(req.query)) {
res.send(req.query.echostr);
return;
}
res.send("error");
});
app.get('/get-signature', function(req, res) {
console.log(req.query);
wx.jssdk.getSignature(req.query.url).then((data) => {
console.log('OK', data);
res.json(data);
}, (reason) => {
console.error(reason);
res.json(reason);
});
});
/**
* @see wechatRedirectUrl in Wechat config
*/
app.get('/oauth', function (req, res) {
//use default openid as the key
const key = req.session.openid;
//use custom key for oauth token store
// const key = req.sessionID;
// console.log('oauth sessionID: %s', key);
wx.oauth.getUserInfo(req.query.code, key)
.then(function(userProfile) {
console.log(userProfile);
//set openid to session to use in following request
req.session.openid = userProfile.openid;
res.render("oauth", {
wechatInfo: JSON.stringify(userProfile)
});
});
});
app.get('/oauth-cache', function (req, res) {
const key = req.session.openid;
console.log('openid: ', key);
// const sid = req.sessionID;
// console.log('sessionID: %s', sid);
//get user info without code, but with cached access token,
//if cached token is expired, or cannot refresh the token,
//it will redirect to the "/oauth" router above in catch handler to get new code
wx.oauth.getUserInfo(null, key)
.then(function(userProfile) {
console.log(userProfile);
res.render("oauth", {
wechatInfo: JSON.stringify(userProfile)
});
})
.catch(() => {
//need to get new code
res.redirect(wx.oauth.snsUserInfoUrl);
});
});
app.get('/client.js', function (req, res) {
res.sendFile(path.join(__dirname, '../dist/client.min.js'));
});
const server = http.createServer(app);
const port = process.env.PORT || 3000;
//should use like nginx to proxy the request to 3000, the signature domain must be on PORT 80.
server.listen(port);
server.on('listening', function() {
debug('Express listening on port %d', port);
});
process.on('exit', function () {
wx.store.flush();
});
| JavaScript | 0 | @@ -558,16 +558,19 @@
auth%22,%0A
+ //
store:
@@ -598,19 +598,16 @@
: 5%7D),%0A
- //
store:
|
88df841c370dedd466d1c15cb06b8d556771bb14 | fix typo | src/app.js | src/app.js | import express from 'express';
import bodyParser from 'body-parser';
import requireDir from 'require-dir';
const routes = requireDir('./routes');
const connectors = (() => {
const c = requireDir('./connectors');
return Object.keys(c).reduce((m, k) => {
const v = c[k];
console.log(`(${k}) connector: ${v.name}`);
return Object.assign({}, m, {
[v.name]: v.action,
});
}, {});
})();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Object.keys(routes).forEach((k) => {
const v = routes[k];
console.log(`(${k}) path: ${v.path}`);
app.use(v.path, async (req, res, next) => {
try {
const start = new Date();
console.log(`[${start}] starting ${v.path}`);
const data = await v.action(req);
console.log(`[${new Date}] data`, data);
const groups = (data || []).reduce((m, d) => {
const g = m[d.conector] || []
g.push(d);
m[d.conector] = g;
return m;
}, {});
await Promise.all(Object.keys(groups).map(async (k) => {
const c = connectors[k];
if (c) {
await c(groups[k]);
} else {
console.warn(`CONNECTOR NOT FOUND: ${k}`);
}
return true;
}));
res.sendStatus(200);
const end = new Date();
console.log(`[${end}] finished ${v.path} after ${end.getTime() - start.getTime()} ms`);
} catch (e) {
console.error(e);
e.status = 500;
next(e);
}
});
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
console.error(err);
res.sendStatus(err.status || 500);
});
export default app;
| JavaScript | 0.000864 | @@ -912,24 +912,25 @@
g = m%5Bd.con
+n
ector%5D %7C%7C %5B%5D
@@ -964,16 +964,17 @@
m%5Bd.con
+n
ector%5D =
|
124c8ebae0c768b25051d5a724486861a88e2dff | fix bug in PATRIC3/patric3_website#1813 | public/js/p3/widget/SelectionToGroup.js | public/js/p3/widget/SelectionToGroup.js | define([
"dojo/_base/declare", "dijit/_WidgetBase", "dojo/on",
"dojo/dom-class", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
"dojo/text!./templates/SelectionToGroup.html", "dojo/_base/lang",
"../WorkspaceManager", "dojo/dom-style", "dojo/parser", "dijit/form/Select", "./WorkspaceFilenameValidationTextBox",
"./WorkspaceObjectSelector"
], function(declare, WidgetBase, on,
domClass, Templated, WidgetsInTemplate,
Template, lang, WorkspaceManager, domStyle, Parser, Select, WorkspaceFilenameValidationTextBox,
WorkspaceObjectSelector){
return declare([WidgetBase, Templated, WidgetsInTemplate], {
"baseClass": "Panel",
"disabled": false,
templateString: Template,
selection: null,
path: null,
type: "genome_group",
idType: null,
inputType: null,
conversionTypes: {
"feature_data": [{label: "Feature", value: "feature_group"}, {label: "Genome",value: "genome_group"}]
},
selectType: false,
_setTypeAttr: function(t){
this.type = t;
if(this.workspaceObjectSelector){
this.workspaceObjectSelector.set("type", [t]);
}
},
_setPathAttr: function(path){
this.path = path;
if(this.workspaceObjectSelector){
this.workspaceObjectSelector.set("path", this.path);
}
// for new groups
if(this.groupPathSelector){
this.groupPathSelector.set("path", '/'+window.App.user.id);
this.groupPathSelector.set("value", this.path);
}
if(this.groupNameBox){
this.groupNameBox.set('path', this.path);
}
},
onChangeOutputType: function(){
this.set('type', this.groupTypeSelect.get('value'));
this.set("path", WorkspaceManager.getDefaultFolder(this.type));
this.onChangeTarget(this.type);
if(this.type == "genome_group"){
this.idType = "genome_id";
}
else if(this.type == "feature_group"){
this.idType = "feature_id";
}
},
// only used for new groups
onChangeGroupPath: function(newPath, thing) {
// need to update path of group name box since validation
// and value (full path) state is kept and fetched from there.
this.groupNameBox.set('path', newPath);
},
onChangeTarget: function(target){
if(!this._started){
return;
}
var targetType = this.targetType.get('value');
var val;
if(targetType == "existing"){
domClass.remove(this.workspaceObjectSelector.domNode, "dijitHidden");
// only if new group
domClass.add(this.groupPathLabel, "dijitHidden");
domClass.add(this.groupPathSelector.domNode, "dijitHidden");
domClass.add(this.groupNameBox.domNode, "dijitHidden");
val = this.workspaceObjectSelector.get('value');
}else{
domClass.add(this.workspaceObjectSelector.domNode, "dijitHidden");
// only if new group
domClass.remove(this.groupPathLabel, "dijitHidden");
domClass.remove(this.groupPathSelector.domNode, "dijitHidden");
domClass.remove(this.groupNameBox.domNode, "dijitHidden");
val = this.groupNameBox.isValid() ? this.groupNameBox.get('value') : false;
}
//console.log("Target Val: ", val);
this.value = val;
if(val){
this.copyButton.set('disabled', false);
}else{
this.copyButton.set('disabled', true);
}
},
startup: function(){
var _self = this;
if(this._started){
return;
}
var currentIcon;
this.watch("selection", lang.hitch(this, function(prop, oldVal, item){
console.log("set selection(): ", arguments);
}));
if(!this.path){
this.path = WorkspaceManager.getDefaultFolder(this.type)
this.set("path", WorkspaceManager.getDefaultFolder(this.type));
}
this.inherited(arguments);
if(this.inputType in this.conversionTypes){
this.selectType = true;
domClass.remove(this.groupTypeBox, "dijitHidden");
this.groupTypeSelect.set("options", this.conversionTypes[this.inputType]);
this.groupTypeSelect.set("value", this.conversionTypes[this.inputType][0]["value"]);
this.groupTypeSelect.set("displayedValue", this.conversionTypes[this.inputType][0]["label"]);
}
},
onCancel: function(evt){
on.emit(this.domNode, "dialogAction", {action: "close", bubbles: true});
},
onCopy: function(evt){
if(!this.idType){
this.idType = "genome_id";
if(this.type == "genome_group"){
this.idType = "genome_id";
}
else if(this.type == "feature_group"){
this.idType = "feature_id";
}
else if(this.type == "experiment_group"){
this.idType = "eid";
}
}
var def;
if(this.targetType.get("value") == "existing"){
def = WorkspaceManager.addToGroup(this.value, this.idType, this.selection.filter(lang.hitch(this, function(d){
return this.idType in d
})).map(lang.hitch(this, function(o){
return o[this.idType];
})));
}else{
def = WorkspaceManager.createGroup(this.value, this.type, this.path, this.idType, this.selection.filter(lang.hitch(this, function(d){
return this.idType in d
})).map(lang.hitch(this, function(o){
return o[this.idType];
})));
}
def.then(lang.hitch(this, function(){
on.emit(this.domNode, "dialogAction", {action: "close", bubbles: true});
}));
}
});
});
| JavaScript | 0 | @@ -1910,18 +1910,36 @@
Path
-, thing) %7B
+) %7B%0A%09%09%09this.path = newPath;%0A
%0A%09%09%09
|
956b553dac919df4cb90421aeeb094a9a3842eaf | Use filter in page search | src/search/find-pages.js | src/search/find-pages.js | import update from 'lodash/fp/update'
import db from '../pouchdb'
import { keyRangeForPrefix } from '../pouchdb'
import { pageKeyPrefix } from '../activity-logger'
import { searchableTextFields, revisePageFields } from '../page-analysis'
// Post-process result list after any retrieval of pages from the database.
const postprocessPagesResult = update('rows', rows => rows.map(
// Let the page analysis module augment or revise the document attributes.
update('doc', revisePageFields)
))
// Get all pages for a given array of page ids
export function getPages({pageIds}) {
return db.allDocs({
keys: pageIds,
include_docs: true,
}).then(
postprocessPagesResult
)
}
// Search the log for pages matching given query (keyword) string
export function searchPages({
query,
limit,
}) {
return db.search({
query,
fields: searchableTextFields,
include_docs: true,
highlighting: true,
limit,
stale: 'update_after',
...keyRangeForPrefix(pageKeyPrefix), // Is this supported yet?
}).then(
postprocessPagesResult
)
}
| JavaScript | 0 | @@ -863,24 +863,139 @@
query,%0A
+ filter: doc =%3E (typeof doc._id === 'string'%0A && doc._id.startsWith(pageKeyPrefix)),%0A
fiel
|
236f51a9e2689cb9d0d2a71e00046ac4a16ab517 | Update App.js | src/App.js | src/App.js | import React, {Component} from 'react';
import {Main} from './components/Main';
import Warnings from './components/Warnings';
import Top from './components/Top/Top';
import {StartAuction} from './components/StartAuction/StartAuction';
import Footer from './components/Footer/Footer';
import {getAddressBalance} from './lib/dAppService';
import 'typeface-roboto';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: '',
balance: '',
source: 'metamask'
};
this.setAccount = this.setAccount.bind(this);
this.setEmptyAccount = this.setEmptyAccount.bind(this);
this.setSource = this.setSource.bind(this);
}
setSource(type) {
this.setState({source: type});
}
setAccount(account) {
const balance = getAddressBalance(account);
this.setState({account, balance});
}
setEmptyAccount() {
this.setState({account: '', balance: ''});
}
render() {
return (
<div className="App">
<Top
{...this.state}
setAccount={this.setAccount}
setEmptyAccount={this.setEmptyAccount}
setSource={this.setSource}
/>
{process.env.REACT_APP_PROVIDER
? <Main/>
: <Warnings/>}
<StartAuction/>
<Footer/>
</div>
);
}
}
export default App;
| JavaScript | 0.000001 | @@ -163,77 +163,8 @@
p';%0A
-import %7BStartAuction%7D from './components/StartAuction/StartAuction';%0A
impo
@@ -1200,34 +1200,8 @@
/%3E%7D%0A
- %3CStartAuction/%3E%0A
|
4f50764ebdc7566c4f192e3ad51dec8b1c4c5338 | Add APP_VERSION in app.js | src/app.js | src/app.js | /* Require libs */
var UI = require('ui');
var Vector2 = require('vector2');
var ajax = require('ajax');
var Vibe = require('ui/vibe');
/* Variables */
var isUpdating = false;
var locationOptions = {"timeout": 15000, "maximumAge": 30000,
"enableHighAccuracy": true};
/* UI Elements */
var main_window = new UI.Window();
var info_text = new UI.Text({
position: new Vector2(0, 50),
size: new Vector2(144, 30),
font: 'gothic-24-bold',
text: 'Uber Now',
textAlign: 'center'
});
var anykey_text = new UI.Text({
position: new Vector2(0, 114),
size: new Vector2(144, 30),
font: 'gothic-14-bold',
text: 'Press any key to update',
textAlign: 'center'
});
/* Image Mapping List */
var image_list = {
uberx: "images/mono-uberx.png",
uberxl: "images/mono-uberxl2.png",
uberblack: "images/mono-black.png",
uberexec: "images/mono-black.png",
ubersuv: "images/mono-suv.png",
ubertaxi: "images/mono-taxi.png",
ubert: "images/mono-nytaxi4.png"
};
function locationSuccess(pos) {
console.log(JSON.stringify(pos.coords));
fetchUber(pos.coords);
}
function locationError(err) {
console.warn('location error (' + err.code + '): ' + err.message);
info_text.text('Can\'t get location.');
info_text.font('gothic-18-bold');
isUpdating = false;
}
function firstUpperCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function showUber(data) {
var times = data.times;
if (times.length === 0 && data.is_available) {
info_text.text('No cars available');
info_text.font('gothic-24-bold');
return;
} else if (data.is_available === false) {
info_text.text('No cars available');
info_text.font('gothic-24-bold');
return;
}
var items = [];
times.forEach(function(product) {
product.surge_multiplier = product.surge_multiplier || 1;
product.display_name = firstUpperCase(product.display_name);
var title = product.display_name;
if (product.surge_multiplier !== 1) {
title += ' *' + Number(product.surge_multiplier).toFixed(2);
}
var item = {
title: title,
subtitle: 'pick up time: ' +
Math.ceil(product.estimate / 60) + ' mins',
product: {
display_name: product.display_name,
capacity: product.capacity,
image: product.image,
description: firstUpperCase(product.description)
}
};
items.push(item);
});
var menu = new UI.Menu({
sections: [{
items: items
}]
});
menu.on('select', function(e) {
var product = e.item.product;
if (product.capacity && product.image && product.description) {
var image = image_list[e.item.title.toLowerCase()] ||
'images/mono-black.png';
var card = new UI.Card({
banner: image,
title: product.display_name,
body: "Capacity: " + product.capacity + '\n' + product.description,
scrollable: true
});
card.show();
}
});
menu.show();
}
function fetchUber(coords) {
var params = 'latitude=' + coords.latitude +
'&longitude=' + coords.longitude +
'&demo=1';
ajax({ url: 'http://pebble-uber.yulun.me/?' + params, type: 'json' },
function(data) {
info_text.text('Uber Now');
info_text.font('gothic-24-bold');
Vibe.vibrate('double');
showUber(data);
isUpdating = false;
},
function() {
info_text.text('Connection Error');
info_text.font('gothic-18-bold');
isUpdating = false;
}
);
}
function update() {
if (isUpdating) return;
isUpdating = true;
info_text.text('Updating...');
info_text.font('gothic-24-bold');
window.navigator.geolocation.getCurrentPosition(locationSuccess,
locationError,
locationOptions);
}
main_window.on('click', 'up', update);
main_window.on('click', 'down', update);
main_window.on('click', 'select', update);
// Init
main_window.add(anykey_text);
main_window.add(info_text);
main_window.show();
update();
| JavaScript | 0.000006 | @@ -143,24 +143,50 @@
ariables */%0A
+var APP_VERSION = %22v2.0%22;%0A
var isUpdati
@@ -3158,15 +3158,30 @@
'&
-demo=1'
+pebble=' + APP_VERSION
;%0A
|
dbf15ea6e4de60662c24ccf49c5640d88c25883d | Fix admin advanced flag | src/server/jwt-helper.js | src/server/jwt-helper.js | import jwt from 'jsonwebtoken'
import config from 'config'
import hashids from 'src/shared/utils/hashids-plus'
import { includes } from 'lodash'
const opts = {}
opts.algorithm = config.jwt.OPTIONS.ALG
opts.expiresIn = config.jwt.OPTIONS.EXP
opts.issuer = config.jwt.OPTIONS.ISS
opts.audience = config.jwt.OPTIONS.AUD
export default function (profile, isAdmin=false) {
const data = {}
data.id = hashids.encode(profile.id)
data.email = profile.email
data.password = profile.password
if (isAdmin) {
data.isAdmin = true
}
// Advanced user permission
if (includes(config.jwt.PERMIT.advanced, profile.email)) {
data.advanced = true
}
return jwt.sign(data, config.jwt.SECRET_OR_KEY, opts)
}
export async function verifyJwt (token, checkAdmin=false) {
return new Promise((resolve, reject) => {
jwt.verify(token, config.jwt.SECRET_OR_KEY, opts, function (err, decoded) {
if (!err) {
if (checkAdmin) {
if (decoded.isAdmin) {
resolve(decoded.id)
} else {
throw new Error('Access Denied.')
}
} else {
resolve(decoded.id)
}
} else {
reject(err)
}
})
})
}
| JavaScript | 0 | @@ -521,24 +521,49 @@
dmin = true%0A
+ data.advanced = true%0A
%7D%0A%0A // Ad
|
6260b1fa7145b27a67aeaf1780cd2b1fbde32f0c | fix failed test on windows | test/common.js | test/common.js | var fs = require('fs');
var assert = require('assert');
var csso = require('../lib/index.js');
describe('csso', function() {
it('justDoIt() should works until removed', function() {
var output = [];
var tmp = console.warn;
try {
console.warn = function() {
output.push(Array.prototype.slice.call(arguments).join(' '));
};
assert.equal(
csso.justDoIt('.foo { color: #ff0000 } .bar { color: rgb(255, 0, 0) }'),
'.bar,.foo{color:red}'
);
} finally {
console.warn = tmp;
}
assert.equal(output.length, 1);
assert(/method is deprecated/.test(String(output[0])), 'should contains `method is deprecated`');
});
it('walk', function() {
function visit(withInfo) {
var visitedTypes = {};
csso.walk(csso.parse('@media (min-width: 200px) { .foo:nth-child(2n) { color: rgb(100%, 10%, 0%); width: calc(3px + 5%) } }', 'stylesheet', withInfo), function(node) {
visitedTypes[node[withInfo ? 1 : 0]] = true;
}, withInfo);
return Object.keys(visitedTypes).sort();
}
var shouldVisitTypes = ['stylesheet', 'atruler', 'atkeyword', 'ident', 'atrulerq', 's', 'braces', 'operator', 'dimension', 'number', 'atrulers', 'ruleset', 'selector', 'simpleselector', 'clazz', 'nthselector', 'nth', 'block', 'declaration', 'property', 'value', 'funktion', 'functionBody', 'percentage', 'decldelim', 'unary'].sort();
assert.deepEqual(visit(), shouldVisitTypes, 'w/o info');
assert.deepEqual(visit(true), shouldVisitTypes, 'with info');
});
it('strigify', function() {
assert.equal(
csso.stringify(csso.parse('.a\n{\rcolor:\r\nred}', 'stylesheet', true)),
fs.readFileSync(__dirname + '/fixture/stringify.txt', 'utf-8').trim()
);
});
});
| JavaScript | 0.000001 | @@ -89,16 +89,91 @@
.js');%0A%0A
+function normalize(str) %7B%0A return str.replace(/%5Cn%7C%5Cr%5Cn?%7C%5Cf/g, '%5Cn');%0A%7D%0A%0A
describe
@@ -1917,16 +1917,26 @@
+normalize(
fs.readF
@@ -1996,16 +1996,17 @@
).trim()
+)
%0A
|
4394d9c821c7fcc9321e271e725b1ba0dc4c6c42 | Improve UX of answering boolean prompts | src/services/Terminal.js | src/services/Terminal.js | const {gray, yellow, red, blue, bold} = require('chalk');
const readline = require('../lib/readline/readline');
const {pathCompleter} = require('./pathCompleter');
const EventEmitter = require('events');
const boxen = require('boxen');
const {terminate} = require('../helpers/proc');
module.exports = class Terminal extends EventEmitter {
static create(options) {
const readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: options.interactive ? blue.bold('>> ') : '',
historySize: 0
});
return new Terminal(console, readlineInterface, options.interactive);
}
/**
* @param {Console} console
* @param {readline.Interface} readlineInterface
* @param {boolean} interactive
*/
constructor(console, readlineInterface, interactive) {
super();
if (!console) {
throw new Error('console is missing');
}
if (!readlineInterface) {
throw new Error('readlineInterface is missing');
}
this._line = null;
this._console = console;
this._readline = readlineInterface;
this._promptEnabled = false;
this._ignoreInput = true;
this._readline.on('close', () => terminate());
if (interactive) {
this._handleReadlineInputEvents();
}
}
clearInput(line = '') {
if (line && !this.promptEnabled) {
throw new Error('Prompt disabled');
}
this._clearLine();
this._line = line;
this._restorePrompt();
}
set promptEnabled(enabled) {
if (enabled && !this._promptEnabled) {
this._promptEnabled = true;
this._restorePrompt();
} else if (!enabled && this._promptEnabled) {
this._hidePrompt();
this._promptEnabled = false;
}
}
get promptEnabled() {
return this._promptEnabled;
}
infoBlock({title, body}) {
const indentedBody = body.split(/\n/).map(line => ` ${blue(line)}`).join('\n');
this._hidePrompt();
this._console.log(boxen(
yellow(title) + '\n' + indentedBody
, {padding: {left: 1, right: 1}, borderStyle: 'round'}));
this._restorePrompt();
}
message(text) {
this._hidePrompt();
this._console.log(yellow(text));
this._restorePrompt();
}
output(text) {
this._hidePrompt();
this._console.log(text);
this._restorePrompt();
}
log(text) {
this._hidePrompt();
this._console.log(indentLog(text, ' '));
this._restorePrompt();
}
info(text) {
this._hidePrompt();
this._console.log(blue(indentLog(text, '>')));
this._restorePrompt();
}
debug(text) {
this._hidePrompt();
this._console.log(indentLog(text, ' '));
this._restorePrompt();
}
warn(text) {
this._hidePrompt();
this._console.log(yellow(indentLog(text, '>')));
this._restorePrompt();
}
error(text) {
this._hidePrompt();
this._console.error(red(indentLog(text, '>')));
this._restorePrompt();
}
returnValue(text) {
this._hidePrompt();
this._console.log(`${gray('<')} ${text}`);
this._restorePrompt();
}
messageNoAppConnected(message) {
this.message(`${message}: no Tabris.js 3 app connected!`);
}
/**
* @param {string} prefix
* @param {string} initialText
*/
async promptText(prefix, initialText = '') {
this._readline.completer = pathCompleter;
this.emit('question');
let result = await new Promise(resolve => {
this._readline.line = initialText;
this._readline.question(bold(`${prefix} ${blue('>> ')}`), resolve);
this._readline._moveCursor(Infinity);
});
this.emit('questionAnswered');
this._readline.completer = null;
this._readline.prompt();
return result;
}
/**
*
* @param {string} prefix
*/
async promptBoolean(prefix) {
this.emit('question');
let result = await new Promise(resolve => {
const question = bold(`${prefix} (y/n) ${blue('>> ')}`);
this._readline.question(question, resolve);
});
this.emit('questionAnswered');
this._readline.prompt();
return result.toLowerCase() === 'y';
}
_handleReadlineInputEvents() {
this._readline.on('line', line => {
if (this._ignoreInput) {
return;
}
if (line) {
this.emit('line', line);
} else {
this.clearInput();
}
});
this._readline.input.prependListener('keypress', (_ev, key) => {
if (key.name === 'return') {
this._replacePromptInLineWith(gray('>> '));
}
});
this._readline.input.on('keypress', (ev, key) => {
if (!this._ignoreInput) {
this.emit('keypress', key);
}
});
}
_replacePromptInLineWith(prefix) {
this._clearLine();
this._readline.output.write(prefix + this._readline.line);
}
_hidePrompt() {
if (this._promptEnabled) {
if (this._line === null) {
this._line = this._readline.line;
}
this._ignoreInput = true;
this._clearLine();
}
}
_restorePrompt() {
if (this._promptEnabled) {
const command = this._line || '';
this._readline.line = command;
this._readline.cursor = command.length;
this._readline.prompt(true);
this._ignoreInput = false;
this._line = null;
}
}
_clearLine() {
this._readline.output.write('\x1b[2K\r');
}
};
const indentLog = (log, prefix) => log.split('\n').map((line, i) => `${i === 0 ? prefix : ' '} ${line}`).join('\n');
| JavaScript | 0.000005 | @@ -278,16 +278,50 @@
roc');%0A%0A
+const PROMPT = blue.bold('%3E%3E ');%0A%0A
module.e
@@ -546,32 +546,22 @@
ctive ?
-blue.bold('%3E%3E ')
+PROMPT
: '',%0A
@@ -3812,75 +3812,33 @@
-let result = await new Promise(resolve =%3E %7B%0A const question =
+this._readline.setPrompt(
bold
@@ -3871,20 +3871,19 @@
%3E%3E ')%7D%60)
+)
;%0A
-
this
@@ -3897,77 +3897,262 @@
ine.
-question(question, resolve);%0A %7D);%0A this.emit('questionAnswered'
+prompt();%0A let result = await new Promise(resolve =%3E %7B%0A this._readline.input.once('keypress', (_char, key) =%3E resolve(key.name === 'y'));%0A %7D);%0A this.emit('questionAnswered');%0A this._readline.line = '';%0A this._readline.setPrompt(PROMPT
);%0A
@@ -4200,30 +4200,8 @@
sult
-.toLowerCase() === 'y'
;%0A
|
525318ffb6c5fb21e22d3f1538a0b643c61b025d | fix syntax of example | hello_world_rtm.js | hello_world_rtm.js | var Bot = require('./Slackbot.js');
var bot = Bot();
bot.init();
bot.startRTM({
team: {
token: process.env.token
}
});
bot.hears(['hello'],'direct_message,direct_mention',function(connection,message) {
bot.reply(connection,message,'Hello!');
});
bot.hears(['lunch'],'direct_message,direct_mention',function(connection,message) {
bot.startTask(connection,message,function(task,convo) {
convo.ask('Say YES or NO',{
'yes': {
callback: function(response) { convo.say('YES! Good.'); },
pattern: bot.utterances.yes,
},
'no': {
callback: function(response) { convo.say('NO?!?! WTF?'); },
pattern: bot.utterances.no,
},
'default': function(response) { convo.say('Huh?'); convo.repeat(); }
});
});
});
| JavaScript | 0.000012 | @@ -181,35 +181,24 @@
n',function(
-connection,
message) %7B%0A
@@ -208,27 +208,16 @@
t.reply(
-connection,
message,
@@ -248,13 +248,22 @@
s(%5B'
-lunch
+question','ask
'%5D,'
@@ -302,27 +302,16 @@
unction(
-connection,
message)
@@ -328,24 +328,21 @@
tart
-Task(connec
+Conversa
tion
-,
+(
mess
@@ -358,13 +358,8 @@
ion(
-task,
conv
@@ -393,25 +393,25 @@
or NO',
-%7B
+%5B
%0A
'yes':
@@ -406,15 +406,8 @@
- 'yes':
%7B%0A
@@ -470,16 +470,30 @@
Good.');
+ convo.next();
%7D,%0A
@@ -549,14 +549,8 @@
- 'no':
%7B%0A
@@ -614,16 +614,30 @@
WTF?');
+ convo.next();
%7D,%0A
@@ -693,19 +693,54 @@
-'
+%7B%0A
default
-'
:
+true,%0A callback:
func
@@ -795,15 +795,40 @@
();
-%7D%0A %7D
+ convo.next(); %7D%0A %7D%0A %5D
);%0A
|
2b819adfe80bab0b52fcf43c5f9a32c1d23cae63 | update proper emit | public/js/data-channel.js | public/js/data-channel.js | var room;
var users = {};
var dataChannels = {};
// when Bistri API client is ready, function
// "onBistriConferenceReady" is invoked
onBistriConferenceReady = function () {
// test if the browser is WebRTC compatible
if ( !bc.isCompatible() ) {
// if the browser is not compatible, display an alert
alert( "your browser is not WebRTC compatible !" );
// then stop the script execution
return;
}
/* Set events handler */
// when local user is connected to the server
bc.signaling.bind( "onConnected", function () {
// show pane with id "pane_1"
showPanel( "pane_1" );
} );
// when an error occured on the server side
bc.signaling.bind( "onError", function () {
// display an alert message
alert( error.text + " (" + error.code + ")" );
} );
// when the user has joined a room
bc.signaling.bind( "onJoinedRoom", function ( data ) {
// set the current room name
room = data.room;
// show pane with id "pane_2"
showPanel( "pane_2" );
// then, for every single members already present in the room ...
for ( var i=0, max=data.members.length; i<max; i++ ) {
// set a couple id/nickname to "users" object
users[ data.members[ i ].id ] = data.members[ i ].name;
// ... open a data channel
bc.openDataChannel( data.members[ i ].id, "chat", data.room );
}
} );
// when an error occurred while trying to join a room
bc.signaling.bind( "onJoinRoomError", function ( error ) {
// display an alert message
alert( error.text + " (" + error.code + ")" );
} );
// when the local user has quitted the room
bc.signaling.bind( "onQuittedRoom", function( room ) {
// show pane with id "pane_1"
showPanel( "pane_1" );
// stop the local stream
bc.stopStream();
} );
// when a remote user has joined a room in which the local user is in
bc.signaling.bind( "onPeerJoinedRoom", function ( peer ) {
// set a couple id/nickname to "users" object
users[ peer.pid ] = peer.name;
} );
// when a remote user has quitted a room in which the local user is in
bc.signaling.bind( "onPeerQuittedRoom", function ( peer ) {
// delete couple id/nickname in "users" object
delete users[ peer.pid ];
} );
// when the local user has created a data channel, invoke "onDataChannel" callback
bc.channels.bind( "onDataChannelCreated", onDataChannel );
// when the remote user has created a data channel, invoke "onDataChannel" callback
bc.channels.bind( "onDataChannelRequested", onDataChannel );
// bind function "setNickname" to button "Set Nickname"
q( "#nick" ).addEventListener( "click", setNickname );
// bind function "joinChatRoom" to button "Join Chat Room"
q( "#join" ).addEventListener( "click", joinChatRoom );
// bind function "quitChatRoom" to button "Quit Chat Room"
q( "#quit" ).addEventListener( "click", quitChatRoom );
// bind function "sendChatMessage" to button "Send Message"
q( "#send" ).addEventListener( "click", sendChatMessage );
}
// when "onDataChannelCreated" or "onDataChannelRequested" are triggered
function onDataChannel( dataChannel, remoteUserId ){
// when the data channel is open
dataChannel.onOpen = function(){
// set a couple id/datachannel to "dataChannels" object
dataChannels[ remoteUserId ] = this;
// check chat partner presence
isThereSomeone();
};
// when the data channel is closed
dataChannel.onClose = function(){
// delete couple id/datachannel from "dataChannels" object
delete dataChannels[ remoteUserId ];
// check chat partner presence
isThereSomeone();
};
// when a message is received from the data channel
dataChannel.onMessage = function( event ){
// display the received message
displayMessage( users[ remoteUserId ], event.data );
};
}
// when button "Set Nickname" has been clicked
function setNickname(){
// get nickname field content
var nickname = q( "#nick_field" ).value;
// if a nickname has been set ...
if( nickname ){
// initialize API client with application keys and nickname
// if you don't have your own, you can get them at:
// https://api.developers.bistri.com/login
bc.init( {
appId: "5c876c85",
appKey: "b7c7af83477160c8cd20015dd0f4c0b0",
userName: nickname,
debug: true
} );
// open a new session on the server
bc.connect();
}
else{
// otherwise, display an alert
alert( "you must enter a nickname !" );
}
}
// when button "Join Chat Room" has been clicked
function joinChatRoom(){
// get chat room field content
var roomToJoin = q( "#room_field" ).value;
// if a chat room name has been set ...
if( roomToJoin ){
// ... join the room
bc.joinRoom( roomToJoin );
}
else{
// otherwise, display an alert
alert( "you must enter a room name !" );
}
}
// when button "Quit Chat Room" has been clicked
function quitChatRoom(){
// for each data channel present in "dataChannels" object ...
for( var id in dataChannels ){
// ... close the data channel
dataChannels[ id ].close();
}
// and quit chat room
bc.quitRoom( room );
}
// when button "Send Message" has been clicked
function sendChatMessage(){
// get message field content
var message = q( "#message_field" ).value;
// if a chat room name has been set ...
if( message ){
// for each data channel present in "dataChannels" object ...
for( var id in dataChannels ){
// ... send a message
dataChannels[ id ].send( message );
}
// display the sent message
displayMessage( "me", message );
// reset message field content
q( "#message_field" ).value = "";
}
}
// when a message must be dislpayed
function displayMessage( user, message ){
// create a message node and insert it in div#messages_container node
var container = q( "#messages_container" );
var textNode = document.createTextNode( user + " > " + message );
var node = document.createElement( "div" );
node.className = "message";
node.appendChild( textNode );
container.appendChild( node );
// scroll to bottom to always display the last message
container.scrollTop = container.scrollHeight;
console.log("new msg received...should be emitting event");
//.emit('rovpilot.setYaw', 0);
window.io.Socket.emit()
}
// when checking for chat partner presence
function isThereSomeone(){
// if "dataChannels" object contains one or more data channel objects ...
if( Object.keys( dataChannels ).length ){
// ... enabled "Send Message" button
q( "#send" ).removeAttribute( "disabled" );
}
else{
// otherwise disable "Send Message" button
q( "#send" ).setAttribute( "disabled", "disabled" );
}
}
function showPanel( id ){
var panes = document.querySelectorAll( ".pane" );
// for all nodes matching the query ".pane"
for( var i=0, max=panes.length; i<max; i++ ){
// hide all nodes except the one to show
panes[ i ].style.display = panes[ i ].id == id ? "block" : "none";
};
}
function q( query ){
// return the DOM node matching the query
return document.querySelector( query );
}
| JavaScript | 0.000001 | @@ -6744,31 +6744,36 @@
;%0A
-window.io.Socket.emit()
+socket.emit(%22escs_poweron%22);
%0A%7D%0A%0A
|
db71ec4183947c7ab25c8436b7eddc03251d67a8 | Tweak instructions link text, fix href warning | src/App.js | src/App.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './appRedux';
import Cell from './Cell.js';
import Settings from './Settings.js';
import Instructions from './Instructions.js';
import './App.css';
const mapStateToProps = state => ({
settings: state.settings,
cells: state.cells,
win: state.win,
movesMade: state.movesMade,
cheatMode: state.cheatMode,
showInstructions: state.showInstructions
});
class App extends Component {
onPlayCell(cellCoords) {
const { dispatch } = this.props;
dispatch(actionCreators.playCell(cellCoords));
}
onStartGame = settings => {
const { dispatch } = this.props;
dispatch(actionCreators.startGame(settings));
};
onToggleCheatMode = () => {
const { dispatch } = this.props;
dispatch(actionCreators.toggleCheatMode());
};
onShowInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.showInstructions());
};
onCloseInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.closeInstructions());
};
renderCellGrids() {
const { depth } = this.props.settings;
return Array(depth).fill().map((_, z) => {
return (
<div key={['grid', z].join('-')} className="App-cell-grid">
{depth > 1 &&
<h5 className="App-cell-grid-title">
Layer {z + 1}
</h5>}
{this.renderCellGrid(z)}
</div>
);
});
}
renderCellGrid(z) {
const { height } = this.props.settings;
return Array(height).fill().map((_, y) => {
return (
<div key={['row', y, z].join('-')} className="App-cell-row">
{this.renderCellRow(y, z)}
</div>
);
});
}
renderCellRow(y, z) {
const { width } = this.props.settings;
return Array(width).fill().map((_, x) => {
return this.renderCell(x, y, z);
});
}
renderCell(x, y, z) {
const { cells, cheatMode, win } = this.props;
const thisCell = cells[z][y][x];
const cycle = cheatMode && thisCell.cycle;
return (
<Cell
onClickCell={() => {
this.onPlayCell([x, y, z]);
}}
value={thisCell.value}
cycle={cycle}
win={win}
key={[x, y, z].join('-')}
/>
);
}
render() {
const { settings, win, movesMade, showInstructions } = this.props;
return (
<div className="App">
<div className="App-header">
<h2>
{win ? `You Win! (${movesMade} moves)` : 'Chroma Tiles'}
</h2>
</div>
<div className="App-settings">
<Settings
settings={settings}
onUpdateSettings={this.onStartGame}
displayCheatMode={movesMade > 50}
onClickCheatMode={this.onToggleCheatMode}
/>
</div>
<div className="App-container">
{this.renderCellGrids()}
</div>
<div className="App-footer">
<div>
<a href="#" onClick={this.onShowInstructions}>
Instructions
</a>
</div>
<div>
<a href="https://github.com/alexcavalli/chroma-tiles">
Code on GitHub
</a>
</div>
</div>
{showInstructions &&
<Instructions onCloseInstructions={this.onCloseInstructions} />}
</div>
);
}
}
export default connect(mapStateToProps)(App);
| JavaScript | 0 | @@ -3039,16 +3039,28 @@
href=%22#
+instructions
%22 onClic
@@ -3102,16 +3102,21 @@
+Show
Instruct
@@ -3119,16 +3119,22 @@
ructions
+ Again
%0A
|
22a0ebd1aed7dd437f672fc5fdc31ec37d72bd26 | Update config.js | test/config.js | test/config.js | module.exports = {
library: "/usr/lib/libsofthsm.so",
name: "SoftHSM",
slot: 0,
sessionFlags: 4, // SERIAL_SESSION
pin: "6789"
}
| JavaScript | 0.000002 | @@ -29,18 +29,32 @@
%22/usr/l
-ib
+ocal/lib/softhsm
/libsoft
@@ -56,16 +56,17 @@
bsofthsm
+2
.so%22,%0A%09n
@@ -78,16 +78,18 @@
%22SoftHSM
+v2
%22,%0A%09slot
@@ -143,12 +143,13 @@
n: %22
-6789
+12345
%22%0A%7D%0A
|
2e58c815b8b9b15dd4e4b7e308f3805c08a79ab2 | Move decodeArticleUrl to parent | client/src/components/ArticleShow.js | client/src/components/ArticleShow.js | import React from 'react'
import BackButton from './BackButton'
function decodeArticleUrl(title) {
const sanitizedTitle = decodeURIComponent(title)
return sanitizedTitle.split("[percent]").join("%")
}
const ArticleShow = ({channel, articles, match}) => {
const matchParams = decodeArticleUrl(match.params.article)
const article = articles.find(article => article.title === matchParams)
return (
<div className="article">
<h1>{article.title}</h1>
<BackButton />
<img src={article.urlToImage} className="image-large" alt=""/>
<h3>{article.description}</h3>
<h3><a href={article.url} className="link" target="_blank">Read full article on {channel.name}</a></h3>
</div>
)
}
export default ArticleShow
| JavaScript | 0.000002 | @@ -63,148 +63,8 @@
'%0A%0A%0A
-function decodeArticleUrl(title) %7B%0A const sanitizedTitle = decodeURIComponent(title)%0A return sanitizedTitle.split(%22%5Bpercent%5D%22).join(%22%25%22)%0A%7D
%0A%0Aco
@@ -107,16 +107,34 @@
s, match
+, decodeArticleUrl
%7D) =%3E %7B%0A
|
ea07381c25811380b99c495f64ac13bcfb085c2f | test of pushing ability | client/src/js/models/SessionModel.js | client/src/js/models/SessionModel.js | /* global gapi */
var _ = require('underscore');
var Backbone = require('backbone');
var UserModel = require('./UserModel.js');
var SessionModel = Backbone.Model.extend({
defaults: {
logged: false,
userId: ''
},
initialize: function() {
this.user = new UserModel({});
},
loginSessionUser: function(googleUser) {
var profile = googleUser.getBasicProfile();
// Get attributes from user's gmail account and assign to
// the current user in this session.
this.updateSessionUser({
id: googleUser.getAuthResponse().id_token,
name: profile.getName(),
email: profile.getEmail(),
image: profile.getImageUrl()
});
// Set the SessionModel's values and show that a user is
// now logged in.
this.set({ userId: this.user.get('id'), logged: true });
},
logoutSessionUser: function() {
// Clear and resets GoogleUser attributes to UserModel
// default values.
this.updateSessionUser(this.user.defaults);
// Reset the SessionModel's values to defaults and show
// that a user is now logged out.
this.set({ userId: this.user.get('id'), logged: false });
},
updateSessionUser: function(userData) {
// A user model is passed into this function.
//
// Select the model's default properties (_.pick its default
// _.keys) and set them using the values passed in from userData.
//
// In this instance, we are picking and updating id, name,
// email, and image.
this.user.set(_.pick(userData, _.keys(this.user.defaults)));
},
checkAuth: function(callback) {
callback = callback || {};
var auth2 = gapi.auth2.getAuthInstance();
var userSignedIn = auth2.isSignedIn.get();
var googleUser = auth2.currentUser.get();
var profile = googleUser.getBasicProfile();
console.log('auth2 is signed in: ', auth2.isSignedIn.get());
// If a User is signed in and their gmail matches a @isl.co gmail,
// log in this user.
if (userSignedIn && profile.getEmail().match(/^.*@isl.co$/g)) {
this.loginSessionUser(googleUser);
if ('success' in callback) {
// If user is successfully signed in, call back the
// auth2SignInChanged()'s success function (in client.js)
callback.success();
}
} else {
this.logoutSessionUser();
if ('error' in callback) {
callback.error();
}
}
console.log('session: ', this.attributes);
console.log('user: ', this.user.attributes);
if ('complete' in callback) {
callback.complete();
}
}
});
module.exports = SessionModel;
| JavaScript | 0.000001 | @@ -478,24 +478,25 @@
his session.
+
%0A this.up
|
b94493ffe7364f72b6aea3187d816849102b13e2 | align margin (#670) | src/App.js | src/App.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'redux-bundler-react'
import NavBar from './navigation/NavBar'
import navHelper from 'internal-nav-helper'
import IpldExploreForm from './ipld/IpldExploreForm'
import AsyncRequestLoader from './loader/AsyncRequestLoader'
export class App extends Component {
static propTypes = {
doInitIpfs: PropTypes.func.isRequired,
doUpdateUrl: PropTypes.func.isRequired,
route: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element
]).isRequired
}
componentWillMount () {
this.props.doInitIpfs()
}
render () {
const Page = this.props.route
return (
<div className='sans-serif' onClick={navHelper(this.props.doUpdateUrl)}>
<div className='dt dt--fixed' style={{minHeight: '100vh'}}>
<div className='dtc v-top bg-navy' style={{width: 240}}>
<NavBar />
</div>
<div className='dtc v-top'>
<div style={{background: '#F0F6FA'}}>
<IpldExploreForm />
</div>
<main className='pa3'>
<Page />
</main>
</div>
</div>
<div className='absolute top-0 left-0 pa2'>
<AsyncRequestLoader />
</div>
</div>
)
}
}
export default connect('selectRoute', 'doUpdateUrl', 'doInitIpfs', App)
| JavaScript | 0 | @@ -1101,23 +1101,33 @@
ain
-className='pa3'
+style=%7B%7Bpadding: '40px'%7D%7D
%3E%0A
|
59d991ea7d10961e90b79231f092a5d780300fbe | Clean up sessionsConverter module | src/sessionsConverter.js | src/sessionsConverter.js | // module pattern
var sessionsConverter = (function(){
// variable to keep track of different labels
var labels = [];
// labels set for checking if label is unique
var labelSet = {};
function init(){
labels = [];
labelSet = {};
}
function getConvertedSessions(sessions){
var convertedSessions = [];
sessions.forEach(function(session){
convertedSessions.push(getConvertedSession(session));
});
return convertedSessions;
}
function getConvertedSession(session){
var now = moment(); // current time
var outcomes = session.outcomes;
// data set item for session
var convertedSession = {};
var momentTimestamp = moment(session.timestamp);
var humanisedTimestamp = moment.duration(momentTimestamp.diff(now)).humanize(true);
convertedSession.label = humanisedTimestamp;
convertedSession.valuesMap = getValuesMapsFromOutcomes(outcomes);
// extract data and notes arrays
var extractedDataAndNotes = getExtractedDataAndTooltipNotes(convertedSession.valuesMap);
convertedSession.data = extractedDataAndNotes.data;
convertedSession.notes = extractedDataAndNotes.notes;
var color = Chart.helpers.color;
//assign random colour to chart
var colour = randomColor({
format: 'rgba'
});
convertedSession.backgroundColor = color(colour).alpha(0.2).rgbString();
convertedSession.borderColor = colour;
convertedSession.pointBackgroundColor = colour;
return convertedSession;
}
function getValuesMapsFromOutcomes(outcomes){
var dataMap = {};
var noteMap = {};
// add each outcome to a set
outcomes.forEach(function(outcome){
var lowerCaseLabel = outcome.outcome.toLowerCase();
updateLabelSet(outcome.outcome);
dataMap[lowerCaseLabel] = outcome.value;
noteMap[lowerCaseLabel] = outcome.notes;
});
return {
data : dataMap,
notes: noteMap
}
}
// check if our set has the value or not
function updateLabelSet(potentialLabel){
var lowerCaseLabel = potentialLabel.toLowerCase();
if(!labelSet.hasOwnProperty(lowerCaseLabel)){
labels.push(potentialLabel);
// now value is in our set
labelSet[lowerCaseLabel] = true;
}
}
function getExtractedDataAndTooltipNotes(valuesMap){
// go over currently added labels
var data = [];
var notes = [];
labels.forEach(function(label){
data.push(getExtractedDataValue(valuesMap.data[label.toLowerCase()]));
notes.push(getExtractedNoteValue(valuesMap.notes[label.toLowerCase()]))
});
return {
data : data,
notes: notes
}
}
function getExtractedDataValue(dataValue){
return dataValue === undefined ? null : dataValue;
}
function getExtractedNoteValue(noteValue){
return noteValue === undefined ? "none" : noteValue;
}
function getLabels(){
return labels;
}
return {
getChartJSConvertedData: function(sessions){
init();
var chartData = {};
chartData.datasets = getConvertedSessions(sessions);
chartData.labels = getLabels();
return chartData;
}
};
})();
| JavaScript | 0 | @@ -1,8 +1,22 @@
+'use strict'%0A%0A
// modul
@@ -853,16 +853,111 @@
stamp;%0A%0A
+ // adding the values map to converted session for developer to view for possible debugging%0A
conv
@@ -1605,24 +1605,157 @@
ssion;%0A %7D%0A%0A
+ // this creates a mapping of the data value as well as notes for each label%0A // to be later used to create the ChartJS data array%0A
function g
@@ -1937,45 +1937,8 @@
el =
- outcome.outcome.toLowerCase();%0A
upd
@@ -1945,19 +1945,17 @@
ateLabel
-Set
+s
(outcome
@@ -2199,19 +2199,17 @@
ateLabel
-Set
+s
(potenti
@@ -2430,34 +2430,160 @@
= true;%0A %7D%0A
-%7D%0A
+ return lowerCaseLabel;%0A %7D%0A%0A // Use values map to create the data and notes arrays confroming to %0A // ChartJS requirements.
%0A function getE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.