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
|
---|---|---|---|---|---|---|---|
e45f7eb62428aa8e5b00afeca2fa0bed5aeb9c21 | Change error message when caching fails | lib/less-browser/cache.js | lib/less-browser/cache.js | // Cache system is a bit outdated and could do with work
module.exports = function(window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
return {
setCSS: function(path, lastModified, styles) {
if (cache) {
logger.info('saving ' + path+ ' to cache.');
try {
cache.setItem(path, styles);
cache.setItem(path + ':timestamp', lastModified);
} catch(e) {
//TODO - could do with adding more robust error handling
logger.error('failed to save');
}
}
},
getCSS: function(path, webInfo) {
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp');
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf())) {
// Use local copy
return css;
}
}
};
};
| JavaScript | 0.000001 | @@ -755,16 +755,61 @@
to save
+ %22' + path + '%22 to local storage for caching.
');%0A
|
b0483165a9125ffc36725bd96b1c5f70bd28d346 | Test corrections. | client/js/controller.js | client/js/controller.js | function AppCtrl($scope) {
'use strict';
$scope.title = 'The Movie Database';
}
function WelcomeCtrl($scope, moviesResponse) {
'use strict';
$scope.movies = moviesResponse.data;
}
WelcomeCtrl.resolve = {
moviesResponse: function ($http) {
'use strict';
return $http.get('/movies');
}
};
function MoviesListCtrl($scope, $location, moviesResponse) {
'use strict';
$scope.movies = moviesResponse.data;
$scope.add = function () {
$location.path('/movies/new');
};
}
MoviesListCtrl.resolve = {
moviesResponse: function ($http) {
'use strict';
return $http.get('/movies');
}
};
function MoviesAddCtrl($scope, $http, $location) {
'use strict';
$scope.movie = {};
$scope.save = function (movie) {
$http.post('/movies', movie)
.success(function (res) {
$location.path('/movies/' + res.id);
});
};
}
function MovieDetailCtrl($scope, $http, $location, moviesResponse) {
'use strict';
$scope.movie = moviesResponse.data;
$scope['delete'] = function () {
$http['delete']('/movies/' + $scope.movie.id).success(function (res) {
$location.path('/movies');
});
};
}
function movieDetailResolver($http, $route) {
'use strict';
var id = $route.current.params.id;
return $http.get('/movies/' + id);
}
MovieDetailCtrl.resolve = {
moviesResponse: movieDetailResolver
};
function MovieEditCtrl($scope, $http, $location, moviesResponse) {
'use strict';
$scope.movie = moviesResponse.data;
$scope.save = function () {
$http.put('/movies/' + $scope.movie.id, $scope.movie)
.success(function (res) {
$location.path('/movies/' + $scope.movie.id);
});
};
}
MovieEditCtrl.resolve = {
moviesResponse: movieDetailResolver
};
function NotFoundCtrl($scope, $location) {
'use strict';
$scope.culprit = $location.search().culprit || 'unknown beast';
}
var ErrorCtrl = NotFoundCtrl;
angular.module('MovieDatabase').controller('NavigationCtrl', function ($scope, $location) {
'use strict';
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) == path) {
if (path == "/" && $location.path() == "/") {
return "active";
} else if (path == "/") {
return "";
}
return "active"
} else {
return ""
}
}
}); | JavaScript | 0.000802 | @@ -2248,16 +2248,17 @@
ngth) ==
+=
path) %7B
@@ -2281,20 +2281,21 @@
(path ==
- %22/%22
+= '/'
&& $loc
@@ -2309,20 +2309,21 @@
ath() ==
- %22/%22
+= '/'
) %7B%0A
@@ -2341,24 +2341,24 @@
return
-%22
+'
active
-%22
+'
;%0A
@@ -2385,12 +2385,13 @@
h ==
- %22/%22
+= '/'
) %7B%0A
@@ -2413,18 +2413,18 @@
return
-%22%22
+''
;%0A
@@ -2454,16 +2454,17 @@
urn
-%22
+'
active
-%22
+';
%0A
@@ -2500,10 +2500,11 @@
urn
-%22%22
+'';
%0A
@@ -2515,14 +2515,14 @@
%7D%0A %7D
-%0A
+;
%0A%0A%7D);
|
e6dbe288868ec172030b02508e2f4a8993553ee9 | Update he.js | dist/locale/he.js | dist/locale/he.js | export default {
after: (field, [target]) => `השדה ${field} חייב להכיל תאריך לאחר ${target}.`,
alpha_dash: (field) => `השדה ${field} יכול להכיל רק אותיות, מספרים ומקפים.`,
alpha_num: (field) => `השדה ${field} יכול להכיל רק אותיות ומספרים..`,
alpha_spaces: (field) => `השדה ${field} יכול להכיל רק אותיות ורווחים.`,
alpha: (field) => `השדה ${field} יכול להכיל רק אותיות.`,
before: (field, [target]) => `השדה ${field} חייב להכיל תאריך לפני ${target}.`,
between: (field, [min, max]) => `הערך ${field} חייב להיות בין ${min} ל- ${max}.`,
confirmed: (field) => `הערכים של ${field} חייבים להיות זהים.`,
date_between: (field, [min, max]) => `השדה ${field} חייב להיות בין התאריכים ${min} ו- ${max}.`,
date_format: (field, [format]) => `השדה ${field} חייב להיות בפורמט ${format}.`,
decimal: (field, [decimals] = ['*']) => `השדה ${field} חייב להיות מספרי ולהכיל ${decimals === '*' ? '' : decimals} נקודות עשרוניות.`,
digits: (field, [length]) => `השדה ${field} חייב להיות מספר ולהכיל ${length} ספרות בדיוק.`,
dimensions: (field, [width, height]) => `השדה ${field} חייב להיות ${width} פיקסלים על ${height} פיקסלים.`,
email: (field) => `השדה ${field} חייב להכיל כתובת אימייל תקינה.`,
ext: (field) => `השדה ${field} חייב להכיל קובץ תקין.`,
image: (field) => `השדה ${field} חייב להכיל תמונה.`,
in: (field) => `השדה ${field} חייב להיות בעל ערך תקין.`,
ip: (field) => `השדה ${field} חייב להכיל כתובת IP תקינה.`,
max: (field, [length]) => `השדה ${field} לא יכול להכיל יותר מ- ${length} ספרות.`,
max_value: (field, [max]) => `השדה ${field} יכול להיות ${max} לכל היותר.`,
mimes: () => `הקובץ חייב להיות מסוג תקין.`,
min: (field, [length]) => `השדה ${field} חייב להכיל ${length} ספרות לפחות.`,
min_value: (field, [min]) => `הערך של ${field} חייב להיות לפחות ${min}.`,
not_in: (field) => `השדה ${field} חייב להכיל ערך תקין.`,
numeric: (field) => `השדה ${field} יכול להכיל ספרות בלבד.`,
regex: (field) => `הפורמט של ${field} אינו תקין.`,
required: (field) => `חובה למלא את השדה ${field}.`,
size: (field, [size]) => `השדה ${field} חייב לשקול פחות מ ${size} KB`,
url: (field) => `${field} אינו מכיל כתובת אינטרנט תקינה.`
};
| JavaScript | 0 | @@ -1536,21 +1536,21 @@
length%7D
-%D7%A1%D7%A4%D7%A8%D7%95%D7%AA
+%D7%AA%D7%95%D7%95%D7%99%D7%9D
.%60,%0A
@@ -1738,21 +1738,21 @@
length%7D
-%D7%A1%D7%A4%D7%A8%D7%95%D7%AA
+%D7%AA%D7%95%D7%95%D7%99%D7%9D
%D7%9C%D7%A4%D7%97%D7%95%D7%AA.%60
|
c42e3066e0147c6fa5ff36451b7a0e8759114e3e | Update the marker form widget when changing the settings | src/public/js/view/editPoiLayerColumn.js | src/public/js/view/editPoiLayerColumn.js |
define([
'underscore',
'backbone',
'marionette',
'bootstrap',
'templates',
],
function (
_,
Backbone,
Marionette,
Bootstrap,
templates
) {
'use strict';
return Marionette.ItemView.extend({
template: JST['editPoiLayerColumn.html'],
behaviors: {
'l20n': {},
'column': {},
},
ui: {
'column': '#edit_poi_layer_column',
'layerName': '#layer_name',
'layerDescription': '#layer_description',
'layerOverpassRequest': '#layer_overpass_request',
'layerPopupContent': '#layer_popup_content',
'editMarkerButton': '.edit_marker_btn',
},
events: {
'click @ui.editMarkerButton': 'onClickEditMarker',
'submit': 'onSubmit',
'reset': 'onReset',
},
templateHelpers: function () {
return {
'markerIcon': this._radio.reqres.request('poiLayerHtmlIcon', this.model),
};
},
initialize: function () {
var self = this;
this._radio = Backbone.Wreqr.radio.channel('global');
this._oldModel = this.model.clone();
},
open: function () {
this.triggerMethod('open');
},
close: function () {
this.triggerMethod('close');
},
onClickEditMarker: function () {
this._radio.commands.execute( 'modal:showEditPoiMarker', this.model.get('_id') );
},
onSubmit: function (e) {
e.preventDefault();
var self = this;
this.model.set('name', this.ui.layerName.val());
this.model.set('description', this.ui.layerDescription.val());
this.model.set('overpassRequest', this.ui.layerOverpassRequest.val());
this.model.set('popupContent', this.ui.layerPopupContent.val());
if ( !this.model.get('_id') ) {
this._radio.reqres.request('poiLayers').add( this.model );
}
this.model.save({}, {
'success': function () {
self._oldModel = self.model.clone();
self.close();
},
'error': function () {
// FIXME
console.error('nok');
},
});
},
onReset: function () {
this.model.set( this._oldModel.toJSON() );
this.ui.column.one('transitionend', this.render);
this.close();
},
});
});
| JavaScript | 0 | @@ -524,24 +524,48 @@
_content',%0A%0A
+%09%09%09'marker': '.marker',%0A
%09%09%09'editMark
@@ -1002,24 +1002,82 @@
del.clone();
+%0A%0A%09%09%09this.model.on('change', this.updateMarkerIcon, this);
%0A%09%09%7D,%0A%0A%09%09ope
@@ -1189,24 +1189,209 @@
se');%0A%09%09%7D,%0A%0A
+%09%09updateMarkerIcon: function () %7B%0A%0A%09%09%09var html = this._radio.reqres.request('poiLayerHtmlIcon', this.model);%0A%0A%09%09%09this.ui.marker.replaceWith( html );%0A%09%09%09%0A%09%09%09this.bindUIElements();%0A%09%09%7D,%0A%0A
%09%09onClickEdi
|
26e37c35f797b376bcd9f2eb5c61e58ec4db265c | move back to lodash keys | packages/substyle/src/coerceSelection.js | packages/substyle/src/coerceSelection.js | // @flow
import type { KeysT } from './types'
const coerceSelection = (select?: KeysT): Array<string> => {
if (!select) {
return []
} else if (typeof select === 'string') {
return [select]
} else if (!Array.isArray(select)) {
const objSelect: { [string]: boolean } = select // workaround for https://github.com/facebook/flow/issues/5781
return Object.keys(select).reduce(
(acc, key: string) => acc.concat(objSelect[key] ? [key] : []),
[]
)
}
return select
}
export default coerceSelection
| JavaScript | 0.000001 | @@ -2,16 +2,46 @@
/ @flow%0A
+import %7B keys %7D from 'lodash'%0A
import t
@@ -394,15 +394,8 @@
urn
-Object.
keys
|
055052725296d9edb43872fd0bd718117cafe277 | fix compilation | dist/http-root/dashboard.js | dist/http-root/dashboard.js |
function switchVersion(node,link)
{
alert('switching node ' + node + ' to version ' + document.getElementById(node+'_newVersion').value);
window.location = link + document.getElementById(node+'_newVersion').value;
}
function commandNode(node, command, link)
{
alert('sending command \'' + command + '\' to node ' + node);
window.location = link;
}
function switchVersionToCheckedItems()
{
var dateRE = /^checkbox_/;
var dates=[],els=document.getElementsByTagName('*');
for (var i=els.length;i--;) if (dateRE.test(els[i].id]) dates.push(els[i]);
var length = arr.length,
var nodes = "";
for (var i = 0; i < length; i++) {
arr[i].checked;
nodes += arr[i].id;
}
alert('switching nodes ' + nodes);
window.location = "/switchVersionAll?ndoes=" + nodes;
}
| JavaScript | 0.000001 | @@ -424,21 +424,19 @@
/;%0A%09var
-dates
+arr
=%5B%5D,els=
@@ -532,13 +532,11 @@
d%5D)
-dates
+arr
.pus
@@ -570,17 +570,17 @@
r.length
-,
+;
%0A%09var no
|
0ba04703202c5468b0a0b2030e4151067598e639 | Fix issue with successive clicks on date breaking multi-selection | modules/gm.datepickerMultiSelect.js | modules/gm.datepickerMultiSelect.js | /*
The MIT License (MIT)
Copyright (c) 2014 Gregory McGee
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
angular.module('gm.datepickerMultiSelect', ['ui.bootstrap'])
.config(function($provide) {
$provide.decorator('daypickerDirective', function($delegate) {
var directive = $delegate[0];
/* Override compile */
var link = directive.link;
directive.compile = function() {
return function(scope, element, attrs, ctrl) {
link.apply(this, arguments);
var selectedDates = [];
/* Called when multiSelect model is updated */
scope.$on('update', function(event, newDates) {
selectedDates = newDates;
});
/* Fires when date is selected or when month is changed */
scope.$parent.$watch('activeDateId', function() {
angular.forEach(scope.rows, function(row) {
angular.forEach(row, function(day) {
day.selected = selectedDates.indexOf(day.date.setHours(0, 0, 0, 0)) > -1
});
});
});
}
}
return $delegate;
});
})
.directive('multiSelect', function() {
return {
require: ['datepicker', 'ngModel'],
link: function(scope, elem, attrs, ctrls) {
var selectedDates = scope.$eval(attrs.multiSelect);
scope.$watchCollection(attrs.multiSelect, function(newVal) {
scope.$broadcast('update', selectedDates);
});
scope.$watch(attrs.ngModel, function(newVal) {
if(!newVal) return;
var dateVal = newVal.getTime();
if(selectedDates.indexOf(dateVal) < 0) {
selectedDates.push(dateVal);
} else {
selectedDates.splice(selectedDates.indexOf(dateVal), 1);
}
});
}
}
});
| JavaScript | 0.000001 | @@ -1485,16 +1485,44 @@
s = %5B%5D;%0A
+ var alreadyUpdated;%0A
@@ -1665,16 +1665,36 @@
wDates;%0A
+ update();%0A
@@ -1716,16 +1716,28 @@
/*
+*%0A *
Fires w
@@ -1785,65 +1785,329 @@
nged
- */%0A scope.$parent.$watch('activeDateId', function
+.%0A * Fires after multiSelect model updates, so check to%0A * see if update was already called this cycle.%0A **/%0A scope.$parent.$watch('activeDateId', function() %7B%0A if(!alreadyUpdated)%0A update();%0A alreadyUpdated = false;%0A %7D);%0A %0A function update
() %7B
@@ -2335,19 +2335,50 @@
-%7D);
+ alreadyUpdated = true;%0A %7D
%0A%09%09%09%7D%0A%09%09
@@ -2782,24 +2782,36 @@
n(newVal
-) %7B%0A%09%09%09%09
+, oldVal) %7B%0A
if(!newV
|
d8bcbfc68d8ec4b24699b8ad9ec030533347ed99 | fix validation errors on send | packages/local-sync/src/local-api/routes/send.js | packages/local-sync/src/local-api/routes/send.js | const Joi = require('joi');
const Utils = require('../../shared/utils');
const {createSyncbackRequest} = require('../route-helpers');
const recipient = Joi.object().keys({
name: Joi.string().required(),
email: Joi.string().email().required(),
// Rest are optional
account_id: Joi.string(),
client_id: Joi.string(),
id: Joi.string(),
thirdPartyData: Joi.object(),
server_id: Joi.string(),
object: Joi.string(),
});
const recipientList = Joi.array().items(recipient);
module.exports = (server) => {
server.route({
method: 'POST',
path: '/send',
config: {
validate: {
payload: {
to: recipientList,
cc: recipientList,
bcc: recipientList,
from: recipientList.length(1).required(),
reply_to: recipientList.min(0).max(1),
subject: Joi.string().required(),
body: Joi.string().required(),
thread_id: Joi.string(),
reply_to_message_id: Joi.string(),
client_id: Joi.string().required(),
account_id: Joi.string(),
id: Joi.string(),
object: Joi.string().equal('draft'),
metadata: Joi.array().items(Joi.object()),
date: Joi.number(),
files: Joi.array().items(Joi.string()),
file_ids: Joi.array(),
uploads: Joi.array(),
events: Joi.array(),
pristine: Joi.boolean(),
categories: Joi.array().items(Joi.string()),
draft: Joi.boolean(),
},
},
},
async handler(request, reply) {
createSyncbackRequest(request, reply, {
type: "SendMessage",
props: {
messagePayload: request.payload,
},
syncbackImmediately: true,
})
},
});
// Initiates a multi-send session by creating a new multi-send draft.
server.route({
method: 'POST',
path: '/send-multiple',
config: {
validate: {
payload: {
message: {
to: recipientList,
cc: recipientList,
bcc: recipientList,
from: recipientList.length(1).required(),
reply_to: recipientList.min(0).max(1),
subject: Joi.string().required(),
body: Joi.string().required(),
thread_id: Joi.string(),
reply_to_message_id: Joi.string(),
client_id: Joi.string().required(),
account_id: Joi.string(),
id: Joi.string(),
object: Joi.string().equal('draft'),
metadata: Joi.array().items(Joi.object()),
date: Joi.number(),
files: Joi.array().items(Joi.string()),
file_ids: Joi.array(),
uploads: Joi.array(),
events: Joi.array(),
pristine: Joi.boolean(),
categories: Joi.array().items(Joi.string()),
draft: Joi.boolean(),
},
uses_open_tracking: Joi.boolean(),
uses_link_tracking: Joi.boolean(),
},
},
},
async handler(request, reply) {
createSyncbackRequest(request, reply, {
type: "SendMessagePerRecipient",
props: {
messagePayload: request.payload.message,
usesOpenTracking: request.payload.uses_open_tracking,
usesLinkTracking: request.payload.uses_link_tracking,
},
syncbackImmediately: true,
})
},
});
// Closes out a multi-send session by marking the sending draft as sent
// and moving it to the user's Sent folder.
server.route({
method: 'DELETE',
path: '/send-multiple/{messageId}',
config: {
validate: {
params: {
messageId: Joi.string(),
},
},
},
async handler(request, reply) {
const {messageId} = request.params;
if (!Utils.isValidId(messageId)) {
reply.badRequest(`messageId is not a base-36 integer`)
return
}
createSyncbackRequest(request, reply, {
type: "ReconcileSentMessagesPerRecipient",
props: { messageId },
syncbackImmediately: true,
})
},
});
};
| JavaScript | 0 | @@ -918,32 +918,44 @@
id: Joi.string()
+.allow(null)
,%0A repl
@@ -975,32 +975,44 @@
id: Joi.string()
+.allow(null)
,%0A clie
@@ -2296,32 +2296,44 @@
id: Joi.string()
+.allow(null)
,%0A re
@@ -2355,32 +2355,44 @@
id: Joi.string()
+.allow(null)
,%0A cl
|
60b4515413250f84adebd256956317413c20b28d | Remove xhr-specific .abort() logic because it's fairly useless | src/model/fancy/ajax.js | src/model/fancy/ajax.js | /**
* model/fancy/ajax.js
*/
models.ajax = asyncModel.extend({
state: function asyncState(dataCallback) {
var self = this;
var myXhr;
function complete() {
removeInFlight(self);
if (myXhr) {
myXhr = null;
}
self.onComplete();
}
var url = _.isString(self.url) ? self.url : self.url();
if (url == null) {
dataCallback(null);
} else {
/**
* If a defined URL function returns null, it will prevent fetching.
* This can be used e.g. to prevent loading until all required
* parameters are set.
**/
self.abortPrevious();
self.fetchedUrl = url;
self.preFetch();
addInFlight(self);
var onData = function asyncStateOnData(str) {
/**
* dataCallback returns true if this update was accepted (i.e.
* is of the current async update generation). So only fire
* the postFetch callback, etc, when the update actually sticks.
*/
if (dataCallback(self.parse(str))) {
self.postFetch();
if (TBONE_DEBUG) {
log(INFO, self, 'updated', self.attributes);
}
}
};
self.ajax({
url: url,
type: 'GET',
dataType: self.dataType,
success: onData,
error: function error(xhr) {
onData(xhr && xhr.responseText);
},
complete: complete,
beforeSend: function beforeSend(xhr) {
myXhr = xhr;
},
});
}
return {
onAbort: function onAbort() {
// If we have an active XHR in flight, we should abort
// it because we don't want that anymore.
if (TBONE_DEBUG) {
log(WARN, self, 'abort',
'aborting obsolete ajax request. old url: <%=oldurl%>', {
oldurl: self.fetchedUrl
});
}
if (myXhr) {
myXhr.abort();
}
complete();
}
};
},
parse: _.identity,
/**
* By default, async models will use $.ajax to fetch data; override this
* with something else if desired.
*/
ajax: function ajax() {
return $.ajax.apply($, arguments);
},
preFetch: function preFetch() {
this.unset();
},
postFetch: noop,
onComplete: noop,
sleepEnabled: true,
dataType: 'json'
});
| JavaScript | 0.000105 | @@ -136,27 +136,8 @@
is;%0A
- var myXhr;%0A
@@ -200,77 +200,8 @@
f);%0A
- if (myXhr) %7B%0A myXhr = null;%0A %7D%0A
@@ -1630,115 +1630,8 @@
te,%0A
- beforeSend: function beforeSend(xhr) %7B%0A myXhr = xhr;%0A %7D,%0A
@@ -2096,90 +2096,8 @@
%7D%0A
- if (myXhr) %7B%0A myXhr.abort();%0A %7D%0A
|
8ec975d9ca2cf218bf2c2eddfe6ed4d8718f45dc | Use utility.js | lexos/static/js/scripts_rwanalysis.js | lexos/static/js/scripts_rwanalysis.js | /**
* Show the milestone input when the milestone check box is checked.
*/
function updateMSopt () {
if ($('#rollinghasmilestone').is(':checked')) {
$('#rollingmilestoneopt').show()
} else {
$('#rollingmilestoneopt').hide()
}
}
/**
* the function to convert the from into json
* @returns {{string: string}} - the from converted to json
*/
function jsonifyForm () {
const form = {}
$.each($('form').serializeArray(), function (i, field) {
form[field.name] = field.value || ''
})
return form
}
/**
* the function to run the error modal
* @param htmlMsg {string} - the message to display, you can put html in it
*/
function runModal (htmlMsg) {
$('#error-modal-message').html(htmlMsg)
$('#error-modal').modal()
}
/**
* The function to create the ajax object
* @param form {object.<string, string>} the form converted into a json
* @returns {jquery.Ajax} - the jquery ajax object (a deferred object)
*/
function sendAjaxRequest (form) {
return $.ajax({
type: 'POST',
url: '/rollingWindowGraph',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(form)
})
}
/**
* the function to submit form via ajax in dendrogram
*/
function submitForm () {
// show loading icon
$('#status-visualize').css({'visibility': 'visible'})
// convert form into an object map string to string
const form = jsonifyForm()
// send the ajax request
sendAjaxRequest(form)
.done(
function (response) {
$('#rwa-result-graph').html(response)
})
.fail(
function (jqXHR, textStatus, errorThrown) {
console.log('textStatus: ' + textStatus)
console.log('errorThrown: ' + errorThrown)
runModal('error encountered while plotting the rolling window analysis.')
})
.always(
function () {
$('#status-visualize').css({'visibility': 'hidden'})
})
}
function getSubmissionError () {
// get the number of active document
const numActiveDoc = Number($('#num_active_files').val())
// if there is no active document
if (numActiveDoc === 0)
return 'Please select a document to analyze.'
// no search pattern and window size
else if ($('#rollingwindowsize').val() === '' || $('#rollingsearchword').val() === '')
return 'Please fill out the \'Search Pattern(s)\' and \'Size of Rolling Window\' fields.'
// cannot search term using window of chars
else if ($('#inputword').prop('checked') && $('#windowletter').prop('checked'))
return 'You cannot use tokens for search terms when analyzing a window of characters. ' +
'The window setting has been changed to a window of tokens.'
// no error found
else
return null
}
/* document.ready() Functions */
$(function () {
// Call update milestone on page load
updateMSopt()
// Bind the function to the checkbox
$('#rollinghasmilestone').click(updateMSopt)
$('#getgraph').click(function () {
/* Validation */
const errorString = getSubmissionError()
if (errorString === null) // no error found
submitForm()
else
runModal(errorString)
})
/* On-Click Validation */
$('#radiowindowletter').click(function () {
if ($('#inputword').prop('checked')) {
$('#windowword').click()
const msg = 'You cannot use a window of characters when analyzing a token.' +
' The setting has been changed to a window of tokens.'
$('#error-modal-message').html(msg)
$('#error-modal').modal()
}
})
/* Other UI functionality */
// Fixes bug where you cannot click second text box in firefox
$('#rollingsearchwordopt, #rollingsearchword').hover(function () {
$(this).focus()
})
// Sets the value of the hidden input
$('.minifilepreview').click(function () {
$('#filetorollinganalyze').val($(this).prop('id'))
})
// Shows the second textbox when rolling ratio gets clicked
$('#radioratio').click(function () {
$('.rollingsearchwordoptdiv').removeClass('hidden')
})
// Removes the second textbox when rolling ratio is not selected
$('#radioaverage').click(function () {
$('.rollingsearchwordoptdiv').addClass('hidden')
})
})
| JavaScript | 0.000003 | @@ -1,12 +1,53 @@
+import * as utility from './utility.js'%0A%0A
/**%0A * Show
@@ -283,902 +283,8 @@
%0A%7D%0A%0A
-/**%0A * the function to convert the from into json%0A * @returns %7B%7Bstring: string%7D%7D - the from converted to json%0A */%0Afunction jsonifyForm () %7B%0A const form = %7B%7D%0A $.each($('form').serializeArray(), function (i, field) %7B%0A form%5Bfield.name%5D = field.value %7C%7C ''%0A %7D)%0A return form%0A%7D%0A%0A/**%0A * the function to run the error modal%0A * @param htmlMsg %7Bstring%7D - the message to display, you can put html in it%0A */%0Afunction runModal (htmlMsg) %7B%0A $('#error-modal-message').html(htmlMsg)%0A $('#error-modal').modal()%0A%7D%0A%0A/**%0A * The function to create the ajax object%0A * @param form %7Bobject.%3Cstring, string%3E%7D the form converted into a json%0A * @returns %7Bjquery.Ajax%7D - the jquery ajax object (a deferred object)%0A */%0Afunction sendAjaxRequest (form) %7B%0A%0A return $.ajax(%7B%0A type: 'POST',%0A url: '/rollingWindowGraph',%0A contentType: 'application/json; charset=utf-8',%0A data: JSON.stringify(form)%0A %7D)%0A%0A%7D%0A%0A
/**%0A
@@ -350,26 +350,37 @@
unction
-submitForm
+generateRollingWindow
() %7B%0A
@@ -526,16 +526,24 @@
form =
+utility.
jsonifyF
@@ -578,16 +578,24 @@
quest%0A
+utility.
sendAjax
@@ -602,16 +602,39 @@
Request(
+'/rollingWindowGraph',
form)%0A
@@ -890,24 +890,32 @@
wn)%0A
+utility.
runModal('er
@@ -912,17 +912,17 @@
nModal('
-e
+E
rror enc
@@ -1942,17 +1942,16 @@
on () %7B%0A
-%0A
// Cal
@@ -2247,18 +2247,29 @@
-submitForm
+generateRollingWindow
()%0A
@@ -2282,16 +2282,24 @@
e%0A
+utility.
runModal
@@ -2484,17 +2484,17 @@
t msg =
-'
+%60
You cann
@@ -2546,19 +2546,17 @@
a token.
-' +
+
%0A
@@ -2556,17 +2556,26 @@
-'
+
The set
@@ -2622,82 +2622,36 @@
ens.
-'
+%60
%0A
-$('#error-modal-message').html(msg)%0A $('#error-modal').modal(
+utility.runModal(msg
)%0A
@@ -2691,17 +2691,16 @@
lity */%0A
-%0A
// Fix
|
7b2ce4258d9cca635f19a12a6babede915229356 | Fix flow error | packages/react-accessible-tooltip/src/Tooltip.js | packages/react-accessible-tooltip/src/Tooltip.js | // @flow
import React, { Component } from 'react';
import type { ElementProps, ComponentType } from 'react';
export type LabelProps = {
labelAttributes: {
role: 'tooltip',
tabIndex: '0',
'aria-describedby': string,
onFocus: () => void,
},
isHidden: boolean,
};
export type OverlayProps = {
overlayAttributes: {
tabIndex: '-1',
id: string,
'aria-hidden': boolean,
},
isHidden: boolean,
};
export type TooltipState = {
isFocused: boolean,
isHovered: boolean,
};
export type TooltipProps = ElementProps<'div'> & {
label: ComponentType<LabelProps>,
overlay: ComponentType<OverlayProps>,
containerRef?: HTMLDivElement => void,
};
let counter = 0;
class Tooltip extends Component<TooltipProps, TooltipState> {
constructor(props: TooltipProps) {
super(props);
this.identifier = `react-accessible-tooltip-${counter}`;
counter += 1;
}
state = {
isFocused: false,
isHovered: false,
};
componentDidMount() {
document.addEventListener('touchstart', this.handleTouch);
}
componentWillUnmount() {
document.removeEventListener('touchstart', this.handleTouch);
}
onFocus = () => {
this.setState({ isFocused: true });
};
onBlur = ({
relatedTarget,
currentTarget,
}: SyntheticFocusEvent<HTMLElement>) => {
// relatedTarget is better for React testability etc, but activeElement works as an IE11 fallback:
const newTarget = relatedTarget || document.activeElement;
// The idea of this logic is that we should only close the tooltip if focus has shifted from the tooltip AND all of its descendents.
if (!(newTarget && newTarget instanceof HTMLElement)) {
this.setState({ isFocused: false });
} else if (!currentTarget.contains(newTarget)) {
this.setState({ isFocused: false });
}
};
onMouseEnter = () => {
this.setState({ isHovered: true });
};
onMouseLeave = () => {
this.setState({ isHovered: false });
};
// This handles the support for touch devices that do not trigger blur on 'touch-away'.
handleTouch = ({ target }: Event) => {
const { activeElement } = document;
if (
activeElement instanceof Element &&
target instanceof Element &&
this.container instanceof Element &&
!this.container.contains(target) && // touch target not a tooltip descendent
this.state.isFocused // prevent redundant state change
) {
this.setState({ isFocused: false });
activeElement.blur();
}
};
container: ?HTMLDivElement;
identifier: string;
render() {
const {
label: Label,
overlay: Overlay,
containerRef,
...rest
} = this.props;
const { isFocused, isHovered } = this.state;
const isHidden = !(isFocused || isHovered);
const labelProps: LabelProps = {
labelAttributes: {
role: 'tooltip',
tabIndex: '0',
'aria-describedby': this.identifier,
onFocus: this.onFocus,
},
isHidden,
};
const overlayProps: OverlayProps = {
overlayAttributes: {
tabIndex: '-1',
id: this.identifier,
'aria-hidden': isHidden.toString(),
},
isHidden,
};
return (
<div
{...rest}
onBlur={this.onBlur}
ref={ref => {
this.container = ref;
if (containerRef) {
containerRef(ref);
}
}}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
<Label {...labelProps} />
<Overlay {...overlayProps} />
</div>
);
}
}
export default Tooltip;
| JavaScript | 0.000003 | @@ -422,23 +422,22 @@
idden':
-boolean
+string
,%0A %7D,
|
0fd0abe7dbcabbd5089b1353f4c0cedee32692ab | fix typo | src/renderers/webgl/WebGLRenderStates.js | src/renderers/webgl/WebGLRenderStates.js | /**
* @author Mugen87 / https://github.com/Mugen87
*/
import { WebGLLights } from './WebGLLights.js';
function WebGLRenderState() {
var lights = new WebGLLights();
var lightsArray = [];
var shadowsArray = [];
var spritesArray = [];
function init() {
lightsArray.length = 0;
shadowsArray.length = 0;
spritesArray.length = 0;
}
function pushLight( light ) {
lightsArray.push( light );
}
function pushShadow( shadowLight ) {
shadowsArray.push( shadowLight );
}
function pushSprite( shadowLight ) {
spritesArray.push( shadowLight );
}
function setupLights( camera ) {
lights.setup( lightsArray, shadowsArray, camera );
}
var state = {
lightsArray: lightsArray,
shadowsArray: shadowsArray,
spritesArray: spritesArray,
lights: lights
};
return {
init: init,
state: state,
setupLights: setupLights,
pushLight: pushLight,
pushShadow: pushShadow,
pushSprite: pushSprite
};
}
function WebGLRenderStates() {
var renderStates = {};
function get( scene, camera ) {
var hash = scene.id + ',' + camera.id;
var renderState = renderStates[ hash ];
if ( renderState === undefined ) {
renderState = new WebGLRenderState();
renderStates[ hash ] = renderState;
}
return renderState;
}
function dispose() {
renderStates = {};
}
return {
get: get,
dispose: dispose
};
}
export { WebGLRenderStates };
| JavaScript | 0.999991 | @@ -510,26 +510,21 @@
prite( s
-hadowLight
+prite
) %7B%0A%0A%09%09
@@ -539,34 +539,29 @@
rray.push( s
-hadowLight
+prite
);%0A%0A%09%7D%0A%0A%09fu
|
c650b20ebb8e20f01a51dfed774c505dfe0efa4c | Add a link to performance tests on JSPerf for replacer() | lib/natural/util/utils.js | lib/natural/util/utils.js | /*
Copyright (c) 2012, Guillaume Marty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* Generate a replacing function given a table of patterns. Inspired by:
* http://code.google.com/p/jslibs/wiki/JavascriptTips#String_converter
* The order of elements is significant. Longer elements should be listed first.
*
* @param {Object.<string, string>} translationTable The translation table of key value.
* @return {function(string): string} A translating function.
*/
function replacer(translationTable) {
/**
* An array of translationTable keys.
* @type {Array.<string>}
*/
var pattern = [];
/**
* The regular expression doing the replacement job.
* @type {RegExp}
*/
var regExp;
/**
* Used to iterate over translationTable.
* @type {string}
*/
var key;
for (key in translationTable) {
// Escaping regexp special chars.
key = key.replace(/(\^|\$|\*|\+|\?|\.|\(|\)|\[|\]|\{|\}|\||\\|\/)/g, '\\\$1');
pattern.push(key);
}
regExp = new RegExp(pattern.join('|'), 'g');
/**
* @param {string} str Input string.
* @return {string} The string replaced.
*/
return function(str) {
return str.replace(regExp, function(str) {
return translationTable[str];
});
};
}
/**
* Exchanges all keys with their associated values in an object.
*
* @param {Object.<string, string>} obj An object of strings.
* @return {Object.<string, string>} An object of strings.
*/
function flip(obj) {
var newObj = Object.create(null),
key;
for (key in obj) {
newObj[obj[key]] = key;
}
return newObj;
}
/**
* Merge several objects. Properties from earlier objects are overwritten by
* laters's in case of conflict.
*
* @param {...Object.<string, string>} var_args One or more objects of strings.
* @return {!Object.<string, string>} An object of strings.
*/
function merge(var_args) {
var args = [].slice.call(arguments),
newObj = Object.create(null),
id = 0, key;
while (args[id]) {
for (key in args[id]) {
newObj[key] = args[id][key];
}
id++;
}
return newObj;
}
exports.replacer = replacer;
exports.flip = flip;
exports.merge = merge;
| JavaScript | 0 | @@ -1308,16 +1308,74 @@
first.%0A
+ * @see Speed test http://jsperf.com/build-a-regexp-table%0A
*%0A * @p
|
3b3fb64d7e0b8f725e2edc412063a96ec23cfec9 | update copy as per Gail's email | packages/ui/src/components/Tracking/CookieBox.js | packages/ui/src/components/Tracking/CookieBox.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import styles from '../css/cookie-box.module.css';
import controls from '../../css/controls.module.css';
// Copy/pasted from pages/PreferencesPage.js.
// TODO: Abstract this is we see this pattern any more times.
const PreferenceCheckbox = ({ children, checked, name, onChange }) => (
<label className={controls.preferenceWrapper}>
<input
className={controls.preferenceInput}
type="checkbox"
name={name}
onChange={onChange}
checked={checked}
/>
<span className={controls.preference}>{children}</span>
</label>
);
const noop = () => {};
class CookieBox extends React.Component {
static propTypes = {
aaAccepted: PropTypes.bool,
gaAccepted: PropTypes.bool,
onSubmit: PropTypes.func,
};
static defaultProps = {
onSubmit: noop,
};
constructor(props, context) {
super(props, context);
this.state = {
aaAccepted: props.aaAccepted || false,
gaAccepted: props.gaAccepted || false,
};
}
handleSubmit = evt => {
evt.preventDefault();
this.props.onSubmit({
aaAccepted: this.state.aaAccepted,
gaAccepted: this.state.gaAccepted,
});
};
render() {
if (!this.props.open) {
return null;
}
return (
<div>
<div className={styles.popupBody}>
<p>
Opt in to a Google Analytics cookie. This will help us improve your experience with the
site, so you can find a loo quicker. By opting in you would be sharing your data with Public
Convenience Ltd and tech partners Neontribe as well as Google itself.
</p>
<form onSubmit={this.handleSubmit}>
<PreferenceCheckbox
onChange={evt =>
this.setState({ gaAccepted: evt.target.checked })
}
checked={this.state.gaAccepted}
>
<span>Opt in to Google Analytics</span>
</PreferenceCheckbox>
<p>
You can also opt into additional cookies to support the
project indirectly. By opting in to additional analytics cookies
we can share your data with Unilever via Google and Adobe Analytics,
and benefit from Unilever's continued sponsorship. This opting in is entirely up to you.
</p>
<PreferenceCheckbox
onChange={evt =>
this.setState({ aaAccepted: evt.target.checked })
}
checked={this.state.aaAccepted}
>
<span>Opt into Adobe Analytics</span>
</PreferenceCheckbox>
<p>
For more detailed information about the cookies we use, see our{' '}
<Link to="/privacy">Cookies page.</Link>
</p>
<div>
<button className={controls.btn}>Save and close</button>
</div>
</form>
</div>
</div>
);
}
}
export default CookieBox;
| JavaScript | 0 | @@ -2101,16 +2101,17 @@
o opt in
+
to addit
@@ -2135,24 +2135,24 @@
support the%0A
-
@@ -2374,45 +2374,8 @@
ip.
-This opting in is entirely up to you.
%0A
@@ -2620,16 +2620,17 @@
n%3EOpt in
+
to Adobe
@@ -2690,32 +2690,32 @@
%3Cp%3E%0A
-
Fo
@@ -2711,16 +2711,49 @@
+ Opting in is entirely up to you.
For mor
|
257f54a79a6efa1137b96ebbb9944fae69f57604 | make sure LIMIT is set | fast-future.js | fast-future.js | var LIMIT = process.maxTickDepth / 2
, factory = function () {
var count = 0
return function (callback) {
if (count >= LIMIT){
global.setImmediate(callback)
count = 0
} else
process.nextTick(callback)
count++
}
}
module.exports = global.setImmediate ? factory : function () { return process.nextTick }
| JavaScript | 0.00003 | @@ -29,16 +29,24 @@
epth / 2
+ %7C%7C 1000
%0A , fac
|
4e38470801b80e54be0732d0b292a6c37aa7e37d | Remove assert import | sperm-whale/database.js | sperm-whale/database.js | const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
console.log(`Connected to MongoDB @${url}`);
const buildings = db.collection('buildings');
const courses = db.collection('courses');
// Courses
module.exports.getAllCourses = function(cb) {
courses.find({}).toArray((err, r) => returnRes(err, r, cb));
};
module.exports.getCourse = function(subjectCode, courseNumber, cb) {
const abbr = `${subjectCode} ${courseNumber}`;
courses.findOne(
{abbr: abbr},
(err, r) => returnRes(err, r, cb)
);
};
// Buildings
module.exports.getAllBuildings = function(cb) {
buildings.find({}).toArray((err, r) => returnRes(err, r, cb));
};
module.exports.getBuilding = function(buildingCode, cb) {
buildings.findOne(
{abbr: buildingCode},
(err, r) => returnRes(err, r, cb)
);
};
function returnRes(err, r, cb) {
if (err) {
cb(err);
} else {
cb(null, r);
}
}
});
| JavaScript | 0.000001 | @@ -48,42 +48,8 @@
ent;
-%0Aconst assert = require('assert');
%0A%0Aco
|
51eb67b717a7ba716bc34f81bf73ae671b37b53c | Update QuadNode.js | src/modules/QuadNode.js | src/modules/QuadNode.js | 'use strict';
/*
* Fast and easy Quad-Tree implementation written by Barbosik.
* Useful for quick object search in the area specified with bounds.
*
* Copyright (c) 2016 Barbosik https://github.com/Barbosik
* License: Apache License, Version 2.0
*/
function QuadNode(bound) {
var halfWidth = (bound.maxx - bound.minx) / 2;
var halfHeight = (bound.maxy - bound.miny) / 2;
this.bound = {
minx: bound.minx,
miny: bound.miny,
maxx: bound.maxx,
maxy: bound.maxy,
halfWidth: halfWidth,
halfHeight: halfHeight,
cx: bound.minx + halfWidth,
cy: bound.miny + halfHeight
};
this.childNodes = [];
this.items = [];
}
module.exports = QuadNode;
QuadNode.prototype.insert = function (item) {
if (this.childNodes.length != 0) {
var quad = this.getQuad(item.bound);
if (quad != -1) {
this.childNodes[quad].insert(item);
return;
}
}
this.items.push(item);
item._quadNode = this; // attached field, used for quick search quad node by item
// check if rebalance needed
if (this.childNodes.length != 0 || this.items.length < 64)
return;
// split and rebalance current node
if (this.childNodes.length == 0) {
// split into 4 subnodes (top, left, bottom, right)
var w = this.bound.halfWidth;
var h = this.bound.halfHeight;
var my = this.bound.miny;
var mx = this.bound.minx;
var mh = my + h;
var mw = mx + w;
var b0 = { minx: mw, miny: my, maxx: mw + w, maxy: my + h };
var b1 = { minx: mx, miny: my, maxx: mx + w, maxy: my + h };
var b2 = { minx: mx, miny: mh, maxx: mx + w, maxy: mh + h };
var b3 = { minx: mw, miny: mh, maxx: mw + w, maxy: mh + h };
this.childNodes.push(new QuadNode(b0));
this.childNodes.push(new QuadNode(b1));
this.childNodes.push(new QuadNode(b2));
this.childNodes.push(new QuadNode(b3));
}
// rebalance
for (var i = 0; i < this.items.length; ) {
var qitem = this.items[i];
var quad = this.getQuad(qitem.bound);
if (quad != -1) {
this.items.splice(i, 1);
qitem._quadNode = null;
this.childNodes[quad].insert(qitem);
}
else i++;
}
};
QuadNode.prototype.remove = function (item) {
if (item._quadNode != this) {
item._quadNode.remove(item);
return;
}
var index = this.items.indexOf(item);
this.items.splice(index, 1);
item._quadNode = null;
};
QuadNode.prototype.find = function (bound, callback) {
if (this.childNodes.length != 0) {
var quad = this.getQuad(bound);
if (quad != -1) {
this.childNodes[quad].find(bound, callback);
} else {
for (var i = 0; i < this.childNodes.length; i++) {
var node = this.childNodes[i];
if (!intersects(node.bound, bound))
node.find(bound, callback);
}
}
}
for (var i = 0; i < this.items.length; i++) {
var item = this.items[i];
if (!intersects(item.bound, bound))
callback(item);
}
};
// Returns quadrant for the bound.
// Returns -1 if bound cannot completely fit within a child node
QuadNode.prototype.getQuad = function (bound) {
var isTop = (bound.miny && bound.maxy) < this.bound.cy;
var isLeft = (bound.minx && bound.maxx) < this.bound.cx;
if (isLeft) {
if (isTop) return 1;
else if (bound.miny > this.bound.cy) return 2; // isBottom
}
else if (bound.minx > this.bound.cx) // isRight
{
if (isTop) return 0;
else if (bound.miny > this.bound.cy) return 3; // isBottom
}
return -1; // cannot fit (too large size)
};
function intersects(a, b) {
return b.minx >= a.maxx ||
b.maxx <= a.minx ||
b.miny >= a.maxy ||
b.maxy <= a.miny;
};
| JavaScript | 0 | @@ -276,28 +276,29 @@
ound) %7B%0A
-var
+this.
halfWidth =
@@ -332,20 +332,21 @@
2;%0A
-var
+this.
halfHeig
@@ -514,70 +514,8 @@
xy,%0A
- halfWidth: halfWidth,%0A halfHeight: halfHeight,%0A
@@ -535,16 +535,21 @@
.minx +
+this.
halfWidt
@@ -576,16 +576,21 @@
.miny +
+this.
halfHeig
@@ -822,34 +822,32 @@
if (quad != -1)
- %7B
%0A thi
@@ -835,32 +835,39 @@
-1)%0A
+return
this.childNodes%5B
@@ -890,38 +890,8 @@
m);%0A
- return;%0A %7D%0A
@@ -953,24 +953,8 @@
//
- attached field,
use
@@ -1263,30 +1263,24 @@
ar w = this.
-bound.
halfWidth;%0A
@@ -1299,22 +1299,16 @@
= this.
-bound.
halfHeig
@@ -1907,335 +1907,8 @@
%7D%0A
- // rebalance%0A for (var i = 0; i %3C this.items.length; ) %7B%0A var qitem = this.items%5Bi%5D;%0A var quad = this.getQuad(qitem.bound);%0A if (quad != -1) %7B%0A this.items.splice(i, 1);%0A qitem._quadNode = null;%0A this.childNodes%5Bquad%5D.insert(qitem);%0A %7D%0A else i++;%0A %7D%0A
%7D;%0A%0A
@@ -1984,18 +1984,16 @@
!= this)
- %7B
%0A
@@ -1989,24 +1989,31 @@
is)%0A
+return
item._quadNo
@@ -2037,95 +2037,50 @@
- return;%0A %7D%0A var index = this.items.indexOf(item);%0A this.items.splice(index
+this.items.splice(this.items.indexOf(item)
, 1)
@@ -2968,21 +2968,12 @@
-var isLeft =
+if (
(bou
@@ -3014,24 +3014,8 @@
d.cx
-;%0A if (isLeft
) %7B%0A
@@ -3115,20 +3115,16 @@
om%0A %7D
-%0A
else if
@@ -3152,16 +3152,18 @@
ound.cx)
+ %7B
// isRi
@@ -3170,14 +3170,8 @@
ght%0A
- %7B%0A
|
6c79e8148be797415ff92d447f6eacfbd7e97857 | Add support for handling native `event` | src/mousetrap-config.js | src/mousetrap-config.js | import Mousetrap from 'mousetrap';
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
import {Configure} from './configure';
/**
* This class binds and stores the keymap, where the keymap and callback are configurable.
* The default implementation for the callback is to publish an event with the same name to
* the EventAggregator
*/
@inject(Configure, EventAggregator)
export class MousetrapConfig {
_keymap = {};
_callback = null;
constructor(configure, eventAggregator) {
// Load the keymap info from the config
if (typeof configure.get('keymap') === 'object') {
this._keymap = configure.get('keymap');
}
// If a callback has been bound in the config
if (typeof configure.get('callback') === 'function') {
// Use that callback
this._callback = configure.get('callback');
} else {
// Otherwise, use a basic implementation of eventAggregator
this._callback = (eventName) => {
eventAggregator.publish(eventName);
}
}
}
/**
* This method actually binds the config with the mousetrap.js library
*/
bindKeymap() {
let keymap = this._keymap;
// Bind each shortcut
for (let combo in keymap) {
if (keymap.hasOwnProperty(combo)) {
let eventName = keymap[combo];
Mousetrap.bind(combo, () => {
this._callback(eventName);
});
}
}
}
/**
* Allow access to the keymap, externally - maybe someone will want it
* @returns {{}}
*/
get keymap() {
return this._keymap;
}
} | JavaScript | 0 | @@ -1477,16 +1477,22 @@
combo, (
+$event
) =%3E %7B%0A
@@ -1526,32 +1526,40 @@
llback(eventName
+, $event
);%0A
@@ -1763,8 +1763,9 @@
%0A %7D%0A%7D
+%0A
|
c77cf00a60d489aaf3ceb45eb9f08ba7a85d2097 | Clean up figlet font loading for node | figlet-node.js | figlet-node.js | /**
* Figlet JS node.js module
*
* Copyright (c) 2010 Scott González
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://github.com/scottgonzalez/figlet-js
*/
var Figlet = require("./figlet").Figlet;
Figlet.loadFont = function(name, fn) {
require("fs").readFile("./fonts/" + name + ".flf", "utf-8", function(err, contents) {
fn(contents);
});
};
exports.Figlet = Figlet;
| JavaScript | 0 | @@ -208,16 +208,68 @@
js%0A */%0A%0A
+var fs = require(%22fs%22);%0Avar path = require('path');%0A
var Figl
@@ -345,65 +345,139 @@
) %7B%0A
-%09require(%22fs%22).readFile(%22./fonts/%22 + name + %22.flf%22
+%0A%09var fontFileName = name + %22.flf%22;%0A%09%0A%09var filePath = path.resolve(__dirname, %22fonts%22, fontFileName);%0A%0A%09fs.readFile(filePath
, %22utf
--
8%22,
@@ -502,16 +502,99 @@
ents) %7B%0A
+%0A%09%09if (err) %7Bthrow err;%7D%0A%09%09// console.log('figlet-node.loadFont', err, contents);%0A%0A
%09%09fn(con
@@ -627,17 +627,16 @@
iglet = Figlet;%0A
-%0A
|
47dceb6610544a1a5537a864448f5a207c0f04b6 | set object-curly-spacing always | xo.config.js | xo.config.js | module.exports = {
space: true,
rules: {
'@typescript-eslint/prefer-readonly-parameter-types': 'off',
'ava/no-skip-test': 'off',
'ava/no-only-test': 'off'
}
};
| JavaScript | 0.000001 | @@ -163,16 +163,64 @@
': 'off'
+,%0A 'object-curly-spacing': %5B'error','always'%5D
%0A %7D%0A%7D;%0A
|
f022e434384ce86c259a449e30e9efd038954c04 | Fix Denkpause: Accidental .split() with "Eintopf" keyword in menu name | parser/mensen/parsers/parser_bistro_denkpause.js | parser/mensen/parsers/parser_bistro_denkpause.js | var bistroparser = function(mensa){
var parser = require('./parser');
var request = require('request');
// process the html data and find the data we are interested in
request(mensa.url, function(error, response, html) {
// moment library for date conversion
var moment = require("moment");
// cheerio library for html parsing
var cheerio = require('cheerio');
// html element id list for parsing & extracting data
var idList = [ "montag", "dienstag", "mittwoch", "donnerstag", "freitag" ];
// check if request was successfull (html response code 200)
if(!error && response.statusCode === 200) {
var $ = cheerio.load(html, { normalizeWhitespace: true });
var contentElement = $("table.contentpaneopen");
// Preise abfragen
// Ergebnisse in Variable preise:
// preise[0] (Menü 1 Student),
// preise[1] (Menü 1 Sonst.),
// preise[2] (Menü 2 Student),
// preise[3] (Menü 2 Sonst.),
// preise[4] (Eintopf Student),
// preise[5] (Eintopf Sonst.)
var preiseMatch = contentElement.text().match(/Stud\. (\d,\d\d) €\/Bediens?t\.? (\d,\d\d) €\/Gäste (\d,\d\d) €/g);
var preisePartials = [];
var preise = [];
preiseMatch.forEach(function(el, index, array){
var parts = el.match(/Stud\. (\d,\d\d) €\/Bediens?t\.? (\d,\d\d) €\/Gäste (\d,\d\d) €/);
preisePartials.push(parts[1]);
preisePartials.push(parts[3]);
});
preise[0] = preisePartials[0];
preise[1] = preisePartials[1];
preise[2] = preisePartials[0];
preise[3] = preisePartials[1];
preise[4] = preisePartials[2];
preise[5] = preisePartials[3];
//console.log("Preise: ", preisePartials, preise);
// Tägliche Menüs
var weekdayTables = contentElement.text().split(/((Montag|Dienstag|Mittwoch|Donnerstag|Freitag|Samstag) [0-9]+\.[0-9]+\.[0-9]+)/);
// contentElement.text().split() produziert ein Array, welches 3x die Länge
// der Wochentage hat, also 3x 6 Tage = 18 Einträge
// deshalb hier wieder geteilt durch 3
for(var i=1; i<= weekdayTables.length/3 ; i++){
var dateToday = weekdayTables[i*3-2].split(" ").pop(); // Teil nach " "
var menusTodayAll = weekdayTables[i*3];
// III, II, I in absteigender Reihenfolge
var menusToday = menusTodayAll.split(/Menü II|Menü I|Eintopf/)
.filter(function(el){
// leere Elemente rausfiltern
return el.trim().length!=0;
});
// Ergebnis ist ein Array mit 3 oder 4 Einträgen:
// Menü I, II, III, Eintopf (Eintopf wird nicht jeden Tag angeboten)
//console.log( dateToday, menusToday );
["Menü I", "Menü II", "Menü III", "Eintopf"].forEach(function(el, index, array){
// JSON Objekt für jedes Menü
if(menusToday[index]){ // index-Nummern stimmen mit index von menusToday & preise überein
var fooditem = {
"mensa": {
"name": mensa.name,
"uid": mensa.uid
},
"date": moment(dateToday, "DD.MM.YYYY").format('YYYY-MM-DD'),
"name": menusToday[index].trim(),
"minPrice": parseFloat( preise[index*2].replace(',','.') ).toFixed(2),
"maxPrice": parseFloat( preise[index*2+1].replace(',','.') ).toFixed(2),
"menuName": el,
"closed": 0
};
if( (fooditem.name.toLowerCase().indexOf("geschloss") !== -1) ||
(fooditem.name.toLowerCase().indexOf("keine ausg") !== -1)) {
fooditem.minPrice = "0";
fooditem.maxPrice = "0";
fooditem.closed = 1;
}
if(fooditem.name.indexOf("Änderungen vorb")) {
fooditem.name = fooditem.name.split("Änderungen vorb")[0].trim();
}
console.log("" + fooditem.date + ": " + fooditem.name + " (" + fooditem.minPrice + "/" + fooditem.maxPrice + ")");
parser.insertData(fooditem);
}
});
}
}
});
}
module.exports.bistroparser = bistroparser;
| JavaScript | 0 | @@ -2253,16 +2253,19 @@
Eintopf/
+, 4
)%0A%09%09%09%09%09.
|
e3796f6f416c70cd72a57ebbd4ec8882232df3ef | Convert the password prompt to ES6 syntax | web/password_prompt.js | web/password_prompt.js | /* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { mozL10n } from './ui_utils';
import { OverlayManager } from './overlay_manager';
import { PasswordResponses } from './pdfjs';
/**
* @typedef {Object} PasswordPromptOptions
* @property {string} overlayName - Name of the overlay for the overlay manager.
* @property {HTMLDivElement} container - Div container for the overlay.
* @property {HTMLParagraphElement} label - Label containing instructions for
* entering the password.
* @property {HTMLInputElement} input - Input field for entering the password.
* @property {HTMLButtonElement} submitButton - Button for submitting the
* password.
* @property {HTMLButtonElement} cancelButton - Button for cancelling password
* entry.
*/
/**
* @class
*/
var PasswordPrompt = (function PasswordPromptClosure() {
/**
* @constructs PasswordPrompt
* @param {PasswordPromptOptions} options
*/
function PasswordPrompt(options) {
this.overlayName = options.overlayName;
this.container = options.container;
this.label = options.label;
this.input = options.input;
this.submitButton = options.submitButton;
this.cancelButton = options.cancelButton;
this.updateCallback = null;
this.reason = null;
// Attach the event listeners.
this.submitButton.addEventListener('click', this.verify.bind(this));
this.cancelButton.addEventListener('click', this.close.bind(this));
this.input.addEventListener('keydown', function (e) {
if (e.keyCode === 13) { // Enter key
this.verify();
}
}.bind(this));
OverlayManager.register(this.overlayName, this.container,
this.close.bind(this), true);
}
PasswordPrompt.prototype = {
open: function PasswordPrompt_open() {
OverlayManager.open(this.overlayName).then(function () {
this.input.type = 'password';
this.input.focus();
var promptString = mozL10n.get('password_label', null,
'Enter the password to open this PDF file.');
if (this.reason === PasswordResponses.INCORRECT_PASSWORD) {
promptString = mozL10n.get('password_invalid', null,
'Invalid password. Please try again.');
}
this.label.textContent = promptString;
}.bind(this));
},
close: function PasswordPrompt_close() {
OverlayManager.close(this.overlayName).then(function () {
this.input.value = '';
this.input.type = '';
}.bind(this));
},
verify: function PasswordPrompt_verify() {
var password = this.input.value;
if (password && password.length > 0) {
this.close();
return this.updateCallback(password);
}
},
setUpdateCallback:
function PasswordPrompt_setUpdateCallback(updateCallback, reason) {
this.updateCallback = updateCallback;
this.reason = reason;
}
};
return PasswordPrompt;
})();
export {
PasswordPrompt,
};
| JavaScript | 0.999999 | @@ -1429,120 +1429,36 @@
*/%0A%0A
-/**%0A * @class%0A */%0Avar PasswordPrompt = (function PasswordPromptClosure() %7B%0A /**%0A * @constructs PasswordPrompt
+class PasswordPrompt %7B%0A /**
%0A
@@ -1506,39 +1506,27 @@
*/%0A
-function PasswordPrompt
+constructor
(options
@@ -2054,20 +2054,14 @@
n',
-function
(e)
+ =%3E
%7B%0A
@@ -2138,27 +2138,16 @@
%7D%0A %7D
-.bind(this)
);%0A%0A
@@ -2273,71 +2273,8 @@
%0A%0A
-PasswordPrompt.prototype = %7B%0A open: function PasswordPrompt_
open
@@ -2274,26 +2274,24 @@
%0A open() %7B%0A
-
OverlayM
@@ -2325,32 +2325,24 @@
e).then(
-function () %7B%0A
+() =%3E %7B%0A
th
@@ -2367,34 +2367,32 @@
assword';%0A
-
-
this.input.focus
@@ -2392,26 +2392,24 @@
t.focus();%0A%0A
-
var pr
@@ -2449,34 +2449,32 @@
d_label', null,%0A
-
'Enter t
@@ -2514,26 +2514,24 @@
.');%0A%0A
-
if (this.rea
@@ -2586,18 +2586,16 @@
-
promptSt
@@ -2649,18 +2649,16 @@
-
-
'Invalid
@@ -2695,23 +2695,19 @@
;%0A
-
%7D%0A%0A
-
th
@@ -2751,68 +2751,19 @@
- %7D.bind(this)
+%7D
);%0A
-
%7D
-,
%0A%0A
-
-close: function PasswordPrompt_
clos
@@ -2764,26 +2764,24 @@
close() %7B%0A
-
OverlayM
@@ -2820,24 +2820,16 @@
hen(
-function () %7B%0A
+() =%3E %7B%0A
@@ -2855,26 +2855,24 @@
= '';%0A
-
this.input.t
@@ -2889,69 +2889,19 @@
- %7D.bind(this));%0A %7D,%0A%0A verify: function PasswordPrompt_
+%7D);%0A %7D%0A%0A
veri
@@ -2903,26 +2903,24 @@
verify() %7B%0A
-
var pass
@@ -2944,26 +2944,24 @@
.value;%0A
-
-
if (password
@@ -2989,26 +2989,24 @@
0) %7B%0A
-
this.close()
@@ -3003,26 +3003,24 @@
is.close();%0A
-
return
@@ -3059,75 +3059,17 @@
- %7D%0A
+%7D%0A
%7D
-,
%0A%0A
-
-setUpdateCallback:%0A function PasswordPrompt_
setU
@@ -3104,26 +3104,24 @@
, reason) %7B%0A
-
this.upd
@@ -3150,26 +3150,24 @@
llback;%0A
-
this.reason
@@ -3182,48 +3182,11 @@
;%0A
- %7D%0A %7D;%0A%0A return PasswordPrompt;%0A%7D)();
+%7D%0A%7D
%0A%0Aex
|
6c63ec12eb9218ab99f5903606a1e52f9144857c | Make the power-save-blocker a bit more concise | lib/browser/api/power-save-blocker.js | lib/browser/api/power-save-blocker.js | var powerSaveBlocker
powerSaveBlocker = process.atomBinding('power_save_blocker').powerSaveBlocker
module.exports = powerSaveBlocker
| JavaScript | 0.000001 | @@ -1,42 +1,18 @@
-var powerSaveBlocker%0A%0ApowerSaveBlocker
+module.exports
= p
@@ -73,39 +73,4 @@
ker%0A
-%0Amodule.exports = powerSaveBlocker%0A
|
d224f5975ba09e3f12c31d61b73d902950b1c823 | Fix webpack config | webpack/prod.config.js | webpack/prod.config.js | import path from 'path';
import webpack from 'webpack';
import importantly from 'postcss-importantly';
export default {
entry: {
todoapp: [path.join(__dirname, '../chrome/extension/todoapp')],
background: [path.join(__dirname, '../chrome/extension/background')],
inject: [path.join(__dirname, '../chrome/extension/inject')]
},
output: {
path: path.join(__dirname, '../build/js'),
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.IgnorePlugin(/[^/]+\/[\S]+.dev$/),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
comments: false,
compressor: {
warnings: false
}
})
],
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
}, {
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'postcss'
]
}]
}
};
| JavaScript | 0.000004 | @@ -52,55 +52,8 @@
ck';
-%0Aimport importantly from 'postcss-importantly';
%0A%0Aex
|
5a5246bff8f2d938fd1481d65b8772c495d41963 | add query equal to botid | lib/controller/replyWithDumbledore.js | lib/controller/replyWithDumbledore.js | const {
INPUT, OUTPUT, DB
} = require('../const');
async function studentStats(originalMessage) {
const student = originalMessage.text.substring(originalMessage.text.indexOf('@') + 1).split('>')[0];
const userName = await this.convertToUserName(student);
if (userName.name !== 'dumbledore') {
const Student = new Parse.Object(DB.STUDENT.CALL);
const query = new Parse.Query(Student);
query.equalTo(DB.STUDENT.BOT_ID, this.id);
query.equalTo(DB.STUDENT.USER_NAME, userName.name);
try {
const record = await query.first();
if (record.attributes !== undefined) {
this.slackBot.announcePlainString(originalMessage, OUTPUT.TELL_ME_ABOUT.PERSON.student(record.attributes));
} else {
this.slackBot.announcePlainString(originalMessage, OUTPUT.TELL_ME_ABOUT.PERSON.NOT_FOUND);
}
} catch (err) {
console.error('DATABASE ERROR', err);
}
} else {
this.slackBot.announcePlainString(originalMessage, OUTPUT.TELL_ME_ABOUT.PERSON.DUMBLEDORE);
}
}
async function bestStudentChannel(student) {
const Student = new Parse.Object(student);
const query = new Parse.Query(Student);
query.descending(DB.STUDENT.POINT);
try {
const record = await query.first();
return record;
} catch (err) {
console.error('DATABASE ERROR', err);
}
}
async function bestStudent(originalMessage) {
const record = await bestStudentChannel(DB.STUDENT.CALL);
this.slackBot.announcePlainString(originalMessage, OUTPUT.getBestStudent(record.attributes));
}
async function worstStudentChannel(student) {
const Student = new Parse.Object(student);
const query = new Parse.Query(Student);
query.ascending(DB.STUDENT.POINT);
try {
const record = await query.first();
return record;
} catch (err) {
console.error('DATABASE ERROR', err);
}
}
async function worstStudent(originalMessage) {
const record = await worstStudentChannel(DB.STUDENT.CALL);
this.slackBot.announcePlainString(originalMessage, OUTPUT.getWorstStudent(record.attributes));
}
function tellMeAbout(originalMessage) {
const text = originalMessage.text.toLowerCase();
if (text.includes('@')) {
studentStats.call(this, originalMessage);
} else if (text.includes(INPUT.PROFESSOR.JASON_MOM)) {
this.slackBot.announcePlainString(originalMessage, OUTPUT.TELL_ME_ABOUT.JASON_MOM);
}
}
async function listStudentChannel(student) {
const Student = new Parse.Object(student);
const query = new Parse.Query(Student);
query.descending(DB.STUDENT.POINT);
try {
const record = await query.find();
return record;
} catch (error) {
console.log(error);
}
}
async function listStudent(originalMessage) {
const record = await listStudentChannel(DB.STUDENT.CALL);
this.slackBot.announcePlainString(originalMessage, OUTPUT.getListStudent(record));
}
function replyWithDumbledore(originalMessage) {
const text = originalMessage.text.toLowerCase();
const parseCase = {
[INPUT.PROFESSOR.GET_BEST_STUDENT]: () => bestStudent.call(this, originalMessage),
[INPUT.PROFESSOR.GET_WORST_STUDENT]: () => worstStudent.call(this, originalMessage),
[INPUT.PROFESSOR.GET_LIST_STUDENT]: () => listStudent.call(this, originalMessage),
[INPUT.PROFESSOR.TELL_ME_ABOUT.CALL]: () => tellMeAbout.call(this, originalMessage)
};
Object.keys(parseCase).forEach(key => {
if (text.includes(key)) {
parseCase[key]();
}
});
}
module.exports = replyWithDumbledore;
| JavaScript | 0.999897 | @@ -1141,32 +1141,76 @@
Query(Student);%0A
+ query.equalTo(DB.STUDENT.BOT_ID, this.id);
%0A query.descend
@@ -1704,16 +1704,60 @@
udent);%0A
+ query.equalTo(DB.STUDENT.BOT_ID, this.id);
%0A query
@@ -2569,32 +2569,77 @@
Query(Student);%0A
+ query.equalTo(DB.STUDENT.BOT_ID, this.id);%0A
query.descendi
|
49f10b54d0f90c8891655c19e6b657e3bc541c30 | Add argument for handling errors on executeSql call | sqldatabase.deferred.js | sqldatabase.deferred.js | (function (window, $, undefined) {
function DeferredSQLTransaction(tx) {
this.transaction = tx;
};
DeferredSQLTransaction.prototype.executeSql = function executeSql(sqlStatement, sqlArguments) {
var self = this,
d = $.Deferred(),
successCallback = function (tx, resultSet) {
d.resolve(self, resultSet);
},
errorCallback = function (tx, error) {
d.reject(self, error);
return true;
};
self.transaction.executeSql(sqlStatement, sqlArguments, successCallback, errorCallback);
return d.promise();
};
function DeferredSQLDatabase(db) {
this.database = db;
this.version = db.version;
}
var openDatabaseDeferred = function openDatabase(name, version, displayName, estimatedSize, creationCallback) {
var self = this,
d = $.Deferred(),
wrappedCreationCallback = function () {
creationCallback(deferredDb);
},
db = window.openDatabase(name, version, displayName, estimatedSize, wrappedCreationCallback),
deferredDb = new DeferredSQLDatabase(db);
return deferredDb;
};
DeferredSQLDatabase.prototype.transaction = function transaction(callback) {
var self = this,
d = $.Deferred(),
errorCallback = function (error) {
d.reject(error);
},
successCallback = function () {
d.resolve();
},
wrappedCallback = function (tx) {
callback(new DeferredSQLTransaction(tx));
};
self.database.transaction(wrappedCallback, errorCallback, successCallback);
return d.promise();
};
DeferredSQLDatabase.prototype.readTransaction = function readTransaction(callback) {
var self = this,
d = $.Deferred(),
errorCallback = function (error) {
d.reject(error);
},
successCallback = function () {
d.resolve();
},
wrappedCallback = function (tx) {
callback(new DeferredSQLTransaction(tx));
};
self.database.readTransaction(wrappedCallback, errorCallback, successCallback);
return d.promise();
};
DeferredSQLDatabase.prototype.changeVersion = function changeVersion(oldVersion, newVersion, callback) {
var self = this,
d = $.Deferred(),
errorCallback = function (error) {
d.reject(error);
},
successCallback = function () {
self.version = self.database.version;
d.resolve();
},
wrappedCallback = function (tx) {
callback(new DeferredSQLTransaction(tx));
};
self.database.changeVersion(oldVersion, newVersion, callback, errorCallback, successCallback);
return d.promise();
};
window.openDatabaseDeferred = openDatabaseDeferred;
})(window, jQuery);
| JavaScript | 0.000001 | @@ -206,16 +206,30 @@
rguments
+, handleErrors
) %7B%0A
@@ -477,32 +477,33 @@
t(self, error);%0A
+%0A
@@ -603,32 +603,47 @@
successCallback,
+ handleErrors ?
errorCallback);
@@ -632,32 +632,44 @@
? errorCallback
+ : undefined
);%0A%0A retu
@@ -1456,32 +1456,295 @@
ction (error) %7B%0A
+ // I need to do some work here. Did the user trigger add a%0A //failure handler? can I tell if they did?%0A //I can ensure that I am the first to handle an error%0A //I can capture the most recent sql error%0A%0A
|
dcfabfccf27d97ed9a0e6adb5dec37bc8688d245 | Fix off-by-one error | lib/controllers/reviews-controller.js | lib/controllers/reviews-controller.js | import React from 'react';
import PropTypes from 'prop-types';
import {Emitter} from 'event-kit';
import {RemoteSetPropType, BranchSetPropType, EndpointPropType, WorkdirContextPoolPropType} from '../prop-types';
import ReviewsView from '../views/reviews-view';
import PullRequestCheckoutController from '../controllers/pr-checkout-controller';
import IssueishDetailItem from '../items/issueish-detail-item';
import translateLines, {getLastLineForDiffHunk} from 'whats-my-line';
export default class ReviewsController extends React.Component {
static propTypes = {
// GraphQL results
repository: PropTypes.shape({
pullRequest: PropTypes.object.isRequired,
}).isRequired,
// Package models
workdirContextPool: WorkdirContextPoolPropType.isRequired,
localRepository: PropTypes.object.isRequired,
isAbsent: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired,
isPresent: PropTypes.bool.isRequired,
isMerging: PropTypes.bool.isRequired,
isRebasing: PropTypes.bool.isRequired,
branches: BranchSetPropType.isRequired,
remotes: RemoteSetPropType.isRequired,
multiFilePatch: PropTypes.object.isRequired,
// Connection properties
endpoint: EndpointPropType.isRequired,
// URL parameters
owner: PropTypes.string.isRequired,
repo: PropTypes.string.isRequired,
number: PropTypes.number.isRequired,
workdir: PropTypes.string.isRequired,
// Atom environment
workspace: PropTypes.object.isRequired,
config: PropTypes.object.isRequired,
commands: PropTypes.object.isRequired,
tooltips: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
this.emitter = new Emitter();
this.state = {
contextLines: 4,
};
}
render() {
return (
<PullRequestCheckoutController
repository={this.props.repository}
pullRequest={this.props.repository.pullRequest}
localRepository={this.props.localRepository}
isAbsent={this.props.isAbsent}
isLoading={this.props.isLoading}
isPresent={this.props.isPresent}
isMerging={this.props.isMerging}
isRebasing={this.props.isRebasing}
branches={this.props.branches}
remotes={this.props.remotes}>
{checkoutOp => (
<ReviewsView
checkoutOp={checkoutOp}
contextLines={this.state.contextLines}
moreContext={this.moreContext}
lessContext={this.lessContext}
openFile={this.openFile}
openDiff={this.openDiff}
openPR={this.openPR}
openIssueish={this.openIssueish}
{...this.props}
/>
)}
</PullRequestCheckoutController>
);
}
openFile = async (filePath, diffHunk) => {
const prCommitSha = this.props.repository.pullRequest.headRefOid;
const lineNumber = getLastLineForDiffHunk(diffHunk);
const translations = await translateLines([lineNumber], this.props.workdir, filePath, prCommitSha);
this.props.workspace.open(
filePath, {
initialLine: translations.get(lineNumber).newPosition,
initialColumn: 0,
pending: true,
});
}
openDiff = async (filePath, lineNumber) => {
const item = await this.getPRDetailItem();
item.openFilesTab({
changedFilePath: filePath,
changedFilePosition: lineNumber,
});
}
openPR = async () => {
const item = await this.getPRDetailItem();
item.onTabSelected(IssueishDetailItem.tabs.OVERVIEW);
}
getPRDetailItem = () => {
return this.props.workspace.open(
IssueishDetailItem.buildURI(
this.props.endpoint.getHost(),
this.props.owner,
this.props.repo,
this.props.number,
this.props.workdir,
), {
pending: true,
searchAllPanes: true,
},
);
}
moreContext = () => this.setState(prev => ({contextLines: prev.contextLines + 1}));
lessContext = () => this.setState(prev => ({contextLines: Math.max(prev.contextLines - 1, 1)}));
openIssueish = async (owner, repo, number) => {
const host = this.props.endpoint.getHost();
const homeRepository = await this.props.localRepository.hasGitHubRemote(host, owner, repo)
? this.props.localRepository
: (await this.props.workdirContextPool.getMatchingContext(host, owner, repo)).getRepository();
const uri = IssueishDetailItem.buildURI(host, owner, repo, number, homeRepository.getWorkingDirectoryPath());
return this.props.workspace.open(uri, {pending: true, searchAllPanes: true});
}
}
| JavaScript | 0.998437 | @@ -3121,16 +3121,20 @@
Position
+ - 1
,%0A
|
2466beb6fc3a2750a6a2f7d18d57309a713e6805 | Modify user schema | lib/dataaccess/handler/mongo/model.js | lib/dataaccess/handler/mongo/model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
/**
* Schemas
*/
var UserSchema = new Schema({
uid: { type: String, required: true, index: { unique: true, dropDups: true} },
pwd: { type: String, required: true, select: false },
nick: { type: String, required: true },
email: { type: String, required: true },
gender: String,
image: String,
status: String,
addres: String,
phone: String
});
var ContactSchema = new Schema({
uid: { type: String, required: true, index: true },
cid: { type: String, required: true, index: true },
alias: { type: String, 'default': '' },
black: { type: Boolean, 'default': false }
});
var MessageSchema = new Schema({
uid: { type: String, required: true, index: true },
mid: { type: String, required: true, index: true },
msg: { type: String, required: true },
time: { type: String, required: true, 'default': Date.now }
});
/**
* Models
*/
var User = module.exports.User = mongoose.model('user', UserSchema);
var Contact = module.exports.Contact = mongoose.model('contact', ContactSchema);
var Message = module.exports.Message = mongoose.model('message', MessageSchema);
module.exports.Q = function Q(fields, params) {
var r = {};
for (var i in fields) {
// required condition
if (fields[i]) {
if (params[i] === undefined) return null;
else r[i] = params[i];
}
// optional condition
else {
if (params[i] != undefined)
r[i] = this.params[i];
}
}
return r;
};
module.exports.F = function F(def, params) {
if (params.filter)
return params.filter.replace(/,/g, ' ');
else return def;
};
module.exports.S = function S(fields, params) {
var r = {};
for (var i in fields) {
// required fields
if (fields[i]) {
if (params[i] === undefined) return null;
else r[i] = params[i];
}
// optional fields
else {
if (params[i] != undefined)
r[i] = this.params[i];
}
}
return { $set: r };
};
module.exports.asArray = function asArray(doc, field) {
var r = [];
doc.forEach(function (obj, index, array) {
if (obj[field] != undefined) r.push(obj[field]);
});
return r;
};
module.exports.toArray = function toArray(doc) {
}; | JavaScript | 0 | @@ -98,16 +98,95 @@
ectId;%0A%0A
+/**%0A * Connect Mongodb%0A */%0A%0Amongoose.connect('mongodb://localhost/speedyfx');%0A%0A
/**%0A * S
@@ -259,32 +259,44 @@
required: true,
+ trim: true,
index: %7B unique
@@ -407,32 +407,44 @@
tring, required:
+ true, trim:
true %7D,%0A ema
@@ -464,32 +464,44 @@
tring, required:
+ true, trim:
true %7D,%0A gen
@@ -505,22 +505,58 @@
gender:
-String
+%7B type: String, enum: %5B'male', 'female'%5D %7D
,%0A im
@@ -1384,16 +1384,61 @@
hema);%0A%0A
+/**%0A * Create query condition expression%0A */%0A
module.e
@@ -1776,37 +1776,32 @@
r%5Bi%5D =
-this.
params%5Bi%5D;%0A
@@ -1821,32 +1821,78 @@
return r;%0A%7D;%0A%0A
+/**%0A * Create selection filter expression%0A */%0A
module.exports.F
@@ -2013,24 +2013,67 @@
rn def;%0A%7D;%0A%0A
+/**%0A * Create update setter expression%0A */%0A
module.expor
@@ -2465,24 +2465,82 @@
t: r %7D;%0A%7D;%0A%0A
+/**%0A * Extract field from query result and make array%0A */%0A
module.expor
|
f40b5d47c98a594fc589f6869e4b724add3bf3d2 | add up | J8-0.0.1.js | J8-0.0.1.js | /**
* Created by lja on 2015/11/20.
*/
var type = (function () {
'use strict';
var class2type = {},
toString = class2type.toString;
('Boolean Number String Function Array Date RegExp Object Error').split(' ').forEach(function (name) {
class2type['[object ' + name + ']'] = name.toLowerCase();
});
function isWindow(obj) {
return obj !== null && obj.window && obj === obj.window;
}
function isFunction(obj) {
return class2type[toString.call(obj)] === 'function';
}
function isDocument(obj) {
return obj && obj.nodeType === obj.DOCUMENT_NODE;
}
function isObject(obj) {
return class2type[toString.call(obj)] === 'object';
}
function isArray(obj) {
return class2type[toString.call(obj)] === 'array';
}
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) &&
Object.getPrototypeOf(obj) === Object.prototype;
}
return {
isWindow: isWindow,
isFunction: isFunction,
isDocument: isDocument,
isObject: isObject,
isPlainObject: isPlainObject,
isArray: isArray
};
})();
var Jackey8 = (function (type) {
'use strict';
var J8,
emptyArray = [],
jackey8 = {},
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
'tr': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},
// special attributes that should be get/set via method calls
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
simpleSelectorRE = /^[\w-]*$/,//字母 数字 或者下划线,不包括空格
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//tag reg
readyRE = /complete|loaded|interactive/,
htmlFragmentRE = /^\s*<(\w+|!)[^>]*>/;//html片段
function filterNullArray(array) {
return emptyArray.filter.call(array, function (item) {
return item !== null;
});
}
//decorate the __proto__ and selector
//todo: __proto__ not supported on IE
jackey8.decorateDom = function (dom, selector) {
dom = dom || [];
dom.__proto__ = J8.fn;//jshint ignore:line
dom.selector = selector;
return dom;
};
jackey8.createNodeByHtmlFragment = function (html, name, properties) {
var dom, nodes, container;
if (simpleSelectorRE.test(html)) {
dom = J8(document.createElement(RegExp.$1));
}
if (!dom) {
if (html.replace) {
html = html.replace(tagExpanderRE, '<$1></$2>');
}
if (name === void 0) {
name = htmlFragmentRE.test(html) && RegExp.$1;
}
if (!(name in containers)) {
name = '*';
}
container = containers[name];
container.innerHTML = '' + html;//add html fragment to dom, make it node
dom = J8.each(emptyArray.slice.call(container.childNodes), function () {
container.removeChild(this);
});
}
if (type.isPlainObject(properties)) {
nodes = J8(dom);
J8.each(properties, function (key, value) {
if (methodAttributes.indexOf(key) > -1) {
nodes[key](value);
} else {
nodes.attr(key, value);
}
});
}
};
/**
* find selector in context
* by id class and 复杂类型:ul li
* @param context
* @param selector
*/
jackey8.queryDom = function (context, selector) {
var found = [],
maybeId = selector[0] === '#',
maybeClass = selector[0] === '.',
name = maybeId || maybeClass ? selector.slice(1) : selector,
isSample = simpleSelectorRE.test(name);
if (!type.isDocument(context)) {
return found;
}
if (!isSample) {
found = emptyArray.slice.call(context.querySelectorAll(selector));
} else {
if (maybeId) {
found = context.getElementById(name);
if (found) {
return [found];
}
return [];
}
if (maybeClass) {
found = context.getElementsByClassName(name);
} else {
found = context.getElementsByTagName(name);
}
}
return emptyArray.slice.call(found);
};
//selector: empty string function object array and the instance of Jackey8
jackey8.init = function (selector, context) {
var dom;
//if nothing given, return an empty collection
if (!selector) {
return jackey8.decorateDom();
}
if (typeof selector === 'string') {
selector = selector.trim();
//如果它是一个html片段,则创建一个节点
//提示:在chrome21和Firefox15下面,
// 如果不是<开头, 会抛错
if (selector[0] === '<' && htmlFragmentRE.test(selector)) {
//todo:
dom = jackey8.createNodeByHtmlFragment(selector, RegExp.$1, context);
selector = null;
}
//如果有parent,则先找到parent,然后使用find去找到selector
else if (context !== void 0) {
J8(context).find(selector);
}
else {
// 正常的选取
// 1 id 2 class 3 复杂选取
// 作用域为document,因为如果存在context,则执行$(conetxt).find(selector)
dom = jackey8.queryDom(document, selector);
}
} else if (type.isFunction(selector)) {
J8(document).ready(selector);
} else if (selector instanceof jackey8.decorateDom) {
return selector;
} else if (type.isArray(selector)) {
dom = filterNullArray(selector);
} else if (type.isObject(selector)) {
dom = [selector];
selector = null;
} else {
dom = [];
}
return jackey8.decorateDom(dom, selector);
};
J8 = function (selector, context) {
return jackey8.init(selector, context);
};
J8.each = function (elements, callback) {
var i, key;
if (type.isArray(elements)) {
for (i = 0; i < elements.length; i++) {
if (callback.call(elements[i], i, elements[i]) === false) {
return elements;
}
}
} else {
for (key in elements) {
if (callback.call(elements[key], key, elements[key]) === false) {
return elements;
}
}
}
return elements;
}
J8.fn = {
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
indexOf: emptyArray.indexOf,
concat: emptyArray.concat,
ready: function (callback) {
if (readyRE.test(document.readyState) && document.body) {
callback(J8);
} else {
//todo: need to test DOMContentLoaded in each browsers
document.addEventListener('DOMContentLoaded', function () {
callback(J8);
}, false);
return this;
}
}
};
return J8;
})(type);
window.Jackey8 = Jackey8;
if (window.J8 === void 0) {
window.J8 = Jackey8;
}
| JavaScript | 0.000048 | @@ -7601,18 +7601,16 @@
%0A %7D;%0A
-%0A%0A
%0A
|
7cb7cba3c88e084dea874b7602af5d351aa20201 | Handle error message in readability mode | data/js/ext.api.js | data/js/ext.api.js | define(function(require, exports, module) {
'use strict';
var TSCORE = require("tscore");
console.log("Loading: ext.api.js");
window.addEventListener("message", handleMessage, false);
function handleMessage(msg) {
var data = JSON.parse(msg.data);
var command = data.command;
switch (command) {
case "readabilityError":
TSCORE.showAlertDialog("This HTML content can't be loaded.");
break;
case "saveDocument":
TSCORE.FileOpener.saveFile();
break;
case "hideAllMenus":
hideMenus();
break;
case "playbackEnded":
openNextFile();
break;
case "openLinkExternally":
if (data.link) {
openLinkExternally(data.link);
}
break;
case "contentChangedInEditor":
TSCORE.FileOpener.setFileChanged(true);
break;
default:
console.log("Not recognized messaging command: " + msg);
break;
}
}
function hideMenus() {
TSCORE.hideAllDropDownMenus();
$('#searchOptions').hide();
$('#fileExtensionMenu').parent().removeClass('open');
$('#perspectiveSwitcher').parent().removeClass('open');
$('#locationsList').parent().removeClass('open');
$('#tagSuggestionsMenu').parent().removeClass('open');
}
function openNextFile() {
//if(TSCORE.selectedFiles.length > 0) {
// TODO open next selected file
//} else {
TSCORE.FileOpener.openFile(TSCORE.PerspectiveManager.getNextFile(TSCORE.FileOpener.getOpenedFilePath()));
//}
}
function openLinkExternally(uri) {
uri = decodeURIComponent(uri);
if (
uri.indexOf("http://") === 0 ||
uri.indexOf("https://") === 0 ||
uri.indexOf("file://") === 0
) {
TSCORE.IO.openFile(uri);
} else {
console.log("Not supported URL format: " + uri);
}
}
}); | JavaScript | 0.000001 | @@ -328,24 +328,23 @@
se %22
-readabilityError
+showAlertDialog
%22:%0A
@@ -383,13 +383,8 @@
his
-HTML
cont
@@ -404,16 +404,28 @@
loaded.%22
+, data.title
);%0A
|
8d4772b3cae9c6df1f31ff11280ebc0a1b83a7fb | Fix href with "#" | src/page-accelerator.js | src/page-accelerator.js | /*
* PageAccelerator - A solution to load web pages faster
* http://github.com/EasyFood/PageAccelerator
* author: Evandro Leopoldino Goncalves <[email protected]>
* http://github.com/EasyFood
* License: MIT
*/
(function(global, factory) {
/*global define: false*/
/*global exports: true*/
if (typeof exports === 'object' && exports) {
factory(exports); // CommonJS
} else if (typeof define === 'function' && define.amd) {
define(['exports'], factory); // AMD
} else {
factory(global); // <script>
}
} (window, function(global) {
var isWindow = global === window;
var w = isWindow ? global : window;
var doc = document;
var M = w._PageAccelerator = w._PageAccelerator || {};
M.PageAccelerator = function() {
this.url = doc.location.href;
this.callback = function() {};
};
M.PageAccelerator.prototype = {
_updateObject: function(obj, body) {
var attrs = body.attributes;
for (var i=0, size=attrs.length; i<size; i++) {
obj.attrs[attrs[i].name] = attrs[i].value;
}
return obj;
},
_updateHistory: function(head, body) {
var obj = this._updateObject({
head: head.innerHTML.trim(),
content: body.innerHTML.trim(),
attrs: {}
}, body);
w.history.pushState(obj, '', this.url);
w.addEventListener('popstate', this._updateBody.bind(this), false);
},
_DOMParser: function(data) {
var parser = new DOMParser();
return parser.parseFromString(data, 'text/html');
},
_updateBodyAttributes: function(data) {
Object.keys(data).forEach(function(key) {
var value = data[key];
doc.body.setAttribute(key, value);
});
},
_updateBody: function(e) {
var data = e.state;
this._updateBodyAttributes(data.attrs);
doc.body.innerHTML = data.content;
var dom = this._DOMParser(data.head);
doc.title = dom.head.querySelector('title').innerText;
this.url = w.location.href;
this.start();
this.callback();
},
_loadStyles: function(head, callback) {
var requests = [].map.call(head.querySelectorAll('link[rel="stylesheet"]'), function(element) {
return M.ajax.get(element.href);
});
w.Promise.all(requests).then(callback.bind(this));
},
_update: function(data) {
var dom = this._DOMParser(data);
var head = dom.head;
this._loadStyles(head, function() {
var body = dom.body;
doc.body = body;
doc.head = head;
doc.title = head.querySelector('title').innerText;
this._updateHistory(head, body);
this.callback();
w.scrollTo(0, 0);
this.start();
}.bind(this));
},
_onClick: function(element) {
this.url = element.href;
M.ajax.get(this.url).then(this._update.bind(this))
.catch(this._update.bind(this));
},
_replaceHistory: function() {
var body = doc.body;
var obj = this._updateObject({
head: doc.head.innerHTML.trim(),
content: body.innerHTML.trim(),
attrs: {}
}, body);
w.history.replaceState(obj, '', this.url);
},
start: function(callback) {
this.callback = callback || this.callback;
var that = this;
var links = doc.querySelectorAll('a:not([data-pageAccelerator="false"])');
[].forEach.call(links, function(element) {
if (element.hostname !== w.location.hostname ||
element.protocol !== w.location.protocol) {
return;
}
element.addEventListener('click', function(e) {
e.preventDefault();
that._onClick.call(that, this);
}, false);
});
this._replaceHistory();
}
};
global.pageAccelerator = function(callback) {
new M.PageAccelerator().start(callback);
};
}));
| JavaScript | 0.000004 | @@ -3545,16 +3545,54 @@
protocol
+ %7C%7C%0A /#/.test(element.href)
) %7B%0A
|
613652f62601ed368d5dd04f1b9cdf2c523fd8fe | Add new lines at end of inserted syntax block | assets/js/code-modal.js | assets/js/code-modal.js | jQuery.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
jQuery.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
(function() {
function htmlspecialchars(string, quote_style, charset, double_encode) {
// discuss at: http://phpjs.org/functions/htmlspecialchars/
// original by: Mirek Slugen
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Nathan
// bugfixed by: Arno
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// input by: Ratheous
// input by: Mailfaker (http://www.weedem.fr/)
// input by: felix
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// note: charset argument not supported
// example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
// returns 1: '<a href='test'>Test</a>'
// example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
// returns 2: 'ab"c'd'
// example 3: htmlspecialchars('my "&entity;" is still here', null, null, false);
// returns 3: 'my "&entity;" is still here'
var optTemp = 0,
i = 0,
noquotes = false;
if (typeof quote_style === 'undefined' || quote_style === null) {
quote_style = 2;
}
string = string.toString();
if (double_encode !== false) { // Put this first to avoid double-encoding
string = string.replace(/&/g, '&');
}
string = string.replace(/</g, '<')
.replace(/>/g, '>');
var OPTS = {
'ENT_NOQUOTES': 0,
'ENT_HTML_QUOTE_SINGLE': 1,
'ENT_HTML_QUOTE_DOUBLE': 2,
'ENT_COMPAT': 2,
'ENT_QUOTES': 3,
'ENT_IGNORE': 4
};
if (quote_style === 0) {
noquotes = true;
}
if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
quote_style = [].concat(quote_style);
for (i = 0; i < quote_style.length; i++) {
// Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
if (OPTS[quote_style[i]] === 0) {
noquotes = true;
} else if (OPTS[quote_style[i]]) {
optTemp = optTemp | OPTS[quote_style[i]];
}
}
quote_style = optTemp;
}
if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
string = string.replace(/'/g, ''');
}
if (!noquotes) {
string = string.replace(/"/g, '"');
}
return string;
}
tinymce.create('tinymce.plugins.flynsyntaxcodemodal', {
init: function(editor, url) {
// Register commands, mceMyown is name of command to be executed.
editor.addCommand('flynsyntaxshowmodal', function() {
// Calls the pop-up modal
editor.windowManager.open({
// Modal settings
title: 'Insert Code Block',
width: jQuery( window ).width() * 0.7,
// minus head and foot of dialog box
height: (jQuery( window ).height() - 36 - 50) * 0.7,
inline: 1,
id: 'plugin-slug-insert-dialog',
file: ajaxurl + '?action=flyn-syntax-code-modal',
buttons: [
{
text: 'Insert',
id: 'plugin-slug-button-insert',
class: 'insert',
onclick: function( e ) {
var frame = e.currentTarget.getElementsByTagName('iframe')[0].contentWindow;
var options = jQuery(frame.document.body).find(':input').serializeObject();
var html = frame.editor.getValue();
if ( !options.escaped )
{
options.escaped = 'true';
html = htmlspecialchars(html);
}
var elem = document.createElement('pre');
jQuery.each(options, function(key, value) {
if ( value )
elem.setAttribute(key, value);
});
elem.innerHTML = html;
editor.insertContent(elem.outerHTML);
editor.windowManager.close();
},
},
{
text: 'Cancel',
id: 'plugin-slug-button-cancel',
onclick: 'close'
}
],
});
});
// Register buttons,this is the button will be displayed on wordpress rich editor
editor.addButton('flynsyntaxcodemodal', {
title: 'Insert code block',
cmd: 'flynsyntaxshowmodal',
image: url + '/../images/code-icon.png'
});
},
getInfo: function() {
return {
longname : 'Flyn-Syntax Code Modal',
author : 'Flyn San',
authorurl : 'http://www.flynsarmy.com',
infourl : 'http://www.flynsarmy.com',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('flynsyntaxcodemodal', tinymce.plugins.flynsyntaxcodemodal);
})(); | JavaScript | 0.000001 | @@ -5329,16 +5329,31 @@
uterHTML
+ + %22%5Cn%5Cn %22
);%0D%0A
|
a53e5b9758bee535de8a449ae9da8d3a2a322a4c | Use newest editor instance. | src/pat/edit-tinymce.js | src/pat/edit-tinymce.js | define([
"jquery",
"../core/parser",
"../core/logger",
"../registry",
"../utils",
"jquery.textchange",
"tinymce"
], function($, Parser, logger, registry, utils) {
var log = logger.getLogger("pat.editTinyMCE"),
parser = new Parser("edit-tinymce");
parser.add_argument("tinymce-baseurl");
var _ = {
name: "editTinyMCE",
trigger: "form textarea.pat-edit-tinymce",
init: function($el, opts) {
var $form = $el.parents("form"),
id = $el.attr("id");
// make sure the textarea has an id
if (!id) {
var formid = $form.attr("id"),
name = $el.attr("name");
if (!formid) {
log.error("Textarea or parent form needs an id", $el, $form);
return false;
}
if (!name) {
log.error("Textarea needs a name", $el);
return false;
}
id = formid + "_" + name;
if ($("#"+id).length > 0) {
log.error("Textarea needs an id", $el);
return false;
}
$el.attr({id: id});
}
// read configuration
var cfg = $el.data("tinymce-json");
if (!cfg) {
log.info("data-tinymce-json empty, using default config", $el);
cfg = {};
}
cfg.elements = id;
cfg.mode = "exact";
cfg.readonly = Boolean($el.attr("readonly"));
// get arguments
var args = parser.parse($el, opts);
if (!args.tinymceBaseurl) {
log.error("tinymce-baseurl has to point to TinyMCE resources");
return false;
}
var base_url = window.location.toString(), idx;
if ((idx=base_url.indexOf("?"))!==-1)
base_url=base_url.slice(0, idx);
// handle rebasing of own urls if we were injected
var parents = $el.parents().filter(function() {
return $(this).data("pat-injected");
});
if (parents.length)
base_url = utils.rebaseURL(base_url, parents.first().data("pat-injected").origin);
if (cfg.content_css)
cfg.content_css = utils.rebaseURL(base_url, cfg.content_css);
if (args.tinymceBaseurl.indexOf("://")!==-1 || args.tinymceBaseurl[0]==="/") {
// tinyMCE.baseURL must be absolute
tinyMCE.baseURL = window.location.protocol + '//' +
window.location.host+'/' + args.tinymceBaseurl;
} else {
tinyMCE.baseURL = utils.rebaseURL(base_url, args.tinymceBaseurl);
}
tinyMCE.baseURI = new tinyMCE.util.URI(tinyMCE.baseURL);
cfg.oninit = function() {
var ed = tinyMCE.editors.filter(function(e) {
return e.id === id;
})[0];
var handler = function() {
tinyMCE.editors[id].save();
$el.trigger("input-change");
};
var setAttribHandler = function(ed, el) {
// handle image resize
if (el.tagName === "IMG") {
handler();
}
};
ed.onKeyUp.add(handler);
ed.onChange.add(handler);
ed.onUndo.add(handler);
ed.onRedo.add(handler);
ed.onSetAttrib.add(setAttribHandler);
};
// initialize editor
tinyMCE.init(cfg);
return $el;
},
destroy: function() {
// XXX
}
};
registry.register(_);
return _;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -2970,16 +2970,21 @@
var ed
+itors
= tinyM
@@ -3031,24 +3031,28 @@
+
return e.id
@@ -3079,12 +3079,65 @@
-%7D)%5B0
+ %7D),%0A ed = editors%5Beditors.length-1
%5D;%0A%0A
|
491388f9a9e0307fc00b70b18e901c60a30c6682 | fix test for chart test component | src/Chart/Chart.spec.js | src/Chart/Chart.spec.js | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import Chart, { styleSheet } from './Chart';
describe('<Chart />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a div', () => {
const wrapper = shallow(
<Chart>Hello World</Chart>,
);
assert.strictEqual(wrapper.is('div'), true, 'should be a div');
});
it('should render with the Chart class, default depth class, and rounded', () => {
const wrapper = shallow(<Chart>Hello World</Chart>);
assert.strictEqual(wrapper.hasClass(classes.Chart), true, 'should have the Chart class');
assert.strictEqual(wrapper.hasClass(classes.rounded), true, 'should be rounded by default');
});
it('should disable the rounded class', () => {
const wrapper = shallow(<Chart rounded={false}>Hello World</Chart>);
assert.strictEqual(wrapper.hasClass(classes.rounded), false, 'should not be rounded');
});
it('should set the zDepth shadow class', () => {
const wrapper = shallow(<Chart zDepth={16}>Hello World</Chart>);
assert.strictEqual(wrapper.hasClass(classes.dp16), true, 'should have the dp16 shadow class');
wrapper.setProps({ zDepth: 24 });
assert.strictEqual(wrapper.hasClass(classes.dp24), true, 'should have the dp24 shadow class');
wrapper.setProps({ zDepth: 2 });
assert.strictEqual(wrapper.hasClass(classes.dp2), true, 'should have the dp2 shadow class');
});
});
| JavaScript | 0 | @@ -751,21 +751,21 @@
classes.
-Chart
+paper
), true,
@@ -778,29 +778,29 @@
ld have the
-Chart
+paper
class');%0A
|
f0bab6b112f72e247a9dfd5fcbd3c32b4c566f0c | use camelCase | web-app/src/components/NotFound/index.js | web-app/src/components/NotFound/index.js | import React, { Component } from 'react';
import crest_background from '../../theme/flying/crest_red_background_no_shadow.svg';
import crest_bird_alone from '../../theme/flying/crest_bird_alone.svg';
import crest_bird_flying from '../../theme/flying/crest_bird_flying.svg';
import './NotFound.css';
import classNames from '../../utils/classNames';
class NotFound extends Component {
constructor(...props) {
super(...props);
this.state = {
fly: false,
}
}
componentDidMount() {
setInterval(() => {
this.setState(({ fly }) => ({ fly: !fly }))
}, 400)
}
render() {
return (
<div className="NotFound">
<div className="NotFound__Wrapper">
<div className="NotFound__Text">
404 not found!
</div>
<div className="NotFound__Logo">
<img className="NotFound_Logo_Background" src={crest_background} alt="CODE9000 crest background" />
<img className="NotFound_Logo_Bird_Alone NotFound_Logo_Bird_Animation"src={crest_bird_alone} alt="CODE9000 crest bird" />
<img className={classNames('NotFound_Logo_Bird_Flying', 'NotFound_Logo_Bird_Animation', this.state.fly && 'hidden')} src={crest_bird_flying} alt="CODE9000 crest bird" />
</div>
<div className="NotFound__SubText">
Woops!<br /><br />
Looks like the bird has flown.
</div>
</div>
</div>
);
}
};
export default NotFound;
| JavaScript | 0.998173 | @@ -43,26 +43,25 @@
import crest
-_b
+B
ackground fr
@@ -128,31 +128,29 @@
import crest
-_bird_a
+BirdA
lone from '.
@@ -198,31 +198,29 @@
import crest
-_bird_f
+BirdF
lying from '
@@ -881,18 +881,17 @@
c=%7Bcrest
-_b
+B
ackgroun
@@ -1016,31 +1016,29 @@
n%22src=%7Bcrest
-_bird_a
+BirdA
lone%7D alt=%22C
@@ -1195,31 +1195,29 @@
%7D src=%7Bcrest
-_bird_f
+BirdF
lying%7D alt=%22
|
bf332b85b9d27186a6f5e313757f76fb9adee17b | Add summary delegation to reporters. | src/pipeline/summary.js | src/pipeline/summary.js | module.exports = () => arguments
| JavaScript | 0 | @@ -15,19 +15,113 @@
= (
-) =%3E arguments
+type, results) =%3E %7B%0A const reporter = require(%60../reporters/$%7Btype%7D-reporter%60)%0A return reporter(results)%0A%7D
%0A
|
6d25d3793d5b9148bca0d3aba30fc3f99c81315f | use slugs for anchors in markdown reporter | lib/reporters/markdown.js | lib/reporters/markdown.js |
/**
* Module dependencies.
*/
var Base = require('./base');
/**
* Expose `Markdown`.
*/
exports = module.exports = Markdown;
/**
* Initialize a new `Markdown` reporter.
*
* @param {Runner} runner
* @api public
*/
function Markdown(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
, level = 0;
function title(str) {
return Array(level).join('#') + ' ' + str;
}
runner.on('suite', function(suite){
++level;
process.stdout.write(title(suite.title) + '\n');
});
runner.on('suite end', function(suite){
--level;
});
runner.on('pass', function(test){
var code = clean(test.fn.toString());
process.stdout.write('\n ' + test.title + '.\n');
process.stdout.write('\n```js');
process.stdout.write(code + '\n');
process.stdout.write('```\n\n');
});
}
/**
* Strip the function definition from `str`,
* and re-indent for pre whitespace.
*/
function clean(str) {
str = str
.replace(/^function *\(.*\) *{/, '')
.replace(/\s+\}$/, '');
var spaces = str.match(/^\n?( *)/)[1].length
, re = new RegExp('^ {' + spaces + '}', 'gm');
str = str.replace(re, '');
return str;
} | JavaScript | 0 | @@ -55,16 +55,48 @@
./base')
+%0A , utils = require('../utils')
;%0A%0A/**%0A
@@ -524,16 +524,81 @@
+level;%0A
+ console.log('%3Ca name=%22' + utils.slug(suite.title) + '%22 /%3E');%0A
proc
@@ -797,36 +797,26 @@
-process.stdout.write('%5Cn ' +
+console.log('%25s.',
tes
@@ -826,16 +826,8 @@
itle
- + '.%5Cn'
);%0A
|
4789636f443fc9f15024d1864469805e9f076ba8 | fix only working once | lib/meteor-template-generator-view.js | lib/meteor-template-generator-view.js | 'use babel';
import fs from 'fs-plus';
export default class MeteorTemplateGeneratorView {
constructor() {
const div = document.createElement('div');
div.classList.add('meteor-template-generator');
const editor = document.createElement('atom-text-editor');
editor.setAttribute('mini', true);
div.appendChild(editor);
this.content = div;
this.panel = atom.workspace.addModalPanel({ item: this.content, visible: false });
// Needs major cleanup
atom.commands.add(div, 'core:confirm', this.confirm.bind(this));
atom.commands.add(div, 'core:cancel', this.cancel.bind(this));
this.editor = editor.model;
this.attach();
}
//
// static content() {
// return this.div({ class: 'meteor-template-generator' }, () => {
// this.tag('atom-text-editor', { mini: true, outlet: 'inputBox' });
// return this.div({ class: 'message', outlet: 'message' });
// },
// );
// }
// Returns an object that can be retrieved when package is activated
initialize() {
this.commandSubscription = atom.commands.add('atom-workspace', {
'meteor-template-generator:generate-template': () => this.attach(),
});
// @inputBox.on 'blur', => @close()
return atom.commands.add(this.element, {
'core:confirm': () => this.confirm(),
'core:cancel': () => this.close(),
},
);
}
// Tear down any state and detach
destroy() {
this.panel.destroy();
return this.commandSubscription.dispose();
}
attach() {
const editor = this.panel.item.firstChild.model;
editor.setText('Enter template name');
this.panel.show();
this.panel.item.firstChild.focus();
}
close() {
this.panel.hide();
}
cancel() {
this.close();
}
confirm() {
this.close();
const editor = this.panel.item.firstChild.model;
const text = editor.getText();
if (text) { this.generatePackage(text); }
}
getPath() {
return (atom.packages.getActivePackage('tree-view').mainModule.treeView.selectedPath);
}
getFileContentJs(name) {
return `Template.${name}.onCreated(function(){\n\n});\n\n
Template.${name}.onRendered(function(){\n\n});\n\n
Template.${name}.events({\n\n});\n\n
Template.${name}.helpers({\n\n});\n`;
}
getFileContentHTML(name) {
return `<template name=\"${name}\">\n\n</template>`;
}
generatePackage(name) {
const path = this.getPath();
if (!fs.isDirectorySync(path)) {
console.error('Not a directory');
return;
}
fs.writeFileSync(`${path}/${name}/${name}.js`, this.getFileContentJs(name));
fs.writeFileSync(`${path}/${name}/${name}.html`, this.getFileContentHTML(name));
}
}
| JavaScript | 0 | @@ -660,24 +660,47 @@
s.attach();%0A
+ this.initialize();%0A
%7D%0A //%0A /
@@ -1279,12 +1279,12 @@
his.
-elem
+cont
ent,
|
cdd4e204faf88cf640a6d4eeb0f252b3e0c0526e | Fix GestureEventListeners generated externs name. | lib/mixins/gesture-event-listeners.js | lib/mixins/gesture-event-listeners.js | /**
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import '../utils/boot.js';
import { dedupingMixin } from '../utils/mixin.js';
import { addListener, removeListener } from '../utils/gestures.js';
/**
* Element class mixin that provides API for adding Polymer's cross-platform
* gesture events to nodes.
*
* The API is designed to be compatible with override points implemented
* in `TemplateStamp` such that declarative event listeners in
* templates will support gesture events when this mixin is applied along with
* `TemplateStamp`.
*
* @mixinFunction
* @polymer
* @summary Element class mixin that provides API for adding Polymer's
* cross-platform
* gesture events to nodes
*/
const _GestureEventListeners = dedupingMixin(
/**
* @template T
* @param {function(new:T)} superClass Class to apply mixin to.
* @return {function(new:T)} superClass with mixin applied.
*/
(superClass) => {
/**
* @polymer
* @mixinClass
* @implements {Polymer_GestureEventListeners}
*/
class GestureEventListeners extends superClass {
/**
* Add the event listener to the node if it is a gestures event.
*
* @param {!EventTarget} node Node to add event listener to
* @param {string} eventName Name of event
* @param {function(!Event):void} handler Listener function to add
* @return {void}
* @override
*/
_addEventListenerToNode(node, eventName, handler) {
if (!addListener(node, eventName, handler)) {
super._addEventListenerToNode(node, eventName, handler);
}
}
/**
* Remove the event listener to the node if it is a gestures event.
*
* @param {!EventTarget} node Node to remove event listener from
* @param {string} eventName Name of event
* @param {function(!Event):void} handler Listener function to remove
* @return {void}
* @override
*/
_removeEventListenerFromNode(node, eventName, handler) {
if (!removeListener(node, eventName, handler)) {
super._removeEventListenerFromNode(node, eventName, handler);
}
}
}
return GestureEventListeners;
});
// Somehow _GestureEventListeners is incorrectly typed as *. For now add this
// cast.
/**
* @template T
* @param {function(new:T)} superClass Class to apply mixin to.
* @return {function(new:T)} superClass with mixin applied.
*/
export const GestureEventListeners = function(superClass) {
return _GestureEventListeners(superClass);
};
| JavaScript | 0 | @@ -1160,17 +1160,16 @@
/%0Aconst
-_
GestureE
@@ -2757,17 +2757,16 @@
Somehow
-_
GestureE
@@ -2983,21 +2983,15 @@
*/%0A
-export
const
+_
Gest
@@ -3042,17 +3042,16 @@
return
-_
GestureE
@@ -3080,8 +3080,67 @@
ss);%0A%7D;%0A
+%0Aexport %7B_GestureEventListeners as GestureEventListeners%7D;%0A
|
bc94cb1396a275e961e2845c983c837857ea30b6 | Validate users length. | backend/sockets/game.js | backend/sockets/game.js | "use strict";
var error = require('debug')('error');
var generate = require('./base');
var verbose = require('debug')('verbose:game');
var games = {};
var incrementId = 0;
// constants
var TurnLength = 15; // in seconds
var TeamSize = 3;
var NumberOfTeam = 2;
function Game(id, users, room) {
verbose('Game() constructor called with users: [%s]', users.map(function (user) {
return user.username;
}));
// TODO:validate users.length
this.id = id;
this.team = [
{ users: users.splice(0, 3) },
{ users: users }
];
this.room = room;
this.turn = 0;
this.joined = {};
function Timer(game) {
this.game = game;
this.handle = null;
}
Timer.prototype.fire = function () {
if (this.handle !== null) {
this.clear();
}
this.handle = setInterval(this.tick, 1000);
};
Timer.prototype.tick = function () {
this.game.turn++;
};
Timer.prototype.clear = function () {
if (this.handle !== null) {
clearInterval(this.handle);
this.handle = null;
}
};
this.timer = new Timer(this);
}
Game.prototype.sockets = function () {
return this.room.sockets;
};
Game.prototype.inTeam = function (num, who) {
return this.team[num].users.filter(function (user) {
return user.username === who.username;
}).length > 0;
};
Game.prototype.ours = function (whose) {
var team;
if (this.inTeam(0, whose)) {
team = this.team[0];
} else if (this.inTeam(1, whose)) {
team = this.team[1];
} else {
error('Game.ours(), no team available for user %s', whose.username);
return null;
}
team.users.forEach(function (user) {
// TODO: check 'current' true
user.me = user.username === whose.username;
});
return team;
};
Game.prototype.opponents = function (whose) {
var team;
if (this.inTeam(1, whose)) {
team = this.team[0];
} else if (this.inTeam(0, whose)) {
team = this.team[1];
} else {
error('Game.opponents(), no team available for user %s', whose.username);
return null;
}
team.users.forEach(function (user) {
// TODO: check 'current' true
user.me = false;
});
return team;
};
Game.prototype.socket = function (whose) {
return this.sockets().filter(function (socket) {
return socket.username === whose.username;
})[0];
};
Game.prototype.broadcast = function (from, eventName, data, postProcess,
exceptForMe) {
var that = this;
var handlerFactory = function (side) {
return function (user) {
data.side = side;
if (postProcess) {
postProcess(user, data);
}
if (!exceptForMe || user.username !== from.username) {
that.socket(user).emit(eventName, data);
}
};
};
this.ours(from).users.forEach(handlerFactory('ours'));
this.opponents(from).users.forEach(handlerFactory('opponents'));
};
Game.prototype.userJoined = function (socket) {
verbose('user(%s) didJoin', socket.username);
this.joined[socket.username] = true;
};
Game.prototype.isEveryoneJoined = function () {
return Object.keys(this.joined).length === this.sockets().length;
};
function updateClient(game, socket) {
if (!game instanceof Game) {
error('game.js, updateClient, check arguments');
}
verbose('game/update');
var update = function (target) {
target.emit('game/update', {
ours: game.ours(target),
opponents: game.opponents(target)
});
};
if (socket) {
update(socket);
} else {
game.sockets().forEach(update);
}
}
function sendNotice(game, text) {
game.sockets().forEach(function (socket) {
socket.emit('game/chat', {
side: 'ours',
chat: { type: 'notice', text: text }
});
});
}
function startGame(game) {
return function () {
verbose('emit game/start!');
game.room.emit('game/start');
};
}
function getProblem() {
var preparationDuration = 5;
return {
title: 'Largest prime factor',
description: 'What is the largest prime factor of the number 600851475143?',
preparationDuration: preparationDuration
};
}
function didJoin() {
verbose('game/didJoin');
var game = games[this.socket.gid];
game.userJoined(this.socket);
updateClient(game, this.socket);
if (game.isEveryoneJoined()) {
verbose('everyone joined! emit game/problem');
var problem = getProblem();
game.room.emit('game/problem', problem);
sendNotice(game, 'Game begins in ' + problem.preparationDuration + 's.');
// wait 1 more second and start a game.
setTimeout(startGame(game), 1000 * (problem.preparationDuration + 1));
}
}
function chat(data) {
verbose('game/chat');
var game = games[this.socket.gid];
game.broadcast(this.socket, 'game/chat', {
chat: {
type: 'normal',
username: this.socket.username,
text: data.text
}
}, function (receiver, data) {
data.chat.me = receiver.username === data.chat.username;
});
}
function code(data) {
verbose('game/code');
var game = games[this.socket.gid];
game.broadcast(this.socket, 'game/code', {code: data.code}, null, true);
}
module.exports = generate({
'game/didJoin': { name: 'didJoin', function: didJoin },
'game/chat': { name: 'chat', function: chat },
'game/code': { name: 'code', function: code }
});
function enterGame(context) {
var game = new Game(incrementId, context.team.members.map(function (username) {
return {
username: username,
me: false,
current: false
};
}), context.team.room);
verbose('a new game is made. id = %s', incrementId);
game.room.emit('game/join', null, function (socket) {
socket.gid = incrementId;
});
games[incrementId++] = game;
}
module.exports.start = enterGame;
| JavaScript | 0.000008 | @@ -414,37 +414,106 @@
%0A%0A
-// TODO:validate users.length
+if (users.length !== TeamSize * NumberOfTeam) %7B%0A error('invaild users.length');%0A return;%0A %7D
%0A%0A
|
def58b3dbb01965478db353fc520f98592ae6616 | Support JSX files. Fixes #6 | lib/standard-formatter.js | lib/standard-formatter.js | /*global atom*/
var pkgConfig = require('pkg-config')
module.exports = {
style: null,
formatters: {},
activate: function () {
this.commands = atom.commands.add('atom-workspace', 'standard-formatter:format', this.format.bind(this))
this.editorObserver = atom.workspace.observeTextEditors(this.handleEvents.bind(this))
},
deactivate: function () {
this.commands.dispose()
this.editorObserver.dispose()
},
requireFormatter: function (pkg) {
if (this.formatters[pkg]) {
return this.formatters[pkg]
}
this.formatters[pkg] = require(pkg)
return this.formatters[pkg]
},
format: function (options) {
if (options === undefined) {
options = {}
}
var selection = typeof options.selection === 'undefined' ? true : !!options.selection
var editor = atom.workspace.getActivePaneItem()
var selectedText = selection ? editor.getSelectedText() : null
var text = selectedText || editor.getText()
var cursorPosition = editor.getCursorScreenPosition()
var transformed = this.transformText(text)
if (selectedText) {
editor.setTextInBufferRange(editor.getSelectedBufferRange(), transformed)
} else {
editor.setText(transformed)
}
editor.setCursorScreenPosition(cursorPosition)
},
transformText: function (text) {
var checkStyleDevDependencies = atom.config.get('standard-formatter.checkStyleDevDependencies')
var style
var formatter
if (checkStyleDevDependencies) {
style = this.getStyleFromDevDeps()
} else {
style = atom.config.get('standard-formatter.style')
}
if (style === 'standard') {
formatter = this.requireFormatter('standard-format')
} else if (style === 'semi-standard') {
formatter = this.requireFormatter('semistandard-format')
} else {
return text
}
try {
return formatter.transform(text)
} catch (e) {
// Failed to transform, likely due to syntax error in `text`
return text
}
},
getStyleFromDevDeps: function () {
var editor = atom.workspace.getActiveTextEditor()
var filepath = editor.getPath()
var style = null
var devDeps = pkgConfig(null, {
cwd: filepath,
root: 'devDependencies',
cache: false
})
if (devDeps && (devDeps.standard || devDeps.semistandard)) {
if (devDeps.standard) {
style = 'standard'
} else {
style = 'semi-standard'
}
}
return style
},
handleEvents: function (editor) {
editor.getBuffer().onWillSave(function () {
var path = editor.getPath()
if (!path) return
var ext = path.substring(path.length - 3)
var formatOnSave = atom.config.get('standard-formatter.formatOnSave', {scope: editor.getRootScopeDescriptor()})
if (ext === '.js' && formatOnSave) {
this.format({selection: false})
}
}.bind(this))
},
config: {
formatOnSave: {
type: 'boolean',
default: false
},
style: {
type: 'string',
default: 'standard',
enum: ['standard', 'semi-standard']
},
checkStyleDevDependencies: {
type: 'boolean',
default: false
}
}
}
| JavaScript | 0 | @@ -47,16 +47,43 @@
config')
+%0Avar path = require('path')
%0A%0Amodule
@@ -127,16 +127,162 @@
ers: %7B%7D,
+%0A fileTypes: %5B'.js', '.jsx'%5D,%0A%0A fileSupported: function (file) %7B%0A var ext = path.extname(file)%0A return !!~this.fileTypes.indexOf(ext)%0A %7D,
%0A%0A acti
@@ -2794,56 +2794,8 @@
rn%0A%0A
- var ext = path.substring(path.length - 3)%0A
@@ -2923,37 +2923,48 @@
if (
-ext === '.js' && formatOnSave
+formatOnSave && this.fileSupported(path)
) %7B%0A
|
b1ffbc05edd9cf840927f4c85af925a881bce3ff | remove useless console.log | lib/translations/index.js | lib/translations/index.js | var fs = require('fs')
var path = require('path')
var defaults = require('defaults-deep')
var t = require('t-component')
/**
* Generate an Array with all the available localizations
*/
var available = fs.readdirSync(path.join(__dirname, 'lib')).map(function (p) {
return p.replace('.json', '')
})
console.log('=======================')
console.log(available)
console.log('=======================')
var defaultTranslations = require('./lib/en')
/**
* Load localization dictionaries to translation application
*/
available.forEach(function (locale) {
var translation = require('./lib/' + locale)
defaults(translation, defaultTranslations)
t[locale] = translation
})
module.exports.t = t
| JavaScript | 0.000002 | @@ -298,109 +298,8 @@
)%0A%7D)
-%0Aconsole.log('=======================')%0Aconsole.log(available)%0Aconsole.log('=======================')
%0A%0Ava
|
f8d197825869f25c0918eacb28ad54262277f977 | Provide string representation props for Boolean | lib/types-base/boolean.js | lib/types-base/boolean.js | 'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, extend = require('es5-ext/lib/Object/extend-properties')
, Base = require('./base')
, BooleanType;
module.exports = BooleanType = Base.$create('Boolean');
BooleanType._$construct.$setValue(Boolean);
BooleanType._is.$setValue(function (value) {
return (typeof value === 'boolean');
});
BooleanType._normalize.$setValue(function (value) { return Boolean(value); });
Object.defineProperties(BooleanType, {
coerce: d('c', BooleanType.normalize),
_serialize_: d('c', function (value) { return '0' + Number(value); })
});
extend(BooleanType, Boolean);
extend(BooleanType.prototype, Boolean.prototype);
delete BooleanType.prototype.toString;
BooleanType.prototype._toString.$setValue(Boolean.prototype.toString);
| JavaScript | 0.99942 | @@ -19,16 +19,20 @@
d
+
= requir
@@ -77,16 +77,20 @@
extend
+
= requir
@@ -142,16 +142,20 @@
Base
+
= requir
@@ -165,16 +165,109 @@
./base')
+%0A , StringType = require('./string')%0A , define = require('../_internals/define').define
%0A%0A , Bo
@@ -865,33 +865,454 @@
lue(
-Boolean.prototype.toString
+function () %7B%0A%09return this.valueOf() ? this.ns.trueString : this.ns.falseString;%0A%7D);%0Adefine(BooleanType, 'trueString');%0ABooleanType._trueString.$setValue('True');%0ABooleanType._trueString._ns.$setValue(StringType);%0ABooleanType._trueString._required.$setValue(true);%0Adefine(BooleanType, 'falseString');%0ABooleanType._falseString.$setValue('False');%0ABooleanType._falseString._ns.$setValue(StringType);%0ABooleanType._falseString._required.$setValue(true
);%0A
|
45a5bd8bfab8e4ec7ce0e3a9f6b685b1f4be58ef | Align the images horizontally. [ci skip] | lib/unexpectedResemble.js | lib/unexpectedResemble.js | var imageType = require('image-type'),
getTemporaryFilePath = require('gettemporaryfilepath'),
_ = require('underscore'),
fs = require('fs'),
resemble;
try {
resemble = require('resemble');
} catch (e) {
resemble = require('resemblejs');
}
module.exports = {
name: 'unexpected-resemble',
installInto: function (expect) {
expect.addAssertion('to resemble', function (expect, subject, otherImage, value) {
return expect.promise(function (resolve, reject) {
if (typeof value === 'number') {
value = {
isSameDimensions: true,
misMatchPercentage: expect.it('to be less than', value)
};
}
var resemblance = resemble.resemble(subject).compareTo(otherImage);
value = value ? _.extend({}, value) : {
isSameDimensions: true,
misMatchPercentage: expect.it('to be less than', 1)
};
['ignoreColors', 'ignoreAntialiasing'].forEach(function (optionName) {
if (value[optionName]) {
resemblance[optionName]();
delete value[optionName];
}
});
resemblance.onComplete(function (data) {
resolve(data);
});
}).then(function (data) {
var getImageDataUrl = data.getImageDataUrl;
// These are noisy in the 'to satisfy' diff output
delete data.getImageDataUrl;
delete data.pngStream;
return expect.withError(function () {
return expect(data, 'to satisfy', value);
}, function (err) {
expect.fail({
diff: function (output, diff, inspect, equal) {
var imageByName = {
actual: subject,
expected: otherImage,
diff: getImageDataUrl.call(data)
};
var originalDiff = (err.getDiff && err.getDiff()) || err.createDiff(output.clone(), diff, inspect, equal);
output.append(originalDiff.diff).nl(2);
Object.keys(imageByName).forEach(function (imageName) {
output.text(imageName, 'cyan').text(':').sp();
output.block(function () {
this.raw({
html: function () {
var image = imageByName[imageName];
if (typeof image === 'string') {
return '<img src="' + image.replace(/"/g, '"') + '">';
} else {
return inspect(image);
}
},
fallback: function () {
var image = imageByName[imageName];
if (typeof image === 'string' && /^data:/.test(image)) {
image = new Buffer(image.replace(/^data:image\/png;base64/, ''), 'base64');
}
if (Buffer.isBuffer(image)) {
var imageInfo = imageType(image);
if (fs.writeFileSync) {
var fileName = getTemporaryFilePath({ prefix: imageName + '-', suffix: '.' + imageInfo.ext });
fs.writeFileSync(fileName, image);
this.text(fileName);
} else {
this.append(inspect(image));
}
} else {
// File name or url
this.text(image);
}
}
});
}).nl(); // FIXME when .raw supports chaining
});
return {
inline: false,
diff: output
};
}
});
});
});
});
}
};
| JavaScript | 0.0002 | @@ -2167,16 +2167,267 @@
%7D;%0A%0A
+ var longestLabelLength = Object.keys(imageByName).reduce(function (longestSeenLabelLength, label) %7B%0A return Math.max(longestSeenLabelLength, label.length);%0A %7D, 0);%0A%0A
@@ -2782,16 +2782,58 @@
':').sp(
+longestLabelLength - imageName.length).sp(
);%0A%0A
|
7bd89774265209bf3f97b1b3168febff5fd2dce2 | Send 0 values to statsd in debug mode | lib/windshaft/profiler.js | lib/windshaft/profiler.js | var debug = 0;
function Profiler(opts) {
if ( opts.statsd_client ) {
this.statsd_client = opts.statsd_client;
}
this.events = [];
this.taskcount = 0;
}
Profiler.prototype.done = function(what) {
var now = Date.now();
if ( debug ) {
console.log("prf " + now + " done " + what);
}
var item = { name:what, time:now };
this.events.push(item);
}
Profiler.prototype.end = function() {
if ( ! this.taskcount ) {
console.log("prf Unbalanced end task event refused");
return;
}
--this.taskcount;
var now = Date.now();
if ( debug ) {
console.log("prf " + now + " end task ");
}
var item = { time:now, end:1 }
this.events.push(item);
}
Profiler.prototype.start = function(what) {
var now = Date.now();
if ( debug ) {
console.log("prf " + now + " start task " + what);
}
var item = { time:now, start:1, name:what }
this.events.push(item);
++this.taskcount;
}
Profiler.prototype.sendStats = function() {
if ( ! this.statsd_client ) return;
if ( debug ) {
console.log("prf " + Date.now() + " SEND STATS! ");
}
var tasks = [];
var prefix = [];
var prefix_string = '';
var prevtime = 0;
for (var i=0; i<this.events.length; ++i) {
var ev = this.events[i];
var t = ev.time;
if ( ev.start ) { // start of a new sub task
var tname = ev.name;
tasks.push({ start:t, name:tname });
if ( debug ) {
console.log("prf Task " + tname + " starts at " + t);
}
prefix.push(tname);
prefix_string = prefix.join('.');
}
else if ( ev.end ) { // end of a new sub task
var task = tasks.pop();
if ( task ) {
var elapsed = t - task.start;
if ( debug ) {
console.log("prf Task " + tname + " stops at " + t + " elapsed: " + elapsed);
}
if ( elapsed ) {
var lbl = prefix_string + '.time';
if ( debug ) {
console.log("prf Sending (task) " + lbl + " " + elapsed);
}
this.statsd_client.timing(lbl, elapsed)
}
prefix.pop();
prefix_string = prefix.join('.');
} else {
console.log("prf Unbalanced end task event found");
}
}
else {
var what = ev.name;
var elapsed = t - prevtime;
if ( elapsed ) {
var lbl = prefix_string + '.' + what + '.time';
if ( debug ) {
console.log("prf Sending (done) " + lbl + " " + elapsed);
}
this.statsd_client.timing(lbl, elapsed)
}
}
prevtime = t;
}
// In case anything is missing...
while ( task = tasks.pop() ) {
var tname = task.name;
var elapsed = t - task.start;
if ( debug ) {
console.log("prf Task " + tname + " stops (uncleanly) at " + t + " elapsed: " + elapsed + " " + tasks.length + " more open tasks in the queue");
}
if ( elapsed ) {
var lbl = prefix_string + '.time';
if ( debug ) {
console.log("prf Sending (task) " + lbl + " " + elapsed);
}
this.statsd_client.timing(lbl, elapsed)
}
prefix.pop();
prefix_string = prefix.join('.');
}
}
Profiler.prototype.toString = function() {
var sitems = [];
var t0;
var prevt;
var ttime = 0;
for (var i=0; i<this.events.length; ++i) {
var ev = this.events[i];
var t = ev.time;
if ( ! i ) t0 = t;
// we're only interested in abs times
if ( ev.start || ev.end ) continue;
var el = ev.time - prevt;
if ( el ) { // skip steps taking no computable time
sitems.push(ev.name + ':' + el);
ttime += el;
}
prevt = t;
}
var s = 'TOT:'+ttime+';'+sitems.join(';');
if ( debug ) {
console.log("prf toString " + s);
}
return s;
}
module.exports = Profiler;
| JavaScript | 0 | @@ -1807,32 +1807,41 @@
if ( elapsed
+%7C%7C debug
) %7B%0A va
@@ -2275,32 +2275,41 @@
if ( elapsed
+%7C%7C debug
) %7B%0A var
@@ -2873,16 +2873,25 @@
elapsed
+%7C%7C debug
) %7B%0A
|
1e8c481c3027ff9cb1a09431259019068e828b04 | remove log from json-editor TASK-2253 | src/webcomponents/commons/json-editor.js | src/webcomponents/commons/json-editor.js | /*
* Copyright 2015-2016 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {html, LitElement} from "lit";
import {JSONEditor} from "vanilla-jsoneditor";
import NotificationUtils from "./utils/notification-utils.js";
import UtilsNew from "../../core/utils-new.js";
import LitUtils from "./utils/lit-utils.js";
import "../download-button.js";
export default class JsonEditor extends LitElement {
constructor() {
super();
this.#init();
}
createRenderRoot() {
return this;
}
static get properties() {
return {
data: {
type: Object
},
active: {
type: Boolean
},
config: {
type: Object
}
};
}
#init() {
this._prefix = UtilsNew.randomString(8);
this.jsonEditor = null;
this.jsonEditorId = this._prefix + "jsoneditor";
this._data = "";
this._config = this.getDefaultConfig();
}
update(changedProperties) {
if (changedProperties.has("config")) {
this._config = {...this.getDefaultConfig(), ...this.config};
}
super.update(changedProperties);
}
updated(changedProperties) {
if (changedProperties.has("data")) {
// If element exist and the jsonEditor Obj not exist
if (document.getElementById(this.jsonEditorId) && !this.jsonEditor) {
this.initJsonEditor();
}
// We need to check if the current JSON displayed is the same that the one being passed.
// This avoids the cursor to move to the beginning.
if (this.jsonEditor && !UtilsNew.isEqual(JSON.stringify(this._data), JSON.stringify(this.data))) {
this.jsonEditor.update({json: this.data});
}
}
}
initJsonEditor() {
const content = {
json: this.data ? this.data : {}
};
const editorElm = document.getElementById(this.jsonEditorId);
// Create Editor
this.jsonEditor = new JSONEditor({
target: editorElm,
props: {
content,
mode: this._config?.mode || "text",
indentation: this._config?.indentation || 4,
readOnly: this._config?.readOnly ?? false,
onChange: (updatedContent, previousContent, {contentErrors, patchResult}) =>
this.onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}),
onError: err => {
NotificationUtils.dispatch(this, NotificationUtils.NOTIFY_ERROR, {
message: err
});
},
onRenderMenu: (mode, items) => {
// Remove transforms we don't need for the moment
return items.filter(item => item.className !== "jse-transform");
},
}
});
}
onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}) {
console.log("onChange", {updatedContent, previousContent, contentErrors, patchResult});
// updatedContent is an object which content 2 props (text & json)
this.data = updatedContent.text ? JSON.parse(updatedContent.text) : updatedContent.json;
// Copy the updated content
this._data = updatedContent.text ? JSON.parse(updatedContent.text) : updatedContent.json;
LitUtils.dispatchCustomEvent(this, "fieldChange", {
json: {...this.data},
text: updatedContent?.text
}, null);
}
render() {
if (!this.data && !this.jsonEditor) {
return html`<h4>No valid data found</h4>`;
}
return html`
${this._config.showDownloadButton ? html`
<div class="text-right">
<download-button
.json="${this.data}"
class="btn-sm">
</download-button>
</div>
` : null
}
<div style="padding-top: 10px" id="${this.jsonEditorId}"></div>
`;
}
getDefaultConfig() {
return {
mode: "text", // Two accepted values: text, tree.
indentation: 4,
readOnly: false,
showDownloadButton: true
};
}
}
customElements.define("json-editor", JsonEditor);
| JavaScript | 0.000048 | @@ -3620,104 +3620,8 @@
) %7B%0A
- console.log(%22onChange%22, %7BupdatedContent, previousContent, contentErrors, patchResult%7D);%0A
|
2cbc24c30b2cb082cb776f176d46e5ba7b6995e2 | Enable "remember me" | config/default.js | config/default.js | const project_name = 'nidarholm';
const serializers = {
req: (req) => ({
method: req.method,
url: req.url,
}),
res: (res) => ({
statusCode: res.statusCode,
}),
};
module.exports = {
auth: {
facebook: {
clientId: '291636897704096',
clientSecret: '39b8e7aa941fa3c74caba6e3d1ecc3d4',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
},
google: {
clientId: '504721013884-86lf0uioi6o4diok2e6l6mjap3evjf52.apps.googleusercontent.com',
clientSecret: 'o7oG428qOXvCsNPtBfDo4Owz',
callbackURL: 'http://localhost:3000/auth/google/callback',
},
twitter: {
clientId: 'Zo1Rbx6sp1j9YTSoqmAapc5yV',
clientSecret: 'EzcmNycN1E50JFZKcRF8SyYW1s1bSgs6eztTqv8VQukO2ZxxUc',
callbackURL: 'http://localhost:3000/auth/twitter/callback',
},
},
bunyan: {
level: 'info',
name: 'nidarholm',
serializers,
},
'bunyan-express': {
excludes: [
'body',
'http-version',
'req-headers',
'res-headers',
],
format: ':remote-address :incoming :method :url HTTP/:http-version :status-code :res-headers[content-length] :referer :user-agent[family] :user-agent[major].:user-agent[minor] :user-agent[os] :response-time ms',
},
express: {
port: 3000,
trust_proxy: true,
session: {
maxAge: 1000 * 60 * 60 * 24 * 30,
name: 'nidarholm.sid',
path: '/',
resave: false,
rolling: true,
saveUninitialized: false,
secret: 'sessionsecret',
httpOnly: true,
secure: true, // false in development
},
},
files: {
raw_prefix: '/home/sigurdga/Prosjekter/nidarholmjs/uploaded_files',
normal_prefix: '/home/sigurdga/Prosjekter/nidarholmjs/uploaded_files/normal',
large_prefix: '/home/sigurdga/Prosjekter/nidarholmjs/uploaded_files/large',
thumbnail_prefix: '/home/sigurdga/Prosjekter/nidarholmjs/uploaded_files/thumbnail',
},
graphql: {
graphiql: false,
pretty: false,
},
html: {
style: true,
},
mongodb: {
servers: ['mongodb://localhost/nidarholm-dev'],
replset: null,
},
news_tag: 'nyheter',
organization: 'nidarholm',
profile_picture_tag: 'profilbilde',
redis: {
host: 'localhost',
port: 6379,
pass: undefined,
},
};
/* secret gen: cat /dev/urandom| base64 | fold -w 64 */
| JavaScript | 0.000015 | @@ -913,32 +913,59 @@
ck',%0A %7D,%0A
+ remember_me: true,%0A
%7D,%0A bunya
|
f38dd4434356f2b0cbd355599ba74ba3bb4866ae | Include reason for replication failure in _replicator doc | script/test/replicator_db_invalid_filter.js | script/test/replicator_db_invalid_filter.js | // 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.
couchTests.replicator_db_invalid_filter = function(debug) {
if (debug) debugger;
var populate_db = replicator_db.populate_db;
var docs1 = replicator_db.docs1;
var dbA = replicator_db.dbA;
var dbB = replicator_db.dbB;
var repDb = replicator_db.repDb;
var usersDb = replicator_db.usersDb;
var wait = replicator_db.wait;
var waitForRep = replicator_db.waitForRep;
var waitForSeq = replicator_db.waitForSeq;
var wait_rep_doc = replicator_db.wait_rep_doc;
function test_invalid_filter() {
// COUCHDB-1199 - replication document with a filter field that was invalid
// crashed the CouchDB server.
var repDoc1 = {
_id: "rep1",
source: "couch_foo_test_db",
target: "couch_bar_test_db",
filter: "test/foofilter"
};
TEquals(true, repDb.save(repDoc1).ok);
waitForRep(repDb, repDoc1, "error");
repDoc1 = repDb.open(repDoc1._id);
TEquals("undefined", typeof repDoc1._replication_id);
TEquals("error", repDoc1._replication_state);
populate_db(dbA, docs1);
populate_db(dbB, []);
var repDoc2 = {
_id: "rep2",
source: dbA.name,
target: dbB.name,
filter: "test/foofilter"
};
TEquals(true, repDb.save(repDoc2).ok);
waitForRep(repDb, repDoc2, "error");
repDoc2 = repDb.open(repDoc2._id);
TEquals("undefined", typeof repDoc2._replication_id);
TEquals("error", repDoc2._replication_state);
var ddoc = {
_id: "_design/mydesign",
language : "javascript",
filters : {
myfilter : (function(doc, req) {
return true;
}).toString()
}
};
TEquals(true, dbA.save(ddoc).ok);
var repDoc3 = {
_id: "rep3",
source: dbA.name,
target: dbB.name,
filter: "mydesign/myfilter"
};
TEquals(true, repDb.save(repDoc3).ok);
waitForRep(repDb, repDoc3, "completed");
repDoc3 = repDb.open(repDoc3._id);
TEquals("string", typeof repDoc3._replication_id);
TEquals("completed", repDoc3._replication_state);
}
var server_config = [
{
section: "couch_httpd_auth",
key: "iterations",
value: "1"
},
{
section: "replicator",
key: "db",
value: repDb.name
},
{
section: "couch_httpd_auth",
key: "authentication_db",
value: usersDb.name
}
];
repDb.deleteDb();
run_on_modified_server(server_config, test_invalid_filter);
// cleanup
repDb.deleteDb();
dbA.deleteDb();
dbB.deleteDb();
usersDb.deleteDb();
} | JavaScript | 0 | @@ -1552,24 +1552,180 @@
tion_state);
+%0A TEquals(%22Could not open source database %60couch_foo_test_db%60: %7Bdb_not_found,%3C%3C%5C%22couch_foo_test_db%5C%22%3E%3E%7D%22,%0A repDoc1._replication_state_reason);
%0A%0A popula
@@ -2131,16 +2131,187 @@
_state);
+%0A TEquals(%22Couldn't open document %60_design/test%60 from source database %60test_suite_rep_db_a%60: %7Berror,%3C%3C%5C%22not_found%5C%22%3E%3E%7D%22,%0A repDoc2._replication_state_reason);
%0A%0A va
|
5c06b60b12006ff9fc3cf423152f664280f42ca1 | Remove export.default | scripts/update-export-default-typescript.js | scripts/update-export-default-typescript.js | #!/usr/bin/env node
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const load = require('load-json-file');
const camelcase = require('camelcase');
// Update index.js export default module (Typescript compatible)
glob.sync(path.join(__dirname, '..', 'packages', 'turf-*', 'index.js')).forEach(filepath => {
let index = fs.readFileSync(filepath, 'utf8');
const dir = path.parse(filepath).dir;
const pckg = load.sync(path.join(dir, 'package.json'));
const name = camelcase(pckg.name).replace('@turf/', '');
// Modules without named export function
if (index.includes('export default function (')) {
// duplicate function names
if (index.includes('function ' + name)) {
throw new Error('duplicate function name', name);
}
index = index.replace('export default function (', `function ${name}(`);
index += `\nexport default ${name};`;
index += `\nmodule.exports.default = ${name};\n`;
fs.writeFileSync(filepath, index);
}
// Modules with named export function
if (index.includes(`export default function ${name}(`)) {
index = index.replace(`export default function ${name}(`, `function ${name}(`);
index += `\nexport default ${name};`;
index += `\nmodule.exports.default = ${name};\n`;
fs.writeFileSync(filepath, index);
}
if (index.includes('export default') && !index.includes('module.exports.default')) {
throw new Error('missing module.exports.default =', name);
}
});
| JavaScript | 0.000001 | @@ -1418,31 +1418,39 @@
x.includes('
+module.
export
-
+s.
default') &&
@@ -1450,29 +1450,75 @@
lt')
- && !index.includes('
+) %7B%0A console.log(name);%0A // throw new Error('invalid
modu
@@ -1539,47 +1539,120 @@
ault
-')) %7B
+ =', name);
%0A
+%7D%0A
-throw new Error('missing
+// Remove module.exports.default (will be handled with Rollup)%0A index = index.replace(%60
modu
@@ -1671,28 +1671,101 @@
efault =
-',
+ $%7B
name
-);%0A %7D
+%7D;%60, '');%0A index = index.trim() + '%5Cn';%0A fs.writeFileSync(filepath, index);
%0A%7D);%0A
|
a84f76043cd16166afc2242f07184b4c2f2c2967 | Add reject error handler to import wrapper | server/build/babel/plugins/handle-import.js | server/build/babel/plugins/handle-import.js | // Based on https://github.com/airbnb/babel-plugin-dynamic-import-webpack
// We've added support for SSR with this version
import template from 'babel-template'
import syntax from 'babel-plugin-syntax-dynamic-import'
import { dirname, relative, resolve } from 'path'
const TYPE_IMPORT = 'Import'
const buildImport = (args) => (template(`
(
typeof window === 'undefined' ?
new (require('next/same-loop-promise').default)((resolve, reject) => {
eval('require.ensure = function (deps, callback) { callback(require) }')
require.ensure([], (require) => {
let m = require(SOURCE)
m.__webpackChunkName = '${args.name}.js'
resolve(m);
}, 'chunks/${args.name}.js');
})
:
new (require('next/same-loop-promise').default)((resolve, reject) => {
const weakId = require.resolveWeak(SOURCE)
try {
const weakModule = __webpack_require__(weakId)
return resolve(weakModule)
} catch (err) {}
require.ensure([], (require) => {
try {
let m = require(SOURCE)
resolve(m)
} catch(error) {
reject(error)
}
}, 'chunks/${args.name}.js');
})
)
`))
export function getModulePath (sourceFilename, moduleName) {
// resolve only if it's a local module
const modulePath = (moduleName[0] === '.')
? resolve(dirname(sourceFilename), moduleName) : moduleName
const cleanedModulePath = modulePath
.replace(/(index){0,1}\.js$/, '') // remove .js, index.js
.replace(/[/\\]$/, '') // remove end slash
return cleanedModulePath
}
export default () => ({
inherits: syntax,
visitor: {
CallExpression (path, state) {
if (path.node.callee.type === TYPE_IMPORT) {
const { opts } = path.hub.file
const arg = path.node.arguments[0]
const chunknameComment = arg.leadingComments && arg.leadingComments.map(({value}) => value.trim()).filter((value) => /webpackChunkName:/.test(value))[0]
const moduleRequest = arg.value
let chunkName
if (chunknameComment) {
chunkName = JSON.parse(chunknameComment.replace(/webpackChunkName:\s*/, ''))
} else {
const currentDir = dirname(opts.filename)
const modulePath = resolve(currentDir, moduleRequest)
chunkName = relative(opts.sourceRoot || process.cwd(), modulePath).replace(/[^\w]/g, '-')
}
const newImport = buildImport({
name: chunkName
})({
SOURCE: path.node.arguments
})
path.replaceWith(newImport)
}
}
}
})
| JavaScript | 0 | @@ -1181,32 +1181,40 @@
%7D%0A %7D,
+ reject,
'chunks/$%7Bargs.
|
f4c3c4005d8a53fcd727e255dc64f424f729ad90 | support react v0.13.x | src/TextareaAutosize.js | src/TextareaAutosize.js | import React from 'react';
import autosize from 'autosize';
const UPDATE = 'autosize:update',
DESTROY = 'autosize:destroy',
RESIZED = 'autosize:resized';
const TextareaAutosize = React.createClass({
propTypes: {
onResize: React.PropTypes.func
},
getDefaultProps() {
return {
rows: 1
};
},
componentDidMount() {
autosize(this.refs.textarea);
if (this.props.onResize) {
this.refs.textarea.addEventListener(RESIZED, this.props.onResize);
}
},
componentWillUnmount() {
if (this.props.onResize) {
this.refs.textarea.removeEventListener(RESIZED, this.props.onResize);
}
this.dispatchEvent(DESTROY);
},
dispatchEvent(EVENT_TYPE, defer) {
const event = document.createEvent('Event');
event.initEvent(EVENT_TYPE, true, false);
const dispatch = () => this.refs.textarea.dispatchEvent(event);
if (defer) {
setTimeout(dispatch);
} else {
dispatch();
}
},
getValue(props) {
if (props) {
return props.valueLink ? props.valueLink.value : props.value;
}
},
render() {
return (
<textarea {...this.props} ref='textarea'>
{this.props.children}
</textarea>
);
},
componentWillReceiveProps(nextProps) {
if (this.getValue(nextProps) !== this.getValue(this.props)) {
this.dispatchEvent(UPDATE, true);
}
},
});
export default TextareaAutosize;
| JavaScript | 0 | @@ -309,32 +309,176 @@
1%0A %7D;%0A %7D,%0A%0A
+ getTextareaDOMNode() %7B%0A return this.refs.textarea.nodeType === 1 ?%0A this.refs.textarea :%0A this.refs.textarea.getDOMNode();%0A %7D,%0A%0A
componentDidMo
@@ -503,29 +503,36 @@
ze(this.
-refs.t
+getT
extarea
+DOMNode()
);%0A i
@@ -568,29 +568,36 @@
this.
-refs.t
+getT
extarea
+DOMNode()
.addEven
@@ -718,29 +718,36 @@
this.
-refs.t
+getT
extarea
+DOMNode()
.removeE
@@ -999,29 +999,36 @@
=%3E this.
-refs.t
+getT
extarea
+DOMNode()
.dispatc
@@ -1538,17 +1538,16 @@
%7D%0A %7D
-,
%0A%0A%7D);%0A%0Ae
|
3b8647f3bdc33b75ea87adf0a3ddb7076a773dc7 | Remove writable flag because it's incompatible with getters and setters | JoiModel.js | JoiModel.js | require('babel-register');
const Joi = require('joi');
const util = require('util');
const _ = require('lodash');
const hashAString = require('string-hash');
const schema = Joi.object().keys({
a: Joi.boolean().valid(true),
b: Joi.alternatives().try([
Joi.string().regex(/^a/),
Joi.string().valid('boom')
]),
c: Joi.number().valid(5),
d: Joi.string().valid('key'),
e: Joi.object().keys({
hi: Joi.string(),
hello: Joi.number()
})
});
// Cache of validated values for each model
const validatedValues = {};
function createJoiModel(schema, defaults) {
// Check if schema is a Joi schema
if (!schema.isJoi && !(schema._type === 'object')) {
throw new Error('Schema passed to joi-model2 must be a Joi schema.');
}
// Check if default object is valid itself
if (defaults) {
const validation = Joi.validate(schema, defaults);
if (validation.error) {
throw new Error('JoiModel default values do not validate against given schema \n' + validation.error);
}
}
// Create a shadow object that
const shadowObj = _.cloneDeep(defaults || {});
// TODO make real random UUIDs
const modelUUID = '12345';
let JoiModel = {
_UUID: modelUUID,
_shadowObj: shadowObj
};
// Create an object to store cached values
validatedValues[ modelUUID ] = {};
const keys = Object.keys(schema.children);
for (let key of keys) {
Object.defineProperty(JoiModel, key, {
enumerable: true,
writable: true,
get() {
return this[key];
},
set(val) {
const _this = this;
const hash = hashAString(JSON.stringify(val));
// If this value has already been validated for this key before, then just set the value
if (validatedValues[ modelUUID ][hash]) {
return _this[ key ] = val;
}
// Do the validation against the shadow object
const oldVal = _this[key];
JoiModel._shadowObj[key] = val;
const validation = Joi.validate(schema, JoiModel._shadowObj);
if (validation.error) {
JoiModel._shadowObj[ key ] = oldVal;
throw new Error('Attempted to change a property to an invalid value: \n' + validation.error);
}
else {
// Cache the validated value
validatedValues[ modelUUID ][hash] = true;
return _this[ key ] = val;
}
}
});
}
JoiModel.toJSON = function() {
};
return JoiModel;
}
export default createJoiModel; | JavaScript | 0 | @@ -1561,36 +1561,8 @@
ue,%0A
- writable: true,%0A
|
aeabcfa4a246adc952bd8b1314ee7bd950b41807 | Disable debug | src/app/index.config.js | src/app/index.config.js | export function config ($locationProvider, $logProvider, toastrConfig) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
// Set options third-party lib
toastrConfig.allowHtml = true;
toastrConfig.timeOut = 3000;
toastrConfig.positionClass = 'toast-top-right';
toastrConfig.preventDuplicates = true;
toastrConfig.progressBar = true;
$locationProvider.html5Mode(true);
}
| JavaScript | 0.000003 | @@ -124,19 +124,20 @@
Enabled(
-tru
+fals
e);%0A%0A /
|
979717d7e60ccd59d886e05b32acdb6ed3de5636 | update settings-tab styling && remove compiler option/action (that has been moved to the compile tab) | src/app/settings-tab.js | src/app/settings-tab.js | var yo = require('yo-yo')
// -------------- styling ----------------------
var csjs = require('csjs-inject')
var styleGuide = require('./style-guide')
var styles = styleGuide()
var css = csjs`
.settingsTabView {
padding: 2%;
display: flex;
}
.info extends ${styles.infoTextBox} {
margin-bottom: 2em;
}
.crow {
margin-top: 1em;
display: flex;
}
.select extends ${styles.dropdown} {
float: left;
max-width: 90%;
}
.button extends ${styles.button} {
background-color: #C6CFF7;
width: 100%;
align-self: center;
text-align: -webkit-center;
}
.col1 extends ${styles.titleL} {
float: left;
align-self: center;
}
.checkboxText {
margin-left: 3px;
}
.compilationWarning extends ${styles.warningTextBox} {
margin-top: 1em;
margin-left: 0.5em;
}
}
`
module.exports = SettingsTab
function SettingsTab (container, appAPI, appEvents, opts) {
if (typeof container === 'string') container = document.querySelector(container)
if (!container) throw new Error('no container given')
var warnCompilationSlow = yo`<div id="warnCompilationSlow"></div>`
warnCompilationSlow.className = css.compilationWarning
appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) {
var settingsView = document.querySelector('#header #menu .settingsView')
if (speed > 1000) {
warnCompilationSlow.innerHTML = `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`
warnCompilationSlow.style.visibility = 'visible'
settingsView.style.color = '#FF8B8B'
} else {
warnCompilationSlow.innerHTML = ''
warnCompilationSlow.style.visibility = 'hidden'
settingsView.style.color = ''
}
})
var el = yo`
<div class="${css.settingsTabView} "id="settingsView">
<div class="${css.info}">
<div>Your current Solidity version is</div>
<div id="version"></div>
</div>
<div class="${css.crow}">
<select class="${css.select}" id="versionSelector"></select>
</div>
<div class="${css.crow}">
<div><input class="${css.col1}" id="editorWrap" type="checkbox"></div>
<span class="${css.checkboxText}">Text Wrap</span>
</div>
<div class="${css.crow}">
<div><input class="${css.col1}" id="optimize" type="checkbox"></div>
<span class="${css.checkboxText}">Enable Optimization</span>
</div>
<div class="${css.crow}">
<div><input class="${css.col1}" id="autoCompile" type="checkbox" checked></div>
<span class="${css.checkboxText}">Auto Compile</span>
</div>
</div>
<div class="${css.crow}">
<div class="${css.button} "id="compile" title="Compile source code">Compile</div>
</div>
${warnCompilationSlow}
</div>
`
container.appendChild(el)
}
| JavaScript | 0 | @@ -309,24 +309,52 @@
ottom: 2em;%0A
+ word-break: break-word;%0A
%7D%0A .crow
@@ -483,1297 +483,239 @@
%7D%0A
- .button extends $%7Bstyles.button%7D %7B%0A background-color: #C6CFF7;%0A width: 100%25;%0A align-self: center;%0A text-align: -webkit-center;%0A %7D%0A .col1 extends $%7Bstyles.titleL%7D %7B%0A float: left;%0A align-self: center;%0A %7D%0A .checkboxText %7B%0A margin-left: 3px;%0A %7D%0A .compilationWarning extends $%7Bstyles.warningTextBox%7D %7B%0A margin-top: 1em;%0A margin-left: 0.5em;%0A %7D%0A%7D%0A%60%0Amodule.exports = SettingsTab%0A%0Afunction SettingsTab (container, appAPI, appEvents, opts) %7B%0A if (typeof container === 'string') container = document.querySelector(container)%0A if (!container) throw new Error('no container given')%0A%0A var warnCompilationSlow = yo%60%3Cdiv id=%22warnCompilationSlow%22%3E%3C/div%3E%60%0A warnCompilationSlow.className = css.compilationWarning%0A appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) %7B%0A var settingsView = document.querySelector('#header #menu .settingsView')%0A if (speed %3E 1000) %7B%0A warnCompilationSlow.innerHTML = %60Last compilation took $%7Bspeed%7Dms. We suggest to turn off autocompilation.%60%0A warnCompilationSlow.style.visibility = 'visible'%0A settingsView.style.color = '#FF8B8B'%0A %7D else %7B%0A warnCompilationSlow.innerHTML = ''%0A warnCompilationSlow.style.visibility = 'hidden'%0A settingsView.style.color = ''%0A %7D%0A %7D
+%7D%0A%60%0Amodule.exports = SettingsTab%0A%0Afunction SettingsTab (container, appAPI, appEvents, opts) %7B%0A if (typeof container === 'string') container = document.querySelector(container)%0A if (!container) throw new Error('no container given'
)%0A%0A
@@ -1409,380 +1409,8 @@
iv%3E%0A
- %3Cdiv class=%22$%7Bcss.crow%7D%22%3E%0A %3Cdiv%3E%3Cinput class=%22$%7Bcss.col1%7D%22 id=%22autoCompile%22 type=%22checkbox%22 checked%3E%3C/div%3E%0A %3Cspan class=%22$%7Bcss.checkboxText%7D%22%3EAuto Compile%3C/span%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3Cdiv class=%22$%7Bcss.crow%7D%22%3E%0A %3Cdiv class=%22$%7Bcss.button%7D %22id=%22compile%22 title=%22Compile source code%22%3ECompile%3C/div%3E%0A %3C/div%3E%0A $%7BwarnCompilationSlow%7D%0A
|
df19d00b8758a88018fe8eca124c134a440c3534 | add a new test for the nullSpace() operator | src/arithmetic/types.js | src/arithmetic/types.js | const base = require('./base');
const mats = require('./matrices');
export const integerMethods = base.arithmetic().register(
require('./integers').methods()
);
export const integers = integerMethods.ops();
export const rationalMethods = integerMethods.register(
require('./fractions').methods(integers, ['Integer', 'LongInt'], 'Fraction')
);
export const rationals = rationalMethods.ops();
export const matrixMethods = rationalMethods.register(
mats.methods(rationals, ['Integer', 'LongInt', 'Fraction'], true)
);
export const matrices = matrixMethods.ops();
export const intMatrixMethods = integerMethods.register(
mats.methods(integers, ['Integer', 'LongInt'], false)
);
export const intMatrices = intMatrixMethods.ops();
export const floatMethods = base.arithmetic().register(
require('./floats').methods()
);
export const floats = floatMethods.ops();
export const floatMatrixMethods = floatMethods.register(
mats.methods(floats, ['Integer', 'Float'], true, Math.pow(2, -50))
);
export const floatMatrices = floatMatrixMethods.ops();
if (require.main == module) {
Array.prototype.toString = function() {
return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
};
const ops = matrices;
const V = [1, 2, 3];
const M = [[1, 2, 3], [4, 5, 6]];
console.log(ops.shape(V));
console.log(ops.negative(V));
console.log(ops.transposed(V));
console.log(ops.squareNorm(V));
console.log(ops.plus(V, [3, 2, 1]));
console.log(ops.plus(V, 2));
console.log(ops.minus(V, [0, 1, 2]));
console.log(ops.minus(V, 1));
console.log(ops.minus(1, V));
console.log(ops.idiv(V, 2));
console.log(ops.crossProduct([1, 0, 0], [1, 2, 0]));
console.log();
console.log(ops.negative(M));
console.log(ops.shape(M));
console.log(ops.transposed(M));
console.log(ops.squareNorm(M));
console.log(ops.plus(M, [[9, 8, 7], [6, 5, 4]]));
console.log(ops.plus(M, 2));
console.log(ops.minus(M, [[0, 1, 2], [3, 4, 5]]));
console.log(ops.minus(M, 1));
console.log(ops.minus(1, M));
console.log();
console.log(ops.times(V, V));
console.log(ops.times(M, V));
console.log(ops.times(V, ops.transposed(M)));
console.log(ops.times(M, ops.transposed(M)));
const A = [[1,2,3],[0,4,5],[6,0,7]];
const T = ops.triangulation(A);
console.log(`T.R = ${T.R}`);
console.log(`T.U = ${T.U}`);
console.log(`T.sign = ${T.sign}`);
console.log(ops.rank(A));
console.log(ops.determinant(A));
console.log();
const b = [1, 1, 1];
const v = ops.solve(A, b);
console.log(`${A} *\n${v} =\n${ops.times(A, v)}\n`);
const Ainv = ops.inverse(A);
console.log(`${A} *\n${Ainv} =\n${ops.times(A, Ainv)}\n`);
const testNullSpace = B => {
const N = ops.nullSpace(B);
console.log(`${B} *\n${N} =\n${N ? ops.times(B, N) : N}\n`);
}
testNullSpace([[1,2,3], [2,4,6], [3,6,9]]);
testNullSpace([[1,2,3,1], [4,5,6,1], [7,8,9,1]]);
const fops = floatMatrices;
console.log();
const B = fops.inverse(A);
console.log(`${A} *`);
console.log(`${B} =`);
console.log(`${fops.times(A, B)}`);
console.log();
const O = fops.orthonormalized(A);
const P = fops.cleanup(fops.times(O, fops.transposed(O)));
console.log(`O = ${O}`);
console.log(`O * O.T = ${P}`);
const iops = intMatrices;
console.log(JSON.stringify(iops.triangulation(A)));
}
| JavaScript | 0.000002 | @@ -2881,16 +2881,44 @@
9,1%5D%5D);%0A
+ testNullSpace(%5B%5B0,2,0%5D%5D);%0A
%0A%0A cons
|
6ca934b7d8c14f365243178bd393dd7f9b5bd76b | Reduce max of recentlyVisited to 5 | server/services/recently-visited-limiter.js | server/services/recently-visited-limiter.js | // Service: Limits LRU recentlyVisited lists up to max 10 (configurable) items
'use strict';
var ensureNaturalNumber = require('es5-ext/object/ensure-natural-number-value')
, startsWith = require('es5-ext/string/#/starts-with')
, debug = require('debug-ext')('recently-visited-limiter')
, ensureStorage = require('dbjs-persistence/ensure-storage');
module.exports = function (storage/*, options*/) {
ensureStorage(storage);
var options = Object(arguments[1])
, limit = (options.limit != null) ? ensureNaturalNumber(options.limit) : 10;
storage.on('update', function (event) {
if (!event.keyPath || !startsWith.call(event.keyPath, 'recentlyVisited/')) {
return; // No recentlyVisited record
}
if (event.keyPath === event.path) return; // No multiple item update
if (event.data.value !== '11') return; // Not expected value
storage.getObjectKeyPath(event.ownerId + '/' + event.keyPath)(function (events) {
events = events.filter(function (event) { return (event.data.value === '11'); });
if (events.length <= limit) return;
return storage.storeMany(events.slice(0, events.length - limit).map(function (event) {
return { id: event.id, data: { value: '' } };
})).aside(function () {
debug("cleared %s out of %s", events.length - limit, event.ownerId + '/' + event.keyPath);
});
}).done();
});
};
| JavaScript | 0.999999 | @@ -48,18 +48,17 @@
to max
-10
+5
(config
@@ -571,10 +571,9 @@
) :
-10
+5
;%0A%09s
|
49667f12bfe10d5e13529761b6268ae6623d11f9 | fix URL routing | examples/booklog-jollen/index.js | examples/booklog-jollen/index.js | /**
* Module dependencies.
*/
var express = require('../../lib/express');
// Path to our public directory
var pub = __dirname + '/public';
// setup middleware
var app = express();
app.use(express.static(pub));
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/booklog2');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('MongoDB: connected.');
});
var postSchema = new mongoose.Schema({
subject: { type: String, default: ''},
content: String
});
app.db = {
posts: mongoose.model('Post', postSchema)
};
// Optional since express defaults to CWD/views
app.set('views', __dirname + '/views');
// Set our default template engine to "jade"
// which prevents the need for extensions
// (although you can still mix and match)
app.set('view engine', 'jade');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.all('*', function(req, res, next){
if (!req.get('Origin')) return next();
// use "*" here to accept any origin
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
// res.set('Access-Control-Allow-Max-Age', 3600);
if ('OPTIONS' == req.method) return res.send(200);
next();
});
app.get('/welcome', function(req, res) {
res.render('index');
});
app.get('/download', function(req, res) {
var events = require('events');
var workflow = new events.EventEmitter();
workflow.outcome = {
success: false,
};
workflow.on('vaidate', function() {
var password = req.query.password;
if (typeof(req.retries) === 'undefined')
req.retries = 3;
if (password === '123456') {
return workflow.emit('success');
}
return workflow.emit('error');
});
workflow.on('success', function() {
workflow.outcome.success = true;
workflow.outcome.redirect = {
url: '/welcome'
};
workflow.emit('response');
});
workflow.on('error', function() {
if (req.retries > 0) {
req.retries--;
workflow.outcome.retries = req.retries;
workflow.emit('response');
}
workflow.outcome.success = false;
workflow.emit('response');
});
workflow.on('response', function() {
return res.send(workflow.outcome);
});
return workflow.emit('vaidate');
});
app.get('/post', function(req, res) {
res.render('post', {
posts: posts
});
});
app.get('/1/post/:id', function(req, res) {
var id = req.params.id;
var posts = req.app.db.posts;
posts.findOne({_id: id}, function(err, post) {
res.send({post: post});
});
});
app.get('/1/post', function(req, res) {
var posts = req.app.db.posts;
posts.find(function(err, posts) {
res.send({posts: posts});
});
});
app.post('/1/post', function(req, res) {
var posts = req.app.db.posts;
var subject;
var content;
if (typeof(req.body) === 'undefined') {
subject = req.query.subject;
content = req.query.content;
} else {
subject = req.body.subject;
content = req.body.content;
}
var data = {
subject: subject,
content: content
};
var post = new posts(data);
post.save();
res.send({ status: 'OK'});
});
app.delete('/1/post', function(req, res) {
res.send("Delete a post");
});
app.put('/1/post/:postId', function(req, res) {
var id = req.params.postId;
res.send("Update a post: " + id);
});
// change this to a better error handler in your code
// sending stacktrace to users in production is not good
app.use(function(err, req, res, next) {
res.send(err.stack);
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
| JavaScript | 0.000003 | @@ -1414,23 +1414,16 @@
p.get('/
-welcome
', funct
|
c73983658a0141037f7951cfac068144d909e321 | Fix helper | shuriken-web/imports/ui/submissionStatus.js | shuriken-web/imports/ui/submissionStatus.js | 'use strict';
// APIs and collections.
import {Evaluations} from '../api/evaluations.js';
// Libs.
import {Template} from 'meteor/templating';
// UI fragments.
import './submissionStatus.html';
// Requires.
const moment = require('moment');
const _ = require('lodash');
const should = require('should');
/**
* #### Context
*
* @todo complete section.
*
* #### Subscription contract
*
* This template is responsible for subscribing to the live evaluation for the
* given submissionId. It has no other dependencies.
*/
Template.submissionStatus.onCreated(function(){
const context = Template.currentData();
should(context)
.have.properties('submission')
.and.have.properties('taskRevision');
this.evaluationSubscriptionHandle =
this.subscribe('LiveEvaluationForSubmission', context.submission._id);
});
/**
* Returns the live evaluation for the submission. If none is found, nil is
* returned.
*
* @private
* @param {Object} context
* @return {?Evaluation}
*/
const _liveEvaluation = function(context) {
//FIXME What if there is more than one live evaluation?
//FIXME Sort by creation time (desc).
return Evaluations.findOne({
submissionId: context.submission._id,
isLive: true,
});
};
/**
* Returns the live evaluation for the submission and the task revision. If none
* is found, nil is returned.
*
* @private
* @param {Object} context
* @return {?Evaluation}
*/
const _liveEvaluationForTaskRevisionId = function(context) {
//FIXME What if there is more than one live evaluation?
return Evaluations.findOne({
submissionId: context.submission._id,
taskRevisionId: context.taskRevision._id,
isLive: true,
});
};
/**
* Checks if the given submission has a live evaluation.
*
* @private
* @param {Object} context
* @return {Boolean}
*/
const _hasLiveEvaluation = function(context) {
const evaluation = _liveEvaluation(context);
return (!_.isNil(evaluation) && evaluation.isLoaded());
};
/**
* Checks if the given submission has a live evaluation matching the given
* revision id.
*
* @private
* @param {Object} context
* @return {Boolean}
*/
const _hasLiveEvaluationForTaskRevisionId = function(context) {
const liveEvaluationForTaskRevisionId =
_liveEvaluationForTaskRevisionId(context);
return (!_.isNil(liveEvaluationForTaskRevisionId) &&
liveEvaluationForTaskRevisionId.isLoaded());
};
/**
* Returns the live evaluation for the given revision id. If none is found,
* returns any live evaluation for the given task. If none is found, returns
* null.
*
* @private
* @param {Object} context
* @return {?Evaluation}
*/
const _selectLiveEvaluation = function(context) {
if (_hasLiveEvaluationForTaskRevisionId(context)) {
return _liveEvaluationForTaskRevisionId(context);
} else if (_hasLiveEvaluation(context)) {
return _liveEvaluation(context);
} else {
return null;
}
};
Template.submissionStatus.helpers({
'isLoaded'() {
return Template.instance().evaluationSubscriptionHandle.ready();
},
'hasLiveEvaluationForTaskRevisionId'() {
return _hasLiveEvaluationForTaskRevisionId(this);
},
'hasLiveEvaluation'() {
return _hasLiveEvaluation(this);
},
'liveEvaluation'() {
return _selectLiveEvaluation(this);
},
'jobConfiguration'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
return JSON.stringify(evaluation.kueData, null, 2);
}
},
'humanEvaluationDateTime'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
//IDEA: in the future, use fromNow() instead of printing the absolute
// dateTime. In order for this to work reactively, .fromNow() should
// invalidate the template on change, via Tracker.
return moment(+evaluation.kueCreatedAt).local()
.format('D MMM YYYY, HH:mm:ss');
} else {
return 'Unknown';
}
},
'headingIcon'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
switch (evaluation.kueState) {
case 'inactive':
if (evaluation.isLost) {
return 'remove_circle_outline';
} else {
return 'change_history';
}
break;
case 'active':
return 'cached';
case 'failed':
return 'error_outline';
case 'delayed':
return 'schedule';
case 'complete':
return 'done_all';
}
} else {
return 'compare_arrows';
}
},
'humanState'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
switch (evaluation.kueState) {
case 'inactive':
return 'Queued';
case 'active':
return 'Evaluating...';
case 'failed':
return 'Evaluation failed';
case 'delayed':
return 'Evaluation delayed';
case 'complete':
const score = evaluation.kueResult.score;
const maxScore = evaluation.kueResult.maxScore;
return 'Evaluated (score: ' + score + '/' + maxScore + ')';
}
} else {
return 'No evaluation scheduled';
}
},
'kueState'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
return evaluation.kueState;
} else {
return null;
}
},
'isLost'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
return evaluation.isLost;
} else {
return false;
}
},
'hasProgressData'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
return evaluation.kueProgressData.trim().length > 0;
} else {
return false;
}
},
'progressData'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
return evaluation.kueProgressData;
} else {
return '';
}
},
'headingColor'() {
if (_hasLiveEvaluation(this)) {
const evaluation = _selectLiveEvaluation(this);
switch (evaluation.kueState) {
case 'inactive':
return '#7f7f7f';
case 'active':
return evaluation.isLost ? '#7f7f7f' : '#03a9f4';
case 'failed':
return '#9d000d';
case 'complete':
return '#4caf50';
}
} else {
return '#7f7f7f';
}
},
});
| JavaScript | 0.000002 | @@ -5700,32 +5700,85 @@
aluation(this);%0A
+ if (!_.isNull(evaluation.kueProgressData)) %7B%0A
return eva
@@ -5820,16 +5820,61 @@
th %3E 0;%0A
+ %7D else %7B%0A return false;%0A %7D%0A
%7D el
|
1fe0d92603486de6057a22180c9ac798dd4cc665 | resolve d3 in $timeout(), avoids problems with $apply() during active $digest() | sirepo/package_data/static/js/angular-d3.js | sirepo/package_data/static/js/angular-d3.js |
// code from http://www.ng-newsletter.com/posts/d3-on-angular.html
angular.module('d3', [])
.factory('d3Service', function($document, $q, $rootScope) {
var d = $q.defer();
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve(window.d3); });
}
// Create a script tag with d3 as the source
// and call our onScriptLoad callback when it
// has been loaded
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = '/static/js/d3-3.5.9.min.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return {
d3: function() { return d.promise; }
};
});
| JavaScript | 0.000005 | @@ -137,25 +137,23 @@
t, $q, $
-rootScope
+timeout
) %7B%0A
@@ -269,24 +269,15 @@
$
-rootScope.$apply
+timeout
(fun
|
f6c509c1d2ea65548ecb99c51d77a0c9147553a6 | index git commit -m index | workspace/index.ios.js | workspace/index.ios.js | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class workspace extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('workspace', () => workspace);
| JavaScript | 0.000005 | @@ -86,984 +86,34 @@
*/%0A%0A
-import React, %7B Component %7D from 'react';%0Aimport %7B%0A AppRegistry,%0A StyleSheet,%0A Text,%0A View%0A%7D from 'react-native';%0A%0Aexport default class workspace extends Component %7B%0A render() %7B%0A return (%0A %3CView style=%7Bstyles.container%7D%3E%0A %3CText style=%7Bstyles.welcome%7D%3E%0A Welcome to React Native!%0A %3C/Text%3E%0A %3CText style=%7Bstyles.instructions%7D%3E%0A To get started, edit index.ios.js%0A %3C/Text%3E%0A %3CText style=%7Bstyles.instructions%7D%3E%0A Press Cmd+R to reload,%7B'%5Cn'%7D%0A Cmd+D or shake for dev menu%0A %3C/Text%3E%0A %3C/View%3E%0A );%0A %7D%0A%7D%0A%0Aconst styles = StyleSheet.create(%7B%0A container: %7B%0A flex: 1,%0A justifyContent: 'center',%0A alignItems: 'center',%0A backgroundColor: '#F5FCFF',%0A %7D,%0A welcome: %7B%0A fontSize: 20,%0A textAlign: 'center',%0A margin: 10,%0A %7D,%0A instructions: %7B%0A textAlign: 'center',%0A color: '#333333',%0A marginBottom: 5,%0A %7D,%0A%7D);%0A%0AAppRegistry.registerComponent('workspace', () =%3E workspace)
+%0Aimport App from %22./src/app%22
;%0A
|
1beea31db15b6dddc5399de1d43e6f9df771ad4f | optimize invalidations | src/reducers/pickers.js | src/reducers/pickers.js | import { combineReducers } from 'redux';
import {
REQUEST_PROGRAMS, RECEIVE_PROGRAMS,
REQUEST_GROUPS, RECEIVE_GROUPS,
SET_YEAR, SET_GROUP, SET_PROGRAM, SET_STUDENT
} from '~/constants/actions';
function studentSelection(state = '', { type, student }) {
switch (type) {
case SET_STUDENT:
return student;
default:
return state;
}
}
function groupSelection(state = {}, { type, ...values }) {
switch (type) {
case SET_YEAR:
return { ...state, ...values, program: null, group: null };
case SET_PROGRAM:
return { ...state, ...values, group: null };
case SET_GROUP:
return { ...state, ...values };
default:
return state;
}
}
export default combineReducers({
studentSelection,
groupSelection
}); | JavaScript | 0.000002 | @@ -448,70 +448,86 @@
pe,
-...values %7D) %7B%0A switch (type) %7B%0A case SET_YEAR:%0A
+year, program, group %7D) %7B%0A if (type === SET_YEAR && year !== state.year) %7B%0A
@@ -549,25 +549,20 @@
.state,
-...values
+year
, progra
@@ -581,36 +581,34 @@
up: null %7D;%0A
-
+%7D%0A
%0A cas
@@ -604,34 +604,65 @@
- case SET_PROGRAM:%0A
+if (type === SET_PROGRAM && program !== state.program) %7B%0A
@@ -684,25 +684,23 @@
.state,
-...values
+program
, group:
@@ -708,28 +708,26 @@
null %7D;%0A
-
+%7D%0A
%0A
@@ -727,32 +727,59 @@
- case SET_GROUP:%0A
+if (type === SET_GROUP && group !== state.group) %7B%0A
@@ -805,25 +805,21 @@
te,
-...values
+group
%7D;%0A
@@ -818,38 +818,15 @@
-
+%7D
%0A
- default:%0A
+%0A
@@ -839,22 +839,16 @@
state;%0A
- %7D%0A
%7D%0A%0Aexpor
|
593668adb390ebadd9648d7de06a8874a39ec51a | Update staging.js | config/staging.js | config/staging.js | exports.config = {
common: {
database: {
url: process.env.NODE_API_DB_URL,
host: process.env.NODE_API_DB_HOST,
port: process.env.NODE_API_DB_PORT,
database: process.env.NODE_API_DB_NAME,
username: process.env.NODE_API_DB_USERNAME,
password: process.env.NODE_API_DB_PASSWORD
},
session: {
header_name: 'authorization',
secret: process.env.NODE_API_SESSION_SECRET
}
}
}
| JavaScript | 0.000001 | @@ -496,9 +496,10 @@
%0A %7D%0A%7D
+;
%0A
|
fecb36d131b57b4b0aade288efb5cfec6791b9f6 | Update js dist | dist/siteshot.js | dist/siteshot.js | var SiteShot;
SiteShot = (function() {
function SiteShot() {
var parseString, phantom, _;
this.fs = require('fs');
if (process.argv.indexOf('config') !== -1) {
this.config();
} else {
this.config = require('../siteshot.json');
parseString = require('xml2js').parseString;
_ = require('underscore');
phantom = require('phantom');
parseString(this.fs.readFileSync(this.config.sitemap), function(err, result) {
var routes;
if (err != null) {
throw err;
} else {
routes = _.flatten(_.pluck(result.urlset.url, 'loc'));
return _.each(routes, function(route) {
return phantom.create(function(ph) {
return ph.createPage(function(page) {
return page.open(route, function(status) {
return console.log(status);
});
});
});
});
}
});
}
}
SiteShot.prototype.config = function() {
var example;
example = {
snapshotDir: "snapshots",
sitemap: 'sitemap.xml',
opts: {
cutImg: true,
cutJs: true,
cutCss: true
}
};
return this.fs.writeFileSync('siteshot.json', JSON.stringify(example));
};
return SiteShot;
})();
module.exports = SiteShot;
new SiteShot;
| JavaScript | 0.000001 | @@ -64,16 +64,31 @@
%0A var
+ async, mkdirp,
parseSt
@@ -92,16 +92,22 @@
eString,
+ path,
phantom
@@ -107,16 +107,21 @@
phantom,
+ url,
_;%0A
@@ -393,24 +393,148 @@
'phantom');%0A
+ async = require('async');%0A url = require('url');%0A path = require('path');%0A mkdirp = require('mkdirp');%0A
parseS
@@ -581,16 +581,50 @@
itemap),
+ (function(_this) %7B%0A return
functio
@@ -644,24 +644,26 @@
) %7B%0A
+
var routes;%0A
@@ -662,16 +662,18 @@
routes;%0A
+
@@ -687,24 +687,26 @@
!= null) %7B%0A
+
th
@@ -718,24 +718,26 @@
rr;%0A
+
%7D else %7B%0A
@@ -729,24 +729,26 @@
%7D else %7B%0A
+
ro
@@ -800,16 +800,120 @@
loc'));%0A
+ return phantom.create(function(ph) %7B%0A var items;%0A items = %5B%5D;%0A
@@ -950,16 +950,19 @@
on(route
+, i
) %7B%0A
@@ -961,32 +961,36 @@
) %7B%0A
+
+
return phantom.c
@@ -978,36 +978,35 @@
return ph
-antom
.create
+Page
(function(ph
@@ -996,33 +996,35 @@
ePage(function(p
-h
+age
) %7B%0A
@@ -1021,32 +1021,36 @@
+
+
return p
h.createPage
@@ -1041,38 +1041,155 @@
rn p
-h.createPage(function(page) %7B%0A
+age.open(route, function(status) %7B%0A if (status === 'success') %7B%0A return page.evaluate((function() %7B%0A
@@ -1204,94 +1204,1081 @@
+
return
-page.open(route, function(status) %7B%0A return console.log(status
+document.documentElement.outerHTML;%0A %7D), function(res) %7B%0A var snapPath, snapPrefix;%0A snapPrefix = url.parse(route).path === '/' ? '/index' : url.parse(route).path;%0A snapPath = %22%22 + _this.config.snapshotDir + snapPrefix + %22.html%22;%0A return mkdirp(path.dirname(snapPath), function(err) %7B%0A if (err != null) %7B%0A throw err;%0A %7D%0A return _this.fs.writeFile(snapPath, res, function(err) %7B%0A if (err != null) %7B%0A throw err;%0A %7D%0A items.push(i);%0A page.close();%0A if (items.length === routes.length) %7B%0A return ph.exit();%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A %7D%0A %7D
);%0A
@@ -2333,34 +2333,32 @@
%7D);%0A %7D
-);
%0A %7D%0A
@@ -2347,24 +2347,25 @@
%7D%0A %7D
+;
%0A %7D);%0A
@@ -2357,24 +2357,31 @@
%7D;%0A %7D)
+(this))
;%0A %7D%0A %7D%0A
|
009152a4c574115a5bf47bace22c0a1d1e7bfb6f | Fix not render null, undefined and boolean when pass on render | src/renderers/render.js | src/renderers/render.js | import { buildComponentFromVNode } from '../isomorphic/createComponent';
let component;
/**
* @public
* @param vnode
* @param parent
*/
const render = (vnode, parent) => {
if (isNullOrBoolean(vnode)) vnode = '';
if (isString(vnode) || isNumber(vnode)) return document.createTextNode(vnode);
if (isFunction(vnode.nodeName)) {
component = buildComponentFromVNode(vnode, {});
vnode = component.vnode;
}
let node = document.createElement(vnode.nodeName);
let attributes = vnode.attributes || {};
setAttributes(component.instance, node, attributes);
(vnode.children || []).forEach( child => node.appendChild(render(child)) );
if (parent) parent.appendChild(node);
return node;
}
/**
* @param vnode
* @return {boolean}
* @internal
*/
const isNullOrBoolean = (vnode) => {
if (vnode == null || typeof vnode === 'boolean') return true;
return false;
}
/**
* @param vnode
* @return {boolean}
* @internal
*/
const isString = (vnode) => {
if (typeof vnode === 'string') return true;
return false;
}
/**
* @param vnode
* @return {boolean}
* @internal
*/
const isNumber = (vnode) => {
if (typeof vnode === 'number') return true;
return false;
}
/**
* @param vnode
* @return {boolean}
* @internal
*/
const isFunction = (vnode) => {
if (typeof vnode === 'function') return true;
return false;
}
/**
* @param component
* @param node
* @param attributes
* @internal
*/
const setAttributes = (component, node, attributes) => {
Object.keys(attributes).forEach(attr => {
if (attributes[attr] === 'null' || attributes[attr] === 'undefined' || !attributes[attr]) return;
if (isEvent(attr)) return addEventListener(component, node, attr, attributes);
node.setAttribute(attr, attributes[attr]);
});
}
/**
* @param component
* @param node
* @param attr
* @param attributes
* @internal
*/
const addEventListener = (component, node, attr, attributes) => {
let eventName = extractEventName(attr);
node.addEventListener(eventName, attributes[attr].bind(component));
}
/**
* @param attr
* @return {boolean}
* @internal
*/
const isEvent = (attr) => {
return /^on/.test(attr);
}
/**
* @param attr
* @return {string}
* @internal
*/
const extractEventName = (attr) => {
return attr.slice('2').toLowerCase();
}
export default render;
| JavaScript | 0.000001 | @@ -81,16 +81,34 @@
mponent;
+%0Alet initialVnode;
%0A%0A/**%0A *
@@ -185,24 +185,246 @@
arent) =%3E %7B%0A
+%09initialVnode = vnode;%0A%0A%09let returnRender = irender(vnode, initialVnode);%0A%0A%09if (parent) parent.appendChild(returnRender);%0A%0A%09return returnRender;%0A%7D%0A%0A/**%0A * Internal of render.%0A */%0Aconst irender = (vnode, initialVnode) =%3E %7B%0A
%09if (isNullO
@@ -647,17 +647,138 @@
vnode;%0A%09
-%7D
+%09component = component.instance;%0A%09%7D%0A%0A%09if (isDef(vnode)) %7B%0A%09%09vnode = initialVnode;%0A%09%09vnode.nodeName = vnode.nodeName();%0A%09%7D;
%0A%0A%09let n
@@ -891,25 +891,16 @@
omponent
-.instance
, node,
@@ -995,48 +995,8 @@
);%0A%0A
-%09if (parent) parent.appendChild(node);%0A%0A
%09ret
@@ -1002,24 +1002,25 @@
turn node;%0A%7D
+;
%0A%0A/**%0A * @pa
@@ -1479,32 +1479,183 @@
eturn false;%0A%7D%0A%0A
+/**%0A * @param vnode%0A * @return %7Bboolean%7D%0A * @internal%0A */%0Aconst isDef = (vnode) =%3E %7B%0A%09if (typeof vnode === 'undefined') return true;%0A%09return false;%0A%7D%0A%0A
/**%0A * @param vn
|
81b0d268bc717b4fcc5c792b77fcc8f333f44fbd | remove dgeni for now | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var karma = require('karma').server;
var Dgeni = require('dgeni');
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
gulp.task('docs', function () {
var dgeni = new Dgeni([require('./docs/dgeni-conf')]);
return dgeni.generate();
});
gulp.task('continuous', ['test']);
gulp.task('default', []);
| JavaScript | 0 | @@ -61,38 +61,8 @@
ver;
-%0Avar Dgeni = require('dgeni');
%0A%0A/*
@@ -245,135 +245,8 @@
;%0A%0A%0A
-%0Agulp.task('docs', function () %7B%0A var dgeni = new Dgeni(%5Brequire('./docs/dgeni-conf')%5D);%0A return dgeni.generate();%0A%7D);%0A%0A%0A
gulp
|
18b0830fef4d1aaa7e215bbba1edbde52be3769f | remove undefined env task | Gulpfile.js | Gulpfile.js | "use strict";
var fs = require("fs");
var copy = require("gulp-copy"),
gulp = require("gulp"),
jshint = require("gulp-jshint"),
rename = require("gulp-rename"),
replace = require("gulp-replace"),
run = require("gulp-run"),
sourcemaps = require("gulp-sourcemaps"),
uglify = require("gulp-uglify"),
env = require('gulp-env'),
webserver = require("gulp-webserver"),
concat = require('gulp-concat'),
mainBowerFiles = require('main-bower-files'),
hb = require("gulp-hb"),
copy = require("gulp-copy");
// Gulp mix-ins
require("gulp-autopolyfiller");
require("gulp-watch");
var paths = {
js: "./js/*.js",
publicJs: "./build/js"
};
//
// Run all default tasks
//
gulp.task("default",function() {
gulp.start("cleanup");
gulp.start("lint");
gulp.start("uglify");
gulp.start("templates");
gulp.start("templates:holos");
gulp.start("static");
});
gulp.task("cleanup",function(cb) {
run("rm -rf ./build/*", {}).exec();
});
//
// Check quality of Javascript
// warn if errors or style problems are found
//
gulp.task("lint", function() {
gulp
.src(paths.js)
.pipe(jshint({
predef: [
"document",
"location",
"navigator",
"window",
"L"
],
expr: true
}))
.pipe(jshint.reporter("jshint-stylish"));
});
gulp.task("uglify", function() {
gulp
.src(mainBowerFiles({filter: new RegExp('.js$', 'i')}).concat([paths.js, "./viewJS/**"]))
.pipe(sourcemaps.init())
.pipe(concat('ecoengine.js'))
.pipe(gulp.dest(paths.publicJs))
.pipe(uglify({
mangle: true,
output: {
beautify: false
}
}))
.pipe(rename({extname: ".min.js"}))
.pipe(sourcemaps.write("./")) // Write a sourcemap for browser debugging
.pipe(gulp.dest(paths.publicJs));
});
gulp.task("static", function() {
return gulp.src(["./static/**"], {"prefix":1})
.pipe(copy("./build/"));
});
//
// Build handlebars templates
// and create html files from them in
// the public directory
//
gulp.task("templates", function() {
gulp
.src("./templates/*.handlebars")
.pipe(hb({
data: "./data/**/*.{js,json}",
helpers: [
"./helpers/*.js"
],
partials: [
"./templates/partials/*.handlebars"
]
}))
.pipe(rename({extname: ".html"}))
.pipe(gulp.dest("./build/"));
});
gulp.task("templates:holos", function() {
gulp
.src("./templates/*.handlebars")
.pipe(hb({
data: ["./data/**/*.{js,json}","./holos/holos-templates.json"],
helpers: [
"./helpers/*.js"
],
partials: [
"./templates/partials/*.handlebars"
]
}))
.pipe(rename({extname: ".ninja2.html"}))
.pipe(gulp.dest("./build/"));
});
//
// Serve contents of the public directory
// locally on port :8000
//
gulp.task("webserver", function() {
gulp
.src("./build/")
.pipe(webserver({
open: false, // unless you want it
livereload: false, // unless you want it
directoryListing: false,
fallback: "index.html",
host:"0.0.0.0",
port:8000
}));
});
//
// Watch directories for changes
//
gulp.task("watch", function() {
gulp.watch(mainBowerFiles().concat([paths.js, "./viewJS/**"]),["lint", "uglify"]);
console.log("watching directory:", paths.js);
gulp.watch("./templates/**", ["set-env","templates, templates:holos"]);
console.log("watching directory:", paths.templates);
gulp.start("webserver");
});
| JavaScript | 0.999677 | @@ -3471,18 +3471,8 @@
, %5B%22
-set-env%22,%22
temp
|
4aaae362eafd2307c8abaffc3b8b284d82af692e | Add render mode enum to generated docs. | Gulpfile.js | Gulpfile.js | var gulp = require('gulp')
var autoprefixer = require('gulp-autoprefixer')
var browserify = require('browserify')
var buffer = require('vinyl-buffer')
var concat = require('gulp-concat')
var del = require('del')
var fs = require('fs')
var KarmaServer = require('karma').Server
var minifyCSS = require('gulp-minify-css')
var source = require('vinyl-source-stream')
var standard = require('gulp-standard')
var shell = require('gulp-shell')
var sourcemaps = require('gulp-sourcemaps')
var ts = require('gulp-typescript')
var tsify = require('tsify')
var tslint = require('gulp-tslint')
var util = require('gulp-util')
var uglify = require('gulp-uglify')
var watchify = require('watchify')
var argv = require('yargs').argv
var browserSync = require('browser-sync').create()
var paths = {
mapillaryjs: 'mapillaryjs',
css: './styles/**/*.css',
build: './build',
ts: {
src: './src/**/*.ts',
tests: './spec/**/*.ts',
dest: 'build',
testDest: 'build/spec'
},
js: {
src: './build/**/*.js',
tests: './spec/**/*.js'
},
sourceMaps: './build/bundle.js.map',
sourceMapsDist: './dist/mapillary-js.map'
}
var config = {
browserify: {
entries: ['./src/Mapillary.ts'],
debug: true,
standalone: 'Mapillary',
cache: {},
packageCache: {}
},
ts: JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8')).compilerOptions,
typedoc: {
includes: [
'./src/viewer/Viewer.ts',
'./src/viewer/interfaces/IViewerOptions.ts',
'./src/graph/edge/EdgeDirection.ts',
'./src/viewer/ImageSize.ts'
],
options: {
target: 'ES5',
module: 'commonjs',
theme: 'minimal',
mode: 'file',
out: './docs-out',
name: 'mapillary-js',
excludeExternals: ''
}
}
}
gulp.task('clean', function () {
return del([
'docs/ts/**/*',
'build/**/*',
'debug/**/*.js'
])
})
var parsedOptions = []
for (var key in config.typedoc.options) {
parsedOptions.push('--' + key + ' ' + config.typedoc.options[key])
}
gulp.task('documentation', shell.task('./node_modules/typedoc/bin/typedoc ' +
parsedOptions.join(' ') +
' ' +
config.typedoc.includes.join(' ')
))
gulp.task('js-lint', function () {
return gulp.src('./Gulpfile.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}))
})
gulp.task('serve', ['ts'], function () {
browserSync.init({
server: {
baseDir: './debug',
routes: {
'/dist': 'dist',
'/build': 'build'
}
},
logFileChanges: false
})
})
gulp.task('test', function (done) {
var config
if (argv.grep) {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
client: {
args: ['--grep', argv.grep]
},
singleRun: true
})
} else {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
singleRun: true
})
}
new KarmaServer(config, function (exitCode) {
if (exitCode) {
process.exit(exitCode)
}
}, done).start()
})
gulp.task('test-watch', function (done) {
var config
if (argv.grep) {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
client: {
args: ['--grep', argv.grep]
},
singleRun: false
})
} else {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
singleRun: false
})
}
new KarmaServer(config, function (exitCode) {
if (exitCode) {
process.exit(exitCode)
}
}, done).start()
})
gulp.task('ts-lint', function (cb) {
var stream = gulp.src(paths.ts.src)
.pipe(tslint())
.pipe(tslint.report('verbose'))
return stream
})
gulp.task('typings', shell.task('./node_modules/typings/dist/bin/typings.js install'))
gulp.task('typescript', ['ts-lint', 'typescript-src', 'typescript-test'], function (cb) { cb() })
gulp.task('typescript-src', function () {
var stream = gulp.src(paths.ts.src)
.pipe(ts(config.ts))
.pipe(gulp.dest(paths.ts.dest))
return stream
})
gulp.task('watch', ['css'], function () {
gulp.watch([paths.ts.src, paths.ts.tests], ['dev:ts'])
gulp.watch([paths.css], ['css'])
})
gulp.task('default', ['serve', 'watch'])
// Helpers
function extendKarmaConfig (path, conf) {
conf.configFile = path
return conf
}
gulp.task('prepublish', ['typings', 'ts-lint', 'css'], function () {
browserify(config.browserify)
.plugin(tsify, config.ts)
.transform('brfs')
.transform('envify')
.bundle()
.on('error', function (error) {
console.error(error.toString())
})
.pipe(source('mapillary-js.min.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist'))
})
// TODO: Refine this task
gulp.task('ts', ['ts-lint'], function () {
var bundler = browserify(config.browserify)
bundler.plugin(tsify, config.ts)
if (util.env.env === 'TEST') {
// skip watchify in test environment
} else {
bundler.plugin(watchify)
}
bundler
.transform('brfs')
.transform('envify')
.bundle()
.on('error', function (error) {
console.error(error.toString())
})
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./build'))
})
gulp.task('dev:ts', ['ts'], function () {
browserSync.reload()
})
gulp.task('copy-style-assets', function () {
gulp.src('styles/**/!(*.css)')
.pipe(gulp.dest('dist'))
})
gulp.task('css', ['copy-style-assets'], function () {
gulp.src([
'styles/mapillary-js.css',
'styles/**/!(mapillary-js)*.css'
])
.pipe(autoprefixer('last 2 version', 'safari 7', 'ie 11'))
.pipe(minifyCSS())
.pipe(concat('mapillary-js.min.css'))
.pipe(gulp.dest('dist'))
.pipe(browserSync.stream())
})
| JavaScript | 0 | @@ -1548,16 +1548,52 @@
Size.ts'
+,%0A './src/render/RenderMode.ts'
%0A %5D,%0A
|
e0827580d7e1c21a578bb818c83eb8ebf5490803 | add cron | geoDownload.js | geoDownload.js | (function() {
var fs = require('fs'),
Sails = require('sails'),
AdmZip = require('adm-zip'),
tempFolder = 'tempFolder/',
http = require("http"),
fs = require('fs'),
rimraf = require('rimraf'),
async = require('async'),
callDataSet = [],
csv = require('fast-csv'),
csvLocation = require('fast-csv'),
ip = require('ip'),
moment = require('moment'),
request = require('request')
if(fs.existsSync(tempFolder)) {
rimraf.sync(tempFolder)
}
fs.mkdirSync(tempFolder)
var updatedOn = moment().format('YYYY-MM-DD HH:mm:ss')
//tempFolder = __dirname+'/'+tempFolder
download('http://geolite.maxmind.com/download/geoip/database/GeoLite2-City-CSV.zip',function() {
var zip = new AdmZip(tempFolder+'geo.zip');
var zipEntries = zip.getEntries();
zip.extractAllTo(tempFolder, true);
var row = 0;
zipEntries.forEach(function(zipEntry) {
if(zipEntry.name == 'GeoLite2-City-Blocks-IPv4.csv') {
callDataSet.push(function(cb){
var ipCSVFS = fs.createWriteStream(tempFolder+"ip.csv", {encoding: "utf8"})
ipCSVFS
.on('finish',function() {
cb()
})
csv
.fromPath(tempFolder+zipEntry.entryName, {headers: true})
.transform(function(data){
var newIP = ip.cidrSubnet(data.network)
row++
console.log(row)
return {
networkID: data.network,
geoNameID:data.geoname_id || 0,
highRange:ip.toLong(newIP.lastAddress),
lowRange:ip.toLong(newIP.firstAddress),
geoCountryNameID: data.registered_country_geoname_id || 0,
postalCode:data.postal_code || '',
latitude:data.latitude || 0,
longitude:data.longitude || 0,
updatedOn: updatedOn
}
})
.pipe(csv.createWriteStream())
.pipe(ipCSVFS)
});
}
if(zipEntry.name == 'GeoLite2-City-Locations-en.csv') {
callDataSet.push(function(cb){
var geonameFS = fs.createWriteStream(tempFolder+"geoname.csv", {encoding: "utf8"})
geonameFS
.on('finish', function() {
cb();
});
csvLocation
.fromPath(tempFolder+zipEntry.entryName, {headers: true})
.transform(function(data){
row++
console.log(row)
return {
id:data.geoname_id || 0,
continent: data.continent_code,
geoNameID:data.geoname_id || 0,
continentName:data.continent_name,
ISOCode:data.country_iso_code,
countryName: data.country_name,
cityName:data.city_name || '',
subdivision:data.subdivision_1_name,
updatedOn:updatedOn
}
})
.pipe(csvLocation.createWriteStream())
.pipe(geonameFS)
});
}
});
async.parallel(callDataSet, function(err,results) {
console.log('end')
console.log(err)
Sails.load({log:{level:'debug'}}, function(err, sails) {
// Do some stuff with sails here
console.log(err);
sails.models.geoname.query("load data local infile '"+tempFolder+"geoname.csv' into table geoname fields"
+" terminated by ',' enclosed by '\"'"
+" lines terminated by '\n'"
+" (continent,geoNameID,continentName,ISOCode,countryName,cityName,subdivision,updatedOn);",
function(err, results) {
if (err) {
console.log(err);
}
sails.models.geoname.query("load data local infile '"+tempFolder+"ip.csv' into table geoip fields"
+" terminated by ',' enclosed by '\"'"
+" lines terminated by '\n'"
+" (id,networkIP,geoNameID,highRange,lowRange,geoCountryNameID,postalCode,latitude,longitude,updatedOn);",
function(err, results) {
if (err)
console.log(err);
});
});
});
})
})
function download(url, cb) {
var data = "";
var file = fs.createWriteStream(tempFolder+'geo.zip');
console.log('downloading')
file
.on('error',function(e) {
console.log(e)
console.log('file error')
})
.on('finish', function() {
file.close(cb);
});
var row = 0;
request
.get(url)
.on('error', function(e) {
console.log("Got error: " + e.message);
})
.pipe(file)
}
}())
| JavaScript | 0.000002 | @@ -4306,32 +4306,88 @@
nsole.log(err);%0A
+ sails.lower()%0A process.exit(1)%0A
%7D);%0A
|
e038ed39f3b7eddb59d3c632df64df5e61249f51 | Fix conversion that kept medical devices counts from showing. | lists/veteran-full-csv.js | lists/veteran-full-csv.js | function(head, req) {
var row;
start({
"headers": {
"Content-Type": "text/csv",
"Content-disposition": "attachment;filename=VeteranInfo.csv"
}
});
var headerNeeded = true;
while(row = getRow()) {
r = row.value;
result = {
app_date: r.app_date,
first_name: r.name.first,
middle_name: r.name.middle,
last_name: r.name.last,
nick_name: r.name.nickname,
addr_street: r.address.street,
addr_city: r.address.city,
addr_county: r.address.county,
addr_state: r.address.state,
addr_zip: r.address.zip,
addr_phone_day: r.address.phone_day,
addr_phone_eve: r.address.phone_eve,
addr_phone_mbl: r.address.phone_mbl,
addr_email: r.address.email,
age: r.age,
birth_date: r.birth_date,
gender: r.gender,
weight: r.weight,
shirt_size: r.shirt.size,
service_branch: r.service.branch,
service_number: r.service.service_number,
service_rank: r.service.rank,
service_dates: r.service.dates,
service_activity: r.service.activity,
ec_relation: r.emerg_contact.relation,
ec_name: r.emerg_contact.name,
ec_addr_street: r.emerg_contact.address.street,
ec_addr_city: r.emerg_contact.address.city,
ec_addr_state: r.emerg_contact.address.state,
ec_addr_zip: r.emerg_contact.address.zip,
ec_addr_phone: r.emerg_contact.address.phone,
ec_addr_email: r.emerg_contact.address.email,
ac_relation: r.alt_contact.relation,
ac_name: r.alt_contact.name,
ac_addr_street: r.alt_contact.address.street,
ac_addr_city: r.alt_contact.address.city,
ac_addr_state: r.alt_contact.address.state,
ac_addr_zip: r.alt_contact.address.zip,
ac_addr_phone: r.alt_contact.address.phone,
ac_addr_email: r.alt_contact.address.email,
medical_uses_cane: r.medical.usesCane,
medical_uses_walker: r.medical.usesWalker,
medical_uses_wc: r.medical.usesWheelchair,
medical_wc_bound: r.medical.isWheelchairBound,
medical_req_oxygen: r.medical.requiresOxygen,
medical_limitations: r.medical.limitations,
medical_review: r.medical.review,
medical_category: r.medical.category,
preferred_airport: r.preferred_airport,
flights: r.availableFlights,
flight_status: r.flight.status,
flight_status_note: r.flight.status_note,
flight_confirmed_date: r.flight.confirmed_date,
flight_confirmed_by: r.flight.confirmed_by,
flight_group: r.flight.group,
flight_id: r.flight.id,
flight_seat: r.flight.seat,
flight_bus: r.flight.bus,
guardian_id: r.guardian.id,
guardian_name: r.guardian.name,
guardian_pref_notes: r.guardian.pref_notes,
id: r._id,
rev: r._rev,
created_at: r.metadata.created_at,
updated_at: r.metadata.updated_at,
created_by: r.metadata.created_by,
updated_by: r.metadata.updated_by
}
if (headerNeeded) {
for (key in result) {
send("\"");
send(key);
send("\",");
}
send("\n");
headerNeeded = false;
}
for (key in result) {
if ((result[key]) && (result[key].length > 0)) {
send("\"");
send(result[key]);
send("\"");
}
send(",");
}
send("\n");
}
}
| JavaScript | 0 | @@ -2023,250 +2023,8 @@
e,%0D%0A
- ac_addr_street: r.alt_contact.address.street,%0D%0A ac_addr_city: r.alt_contact.address.city,%0D%0A ac_addr_state: r.alt_contact.address.state,%0D%0A ac_addr_zip: r.alt_contact.address.zip,%0D%0A
@@ -2638,60 +2638,8 @@
t,%0D%0A
- flights: r.availableFlights,%0D%0A
@@ -3712,17 +3712,16 @@
if
-(
(result%5B
@@ -3730,10 +3730,21 @@
y%5D)
-&&
+%7B%0D%0A if
(re
@@ -3764,21 +3764,22 @@
gth %3E 0)
-)
%7B%0D%0A
+
@@ -3795,24 +3795,26 @@
);%0D%0A
+
send(result%5B
@@ -3821,32 +3821,34 @@
key%5D);%0D%0A
+
send(%22%5C%22%22);%0D%0A
@@ -3840,24 +3840,147 @@
end(%22%5C%22%22);%0D%0A
+ %7D else %7B%0D%0A if (!isNaN(result%5Bkey%5D)) %7B%0D%0A send(result%5Bkey%5D.toString());%0D%0A %7D%0D%0A %7D%0D%0A
%7D%0D%0A
|
0518b2aa0d78a95e51fbb7d8a650dc9f1b5c2649 | remove activeOpacity+highlight from Thumbnail | source/views/streaming/webcams/thumbnail.js | source/views/streaming/webcams/thumbnail.js | // @flow
import * as React from 'react'
import {StyleSheet, View, Text, Image} from 'react-native'
import {Touchable} from '@frogpond/touchable'
import * as c from '@frogpond/colors'
import {images as webcamImages} from '../../../../images/webcams'
import {trackedOpenUrl} from '@frogpond/open-url'
import LinearGradient from 'react-native-linear-gradient'
import type {Webcam} from './types'
const transparentPixel = require('../../../../images/transparent.png')
type Props = {
webcam: Webcam,
viewportWidth: number,
}
export class StreamThumbnail extends React.PureComponent<Props> {
handlePress = () => {
const {name, pageUrl} = this.props.webcam
trackedOpenUrl({url: pageUrl, id: `${name}WebcamView`})
}
render() {
const {viewportWidth, webcam} = this.props
const {name, thumbnail, accentColor, textColor, thumbnailUrl} = webcam
const [r, g, b] = accentColor
const baseColor = `rgba(${r}, ${g}, ${b}, 1)`
const startColor = `rgba(${r}, ${g}, ${b}, 0.1)`
const width = viewportWidth / 2 - CELL_MARGIN * 1.5
const cellRatio = 2.15625
const height = width / cellRatio
const img = thumbnailUrl
? {uri: thumbnailUrl}
: webcamImages.hasOwnProperty(thumbnail)
? webcamImages[thumbnail]
: transparentPixel
return (
// do not remove this View; it is needed to prevent extra highlighting
<View style={styles.cell}>
<Touchable
activeOpacity={0.7}
highlight={true}
onPress={this.handlePress}
style={{width, height}}
underlayColor={baseColor}
>
<Image
resizeMode="cover"
source={img}
style={[StyleSheet.absoluteFill, {width, height}]}
/>
<View style={styles.titleWrapper}>
<LinearGradient
colors={[startColor, baseColor]}
locations={[0, 0.8]}
>
<Text style={[styles.titleText, {color: textColor}]}>{name}</Text>
</LinearGradient>
</View>
</Touchable>
</View>
)
}
}
const CELL_MARGIN = 10
const styles = StyleSheet.create({
cell: {
overflow: 'hidden',
margin: CELL_MARGIN / 2,
borderRadius: 6,
},
titleWrapper: {
flex: 1,
justifyContent: 'flex-end',
},
titleText: {
backgroundColor: c.transparent,
fontSize: 12,
paddingHorizontal: 4,
paddingVertical: 2,
textAlign: 'center',
fontWeight: 'bold',
},
})
| JavaScript | 0 | @@ -1379,33 +1379,8 @@
ble%0A
-%09%09%09%09%09activeOpacity=%7B0.7%7D%0A
%09%09%09%09
|
8c86562a38bc25a591a9187c71b857eb0202040b | update async/concurrent | src/async/concurrent.js | src/async/concurrent.js | // lightweight parallel async iterators:
// [each, reduce, map, filter, reject, detect, every, some, concat, times, sort, parallel]
// adpoted from: https://github.com/aliaksandr-pasynkau/async-iterate
function asyncEachArray (arr, iterator, done) {
if (!arr || !arr.length) return done()
var idx = -1
var len
var lastIdx
lastIdx = len = arr.length
while (++idx < lastIdx) {
iterator(arr[idx], idx, next)
}
function next (err) {
if (err) return once(done(err))
if (--len === 0) return done(null)
}
}
function asyncEach (obj, iterator, done) {
if (Array.isArray(obj)) {
asyncEachArray(obj, iterator, done)
return
}
asyncEachArray(obj && Object.keys(obj), function (key, index, done) {
iterator(obj[key], key, done)
}, done)
}
function asyncReduce (obj, result, iterator, done) {
asyncEach(obj, function (v, k, done) {
iterator(result, v, k, function (err, value) {
result = value
done(err)
})
}, function (err) {
done(err, result)
})
}
function asyncMap (obj, iterator, done) {
asyncReduce(obj, [], function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
resultObject.push(result)
done(err, resultObject)
})
}, done)
}
function asyncFilter (obj, iterator, done) {
asyncReduce(obj, [], function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
if (result) resultObject.push(obj[k])
done(err, resultObject)
})
}, done)
}
function asyncReject (obj, iterator, done) {
asyncReduce(obj, [], function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
if (!result) resultObject.push(obj[k])
done(err, resultObject)
})
}, done)
}
function asyncEvery (obj, iterator, done) {
asyncReduce(obj, true, function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
if (!result) resultObject = false
done(err, resultObject)
})
}, done)
}
function asyncSome (obj, iterator, done) {
asyncReduce(obj, false, function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
if (result) resultObject = true
done(err, resultObject)
})
}, done)
}
function asyncConcat (obj, iterator, done) {
asyncReduce(obj, [], function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
resultObject = resultObject.concat(result || [])
done(err, resultObject)
})
}, done)
}
function asyncTimes (num, iterator, done) {
var obj = Array(num)
asyncReduce(obj, [], function (resultObject, v, k, done) {
iterator(num, function (err, res) {
resultObject.push(res)
done(null, resultObject)
})
}, done)
}
function asyncReduceSort (obj, result, iterator, done) {
asyncEach(obj, function (v, k, done) {
iterator(result, v, k, function (err, value) {
result = value
done(err)
})
}, function (err) {
done(err, _map(result.sort(comparator), function (x) {
return x.value
}))
})
}
function asyncSort (obj, iterator, done) {
asyncReduceSort(obj, [], function (resultObject, v, k, done) {
iterator(v, k, function (err, result) {
resultObject.push({value: v, result: result})
done(err, resultObject)
})
}, done)
}
function asyncParallel (obj, done) {
asyncReduce(obj, [], function (resultObject, v, k, done) {
v.call(null, function (err, res) {
resultObject.push(res)
done(null, resultObject)
})
}, done)
}
function once (fn) {
return function () {
var ret = fn.apply(this, arguments)
fn = noop
return ret
}
}
function comparator (left, right) {
var a = left.result
var b = right.result
return a < b ? -1 : a > b ? 1 : 0
}
function _map (arr, iterator) {
var idx = -1
var len = arr.length
var result = Array(len)
while (++idx < len) {
result[idx] = iterator(arr[idx], idx, arr)
}
return result
}
function noop () {}
exports.each = asyncEach
exports.map = asyncEach
exports.filter = asyncFilter
exports.map = asyncMap
exports.reject = asyncReject
exports.every = asyncEvery
exports.some = asyncSome
exports.concat = asyncConcat
exports.times = asyncTimes
exports.sort = asyncSort
exports.parallel = asyncParallel
| JavaScript | 0 | @@ -2731,325 +2731,8 @@
%0A%7D%0A%0A
-function asyncReduceSort (obj, result, iterator, done) %7B%0A asyncEach(obj, function (v, k, done) %7B%0A iterator(result, v, k, function (err, value) %7B%0A result = value%0A done(err)%0A %7D)%0A %7D, function (err) %7B%0A done(err, _map(result.sort(comparator), function (x) %7B%0A return x.value%0A %7D))%0A %7D)%0A%7D%0A%0A
func
@@ -2783,20 +2783,16 @@
ncReduce
-Sort
(obj, %5B%5D
@@ -2961,36 +2961,142 @@
ct)%0A %7D)%0A %7D,
-done
+function (err, res) %7B%0A done(err, _map(res.sort(comparator), function (x) %7B%0A return x.value%0A %7D))%0A %7D
)%0A%7D%0A%0Afunction as
@@ -4084,9 +4084,8 @@
arallel%0A
-%0A
|
73c9fa85a1e985782f307883631839a015e11b89 | fix uploadFolder bug | plugins/Files/js/loader.js | plugins/Files/js/loader.js | 'use strict';
/*
* fileLoader namespace module:
* fileLoader contains the logic for uploading and loading files
*/
// Node modules
const fs = require('fs');
const path = require('path');
const tools = require('./uiTools');
const siad = require('sia.js');
// Whether to upload files with autorenew feature or some block duration
// Default behavior is to renew automatically
// TODO: Settings page
var renew = true;
var duration = null;
// Get files plugin settings for uploading
var settings = tools.config('files');
if (!settings) {
tools.config('files', {
renew: renew,
duration: duration,
});
} else {
renew = settings.renew;
duration = settings.duration;
}
// Uploads a file from the given source to the given siapath.
function uploadFile(source, siapath, callback) {
// Determine the siapath
var fileName = path.basename(source);
if (siapath !== '') {
siapath = `${siapath}/${fileName}`;
} else {
siapath = fileName;
}
// Upload the file
siad.apiCall({
url: '/renter/upload/' + siapath,
method: 'POST',
qs: {
source: source,
duration: duration,
renew: renew,
},
}, callback);
}
// Recursively upload all files in a directory
function uploadFolder(dirPath, siapath, callback) {
var dirName = path.basename(dirPath);
if (siapath !== '') {
siapath = `${siapath}/${dirName}`;
} else {
siapath = dirName;
}
// Get a list of files in the chosen directory
fs.readdir(dirPath, function(err, files) {
if (err) {
tools.notify('Failed retrieving directory contents', 'error');
return;
}
// Process files into sources and siapaths
var filePaths = files.map(file => path.resolve(dirPath, file));
// Process the appropriate function per file
var functs = filePaths.map(filePath =>
fs.statSync(filePath).isFile() ? uploadFile : uploadFolder);
tools.waterfall(functs, siapath, callback);
});
}
// Loads a .sia file into the library
function loadDotSia(source, callback) {
siad.apiCall({
url: '/renter/load',
method: 'POST',
qs: {
source: source,
}
}, callback);
}
// Loads an ascii represenation of a .sia file into the library
function loadAscii(ascii, callback) {
siad.apiCall({
url: '/renter/loadascii',
method: 'POST',
qs: {
asciisia: ascii,
}
}, callback);
}
// Place one .sia file to destination for potentially many file paths
function shareDotSia(paths, destination, callback) {
siad.apiCall({
url: '/renter/share',
qs: {
siapaths: paths.join(','),
destination: destination,
}
}, callback);
}
// Share one .sia ascii for potentially many file paths
function shareAscii(paths, callback) {
siad.apiCall({
url: '/renter/shareascii',
qs: {
siapaths: paths.join(','),
}
}, callback);
}
module.exports = {
uploadFile: uploadFile,
uploadFolder: uploadFolder,
loadDotSia: loadDotSia,
loadAscii: loadAscii,
shareDotSia: shareDotSia,
shareAscii: shareAscii,
};
| JavaScript | 0 | @@ -1833,16 +1833,27 @@
(functs,
+ filePaths,
siapath
|
5d80633206ffbe019a925d83a76f6eb94eb0c5c2 | add watchSendSiacoin saga to middleware | plugins/Wallet/js/index.js | plugins/Wallet/js/index.js | // index.js: main entrypoint for the Sia-UI wallet plugin.
'use strict'
import React from 'react';
import ReactDOM from 'react-dom';
import createSagaMiddleware from 'redux-saga';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './js/reducers/index.js';
import * as sagas from './js/sagas/wallet.js'
import { getLockStatus, getBalance, getTransactions } from './js/actions/wallet.js';
import WalletApp from './js/components/app.js';
// Set up saga middleware system
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(sagas.watchGetLockStatus);
sagaMiddleware.run(sagas.watchUnlockWallet);
sagaMiddleware.run(sagas.watchCreateNewWallet);
sagaMiddleware.run(sagas.watchGetBalance);
sagaMiddleware.run(sagas.watchGetTransactions);
sagaMiddleware.run(sagas.watchGetNewReceiveAddress);
// Render the wallet plugin
const rootElement = (
<Provider store={store}>
<WalletApp />
</Provider>
);
ReactDOM.render(rootElement, document.getElementById('react-root'));
// Poll Siad for state changes.
setInterval(() => {
store.dispatch(getLockStatus());
store.dispatch(getBalance());
store.dispatch(getTransactions());
}, 1000);
| JavaScript | 0 | @@ -938,16 +938,60 @@
ddress);
+%0AsagaMiddleware.run(sagas.watchSendSiacoin);
%0A%0A// Ren
|
fce2272b6fe337fa013a63563c67b1cb1057c7e5 | add useless "fetch" handler to meet installable criteria | www/notification-sw.js | www/notification-sw.js | // This will be called only once when the service worker is activated.
self.addEventListener('activate', function () {
console.log('RP Service Worker installed!')
})
self.addEventListener('message', function (event) {
console.log(event.data)
if (event.data.action === 'setup') {
setupSubscription(event.data.url, event.data.token)
} else if (event.data.action === 'title') {
rememberTitle(event.data.databaseId, event.data.title)
}
})
self.addEventListener('push', function (event) {
console.log(event)
var data = event.data.json()
if (data.test === 'ok') {
return event.waitUntil(self.registration.showNotification('Subscribed to RPNow push notifications'))
} else if (data.update) {
var promise = clients.matchAll({
type: 'window',
includeUncontrolled: true
})
.then(function(clientList) {
return clientList.find(c => c.visibilityState === 'visible' && c.url.includes(data.update.databaseId))
})
.then(function (client) {
if (client) return null;
else return self.registration.showNotification('New RP Message', {
actions: [{ action: `open ${data.update.databaseId}`, title: 'Read' }]
})
});
event.waitUntil(promise);
}
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
console.log(event.action)
if (event.action.startsWith('open ')) {
var roomId = event.action.substr(5)
var promise = clients.matchAll({ type: 'window' })
.then(function (clientList) {
var client = clientList.find(c => c.url.endsWith(`?room=${roomId}`))
if (client) return client.focus()
else if (clients.openWindow) return clients.openWindow(`/rp.html?room=${roomId}`)
})
return event.waitUntil(promise)
}
})
function setupSubscription(url, token) {
self.registration.pushManager.getSubscription().then(function (existingSubscription) {
if (existingSubscription) return existingSubscription
// var applicationServerKey = "BH65dM6/Kc1I9fXdujbCcnkKaJEAMCD2AZdleKh2agvimEPmasK3CNNV9aFngcA5Xjg3ODogLcEbZZhTzjhNci0="
var applicationServerKey = Uint8Array.from([4, 126, 185, 116, 206, 191, 41, 205, 72, 245, 245, 221, 186, 54, 194, 114, 121, 10, 104, 145, 0, 48, 32, 246, 1, 151, 101, 120, 168, 118, 106, 11, 226, 152, 67, 230, 106, 194, 183, 8, 211, 85, 245, 161, 103, 129, 192, 57, 94, 56, 55, 56, 58, 32, 45, 193, 27, 101, 152, 83, 206, 56, 77, 114, 45])
var options = {
applicationServerKey: applicationServerKey,
userVisibleOnly: true
};
return self.registration.pushManager.subscribe(options)
}).then(function (subscription) {
console.log(JSON.stringify(subscription))
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Token': token,
'X-Subscription': JSON.stringify(subscription),
},
})
});
}
function rememberTitle(databaseId, title) {
// TODO
}
| JavaScript | 0.000001 | @@ -158,24 +158,179 @@
lled!')%0A%7D)%0A%0A
+self.addEventListener('fetch', event =%3E %7B%0A // not useful, but required to meet %22installable%22 criteria%0A console.log(%60fetching $%7Bevent.request.url%7D%60);%0A%7D)%0A%0A
self.addEven
|
96cc8a957f106ce1f51b97f07489953a6c1fbb67 | Declare images precompiled | app/assets/config/manifest.js | app/assets/config/manifest.js | /* eslint-disable spaced-comment */
//= link application.css
| JavaScript | 0.000003 | @@ -29,16 +29,45 @@
ment */%0A
+//= link_directory ../images%0A
//= link
|
3ca22640744353d6576cf7435c1d08342811a729 | change zoom condition | app/assets/javascripts/map.js | app/assets/javascripts/map.js | $(document).on("ready", function() {
L.mapbox.accessToken = 'pk.eyJ1IjoibXR0aHdncnkiLCJhIjoibW82OTJicyJ9.ykVo84aS5xtK3jPy_iX6Sg';
var map = L.mapbox.map('map', 'mtthwgry.bcb9b827', { zoomControl: false })
.setView([37.771167, -122.402504], 12);
var featureLayer = L.mapbox.featureLayer().loadURL('/all_locations');
var userColors = {};
featureLayer.on('ready', function(f) {
// Don't display markers until a user filter has been clicked
this.setFilter(function() {
return false;
});
// Generate user:color key/value pairs
var geoJSON = this.getGeoJSON();
geoJSON.forEach(function(obj) {
var userId = obj.properties.user_id;
userColors[userId] = userColors[userId] || randomColor();
obj.properties['marker-color'] = userColors[userId];
});
this.addTo(map);
});
// This will keep track of which users filters have been clicked
var usersOn = [];
$('.user-list').on("click", '.user-list-item a', function(event) {
event.preventDefault();
var userId = $(this).data('user-id');
var index = usersOn.indexOf(userId);
var $userListItem = $(this).closest('.user-list-item');
$userListItem.toggleClass('active');
// Set the background color according to the user's filter status
if(index > -1) {
$userListItem.css("background-color", "");
usersOn.splice(index, 1);
} else {
$userListItem.css("background-color", userColors[userId]);
usersOn.push(userId);
}
// Now filter the markers
featureLayer.setFilter(function(f) {
return usersOn.indexOf(f.properties.user_id) > -1;
});
// If the map is zoomed out and only one user is being filtered, re-zoom the map
if(map.getZoom() < 8 && usersOn.length <= 1) {
map.fitBounds(featureLayer.getBounds());
}
});
}); | JavaScript | 0 | @@ -164,24 +164,21 @@
, 'm
-tthwgry.bcb9b827
+apbox.emerald
', %7B
@@ -1732,31 +1732,8 @@
%3C 8
- && usersOn.length %3C= 1
) %7B%0A
|
6c95aa40a90f779cf5772f51696bc17337bd93cd | Update canvas.js | src/client/js/canvas.js | src/client/js/canvas.js | var global = require('./global');
class Canvas {
constructor(params) {
this.directionLock = false;
this.target = global.target;
this.reenviar = true;
this.socket = global.socket;
this.directions = [];
var self = this;
this.cv = document.getElementById('cvs');
this.cv.width = global.screenWidth;
this.cv.height = global.screenHeight;
this.cv.addEventListener('mousemove', this.gameInput, false);
this.cv.addEventListener('mouseout', this.outOfBounds, false);
this.cv.addEventListener('keypress', this.keyInput, false);
this.cv.addEventListener('keyup', function(event) {
self.reenviar = true;
self.directionUp(event);
}, false);
this.cv.addEventListener('keydown', this.directionDown, false);
this.cv.addEventListener('touchstart', this.touchInput, false);
this.cv.addEventListener('touchmove', this.touchInput, false);
this.cv.parent = self;
global.canvas = this;
}
// Function called when a key is pressed, will change direction if arrow key.
directionDown(event) {
var key = event.which || event.keyCode;
var self = this.parent; // have to do this so we are not using the cv object
if (self.directional(key)) {
self.directionLock = true;
if (self.newDirection(key, self.directions, true)) {
self.updateTarget(self.directions);
self.socket.emit('0', self.target);
}
}
}
// Function called when a key is lifted, will change direction if arrow key.
directionUp(event) {
var key = event.which || event.keyCode;
if (this.directional(key)) { // this == the actual class
if (this.newDirection(key, this.directions, false)) {
this.updateTarget(this.directions);
if (this.directions.length === 0) this.directionLock = false;
this.socket.emit('0', this.target);
}
}
}
// Updates the direction array including information about the new direction.
newDirection(direction, list, isAddition) {
var result = false;
var found = false;
for (var i = 0, len = list.length; i < len; i++) {
if (list[i] == direction) {
found = true;
if (!isAddition) {
result = true;
// Removes the direction.
list.splice(i, 1);
}
break;
}
}
// Adds the direction.
if (isAddition && found === false) {
result = true;
list.push(direction);
}
return result;
}
// Updates the target according to the directions in the directions array.
updateTarget(list) {
this.target = { x : 0, y: 0 };
var directionHorizontal = 0;
var directionVertical = 0;
for (var i = 0, len = list.length; i < len; i++) {
if (directionHorizontal === 0) {
if (list[i] == global.KEY_LEFT) directionHorizontal -= Number.MAX_VALUE;
else if (list[i] == global.KEY_RIGHT) directionHorizontal += Number.MAX_VALUE;
}
if (directionVertical === 0) {
if (list[i] == global.KEY_UP) directionVertical -= Number.MAX_VALUE;
else if (list[i] == global.KEY_DOWN) directionVertical += Number.MAX_VALUE;
}
}
this.target.x += directionHorizontal;
this.target.y += directionVertical;
global.target = this.target;
}
directional(key) {
return this.horizontal(key) || this.vertical(key);
}
horizontal(key) {
return key == global.KEY_LEFT || key == global.KEY_RIGHT;
}
vertical(key) {
return key == global.KEY_DOWN || key == global.KEY_UP;
}
// Register when the mouse goes off the canvas.
outOfBounds() {
if (!global.continuity) {
this.parent.target = { x : 0, y: 0 };
global.target = this.parent.target;
}
}
gameInput(mouse) {
if (!this.directionLock) {
this.parent.target.x = mouse.clientX - this.width / 2;
this.parent.target.y = mouse.clientY - this.height / 2;
global.target = this.parent.target;
}
}
touchInput(touch) {
touch.preventDefault();
touch.stopPropagation();
if (!this.directionLock) {
this.parent.target.x = touch.touches[0].clientX - this.width / 2;
this.parent.target.y = touch.touches[0].clientY - this.height / 2;
global.target = this.parent.target;
}
}
// Chat command callback functions.
keyInput(event) {
var key = event.which || event.keyCode;
if (key === global.KEY_FIREFOOD && this.parent.reenviar) {
this.parent.socket.emit('1');
this.parent.reenviar = false;
}
else if (key === global.KEY_SPLIT && this.parent.reenviar) {
document.getElementById('split_cell').play();
this.parent.socket.emit('2');
this.parent.reenviar = false;
}
else if (key === global.KEY_CHAT) {
document.getElementById('chatInput').focus();
}
}
}
module.exports = Canvas;
| JavaScript | 0.000001 | @@ -26,16 +26,53 @@
lobal');
+%0Avar joystick = new VirtualJoystick()
%0A%0Aclass
@@ -1008,32 +1008,224 @@
hInput, false);%0A
+ //Register joystick movements%0A this.cv.addEventListener (joystick.up(), function (event)%7B%0A %09self.reenviar = true;%0A self.directionUp (event);%0A %7D,false);%0A
this.cv.
|
1910bb0f6f9da8f90cf0cba9a16c98975144b651 | fix link typo | app/components/About/index.js | app/components/About/index.js | /**
*
* About
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import { Link } from 'react-router';
import slacLogo from 'components/Header/SLAC_Logo.png';
import doeLogo from 'components/Header/DOE_Logo.gif';
import stanfordLogo from 'components/Header/stanford_crop.png';
import { mainPeople, otherPeople } from 'utils/constants';
import { styles } from './styles';
import ccLogoBig from './ccLogoBig.svg';
function toSlugFormat(s) {
return s.split(',')
.reverse()
.map((x) => x.trim())
.join(' ')
.replace('.', '')
.replace(/\s/g, '-')
.toLowerCase();
}
class About extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<Paper className={this.props.classes.paper}>
<h2>About Catalysis-Hub.org</h2>
<div className={this.props.classes.paragraph}>
Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research. The Surface Reactions database (CatApp v2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.
</div>
<div className={this.props.classes.paragraph}>
Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
</div>
<div className={this.props.classes.paragraph}>
Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
</div>
<div className={this.props.classes.paragraph}>
All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
</div>
<div className={this.props.classes.paragraph}>
As such Catalysis-Hub aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.
</div>
</Paper>
{/*
<Paper className={this.props.classes.paper}>
<h2>Database Statistics</h2>
</Paper>
*/}
<Paper className={this.props.classes.paper}>
<h2>License</h2>
<img src={ccLogoBig} alt="ccLogoBig" />
<div className={this.props.classes.text}>
Except where otherwise noted, content on Catalysis-Hub is licensed under a
{' '}
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>
.
</div>
</Paper>
<Paper className={this.props.classes.paper}>
<h2>People</h2>
<ul className={this.props.classes.peopleList}>
{Object.keys(mainPeople).map((name, i) => (
<li key={`person_${i}`}>
<a href={mainPeople[name][1]} target="_blank">
{name}
</a>
{' '}
{mainPeople[name][0]}
</li>
))}
</ul>
<h2>Contributors & Collaborators</h2>
<ul className={this.props.classes.peopleList}>
{Object.keys(otherPeople).map((name, i) => (
<li key={`person_${i}`}>
<a href={`http://suncat.stanford.edu/people/${toSlugFormat(name)}`} target="_blank">
{name}
</a>
</li>
))}
<li key="all_pup_people">
<Link
to={'/profile}'}
>
See all dataset contributors
</Link>
</li>
</ul>
</Paper>
<Paper className={this.props.classes.paper}>
<h2>Partners and Support</h2>
<Grid
container
direction="row"
justify="space-between"
style={{
padding: '4%',
}}
>
<Grid item lg={4} className={this.props.classes.bannerBox}>
<a href="https://www6.slac.stanford.edu/" target="_blank">
<img
src={slacLogo}
alt="SLAC Logo"
style={{
width: '240px', height: 'auto', display: 'block', margin: '0 auto',
}}
/>
</a>
</Grid>
<Grid item lg={4} className={this.props.classes.bannerBox}>
<a href="https://www.stanford.edu/" target="_blank">
<img
src={stanfordLogo}
alt="Stanford Logo"
style={{
width: '300px', height: 'auto', display: 'block', margin: '0 auto',
}}
/>
</a>
</Grid>
<Grid item lg={4} className={this.props.classes.bannerBox}>
<a href="https://www.energy.gov/" target="_blank">
<img
src={doeLogo}
alt="Department of Energy Logo"
style={{
width: '260px', height: 'auto', display: 'block', margin: '0 auto',
}}
/>
</a>
</Grid>
</Grid>
</Paper>
</div>
);
}
}
About.propTypes = {
classes: PropTypes.object,
};
export default withStyles(styles, { withTheme: true })(About);
| JavaScript | 0.000001 | @@ -5219,17 +5219,16 @@
/profile
-%7D
'%7D%0A
|
3512e40c1af015fb32af911778c2b73d351e1997 | set optional mapping function as data attribute and pull JSON formatting into function | app/components/export-tool.js | app/components/export-tool.js | import Ember from 'ember';
export default Ember.Component.extend({
attributeBindings: ['data', 'mappingFunction'],
processedData: Ember.computed( 'data', {
get() {
var dataArray = this.get('data');
if (Ember.isPresent(dataArray)) {
console.log(dataArray);
// var dataArray = data.content;
var jsonData = "";
for (var i = 0; i < dataArray.length; i++) {
jsonData = jsonData + JSON.stringify(dataArray[i]._data);
}
//var csvData = this.convertToCSV(dataArray);
return jsonData;
} else {
return null;
}
},
set(_, value) {
this.set('processedData', value);
}
}),
convertToCSV: function (objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
},
});
| JavaScript | 0 | @@ -155,19 +155,38 @@
'data',
+ 'mappingFunction',
%7B%0A
-
@@ -239,16 +239,79 @@
data');%0A
+ var mappingFunction = this.get('mappingFunction');%0A
@@ -344,16 +344,52 @@
taArray)
+ && Ember.isPresent(mappingFunction)
) %7B%0A
@@ -412,25 +412,31 @@
ole.log(
-dataArray
+mappingFunction
);%0A
@@ -450,249 +450,99 @@
-// var dataArray = data.content;%0A var jsonData = %22%22;%0A %0A for (var i = 0; i %3C dataArray.length; i++) %7B%0A jsonData = jsonData + JSON.stringify(dataArray%5Bi%5D._data);%0A %7D
+return this.convertToJSON(dataArray); %0A %7D else if (Ember.isPresent(dataArray)) %7B
%0A
@@ -558,23 +558,14 @@
-//var csvData =
+return
thi
@@ -575,19 +575,20 @@
onvertTo
-CSV
+JSON
(dataArr
@@ -595,41 +595,8 @@
ay);
-%0A return jsonData;
%0A
@@ -661,21 +661,8 @@
%7D%0A
- %0A
@@ -753,16 +753,16 @@
%7D%0A
-
%7D),%0A
@@ -757,16 +757,291 @@
%7D),%0A
+ convertToJSON: function (dataArray) %7B%0A console.log(dataArray);%0A var jsonData = %22%22;%0A %0A for (var i = 0; i %3C dataArray.length; i++) %7B%0A jsonData = jsonData + JSON.stringify(dataArray%5Bi%5D._data);%0A %7D%0A return jsonData;%0A %7D,%0A
conv
|
39b57da42b1f5f98f4db327df5a1f09d3449d289 | Remove a debugging trace. | src/collection/redis.js | src/collection/redis.js | import Bluebird, {coroutine} from 'bluebird';
import Collection, {ModelAlreadyExists} from '../collection';
import difference from 'lodash.difference';
import filter from 'lodash.filter';
import forEach from 'lodash.foreach';
import getKey from 'lodash.keys';
import isEmpty from 'lodash.isempty';
import map from 'lodash.map';
import thenRedis from 'then-redis';
//////////////////////////////////////////////////////////////////////
// Data model:
// - prefix +'_id': value of the last generated identifier;
// - prefix +'_ids': set containing identifier of all models;
// - prefix +'_'+ index +':' + value: set of identifiers which have
// value for the given index.
// - prefix +':'+ id: hash containing the properties of a model;
//////////////////////////////////////////////////////////////////////
// TODO: then-redis sends commands in order, we should use this
// semantic to simplify the code.
// TODO: Merge the options in the object to obtain extend-time
// configuration like Backbone.
// TODO: Remote events.
export default class Redis extends Collection {
constructor({
connection,
indexes = [],
prefix,
uri = 'tcp://localhost:6379',
}) {
super();
this.indexes = indexes;
this.prefix = prefix;
this.redis = connection || thenRedis.createClient(uri);
}
_extract(ids) {
let prefix = this.prefix + ':';
let {redis} = this;
return Bluebird.map(ids, id => {
return redis.hgetall(prefix + id).then(model => {
// If empty, consider it a no match and return null.
if (isEmpty(model)) {
return null;
}
// Mix the identifier in.
model.id = id;
return model;
});
}).tap(console.log);
}
_add(models, {replace = true} = {}) {
// TODO: remove “replace” which is a temporary mesure, implement
// “set()” instead.
let {indexes, prefix, redis} = this;
return Bluebird.map(models, coroutine(function *(model) {
// Generate a new identifier if necessary.
if (model.id === undefined) {
model.id = yield redis.incr(prefix + '_id');
}
let success = yield redis.sadd(prefix + '_ids', model.id);
// The entry already exists an we are not in replace mode.
if (!success && !replace) {
throw new Collection.ModelAlreadyExists(model.id);
}
// TODO: Remove existing fields.
let params = [];
forEach(model, (value, name) => {
// No need to store the identifier (already in the key).
if (name === 'id') {
return;
}
params.push(name, value);
});
let promises = [
redis.hmset(prefix + ':' + model.id, ...params),
];
// Update indexes.
forEach(indexes, (index) => {
let value = model[index];
if (value === undefined) {
return;
}
let key = prefix + '_' + index + ':' + value;
promises.push(redis.sadd(key, model.id));
});
yield Bluebird.all(promises);
return model;
}));
}
_get(properties) {
let {prefix, redis} = this;
if (isEmpty(properties)) {
return redis.smembers(prefix + '_ids').then(ids => this._extract(ids));
}
// Special treatment for the identifier.
let id = properties.id;
if (id !== undefined) {
delete properties.id
return this._extract([id]).then(models => {
return (models.length && !isEmpty(properties)) ?
filter(models) :
models
;
});
}
let {indexes} = this;
// Check for non indexed fields.
let unfit = difference(getKey(properties), indexes);
if (unfit.length) {
throw new Error('fields not indexed: ' + unfit.join());
}
let keys = map(properties, (value, index) => prefix + '_' + index + ':' + value);
return redis.sinter(...keys).then(ids => this._extract(ids));
}
_remove(ids) {
let {prefix, redis} = this;
// TODO: handle indexes.
return Bluebird.all([
// Remove the identifiers from the main index.
redis.srem(prefix + '_ids', ...ids),
// Remove the models.
redis.del(map(ids, id => prefix + ':' + id)),
]);
}
_update(models) {
return this._add(models, { replace: true });
}
}
| JavaScript | 0.000003 | @@ -1704,25 +1704,8 @@
%7D)
-.tap(console.log)
;%0A
|
77484ccdf3ea41eb660c01cc50877dbf50566507 | Remove duplicate definition of path variable | src/command-line/add.js | src/command-line/add.js | var ClientManager = new require("../clientManager");
var bcrypt = require("bcrypt");
var fs = require("fs");
var program = require("commander");
var mkdirp = require("mkdirp");
var Helper = require("../helper");
program
.command("add <name>")
.description("Add a new user")
.action(function(name) {
try {
var path = Helper.resolveHomePath("users");
mkdirp.sync(path);
} catch (e) {
console.log("");
console.log("Could not create " + path);
console.log("Try running the command as sudo.");
console.log("");
return;
}
try {
var path = Helper.resolveHomePath("users");
var test = path + "/.test";
fs.mkdirSync(test);
fs.rmdirSync(test);
} catch (e) {
console.log("");
console.log("You have no permissions to write to " + path);
console.log("Try running the command as sudo.");
console.log("");
return;
}
var manager = new ClientManager();
var users = manager.getUsers();
if (users.indexOf(name) !== -1) {
console.log("");
console.log("User '" + name + "' already exists.");
console.log("");
return;
}
require("read")({
prompt: "Password: ",
silent: true
}, function(err, password) {
console.log("");
if (err) {
return;
}
var hash = bcrypt.hashSync(password, 8);
manager.addUser(
name,
hash
);
console.log("Added '" + name + "'.");
console.log("");
});
});
| JavaScript | 0.00002 | @@ -179,43 +179,51 @@
);%0D%0A
-var Helper = require(%22../helper%22);%0D
+%0Aconst HOME = process.env.HOME + %22/.shout%22;
%0A%0D%0Ap
@@ -315,26 +315,16 @@
ame) %7B%0D%0A
-%09%09try %7B%0D%0A%09
%09%09var pa
@@ -356,24 +356,32 @@
th(%22users%22);
+%0A%09%09try %7B
%0D%0A%09%09%09mkdirp.
@@ -580,56 +580,8 @@
%7B%0D%0A
-%09%09%09var path = Helper.resolveHomePath(%22users%22);%0D%0A
%09%09%09v
|
e0f5a29eb0d2bd397b5c5abf4f0ab0de68f89ef2 | Migrate to new config layout | src/commands/release.js | src/commands/release.js | const path = require('path')
const chalk = require('chalk')
const { prompt } = require('inquirer')
const Listr = require('listr')
const Command = require('../Command')
const readProjectConfiguration = require('../tasks/readProjectConfiguration')
const scanPluginsVersion = require('../tasks/scanPluginsVersion')
const createCheckoutPlugin = require('../tasks/checkoutPlugin')
const updatePluginsVersion = require('../tasks/updatePluginsVersion')
const { checkMode } = require('../utils/tasks')
const { DEFAULT_PLUGIN_DEV_BRANCH, PLUGIN_PREFIX, DEV_MODE } = require('../constants')
const selectNextVersion = versions => prompt([{
type: 'list',
name: 'nextVersion',
choices: Object.entries(versions).map(([name, version]) => ({
name: `${name} ${version}`,
value: version,
})),
message: 'Select next version:',
}])
const askWantToContinue = () => prompt([{
type: 'confirm',
name: 'confirm',
message: 'Want to continue ?',
default: false,
}])
class ReleaseCommand extends Command {
constructor([...args], options) {
super(options)
}
init() {
return [
readProjectConfiguration,
{
title: 'Checkout plugins',
before: ctx => {
if (!checkMode(ctx, DEV_MODE)) {
throw new Error('Release available only in development mode')
}
},
task: ctx => {
const pluginsPath = path.resolve(ctx.projectPath, ctx.configuration.pluginsPath)
const plugins = ctx.configuration.plugins.map(pluginName => ({
name: pluginName,
path: path.resolve(pluginsPath, `./${pluginName}`),
}))
ctx.plugins = plugins
return new Listr(plugins.map(plugin =>
createCheckoutPlugin(plugin.name, plugin.path, DEFAULT_PLUGIN_DEV_BRANCH)
))
},
},
scanPluginsVersion,
{
title: 'Check dependencies',
task: ctx => {
const pluginNames = ctx.plugins.map(({ packageInfo }) => packageInfo.name)
const dependencies = Object.keys(
ctx.plugins.reduce((result, { packageInfo }) => Object.assign(
result,
packageInfo.dependencies,
packageInfo.devDependencies,
packageInfo.peerDependencies
), {})
).filter(dependency => dependency.startsWith(PLUGIN_PREFIX))
const notFoundDependencies = dependencies.filter(dependency => pluginNames.indexOf(dependency) === -1)
if (notFoundDependencies.length) {
console.log(
chalk.bold.red('Can\'t find dependencies in project:\n'),
chalk.cyan(notFoundDependencies.join(', '))
)
return askWantToContinue()
.then(({ confirm }) =>
!confirm && Promise.reject(new Error('Interrupt command'))
)
}
return Promise.resolve()
},
},
{
title: 'Select version',
task: ctx => {
const { major, minor, patch } = ctx.maxVersion
const versions = {
CURRENT: `${major}.${minor}.${patch}`,
PATCH: `${major}.${minor}.${+patch + 1}`,
MINOR: `${major}.${+minor + 1}.0`,
MAJOR: `${+major + 1}.0.0`,
}
return selectNextVersion(versions)
.then(({ nextVersion }) => {
ctx.nextVersion = nextVersion
})
},
},
updatePluginsVersion,
]
}
}
ReleaseCommand.commandName = 'release'
ReleaseCommand.commandDescription = 'Release plugins'
module.exports = ReleaseCommand
| JavaScript | 0 | @@ -1500,20 +1500,16 @@
p(plugin
-Name
=%3E (%7B%0A
@@ -1531,17 +1531,18 @@
: plugin
-N
+.n
ame,%0A
@@ -1593,17 +1593,18 @@
$%7Bplugin
-N
+.n
ame%7D%60),%0A
|
9c1cecbb7d747f7d03416912bf0eff4309996c45 | disable for now | src/common/dev-tools.js | src/common/dev-tools.js | module.exports = process.env.NODE_ENV !== 'production' && require('./dev-tools.dev')
| JavaScript | 0 | @@ -9,16 +9,25 @@
xports =
+ false //
process
|
14cb0ea3005694e1453e80ae80e9a286cd0c3acb | Update core.client.routes.js | public/modules/core/config/core.client.routes.js | public/modules/core/config/core.client.routes.js | 'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/');
// Home state routing
$stateProvider.
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('test', {
url: '/test',
templateUrl: 'modules/core/views/test.client.view.html'
}).
state('item', {
url: '/item',
templateUrl: 'modules/core/views/item.client.view.html'
}).
state('wizard', {
url: '/item-form',
templateUrl: 'modules/core/views/form.item.client.view.html',
resolve: {
loadPlugin: function ($ocLazyLoad) {
return $ocLazyLoad.load([
{
files: ['modules/core/css/plugins/steps/jquery.steps.css']
}
]);
}
}
}).
state('item.forms.wizard.step_one', {
url: '/item-form/step_one',
templateUrl: 'modules/core/views/wizard/step_one.html'
})
.state('item.forms.wizard.step_two', {
url: '/item-form/step_two',
templateUrl: 'modules/core/views/wizard/step_two.html'
})
.state('item.forms.wizard.step_three', {
url: '/item-form/step_three',
templateUrl: 'modules/core/views/wizard/step_three.html'
})
;
}
]);
| JavaScript | 0.000002 | @@ -671,25 +671,24 @@
%09url: '/item
--
form',%0A%09%09%09te
|
785458b5b04b3e88c0f04ef772bf350553d1ae67 | Remove passwords | e2e/helpers/authenticate.js | e2e/helpers/authenticate.js | 'use strict';
const roles = {
EMPLOYEE: {
password: process.env.PASSWORD_EMPLOYEE || 'Winterdag2016',
username: process.env.USERNAME_EMPLOYEE || '[email protected]'
},
EMPLOYEE_PLUS: {
password: process.env.PASSWORD_EMPLOYEE_PLUS || 'Winterdag2016',
username: process.env.USERNAME_EMPLOYEE_PLUS || '[email protected]'
}
};
module.exports = {
login: (role) => {
browser.get('http://localhost:8000');
element(by.css('.qa-menu__login')).isPresent().then((present) => {
if (present && role) {
browser.driver.findElement(by.css('.qa-menu__login')).click();
browser.driver.findElement(by.css('input[name="email"]')).sendKeys(roles[role].username);
browser.driver.findElement(by.css('input[name="password"]')).sendKeys(roles[role].password);
browser.driver.findElement(by.css('.c-form-buttons__button[value="employee_plus"]')).click();
browser.refresh();
}
browser.getLocationAbsUrl(); // NB: Forces to await login flow completion
});
},
logout: () => {
element(by.css('.qa-menu__user-menu .c-menu__item--toggle')).isDisplayed().then((present) => {
if (present) {
browser.driver.findElement(by.css('.qa-menu__toggle .qa-menu__link')).click();
browser.driver.findElement(by.css('.qa-menu__dropdown dp-logout-button button')).click();
}
});
}
};
| JavaScript | 0.000149 | @@ -87,35 +87,16 @@
EMPLOYEE
- %7C%7C 'Winterdag2016'
,%0A
@@ -254,27 +254,8 @@
PLUS
- %7C%7C 'Winterdag2016'
,%0A
|
ecbb6626e5c8ca4ed19d5eb49caf4f90a41f5833 | Change prefix to '?' | Commando.js | Commando.js | global.Promise = require('bluebird');
const commando = require('discord.js-commando');
const oneLine = require('common-tags').oneLine;
const path = require('path');
const winston = require('winston');
const Database = require('./postgreSQL/postgreSQL');
const config = require('./settings');
const database = new Database();
const client = new commando.Client({
owner: config.owner,
commandPrefix: 'sir, ',
unknownCommandResponse: false,
disableEveryone: true
});
client.on('error', winston.error)
.on('warn', winston.warn)
.on('ready', () => {
winston.info(`Client ready; logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id})`);
})
.on('disconnect', () => { winston.warn('Disconnected!'); })
.on('reconnect', () => { winston.warn('Reconnecting...'); })
.on('commandError', (cmd, err) => {
if (err instanceof commando.FriendlyError) return;
winston.error(`Error in command ${cmd.groupID}:${cmd.memberName}`, err);
})
.on('commandBlocked', (msg, reason) => {
winston.info(oneLine`
Command ${msg.command ? `${msg.command.groupID}:${msg.command.memberName}` : ''}
blocked; ${reason}
`);
})
.on('commandPrefixChange', (guild, prefix) => {
winston.info(oneLine`
Prefix changed to ${prefix || 'the default'}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
})
.on('commandStatusChange', (guild, command, enabled) => {
winston.info(oneLine`
Command ${command.groupID}:${command.memberName}
${enabled ? 'enabled' : 'disabled'}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
})
.on('groupStatusChange', (guild, group, enabled) => {
winston.info(oneLine`
Group ${group.id}
${enabled ? 'enabled' : 'disabled'}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
});
client.registry
.registerGroups([
['info', 'Info'],
['math', 'Math'],
['fun', 'Fun'],
['weather', 'Weather'],
['music', 'Music'],
['tags', 'Tags'],
['rep', 'Reputation']
])
.registerDefaults()
.registerCommandsIn(path.join(__dirname, 'commands'));
database.start();
client.login(config.token);
| JavaScript | 0.002456 | @@ -401,13 +401,9 @@
x: '
-sir,
+?
',%0A%09
|
4ad6ff1ffa55320236c0596ecda35db95ba1d24a | update json limit | HUla/app.js | HUla/app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
global._ = global._ || require('underscore');
var routes = require('./routes/index');
// var contractRouter = require('./routes/contract');
// var serviceRouter = require('./routes/service');
// var caseRouter = require('./routes/case');
// var restServiceRouter = require('./routes/restapi/service');
// var restContractRouter = require('./routes/restapi/contract');
// var restCaseRouter = require('./routes/restapi/case');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// app.use('/service', serviceRouter);
// app.use('/contract', contractRouter);
// app.use('/case', caseRouter);
// app.use('/restapi/service', restServiceRouter);
// app.use('/restapi/contract', restContractRouter);
// app.use('/restapi/case', restCaseRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| JavaScript | 0.000001 | @@ -920,16 +920,30 @@
er.json(
+%7Blimit: '5mb'%7D
));%0Aapp.
|
5cf46a28efec1ffd12edaa21de18860c7e6d4591 | Set the install task to a dependency of build. | Gulpfile.js | Gulpfile.js | 'use strict';
var gulp = require('gulp'),
addsrc = require('gulp-add-src'),
concat = require('gulp-concat'),
cssnano = require('gulp-cssnano'),
del = require('del'),
filter = require('gulp-filter'),
htmlmin = require('gulp-htmlmin'),
imagemin = require('gulp-imagemin'),
install = require('gulp-install'),
jshint = require('gulp-jshint'),
mainBowerFiles = require('gulp-main-bower-files'),
pngquant = require('imagemin-pngquant'),
run = require('childish-process'),
sourcemaps = require('gulp-sourcemaps'),
uglify = require('gulp-uglify'),
watch = require('gulp-watch');
gulp.task('default', ['serve']);
gulp.task('serve', function() {
run('node ./bin/www');
run('gulp watch');
});
gulp.task('watch', ['build', 'registerWatchTasks']);
gulp.task('build', ['clean', 'jshint', 'minHtml', 'minCss', 'minJs', 'minImages']);
gulp.task('install', function() {
gulp.src(['./bower.json', './package.json'])
.pipe(install());
});
gulp.task('clean', function(cb) {
del.sync(['public/dist', 'public/src/css/vendor', 'public/src/js/vendor'], cb);
});
gulp.task('registerWatchTasks', function() {
watch('Gulpfile.js', function() {
gulp.start('build');
});
watch('public/src/js/**/*.html', function() {
gulp.start('minHtml');
});
watch('bower_components/**/*.css', function() {
gulp.start('minVendorCss');
});
watch('public/src/css/**/*.css', function() {
gulp.start('minAppCss');
});
watch('bower_components/**/*.js', function() {
gulp.start('minVendorJs');
});
watch('public/src/js/**/*.js', function() {
gulp.start('jshint');
gulp.start('minAppJs');
});
watch('public/images/**/*.*', function() {
gulp.start('minImages');
});
});
gulp.task('minHtml', function() {
return gulp.src('public/src/**/*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('public/dist'));
});
gulp.task('minCss', ['minVendorCss', 'minAppCss']);
gulp.task('minVendorCss', function() {
var cssFilter = filter('**/*.css');
return gulp.src('./bower.json')
.pipe(mainBowerFiles())
.pipe(cssFilter)
.pipe(addsrc.prepend('bower_components/html5-boilerplate/dist/css/main.css'))
.pipe(addsrc.prepend('bower_components/html5-boilerplate/dist/css/normalize.css'))
.pipe(sourcemaps.init())
.pipe(concat('vendor.css'))
.pipe(cssnano())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('public/dist/css'));
});
gulp.task('minAppCss', function() {
return gulp.src('public/src/css/**/*.css')
.pipe(sourcemaps.init())
.pipe(cssnano())
.pipe(concat('app.css'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('public/dist/css'));
});
gulp.task('minJs', ['minVendorJs', 'minAppJs']);
gulp.task('minVendorJs', function() {
var jsFilter = filter('**/*.js');
return gulp.src('./bower.json')
.pipe(mainBowerFiles())
.pipe(jsFilter)
.pipe(sourcemaps.init())
.pipe(concat('vendor.js'))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('public/dist/js'));
});
gulp.task('jshint', function() {
return gulp.src('public/src/js/**/*.js')
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('minAppJs', ['jshint'], function() {
return gulp.src('public/src/js/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('app.js'))
.pipe(uglify())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('public/dist/js'));
});
gulp.task('minImages', function() {
return gulp.src('public/src/images/*')
.pipe(imagemin({
// JPG
progressive: true,
// PNG
optimizationLevel: 4,
use: [pngquant()],
// SVG
multipass: true,
svgoPlugins: [{ removeViewBox: false }]
}))
.pipe(gulp.dest('public/dist/images'));
});
| JavaScript | 0 | @@ -778,16 +778,27 @@
'clean',
+ 'install',
'jshint
|
895ce9963ee3c23ffd25f032ac0806d23f55be86 | fix up gulp build. watch processes killed for bundler | Gulpfile.js | Gulpfile.js | 'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var mergeStream = require('merge-stream');
var objectAssign = require('object-assign');
var browserify = require('browserify');
var reactify = require('reactify');
var concat = require('gulp-concat'),
livereload = require('gulp-livereload'),
dest = 'dist',
lvPort = 35729;
var static_server = require('./static_server');
var indexBundler = bundlerBuilder('./src/js/index.jsx', 'index.js');
var viewerBundler = bundlerBuilder('./src/js/viewer.jsx', 'viewer.js');
function bundlerBuilder (startPath, finishName) {
var bundler = watchify(browserify(startPath, objectAssign({debug: true}, watchify.args)));
bundler.transform(reactify);
var rebundle = function() {
return bundler.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source(finishName))
.pipe(gulp.dest('dist/js'));
};
return {bundler: bundler, rebundle: rebundle};
}
gulp.task('html', function() {
return gulp.src('src/*.html')
.pipe(gulp.dest('dist'));
});
gulp.task('css', function() {
return gulp.src('src/css/**/*.css')
.pipe(gulp.dest(dest + '/css'));
});
gulp.task('bundlejs', function() {
return mergeStream(
indexBundler.rebundle(),
viewerBundler.rebundle()
);
});
gulp.task('build', ['bundlejs', 'html', 'css']);
gulp.task('watch', function () {
// trigger livereload on any change to dest
livereload.listen(lvPort);
gulp.watch(dest + '/**').on('change', livereload.changed);
// html changes
gulp.watch('src/*.html', ['html']);
// css changes
gulp.watch('src/css/**/*.css', ['css']);
indexBundler.bundler.on('update', indexBundler.rebundle);
viewerBundler.bundler.on('update', viewerBundler.rebundle);
});
gulp.task('serve', ['build'], function(next) {
static_server(dest, {callback: next, livereload: true});
});
gulp.task('deploy', ['build'], function() {
var deployCdn = require('deploy-azure-cdn');
return gulp.src(['dist/**/*'])
.pipe(deployCdn.gulpPlugin({
containerName: 'site',
serviceOptions: ['mediaplayercontroller', '6mzoatD04udXOQE1EpxIHhCDQLui3G6kKWtE4kJqWGO7n6mdKYXB14P/8okDfKTF/wyVmgOIlzgt/4yOotTl0g==']
}));
});
gulp.task('default', ['build', 'serve', 'watch']); | JavaScript | 0.000001 | @@ -1328,32 +1328,141 @@
', function() %7B%0A
+ // watchify watch handles must be closed, otherwise gulp task will hang,%0A // thus the .on('end', ...)%0A
return merge
@@ -1469,16 +1469,20 @@
Stream(%0A
+
@@ -1510,24 +1510,28 @@
(),%0A
+
+
viewerBundle
@@ -1546,15 +1546,139 @@
le()
-%0A );
+)%0A .on('end', function() %7B%0A indexBundler.bundler.close();%0A viewerBundler.bundler.close();%0A %7D);%0A
%0A%7D);
|
ee59d82849dd72f593d1d39c0c91b073a3f63e92 | Add `"type": "module"` to `@apollo/client/core` | config/prepareDist.js | config/prepareDist.js | // The Apollo Client source that is published to npm is located in the
// "dist" directory. This utility script is called when building Apollo Client,
// to make sure the "dist" directory is prepared for publishing.
//
// This script will:
//
// - Copy the current root package.json into "dist" after adjusting it for
// publishing.
// - Copy the supporting files from the root into "dist" (e.g. `README.MD`,
// `LICENSE`, etc.).
// - Create a new `package.json` for each sub-set bundle we support, and
// store it in the appropriate dist sub-directory.
const fs = require('fs');
const path = require('path');
const recast = require('recast');
const distRoot = `${__dirname}/../dist`;
/* @apollo/client */
const packageJson = require('../package.json');
const entryPoints = require('./entryPoints.js');
// The root package.json is marked as private to prevent publishing
// from happening in the root of the project. This sets the package back to
// public so it can be published from the "dist" directory.
packageJson.private = false;
// Remove package.json items that we don't need to publish
delete packageJson.scripts;
delete packageJson.bundlesize;
// The root package.json points to the CJS/ESM source in "dist", to support
// on-going package development (e.g. running tests, supporting npm link, etc.).
// When publishing from "dist" however, we need to update the package.json
// to point to the files within the same directory.
const distPackageJson = JSON.stringify(packageJson, (_key, value) => {
if (typeof value === 'string' && value.startsWith('./dist/')) {
const parts = value.split('/');
parts.splice(1, 1); // remove dist
return parts.join('/');
}
return value;
}, 2) + "\n";
// Save the modified package.json to "dist"
fs.writeFileSync(`${distRoot}/package.json`, distPackageJson);
// Copy supporting files into "dist"
const srcDir = `${__dirname}/..`;
const destDir = `${srcDir}/dist`;
fs.copyFileSync(`${srcDir}/README.md`, `${destDir}/README.md`);
fs.copyFileSync(`${srcDir}/LICENSE`, `${destDir}/LICENSE`);
// Create individual bundle package.json files, storing them in their
// associated dist directory. This helps provide a way for the Apollo Client
// core to be used without React, as well as AC's cache, utilities, SSR,
// components, HOC, and various links to be used by themselves, via CommonJS
// entry point files that only include the exports needed for each bundle.
entryPoints.forEach(function buildPackageJson({
dirs,
bundleName = dirs[dirs.length - 1],
sideEffects = false,
}) {
if (!dirs.length) return;
fs.writeFileSync(
path.join(distRoot, ...dirs, 'package.json'),
JSON.stringify({
name: path.posix.join('@apollo', 'client', ...dirs),
main: `${bundleName}.cjs.js`,
module: 'index.js',
types: 'index.d.ts',
sideEffects,
}, null, 2) + "\n",
);
});
| JavaScript | 0.999999 | @@ -2840,16 +2840,70 @@
ffects,%0A
+ ...dirs.includes('core') && %7B type: %22module%22 %7D,%0A
%7D, n
|
91e3c6bddf1345970b7e2f8a34a487ccf9dc5224 | Add code framework to return data from test | sashimi-webapp/test/database/sqlCommands_test.js | sashimi-webapp/test/database/sqlCommands_test.js | /*
* Test-unit framework for sqlCommands.js
*/
const assert = require('assert');
const vows = require('vows');
const Sql = require('../../src/database/sql-related/sqlCommands');
const sqlCommands = new Sql();
const isNotEmptyTable = function isNotEmptyTable(stringResult) {
return stringResult !== undefined;
};
const sqlCommandsTest = function sqlCommandsTest() {
this.testCreateTable = function testCreateTable() {
try {
sqlCommands.deleteTable('demo');
} catch (e) {
//
}
sqlCommands.createTable('CREATE TABLE demo (paramX INT)');
const tableData = sqlCommands.getFullTableData('demo');
assert.isTrue(isNotEmptyTable(tableData));
sqlCommands.deleteTable('demo');
};
this.testCreateTable();
};
module.exports = sqlCommandsTest;
sqlCommandsTest();
/* Failed attempt to test on travis
vows.describe('Test SQL Statements').addBatch({
'table creation': {
topic: createTable(),
'create table': CreateTable(topic) {
DeleteTable(tableName);
CreateTable(createTableSql);
const tableData = sqlCommands.getFullTableData('tableName');
assert.isNotEmptyTable(tableData);
}
}
}).export(module);
*/
| JavaScript | 0.000003 | @@ -315,16 +315,94 @@
ed;%0A%7D;%0A%0A
+const returnTableToMemory = function(tableData) %7B%0A // do nothing for now%0A%7D;%0A%0A
const sq
@@ -496,24 +496,79 @@
teTable() %7B%0A
+ let preData = '';%0A let isPreDataExists = false;%0A
try %7B%0A
@@ -628,18 +628,93 @@
%7B%0A
-//
+preData = sqlCommands.getFullTableData('demo');%0A isPreDataExists = true;
%0A %7D%0A
@@ -919,16 +919,85 @@
demo');%0A
+ if (isPreDataExists) %7B%0A returnTableToMemory(preData);%0A %7D%0A
%7D;%0A%0A
|
a2981360a9531458ce590eb8c6144fbd64848d90 | Add parser to ts overrides | configs/typescript.js | configs/typescript.js | module.exports = {
plugins: ['@typescript-eslint'],
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
// typescript will handle this so no need for it
'no-undef': 'off',
'no-unused-vars': 'off',
'no-use-before-define': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-use-before-define': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-expect-error': 'allow-with-description',
'ts-ignore': 'allow-with-description',
'ts-nocheck': true,
'ts-check': false,
minimumDescriptionLength: 3,
},
],
},
},
],
};
| JavaScript | 0 | @@ -106,16 +106,59 @@
.tsx'%5D,%0A
+ parser: '@typescript-eslint/parser',%0A
ru
|
0aa2e65b17c3d442ba3b533c9b9f97a097d9ee6d | Use tooltip titles | assets/js/bootstrap-global.js | assets/js/bootstrap-global.js | (function ($, document, window, undefined) {
'use strict';
var $document = $(document), $window = $(window), eventNames = {
ready: 'ise:ready',
load: 'ise:load'
}, selectors = {
time: '.timeago',
modal: '.modal'
};
/**
* Initialise
*/
function initialise() {
$document.ready(documentReady).on(eventNames.ready, iseReady);
$window.load(windowLoad);
}
/**
* Register document ready event
*/
function documentReady() {
// Wrap it to unsure it fires last
$document.ready(function() {
$document.trigger(eventNames.ready);
});
}
/**
* Register window load event
*/
function windowLoad() {
$window.trigger(eventNames.load);
}
/**
* Custom ready event
*/
function iseReady() {
$(selectors.time).timeago();
$(selectors.modal).modal().on('shown.bs.modal', modalShown);
}
/**
* Modal is shown
*/
function modalShown() {
$(this).focus();
}
// Initialise
initialise();
})(jQuery, document, window); | JavaScript | 0.000001 | @@ -267,16 +267,43 @@
'.modal'
+,%0D%0A title: '%5Btitle%5D'
%0D%0A %7D;
@@ -1056,24 +1056,138 @@
dalShown);%0D%0A
+ $(selectors.title).tooltip(%7B%0D%0A container: 'body',%0D%0A placement: 'auto'%0D%0A %7D);%0D%0A
%7D%0D%0A %0D
|
abb266defb3456802e39b872a68975cbc29947ef | Add support for fundraising event donate links | controllers/donate.js | controllers/donate.js | 'use strict';
const menu = require('./common/menu');
const donate = require('./common/donate');
/* A controller for the donate page. */
function controller(app) {
app.get('/donate', function (req, res) {
donate(app).then(function(donate) {
let data = {
menu: menu(),
donate: donate
};
res.render('donate', data);
});
});
}
module.exports = controller;
| JavaScript | 0 | @@ -197,24 +197,264 @@
req, res) %7B%0A
+ if(process.env.DONATE_URI) %7B%0A // If a donate uri is provided, redirect to that instead of using our%0A // default donate page. This is useful during fundraising events.%0A res.redirect(process.env.DONATE_URI);%0A %7D else %7B%0A
donate(a
@@ -477,24 +477,26 @@
n(donate) %7B%0A
+
let da
@@ -510,16 +510,18 @@
+
menu: me
@@ -526,16 +526,18 @@
menu(),%0A
+
@@ -561,11 +561,15 @@
+
%7D;%0A
+
@@ -602,20 +602,28 @@
a);%0A
+
%7D);%0A
+ %7D%0A
%7D);%0A%7D%0A
|
87cc0594cab7d8b9e660236f32251dcbfe907cb8 | Improve Set polyfill name. Fixes #2 | polyfill.js | polyfill.js | 'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call
, defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf
, SetPoly, getValues;
module.exports = SetPoly = function (/*iterable*/) {
var iterable = arguments[0], self;
if (!(this instanceof SetPoly)) throw new TypeError('Constructor requires \'new\'');
if (isNative && setPrototypeOf) self = setPrototypeOf(new Set(), getPrototypeOf(this));
else self = this;
if (iterable != null) iterator(iterable);
defineProperty(self, '__setData__', d('c', []));
if (!iterable) return self;
forOf(iterable, function (value) {
if (eIndexOf.call(this, value) !== -1) return;
this.push(value);
}, self.__setData__);
return self;
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(SetPoly, Set);
SetPoly.prototype = Object.create(Set.prototype, { constructor: d(SetPoly) });
}
ee(Object.defineProperties(SetPoly.prototype, {
add: d(function (value) {
if (this.has(value)) return this;
this.emit('_add', this.__setData__.push(value) - 1, value);
return this;
}),
clear: d(function () {
if (!this.__setData__.length) return;
clear.call(this.__setData__);
this.emit('_clear');
}),
delete: d(function (value) {
var index = eIndexOf.call(this.__setData__, value);
if (index === -1) return false;
this.__setData__.splice(index, 1);
this.emit('_delete', index, value);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result, value;
callable(cb);
iterator = this.values();
result = iterator._next();
while (result !== undefined) {
value = iterator._resolve(result);
call.call(cb, thisArg, value, value, this);
result = iterator._next();
}
}),
has: d(function (value) {
return (eIndexOf.call(this.__setData__, value) !== -1);
}),
keys: d(getValues = function () { return this.values(); }),
size: d.gs(function () { return this.__setData__.length; }),
values: d(function () { return new Iterator(this); }),
toString: d(function () { return '[object Set]'; })
}));
defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
| JavaScript | 0 | @@ -726,16 +726,59 @@
etValues
+, NativeSet;%0A%0Aif (isNative) NativeSet = Set
;%0A%0Amodul
@@ -808,16 +808,19 @@
unction
+Set
(/*itera
@@ -1009,16 +1009,22 @@
eOf(new
+Native
Set(), g
@@ -1393,16 +1393,22 @@
etPoly,
+Native
Set);%0A%09S
@@ -1440,16 +1440,22 @@
.create(
+Native
Set.prot
|
437cd3d54ae15a78a64357f22d3ed213f72e8a22 | Fix build | Jakefile.js | Jakefile.js | /* jshint node: true, camelcase: false */
/* globals jake: false, task: false */ // Globals exposed by jake
var path = require('path');
task('lint', [], function() {
require('./smpl-build-test');
var files = [];
files.push(path.join(__dirname, 'Jakefile.js'));
files.push(path.join(__dirname, 'package.json'));
files.push(path.join(__dirname, 'smpl-build-test.js'));
var globals = {
};
jake.Task['smpl-build-test:lint'].invoke(files, globals);
}); | JavaScript | 0.000003 | @@ -130,16 +130,58 @@
ath');%0A%0A
+task('test', %5B'lint'%5D, function() %7B%0A%09%0A%7D);%0A
task('li
|
6370d600b19cae30dc7142e3cefa06aeb0579a8b | Add update target | Jakefile.js | Jakefile.js | "use strict";
var child_process = require("child_process");
var fs = require("fs");
var util = require("util");
// for use with child_process.exec/execFile
function execCallback(task) {
return function (error, stdout, stderr) {
if (stdout) console.log(stdout.toString());
if (stderr) console.error(stderr.toString());
if (error) {
console.error(error);
task.fail(error);
}
else task.complete();
}
}
function expand(dir) {
if (Array.isArray(dir)) {
let r = []
dir.forEach(f => expand(f).forEach(x => r.push(x)))
return r
}
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory())
return fs.readdirSync(dir).map(f => dir + "/" + f)
else return [dir]
}
function catFiles(out, files) {
file(out, files, function () {
let cont = files.map(f => fs.readFileSync(f, "utf8").replace(/\r/g, ""))
cont.unshift('"use strict";')
fs.writeFileSync(out, cont.join("\n"))
})
}
function cmdIn(task, dir, cmd) {
console.log(`[${task.name}] cd ${dir}; ${cmd}`)
child_process.exec(cmd, { cwd: dir }, execCallback(task))
}
function tscIn(task, dir) {
cmdIn(task, dir, 'node ../node_modules/typescript/bin/tsc')
}
function compileDir(name, deps) {
if (!deps) deps = []
let dd = expand([name].concat(deps))
file('built/' + name + '.js', dd, {async : true}, function () { tscIn(this, name) })
}
task('default', ['runprj'])
task('clean', function() {
// jake.rmRf("built") - doesn't work?
expand("built").forEach(f => {
try {
fs.unlinkSync(f)
} catch (e) {
console.log("cannot unlink:", f, e.message)
}
})
})
task('runprj', ['built/microbit.js', 'built/mbitsim.js'], {async:true, parallelLimit: 10}, function() {
cmdIn(this, "mbitprj", 'node ../built/mbitsim.js')
})
file('built/microbit.js', ['built/yelm.js'], {async:true}, function() {
let f = fs.readdirSync("mbitprj").filter(f => /\.ts$/.test(f)).join(" ")
cmdIn(this, "mbitprj", 'node ../built/yelm.js compile ' + f)
})
catFiles('built/yelm.js', [
"node_modules/typescript/lib/typescript.js",
"built/emitter.js",
"built/yelmlib.js",
"built/nodeutil.js",
"built/cli.js"
])
file('built/nodeutil.js', ['built/cli.js'])
compileDir("yelmlib", ["built/emitter.js"])
compileDir("cli", ["built/yelmlib.js"])
compileDir("emitter")
compileDir("mbitsim")
| JavaScript | 0 | @@ -2345,8 +2345,163 @@
itsim%22)%0A
+%0Atask('update', %7Basync:true%7D, function() %7B%0A jake.exec(%5B%0A %22git pull%22,%0A %22npm install%22,%0A %22tsd reinstall%22%0A %5D, %7BprintStdout: true%7D);%0A%7D)%0A%0A
|
9e35deb851d5d72eb957dce6565631ddc25e9a80 | fix issue #82 (ticket validation regexp limit) | lib/ticket.js | lib/ticket.js | "use strict";
//const { promisify } = require('util');
var parseUrl = require('url').parse
var querystring = require('querystring')
var logger = require('./logger')('cas_validate::ticket')
var force_protocol=require('./force_protocol')
const got = require('got')
const xmlparser = require('./xml_parser')
function ticket(options){
const cas_host = force_protocol(options.cas_host,options.cas_port)
if (! cas_host ) throw new Error('No CAS host specified. Either include it in the options object {cas_host:"my.cas.host"} or as an environment variable CAS_HOST');
var opt_service = options.service; // for example: 'http://safety.ctmlabs.net/geojson';
if(opt_service === undefined){
throw new Error('API change. The service parameter is now required in the options object because guessing the service from the request header is a security bug')
}
var login_service = options.login_service; // for example: 'http://safety.ctmlabs.net/geojson';
if(login_service === undefined){
// for now, just go with standard path, but perhaps throw here too?
login_service = '/cas/login'
logger.info('setting login service endpoint on CAS server to '+login_service)
}
var validation_service = options.validation_service;
if(validation_service === undefined){
// for now, just go with standard path, but perhaps throw here too?
validation_service = '/cas/serviceValidate'
logger.info('setting validation service endpoint on CAS server to '+validation_service)
}
return function(req,res,next){
// stupid connect/express change, I guess logger.debug('in
// ticket handler, request url is ' + req.url) so url isn't
// passed through cleanly anymore, as the "mount point" is
// stripped.
var url = parseUrl(req.originalUrl,true);
if(url.query === undefined || url.query.ticket === undefined){
logger.debug('moving along, no ticket');
return next();
}
logger.debug('have ticket in query')
if(req.session.st){
// have session, so move along)
logger.debug('session still valid, do not reparse ticket')
return next()
}
// prevent double checking. issue #5
if(req.session.ticket !== undefined
&& req.session.ticket === url.query.ticket){
logger.debug('ticket already checked')
// tried various ways to strip the ticket and redirect
// back, but they all failed, as the browser kept clearing
// the session
// so live with the ticket in the URL
return next()
}
logger.debug('checking ticket')
// validate the ticket.
//
// MUST begin with the characters, "ST-", and must be between
// 32 and 256 characters in length. Unclear is 32 includes
// the ST- characters, so allow for it
//
if(!/^ST-.{28,256}$/.test(url.query.ticket)){
var queryopts = {'service':opt_service};
res.writeHead(307, { 'location': cas_host+login_service
+'?'
+querystring.stringify(queryopts)
});
res.end()
// res.statusCode = 400
// res.end('Invalid service ticket. Contact the Central Authentication Service server administrator')
return null
}
// at this point, the above regex has validated the ticket, so it is okay to pass on as is to the CAS server
// validate the service ticket
var ticket = url.query.ticket;
req.session.ticket = ticket // for next time, to prevent double checks
var cas_uri = cas_host+validation_service
+'?'
+querystring.stringify(
{'service':opt_service,
'ticket':ticket});
logger.debug('make xml parser for response')
const my_parser = xmlparser.make_xml_parser(req,res,next)
const use_resolved = (response)=>{
// logger.error('ticket resolved, statusCode: '+response.statusCode);
// logger.error('body: '+ response.body);
return my_parser(response.body)
}
const handle_reject = (error)=>{
// probably not logged in, but don't get worked up about it
logger.error('error trying to check ticket: '+ error);
return next()
}
logger.debug('firing: '+cas_uri)
// FIXME: reject unauthorized isn't a great idea here, but not
// sure how to fix it. In a testing context, it is unlikely
// that I can get the fake CA injected here. In a real setup,
// it is most likely that the cas service is properly set up
// with correct keys, etc.
// but still, rejectUnauthorized is a hack
const res_promise = got(cas_uri,
{'rejectUnauthorized': false,})
.then(use_resolved,
handle_reject)
.catch((error)=>{
logger.error('caught error outside of handlers: '+error)
return next()
})
return res_promise
}
}
module.exports=ticket
| JavaScript | 0 | @@ -2989,9 +2989,9 @@
-.%7B2
-8
+6
,256
|
de112eb4e3b6529ec68b8e6b3c00950f004a4d6a | Add track link support | lib/tomahk.js | lib/tomahk.js | JavaScript | 0 | @@ -0,0 +1,647 @@
+var http = require('http');%0A%0Amodule.exports = %7B%0A shortenUrl: function (url, cb) %7B%0A http.get(url, function (res) %7B%0A res.on('data', function (data) %7B%0A // seek through data%0A %7D);%0A res.on('end', function () %7B%0A cb(res.headers.location %7C%7C url)%0A %7D);%0A %7D);%0A %7D,%0A%0A shortTrackUrl: function (artist, title, cb) %7B%0A var url = this.trackUrl(artist, title);%0A this.shortenUrl(url, cb);%0A %7D,%0A%0A trackUrl: function (artist, title) %7B%0A return 'http://toma.hk/?artist=' + encodeURIComponent(artist) + '&title=' + encodeURIComponent(title);%0A %7D%0A%0A%7D%0A
|
|
635c895f83407708945633dfefa76ce61d4331ed | Add hyperterm-subpixel-antialiased | .hyperterm.js | .hyperterm.js | module.exports = {
config: {
fontSize: 12,
fontFamily: 'Menlo, "DejaVu Sans Mono", "Lucida Console", monospace',
padding: '10px',
},
plugins: [
'hypercwd',
'hyperterm-blink',
'hyperterm-title',
'hyperterm-one-light'
],
localPlugins: []
};
| JavaScript | 0.998795 | @@ -242,16 +242,54 @@
e-light'
+,%0A 'hyperterm-subpixel-antialiased'
%0A %5D,%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.