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 |
|---|---|---|---|---|---|---|---|
f8ceb41fb04302eeb73302d908b1dfa1e4ab1f23 | Update testPageMetaTags.js | __tests__/e2e/extensions/testPageMetaTags.js | __tests__/e2e/extensions/testPageMetaTags.js | /* eslint-disable no-unused-expressions */
module.exports.command = function (title, description) {
this.expect.element(`meta[name="title"][content="${title}"]`).to.be.present
this.expect.element(`meta[property="og:title"][content="${title}"]`).to.be.present
this.expect.element(`meta[name="twitter:title"][content="${title}"]`).to.be.present
this.expect.element(`meta[name="description"][content="${description}"]`).to.be.present
this.expect.element(`meta[property="og:description"][content="${description}"]`).to.be.present
this.expect.element(`meta[name="twitter:description"][content="${description}"]`).to.be.present
return this
}
| JavaScript | 0.000001 | @@ -112,71 +112,33 @@
ect.
-element(%60meta%5Bname=%22title%22%5D%5Bcontent=%22$%7Btitle%7D%22%5D%60).to.be.present
+title().to.contain(title)
%0A t
|
2160ef938093d01c662c8b5624dcf4db209b41f3 | fix name clash in last JS commit | app/assets/javascripts/app/projects.js | app/assets/javascripts/app/projects.js | $(function(){
var projects = {
init: function() {
this.autoSuggest();
},
autoSuggest: function() {
var $oas = $('input.project-auto-suggest');
var _this = this;
if ($oas.length) {
$oas.keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13)
_this.getSuggestions(true);
else
$(this).data('timer', setTimeout(_this.getSuggestions, 500));
e.preventDefault();
return false;
});
}
},
getSuggestions: function() {
var $oas = $('input.project-auto-suggest');
var str = $oas.val();
if (str.length < 3) {
projects.hideSuggestions();
return;
}
else {
$.ajax({
type: 'GET',
url: '/projects',
data: {
q: str
},
beforeSend: function(){
$oas.addClass('loading');
},
complete: function(){
$oas.removeClass('loading');
},
error: function(){
alert('error');
},
success: function(data){
$('.suggestions').slideUp('fast', function(){
projects.clearSuggestions();
projects.addSuggestions(data);
});
},
dataType: 'json'
});
}
},
addSuggestions: function(data) {
if (data.projects && data.projects.length > 0) {
var projects = data.projects;
var current_project_uris = data.current_project_uris;
var requested_project_uris = data.requested_project_uris;
$.each(projects, function(index, project){
var $suggestion = $('.suggestion-template').clone()
$suggestion.removeClass('suggestion-template').addClass('suggestion');
$suggestion.find('.header').text(project.name);
$suggestion.find('.subheader').text(project.organisation_names);
$suggestion.find('.image img').attr('src', project.image_url);
if($.inArray( project.uri, current_project_uris ) > -1 ){
$suggestion.addClass("current");
$suggestion.find('.messages').text("(already a member)");
}
if($.inArray( project.uri, requested_project_uris ) > -1 ){
$suggestion.addClass("requested");
$suggestion.find('.messages').text("(already requested)");
}
var anchor = $suggestion.find('.action a');
var urlTemplate = anchor.attr('href');
anchor.attr('href', urlTemplate.replace(':project_id', project.guid));
$('.suggestions').append($suggestion);
});
projects.showSuggestions();
}
},
clearSuggestions: function() {
$('.suggestion').remove();
},
showSuggestions: function() {
$('.suggestions').slideDown('fast');
},
hideSuggestions: function() {
$('.suggestions').slideUp('fast', function(){
projects.clearSuggestions();
});
}
}
projects.init();
}); | JavaScript | 0 | @@ -1485,27 +1485,24 @@
var proj
-ect
s = data.pro
@@ -1656,19 +1656,16 @@
ach(proj
-ect
s, funct
|
1d49c8626ec40519a19764959b18efb2868d8f61 | Revert "V8: Don't show multiple open menus (take two) (#5609)" | src/Umbraco.Web.UI.Client/src/common/directives/components/events/events.directive.js | src/Umbraco.Web.UI.Client/src/common/directives/components/events/events.directive.js | /**
* @description Utillity directives for key and field events
**/
angular.module('umbraco.directives')
.directive('onDragEnter', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragEnter);
};
elm.on("dragenter", f);
scope.$on("$destroy", function () { elm.off("dragenter", f); });
}
};
})
.directive('onDragLeave', function () {
return function (scope, elm, attrs) {
var f = function (event) {
var rect = this.getBoundingClientRect();
var getXY = function getCursorPosition(event) {
var x, y;
if (typeof event.clientX === 'undefined') {
// try touch screen
x = event.pageX + document.documentElement.scrollLeft;
y = event.pageY + document.documentElement.scrollTop;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return { x: x, y: y };
};
var e = getXY(event.originalEvent);
// Check the mouseEvent coordinates are outside of the rectangle
if (e.x > rect.left + rect.width - 1 || e.x < rect.left || e.y > rect.top + rect.height - 1 || e.y < rect.top) {
scope.$apply(attrs.onDragLeave);
}
};
elm.on("dragleave", f);
scope.$on("$destroy", function () { elm.off("dragleave", f); });
};
})
.directive('onDragOver', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragOver);
};
elm.on("dragover", f);
scope.$on("$destroy", function () { elm.off("dragover", f); });
}
};
})
.directive('onDragStart', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragStart);
};
elm.on("dragstart", f);
scope.$on("$destroy", function () { elm.off("dragstart", f); });
}
};
})
.directive('onDragEnd', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragEnd);
};
elm.on("dragend", f);
scope.$on("$destroy", function () { elm.off("dragend", f); });
}
};
})
.directive('onDrop', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDrop);
};
elm.on("drop", f);
scope.$on("$destroy", function () { elm.off("drop", f); });
}
};
})
.directive('onOutsideClick', function ($timeout, angularHelper) {
return function (scope, element, attrs) {
var eventBindings = [];
function oneTimeClick(event) {
// ignore clicks on button groups toggles (i.e. the save and publish button)
var parents = $(event.target).closest("[data-element='button-group-toggle']");
if (parents.length > 0) {
return;
}
// ignore clicks on new overlay
parents = $(event.target).parents(".umb-overlay,.umb-tour");
if (parents.length > 0) {
return;
}
// ignore clicks on dialog from old dialog service
var oldDialog = $(event.target).parents("#old-dialog-service");
if (oldDialog.length === 1) {
return;
}
// ignore clicks in tinyMCE dropdown(floatpanel)
var floatpanel = $(event.target).closest(".mce-floatpanel");
if (floatpanel.length === 1) {
return;
}
// ignore clicks in flatpickr datepicker
var flatpickr = $(event.target).closest(".flatpickr-calendar");
if (flatpickr.length === 1) {
return;
}
// ignore clicks on dialog actions
var actions = $(event.target).parents(".umb-action");
if (actions.length === 1) {
return;
}
//ignore clicks inside this element
if ($(element).has($(event.target)).length > 0) {
return;
}
// please to not use angularHelper.safeApply here, it won't work
scope.$apply(attrs.onOutsideClick);
}
$timeout(function () {
if ("bindClickOn" in attrs) {
eventBindings.push(scope.$watch(function () {
return attrs.bindClickOn;
}, function (newValue) {
if (newValue === "true") {
$(document).on("click", oneTimeClick);
} else {
$(document).off("click", oneTimeClick);
}
}));
} else {
$(document).on("click", oneTimeClick);
}
scope.$on("$destroy", function () {
$(document).off("click", oneTimeClick);
// unbind watchers
for (var e in eventBindings) {
eventBindings[e]();
}
});
}); // Temp removal of 1 sec timeout to prevent bug where overlay does not open. We need to find a better solution.
};
})
.directive('onRightClick', function ($parse) {
document.oncontextmenu = function (e) {
if (e.target.hasAttribute('on-right-click')) {
e.preventDefault();
e.stopPropagation();
return false;
}
};
return function (scope, el, attrs) {
el.on('contextmenu', function (e) {
e.preventDefault();
e.stopPropagation();
var fn = $parse(attrs.onRightClick);
scope.$apply(function () {
fn(scope, { $event: e });
});
return false;
});
};
})
.directive('onDelayedMouseleave', function ($timeout, $parse) {
return {
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
var active = false;
var fn = $parse(attrs.onDelayedMouseleave);
var leave_f = function (event) {
var callback = function () {
fn(scope, { $event: event });
};
active = false;
$timeout(function () {
if (active === false) {
scope.$apply(callback);
}
}, 650);
};
var enter_f = function (event, args) {
active = true;
};
element.on("mouseleave", leave_f);
element.on("mouseenter", enter_f);
//unsub events
scope.$on("$destroy", function () {
element.off("mouseleave", leave_f);
element.off("mouseenter", enter_f);
});
}
};
});
| JavaScript | 0 | @@ -3515,265 +3515,192 @@
-// ignore clicks on button groups toggles (i.e. the save and publish button)%0A var parents = $(event.target).closest(%22%5Bdata-element='button-group-toggle'%5D%22);%0A if (parents.length %3E 0) %7B%0A return;%0A
+var el = event.target.nodeName;%0A%0A //ignore link and button clicks%0A var els = %5B%22INPUT%22, %22A%22, %22BUTTON%22%5D;%0A if (els.indexOf(el) %3E= 0) %7B return;
%7D%0A%0A
@@ -3763,16 +3763,20 @@
+var
parents
@@ -3798,24 +3798,33 @@
t).parents(%22
+a,button,
.umb-overlay
@@ -4636,220 +4636,8 @@
%7D%0A%0A
- // ignore clicks on dialog actions%0A var actions = $(event.target).parents(%22.umb-action%22);%0A if (actions.length === 1) %7B%0A return;%0A %7D%0A%0A
|
43fa3dc60c6b3652ef5655eb4348277fe4d23dcd | clear filter on log out (#2311) | src/main/webapp/scripts/searchmanagement/directives/search-filter-panel.controller.js | src/main/webapp/scripts/searchmanagement/directives/search-filter-panel.controller.js | /* global _, document */
'use strict';
angular.module('metadatamanagementApp')
.controller('SearchFilterPanelController', [
'$scope', 'SearchHelperService', '$timeout',
'$element', 'CleanJSObjectService', '$mdSelect',
function($scope, SearchHelperService, $timeout,
$element, CleanJSObjectService, $mdSelect) {
var elasticSearchTypeChanged = false;
var searchParamsFilterChanged = false;
$scope.filtersCollapsed = false;
var createDisplayAvailableFilterList = function(availableFilters) {
var displayAvailableFilters = [];
var i18nGermanEnding = '-de';
var i18nEnglishEnding = '-en';
availableFilters.forEach(function(filter) {
if (filter.endsWith(i18nGermanEnding)) {
if ($scope.currentLanguage === 'de') {
displayAvailableFilters.push(filter);
}
//Else case, no save of the german filter
} else if (filter.endsWith(i18nEnglishEnding)) {
if ($scope.currentLanguage === 'en') {
displayAvailableFilters.push(filter);
}
//Else Case no save of the english filter
} else {
//Standard Case
displayAvailableFilters.push(filter);
}
});
return displayAvailableFilters;
};
$scope.$watch('currentElasticsearchType', function() {
elasticSearchTypeChanged = true;
$scope.availableFilters = SearchHelperService.getAvailableFilters(
$scope.currentElasticsearchType);
$scope.displayAvailableFilters = createDisplayAvailableFilterList(
$scope.availableFilters);
$scope.availableHiddenFilters = _.intersection(
SearchHelperService.getHiddenFilters(
$scope.currentElasticsearchType),
_.keys($scope.currentSearchParams.filter)
);
$scope.selectedFilters = [];
if ($scope.currentSearchParams.filter) {
$scope.selectedFilters = _.intersection(
_.keys($scope.currentSearchParams.filter),
_.union($scope.availableFilters, $scope.availableHiddenFilters)
);
}
$timeout(function() {
elasticSearchTypeChanged = false;
});
});
$scope.onOneFilterChanged = function() {
$scope.filterChangedCallback();
};
$scope.$watch('selectedFilters', function(newSelectedFilters,
oldSelectedFilters) {
$scope.filtersCollapsed = false;
if ($scope.selectedFilters && !_.isEmpty($scope.selectedFilters)) {
$timeout(function() {
// add md class manually to fix overlapping labels
$element.find('.fdz-filter-select').addClass('md-input-has-value');
});
}
if (elasticSearchTypeChanged || searchParamsFilterChanged) {
return;
}
var unselectedFilters = _.difference(
oldSelectedFilters, newSelectedFilters);
if ($scope.currentSearchParams.filter && unselectedFilters.length > 0) {
unselectedFilters.forEach(function(unselectedFilter) {
delete $scope.currentSearchParams.filter[unselectedFilter];
});
$scope.availableHiddenFilters = _.difference(
$scope.availableHiddenFilters, unselectedFilters);
$scope.filterChangedCallback();
}
});
$scope.$watch('currentSearchParams.filter', function() {
searchParamsFilterChanged = true;
$scope.selectedFilters = [];
if ($scope.currentSearchParams.filter) {
$scope.selectedFilters = _.intersection(
_.keys($scope.currentSearchParams.filter),
_.union($scope.availableFilters, $scope.availableHiddenFilters)
);
}
$timeout(function() {
searchParamsFilterChanged = false;
});
});
$element.find('#searchFilterInput').on('keydown', function(event) {
// close filter chooser on escape
if (event.keyCode === 27 &&
CleanJSObjectService.isNullOrEmpty($scope.filterSearchTerm)) {
return;
}
// The md-select directive eats keydown events for some quick select
// logic. Since we have a search input here, we don't need that logic.
event.stopPropagation();
});
$scope.closeSelectMenu = function() {
$mdSelect.hide();
};
$scope.clearFilterSearchTerm = function() {
$scope.filterSearchTerm = '';
};
$scope.hideMobileKeyboard = function() {
document.activeElement.blur();
};
$scope.getFilterPanelStyle = function() {
var minHeight = (56 * $scope.selectedFilters.length) + 'px';
return {'min-height': minHeight};
};
}
]);
| JavaScript | 0 | @@ -2250,32 +2250,129 @@
%7D);%0A %7D);%0A%0A
+ $scope.$on('user-logged-out', function() %7B%0A $scope.selectedFilters = %5B%5D;%0A %7D);%0A%0A
$scope.onO
|
e2ee5f819c90cd36ee98d3c21a35edd67d8b9b0f | write a function that changes the name of what I wish for and hide it | app/assets/javascripts/websites/wish_page.js | app/assets/javascripts/websites/wish_page.js | JavaScript | 0.000061 | @@ -0,0 +1,501 @@
+function wish() %7B%0A var wishes = %5B'were younger.',%0A 'could take bigger bong hits.',%0A 'could think faster and be sharper.'%5D;%0A var index = 0;%0A%0A function showMessage() %7B%0A $('#message').text(wishes%5Bindex%5D).show();%0A%0A setTimeout(hideMessage, 380)%0A %7D;%0A%0A function hideMessage() %7B%0A $('#message').hide();%0A%0A updateMessage()%0A %7D;%0A%0A function updateMessage() %7B%0A index += 1;%0A%0A if (index %3E 2) %7B%0A index = 0;%0A %7D%0A%0A showMessage();%0A %7D;%0A%0A showMessage();%0A%7D;%0A
| |
663129a71c0aa6f093cb958be0c056495bae5e01 | Temperature and humidity values truncated to 2nd decimal. Gotta handle true and false | app/control-panel/controllers/viewHubCtrl.js | app/control-panel/controllers/viewHubCtrl.js | app.controller('ViewHubCtrl', ViewHubCtrl);
ViewHubCtrl.$inject = ['$scope','$state','$stateParams','$q','hub','printer','sensor'];
function ViewHubCtrl($scope, $state, $stateParams,$q, hub, printer, sensor) {
var hubId = Number($stateParams.hubId);
var hubPromise = hub.getHub(hubId);
var changed = false;
$scope.printersCurrentPage = 1;
$scope.printersItemsPerPage = 2;
hubPromise.then(function(_hub) {
$scope.hub = _hub;
});
var sensorsPromise = hub.getSensors(hubId);
sensorsPromise.then(function(_sensors) {
var sensorDataPromises = [];
$scope.sensors = _sensors;
for (var i = 0; i < $scope.sensors.length; i++) {
sensorDataPromises.push(sensor.getData($scope.sensors[i].id));
}
$q.all(sensorDataPromises).then(function(_data) {
$scope.sensorData = _data;
console.log('Sensor Data Size: ' + $scope.sensorData.length);
for (var j = 0; j < $scope.sensorData.length; j++) {
$scope.sensors[j].data = $scope.sensorData[j];
var dataLength = $scope.sensors[j].data.length;
$scope.sensors[j].newestDatum = $scope.sensors[j].data[dataLength - 1];
console.log('Newest Datum: ' + $scope.sensors[j].newestDatum);
}
});
});
var printersPromise = hub.getPrinters(hubId);
printersPromise.then(function(_printers) {
$scope.printers = _printers;
$scope.printersTotalItems = _printers.length;
});
/**
* ToHubsPage
* Sets the state to the main hubs page, takes in a boolean if the page should refresh or not
* @param refresh
* @returns {}
*/
$scope.toHubsPage = function() {
$state.go('dashboard.hubs',{},{reload: changed});
changed = false;
};
/**
* UpdateHub
* Updates a hub in the DB with the hub object gathered from the form
* @param _hubId
* @param _hub
* @returns {undefined}
*/
$scope.updateHub = function(_hubId, _hub) {
console.log('Updating hub!' + _hubId);
hub.updateHub(_hubId, _hub);
changed = true;
};
$scope.pageChanged = function() {
console.log('Printers Page changed to: ' + $scope.printersCurrentPage);
};
}
| JavaScript | 0.999999 | @@ -1148,68 +1148,257 @@
-console.log('Newest Datum: ' + $scope.sensors%5Bj%5D.newestDatum
+$scope.sensors%5Bj%5D.newestDatum.value = parseFloat($scope.sensors%5Bj%5D.data%5BdataLength - 1%5D.value).toFixed(2);%0A console.log('Newest Datum: ' + $scope.sensors%5Bj%5D.newestDatum + ' it%5C's value type is: ' + typeof ($scope.sensors%5Bj%5D.newestDatum.value)
);%0A
|
c0e5a946ad535bc3f2cfe144f9032ec66092feb2 | Fix [IQSLDSH-164]. | app/controllers/devices.server.controller.js | app/controllers/devices.server.controller.js | /*jslint nomen: true, vars: true, unparam: true*/
/*global require, exports, console*/
(function () {
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
messagingEngineFactory = require('../services/messaging/messagingEngineFactory'),
Device = mongoose.model('Device'),
Config = mongoose.model('Config'),
lodash = require('lodash'),
Promise = require('promise'),
User = mongoose.model('User'),
messageHandler = require('../services/messaging/messageHandler');
/**
* Show the current Device
*/
exports.read = function (req, res) {
res.jsonp(req.device);
};
function DeviceAttributesChanges(device, updatedDevice) {
this.updatedDevice = updatedDevice;
this.device = device;
this.deviceJustSetActive = function (updatedDevice, device) {
return this.device.active === false && this.updatedDevice.active === true;
};
this.defaultSlideShowChangedInActiveMode = function () {
return this.device.defaultSlideShowId !== this.updatedDevice.defaultSlideShowId
&& this.device.active === this.updatedDevice.active
&& this.device.active;
};
this.deviceJustSetInactive = function (updatedDevice, device) {
return this.device.active === true && this.updatedDevice.active === false;
};
}
function ensureUniqueDeviceName(res, device, onDeviceUnique) {
Device.findByName(device.name, function (devices) {
if (devices.length === 0
|| (devices.length === 1 && devices[0]._id.toString() === device._id)) {
onDeviceUnique();
} else {
res.status(400).send({
message: "Device with name '" + device.name + "' already exists."
});
}
}, function (err) {
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
}
function executeUpdate(req, res) {
var device = req.device,
updatedDevice = req.body,
slideShowIdToPlay,
config,
deviceAttributesChanges = new DeviceAttributesChanges(device, updatedDevice),
deviceSetupMessageSlideShowIdToPlay;
if (deviceAttributesChanges.deviceJustSetActive() || deviceAttributesChanges.defaultSlideShowChangedInActiveMode()) {
deviceSetupMessageSlideShowIdToPlay = updatedDevice.defaultSlideShowId;
} else if (deviceAttributesChanges.deviceJustSetInactive()) {
Config.findOne(function (err, config) {
if (err) {
throw err;
}
deviceSetupMessageSlideShowIdToPlay = config.defaultSlideShowId;
});
}
device = lodash.extend(device, req.body);
device.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Device.findOne({
deviceId: device.deviceId
}).populate('slideAgregation.playList.slideShow').exec(function (err, fullDevice) {
if (err) {
throw err;
}
fullDevice.sendDeviceSetupMessage();
});
res.jsonp(device);
}
});
}
exports.update = function (req, res) {
var device = req.device,
updatedDevice = req.body;
ensureUniqueDeviceName(res, updatedDevice, function () {
executeUpdate(req, res);
});
};
/**
* Delete an Device
*/
exports.delete = function (req, res) {
var device = req.device;
device.remove(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(device);
}
});
};
var getNameFilterExpression = function (nameFilter) {
return { $regex: '^' + nameFilter, $options: 'i' };
};
exports.list = function (req, res) {
var select = {},
locationsFilter,
nameFilter;
Device.findByFilter(req.query, function (devices) {
res.jsonp(devices);
}, function (err) {
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Device middleware
*/
exports.deviceByID = function (req, res, next, id) {
Device.byId(id).exec(function (err, device) {
if (err) {
return next(err);
}
if (!device) {
return next(new Error('Failed to load Device ' + id));
}
req.device = device;
next();
});
};
exports.deviceWithSlidesByID = function (req, res, next, id) {
Device.findOne({"deviceId": id}).populate({ //TODO: this dosen't work. I don't understand why!!!!
path: 'slideAgregation.playList.slideShow',
model: 'Slideshow',
populate: {
path: 'user',
model: 'User',
select: 'displayName'
}
}).exec(function (err, device) {
if (err) {
return next(err);
}
if (!device) {
return next(new Error('Failed to load Device ' + id));
}
//TODO: had to populate the users in this way because populate on graph dosen't work :(
var promises = [];
device.slideAgregation.playList.forEach(function (item) {
promises.push(new Promise(function (resolve, error) {
item.slideShow.populate('user', 'displayName', function () {
resolve();
});
}));
});
Promise.all(promises).then(function () {
req.device = device;
next();
}, function () {
next();
});
//next();
});
};
exports.getSlides = function (req, res) {
res.jsonp(req.device.getSlides());
};
exports.healthReport = function (req, res) {
var device = req.device;
device.lastHealthReport = new Date();
device.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp({ report: 'ok' });
}
});
};
exports.devicesByLocation = function (req, res, next, locationName) {
Device.find({"location": locationName}).exec(function (err, devices) {
if (err) {
return next(err);
}
if (!devices) {
req.devices = [];
}
req.devices = devices;
next();
});
};
exports.getDevicesByLocation = function (req, res, next) {
res.jsonp(req.devices);
};
var mapDeviceToFilteredName = function (device) {
return {_id: device._id, name: device.name};
};
exports.filteredNames = function (req, res, next, nameFilter) {
Device.find({name: getNameFilterExpression(nameFilter)}).exec(function (err, devices) {
if (err) {
return next(err);
}
if (!devices) {
req.filteredNames = [];
}
req.filteredNames = lodash.map(devices, mapDeviceToFilteredName);
next();
});
};
exports.getFilteredNames = function (req, res, next) {
res.jsonp(req.filteredNames);
next();
};
exports.hasAuthorization = function (req, res, next) {
next();
};
}());
| JavaScript | 0 | @@ -4332,187 +4332,145 @@
-return %7B $regex: '%5E' + nameFilter, $options: 'i' %7D;%0A %7D;%0A%0A exports.list = function (req, res) %7B%0A var select = %7B%7D,%0A locationsFilter,%0A nameFilter;%0A
+var regex = new RegExp('.*' + nameFilter + '.*', 'i');%0A return %7B $regex: regex %7D;%0A %7D;%0A%0A exports.list = function (req, res) %7B
%0A
@@ -8064,32 +8064,16 @@
Names);%0A
- next();%0A
%7D;%0A%0A
|
5b5ce871a92c2c4f504926c411cbd974bc99b2df | Add billingAddressParameters to GooglePay | app/javascript/components/GooglePayButton.js | app/javascript/components/GooglePayButton.js | // @flow
import React, { Component } from 'react';
import googlePayment from 'braintree-web/google-payment';
import { connect } from 'react-redux';
import { setSubmitting } from '../state/fundraiser/actions';
import type { AppState, PaymentMethod } from '../state';
type Props = {
client: ?any,
onSubmit: (result: Object) => void,
onError: (error: any) => void,
} & typeof mapStateToProps &
typeof mapDispatchToProps;
type State = {
paymentsClient?: Object,
googlePaymentInstance?: Object,
ready: boolean,
};
// TODO:
// Do with this as you please...
// Do we want to display google pay only on androids? Unlike Apple Pay,
// Google Pay not restricted to Android devices.
const isAndroid = navigator.userAgent.toLowerCase().indexOf('android') >= 0;
// GooglePayButton renders a Google Pay button. In order to do that, we need:
// 1. A Braintree client to be initialised
// 2. A Braintree Google Payments client to be initialised (with the braintree client)
// 3. Fetch pay.js from Google, and use that to create the Google Pay button.
// This component / class orchestrates the process.
// Note: One aspect of this that's not ideal is that this button component and
// its corresponding the "google" payment method option in the PaymentTypeSelection
// component are independent of each other, so if this button fails to initialise
// properly, the option might still be visible (but no button would be rendered). We
// could try to couple them but it would require communicating both components via
// the global state, or refactor the fundraising component to contain that state at
// the parent, or to "register" itself once it's "ready" (with a callback to the parent).
export class GooglePayButton extends Component {
props: Props;
state: State;
buttonRef: any;
constructor(props: Props) {
super(props);
// $FlowIgnore
this.buttonRef = React.createRef();
this.state = {
paymentsClient: undefined,
googlePaymentInstance: undefined,
ready: false,
};
}
// createGooglePayButton downloads the pay.js script from Google,
// and if successful, creates a google payments client. That client is
// then used to create a google pay button.
createGooglePayButton = () => {
$.ajax({
url: 'https://pay.google.com/gp/p/js/pay.js',
dataType: 'script',
}).then(() => {
if (window.google) {
const paymentsClient = new window.google.payments.api.PaymentsClient({
environment:
process.env.NODE_ENV === 'production' ? 'PRODUCTION' : 'TEST',
});
const button = paymentsClient.createButton({
onClick: this.onClick,
buttonType: 'short',
});
this.buttonRef.current.appendChild(button);
this.setState({ paymentsClient });
}
});
};
// setupGooglePay creates a *Braintree* google payment instance. This
// is necessary since we're integrating through Braintree. It requires
// a braintree client (passed down via props) and a google payments client
// (to check `isReadyToPay` method)
// Once the isReadyToPay promise resolves, we update state and set ready: true,
// which enables this component.
setupGooglePay() {
const { client } = this.props;
const { paymentsClient } = this.state;
if (client && paymentsClient) {
googlePayment.create({ client }, (err, googlePaymentInstance) => {
paymentsClient
.isReadyToPay({
allowedPaymentMethods: googlePaymentInstance.createPaymentDataRequest()
.allowedPaymentMethods,
})
.then(response => {
if (response.result) {
this.setState({
paymentsClient,
googlePaymentInstance,
ready: true,
});
}
});
});
}
}
componentDidMount() {
this.createGooglePayButton();
this.setupGooglePay();
}
componentDidUpdate(prevProps: Props, prevState: State) {
if (
prevProps.client !== this.props.client ||
prevState.paymentsClient !== this.state.paymentsClient
) {
this.setupGooglePay();
}
}
onClick = (e: any) => {
e.preventDefault();
this.props.setSubmitting(true);
const { ready, googlePaymentInstance, paymentsClient } = this.state;
if (ready && googlePaymentInstance && paymentsClient) {
const paymentDataRequest = googlePaymentInstance.createPaymentDataRequest(
{
merchantId: undefined,
transactionInfo: {
currencyCode: this.props.currency,
totalPrice: this.props.amount.toString(),
totalPriceStatus: 'FINAL',
},
cardRequirements: {
billingAddressRequired: true,
},
}
);
paymentsClient
.loadPaymentData(paymentDataRequest)
.then(paymentData => {
googlePaymentInstance.parseResponse(paymentData, (err, result) => {
if (err) return this.props.onError(err);
this.props.onSubmit(result);
});
})
.catch(this.props.onError);
}
};
render() {
const style = {
display: this.props.currentPaymentType === 'google' ? 'block' : 'none',
};
return <div ref={this.buttonRef} style={style} />;
}
}
const mapStateToProps = (state: AppState) => ({
currentPaymentType: state.fundraiser.currentPaymentType,
fundraiser: state.fundraiser,
currency: state.fundraiser.currency,
amount: state.fundraiser.donationAmount,
});
const mapDispatchToProps = (dispatch: Dispatch<*>) => ({
setSubmitting: (submitting: boolean) => dispatch(setSubmitting(submitting)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(GooglePayButton);
| JavaScript | 0 | @@ -4753,32 +4753,89 @@
Required: true,%0A
+ billingAddressParameters: %7B format: 'MIN' %7D,%0A
%7D,%0A
|
814b7895c837d5dc75aa7e46e2f57f9338fb4459 | Fix organization bikes error (#1669) | app/javascript/packs/pages/binx_org_bikes.js | app/javascript/packs/pages/binx_org_bikes.js | import log from "../utils/log";
function BinxAppOrgBikes() {
return {
init() {
// I'm concerned about javascript breaking, and the bikes being hidden and unable to be shown.
// To prevent that, only hide columns after adding this class
$("#organized_bikes_index").addClass("javascriptFunctioning");
let self = this;
this.selectStoredVisibleColumns();
this.updateVisibleColumns();
$("#organizedSearchSettings input").on("change", function(e) {
self.updateVisibleColumns();
});
// Make the stolenness toggle work
$(".organized-bikes-stolenness-toggle").on("click", function(e) {
e.preventDefault();
const stolenness = $(".organized-bikes-stolenness-toggle").attr(
"data-stolenness"
);
$("#stolenness").val(stolenness);
return $("#bikes_search_form").submit();
});
},
selectStoredVisibleColumns() {
const defaultCells = JSON.parse(
$("#organizedSearchSettings").attr("data-defaultcols")
);
let visibleCells = localStorage.getItem("organizationBikeColumns");
// If we have stored cells, select them.
if (typeof visibleCells === "string") {
visibleCells = JSON.parse(visibleCells);
}
// Unless we have an array with at least one item, make it default
if (typeof visibleCells !== "array" || visibleCells.length < 1) {
visibleCells = defaultCells;
}
visibleCells.forEach((cellClass) =>
$(`input#${cellClass}`).prop("checked", true)
);
},
updateVisibleColumns() {
$(".full-screen-table th, .full-screen-table td").addClass(
"hiddenColumn"
);
let enabledCells = $("#organizedSearchSettings input:checked")
.get()
.map((cellClass) => cellClass.value);
enabledCells.forEach((cellClass) =>
$(`.${cellClass}`).removeClass("hiddenColumn")
);
// Then store the enabled columns
localStorage.setItem(
"organizationBikeColumns",
JSON.stringify(enabledCells)
);
},
};
}
export default BinxAppOrgBikes;
| JavaScript | 0 | @@ -471,32 +471,33 @@
hange%22, function
+
(e) %7B%0A se
@@ -640,16 +640,17 @@
function
+
(e) %7B%0A
@@ -927,24 +927,105 @@
Columns() %7B%0A
+ if (!$(%22#organizedSearchSettings%22).length) %7B%0A return false;%0A %7D%0A
const
|
ee1f192e5cf0bbf4399e69e8501fbb36d1fc4303 | add pinch trigger to pop up enlargements | application/labels/static/js/jquery.hooks.js | application/labels/static/js/jquery.hooks.js | jQuery(document).ready(function() {
if( $(window).height()<710 && window.devicePixelRatio>1 ){
var v = $('meta[name^="viewport"]'),
c = v.attr('content');
v.attr('content', c.replace('initial-scale=1', 'initial-scale='+$(window).height()/710));
}
$(window).each(function(){
$(this).on('resize', function(){
$('#img li.active').removeClass('active').trigger('click');
$('.pop').each(function(){
var l = ($(window).width()-$(this).outerWidth())/2;
l = l>0? l:0;
$(this).css('left',l);
});
$('#mousetrap').height($(document).height()).width($(document).width());
});
});
$('#img, #txt').each(function(){
if( $(this).find('li.home').length < 1 ){
$(this).find('li').eq(0).addClass('active');
}else{
$(this).find('li.home').eq(0).addClass('active');
}
var i = $(this).find('li').not('.active'),
w = i.outerWidth() + parseFloat(i.css('margin-left'))*2,
iA = $(this).find('li.active'),
wA = iA.outerWidth() + parseFloat(iA.css('margin-left'))*2;
$(this).find('li.active').removeClass('active');
$(this).width(w*($(this).find('li:last-child').index()+1)+wA);
this.hit = function(i){
var t = 1024;
$(this).find('.active>.mask').animate({'opacity':'0.5'}, t/4, null, $(this).find('li>.mask').show());
$(this).animate({'left':$(window).width()/2-((i*w)+(0.5*wA))}, t, function(){
$(this).find('li').removeClass('active').find('.mask').css({'opacity':'0.5','display':'block'});
$(this).find('li:nth-child('+(i+1)+')').addClass('active').find('.mask').fadeToggle(t/4);
});
};
});
$('#img, #txt').on('click', 'li:not(.active)', function(){
var i = $(this).index();
$('#img, #txt').each(function(){ this.hit(i); });
});
$('#img, #txt').find('li').each(function(){
$(this).hammer({css_hacks:false, swipe:false}).on('dragstart', function(e){
var li = $(this),
a = Math.abs(e.angle);
if( a<60 || a>150 ){
if( li.is('.active') ){
$('#img, #txt').each(function(){
var d = (a<60? 1:-1);
var n = li.index() - d;
if( n>-1 && n<$(this).find('li').length){
this.hit(n);
}
});
}else{
$('#img, #txt').each(function(){ this.hit($(li).index()); });
}
}
});
});
$('#img').on('click', '.active', function(e){
var pip = (e.target.tagName.toLowerCase()==='img')? e.target : $(this).find('img').get(0),
l = ($(window).width()-$('#imgpop').outerWidth())/2;
l = l>0? l:0;
$('#imgbig').remove();
$('#imgbox').prepend('<img id="imgbig" src="'+ $(pip).data('img-l') +'" alt=""/>');
$('#imgtxt').html(pip.title);
$('#imgpop').css('left',l).show().mouseTrap({'mask':1});
});
$('#txt').on('click', '.active', function(){
var l = ($(window).width()-$('#txtpop').outerWidth())/2;
l = l>0? l:0;
$('#txtpop').removeClass('home').html($(this).html()).css('left',l).show().mouseTrap({'mask':1});
if( $(this).hasClass('home') ){ $('#txtpop').addClass('home'); }
});
$('.pop').on('click', function(){
$('.pop').hide();
$('#mousetrap').remove();
});
$('#img').each(function(){
if( $(this).find('li.home').length < 1 ){
$(this).find('li').eq(Math.floor($(this).find('li').length/2)).trigger('click');
}else{
$(this).find('li.home').eq(0).trigger('click');
}
});
}); //end doc.ready
/* plugins + fns */
/* Generic carini plugin for catching mouseclicks outside a JQ el */
(function($){
$.fn.extend({
mouseTrap: function(opt){
var def = { close:this, mask:0 };
opt = $.extend(def,opt);
return this.each(function(){
var obj = $(this);
$('#mousetrap').remove();
obj.before($('<div id="mousetrap" class="'+(opt.mask?'mask':'')+'"/>').height($(document).height()).width($(document).width()).on('click', function(){ $(opt.close).hide(); $('#mousetrap').remove(); }));
obj.click(function(){ if( $(opt.close).is(':hidden') ){ $('#mousetrap').remove(); } });
});
}
});
})(jQuery);
| JavaScript | 0 | @@ -2717,32 +2717,146 @@
%7D%0A %7D%0A
+ %7D).on('transformstart', function(e)%7B%0A if( $(this).is('.active') )%7B $(this).trigger('click') %7D;%0A
%7D);%0A
|
cfef8ddb085f28b15efb8a883b07348702625d9f | Add styling class. | assets/js/components/settings/SetupModule.js | assets/js/components/settings/SetupModule.js | /**
* SetupModule component.
*
* Site Kit by Google, Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
// import PropTypes from 'prop-types';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { sprintf, __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import {
activateOrDeactivateModule,
getReAuthURL,
showErrorNotification,
} from '../../util';
import { refreshAuthentication } from '../../util/refresh-authentication';
import data from '../data';
import ModuleIcon from '../ModuleIcon';
import Spinner from '../Spinner';
import Link from '../Link';
import GenericError from '../../components/notifications/generic-error';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import Data from 'googlesitekit-data';
import ErrorIcon from '../../../svg/error.svg';
const { useSelect } = Data;
export default function SetupModule( {
slug,
name,
description,
active,
} ) {
const [ isSaving, setIsSaving ] = useState( false );
const activateOrDeactivate = async () => {
try {
setIsSaving( true );
await activateOrDeactivateModule( data, slug, ! active );
await refreshAuthentication();
// Redirect to ReAuthentication URL.
global.location = getReAuthURL( slug, true );
} catch ( err ) {
showErrorNotification( GenericError, {
id: 'activate-module-error',
title: __( 'Internal Server Error', 'google-site-kit' ),
description: err.message,
format: 'small',
type: 'win-error',
} );
setIsSaving( false );
}
};
// @TODO: Resolver only runs once per set of args, so we are working around
// this to rerun after modules are loaded.
// Once #1769 is resolved, we can remove the call to getModules,
// and remove the !! modules cache busting param.
const modules = useSelect( ( select ) => select( CORE_MODULES ).getModules() );
const canActivateModule = useSelect( ( select ) => select( CORE_MODULES ).canActivateModule( slug, !! modules ) );
const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES ).getCheckRequirementsStatus( slug, !! modules ) );
const errorMessage = canActivateModule ? null : requirementsStatus;
return (
<div
className={ classnames(
'googlesitekit-settings-connect-module',
`googlesitekit-settings-connect-module--${ slug }`,
{ 'googlesitekit-settings-connect-module--disabled': ! canActivateModule }
) }
key={ slug }
>
<div className="googlesitekit-settings-connect-module__switch">
<Spinner isSaving={ isSaving } />
</div>
<div className="googlesitekit-settings-connect-module__logo">
<ModuleIcon slug={ slug } />
</div>
<h3 className="
googlesitekit-subheading-1
googlesitekit-settings-connect-module__title
">
{ name }
</h3>
<p className="googlesitekit-settings-connect-module__text">
{ description }
</p>
{ errorMessage &&
<div
className={ classnames( 'googlesitekit-settings-module-warning' ) } >
<ErrorIcon height="20" width="23" /> { errorMessage }
</div>
}
<p className="googlesitekit-settings-connect-module__cta">
<Link
onClick={ activateOrDeactivate }
href=""
inherit
disabled={ ! canActivateModule }
arrow
>
{
sprintf(
/* translators: %s: module name */
__( 'Set up %s', 'google-site-kit' ),
name
)
}
</Link>
</p>
</div>
);
}
| JavaScript | 0 | @@ -3594,16 +3594,71 @@
warning'
+, 'googlesitekit-settings-module-warning--modules-list'
) %7D %3E%0A%09
|
e691f30aeeef919e59e5a19adbc9ec91a7339ecd | Remove console statements | backend/servers/mcapid/__tests__/example2.js | backend/servers/mcapid/__tests__/example2.js | 'use strict';
const ActionHero = require('actionhero');
const actionhero = new ActionHero.Process();
let api;
describe('actionhero Tests', () => {
beforeAll(async() => { api = await actionhero.start(); });
afterAll(async() => {
console.log('Calling actionhero.stop()');
await actionhero.stop();
console.log('past actionhero.stop()');
});
test('should have booted into the test env', () => {
expect(process.env.NODE_ENV).toEqual('test');
expect(api.env).toEqual('test');
expect(api.id).toBeTruthy();
});
test('can retrieve server uptime via the status action', async() => {
let {uptime} = await api.specHelper.runAction('status');
expect(uptime).toBeGreaterThan(0);
});
});
| JavaScript | 0.000008 | @@ -243,127 +243,30 @@
-console.log('Calling actionhero.stop()');%0A await actionhero.stop();%0A console.log('past actionhero.stop()'
+await actionhero.stop(
);%0A
|
74e6ce76b190549fe0d648d6c212e89989e32a21 | add test whether we can instance pipelineRecord | blueocean-admin/src/test/js/pipeline-spec.js | blueocean-admin/src/test/js/pipeline-spec.js | import React from 'react';
import {createRenderer} from 'react-addons-test-utils';
import { assert} from 'chai';
import sd from 'skin-deep';
import Pipeline from '../../main/js/components/Pipeline.jsx';
const
hack={
MultiBranch:()=>{},
Pr:()=>{},
Activity:()=>{},
} ,
pipelineMulti = {
'displayName': 'moreBeers',
'name': 'morebeers',
'organization': 'jenkins',
'weatherScore': 0,
'branchNames': ['master'],
'numberOfFailingBranches': 1,
'numberOfFailingPullRequests': 0,
'numberOfSuccessfulBranches': 0,
'numberOfSuccessfulPullRequests': 0,
'totalNumberOfBranches': 1,
'totalNumberOfPullRequests': 0
},
pipelineMultiSuccess = {
'displayName': 'moreBeersSuccess',
'name': 'morebeersSuccess',
'organization': 'jenkins',
'weatherScore': 0,
'branchNames': ['master'],
'numberOfFailingBranches': 0,
'numberOfFailingPullRequests': 0,
'numberOfSuccessfulBranches': 3,
'numberOfSuccessfulPullRequests': 3,
'totalNumberOfBranches': 3,
'totalNumberOfPullRequests': 3
},
pipelineSimple = {
'displayName': 'beers',
'name': 'beers',
'organization': 'jenkins',
'weatherScore': 0
},
testElementSimple = (<Pipeline
hack={hack}
pipeline={pipelineSimple}
simple={true}/>
),
testElementMultiSuccess = (<Pipeline
hack={hack}
pipeline={pipelineMultiSuccess}
/>
),
testElementMulti = (<Pipeline
hack={hack}
pipeline={pipelineMulti}/>
);
describe("pipeline component simple rendering", () => {
const
renderer = createRenderer();
before('render element', () => renderer.render(testElementSimple));
it("renders a pipeline", () => {
const
result = renderer.getRenderOutput(),
children = result.props.children;
assert.equal(result.type, 'tr');
assert.equal(children[0].props.children, pipelineSimple.name);
// simple element has no children
assert.equal(children[2].type, 'td');
assert.isObject(children[2].props);
assert.equal(children[2].props.children, ' - ');
});
});
describe("pipeline component multiBranch rendering", () => {
const
renderer = createRenderer();
before('render element', () => renderer.render(testElementMulti));
it("renders a pipeline with error branch", () => {
const
result = renderer.getRenderOutput(),
children = result.props.children;
assert.equal(result.type, 'tr');
assert.equal(children[0].props.children, pipelineMulti.name);
// simple element has no children
assert.equal(children[2].type, 'td');
assert.isObject(children[2].props);
// multiBranch has more information
assert.isDefined(children[2].props.children);
assert.equal(children[2].props.children[0], pipelineMulti.numberOfFailingBranches);
});
});
describe("pipeline component multiBranch rendering - success", () => {
const
renderer = createRenderer();
before('render element', () => renderer.render(testElementMultiSuccess));
it("renders a pipeline with success branch", () => {
const
result = renderer.getRenderOutput(),
children = result.props.children;
assert.equal(result.type, 'tr');
assert.equal(children[0].props.children, pipelineMultiSuccess.name);
// simple element has no children
assert.equal(children[2].type, 'td');
assert.isObject(children[2].props);
// multiBranch has more information
assert.isDefined(children[2].props.children);
assert.equal(children[2].props.children[0], pipelineMultiSuccess.numberOfSuccessfulBranches);
});
});
describe("weatherIcon pipeline component simple rendering", () => {
const
renderer = createRenderer();
before('render element', () => renderer.render(testElementSimple));
it("renders a weather-icon", () => {
const
result = renderer.getRenderOutput(),
children = result.props.children,
tree = sd.shallowRender(children[1].props.children),
vdom = tree.getRenderOutput();
assert.oneOf('weather-icon', vdom.props.className.split(' '));
});
});
| JavaScript | 0 | @@ -135,17 +135,16 @@
deep';%0A%0A
-%0A
import P
@@ -196,16 +196,87 @@
ne.jsx';
+%0Aimport %7B PipelineRecord %7D from '../../main/js/components/records.jsx';
%0A%0Aconst%0A
@@ -1571,24 +1571,220 @@
ti%7D/%3E%0A );%0A%0A
+describe(%22PipelineRecord can be created %22, () =%3E %7B%0A it(%22without error%22, () =%3E %7B%0A const pipeRecord = new PipelineRecord(pipelineMultiSuccess);%0A console.log(pipeRecord)%0A %7D)%0A%7D);%0A%0A
describe(%22pi
@@ -2344,33 +2344,32 @@
, ' - ');%0A %7D);%0A
-%0A
%7D);%0A%0Adescribe(%22p
|
f8984a9c78266252670ea48510e3c72a15933b2a | Fix issue 9: Incorrect polling locations are being returned | app/scripts/polling_location_finder.js | app/scripts/polling_location_finder.js | define(['geojson', 'json!vendor/ELECTIONS_WardsPrecincts.geojson', 'json!vendor/ELECTIONS_PollingLocations.geojson'], function(GeoJSON, precinctsJSON, locationsJSON) {
'use strict';
var precincts = new GeoJSON(precinctsJSON),
pollingLocations = new GeoJSON(locationsJSON);
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(42.3736, -71.1106), // Cambridge!
zoom: 12
});
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
panel: document.getElementById('directions')
});
// keep track of user precinct across calls so we can erase previous precincts if necessary
var userPrecinct = null;
return function(coords) {
// if we've already drawn a user precinct, erase it
if (userPrecinct) {
userPrecinct.setMap(null);
userPrecinct = null;
}
// find out which ward they're in using Point in Polygon
var pollingLocation = null;
for (var i = 0; i < precincts.length; i++) {
if (precincts[i].containsLatLng(coords)) {
userPrecinct = precincts[i];
// polling locations are stored in the same order, so we can use the same index
pollingLocation = pollingLocations[i];
break;
}
}
if (!userPrecinct) {
// TODO handle what happens if they don't live in any precinct
document.getElementById('directions').innerHTML = "We can't find your precinct! Sorry. Try again?";
} else {
// highlight the precinct on the map
userPrecinct.setMap(map);
map.fitBounds(userPrecinct.getBounds());
// show step-by-step directions
var request = {
origin: coords,
destination: pollingLocation.geojsonProperties.Address + ', Cambridge, MA',
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(result, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
};
});
| JavaScript | 0.000001 | @@ -1128,23 +1128,44 @@
cation =
+ null, wardPrecinct =
null;%0A
-
@@ -1305,24 +1305,100 @@
ecincts%5Bi%5D;%0A
+ wardPrecinct = userPrecinct.geojsonProperties.WardPrecinct;%0A
@@ -1403,16 +1403,30 @@
//
+Search for the
polling
@@ -1438,69 +1438,205 @@
tion
-s are stored in the same order, so we can use the same index%0A
+ that matches the precinct and ward%0A for (var j = 0; j %3C pollingLocations.length; j++) %7B%0A if (pollingLocations%5Bj%5D.geojsonProperties.W_P == wardPrecinct) %7B%0A
@@ -1682,20 +1682,91 @@
cations%5B
-i
+j
%5D;%0A
+ break;%0A %7D%0A %7D%0A
|
dbf878d4a3cc3a9cd7ff314cc4bb58e87a9d6e3b | enable usage of https Marvel services | app/scripts/services/marvel-wrapper.js | app/scripts/services/marvel-wrapper.js | 'use strict';
/*
* Wraps Marvel's rest API and does things like caching results and logging
* errors
*/
angular.module('marvelQuizApp.common')
.provider('MarvelWrapper', function MarvelWrapperProvider() {
// contains the Marvel API key to attach to every request
var apiKey;
/*
* Set Marvel's API key
*/
this.setApiKey = function (newKey) {
apiKey = newKey;
};
/*
* Service constructor
*/
this.$get = function MarvelWrapper($http, Cache, $q, GoogleAnalytics) {
var BASE_URL = 'http://gateway.marvel.com/v1/public';
/*
* Returns a promise for a constant value
*/
function _future(value) {
var deferred = $q.defer();
deferred.resolve(value);
return deferred.promise;
}
/*
* Common function that handles error responses from marvel services
*/
function _marvelServiceError(res) {
// TODO: when maximum request number is exceeded, set some global variable
// that completely disable the application with an alert
// every time that a user access the application that has been disabled,
// signal it somewhere so that I can keep track of it
if (res.status === 429) {
GoogleAnalytics.marvelServiceLimitExceeded();
}
else {
GoogleAnalytics.marvelServiceError('' + res.status + ' - ' + res.data);
}
}
/*
* Get the total number of character present in the database
*/
function totalCharacters() {
var CACHE_KEY = 'totalCharacters';
var cacheValue = Cache.get(CACHE_KEY);
if (cacheValue) {
return _future(cacheValue);
}
else {
return $http.get(BASE_URL + '/characters', {
params: {
limit: 1,
apikey: apiKey
}
}).then(
function (res) {
var count = res.data.data.total;
Cache.put(CACHE_KEY, count);
GoogleAnalytics.marvelServiceRequest('characters');
return count;
},
_marvelServiceError
);
}
}
/*
* Interface to the "characters" service
*/
function characters(params) {
var CACHE_KEY = 'characters/' + angular.toJson(params);
var cacheValue = Cache.get(CACHE_KEY);
if (cacheValue) {
return _future(cacheValue);
}
else {
return $http.get(BASE_URL + '/characters', {
params: angular.extend(params, {
apikey: apiKey
})
}).then(
function (res) {
var characters = res.data.data.results;
Cache.put(CACHE_KEY, characters);
GoogleAnalytics.marvelServiceRequest('characters');
return characters;
},
_marvelServiceError
);
}
}
return {
totalCharacters: totalCharacters,
characters: characters
};
};
});
| JavaScript | 0 | @@ -543,13 +543,8 @@
= '
-http:
//ga
|
9de2dd374b65583e8060bd1ce327cd0a0a4057fc | Remove newline. (#251) | lib/generateElement.js | lib/generateElement.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
'use strict';
const generate = require('./generate');
/**
* Wrap SRI data for resourceUrl in a script tag
*
* @deprecated pending move to isomorphic app
* @param {string} resourceUrl
* @param {Array} algorithms
* @param {Function} cb - callback
*/
const generateElement = (resourceUrl, algorithms, cb) => {
const options = {
url: resourceUrl,
algorithms
};
generate(options, (resource) => {
let element;
if (!resource.success) {
if (resource.status > 0) {
return cb(`Error: fetching the resource returned a ${parseInt(resource.status, 10)} error code.`);
}
return cb('Error: fetching the resource returned an unexpected error.');
}
if (resource.eligibility.length !== 0) {
return cb('Error: this resource is not eligible for integrity checks. See https://enable-cors.org/server.html');
}
switch (resource.type) {
case 'js':
element = `<script src="${resource.url}" integrity="${resource.integrity}" crossorigin="anonymous"></script>`;
break;
case 'css':
element = `<link rel="stylesheet" href="${resource.url}" integrity="${resource.integrity}" crossorigin="anonymous">`;
break;
case '.forbidden':
element = `Error: Forbidden content-type
https://html.spec.whatwg.org/multipage/scripting.html#scriptingLanguages
https://developer.mozilla.org/en/docs/Incorrect_MIME_Type_for_CSS_Files`;
break;
default:
element = `<!-- Warning: Unrecognized content-type. Are you sure this is the right resource? -->
<script src="${resource.url}" integrity="${resource.integrity}" crossorigin="anonymous"></script>`;
break;
}
return cb(element);
});
};
module.exports = generateElement;
| JavaScript | 0.000249 | @@ -457,17 +457,16 @@
ack%0A */%0A
-%0A
const ge
|
cb2c1db1b64a89bd587c446cd2f39e6de013fcdd | fix emailConfirmation graphql mutation | packages/plugins/users-permissions/server/graphql/mutations/auth/email-confirmation.js | packages/plugins/users-permissions/server/graphql/mutations/auth/email-confirmation.js | 'use strict';
const { toPlainObject } = require('lodash/fp');
const { checkBadRequest } = require('../../utils');
module.exports = ({ nexus, strapi }) => {
const { nonNull } = nexus;
return {
type: 'UsersPermissionsLoginPayload',
args: {
confirmation: nonNull('String'),
},
description: 'Confirm an email users email address',
async resolve(parent, args, context) {
const { koaContext } = context;
koaContext.request.body = toPlainObject(args);
await strapi
.plugin('users-permissions')
.controller('auth')
.emailConfirmation(koaContext, null, true);
const output = koaContext.body;
checkBadRequest(output);
return {
user: output.user || output,
jwt: output.jwt,
};
},
};
};
| JavaScript | 0.000001 | @@ -456,19 +456,12 @@
ext.
-re
que
-st.bod
+r
y =
|
9605ed21921e4fc7eb2a8537c943d209fb4f4fef | Correct authentication methods in place for tournament | api/models/tournament.js | api/models/tournament.js | 'use strict';
const app_config = require('../config');
const dynamoose = require('dynamoose');
dynamoose.AWS.config.update(app_config.aws);
const Schema = dynamoose.Schema;
dynamoose.local();
const options = {
create: true,
udpate: true,
timestamps: true,
useDocumentTypes: true,
};
let tournamentSchema = new Schema({
id: {
type: String,
hashKey: true,
},
name: {
type: String,
},
official: {
type: String,
},
secret: {
type: String,
},
date: {
type: Date,
},
rounds_finished: {
type: Object,
required: true,
default: {
prelim: false,
semi: false,
final: false,
},
},
pools: {
type: 'list',
list: [{
id: {
type: String,
required: true,
},
teams: {
type: [String],
required: true,
},
}],
}
});
tournamentSchema.statics.authenticate = function(id, secret, cb) {
// checks the provided id and secret key and returns true / false depending
// on if correct or not.
//
this.query('id').eq(id).and().filter('secret').eq(secret).exec((err, matches) => {
if (err) cb(false);
cb( matches.count === 1 );
});
};
let Tournament = dynamoose.model('Tournament',tournamentSchema, options);
module.exports = Tournament;
| JavaScript | 0.000008 | @@ -1317,17 +1317,16 @@
false);%0A
-%0A
@@ -1331,10 +1331,10 @@
cb
-(
+(
matc
@@ -1348,17 +1348,16 @@
nt === 1
-
);%0A %7D
@@ -1359,18 +1359,16 @@
%7D);%0A
-%0A%0A
%7D;%0A%0Alet
|
6186c278fd87d2bc8854f68d896011c608129584 | tweak keymater with our own changes | vendor/keymaster.js | vendor/keymaster.js | // keymaster.js
// (c) 2011 Thomas Fuchs
// keymaster.js may be freely distributed under the MIT license.
;(function(global){
var k,
_handlers = {},
_mods = { 16: false, 18: false, 17: false, 91: false },
_scope = 'all',
// modifier keys
_MODIFIERS = {
'⇧': 16, shift: 16,
option: 18, '⌥': 18, alt: 18,
ctrl: 17, control: 17,
command: 91, '⌘': 91
},
// special keys
_MAP = {
backspace: 8, tab: 9, clear: 12,
enter: 13, 'return': 13,
esc: 27, escape: 27, space: 32,
left: 37, up: 38,
right: 39, down: 40,
del: 46, 'delete': 46,
home: 36, end: 35,
pageup: 33, pagedown: 34,
',': 188, '.': 190, '/': 191,
'`': 192, '-': 189, '=': 187,
';': 186, '\'': 222,
'[': 219, ']': 221, '\\': 220
};
for(k=1;k<20;k++) _MODIFIERS['f'+k] = 111+k;
// IE doesn't support Array#indexOf, so have a simple replacement
function index(array, item){
var i = array.length;
while(i--) if(array[i]===item) return i;
return -1;
}
// handle keydown event
function dispatch(event){
var key, tagName, handler, k, i, modifiersMatch;
tagName = (event.target || event.srcElement).tagName;
key = event.keyCode;
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
if(key in _mods) {
_mods[key] = true;
// 'assignKey' from inside this closure is exported to window.key
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
return;
}
// ignore keypressed in any elements that support keyboard data input
if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA') return;
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;
// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
// see if it's in the current scope
if(handler.scope == _scope || handler.scope == 'all'){
// check if modifiers match if any
modifiersMatch = handler.mods.length > 0;
for(k in _mods)
if((!_mods[k] && index(handler.mods, +k) > -1) ||
(_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
// call the handler and stop the event if neccessary
if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
if(handler.method(event, handler)===false){
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(event.stopPropagation) event.stopPropagation();
if(event.cancelBubble) event.cancelBubble = true;
}
}
}
}
};
// unset modifier keys on keyup
function clearModifier(event){
var key = event.keyCode, k;
if(key == 93 || key == 224) key = 91;
if(key in _mods) {
_mods[key] = false;
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
}
};
// parse and assign shortcut
function assignKey(key, scope, method){
var keys, mods, i, mi;
if (method === undefined) {
method = scope;
scope = 'all';
}
key = key.replace(/\s/g,'');
keys = key.split(',');
if((keys[keys.length-1])=='')
keys[keys.length-2] += ',';
// for each shortcut
for (i = 0; i < keys.length; i++) {
// set modifier keys if any
mods = [];
key = keys[i].split('+');
if(key.length > 1){
mods = key.slice(0,key.length-1);
for (mi = 0; mi < mods.length; mi++)
mods[mi] = _MODIFIERS[mods[mi]];
key = [key[key.length-1]];
}
// convert to keycode and...
key = key[0]
key = _MAP[key] || key.toUpperCase().charCodeAt(0);
// ...store handler
if (!(key in _handlers)) _handlers[key] = [];
_handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
}
};
// initialize key.<modifier> to false
for(k in _MODIFIERS) assignKey[k] = false;
// set current scope (default 'all')
function setScope(scope){ _scope = scope || 'all' };
// cross-browser events
function addEvent(object, event, method) {
if (object.addEventListener)
object.addEventListener(event, method, false);
else if(object.attachEvent)
object.attachEvent('on'+event, function(){ method(window.event) });
};
// set the handlers globally on document
addEvent(document, 'keydown', dispatch);
addEvent(document, 'keyup', clearModifier);
// set window.key and window.key.setScope
global.key = assignKey;
global.key.setScope = setScope;
if(typeof module !== 'undefined') module.exports = key;
})(this);
| JavaScript | 0 | @@ -1717,16 +1717,19 @@
a input%0A
+//
if (
@@ -3613,11 +3613,14 @@
lit(
-'+'
+/-%7C%5C+/
);%0A
@@ -3771,16 +3771,30 @@
mods%5Bmi%5D
+.toLowerCase()
%5D;%0A
@@ -4880,16 +4880,23 @@
ports =
+global.
key;%0A%0A%7D)
|
1ab1a8fbe5aa7e4de31e2694b101691b4eb3e2e9 | fix for DFL-294, Editing the matching text (highlighted one) is not reflected in search on reverting back the edited text to the original one. | src/scripts/TextSearch.js | src/scripts/TextSearch.js | /**
* @constructor
*/
var TextSearch = function()
{
const
DEFAULT_STYLE = "background-color:#ff0; color:#000;",
HIGHLIGHT_STYLE = "background-color:#0f0; color:#000;",
DEFAULT_SCROLL_MARGIN = 50,
SEARCH_DELAY = 50;
var
self = this,
search_therm = '',
search_results = [], // collection of span elements
cursor = -1,
container = null,
__input = null,
timeouts = new Timeouts(),
span_set_default_style = function(span)
{
span.style.cssText = DEFAULT_STYLE;
},
span_set_highlight_style = function(span)
{
span.style.cssText = HIGHLIGHT_STYLE;
},
check_parent = function(hit)
{
return hit[0].parentElement;
},
search_node = function(node)
{
var
text_content = container.textContent.toLowerCase(),
search_term_length = search_therm.length,
match = text_content.indexOf(search_therm),
last_match = match != -1 && match + search_term_length || 0,
consumed_total_length = 0,
to_consume_hit_length = 0,
span = null,
search_result = null,
consume_node = function(node)
{
if( node && ( match != -1 || to_consume_hit_length ) )
{
switch(node.nodeType)
{
case 1:
{
consume_node(node.firstChild);
break;
}
case 3:
{
if(to_consume_hit_length)
{
if( node.nodeValue.length >= to_consume_hit_length )
{
node.splitText(to_consume_hit_length);
}
to_consume_hit_length -= node.nodeValue.length;
search_result[search_result.length] = span = document.createElement('span');
node.parentNode.replaceChild(span, node);
span.appendChild(node);
span.style.cssText = DEFAULT_STYLE;
consumed_total_length += node.nodeValue.length;
node = span;
}
else
{
if( match - consumed_total_length < node.nodeValue.length )
{
node.splitText(match - consumed_total_length);
if( ( match = text_content.indexOf(search_therm, last_match) ) != -1 )
{
last_match = match + search_term_length;
}
to_consume_hit_length = search_term_length;
search_result = search_results[search_results.length] = [];
}
consumed_total_length += node.nodeValue.length;
}
}
}
consume_node(node.nextSibling);
}
};
consume_node(container);
},
update_status_bar = function()
{
topCell.statusbar.updateInfo(ui_strings.S_TEXT_STATUS_SEARCH.
replace("%(SEARCH_TERM)s", search_therm).
replace("%(SEARCH_COUNT_TOTAL)s", search_results.length).
replace("%(SEARCH_COUNT_INDEX)s", ( cursor + 1 )) );
};
this.search = function(new_search_therm, old_cursor)
{
var cur = null, i = 0, parent = null, search_hit = null, j = 0;
if( new_search_therm != search_therm )
{
search_therm = new_search_therm;
if(search_results)
{
for( ; cur = search_results[i]; i++)
{
for( j = 0; search_hit = cur[j]; j++)
{
if( parent = search_hit.parentNode )
{
parent.replaceChild(search_hit.firstChild, search_hit);
parent.normalize();
}
}
}
}
search_results = [];
cursor = -1;
if( search_therm.length > 2 )
{
if(container)
{
search_node(container);
if( old_cursor && search_results[old_cursor] )
{
cursor = old_cursor;
search_results[cursor].style.cssText = HIGHLIGHT_STYLE;
update_status_bar();
}
else
{
self.highlight(true);
}
}
}
else
{
topCell.statusbar.updateInfo('');
}
}
}
this.searchDelayed = function(new_search_therm)
{
timeouts.set(this.search, SEARCH_DELAY, new_search_therm.toLowerCase());
}
this.update = function()
{
var new_search_therm = search_therm;
if( search_therm.length > 2 )
{
search_therm = '';
this.search(new_search_therm);
}
}
this.highlight = function(check_position)
{
if(search_results.length)
{
if( cursor >= 0 )
{
search_results[cursor].forEach(span_set_default_style);
}
if( check_position )
{
cursor = 0;
while( search_results[cursor] && search_results[cursor][0].offsetTop < 0 )
{
cursor++;
}
}
else
{
cursor++;
}
if( cursor > search_results.length - 1)
{
cursor = 0;
}
search_results[cursor].forEach(span_set_highlight_style);
if( !check_position || search_results[cursor][0].offsetTop > DEFAULT_SCROLL_MARGIN )
{
container.scrollTop += search_results[cursor][0].offsetTop - DEFAULT_SCROLL_MARGIN;
}
update_status_bar();
}
}
this.revalidateSearch = function()
{
if( !search_results.every(function(hit){ return hit[0].parentElement } ) )
{
var new_search_therm = search_therm;
search_therm = '';
this.search(new_search_therm, cursor);
}
}
this.setContainer = function(_container)
{
if( container != _container )
{
container = _container;
}
}
this.setFormInput = function(input)
{
__input = input;
if(search_therm)
{
var new_search_therm = search_therm;
__input.value = search_therm;
__input.parentNode.firstChild.textContent = '';
search_therm = '';
this.searchDelayed (new_search_therm);
}
}
this.cleanup = function()
{
search_results = [];
cursor = -1;
__input = container = null;
}
}; | JavaScript | 0 | @@ -5207,76 +5207,33 @@
if(
-!search_results.every(function(hit)%7B return hit%5B0%5D.parentElement %7D )
+container && search_therm
)%0A
|
5f378db409a3813c2700628f077e7f7342fc5acc | Fix assets init processor | lib/init/app/assets.js | lib/init/app/assets.js | // `bin` section processor
//
// .
// |- /assets/
// | |- /<package>/
// | | |- **/*.*
// | | `- ...
// | `- ...
// `- ...
//
'use strict';
// stdlib
var fs = require('fs');
var path = require('path');
// 3rd-party
var async = require('nlib').Vendor.Async;
var fstools = require('nlib').Vendor.FsTools;
var _ = require('underscore');
// internal
var findPaths = require('./utils').findPaths;
var stopWatch = require('./utils').stopWatch;
////////////////////////////////////////////////////////////////////////////////
function processAssets(config, callback) {
async.forEachSeries(config.lookup, function (options, next) {
findPaths(options, function (err, pathnames) {
if (err) {
next(err);
return;
}
async.forEachSeries(pathnames, function (pathname, nextPathname) {
var
basepath = new RegExp('^' + options.root + '/*'),
relative = String(pathname).replace(basepath, '');
N.runtime.assets.bin[relative] = String(pathname);
next();
}, next);
});
}, callback);
}
////////////////////////////////////////////////////////////////////////////////
module.exports = function (tmpdir, config, callback) {
var timer = stopWatch();
async.forEachSeries(_.keys(config.packages), function (pkgName, next) {
var assetsConfig = config.packages[pkgName].bin;
if (!assetsConfig) {
next();
return;
}
processAssets(assetsConfig, next);
}, function (err) {
N.logger.info('Processed assets (bin) section ' + timer.elapsed);
callback(err);
});
};
| JavaScript | 0.000002 | @@ -600,34 +600,24 @@
ck) %7B%0A
-async.forEachSerie
+findPath
s(config
@@ -628,58 +628,8 @@
kup,
- function (options, next) %7B%0A findPaths(options,
fun
@@ -657,18 +657,16 @@
) %7B%0A
-
if (err)
@@ -678,23 +678,23 @@
- next
+callback
(err);%0A
-
@@ -703,18 +703,16 @@
return;%0A
-
%7D%0A%0A
@@ -714,37 +714,22 @@
%7D%0A%0A
- async.forEachSeries
+_.each
(pathnam
@@ -747,171 +747,12 @@
n (p
-athname, nextPathname) %7B%0A var%0A basepath = new RegExp('%5E' + options.root + '/*'),%0A relative = String(pathname).replace(basepath, '');%0A%0A
+) %7B%0A
@@ -774,16 +774,18 @@
ets.bin%5B
+p.
relative
@@ -800,62 +800,23 @@
ng(p
-athname);%0A next();%0A %7D, next);%0A %7D);%0A %7D,
+);%0A %7D);%0A%0A
cal
@@ -820,16 +820,23 @@
callback
+();%0A %7D
);%0A%7D%0A%0A%0A/
|
ad594f1a2026ef4fa8f4b9d06a79bbc8c48b8ba0 | Improve jekyll template | lib/jekyll-template.js | lib/jekyll-template.js | 'use strict';
let path = require('path');
module.exports = function jekyllTemplate(answers) {
return `
---
layout: post
title: ${answers.title || 'Unknown'}
speakers: ${answers.speakers || 'Unknown'}
date: ${answers.date}
duration: ${answers.duration || '0min'}
tags: [ ${answers.tags || 'uncategorized'} ]
img: /assets/image/speakers/${answers.imageName || 'no-image.jpg'}
link: ${answers.link}
---
`.replace(/^(?:\n|\s{2,4})/gm, '');
}
| JavaScript | 0 | @@ -12,54 +12,8 @@
';%0A%0A
-let path = require('path');%0A%0Amodule.exports =
func
@@ -17,17 +17,20 @@
unction
-j
+getJ
ekyllTem
@@ -302,140 +302,408 @@
mg:
-/assets/image/speakers/$%7Banswers.imageName %7C%7C 'no-image.jpg'%7D%0A link: $%7Banswers.link%7D%0A ---%0A %60.replace(/%5E(?:%5Cn%7C%5Cs%7B2,4%7D)/gm, '')
+$%7BgetImagePath(answers)%7D%0A link: $%7Banswers.link%7D%0A ---%0A %60.replace(regexSpaceAtBegin(), '');%0A%7D;%0A%0Afunction getImagePath(answers) %7B%0A let hasFullPath = /%5C//.test(answers.imageName);%0A return hasFullPath%0A ? answers.imageName%0A : %60/assets/image/speakers/$%7Banswers.imageName %7C%7C 'no-image.jpg'%7D%60;%0A%7D%0A%0Afunction regexSpaceAtBegin() %7B%0A return /%5E(?:%5Cn%7C%5Cs%7B2,4%7D)/gm;%0A%7D%0A%0Amodule.exports = getJekyllTemplate
;%0A
-%7D
%0A
|
e280a0dc0da89803cad012f242239df9df9a6df8 | Fix sample prog err | lib/jserver/tserver.js | lib/jserver/tserver.js | var jlib = require('./jamlib'),
async = require('asyncawait/async'),
await = require('asyncawait/await'),
readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.setPrompt('J-Core > ');
rl.prompt();
rl.on('line', (line) => {
var toks = line.split(" ");
switch (toks[0]) {
case 'sync':
sync_test();
break;
case 'status':
console.log("Number of devices: " + jlib.JServer.devCount());
break;
case 'help':
showHelp();
break;
default:
console.log("Invalid command...type 'help' to get more info.");
break;
}
rl.prompt();
}).on('close', () => {
console.log("Shutting down the J-Core!");
process.exit(0);
});
function showHelp() {
console.log("sync\nstatus\nhelp");
}
function async_test(){
console.log("Attempting to async ...");
process.stdout.write(".");
jlib.JServer.remoteAsyncExec("hellofk", ["mcgill university", 343 + i * 10, "canada"], "true");
setTimeout( async_test, 2000);
}
//setTimeout( async_test, 2000);
function test(a, b, c) {
console.log("hello.. this is output from j-core");
console.log(a, b, c);
return b + c;
}
function testfg(a, b, c) {
console.log("hello.. this is output from j-core");
console.log(a, b, c);
return b - c;
}
var current_temp = 20;
var temp_status = 1;
function custom_sleep(time){
var start = new Date().getTime();
var end = start;
while(end < start + time * 1000) {
end = new Date().getTime();
}
}
function timer(a, b, c){
console.log("Testing ..... Timing for " + b + " seconds");
var start = new Date().getTime();
var end = start;
while(end < start + b * 1000) {
end = new Date().getTime();
}
console.log("Time Spent Waiting " + (end-start)/1000);
return end;
}
function process_status(status_msg, status){
console.log(status);
if(status == 0){
console.log(status_msg);
}else if(status == 1){
console.log(status_msg);
console.log("Initiating Reboot Sequence ..... \n");
}
}
function temp_report(status_msg, temperature){
console.log(status_msg);
current_temp = temperature;
console.log("Temperature Logged at " + current_temp);
}
function status_report(status_msg, status){
if(temp_status != status){
temp_status = status;
console.log("Status has been changed\n");
}else {
console.log("No Change... \n");
}
}
function temp_action(status_msg, status){
console.log("\n\n-----------COMMENCING OPERATIONS-------------------\n\n");
console.log(status_msg);
if(temp_status != status){
console.log("Action taken\n");
process.stdout.write(".");
//jlib.JServer.remoteAsyncExec("hellofk", ["mcgill university", 343 + i * 10, "canada"], "true");
//jlib.JServer.remoteAsyncExec("set_temp_control", ["set_temp_control", "Changing Action... \n", status], "true");
temp_status = status;
sync_call = async(function() {
value = await (jlib.JServer.remoteSyncExec("set_temp_control", ["set_temp_control", "Changing Action... \n", status], "true"));
console.log("Return value : " + value);
});
sync_call();
}else{
console.log("No New Action Required\n");
}
}
var ID = 1;
var msg_list = ["Chat Service Initiated... ", "Hope this works ... "];
function get_past_msg(num_msg){
var begin = 0;
var end = num_msg;
var ret = "";
if(num_msg > msg_list.length){
begin = msg_list.length - num_msg;
}else{
end = 0;
}
ret += msg_list.slice(begin, end).join("\n");
console.log("We are sending.... \n-------------------------------------------------\n" + ret)
return ret;
}
function get_new_id(status_msg){
console.log(status_msg + " and " + ID);
ID += 1;
return ID;
}
function j_node_get_msg(usr_name, msg, user_id){
console.log("\n----------------Server Message Received-------------\n" + usr_name + ": " + msg);
//process.stdout.write(".");
//jlib.JServer.remoteAsyncExec("hellofk", ["mcgill university", 343 + i * 10, "canada"], "true");
jlib.JServer.remoteAsyncExec("c_node_get_msg", [usr_name, msg, user_id], "true");
/*sync_call = async(function() {
value = await (jlib.JServer.remoteSyncExec("c_node_get_msg", [usr_name, msg, user_id], "true"));
console.log("Return value : " + value);
});*/
//sync_call();
}
jlib.JServer.registerCallback(j_node_get_msg, "ssn");
jlib.JServer.registerCallback(get_new_id, "s");
jlib.JServer.registerCallback(get_past_msg, "n");
jlib.JServer.registerCallback(test, "snn");
jlib.JServer.registerCallback(testfg, "snn");
jlib.JServer.registerCallback(timer, "snn");
jlib.JServer.registerCallback(process_status, "sn");
jlib.JServer.registerCallback(temp_report, "sn");
jlib.JServer.registerCallback(temp_action, "sn");
jlib.JServer.registerCallback(status_report, "sn");
//
program = async(function() {
value = await (jlib.JServer.remoteSyncExec("hellofk", ["mcgill university", 343 + 10, "canada"], "true"));
console.log("Return value : " + value);
});
function sync_test(){
console.log("Attempting to sync ...");
program();
setTimeout( sync_test, 2000);
}
//sync_test();
| JavaScript | 0.000012 | @@ -4056,16 +4056,55 @@
+ msg);%0A
+%09msg_list.push(usr_name + %22: %22 + msg);%0A
%09//proce
|
26b7b34bd4cd6af13ec0786f2e6aa22e0e783ade | Add check for metadata | platform/core/src/utils/xhrRetryRequestHook.js | platform/core/src/utils/xhrRetryRequestHook.js | import retry from 'retry';
const defaultRetryOptions = {
retries: 5,
factor: 3,
minTimeout: 1 * 1000,
maxTimeout: 60 * 1000,
randomize: true,
retryableStatusCodes: [429, 500],
};
let retryOptions = { ...defaultRetryOptions };
/**
* Request hook used to add retry functionality to XHR requests.
*
* @param {XMLHttpRequest} request XHR request instance
* @param {object} metadata Metadata about the request
* @param {object} metadata.url URL
* @param {object} metadata.method HTTP method
* @returns {XMLHttpRequest} request instance optionally modified
*/
const xhrRetryRequestHook = (request, metadata) => {
const { url, method } = metadata;
function faultTolerantRequestSend(...args) {
const operation = retry.operation(retryOptions);
operation.attempt(function operationAttempt(currentAttempt) {
const originalOnReadyStateChange = request.onreadystatechange;
/** Overriding/extending XHR function */
request.onreadystatechange = function onReadyStateChange() {
originalOnReadyStateChange.call(request);
if (retryOptions.retryableStatusCodes.includes(request.status)) {
const errorMessage = `Attempt to request ${url} failed.`;
const attemptFailedError = new Error(errorMessage);
operation.retry(attemptFailedError);
}
};
console.warn(`Requesting ${url}... (attempt: ${currentAttempt})`);
request.open(method, url, true);
originalRequestSend.call(request, ...args);
});
}
/** Overriding/extending XHR function */
const originalRequestSend = request.send;
request.send = faultTolerantRequestSend;
return request;
};
/**
* Returns a configured retry request hook function
* that can be used to add retry functionality to XHR request.
*
* Default options:
* retries: 5
* factor: 3
* minTimeout: 1 * 1000
* maxTimeout: 60 * 1000
* randomize: true
*
* @param {object} options
* @param {number} options.retires number of retries
* @param {number} options.factor factor
* @param {number} options.minTimeout the min timeout
* @param {number} options.maxTimeout the max timeout
* @param {boolean} options.randomize randomize
* @param {array} options.retryableStatusCodes status codes that can trigger retry
* @returns {function} the configured retry request function
*/
export const getXHRRetryRequestHook = (options = {}) => {
retryOptions = { ...defaultRetryOptions };
if ('retries' in options) {
retryOptions.retries = options.retries;
}
if ('factor' in options) {
retryOptions.factor = options.factor;
}
if ('minTimeout' in options) {
retryOptions.minTimeout = options.minTimeout;
}
if ('maxTimeout' in options) {
retryOptions.maxTimeout = options.maxTimeout;
}
if ('randomize' in options) {
retryOptions.randomize = options.randomize;
}
return xhrRetryRequestHook;
};
export default getXHRRetryRequestHook;
| JavaScript | 0 | @@ -623,16 +623,60 @@
a) =%3E %7B%0A
+ if (!metadata) %7B%0A return request;%0A %7D%0A%0A
const
|
489a13f60b7a5817c8c0818a0895fbc114c3237e | Add initial, tentative pg setup | dbserver/dbroutes.js | dbserver/dbroutes.js |
var express = require('express')
var path = require('path')
var cors = require('cors')
var bodyparser = require('body-parser')
var uuid = require('uuid')
var compression = require('compression')
var bcrypt = require('bcryptjs')
var knex = require('knex')({
client: 'sqlite3',
connection: {
filename: '../datastore/tandp.sqlite3'
},
useNullAsDefault: true
})
module.exports = function routes(app) {
var urlencodedParser = bodyparser.urlencoded({ extended: false })
app.use(bodyparser.json())
// GET
app.get('/', function(req, res) {
res.send('hello world')
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/recipients', function(req, res) {
knex('recipients')
.select('*')
.then(function(resp) {
res.send(resp)
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/recipients/:recipientID', function(req, res) {
// console.log("in GET for user", req.params.recipientID)
knex('recipients')
.where('recipients.recipientID', req.params.recipientID)
.then(function(resp) {
// console.log ("in get with recipientid", resp)
res.send(resp[0])
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donations', function(req, res) {
// console.log("in GET all donations")
knex('donations')
.select('*')
.then(function(resp) {
res.send(resp)
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donations/:donationID', function(req, res) {
// console.log("in GET donations for a single donation", req.params.donationID)
knex('donations')
.where('donations.donationID', req.params.donationID)
.then(function(resp) {
res.send(resp[0])
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donations/donor/:donorID', function(req, res) {
// console.log("in GET donations for a single donor", req.params.donorID)
knex('donations')
.where('donations.donorID', req.params.donorID)
.select('*')
.then(function(resp) {
res.send(resp)
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donations/recipient/:recipientID', function(req, res) {
// console.log("in GET donations for a single recipient", req.params.recipientID)
knex('donations')
.where('donations.recipientID', req.params.recipientID)
.select('*')
.then(function(resp) {
res.send(resp)
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donors', function(req, res) {
// console.log("in GET all donors")
knex('donors')
.select('*')
.then(function(resp) {
res.send(resp)
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donors/:donorID', function(req, res) {
// console.log("in GET donors by donorID", req.params.donorID)
knex('donors')
.where('donors.donorID', req.params.donorID)
.then(function(resp) {
res.send(resp[0])
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donors/name/:donorName', function(req, res) {
// console.log("in GET donors by donorName", req.params.donorName)
knex('donors')
.where('donors.donorName', req.params.donorName)
.then(function(resp) {
res.send(resp[0])
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
app.get('/donors/email/:email', function(req, res) {
// console.log("in GET donors by email", req.params.email)
knex('donors')
.where('donors.email', req.params.email)
.then(function(resp) {
res.send(resp[0])
})
// .catch(function(err){
// console.log("ERROR! ", err)
// })
})
// ENCRYPTION
app.post('/encrypt', function(req, res) {
bcrypt.genSalt(10, function(err, salt) {
if (err) { console.log("ERROR GENERATING SALT: ", err); return }
bcrypt.hash(req.body.password, salt, (err, hash) => {
if (err) { console.log("ERROR ENCRYPTING: ", err); return }
res.send(hash)
})
})
})
app.post('/unencrypt', function(req, res) {
bcrypt.compare(req.body.password, req.body.passwordHash, function(err, resp) {
if (resp === true) {
console.log("password returned match TRUE")
res.send(true)
} else {
console.log("password returned match FALSE")
res.send(false)
}
})
})
// POST
app.post('/donors', function(req, res) {
console.log("in POST to donors", req.body)
var newId = uuid.v4()
knex('donors')
.insert({
donorID: newId ,
donorName: req.body.donorName,
passwordHash: req.body.passwordHash,
email: req.body.email
})
.then(function(resp) {
res.send(newId)
})
})
app.post('/donations', function(req, res) {
console.log("in POST to donations", req.body)
var newId = uuid.v4()
knex('donations')
.insert({
donationID: newId,
donorID: req.body.donorID,
recipientID: req.body.recipientID,
amount: req.body.amount
})
.then(function(resp) {
res.send(resp)
})
})
app.post('/recipients', function(req, res) {
var newId = uuid.v4()
knex('recipients')
.insert({
recipientID: newId ,
name: req.body.Name,
imgURL: req.body.imgURL,
received: req.body.received,
target: req.body.target,
sobStory: req.body.sobStory
})
.then(function(resp) {
res.send(resp)
})
})
// PUT
app.put('/recipients/:recipientID', function(req, res) {
console.log("in dbroutes PUT recp")
knex('recipients')
.where('recipients.recipientID', req.params.recipientID)
.update({
name: req.body.Name,
imgURL: req.body.imgURL,
received: req.body.received,
target: req.body.target,
sobStory: req.body.sobStory
})
.then(function(resp) {
res.send(resp)
})
})
}
| JavaScript | 0 | @@ -366,16 +366,153 @@
rue%0A%7D)%0A%0A
+// var knex = require('knex')(%7B%0A// client: 'pg',%0A// connection: 'postgresql://localhost:3000',%0A// searchPath: 'knex,public'%0A// %7D)%0A%0A
module.e
|
f934f78fb811924db152551e24b77e8776acac7f | update binding handler | validate.js | validate.js | var defaultMessage = 'Invalid Value',
defaultValidator = function (value) {
return value !== undefined && value !== null && (value.length === undefined || value.length > 0);
};
var getValidationFunction = function (validator) {
//Allow Regex validations
if (validator instanceof RegExp) {
var validationRegex = validator;
validator = function (value) {
return value !== undefined && value !== null && validationRegex.test(value);
};
return validator;
}
if (typeof validator === 'object') {
var validation = validator;
validator = function (value) {
var passed = true,
valueFloat = parseFloat(value, 10);
//If we require numbers, we use a parsed value, any isNaN is a failure
if (validation.min && (valueFloat < ko.unwrap(validation.min) || isNaN(valueFloat)))
passed = false;
if (validation.max && (valueFloat > ko.unwrap(validation.max) || isNaN(valueFloat)))
passed = false;
if (validation.minLength && value.length < ko.unwrap(validation.minLength))
passed = false;
if (validation.maxLength && value.length > ko.unwrap(validation.maxLength))
passed = false;
var options = ko.unwrap(validation.options);
if (options && options instanceof Array && options.indexOf(value) === -1)
passed = false;
return passed;
};
}
//If validator isn't regex or function, provide default validation
return typeof validator === 'function' ? validator : defaultValidator;
};
var getValidation = function (validator) {
var message = defaultMessage,
handler;
if (typeof validator === 'object') {
if (validator.message)
message = validator.message;
handler = getValidationFunction(validator.validate);
} else {
handler = getValidationFunction(validator);
}
return {
validate: handler,
message: message
};
};
ko.extenders.isValid = function (target, validator) {
//Use for tracking whether validation should be used
//The validate binding will init this on blur, and clear it on focus
//So that editing the field immediately clears errors
target.isModified = ko.observable(false);
var validations = [];
if (validator instanceof Array) {
validator.forEach(function (v) {
validations.push(getValidation(v));
});
} else {
validations.push(getValidation(validator));
}
//We need to track both failure and the message in one step
//Having one set the other feels odd, and having both run through
//All the validation methods is inefficient.
var error = ko.computed(function () {
var value = target();
//We want just the first failing validation, but we want to run
//All the functions to establish an closed-over dependencies that might exist
//in each function. We are trading performance for additional flexiblity here.
var result = validations.filter(function (validation) {
return !validation.validate(value);
});
return result.length > 0 ? result[0] : undefined;
});
target.isValid = ko.computed(function () {
return error() === undefined;
});
target.errorMessage = ko.computed(function () {
return error() !== undefined ? ko.unwrap(error().message) : '';
});
//Just a convienient wrapper to bind against for error displays
//Will only show errors if validation is active AND invalid
target.showError = ko.computed(function () {
var active = target.isModified(),
isValid = target.isValid();
return active && !isValid;
});
return target;
};
//Just activate whatever observable is given to us on first blur
ko.bindingHandlers.validate = {
init: function (element, valueAccessor) {
if (!ko.isObservable(valueAccessor()))
throw new Error("The validate binding cannot be used with non-observables.");
ko.bindingHandlers.value.init.apply(this, arguments); //Wrap value init
//Starting the input with validation errors is bad
//We will activate the validation after the user has done something
//Select's get change raised when OPTIONS are bound, which is very common
//We don't want that to activate validation
if (element.nodeName.toLowerCase() === "select") {
valueAccessor().__selectInit = false;
}
//Active will remain false until we have left the field
ko.utils.registerEventHandler(element, 'blur', function () {
valueAccessor().isModified(true);
});
},
update: function (element, valueAccessor) {
//Input's get activated on blur, not update
if (element.nodeName.toLowerCase() === "select") {
//The update handler runs on INIT, so we need a way to skip the 1st time only
if (!valueAccessor().__selectInit)
valueAccessor().__selectInit = true;
else
valueAccessor().isModified(true);
}
ko.bindingHandlers.value.update.apply(this, arguments); //just wrap the update binding handler
}
};
| JavaScript | 0 | @@ -3979,16 +3979,112 @@
ate = %7B%0A
+ preprocess: function (value, name, addBinding) %7B%0A addBinding('value', value);%0A %7D,%0A
init
@@ -4113,32 +4113,32 @@
alueAccessor) %7B%0A
-
if (!ko.
@@ -4263,89 +4263,8 @@
);%0A%0A
- ko.bindingHandlers.value.init.apply(this, arguments); //Wrap value init%0A%0A
@@ -4476,20 +4476,16 @@
common%0A
-
@@ -5276,111 +5276,8 @@
%7D%0A
- ko.bindingHandlers.value.update.apply(this, arguments); //just wrap the update binding handler%0A
|
e5e8d645b2e1caa44903d1725e42d19e82f3931d | make sure we approximate a valid index for hover details | src/js/Rickshaw.Graph.HoverDetail.js | src/js/Rickshaw.Graph.HoverDetail.js | Rickshaw.namespace('Rickshaw.Graph.HoverDetail');
Rickshaw.Graph.HoverDetail = Rickshaw.Class.create({
initialize: function(args) {
var graph = this.graph = args.graph;
this.xFormatter = args.xFormatter || function(x) {
return new Date( x * 1000 ).toUTCString();
};
this.yFormatter = args.yFormatter || function(y) {
return y.toFixed(2);
};
var element = this.element = document.createElement('div');
element.className = 'detail';
this.visible = true;
graph.element.appendChild(element);
this.lastEvent = null;
this._addListeners();
this.onShow = args.onShow;
this.onHide = args.onHide;
this.onRender = args.onRender;
this.formatter = args.formatter || this.formatter;
},
formatter: function(series, x, y, formattedX, formattedY, d) {
return series.name + ': ' + formattedY;
},
update: function(e) {
e = e || this.lastEvent;
if (!e) return;
this.lastEvent = e;
if (e.target.nodeName != 'path' && e.target.nodeName != 'svg') return;
var graph = this.graph;
var eventX = e.offsetX || e.layerX;
var eventY = e.offsetY || e.layerY;
var domainX = graph.x.invert(eventX);
var stackedData = graph.stackedData;
var topSeriesData = stackedData.slice(-1).shift();
var domainIndexScale = d3.scale.linear()
.domain([topSeriesData[0].x, topSeriesData.slice(-1).shift().x])
.range([0, topSeriesData.length]);
var approximateIndex = Math.floor(domainIndexScale(domainX));
var dataIndex = approximateIndex || 0;
for (var i = approximateIndex; i < stackedData[0].length - 1;) {
if (!stackedData[0][i] || !stackedData[0][i + 1]) {
break;
}
if (stackedData[0][i].x <= domainX && stackedData[0][i + 1].x > domainX) {
dataIndex = i;
break;
}
if (stackedData[0][i + 1] < domainX) { i++ } else { i-- }
}
var domainX = stackedData[0][dataIndex].x;
var formattedXValue = this.xFormatter(domainX);
var graphX = graph.x(domainX);
var order = 0;
var detail = graph.series.active()
.map( function(s) { return { order: order++, series: s, name: s.name, value: s.stack[dataIndex] } } );
var activeItem;
var sortFn = function(a, b) {
return (a.value.y0 + a.value.y) - (b.value.y0 + b.value.y);
};
var domainMouseY = graph.y.magnitude.invert(graph.element.offsetHeight - eventY);
detail.sort(sortFn).forEach( function(d) {
d.formattedYValue = (this.yFormatter.constructor == Array) ?
this.yFormatter[detail.indexOf(d)](d.value.y) :
this.yFormatter(d.value.y);
d.graphX = graphX;
d.graphY = graph.y(d.value.y0 + d.value.y);
if (domainMouseY > d.value.y0 && domainMouseY < d.value.y0 + d.value.y && !activeItem) {
activeItem = d;
d.active = true;
}
}, this );
this.element.innerHTML = '';
this.element.style.left = graph.x(domainX) + 'px';
if (this.visible) {
this.render( {
detail: detail,
domainX: domainX,
formattedXValue: formattedXValue,
mouseX: eventX,
mouseY: eventY
} );
}
},
hide: function() {
this.visible = false;
this.element.classList.add('inactive');
if (typeof this.onHide == 'function') {
this.onHide();
}
},
show: function() {
this.visible = true;
this.element.classList.remove('inactive');
if (typeof this.onShow == 'function') {
this.onShow();
}
},
render: function(args) {
var detail = args.detail;
var domainX = args.domainX;
var mouseX = args.mouseX;
var mouseY = args.mouseY;
var formattedXValue = args.formattedXValue;
var xLabel = document.createElement('div');
xLabel.className = 'x_label';
xLabel.innerHTML = formattedXValue;
this.element.appendChild(xLabel);
detail.forEach( function(d) {
var item = document.createElement('div');
item.className = 'item';
item.innerHTML = this.formatter(d.series, domainX, d.value.y, formattedXValue, d.formattedYValue, d);
item.style.top = this.graph.y(d.value.y0 + d.value.y) + 'px';
this.element.appendChild(item);
var dot = document.createElement('div');
dot.className = 'dot';
dot.style.top = item.style.top;
dot.style.borderColor = d.series.color;
this.element.appendChild(dot);
if (d.active) {
item.className = 'item active';
dot.className = 'dot active';
}
}, this );
this.show();
if (typeof this.onRender == 'function') {
this.onRender(args);
}
},
_addListeners: function() {
this.graph.element.addEventListener(
'mousemove',
function(e) {
this.visible = true;
this.update(e)
}.bind(this),
false
);
this.graph.onUpdate( function() { this.update() }.bind(this) );
this.graph.element.addEventListener(
'mouseout',
function(e) {
if (e.relatedTarget && !(e.relatedTarget.compareDocumentPosition(this.graph.element) & Node.DOCUMENT_POSITION_CONTAINS)) {
this.hide();
}
}.bind(this),
false
);
}
});
| JavaScript | 0 | @@ -1466,16 +1466,25 @@
Index =
+Math.min(
approxim
@@ -1496,16 +1496,44 @@
dex %7C%7C 0
+, stackedData%5B0%5D.length - 1)
;%0A%0A%09%09for
|
7933e1739679ea772828d5a488615b4eacbc7ef2 | Use factory parameters | lib/logger/loglevel.js | lib/logger/loglevel.js | /**
*
* @licstart The following is the entire license notice for the JavaScript code in this file.
*
* Loglevel logger implementation for recordLoader
*
* Copyright (c) 2015-2016 University Of Helsinki (The National Library Of Finland)
*
* This file is part of record-loader-logger-loglevel
*
* record-loader-prototypes is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @licend The above is the entire license notice
* for the JavaScript code in this file.
*
**/
/* istanbul ignore next: umd wrapper */
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['loglevel', 'loglevel-std-streams', 'loglevel-message-prefix'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('loglevel'), require('loglevel-std-streams'), require('loglevel-message-prefix'));
}
}(this, factory));
function factory(log, loglevelStdStreams, loglevelMessagePrefix) {
'use strict';
return function() {
return function(level, prefixes, module_name)
{
function loadPlugins()
{
var messagePrefixParameters = {};
loglevelStdStreams(logger);
if (Array.isArray(prefixes)) {
messagePrefixParameters.prefixes = prefixes.filter(function(prefix) {
return prefix !== 'module';
});
}
if (module_name !== undefined && prefixes.indexOf('module') >= -1) {
messagePrefixParameters.staticPrefixes = [module_name];
}
loglevelMessagePrefix(logger, messagePrefixParameters);
}
var logger = log.getLogger(module_name === undefined ? 'root' : module_name);
loadPlugins();
logger.setLevel(level);
return {
error: function(message)
{
logger.error(message);
},
warn: function(message)
{
logger.warn(message);
},
info: function(message)
{
logger.info(message);
},
debug: function(message)
{
logger.debug(message);
},
trace: function(message)
{
logger.trace(message);
}
};
};
};
}
| JavaScript | 0.000001 | @@ -1637,16 +1637,34 @@
unction(
+parameters_factory
) %7B%0A%09ret
@@ -1680,22 +1680,17 @@
ion(
-level, prefixe
+parameter
s, m
@@ -1829,16 +1829,35 @@
isArray(
+parameters_factory.
prefixes
@@ -1902,16 +1902,35 @@
fixes =
+parameters_factory.
prefixes
@@ -2037,16 +2037,35 @@
ined &&
+parameters_factory.
prefixes
@@ -2351,16 +2351,35 @@
etLevel(
+parameters_factory.
level);%0A
|
87908e52fabcc87a349fe81cd51cdf96a553a539 | maintain modified/saved classes and lastSaved timestamp for tiny forms | src/patterns/edit-tinymce.js | src/patterns/edit-tinymce.js | define([
'jquery',
'../lib/ajax',
"../core/parser",
'../core/logging',
'../registry',
'URIjs/URI',
'tinymce'
], function($, ajax, Parser, logging, registry, URI) {
var log = logging.getLogger('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'),
$resetbtn = $form.find('[type=reset]'),
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 u = new URI();
u._parts.query = null;
// handle rebasing of own urls if we were injected
var parents = $el.parents().filter(function() {
return $(this).data('pat-injected');
});
if (parents.length)
u = URI(parents.first().data('pat-injected').origin).absoluteTo(u);
if (cfg.content_css)
cfg.content_css = URI(cfg.content_css).absoluteTo(u).toString();
tinyMCE.baseURL = URI(args.tinymceBaseurl).absoluteTo(u).toString();
tinyMCE.baseURI = new tinyMCE.util.URI(tinyMCE.baseURL);
// initialize editor
var tinymce = tinyMCE.init(cfg);
// ajaxify form
var ajaxopts = {
beforeSerialize: (function(id) {
return function() {
tinyMCE.editors[id].save();
};
})(id)
};
$form.on('submit', function(ev) {
ev.preventDefault();
ajax($form, ajaxopts);
});
// XXX: we hijack the reset button, but currently only reset
// the tiny textarea.
$resetbtn.on('click.pat-edit-tinymce', (function(id) {
return function(ev) {
ev.preventDefault();
tinyMCE.editors[id].load();
};
})(id));
return $el;
},
destroy: function($el) {
// XXX
}
};
registry.register(_);
return _;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -95,24 +95,40 @@
/registry',%0A
+ %22../utils%22,%0A
'URIjs/U
@@ -193,16 +193,23 @@
egistry,
+ utils,
URI) %7B%0A
@@ -2562,24 +2562,904 @@
.baseURL);%0A%0A
+ var $tinymce,%0A modified = utils.debounce(function() %7B%0A $tinymce.off('.pat-tinymce');%0A $form.removeClass(%22saved%22).addClass(%22modified%22);%0A $form.data(%7Bmodified: true%7D);%0A log.debug('modified');%0A %7D, 400);%0A $form.on('pat-ajax-success.pat-tinymce', function() %7B%0A $tinymce.on('keyup.pat-tinymce', modified);%0A $form.removeClass(%22modified%22).addClass(%22saved%22);%0A $form.data(%7B%0A lastSaved: new Date(),%0A modified: false%0A %7D);%0A log.debug('saved');%0A %7D);%0A cfg.oninit = function() %7B%0A $tinymce = $('#' + id + '_ifr').contents().find('#tinymce');%0A $tinymce.on('keyup.pat-tinymce', modified);%0A %7D;%0A%0A
|
138b21ce6033b9beac28804a295124ff9dee318f | remove deprecated req.session._csrf getter | lib/middleware/csrf.js | lib/middleware/csrf.js | /*!
* Connect - csrf
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('../utils');
var uid = require('uid2');
var crypto = require('crypto');
/**
* Anti CSRF:
*
* CSRF protection middleware.
*
* This middleware adds a `req.csrfToken()` function to make a token
* which should be added to requests which mutate
* state, within a hidden form field, query-string etc. This
* token is validated against the visitor's session.
*
* The default `value` function checks `req.body` generated
* by the `bodyParser()` middleware, `req.query` generated
* by `query()`, and the "X-CSRF-Token" header field.
*
* This middleware requires session support, thus should be added
* somewhere _below_ `session()` and `cookieParser()`.
*
* Options:
*
* - `value` a function accepting the request, returning the token
*
* @param {Object} options
* @api public
*/
module.exports = function csrf(options) {
options = options || {};
var value = options.value || defaultValue;
return function(req, res, next){
// already have one
var secret = req.session._csrfSecret;
if (secret) return createToken(secret);
// generate secret
uid(24, function(err, secret){
if (err) return next(err);
req.session._csrfSecret = secret;
createToken(secret);
});
// generate the token
function createToken(secret) {
var token;
// lazy-load token
req.csrfToken = function csrfToken() {
return token || (token = saltedToken(secret));
};
// compatibility with old middleware
Object.defineProperty(req.session, '_csrf', {
configurable: true,
get: function() {
console.warn('req.session._csrf is deprecated, use req.csrfToken() instead');
return req.csrfToken();
}
});
// ignore these methods
if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();
// determine user-submitted value
var val = value(req);
// check
if (!checkToken(val, secret)) return next(utils.error(403));
next();
}
}
};
/**
* Default value function, checking the `req.body`
* and `req.query` for the CSRF token.
*
* @param {IncomingMessage} req
* @return {String}
* @api private
*/
function defaultValue(req) {
return (req.body && req.body._csrf)
|| (req.query && req.query._csrf)
|| (req.headers['x-csrf-token'])
|| (req.headers['x-xsrf-token']);
}
/**
* Return salted token.
*
* @param {String} secret
* @return {String}
* @api private
*/
function saltedToken(secret) {
return createToken(generateSalt(10), secret);
}
/**
* Creates a CSRF token from a given salt and secret.
*
* @param {String} salt (should be 10 characters)
* @param {String} secret
* @return {String}
* @api private
*/
function createToken(salt, secret) {
return salt + crypto
.createHash('sha1')
.update(salt + secret)
.digest('base64');
}
/**
* Checks if a given CSRF token matches the given secret.
*
* @param {String} token
* @param {String} secret
* @return {Boolean}
* @api private
*/
function checkToken(token, secret) {
if ('string' != typeof token) return false;
return token === createToken(token.slice(0, 10), secret);
}
/**
* Generates a random salt, using a fast non-blocking PRNG (Math.random()).
*
* @param {Number} length
* @return {String}
* @api private
*/
function generateSalt(length) {
var i, r = [];
for (i = 0; i < length; ++i) {
r.push(SALTCHARS[Math.floor(Math.random() * SALTCHARS.length)]);
}
return r.join('');
}
var SALTCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
| JavaScript | 0.000002 | @@ -1582,306 +1582,8 @@
%0A
- // compatibility with old middleware%0A Object.defineProperty(req.session, '_csrf', %7B%0A configurable: true,%0A get: function() %7B%0A console.warn('req.session._csrf is deprecated, use req.csrfToken() instead');%0A return req.csrfToken();%0A %7D%0A %7D);%0A %0A
|
e21a4ff69e5090bcfae4f272781ef019d936606a | Fix for enter key clearing validation warnings | src/main/resources/static/js/main.js | src/main/resources/static/js/main.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* RequireJS configuration with all possible dependencies
*/
requirejs.config({
baseUrl: '/bower_components',
paths: {
'jquery': 'jquery/dist/jquery.min',
}
});
/**
* Suggestions on the main page
*/
require(['jquery'],
function ($) {
$(".example").click(function(e) {
$("#url").val($(this).attr("href"));
e.preventDefault();
});
});
/**
* Validation for form
*/
require(['jquery'],
function ($) {
var generalPattern = "\\/([A-Za-z0-9_.-]+)\\/([A-Za-z0-9_.-]+)\\/?(?:tree|blob)\\/([^/]+)(?:\\/(.+\\.cwl))$";
var githubPattern = new RegExp("^https?:\\/\\/github\\.com" + generalPattern);
var gitlabPattern = new RegExp("^https?:\\/\\/gitlab\\.com" + generalPattern);
var gitPattern = new RegExp("((git|ssh|http(s)?)|(git@[\\w\\.]+))(:(//)?)([\\w\\.@\\:/\\-~]+)(\\.git)(/)?");
/**
* Show extra details in form if generic git repository
*/
$("#url").on('change keyup paste', function () {
var input = $(this).val();
if (gitPattern.test(input)) {
$("#extraInputs").fadeIn();
} else {
$("#extraInputs").fadeOut();
}
});
/**
* Clear warnings when fields change
*/
$("input").keyup(function() {
var field = $(this);
field.parent().removeClass("has-error");
field.next().text("");
});
/**
* Validate form before submit
*/
$('#add').submit(function() {
var pathPattern = new RegExp("^\\/?(\\w+\\/)*\\w+\\.cwl$");
var input = $("#url").val();
if (gitPattern.test(input)) {
var success = true;
if (!$("#branch").val()) {
addWarning("branch", "You must provide a branch name for the workflow");
success = false;
}
if (!$("#path").val()) {
addWarning("path", "You must provide a path to the workflow");
success = false;
} else if (!pathPattern.test($("#path").val())) {
addWarning("path", "Must be a valid path from the root to a .cwl workflow");
success = false;
}
return success;
} else if (!githubPattern.test(input) && !gitlabPattern.test(input)) {
addWarning("url", "Must be a URL to a workflow on Gitlab or Github, or a Git repository URL");
return false;
}
});
/**
* Adds warning state and message to the a field
* @param id The ID of the field
* @param message The message to be displayed on the form element
*/
function addWarning(id, message) {
var field = $("#" + id);
field.parent().addClass("has-error");
field.next().text(message);
}
}); | JavaScript | 0 | @@ -2150,36 +2150,136 @@
.keyup(function(
+e
) %7B%0A
+ // Fix for enter key being detected as a change%0A if (e.keyCode != 13) %7B%0A
var
@@ -2295,16 +2295,20 @@
(this);%0A
+
@@ -2356,32 +2356,36 @@
%22);%0A
+
+
field.next().tex
@@ -2387,24 +2387,38 @@
).text(%22%22);%0A
+ %7D%0A
%7D);%0A
|
946b8af653c7e2ddd2137546afb315fc14bc48b3 | Bring back number of greenlets display in the dashboard | mrq/dashboard/static/js/views/workers.js | mrq/dashboard/static/js/views/workers.js | define(["jquery", "underscore", "views/generic/datatablepage", "models", "moment"],function($, _, DataTablePage, Models, moment) {
return DataTablePage.extend({
el: '.js-page-workers',
template:"#tpl-page-workers",
events:{
"change .js-datatable-filters-showstopped": "filterschanged",
"click .js-workers-io": "showworkerio",
},
initFilters: function() {
this.filters = {
"showstopped": this.options.params.showstopped||""
};
},
setOptions:function(options) {
this.options = options;
this.initFilters();
this.flush();
},
showworkerio: function(evt) {
var self = this;
var worker_id = $(evt.currentTarget).data("workerid");
var worker_data = _.find(this.dataTableRawData.aaData, function(worker) {
return worker._id == worker_id;
});
var html_modal = _.template($("#tpl-modal-workers-io").html())({"worker": worker_data});
self.$(".js-workers-modal .js-workers-modal-content").html(html_modal);
self.$(".js-workers-modal h4").html("I/O for this worker, by task & by type");
self.$(".js-workers-modal").modal({});
return false;
},
renderDatatable:function() {
var self = this;
var datatableConfig = self.getCommonDatatableConfig("workers");
_.extend(datatableConfig, {
"aoColumns": [
{
"sTitle": "Name",
"sClass": "col-name",
"sType":"string",
"sWidth":"150px",
"mData":function(source, type/*, val*/) {
return "<a href='/#jobs?worker="+source._id+"'>"+source.name+"</a><br/><small>"+source.config.local_ip + " " + source._id+"</small>";
}
},
{
"sTitle": "Queues",
"sClass": "col-queues",
"sType":"string",
"mData":function(source, type/*, val*/) {
return _.map(source.config.queues||[], function(q) {
return "<a href='/#jobs?queue="+q+"'>"+q+"</a>";
}).join(" ");
}
},
{
"sTitle": "Status",
"sClass": "col-status",
"sType":"string",
"sWidth":"80px",
"mData":function(source, type/*, val*/) {
return source.status;
}
},
{
"sTitle": "Last report",
"sClass": "col-last-report",
"sType":"string",
"sWidth":"150px",
"mData":function(source, type/*, val*/) {
if (type == "display") {
return "<small>" + (source.datereported?moment.utc(source.datereported).fromNow():"Never")
+ "<br/>"
+ "started " + moment.utc(source.datestarted).fromNow() + "</small>";
} else {
return source.datereported || "";
}
}
},
{
"sTitle": "CPU usr/sys",
"sClass": "col-cpu",
"sType":"string",
"sWidth":"120px",
"mData":function(source, type/*, val*/) {
var usage = (source.process.cpu.user + source.process.cpu.system) * 1000 / (moment.utc(source.datereported || null).valueOf() - moment.utc(source.datestarted).valueOf());
var html = Math.round(source.process.cpu.user) + "s / " + Math.round(source.process.cpu.system) + "s"
+ "<br/>"
+ (Math.round(usage * 100)) + "% use";
if (((source.io || {}).types || []).length) {
html += "<br/>I/O: <a data-workerid='"+source._id+"' href='#' class='js-workers-io'>"+Math.round(source.io.total)+"s </a>";
}
return html;
}
},
{
"sTitle": "RSS",
"sClass": "col-mem",
"sType":"numeric",
"sWidth":"130px",
"mData":function(source, type/*, val*/) {
if (type == "display") {
return Math.round((source.process.mem.rss / (1024*1024)) *10)/10 + "M"
+ "<br/>"
+ '<span class="inlinesparkline" values="'+self.addToCounter("worker.mem."+source._id, source.process.mem.rss / (1024*1024), 50).join(",")+'"></span>';
} else {
return source.process.mem.rss
}
}
},
{
"sTitle": "Done Jobs",
"sClass": "col-done-jobs",
"sType":"numeric",
"sWidth":"120px",
"mData":function(source, type/*, val*/) {
var cnt = (source.done_jobs || 0);
if (type == "display") {
return "<a href='/#jobs?worker="+source._id+"'>"+cnt+"</a>"
+ "<br/>"
+ '<span class="inlinesparkline" values="'+self.addToCounter("worker.donejobs."+source._id, cnt, 50).join(",")+'"></span>';
} else {
return cnt;
}
}
},
{
"sTitle": "Speed",
"sClass": "col-eta",
"sType":"numeric",
"sWidth":"120px",
"mData":function(source, type, val) {
return (Math.round(self.getCounterSpeed("worker.donejobs."+source._id) * 100) / 100) + " j/s";
}
},
{
"sTitle": "Current Jobs",
"sClass": "col-current-jobs",
"sType":"numeric",
"sWidth":"120px",
"mData":function(source, type/*, val*/) {
var cnt = (source.jobs || []).length;
if (type == "display") {
return "<a href='/#jobs?worker="+source._id+"&status=started'>"+cnt+"</a> / "+source.config.gevent
+ "<br/>"
+ '<span class="inlinesparkline" values="'+self.addToCounter("worker.currentjobs."+source._id, cnt, 50).join(",")+'"></span>';
} else {
return cnt;
}
}
}
],
"fnDrawCallback": function (oSettings) {
$(".inlinesparkline", oSettings.nTable).sparkline("html", {"width": "100px", "height": "30px", "defaultPixelsPerValue": 1});
},
"aaSorting":[ [0,'asc'] ],
});
this.initDataTable(datatableConfig);
}
});
});
| JavaScript | 0 | @@ -5772,21 +5772,24 @@
config.g
-event
+reenlets
%0A
|
8b41841202abcde4bfe7a5b0426f091668f35d15 | Update hyphen stitching regex to include dangling 'not signs' | src/plugins/tts/PageChunk.js | src/plugins/tts/PageChunk.js | /**
* Class to manage a 'chunk' (approximately a paragraph) of text on a page.
*/
export default class PageChunk {
/**
* @param {number} leafIndex
* @param {number} chunkIndex
* @param {string} text
* @param {DJVURect[]} lineRects
*/
constructor(leafIndex, chunkIndex, text, lineRects) {
this.leafIndex = leafIndex;
this.chunkIndex = chunkIndex;
this.text = text;
this.lineRects = lineRects;
}
/**
* @param {string} server
* @param {string} bookPath
* @param {number} leafIndex
* @return {Promise<PageChunk[]>}
*/
static fetch(server, bookPath, leafIndex) {
// jquery's ajax "PromiseLike" implementation is inconsistent with
// modern Promises, so convert it to a full promise (it doesn't forward
// a returned promise to the next handler in the chain, which kind of
// defeats the entire point of using promises to avoid "callback hell")
return new Promise((res, rej) => {
$.ajax({
type: 'GET',
url: `https://${server}/BookReader/BookReaderGetTextWrapper.php`,
dataType:'jsonp',
cache: true,
data: {
path: `${bookPath}_djvu.xml`,
page: leafIndex
},
error: rej,
})
.then(chunks => {
res(PageChunk._fromTextWrapperResponse(leafIndex, chunks));
});
});
}
/**
* Convert the response from BookReaderGetTextWrapper.php into a {@link PageChunk} instance
* @param {number} leafIndex
* @param {Array<[String, ...DJVURect[]]>} chunksResponse
* @return {PageChunk[]}
*/
static _fromTextWrapperResponse(leafIndex, chunksResponse) {
return chunksResponse.map((c, i) => {
const correctedLineRects = PageChunk._fixChunkRects(c.slice(1));
const correctedText = PageChunk._removeDanglingHyphens(c[0]);
return new PageChunk(leafIndex, i, correctedText, correctedLineRects);
});
}
/**
* @private
* Sometimes the first rectangle will be ridiculously wide/tall. Find those and fix them
* *NOTE*: Modifies the original array and returns it.
* *NOTE*: This should probably be fixed on the petabox side, and then removed here
* Has 2 problems:
* - If the rect is the last rect on the page (and hence the only rect in the array),
* the rect's size isn't fixed
* - Because this relies on the second rect, there's a chance it won't be the right
* width
* @param {DJVURect[]} rects
* @return {DJVURect[]}
*/
static _fixChunkRects(rects) {
if (rects.length < 2) return rects;
const [firstRect, secondRect] = rects;
const [left, bottom, right] = firstRect;
const width = right - left;
const secondHeight = secondRect[1] - secondRect[3];
const secondWidth = secondRect[2] - secondRect[0];
const secondRight = secondRect[2];
if (width > secondWidth * 30) {
// Set the end to be the same
firstRect[2] = secondRight;
// And the top to be the same height
firstRect[3] = bottom - secondHeight;
}
return rects;
}
/**
* Remove "dangling" hyphens from read aloud text to avoid TTS stuttering
* @param {string} text
* @return {string}
*/
static _removeDanglingHyphens(text) {
return text.replace(/-\s+/g, '');
}
}
/**
* @typedef {[number, number, number, number]} DJVURect
* coords are in l,b,r,t order
*/
| JavaScript | 0 | @@ -3206,24 +3206,236 @@
ens(text) %7B%0A
+ // Some books mis-OCR a dangling hyphen as a %C2%AC (mathematical not sign) . Since in math%0A // the not sign should not appear followed by a space, we think we can safely assume%0A // this should be replaced.%0A
return t
@@ -3447,17 +3447,20 @@
eplace(/
--
+%5B-%C2%AC%5D
%5Cs+/g, '
|
df4aa5c1ccc26f11f5dfbd281666f1b9ae70122c | Add index changes to start | core/pwa/scripts/start.js | core/pwa/scripts/start.js | /* eslint-disable no-console, global-require */
const { emptyDir } = require('fs-extra');
const express = require('express');
const webpack = require('webpack');
const noFavicon = require('express-no-favicons');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackHotServerMiddleware = require('webpack-hot-server-middleware');
const clientConfig = require('./webpack/client.dev');
const serverConfig = require('./webpack/server.dev');
const clientConfigProd = require('./webpack/client.prod');
const serverConfigProd = require('./webpack/server.prod');
const { publicPath, path: outputPath } = clientConfig.output;
const DEV = process.env.NODE_ENV === 'development';
const start = async () => {
await emptyDir('.build/pwa');
const app = express();
app.use(noFavicon());
let isBuilt = false;
const done = () =>
!isBuilt &&
app.listen(3000, () => {
isBuilt = true;
console.log('BUILD COMPLETE -- Listening @ http://localhost:3000');
});
if (DEV) {
const compiler = webpack([clientConfig, serverConfig]);
const clientCompiler = compiler.compilers[0];
const options = { publicPath, stats: { colors: true } };
app.use(webpackDevMiddleware(compiler, options));
app.use(webpackHotMiddleware(clientCompiler));
app.use(webpackHotServerMiddleware(compiler));
compiler.plugin('done', done);
} else {
webpack([clientConfigProd, serverConfigProd]).run((err, stats) => {
const clientStats = stats.toJson().children[0];
const serverRender = require('../../../.build/pwa/server/main.js').default; // eslint-disable-line
app.use(publicPath, express.static(outputPath));
app.use(serverRender({ clientStats }));
done();
});
}
};
start();
| JavaScript | 0 | @@ -51,18 +51,59 @@
nst
-%7B emptyDir
+path = require('path');%0Aconst %7B emptyDir, writeFile
%7D =
@@ -688,74 +688,11 @@
nst
-%7B publicPath, path: outputPath %7D = clientConfig.output;%0A%0Aconst DEV
+dev
= p
@@ -790,16 +790,228 @@
d/pwa');
+%0A const buildInfo = %7B%0A buildPath: path.resolve(__dirname, '../../..'),%0A nodeEnv: dev ? 'development' : 'production',%0A %7D;%0A await writeFile('.build/pwa/buildInfo.json', JSON.stringify(buildInfo, null, 2));
%0A%0A cons
@@ -1259,11 +1259,11 @@
if (
-DEV
+dev
) %7B%0A
@@ -1397,20 +1397,8 @@
= %7B
- publicPath,
sta
@@ -1422,16 +1422,111 @@
e %7D %7D;%0A%0A
+ app.use('/static', express.static(path.resolve(__dirname, '../../../.build/pwa/client')));%0A
app.
@@ -1970,18 +1970,17 @@
use(
-publicPath
+'/static'
, ex
@@ -1992,16 +1992,40 @@
.static(
+clientConfigProd.output.
outputPa
|
f597ee9ab3206d2d8a3c4e61b812fcf35ab1c37f | return xhr | client/zdr/daily/controllers/DailyManager.js | client/zdr/daily/controllers/DailyManager.js | import _ from "lodash";
import $ from "jquery";
const _stories = {};
export default class DailyManager
{
/**
* 获取目前已从服务端获取到的所有日报内容的缓存(以日报 id 进行检索,无序,请勿用 index 检索)。
*/
static getFetchedStories()
{
return _stories;
}
/**
* 获取最新热门日报的 ID 列表。
* @param {Function(err, res)} [p_callback]
*/
static getTopStoryIDs(p_callback)
{
$.get("/api/4/news/top", (p_data) =>
{
p_callback(null, p_data);
}).fail(() =>
{
p_callback("/api/4/news/top error");
});
}
/**
* 获取指定日期的日报的 ID 列表。
* @param String p_date 指定的日期。如果未指定,则返回最新日报的索引;如果小于 20130519,则返回 {}。
* @param {Function(err, res)} [p_callback]
*/
static getStoryIDs(p_date, p_callback)
{
if (_.isFunction(p_date))
{
p_callback = p_date;
p_date = null;
}
if (_.isEmpty(_.trim(p_date)))
{
$.get("/api/4/news/before", (p_data) =>
{
p_callback(null, p_data);
}).fail(() =>
{
p_callback("/api/4/news/before error");
});
}
else
{
$.get("/api/4/news/before/" + p_date, (p_data) =>
{
p_callback(null, p_data);
}).fail(() =>
{
p_callback("/api/4/news/before/" + p_date + " error");
});
}
}
/**
* 获取指定唯一标识的日报。
* @param String p_id 指定的唯一标识。
* @param {Function(err, res)} [p_callback]
*/
static getStory(p_id, p_callback)
{
if (_.isFunction(p_callback))
{
if (_.isEmpty(_.trim(p_id)))
{
if (_.isFunction(p_callback))
{
p_callback("p_id must not be null");
}
}
else
{
$.get("/api/4/news/" + p_id, (p_data) =>
{
_stories[p_id] = p_data;
p_callback(null, p_data);
}).fail(() =>
{
p_callback("/api/4/news/ error");
});
}
}
}
}
| JavaScript | 0.999997 | @@ -378,32 +378,39 @@
)%0A %7B%0A
+return
$.get(%22/api/4/ne
@@ -422,32 +422,32 @@
p%22, (p_data) =%3E%0A
-
%7B%0A
@@ -961,32 +961,39 @@
%7B%0A
+return
$.get(%22/api/4/ne
@@ -1221,32 +1221,39 @@
%7B%0A
+return
$.get(%22/api/4/ne
@@ -1928,32 +1928,32 @@
e%0A %7B%0A
-
@@ -1952,16 +1952,23 @@
+return
$.get(%22/
|
ca77d7a8a76755cfc297af14c2a7788982f95da1 | Add some pauses to ensure the application has time to load | cypress/integration/gpu-dependant/cross-section-view.js | cypress/integration/gpu-dependant/cross-section-view.js | context('Snapshot-based tests', () => {
beforeEach(function () {
cy.visit('/?endTime=2018-01-01T12:00:00.000Z')
cy.waitForSplashscreen()
cy.waitForSpinner()
})
context('Cross section interactions', () => {
it('ensures user can enter and exit cross-section mode', () => {
// Show some earthquakes
cy.get('.earthquake-playback .slider-big .rc-slider-rail').click()
cy.wait(500) // animation
cy.get('[data-test=draw-cross-section]').click()
cy.drag('.map', [ { x: 250, y: 650 }, { x: 400, y: 650 } ])
cy.matchImageSnapshot('cross-section-1-line-visible')
cy.get('[data-test=open-3d-view]').click()
cy.wait(3000) // animation
cy.matchImageSnapshot('cross-section-2-3d-view')
cy.drag('.canvas-3d', [ { x: 900, y: 500 }, { x: 800, y: 600 } ])
cy.matchImageSnapshot('cross-section-3-rotated-3d-view')
cy.get('[data-test=exit-3d-view]').click()
cy.wait(1000)
cy.matchImageSnapshot('cross-section-4-map-again')
cy.get('[data-test=cancel-drawing]').click()
cy.wait(1000)
cy.matchImageSnapshot('cross-section-5-no-cross-section-line')
})
})
})
| JavaScript | 0 | @@ -405,16 +405,17 @@
cy.wait(
+1
500) //
@@ -542,24 +542,42 @@
y: 650 %7D %5D)%0A
+ cy.wait(500)
%0A cy.ma
|
4fca25241bb37310bfa87eea354a88460275ba0a | Support vendor sourcemaps for debugging | flexget/ui/gulpfile.js | flexget/ui/gulpfile.js | var del = require('del'),
gulp = require('gulp'),
mainBowerFiles = require('main-bower-files'),
uglify = require('gulp-uglify'),
gutil = require('gulp-util'),
concat = require('gulp-concat'),
sourcemaps = require('gulp-sourcemaps'),
vendor = require('gulp-concat-vendor'),
flatten = require('gulp-flatten'),
rename = require('gulp-rename'),
bower = require('gulp-bower'),
sass = require('gulp-sass'),
minifyCSS = require('gulp-minify-css'),
replace = require('gulp-replace');
var distPath = './vendor',
config = require('./config.json'),
bowerDir = './bower_components';
////
// Build JS Files
////
gulp.task('js:clean', function () {
return del([
distPath + '/js'
]);
});
gulp.task('js', ['js:clean'], function() {
gulp.src(mainBowerFiles('**/*.js'), { base: bowerDir })
.pipe(flatten())
.pipe(uglify({'preserveComments': 'license'}))
.pipe(rename({extname: '.min.js'}))
.pipe(gulp.dest(distPath + '/js'));
gulp.src(bowerDir + '/please-wait/build/please-wait.min.js')
.pipe(rename('splash.min.js'))
.pipe(gulp.dest(distPath + '/js'));
});
////
// Copy vendor css
////
gulp.task('css:clean', function () {
return del([
distPath + '/css'
]);
});
gulp.task('css', ['css:clean'], function () {
gulp.src('./css/vendor/*.scss')
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
// Fix for font paths in angular-ui-grid (does not support sass)
.pipe(minifyCSS())
.pipe(rename({extname: '.min.css'}))
.pipe(replace('../../bower_components/angular-ui-grid', '/ui/vendor/fonts'))
.pipe(gulp.dest(distPath + '/css'));
gulp.src(bowerDir + '/please-wait/build/please-wait.css')
.pipe(rename('splash.css'))
.pipe(gulp.dest(distPath + '/css'));
});
////
// Build Fonts
////
gulp.task('fonts:clean', function () {
return del([
distPath + '/fonts'
]);
});
gulp.task('fonts', ['fonts:clean'], function() {
return gulp.src(config['fonts'])
.pipe(flatten())
.pipe(gulp.dest(distPath + '/fonts'));
});
////
// Build All by default
////
gulp.task('default', ['fonts', 'css', 'js']); | JavaScript | 0 | @@ -821,32 +821,61 @@
pipe(flatten())%0A
+ .pipe(sourcemaps.init())%0A
.pipe(uglify
@@ -945,24 +945,57 @@
.min.js'%7D))%0A
+ .pipe(sourcemaps.write('.'))%0A
.pipe(gu
|
a9eb62880e45c166bdcd84811b6f33dac5cf6cef | Remove behaviour where backspace re-focuses on title field | js/forum/src/components/DiscussionComposer.js | js/forum/src/components/DiscussionComposer.js | import ComposerBody from 'flarum/components/ComposerBody';
import extractText from 'flarum/utils/extractText';
/**
* The `DiscussionComposer` component displays the composer content for starting
* a new discussion. It adds a text field as a header control so the user can
* enter the title of their discussion. It also overrides the `submit` and
* `willExit` actions to account for the title.
*
* ### Props
*
* - All of the props for ComposerBody
* - `titlePlaceholder`
*/
export default class DiscussionComposer extends ComposerBody {
init() {
super.init();
/**
* The value of the title input.
*
* @type {Function}
*/
this.title = m.prop('');
}
static initProps(props) {
super.initProps(props);
props.placeholder = props.placeholder || extractText(app.trans('core.forum.composer_discussion_body_placeholder'));
props.submitLabel = props.submitLabel || app.trans('core.forum.composer_discussion_submit_button');
props.confirmExit = props.confirmExit || extractText(app.trans('core.forum.composer_discussion_discard_confirmation'));
props.titlePlaceholder = props.titlePlaceholder || extractText(app.trans('core.forum.composer_discussion_title_placeholder'));
}
headerItems() {
const items = super.headerItems();
items.add('title', (
<h3>
<input className="FormControl"
value={this.title()}
oninput={m.withAttr('value', this.title)}
placeholder={this.props.titlePlaceholder}
disabled={!!this.props.disabled}
onkeydown={this.onkeydown.bind(this)}/>
</h3>
));
return items;
}
/**
* Handle the title input's keydown event. When the return key is pressed,
* move the focus to the start of the text editor.
*
* @param {Event} e
*/
onkeydown(e) {
if (e.which === 13) { // Return
e.preventDefault();
this.editor.setSelectionRange(0, 0);
}
m.redraw.strategy('none');
}
config(isInitialized, context) {
super.config(isInitialized, context);
// If the user presses the backspace key in the text editor, and the cursor
// is already at the start, then we'll move the focus back into the title
// input.
this.editor.$('textarea').keydown((e) => {
if (e.which === 8 && e.target.selectionStart === 0 && e.target.selectionEnd === 0) {
e.preventDefault();
const $title = this.$(':input:enabled:visible:first')[0];
$title.focus();
$title.selectionStart = $title.selectionEnd = $title.value.length;
}
});
}
preventExit() {
return (this.title() || this.content()) && this.props.confirmExit;
}
/**
* Get the data to submit to the server when the discussion is saved.
*
* @return {Object}
*/
data() {
return {
title: this.title(),
content: this.content()
};
}
onsubmit() {
this.loading = true;
const data = this.data();
app.store.createRecord('discussions').save(data).then(
discussion => {
app.composer.hide();
app.cache.discussionList.addDiscussion(discussion);
m.route(app.route.discussion(discussion));
},
this.loaded.bind(this)
);
}
}
| JavaScript | 0.000001 | @@ -1972,611 +1972,8 @@
%7D%0A%0A
- config(isInitialized, context) %7B%0A super.config(isInitialized, context);%0A%0A // If the user presses the backspace key in the text editor, and the cursor%0A // is already at the start, then we'll move the focus back into the title%0A // input.%0A this.editor.$('textarea').keydown((e) =%3E %7B%0A if (e.which === 8 && e.target.selectionStart === 0 && e.target.selectionEnd === 0) %7B%0A e.preventDefault();%0A%0A const $title = this.$(':input:enabled:visible:first')%5B0%5D;%0A $title.focus();%0A $title.selectionStart = $title.selectionEnd = $title.value.length;%0A %7D%0A %7D);%0A %7D%0A%0A
pr
|
c9db90cec7ef29b1cf4cba8f842df76345863138 | Include description in the field search drop down (#182) | ui/src/App.js | ui/src/App.js | import React, { Component } from "react";
import { MuiThemeProvider } from "material-ui";
import "App.css";
import {
ApiClient,
DatasetApi,
FacetsApi,
FieldsApi
} from "data_explorer_service";
import ExportFab from "components/ExportFab";
import ExportUrlApi from "api/src/api/ExportUrlApi";
import FacetsGrid from "components/facets/FacetsGrid";
import FieldSearch from "components/FieldSearch";
import Header from "components/Header";
const Disclaimer = (
<div style={{ margin: "20px" }}>
This dataset is publicly available for anyone to use under the terms
provided by the dataset source (<a href="http://www.internationalgenome.org/data">
http://www.internationalgenome.org/data
</a>) and are provided "AS IS" without any warranty, express or implied,
from Verily Life Sciences, LLC. Verily Life Sciences, LLC disclaims all
liability for any damages, direct or indirect, resulting from the use of the
dataset.
</div>
);
class App extends Component {
constructor(props) {
super(props);
this.state = {
datasetName: "",
enableFieldSearch: false,
facets: null,
totalCount: null,
filter: null,
// These are all fields which can be searched using field search.
// This is an array of react-select options. A react-select option
// is an Object with value and label. See
// https://github.com/JedWatson/react-select#installation-and-usage
fields: [],
// These represent fields selected via field search.
// This is an array of react-select options.
extraFacetsOptions: []
};
this.apiClient = new ApiClient();
this.apiClient.basePath = "/api";
this.facetsApi = new FacetsApi(this.apiClient);
this.facetsCallback = function(error, data) {
if (error) {
console.error(error);
// TODO(alanhwang): Redirect to an error page
} else {
this.setState({
facets: data.facets,
totalCount: data.count
});
}
}.bind(this);
this.fieldsApi = new FieldsApi(this.apiClient);
this.fieldsCallback = function(error, data) {
if (error) {
console.error(error);
} else {
this.setState({
fields: data.fields.map(field => {
return {
label: field.name,
value: field.elasticsearch_name
};
})
});
}
}.bind(this);
// Map from facet name to a list of facet values.
this.filterMap = new Map();
this.updateFacets = this.updateFacets.bind(this);
this.handleFieldSearchChange = this.handleFieldSearchChange.bind(this);
}
render() {
if (this.state.facets == null || this.state.datasetName === "") {
// Server has not yet responded or returned an error
return <div />;
} else {
return (
<MuiThemeProvider>
<div className="app">
<Header
datasetName={this.state.datasetName}
totalCount={this.state.totalCount}
/>
{this.state.enableFieldSearch && (
<FieldSearch
fields={this.state.fields}
handleChange={this.handleFieldSearchChange}
extraFacetsOptions={this.state.extraFacetsOptions}
/>
)}
<FacetsGrid
updateFacets={this.updateFacets}
facets={this.state.facets}
/>
<ExportFab
exportUrlApi={new ExportUrlApi(this.apiClient)}
filter={this.state.filter}
/>
{this.state.datasetName == "1000 Genomes" ? Disclaimer : null}
</div>
</MuiThemeProvider>
);
}
}
componentDidMount() {
this.fieldsApi.fieldsGet(this.fieldsCallback);
this.facetsApi.facetsGet({}, this.facetsCallback);
// Call /api/dataset
let datasetApi = new DatasetApi(this.apiClient);
let datasetCallback = function(error, data) {
if (error) {
// TODO: Show error in snackbar.
console.error(error);
} else {
this.setState({
datasetName: data.name,
enableFieldSearch: data.enableFieldSearch
});
}
}.bind(this);
datasetApi.datasetGet(datasetCallback);
}
handleFieldSearchChange(extraFacetsOptions) {
// Remove deleted facets from filter, if necessary.
// - User adds extra facet A
// - User checks A_val in facet A. filter is now "A=A_val"
// - In FieldSearch component, user deletes chip for facet A. We need to
// remove "A=A_val" from filter.
let deletedFacets = this.state.extraFacetsOptions.filter(
x => !extraFacetsOptions.includes(x)
);
deletedFacets.forEach(removed => {
if (this.filterMap.get(removed.label) !== undefined) {
this.filterMap.delete(removed.label);
}
});
let filterArray = this.filterMapToArray(this.filterMap);
this.setState({
extraFacetsOptions: extraFacetsOptions,
filter: filterArray
});
this.facetsApi.facetsGet(
{
filter: filterArray,
extraFacets: extraFacetsOptions.map(option => option.value)
},
this.facetsCallback
);
}
/**
* Updates the selection for a single facet value and refreshes the facets data from the server.
* @param facetName string containing the name of the facet corresponding to this value
* @param facetValue string containing the name of this facet value
* @param isSelected bool indicating whether this facetValue should be added to or removed from the query
* */
updateFacets(facetName, facetValue, isSelected) {
let currentFacetValues = this.filterMap.get(facetName);
if (isSelected) {
// Add facetValue to the list of filters for facetName
if (currentFacetValues === undefined) {
this.filterMap.set(facetName, [facetValue]);
} else {
currentFacetValues.push(facetValue);
}
} else if (this.filterMap.get(facetName) !== undefined) {
// Remove facetValue from the list of filters for facetName
this.filterMap.set(
facetName,
this.removeFacet(currentFacetValues, facetValue)
);
}
let filterArray = this.filterMapToArray(this.filterMap);
this.setState({ filter: filterArray });
this.facetsApi.facetsGet(
{
filter: filterArray,
extraFacets: this.state.extraFacetsOptions.map(option => option.value)
},
this.facetsCallback
);
}
removeFacet(valueList, facetValue) {
let newValueList = [];
for (let i = 0; i < valueList.length; i++) {
if (valueList[i] !== facetValue) {
newValueList.push(valueList[i]);
}
}
return newValueList;
}
/**
* Converts a Map of filters to an Array of filter strings interpretable by
* the backend
* @param filterMap Map of facetName:[facetValues] pairs
* @return [string] Array of "facetName=facetValue" strings
*/
filterMapToArray(filterMap) {
let filterArray = [];
filterMap.forEach((values, key) => {
// Scenario where there are no values for a key: A single value is
// checked for a facet. The value is unchecked. The facet name will
// still be a key in filterMap, but there will be no values.
if (values.length > 0) {
for (let value of values) {
filterArray.push(key + "=" + value);
}
}
});
return filterArray;
}
}
export default App;
| JavaScript | 0 | @@ -2257,24 +2257,226 @@
(field =%3E %7B%0A
+ if (field.description) %7B%0A return %7B%0A label: field.name + %22 - %22 + field.description,%0A value: field.elasticsearch_name%0A %7D;%0A %7D%0A
|
f4d3ff4c8de242a0f51237bec0a244896306f8ea | fix pnpm postinstall error (#39) | lib/rules/node-path.js | lib/rules/node-path.js | 'use strict';
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
const message = require('../message');
exports.description = 'NODE_PATH matches the npm root';
const errors = {
npmFailure() {
return message.get('node-path-npm-failure', {});
},
pathMismatch(npmRoot) {
let msgPath = 'node-path-path-mismatch';
if (process.platform === 'win32') {
msgPath += '-windows';
}
return message.get(msgPath, {
path: process.env.NODE_PATH,
npmroot: npmRoot
});
}
};
exports.errors = errors;
function fixPath(filepath) {
let fixedPath = path.resolve(path.normalize(filepath.trim()));
try {
fixedPath = fs.realpathSync(fixedPath);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
return fixedPath;
}
exports.verify = cb => {
if (process.env.NODE_PATH === undefined) {
cb(null);
return;
}
const nodePaths = (process.env.NODE_PATH || '').split(path.delimiter).map(fixPath);
childProcess.exec('npm -g root --silent', (err, stdout) => {
if (err) {
cb(errors.npmFailure());
return;
}
const npmRoot = fixPath(stdout);
if (nodePaths.indexOf(npmRoot) < 0) {
cb(errors.pathMismatch(npmRoot));
return;
}
cb(null);
});
};
| JavaScript | 0 | @@ -775,16 +775,42 @@
'ENOENT'
+ && err.code !== 'ENOTDIR'
) %7B%0A
|
f1bbb82201380edb6344b1e34896cc93a2ed1b1c | Update styling on conference tab bar | app/views/conference/ConferenceView.js | app/views/conference/ConferenceView.js | import React, { Component } from 'react';
import {
View,
StyleSheet,
Platform,
Text,
} from 'react-native';
import logger from '../../util/logger';
import css from '../../styles/css';
import ConferenceListView from './ConferenceListView';
import { platformIOS } from '../../util/general';
import { TAB_BAR_HEIGHT } from '../../styles/LayoutConstants';
import Touchable from '../common/Touchable';
export default class ConferenceView extends Component {
constructor(props) {
super(props);
this.state = {
personal: false
};
}
componentDidMount() {
logger.ga('View Loaded: ConferenceView');
}
handleFullPress = () => {
this.setState({ personal: false });
}
handleMinePress = () => {
this.setState({ personal: true });
}
render() {
return (
<View
style={[css.main_container, styles.greybg]}
>
<ConferenceListView
style={styles.conferenceListView}
scrollEnabled={true}
personal={this.state.personal}
/>
<FakeTabBar
personal={this.state.personal}
handleFullPress={this.handleFullPress}
handleMinePress={this.handleMinePress}
/>
</View>
);
}
}
const FakeTabBar = ({ personal, handleFullPress, handleMinePress }) => (
<View style={ platformIOS ? styles.tabBarIOS : styles.tabBarAndroid }>
<View
style={styles.buttonContainer}
>
<Touchable
style={styles.button}
onPress={() => handleFullPress()}
>
<Text
style={personal ? styles.plainText : styles.selectedText}
>
Full Schedule
</Text>
</Touchable>
<Touchable
style={styles.button}
onPress={() => handleMinePress()}
>
<Text
style={personal ? styles.selectedText : styles.plainText}
>
My Schedule
</Text>
</Touchable>
</View>
</View>
);
const styles = StyleSheet.create({
conferenceListView: { marginBottom: TAB_BAR_HEIGHT, flexGrow: 1 },
greybg: { backgroundColor: '#F9F9F9' },
buttonContainer: { flex: 1, flexDirection: 'row' },
button: { flex: 1, alignItems: 'center', justifyContent: 'center' },
selectedText: { fontSize: 18 },
plainText: { fontSize: 18, opacity: 0.5 },
tabBarIOS: { marginTop: -TAB_BAR_HEIGHT, borderTopWidth: 1, borderColor: '#DADADA', backgroundColor: '#FFF', height: TAB_BAR_HEIGHT },
tabBarAndroid: { borderBottomWidth: 1, borderColor: '#DADADA', backgroundColor: '#FFF', height: TAB_BAR_HEIGHT },
});
| JavaScript | 0 | @@ -286,16 +286,121 @@
neral';%0A
+import %7B%0A%09COLOR_PRIMARY,%0A%09COLOR_MGREY,%0A%09COLOR_LGREY,%0A%09COLOR_WHITE,%0A%7D from '../../styles/ColorConstants';%0A
import %7B
@@ -500,16 +500,17 @@
able';%0A%0A
+%0A
export d
@@ -1444,32 +1444,33 @@
able%0A%09%09%09%09style=%7B
+%5B
styles.button%7D%0A%09
@@ -1458,32 +1458,94 @@
=%7B%5Bstyles.button
+, %7B backgroundColor: personal ? COLOR_WHITE : COLOR_PRIMARY %7D%5D
%7D%0A%09%09%09%09onPress=%7B(
@@ -1716,32 +1716,33 @@
able%0A%09%09%09%09style=%7B
+%5B
styles.button%7D%0A%09
@@ -1738,16 +1738,78 @@
s.button
+, %7B backgroundColor: personal ? COLOR_PRIMARY : COLOR_WHITE %7D%5D
%7D%0A%09%09%09%09on
@@ -2127,17 +2127,19 @@
or:
-'#F9F9F9'
+COLOR_LGREY
%7D,%0A
@@ -2261,16 +2261,69 @@
ter' %7D,%0A
+%09buttonSelected: %7B backgroundColor: COLOR_PRIMARY %7D,%0A
%09selecte
@@ -2343,16 +2343,36 @@
Size: 18
+, color: COLOR_WHITE
%7D,%0A%09pla
@@ -2505,38 +2505,43 @@
ackgroundColor:
-'#FFF'
+COLOR_WHITE
, height: TAB_BA
@@ -2637,14 +2637,19 @@
or:
-'#FFF'
+COLOR_WHITE
, he
|
f5f73d87f8018ef6d27f5e11b95800ea3a8fa1d2 | implement relationModelMeta | addon/field-meta.js | addon/field-meta.js |
import Ember from 'ember';
export default Ember.ObjectProxy.extend({
name: null,
modelMeta: null,
content: function() {
var name = this.get('name');
var modelMeta = this.get('modelMeta');
return modelMeta.get('properties.'+name);
}.property('name', 'modelMeta'),
label: function() {
return this.get('content.label') || this.get('name').dasherize().split('-').join(' '); // TODO check i18n
}.property('content.label', 'name'),
widgetConfig: function() {
var config = this.get('widget');
if (config) {
if (typeof(config) === 'string') {
config = {type: config};
}
return config;
}
}.property('widget'),
/** returns the component name of the widget
* depending of `widgetType` (which can be `form` or `display`)
*/
getWidgetComponentName: function(widgetType, isMulti) {
var container = this.get('modelMeta.store.container');
var dasherizedModelType = this.get('modelMeta.resource').dasherize();
var componentName = dasherizedModelType + '-' + this.get('name') + '-widget-property-'+widgetType;
if (!container.resolve('component:'+componentName)) {
var widget = this.get('widgetConfig');
if (widget) {
var multi = '';
if (this.get('isMulti')) {
multi = '-multi';
}
componentName = 'widget-property'+ multi + '-' + widget.type + '-'+widgetType;
if (!container.resolve('component:'+componentName)) {
console.error('Error: cannot found the property widget', componentName, 'falling back to a generic one');
componentName = null;
}
} else {
componentName = null;
}
}
if (componentName === null) {
if (this.get('isRelation')) {
if (isMulti) {
componentName = 'widget-property-multi-relation-'+widgetType;
} else {
componentName = 'widget-property-relation-'+widgetType;
}
} else {
if (isMulti) {
componentName = 'widget-property-multi-'+widgetType;
} else if (this.get('isText')) {
componentName = 'widget-property-text-'+widgetType;
} else if (this.get('isNumber')) {
componentName = 'widget-property-number-'+widgetType;
} else if (this.get('isBoolean')) {
componentName = 'widget-property-bool-'+widgetType;
} else if (this.get('isDate')) {
componentName = 'widget-property-date-'+widgetType;
} else if (this.get('isDateTime')) {
componentName = 'widget-property-datetime-'+widgetType;
} else {
componentName = 'widget-property-text-'+widgetType;
}
}
}
return componentName;
},
displayWidgetComponentName: function() {
var isMulti = this.get('isMulti');
return this.getWidgetComponentName('display', isMulti);
}.property('name', 'resource'),
formWidgetComponentName: function() {
var isMulti = this.get('isMulti');
return this.getWidgetComponentName('form', isMulti);
}.property('name', 'resource'),
isRelation: function() {
var fieldType = this.get('content.type');
return !!this.get('modelMeta.store.db')[fieldType];
}.property('content.type', 'modelMeta.store.db'),
isMulti: Ember.computed.bool('content.multi'),
isDate: Ember.computed.equal('type', 'date'),
isDateTime: Ember.computed.equal('type', 'datetime'),
isTime: Ember.computed.equal('type', 'time'),
isText: function() {
return ['text', 'string'].indexOf(this.get('type')) > -1;
}.property('type'),
isNumber: function() {
return ['float', 'double', 'integer', 'number'].indexOf(this.get('type')) > -1;
}.property('type'),
isBoolean: function() {
return ['bool', 'boolean'].indexOf(this.get('type')) > -1;
}.property('type')
}); | JavaScript | 0.000004 | @@ -102,16 +102,426 @@
null,%0A%0A
+ /** if the field type is a relation, then%0A * returns the modelMeta of this relation%0A */%0A relationModelMeta: function() %7B%0A var fieldType = this.get('content.type');%0A var relationResource = this.get('modelMeta.store.db')%5BfieldType%5D%0A if (relationResource) %7B%0A return relationResource.get('modelMeta');%0A %7D%0A %7D.property('modelMeta.store.db', 'content.type'),%0A%0A
cont
|
71d6d98122c05bab4f50727b2208590b750d9771 | Add missing requirements to lib/confluence/metric_computer_service | lib/confluence/metric_computer_service.es6.js | lib/confluence/metric_computer_service.es6.js | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
require('../web_apis/release.es6.js');
require('../web_apis/release_interface_relationship.es6.js');
require('../web_apis/web_interface.es6.js');
require('./aggressive_removal.es6.js');
require('./api_velocity.es6.js');
require('./api_velocity_data.es6.js');
require('./browser_metric_data.es6.js');
require('./metric_computer.es6.js');
foam.ENUM({
name: 'MetricComputerType',
package: 'org.chromium.apis.web',
requries: [
'org.chromium.apis.web.AggressiveRemoval',
'org.chromium.apis.web.ApiVelocity',
'org.chromium.apis.web.BrowserSpecific',
'org.chromium.apis.web.FailureToShip',
],
properties: [
{
class: 'Class',
name: 'metricComputerCls',
},
{
class: 'String',
name: 'daoName',
value: 'browserMetricsDAO',
},
],
values: [
{
name: 'AGGRESSIVE_REMOVAL',
metricComputerCls: 'org.chromium.apis.web.AggressiveRemoval',
},
{
name: 'BROWSER_SPECIFIC',
metricComputerCls: 'org.chromium.apis.web.BrowserSpecific',
},
{
name: 'FAILURE_TO_SHIP',
metricComputerCls: 'org.chromium.apis.web.FailureToShip',
},
{
name: 'API_VELOCITY',
metricComputerCls: 'org.chromium.apis.web.ApiVelocity',
daoName: 'apiVelocityDAO',
},
],
});
foam.CLASS({
name: 'MetricComputerService',
package: 'org.chromium.apis.web',
requires: [
'org.chromium.apis.web.ApiVelocityData',
'org.chromium.apis.web.BrowserMetricData',
'org.chromium.apis.web.LocalJsonDAO',
'org.chromium.apis.web.Release',
'org.chromium.apis.web.ReleaseWebInterfaceJunction',
'org.chromium.apis.web.WebInterface',
],
imports: ['container'],
properties: [
{
class: 'FObjectProperty',
of: 'foam.mlang.predicate.Predicate',
name: 'releasePredicate',
required: true,
},
{
class: 'foam.dao.DAOProperty',
name: 'releaseDAO',
transient: true,
factory: function() {
this.validate();
// Ensure that releases are filtered according to service configuration.
// This maintains consistency between releases passed in to "compute"
// and releases available to seen by this service.
return this.getDAO_(this.Release).where(this.releasePredicate);
},
},
{
class: 'foam.dao.DAOProperty',
name: 'webInterfaceDAO',
transient: true,
factory: function() {
return this.getDAO_(this.WebInterface);
},
},
{
class: 'foam.dao.DAOProperty',
name: 'releaseWebInterfaceJunctionDAO',
transient: true,
factory: function() {
return this.getDAO_(this.ReleaseWebInterfaceJunction);
},
},
{
class: 'foam.dao.DAOProperty',
name: 'browserMetricsDAO',
transient: true,
factory: function() {
return this.lookup('foam.dao.MDAO').create({
of: this.BrowserMetricData
}, this.container);
},
},
{
class: 'foam.dao.DAOProperty',
name: 'apiVelocityDAO',
transient: true,
factory: function() {
return this.lookup('foam.dao.MDAO').create({
of: this.BrowserMetricData
}, this.container);
},
},
{
class: 'Function',
name: 'lookup',
transient: true,
factory: function() { return foam.lookup; },
},
],
methods: [
{
name: 'compute',
returns: 'Promise',
code: function(metricComputerType, releases, date) {
this.onBeforeCompute();
// Shift releases' context to be within their container, but outside
// whitelisted-for-deserialization context.
releases = this.recontextualizeReleases_(releases);
const metricComputer = metricComputerType.metricComputerCls
.create(null, this.container);
const dateObj = new Date(date);
if (isNaN(dateObj.getTime()))
return Promise.reject('Invalid Date: ' + date);
// Compute metrics (which output to
// "{browserMetrics|apiVelocity}DAO"), then return array of computed
// metrics.
return metricComputer.compute(releases, dateObj)
.then(() => this[metricComputerType.daoName].select())
.then(arraySink => arraySink.array);
},
},
function getDAO_(cls) {
// Load JSON in to ArrayDAO.
const jsonDAO = this.lookup('org.chromium.apis.web.LocalJsonDAO').create({
of: cls,
path: `${__dirname}/../../data/json/${cls.id}.json`,
}, this.container);
// Create indexed MDAO for fast queries.
const dao = this.lookup('foam.dao.MDAO').create({
of: cls,
}, this.container);
// Special indexing for Release <==> WebInterface junctions.
if (cls === this.ReleaseWebInterfaceJunction) {
dao.addPropertyIndex(this.ReleaseWebInterfaceJunction.SOURCE_ID);
}
// Copy ArrayDAO => MDAO; return MDAO.
return this.lookup('foam.dao.PromisedDAO').create({
of: cls,
promise: new Promise((resolve, reject) => {
// Note: Use of DAOSink without further synchronization is sound
// because "dao" is a *synchronous* DAO implementation.
return jsonDAO.select(this.lookup('foam.dao.DAOSink').create({
dao
}, this.container)).then(() => resolve(dao)).catch(reject);
}),
}, this.container);
},
function recontextualizeReleases_(releases) {
return releases.map(release => release.clone(this.container));
},
],
listeners: [
{
name: 'onBeforeCompute',
documentation: `Listener run before compute() to bind DAOs to container.`,
code: function() {
// Ensure input DAOs are bound to container.
this.container.releaseDAO = this.releaseDAO;
this.container.webInterfaceDAO = this.webInterfaceDAO;
this.container.releaseWebInterfaceJunctionDAO =
this.releaseWebInterfaceJunctionDAO;
// Bind fresh output DAOs to container.
this.browserMetricsDAO = this.container.browserMetricsDAO =
this.lookup('foam.dao.MDAO').create({
of: this.BrowserMetricData
}, this.container);
this.apiVelocityDAO = this.container.apiVelocityDAO =
this.lookup('foam.dao.MDAO').create({
of: this.ApiVelocityData
}, this.container);
},
},
],
});
| JavaScript | 0.000012 | @@ -201,16 +201,39 @@
/release
+_interface_relationship
.es6.js'
@@ -263,39 +263,16 @@
/release
-_interface_relationship
.es6.js'
@@ -351,32 +351,111 @@
moval.es6.js');%0A
+require('./aggressive_removal.es6.js');%0Arequire('./api_velocity_data.es6.js');%0A
require('./api_v
@@ -487,37 +487,32 @@
('./api_velocity
-_data
.es6.js');%0Arequi
@@ -539,32 +539,107 @@
_data.es6.js');%0A
+require('./browser_specific.es6.js');%0Arequire('./failure_to_ship.es6.js');%0A
require('./metri
|
f382538caa4358927f1ca39e0bb343b81699365f | return dialog on render | lib/scripts/factory.js | lib/scripts/factory.js | var Factory = function (dialogs, options) {
this.dialogs = dialogs;
this.options = options || {};
this.config = options.config || {};
this.templates = options.templates || {};
};
Factory.prototype.createDialog = function (dialog, options) {
var opts = options || {};
opts.dialog = dialog;
var Dialog = this.dialogs.get(dialog.type);
// add any classname if defined
if (dialog.className) {
opts.className = Dialog.prototype.className + ' ' + dialog.className;
}
// instanciate dialog
var view = new Dialog(opts);
// we need to set the template before rendering the view
// if no template has been attached to the view search for the main template registry
if (!view.template) {
view.template = this.templates[dialog.template];
}
return view;
};
Factory.prototype.create = function (slug, options) {
if (!slug && !this.config.dialogs[slug]) {
return;
}
var dialog = this.config.dialogs[slug];
return this.createDialog(dialog, options);
};
Factory.prototype.render = function (region, slug, options) {
if (!region) {
return;
}
var dialog = this.create(slug, options);
if (!dialog) {
return false;
}
region.show(dialog);
};
| JavaScript | 0.000001 | @@ -1195,12 +1195,30 @@
dialog);
+%0A%0A return dialog;
%0A%7D;%0A
|
c2e13e12c6f0e3f99dcfb89697a036ad8d0a34f4 | minify js | typogr.min.js | typogr.min.js | /*!
* typogr.js
* Copyright(c) 2011 Eugene Kalinin
* MIT Licensed
*/(function(a){var b=function(a){return new o(a)};b.version="0.4.0",typeof module!="undefined"&&module.exports?module.exports=b:a.typogr=b;var c=function(a,b){return new RegExp(a,b)},d=b.amp=function(a){var b=/(\s| )(&|&|&\#38;)(\s| )/g,c=/(<[^<]*>)?([^<]*)(<\/[^<]*>)?/g;if(!!a)return a.replace(c,function(a,c,d,e){var c=c||"",e=e||"",d=d.replace(b,'$1<span class="amp">&</span>$3');return c+d+e})},e=b.ord=function(a){var b=/(\d+)(st|nd|rd|th)/g;if(!!a)return a.replace(b,'$1<span class="ord">$2</span>')},f=b.quotes=function(a){var b=c("(?:(?:<(?:p|h[1-6]|li|dt|dd)[^>]*>|^)\\s*(?:<(?:a|em|span|strong|i|b)[^>]*>s*)*)(?:(\"|“|“)|('|‘|‘))","i");if(!!a)return a.replace(b,function(a,b,c){var d=b?"dquo":"quo",e=b?b:c;return[a.slice(0,a.lastIndexOf(e)),'<span class="',d,'">',e,"</span>"].join("")})},g=b.widont=function(a){var b=c("((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\\s])\\s+([^<>\\s]+\\s*(</(a|em|span|strong|i|b)>\\s*)*((</(p|h[1-6]|li|dt|dd)>)|$))","gi");return a.replace(b,"$1 $2")};b.typogrify=function(a){a=d(a),a=g(a),a=h(a),a=f(a),a=e(a);return a};var h=b.smartypants=function(a){var b=i(a),c=[],d=/<(\/)?(pre|code|kbd|script|math)[^>]*>/i,e=[],f="",g="",h=!1,o="",p,q;b.forEach(function(a){if(a.type==="tag")c.push(a.txt),(g=d.exec(a.txt))!=null&&(f=g[2].toLowerCase(),g[1]?(e.length>0&&f===e[-1]&&e.pop(),e.length===0&&(h=!1)):(e.push(f),h=!0));else{q=a.txt,p=q.slice(-1);if(!h){q=j(q),q=k(q),q=l(q),q=m(q);switch(q){case"'":/\S/.test(o)?q="’":q="‘";break;case'"':/\S/.test(o)?q="”":q="“";break;default:q=n(q)}}o=p,c.push(q)}});return c.join("")},i=b.tokenize=function(a){var b=[],c=0,d=/([^<]*)(<[^>]*>)/gi,e;while((e=d.exec(a))!=null){var f=e[1],g=e[2];f&&b.push({type:"text",txt:f}),b.push({type:"tag",txt:g}),c=d.lastIndex}d.lastIndex<=a.length&&b.push({type:"text",txt:a.slice(c)});return b},j=b.smartEscapes=function(a){return a.replace(/\\"/g,""").replace(/\\'/g,"'").replace(/\\-/g,"-").replace(/\\\./g,".").replace(/\\\\/g,"\").replace(/\\`/g,"`")},k=b.smartDashes=function(a){return a.replace(/---/g,"–").replace(/--/g,"—")},l=b.smartEllipses=function(a){return a.replace(/\.\.\./g,"…").replace(/\. \. \./g,"…")},m=b.smartBackticks=function(a){return a.replace(/``/g,"“").replace(/''/g,"”")},n=b.smartQuotes=function(a){var b="[!\"#$%'()*+,-./:;<=>?@[\\]^_`{|}~]",d="(?=%s\\B)".replace("%s",b),e="[^ \t\r\n[{(-]",f="–|—",g=c("(s| |--|&[mn]dash;|"+f+"|"+"ȁ[34];"+")"+"'"+"(?=w)","g"),h=c("("+e+")"+"'"+"(?!s | s\b | d)","g"),i=c("("+e+")"+"'"+"(?!s | s\b)","g"),j=c("(s| |--|&[mn]dash;|"+f+"|"+"ȁ[34];"+")"+'"'+"(?=w)","g"),k=c('"(?=s)',"g"),l=c("("+e+')"',"g");return a.replace(c("^'%s".replace("%s",d),"g"),"’").replace(c('^"%s'.replace("%s",d),"g"),"”").replace(/"'(?=\w)/g,"“‘").replace(/'"(?=\w)/g,"‘“").replace(/\b'(?=\d{2}s)/g,"’").replace(g,"$1‘").replace(h,"$1’").replace(i,"$1’$2").replace("'","‘").replace(j,"$1“").replace(k,"”").replace(l,"$1”").replace('"',"“")},o=function(a){this._wrapped=a},p=function(a,c){return c?b(a).chain():a},q=function(a,c){o.prototype[a]=function(){return p(c.apply(b,[this._wrapped]),this._chain)}},r=function(a){return!!(a&&a.constructor&&a.call&&a.apply)};for(var s in b)r(b[s])&&q(s,b[s]);o.prototype.chain=function(){this._chain=!0;return this},o.prototype.value=function(){return this._wrapped}})(this) | JavaScript | 0.998106 | @@ -132,17 +132,17 @@
on=%220.4.
-0
+1
%22,typeof
|
ce2bca76cea79e1793e952a3d6a442f55c9e8b15 | fix error location property | lib/rules/validate-jsdoc/enforce-existence.js | lib/rules/validate-jsdoc/enforce-existence.js | var assert = require('assert');
module.exports = enforceExistence;
module.exports.scopes = ['function'];
module.exports.options = {
enforceExistence: true
};
/**
* @param {Object} options
*/
enforceExistence.configure = function(options) {
// set default policy
var policy = this._enforceExistencePolicy = {
all: true,
anonymous: false,
exports: true,
expressions: true
};
// check options are valid
var o = options.enforceExistence;
assert(
o === true || o === false || typeof o === 'string' || (typeof o === 'object' && Array.isArray(o.allExcept)),
'jsDoc.enforceExistence rule was not configured properly'
);
// parse options for policies
if (o === false) {
policy.all = false;
} else if (typeof o === 'string' && o === 'exceptExports') { // backward compatible string option
policy.exports = false;
} else if (typeof o === 'object' && Array.isArray(o.allExcept)) {
if (o.allExcept.indexOf('exports') > -1) {
policy.exports = false;
}
if (o.allExcept.indexOf('expressions') > -1) {
policy.expressions = false;
}
}
};
/**
* Validator for jsdoc data existence
*
* @param {(FunctionDeclaration|FunctionExpression)} node
* @param {Function} err
*/
function enforceExistence(node, err) {
var policy = this._enforceExistencePolicy;
// enforce 'break-out' policies
var parentNode = node.parentNode || {};
if (policy.all === false) {
// don't check anything
return;
}
if (policy.anonymous === false) {
if (!node.id && ['AssignmentExpression', 'VariableDeclarator', 'Property'].indexOf(parentNode.type) === -1) {
// don't check anonymous functions
return;
}
}
if (policy.exports === false) {
if (parentNode.type === 'AssignmentExpression') {
var left = parentNode.left;
if ((left.object && left.object.name) === 'module' &&
(left.property && left.property.name) === 'exports') {
// don't check exports functions
return;
}
}
}
if (policy.expressions === false) {
if (['AssignmentExpression', 'VariableDeclarator', 'Property'].indexOf(parentNode.type) > -1) {
// don't check expression functions
return;
}
}
// now clear to check for documentation
if (node.jsdoc) {
if (!node.jsdoc.valid) {
err('Invalid jsdoc-block definition', node.jsdoc.loc);
}
return;
}
// report absence
err('Expect valid jsdoc-block definition', node.loc.start);
}
| JavaScript | 0.000003 | @@ -2585,16 +2585,22 @@
sdoc.loc
+.start
);%0A
|
051af3a73ab25a591d0f63a2a3216e807fd23ad6 | return all error properties to socket | lib/socket/handlers.js | lib/socket/handlers.js | const config = require('../config');
const convertError = require(`../utils/convertError`);
const db = require(`../db`);
const defaultCallback = () => {};
const parseArgs = (options, callback) => {
let cb;
let opts;
if (!(options || callback)) {
cb = defaultCallback;
opts = {};
}
if (options instanceof Function) {
cb = options;
opts = {};
} else {
cb = callback || defaultCallback;
opts = options || {};
}
if (!(opts instanceof Object)) {
const err = new TypeError(`The options argument must be an Object.`);
err.status = 400;
throw err;
}
if (!(cb instanceof Function)) {
const err = new TypeError(`The callback argument must be a Function.`);
err.status = 400;
throw err;
}
return {
cb,
opts,
};
};
module.exports = socket => {
// GENERIC CRUD METHODS
const add = async (type, data = {}, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const token = socket.decoded_token;
const model = await db.create(data, token.sub, type, opts);
const lastModified = new Date(model._ts).toUTCString();
cb(undefined, model, {
lastModified,
status: 201,
});
};
const destroy = async (id, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const token = socket.decoded_token;
const res = await db.delete(id, token.sub, opts);
cb(undefined, res, { status: 204 });
socket.broadcast.emit(`delete`, id, res.type);
};
const get = async (id, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const model = await db.get(id, socket.decoded_token.sub, opts);
const lastModified = new Date(model._ts).toUTCString();
cb(undefined, model, {
lastModified,
status: 200,
});
};
const getAll = async (type, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const models = await db.getAll(socket.decoded_token.sub, type, opts);
const info = { status: 200 };
if (models.continuation) {
info.continuation = models.continuation;
Reflect.deleteProperty(models, `continuation`);
}
cb(undefined, models, info);
};
const update = async (data, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const token = socket.decoded_token;
const model = await db.update(data, token.sub, opts);
const lastModified = new Date(model._ts).toUTCString();
cb(undefined, model, {
lastModified,
status: 200,
});
socket.broadcast.emit(`update`, model.id);
};
const upsert = async (data, options = {}, callback = defaultCallback) => {
const { cb, opts } = parseArgs(options, callback);
const token = socket.decoded_token;
const model = await db.upsert(data, token.sub, opts);
const lastModified = new Date(model._ts).toUTCString();
cb(undefined, model, {
lastModified,
status: 201,
});
socket.broadcast.emit(`upsert`, model.id);
};
const handlers = {
// generic handlers
add,
delete: destroy,
destroy,
get,
getAll,
update,
upsert,
// type-specific handlers
addLanguage: (...args) => add(`Language`, ...args),
deleteLanguage: destroy,
getLanguage: (...args) => get(...args),
getLanguages: (...args) => getAll(`Language`, ...args),
updateLanguage: (...args) => update(...args),
upsertLanguage: (...args) => upsert(...args),
};
// WRAP HANDLERS TO CATCH ERRORS IN PROMISES
const wrap = handler => (...args) => handler(...args).catch(err => {
const cb = args.filter(arg => typeof arg === `function`)[0];
const e = convertError(err);
const res = {
error: e.error,
error_description: e.error_description,
status: e.status,
};
if (config.logErrors && res.status >= 500) console.error(res);
if (cb) return cb(res);
socket.emit(`exception`, res);
});
Object.entries(handlers).forEach(([key, val]) => {
handlers[key] = wrap(val);
});
return handlers;
};
| JavaScript | 0.000008 | @@ -3916,130 +3916,28 @@
s =
-%7B%0A error: e.error,%0A error_description: e.error_description,%0A status: e.status,%0A %7D
+Object.assign(%7B%7D, e)
;%0A
@@ -3962,19 +3962,17 @@
rors &&
-res
+e
.status
@@ -3993,19 +3993,17 @@
e.error(
-res
+e
);%0A i
|
97ee83d8459801450868303b201069dd16db3a6a | attach dependent scripts to exampleDoc | ngdoc/processors/examples-generate.js | ngdoc/processors/examples-generate.js | var _ = require('lodash');
var log = require('winston');
var path = require('canonical-path');
var trimIndentation = require('dgeni/lib/utils/trim-indentation');
var code = require('dgeni/lib/utils/code');
var templateFolder, commonFiles;
function outputPath(example, fileName) {
return path.join(example.outputFolder, fileName);
}
function createExampleDoc(example) {
var exampleDoc = {
id: example.id,
docType: 'example',
template: path.join(templateFolder, 'index.template.html'),
file: example.doc.file,
startingLine: example.doc.startingLine,
example: example,
path: example.id,
outputPath: example.outputFolder + '/index.html'
};
// Copy in the common scripts
exampleDoc.scripts = _.map(commonFiles.scripts || [], function(script) { return { path: script }; });
exampleDoc.stylesheets = _.map(commonFiles.stylesheets || [], function(stylesheet) { return { path: stylesheet }; });
// If there is an index.html file specified then use it contents for this doc
// and remove it from the files property
if ( example.files['index.html'] ) {
exampleDoc.fileContents = example.files['index.html'].fileContents;
delete example.files['index.html'];
}
return exampleDoc;
}
function createFileDoc(example, file) {
var fileDoc = {
docType: 'example-' + file.type,
id: example.id + '/' + file.name,
template: path.join(templateFolder, 'template.' + file.type),
file: example.doc.file,
startingLine: example.doc.startingLine,
example: example,
path: file.name,
outputPath: outputPath(example, file.name),
fileContents: file.fileContents
};
return fileDoc;
}
module.exports = {
name: 'examples-generate',
description: 'Search the documentation for examples that need to be extracted',
runAfter: ['adding-extra-docs'],
runBefore: ['extra-docs-added'],
init: function(config, injectables) {
exampleNames = {};
commonFiles = config.get('processing.examples.commonFiles', []);
templateFolder = config.get('processing.examples.templateFolder', 'examples');
},
process: function(docs, examples) {
_.forEach(examples, function(example) {
// Create a new document for the example
var exampleDoc = createExampleDoc(example);
docs.push(exampleDoc);
// Create a new document for each file of the example
_.forEach(example.files, function(file) {
var fileDoc = createFileDoc(example, file);
docs.push(fileDoc);
// Store a reference to the fileDoc in the relevant property on the exampleDoc
if ( file.type == 'css' ) {
exampleDoc.stylesheets.push(fileDoc);
} else if ( file.type == 'js' ) {
exampleDoc.scripts.push(fileDoc);
}
});
});
}
}; | JavaScript | 0.000001 | @@ -230,18 +230,34 @@
monFiles
+, dependencyPath
;%0A
-
%0A%0Afuncti
@@ -718,16 +718,32 @@
scripts
+ and stylesheets
%0A examp
@@ -839,16 +839,16 @@
%7D; %7D);%0A
-
exampl
@@ -960,16 +960,242 @@
%7D; %7D);%0A%0A
+ // Copy in any dependencies for this example%0A if ( example.deps ) %7B%0A _.forEach(example.deps.split(';'), function(dependency) %7B%0A exampleDoc.scripts.push(%7B path: path.join(dependencyPath, dependency) %7D);%0A %7D);%0A %7D%0A%0A
// If
@@ -2328,16 +2328,92 @@
ples');%0A
+ dependencyPath = config.get('processing.examples.dependencyPath', '.');%0A
%7D,%0A p
|
c4de47f6ae0e1699ac0c3f1084fab04db5727bd8 | handle undefined | app/views/management/tasks/tasks-id.js | app/views/management/tasks/tasks-id.js | define(['lodash', 'directives/management/register-facets', 'authentication', "directives/formats/views/form-loader", 'utilities/km-workflows', 'utilities/km-storage', 'utilities/km-utilities'], function(_) { 'use strict';
return [ "$scope", "$timeout", "$http", "$route", "IStorage", "IWorkflows", "authentication", function ($scope, $timeout, $http, $route, IStorage, IWorkflows, authentication)
{
//==================================================
//
//
//==================================================
function load() {
IWorkflows.get($route.current.params.id).then(function(workflow){
$scope.workflow = workflow;
if(workflow.data.identifier && !workflow.closedOn) {
IStorage.drafts.get(workflow.data.identifier).then(function(result){
$scope.document = result.data || result;
});
}
});
}
//==================================================
//
//
//==================================================
$scope.isAssignedToMe = function(activity) {
return activity && _.contains(activity.assignedTo||[], authentication.user().userID||-1);
};
//==================================================
//
//
//==================================================
$scope.isOpen = function(element) {
return element && !element.closedOn;
};
//==================================================
//
//
//==================================================
$scope.isClose = function(element) {
return element && element.closedOn;
};
//==============================
//
//==============================
$scope.formatWID = function (workflowID) {
return workflowID.replace(/(?:.*)(.{3})(.{4})$/g, "W$1-$2");
};
load();
}];
});
| JavaScript | 0.001417 | @@ -1607,16 +1607,17 @@
%09return
+(
workflow
@@ -1618,16 +1618,21 @@
rkflowID
+%7C%7C'')
.replace
|
3d3941e31837bb8182825f4b2c57e3ccc7648c4f | Tidy up | ui/actions.js | ui/actions.js | import _ from 'lodash';
import { pushPath } from 'redux-simple-router';
import { Actions, Alert } from './constants';
import * as WebAPI from './api';
function movieLoaded(movie) {
return {
type: Actions.MOVIE_LOADED,
payload: movie
};
}
export function addMessage(status, message) {
return {
type: Actions.ADD_MESSAGE,
payload: {
status,
message,
id: _.uniqueId()
}
};
}
export function dismissMessage(id) {
return {
type: Actions.DISMISS_MESSAGE,
payload: id
};
}
export function getMovie(id) {
return (dispatch) => {
WebAPI
.getMovie(id)
.then(result => dispatch(movieLoaded(result.data)))
.catch(() => {
dispatch(addMessage(Alert.DANGER, "Sorry, no movie found"));
dispatch(pushPath("/all/"));
});
}
}
export function addMovie(title) {
return (dispatch) => {
WebAPI
.addMovie(title)
.then(result => {
dispatch(movieLoaded(result.data));
dispatch(addMessage(Alert.SUCCESS, "New movie added"));
dispatch(pushPath(`/movie/${result.data.imdbID}/`));
})
.catch(() => {
dispatch(addMessage(Alert.WARNING, `Sorry, couldn't find the movie "${title}"`));
});
}
}
export function deleteMovie(movie) {
return (dispatch) => {
WebAPI.deleteMovie(movie.imdbID);
dispatch(addMessage(Alert.INFO, "Movie deleted"));
dispatch(pushPath("/all/"));
}
}
export function getMovies() {
return (dispatch) => {
WebAPI.getMovies()
.then(result => {
dispatch({
type: Actions.MOVIES_LOADED,
payload: result.data
});
});
}
}
export function clearMovie() {
return movieLoaded(null);
}
export function getRandomMovie() {
return (dispatch) => {
WebAPI
.getRandomMovie()
.then(result => dispatch(movieLoaded(result.data)));
}
}
export function markSeen(movie) {
WebAPI.markSeen(movie.imdbID);
return {
type: Actions.MARK_SEEN
};
}
export function suggest(movie) {
return {
type: Actions.NEW_SUGGESTION,
payload: movie
}
}
| JavaScript | 0.000027 | @@ -563,33 +563,32 @@
%7B%0A return
-(
dispatch
) =%3E %7B%0A W
@@ -567,33 +567,32 @@
return dispatch
-)
=%3E %7B%0A WebAPI
@@ -841,33 +841,32 @@
%7B%0A return
-(
dispatch
) =%3E %7B%0A W
@@ -845,33 +845,32 @@
return dispatch
-)
=%3E %7B%0A WebAPI
@@ -1247,33 +1247,32 @@
%7B%0A return
-(
dispatch
) =%3E %7B%0A W
@@ -1251,33 +1251,32 @@
return dispatch
-)
=%3E %7B%0A WebAPI
@@ -1433,33 +1433,32 @@
%7B%0A return
-(
dispatch
) =%3E %7B%0A W
@@ -1437,33 +1437,32 @@
return dispatch
-)
=%3E %7B%0A WebAPI
@@ -1714,17 +1714,16 @@
urn
-(
dispatch
) =%3E
@@ -1718,17 +1718,16 @@
dispatch
-)
=%3E %7B%0A
|
25f3aa10038c4d2e7c27666f4a5337f98bcf4f2c | remove unset data and content type | plugins/de.kcct.hi5/resources/hi5-io.js | plugins/de.kcct.hi5/resources/hi5-io.js | define(['jquery'], function($) {
let module = {};
module.ax = function(method, dataType, contentType, url, o) {
const opts = {method, dataType, contentType, url, ...o};
if (opts.data && typeof opts.data == 'object') {
opts.data = JSON.stringify(o.data);
}
if (opts.params) {
opts.url = opts.url + '?' + $.param(opts.params);
}
return $.ajax(opts);
};
return module;
}); | JavaScript | 0.000001 | @@ -166,16 +166,114 @@
...o%7D;%0A
+%09%09opts.dataType = opts.dataType %7C%7C undefined;%0A%09%09opts.contentType = opts.contentType %7C%7C undefined;%0A
%09%09if (op
|
5424b6727dd651d4def8d67436227e583a394b0b | replace js | charat2/static/js/rp/quirks.js | charat2/static/js/rp/quirks.js | function applyQuirks(text,pattern) {
// Case
switch (pattern['case']) {
case "lower":
text = text.toLowerCase();
break;
case "upper":
text = text.toUpperCase();
break;
case "title":
text = text.toLowerCase().replace(/\b\w/g, function(t) { return t.toUpperCase(); });
break;
case "inverted":
var buffer = text.replace(/[a-zA-Z]/g, function(t) {
var out = t.toUpperCase();
if (out==t) {
return t.toLowerCase();
} else {
return out;
}
}).replace(/\bI\b/g, 'i').replace(/,\s*[A-Z]/g, function(t) { return t.toLowerCase(); });
text = buffer.charAt(0).toLowerCase()+buffer.substr(1);
break;
case "alternating":
var buffer = text.toLowerCase().split('');
for(var i=0; i<buffer.length; i+=2){
buffer[i] = buffer[i].toUpperCase();
}
text = buffer.join('');
break;
}
// Replacements
var replace = {};
for (i=0; i<pattern.replacements.length; i++) {
var replacement = pattern.replacements[i];
replace[replacement[0]] = replacement[1];
}
var regex = {};
for (i=0; i<pattern.regexes.length; i++) {
var re = pattern.regexes[i];
regex[re[0]] = re[1];
}
var empty = true;
for(var key in replace) {
empty = false;
break;
}
for(var key in regex) {
empty = false;
break;
}
if (!empty) {
var replacementStrings = Object.keys(replace);
for (i=0;i<replacementStrings.length;i++) {
replacementStrings[i] = replacementStrings[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var regexStrings = Object.keys(regex);
var reg_from = new RegExp(replacementStrings.join("|")+"|"+regexStrings.join("|"), "g");
text = text.replace(reg_from, function($1) {
if (replace[$1]) {
return replace[$1]
} else {
for (var reg in regexStrings) {
if (RegExp(regexStrings[reg],'g').test($1)) {
return regex[regexStrings[reg]];
}
}
}
});
}
// Prefix
if (pattern.quirk_prefix) {
text = pattern.quirk_prefix+' '+text;
}
// Suffix
if (pattern.quirk_suffix) {
text = text+' '+pattern.quirk_suffix;
}
return text
}
function depunct(txt) {
return txt.replace(/[.,?!']/g, '');
} | JavaScript | 0.999904 | @@ -2297,53 +2297,239 @@
-if (RegExp(regexStrings%5Breg%5D,'g').test($1)) %7B
+var original_text = $1;%0D%0A if (RegExp(regexStrings%5Breg%5D,'g').test($1)) %7B%0D%0A var replaced_text = regex%5BregexStrings%5Breg%5D%5D;%0D%0A replaced_text.replace(/%5C$1/g,original_text);
%0D%0A
|
b3566fc8e8fa0b79219eed7c342e78e32e847eb3 | add splay when building packages | aws/lambdas/hhvm-build-binary-packages/index.js | aws/lambdas/hhvm-build-binary-packages/index.js | 'use strict';
const AWS = require('aws-sdk');
const promise = require('promise');
const rp = require('request-promise');
function get_distros_uri(event) {
return 'https://raw.githubusercontent.com/hhvm/packaging/'
+ event.packagingBranch + '/CURRENT_TARGETS';
}
function get_userdata_uri(event) {
return 'https://raw.githubusercontent.com/hhvm/packaging/'
+ event.packagingBranch + '/aws/userdata/make-binary-package.sh';
}
function make_binary_package(distro, event, user_data) {
if (distro === undefined) {
throw "distro must be specified";
}
user_data =
"#!/bin/bash\n"+
"DISTRO="+distro+"\n"+
"VERSION="+event.version+"\n"+
"IS_NIGHTLY="+(event.nightly ? 'true' : 'false')+"\n"+
"S3_SOURCE=s3://"+event.source.bucket+'/'+event.source.path+"\n"+
"PACKAGING_BRANCH="+event.packagingBranch+"\n"+
user_data;
const params = {
ImageId: /* ubuntu 16.04 */ 'ami-6e1a0117',
MaxCount: 1,
MinCount: 1,
InstanceType: /* 8 cores, 16GB RAM */ 'c4.2xlarge',
SecurityGroups: [ 'hhvm-binary-package-builders' ],
IamInstanceProfile: { Arn: 'arn:aws:iam::223121549624:instance-profile/hhvm-binary-package-builder' },
KeyName: "hhvm-package-builders",
TagSpecifications: [
{
ResourceType: 'instance',
Tags: [{
Key: 'Name',
Value: 'hhvm-build-'+event.version+'-'+distro
}]
}
],
BlockDeviceMappings: [{
DeviceName: '/dev/sda1',
Ebs: {
DeleteOnTermination: true,
VolumeSize: 50 /*gb*/,
VolumeType: 'gp2'
}
}],
UserData: (new Buffer(user_data)).toString('base64')
};
const ec2 = new AWS.EC2();
return ec2.runInstances(params).promise();
}
function get_distros(event) {
return new promise((resolve, reject) => {
if (event.distros) {
resolve(event.distros);
return;
}
rp(get_distros_uri(event)).then(response => {
resolve(response.trim().split("\n"));
});
});
}
exports.handler = (event, context, callback) => {
promise.all([
get_distros(event),
rp(get_userdata_uri(event))
])
.then(values => {
const distros = values[0];
const user_data = values[1];
event.distros = distros;
return promise.all(
distros.map(distro => {
return make_binary_package(distro, event, user_data);
})
);
})
.then(values => {
event.instances = values.map(ec2_response => {
return ec2_response.Instances[0].InstanceId;
});
callback(null, event);
})
.done();
};
| JavaScript | 0 | @@ -2034,16 +2034,191 @@
k) =%3E %7B%0A
+ (new promise(%0A // splay over 10 seconds for when doing multiple release builds at the same time%0A resolve =%3E setTimeout(resolve, Math.random() * 10000)%0A ))%0A .then(%0A
promis
@@ -2225,16 +2225,18 @@
e.all(%5B%0A
+
get_
@@ -2251,24 +2251,26 @@
event),%0A
+
rp(get_userd
@@ -2287,17 +2287,23 @@
ent))%0A
+
-%5D
+ %5D)%0A
)%0A .the
|
a2d56e8876b42b05688fedd93b1853720731fcf3 | Automatically expand the current panel group on dashboard expansion | horizon/static/horizon/js/horizon.accordion_nav.js | horizon/static/horizon/js/horizon.accordion_nav.js | horizon.addInitFunction(function() {
var allPanelGroupBodies = $('.nav_accordion > dd > div > ul');
allPanelGroupBodies.each(function(index, value) {
var activePanels = $(this).find('li > a.active');
if(activePanels.length === 0) {
$(this).slideUp(0);
}
});
// mark the active panel group
var activePanel = $('.nav_accordion > dd > div > ul > li > a.active');
activePanel.closest('div').find('h4').addClass('active');
// dashboard click
$('.nav_accordion > dt').click(function() {
var myDashHeader = $(this);
var myDashWasActive = myDashHeader.hasClass("active");
// mark the active dashboard
var allDashboardHeaders = $('.nav_accordion > dt');
allDashboardHeaders.removeClass("active");
// collapse all dashboard contents
var allDashboardBodies = $('.nav_accordion > dd');
allDashboardBodies.slideUp();
// if the current dashboard was active, leave it collapsed
if(!myDashWasActive) {
myDashHeader.addClass("active");
// expand the active dashboard body
var myDashBody = myDashHeader.next();
myDashBody.slideDown();
var activeDashPanel = myDashBody.find("div > ul > li > a.active");
// if the active panel is not in the expanded dashboard
if (activeDashPanel.length === 0) {
// expand the active panel group
var activePanel = myDashBody.find("div:first > ul");
activePanel.slideDown();
activePanel.closest('div').find("h4").addClass("active");
// collapse the inactive panel groups
var nonActivePanels = myDashBody.find("div:not(:first) > ul");
nonActivePanels.slideUp();
}
// the expanded dashboard contains the active panel
else
{
// collapse the inactive panel groups
activeDashPanel.closest('div').find("h4").addClass("active");
allPanelGroupBodies.each(function(index, value) {
var activePanels = $(value).find('li > a.active');
if(activePanels.length === 0) {
$(this).slideUp();
}
});
}
}
return false;
});
// panel group click
$('.nav_accordion > dd > div > h4').click(function() {
var myPanelGroupHeader = $(this);
myPanelGroupWasActive = myPanelGroupHeader.hasClass("active");
// collapse all panel groups
var allPanelGroupHeaders = $('.nav_accordion > dd > div > h4');
allPanelGroupHeaders.removeClass("active");
allPanelGroupBodies.slideUp();
// expand the selected panel group if not already active
if(!myPanelGroupWasActive) {
myPanelGroupHeader.addClass("active");
myPanelGroupHeader.closest('div').find('ul').slideDown();
}
});
// panel selection
$('.nav_accordion > dd > div > ul > li > a').click(function() {
horizon.modals.modal_spinner(gettext("Loading"));
});
});
| JavaScript | 0.999937 | @@ -1844,24 +1844,75 @@
(%22active%22);%0A
+ activeDashPanel.closest('ul').slideDown();%0A
allP
|
c0fb0ef6ec706df71a9cc9cfc9993b5cf73d8585 | fix typo | lib/templates/index.js | lib/templates/index.js | var fs = require('fs')
var path = require('path')
var jade = require('jade')
var t = require('../translations').t
var log = require('debug')('democracyos:notifier:templates')
function _jade(opts, vars, callback) {
if ('string' === typeof opts) return _jade({ name: opts }, vars, callback)
if (!opts.name) return callback(new Error('Undefined template name'))
var name = opts.name
var lang = t.hasOwnProperty(opts.lang) ? opts.lang || 'en'
var filePath = path.join(__dirname, './lib/' + name + '.jade')
log('looking for mail template [' + name + '] in path: ' + filePath)
fs.readFile(filePath, { encoding: 'utf-8' }, function (err, template) {
if (err) return callback(err)
var mail = jade.compile(template)
t.lang(lang)
var content = replaceVars(mail({ t: t }), vars)
callback(null, content)
})
}
function replaceVars(template, vars) {
if (!vars) return template
var res = template
if (res) {
vars.forEach(function (v) {
res = res.replace(v.name, v.content)
})
}
return res
}
module.exports = {
jade: _jade
} | JavaScript | 0.999991 | @@ -439,10 +439,9 @@
ang
-%7C%7C
+:
'en
|
b3890e8a4a7d475c439c9d39685dfa0fd6a10f1a | Remove global variable leak | util/event.js | util/event.js | steal('can/util/can.js',function(can){
// event.js
// ---------
// _Basic event wrapper._
can.addEvent = function( event, fn ) {
var allEvents = this.__bindEvents || (this.__bindEvents = {}),
eventList = allEvents[event] || (allEvents[event] = []);
eventList.push({
handler: fn,
name: event
});
return this;
};
// can.listenTo works without knowing how bind works
// the API was heavily influenced by BackboneJS:
// http://backbonejs.org/
can.listenTo = function(other, event, handler){
var idedEvents = this.__listenToEvents;
if(!idedEvents){
idedEvents = this.__listenToEvents = {};
}
var otherId = can.cid(other);
var othersEvents = idedEvents[otherId];
if(!othersEvents){
othersEvents = idedEvents[otherId] = {
obj: other,
events: {}
};
}
var eventsEvents = othersEvents.events[event]
if(!eventsEvents){
eventsEvents = othersEvents.events[event] = []
}
eventsEvents.push(handler);
can.bind.call(other, event, handler);
}
can.stopListening = function(other, event, handler){
var idedEvents = this.__listenToEvents,
iterIdedEvents = idedEvents,
i = 0;
if(!idedEvents) {
return this;
}
if( other ) {
var othercid = can.cid(other);
(iterIdedEvents = {})[othercid] = idedEvents[othercid];
// you might be trying to listen to something that is not there
if(!idedEvents[othercid]){
return this;
}
}
for(var cid in iterIdedEvents) {
var othersEvents = iterIdedEvents[cid],
eventsEvents;
other = idedEvents[cid].obj;
if( ! event ) {
eventsEvents = othersEvents.events;
} else {
(eventsEvents = {})[event] = othersEvents.events[event]
}
for(var eventName in eventsEvents) {
var handlers = eventsEvents[eventName] || [];
i = 0;
while(i < handlers.length){
if( (handler && handler === handlers[i]) || (! handler ) ) {
can.unbind.call(other, eventName, handlers[i])
handlers.splice(i, 1);
} else {
i++;
}
}
// no more handlers?
if( !handlers.length ){
delete othersEvents.events[eventName]
}
}
if( can.isEmptyObject(othersEvents.events )){
delete idedEvents[cid]
}
}
return this;
}
can.removeEvent = function(event, fn){
if(!this.__bindEvents){
return this;
}
var events = this.__bindEvents[event] || [],
i =0,
ev,
isFunction = typeof fn == 'function';
while(i < events.length){
ev = events[i]
if( (isFunction && ev.handler === fn) || (!isFunction && ev.cid === fn ) ) {
events.splice(i, 1);
} else {
i++;
}
}
return this;
};
can.dispatch = function(event, args){
if(!this.__bindEvents){
return;
}
if(typeof event == "string"){
event = {type: event}
}
var eventName = event.type,
handlers = (this.__bindEvents[eventName] || []).slice(0),
args = [event].concat(args||[]);
for(var i =0, len = handlers.length; i < len; i++) {
ev = handlers[i];
ev.handler.apply(this, args);
};
}
return can;
})
| JavaScript | 0.000002 | @@ -2776,16 +2776,22 @@
rgs%7C%7C%5B%5D)
+,%0A%09%09ev
;%0A%09%0A%09for
@@ -2895,17 +2895,16 @@
rgs);%0A%09%7D
-;
%0A%7D%0A%0Aretu
|
8e9ea1b8c13d04d30bb7ac3c09c06f79030e08cb | Remove checksum warning until we can provide a way of fixing (#757) | packages/@sanity/core/src/actions/config/reinitializePluginConfigs.js | packages/@sanity/core/src/actions/config/reinitializePluginConfigs.js | import path from 'path'
import pathExists from 'path-exists'
import fse from 'fs-extra'
import resolveTree from '@sanity/resolver'
import normalizePluginName from '../../util/normalizePluginName'
import generateConfigChecksum from '../../util/generateConfigChecksum'
import {getChecksums, setChecksums, localConfigExists} from '../../util/pluginChecksumManifest'
async function reinitializePluginConfigs(options, flags = {}) {
const {workDir, output} = options
const localChecksums = await getChecksums(workDir)
const allPlugins = await resolveTree({basePath: workDir})
const pluginsWithDistConfig = (await Promise.all(allPlugins.map(pluginHasDistConfig))).filter(
Boolean
)
const distChecksums = await Promise.all(pluginsWithDistConfig.map(getPluginConfigChecksum))
const withLocalConfigs = await Promise.all(distChecksums.map(hasLocalConfig))
const missingConfigs = await Promise.all(withLocalConfigs.map(createMissingConfig))
const configPlugins = missingConfigs.map(warnOnDifferingChecksum)
return missingConfigs.length > 0 ? saveNewChecksums(configPlugins) : Promise.resolve()
function hasLocalConfig(plugin) {
return localConfigExists(workDir, plugin.name).then(configDeployed =>
Object.assign({}, plugin, {configDeployed})
)
}
function createMissingConfig(plugin) {
if (plugin.configDeployed) {
return plugin
}
const srcPath = path.join(plugin.path, 'config.dist.json')
const dstPath = path.join(workDir, 'config', `${normalizePluginName(plugin.name)}.json`)
const prtPath = path.relative(workDir, dstPath)
if (!flags.quiet) {
output.print(
`Plugin "${plugin.name}" is missing local configuration file, creating ${prtPath}`
)
}
return fse.copy(srcPath, dstPath).then(() => plugin)
}
function warnOnDifferingChecksum(plugin) {
if (flags.quiet) {
return plugin
}
const local = localChecksums[plugin.name]
if (typeof local !== 'undefined' && local !== plugin.configChecksum) {
const name = normalizePluginName(plugin.name)
output.print(
`[WARN] Default configuration file for plugin "${name}" has changed since local copy was created`
)
}
return plugin
}
function saveNewChecksums(plugins) {
const sums = Object.assign({}, localChecksums)
plugins.forEach(plugin => {
if (!sums[plugin.name]) {
sums[plugin.name] = plugin.configChecksum
}
})
return setChecksums(workDir, sums)
}
}
export async function tryInitializePluginConfigs(options, flags = {}) {
try {
await reinitializePluginConfigs(options, flags)
} catch (err) {
if (err.code !== 'PluginNotFound') {
throw err
}
const manifest = await fse
.readJson(path.join(options.workDir, 'package.json'))
.catch(() => ({}))
const dependencies = Object.keys(
Object.assign({}, manifest.dependencies, manifest.devDependencies)
)
const depName = err.plugin[0] === '@' ? err.plugin : `sanity-plugin-${err.plugin}`
if (dependencies.includes(depName)) {
err.message = `${err.message}\n\nTry running "sanity install"?`
} else {
err.message = `${err.message}\n\nTry running "sanity install ${depName}"?`
}
throw err
}
}
export default reinitializePluginConfigs
function getPluginConfigPath(plugin) {
return path.join(plugin.path, 'config.dist.json')
}
function pluginHasDistConfig(plugin) {
const configPath = getPluginConfigPath(plugin)
return pathExists(configPath).then(exists => exists && plugin)
}
function getPluginConfigChecksum(plugin) {
return generateConfigChecksum(getPluginConfigPath(plugin)).then(configChecksum =>
Object.assign({}, plugin, {configChecksum})
)
}
| JavaScript | 0 | @@ -1840,24 +1840,251 @@
lugin) %7B%0A
+ return plugin%0A%0A // Disabled for now, until we can provide a way to fix.%0A // NOTE: A similar checksum diff check is also done when running the install command%0A // See https://github.com/sanity-io/sanity/pull/298%0A //
if (flags.q
@@ -2090,24 +2090,27 @@
quiet) %7B%0A
+ //
return pl
@@ -2114,30 +2114,42 @@
plugin%0A
-%7D%0A
+// %7D%0A //
%0A
+ //
const local
@@ -2178,24 +2178,27 @@
in.name%5D%0A
+ //
if (typeof
@@ -2260,16 +2260,19 @@
m) %7B%0A
+ //
const
@@ -2311,24 +2311,27 @@
in.name)%0A
+ //
output.pr
@@ -2339,20 +2339,23 @@
nt(%0A
+//
+
%60%5BWARN%5D
@@ -2443,24 +2443,27 @@
created%60%0A
+ //
)%0A %7D%0A%0A
@@ -2451,38 +2451,50 @@
%0A // )%0A
-%7D%0A
+// %7D%0A //
%0A
+ //
return plugin%0A
|
dd70ab33889a64630a271c92ded7f29ef9e773dc | Update Recyclable_Base.js | CNN/util/Recyclable/Recyclable_Base.js | CNN/util/Recyclable/Recyclable_Base.js | export { Base, Root };
import * as Pool from "../Pool.js";
/**
* The base class representing a object could be recycled (i.e. disposed without release its main object memory for re-using in the
* future).
*
* Every sub-class of this Recyclable.Base MUST define a static propery named Pool which is usually an instance of Pool.Base:
* <pre>
* class SomeClass extends Recyclable.Base {
*
* static Pool = new XxxPool();
*
* }
* </pre>
*
* Or,
* <pre>
* class SomeClass extends Recyclable.Base {
*
* ...
*
* }
*
* SomeClass.Pool = new XxxPool();
*
* </pre>
*
*
*/
let Base = ( ParentClass = Object ) => class Base extends ParentClass {
/**
* This method will do the following in sequence:
* - call this.disposeResources() (if exists)
* - call this.constructor.Pool.recycle()
*
* Sub-class should NEVER override this method (so NEVER call super.disposeResources_and_recycleToPool()).
*
*
* After calling this method, this object should be viewed as disposed and should not be operated again.
*/
disposeResources_and_recycleToPool() {
if ( this.disposeResources instanceof Function ) { // If this object needs disposing, do it before being recyled.
this.disposeResources();
}
this.constructor.Pool.recycle( this );
}
}
/**
* Almost the same as Recyclable.Base class except its parent class is fixed to Object. In other words, caller can not specify the
* parent class of Recyclable.Root (so it is named "Root" which can not have parent class).
*/
class Root extends Base {
}
| JavaScript | 0.000001 | @@ -1553,14 +1553,16 @@
nds Base
+()
%7B%0A%7D%0A%0A
|
9c80b9c99a02af94d4dbec76a08e64e55d9a8fc3 | fix YERROR in notebook index.js | applications/desktop/src/main/index.js | applications/desktop/src/main/index.js | import { Menu, dialog, app, ipcMain as ipc, BrowserWindow } from "electron";
import { resolve, join } from "path";
import { existsSync } from "fs";
import { Subscriber } from "rxjs/Subscriber";
import { fromEvent } from "rxjs/observable/fromEvent";
import { forkJoin } from "rxjs/observable/forkJoin";
import { zip } from "rxjs/observable/zip";
import {
mergeMap,
takeUntil,
skipUntil,
buffer,
catchError,
first
} from "rxjs/operators";
import {
mkdirpObservable,
readFileObservable,
writeFileObservable
} from "fs-observable";
import { launch, launchNewNotebook } from "./launch";
import { initAutoUpdater } from "./auto-updater.js";
import { loadFullMenu } from "./menu";
import prepareEnv from "./prepare-env";
import initializeKernelSpecs from "./kernel-specs";
import { setKernelSpecs } from "./actions";
import configureStore from "./store";
const store = configureStore();
// HACK: The main process store should not be stored in a global.
global.store = store;
const log = require("electron-log");
const kernelspecs = require("kernelspecs");
const jupyterPaths = require("jupyter-paths");
const path = require("path");
const yargs = require("yargs/yargs");
const argv = yargs()
.version(() => require("./../../package.json").version)
.usage("Usage: nteract <notebooks> [options]")
.example("nteract notebook1.ipynb notebook2.ipynb", "Open notebooks")
.example("nteract --kernel javascript", "Launch a kernel")
.describe("kernel", "Launch a kernel")
.default("kernel", "python3")
.alias("k", "kernel")
.alias("v", "version")
.alias("h", "help")
.describe("verbose", "Display debug information")
.help("help")
.parse(process.argv.slice(1));
log.info("args", argv);
const notebooks = argv._.filter(x => /(.ipynb)$/.test(x)).filter(x =>
existsSync(resolve(x))
);
ipc.on("new-kernel", (event, k) => {
launchNewNotebook(k);
});
ipc.on("open-notebook", (event, filename) => {
launch(resolve(filename));
});
app.on("ready", initAutoUpdater);
const electronReady$ = fromEvent(app, "ready");
const windowReady$ = fromEvent(ipc, "react-ready");
const fullAppReady$ = zip(electronReady$, prepareEnv).pipe(first());
const jupyterConfigDir = path.join(app.getPath("home"), ".jupyter");
const nteractConfigFilename = path.join(jupyterConfigDir, "nteract.json");
const prepJupyterObservable = prepareEnv.pipe(
mergeMap(() =>
// Create all the directories we need in parallel
forkJoin(
// Ensure the runtime Dir is setup for kernels
mkdirpObservable(jupyterPaths.runtimeDir()),
// Ensure the config directory is all set up
mkdirpObservable(jupyterConfigDir)
)
),
// Set up our configuration file
mergeMap(() =>
readFileObservable(nteractConfigFilename).pipe(
catchError(err => {
if (err.code === "ENOENT") {
return writeFileObservable(
nteractConfigFilename,
JSON.stringify({
theme: "light"
})
);
}
throw err;
})
)
)
);
const kernelSpecsPromise = prepJupyterObservable
.toPromise()
.then(() => kernelspecs.findAll())
.then(specs => initializeKernelSpecs(specs));
/**
* Creates an Rx.Subscriber that will create a splash page onNext and close the
* splash page onComplete.
* @return {Rx.Subscriber} Splash Window subscriber
*/
export function createSplashSubscriber() {
let win;
return Subscriber.create(
() => {
win = new BrowserWindow({
width: 565,
height: 233,
useContentSize: true,
title: "loading",
frame: false,
show: false
});
const index = join(__dirname, "..", "static", "splash.html");
win.loadURL(`file://${index}`);
win.once("ready-to-show", () => {
win.show();
});
},
null,
() => {
// Close the splash page when completed
if (win) {
win.close();
}
}
);
}
const appAndKernelSpecsReady = zip(
fullAppReady$,
windowReady$,
kernelSpecsPromise
);
electronReady$
.pipe(takeUntil(appAndKernelSpecsReady))
.subscribe(createSplashSubscriber());
function closeAppOnNonDarwin() {
// On macOS, we want to keep the app and menu bar active
if (process.platform !== "darwin") {
app.quit();
}
}
const windowAllClosed = fromEvent(app, "window-all-closed");
windowAllClosed
.pipe(skipUntil(appAndKernelSpecsReady))
.subscribe(closeAppOnNonDarwin);
const openFile$ = fromEvent(app, "open-file", (event, filename) => ({
event,
filename
}));
function openFileFromEvent({ event, filename }) {
event.preventDefault();
launch(resolve(filename));
}
// Since we can't launch until app is ready
// and macOS will send the open-file events early,
// buffer those that come early.
openFile$.pipe(buffer(fullAppReady$), first()).subscribe(buffer => {
// Form an array of open-file events from before app-ready // Should only be the first
// Now we can choose whether to open the default notebook
// based on if arguments went through argv or through open-file events
if (notebooks.length <= 0 && buffer.length <= 0) {
log.info("launching an empty notebook by default");
kernelSpecsPromise.then(specs => {
let kernel;
if (argv.kernel in specs) {
kernel = argv.kernel;
} else if ("python2" in specs) {
kernel = "python2";
} else {
const specList = Object.keys(specs);
specList.sort();
kernel = specList[0];
}
launchNewNotebook(specs[kernel]);
});
} else {
notebooks.forEach(f => {
try {
launch(resolve(f));
} catch (e) {
log.error(e);
console.error(e);
}
});
}
buffer.forEach(openFileFromEvent);
});
// All open file events after app is ready
openFile$.pipe(skipUntil(fullAppReady$)).subscribe(openFileFromEvent);
fullAppReady$.subscribe(() => {
kernelSpecsPromise
.then(kernelSpecs => {
if (Object.keys(kernelSpecs).length !== 0) {
store.dispatch(setKernelSpecs(kernelSpecs));
const menu = loadFullMenu();
Menu.setApplicationMenu(menu);
} else {
dialog.showMessageBox(
{
type: "warning",
title: "No Kernels Installed",
buttons: [],
message: "No kernels are installed on your system.",
detail:
"No kernels are installed on your system so you will not be " +
"able to execute code cells in any language. You can read about " +
"installing kernels at " +
"https://ipython.readthedocs.io/en/latest/install/kernel_install.html"
},
index => {
if (index === 0) {
app.quit();
}
}
);
}
})
.catch(err => {
dialog.showMessageBox(
{
type: "error",
title: "No Kernels Installed",
buttons: [],
message: "No kernels are installed on your system.",
detail:
"No kernels are installed on your system so you will not be " +
"able to execute code cells in any language. You can read about " +
"installing kernels at " +
"https://ipython.readthedocs.io/en/latest/install/kernel_install.html" +
`\nFull error: ${err.message}`
},
index => {
if (index === 0) {
app.quit();
}
}
);
});
});
| JavaScript | 0 | @@ -1217,16 +1217,17 @@
ersion((
+(
) =%3E req
@@ -1263,16 +1263,19 @@
version)
+())
%0A .usag
|
6f50c0f92f91ca8061b14dc9f212da18d500f783 | 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: '/itemform',
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 | @@ -650,16 +650,27 @@
%09state('
+item.forms.
wizard',
@@ -686,16 +686,17 @@
: '/item
+-
form',%0A%09
|
ac887125a4d220faf7e6d03f8a1fddb6f001fdc0 | debug flag for internal use | lib/AttributeValue.js | lib/AttributeValue.js | var isArray = require('util').isArray;
var errs = require('./errs');
function test(arr, fn) {
for (var i = 0; i < arr.length; i++) {
if (!fn(arr[i]))
return false;
}
return true;
}
function isnumber(el) {
return typeof el === 'number' || el instanceof Number;
}
function isstring(el) {
return typeof el === 'string' || el instanceof String;
}
function isbinary(el) {
return false;
}
function getType(val) {
if (isArray(val)) {
var arr = val;
if (test(arr, isnumber))
return 'NS';
if (test(arr, isstring))
return 'SS';
if (test(arr, isbinary))
return 'BS';
return 'L';
}
if (isstring(val))
return 'S';
if (isnumber(val))
return 'N';
if (isbinary(val))
return 'B';
if (val === null)
return 'NULL';
if (typeof val === 'boolean')
return 'BOOL';
if (typeof val === 'object') {
return 'M';
}
}
function eachToString(arr) {
return arr.map(function(v) {
return v.toString();
});
}
/**
* Wrap a single value into DynamoDB's AttributeValue.
* @param {String|Number|Array} val The value to wrap.
* @return {Object} DynamoDB AttributeValue.
*/
function wrap1(val) {
// Note: _String and _StringS are not DynamoDb types. They indicate String
// objects for which toString needs to be called.
switch(getType(val)) {
case 'B': return {'B': val};
case 'BS': return {'BS': val};
case 'N': return {'N': val.toString()};
case 'NS': return {'NS': eachToString(val)};
case 'S': return {'S': val.toString()};
case 'SS': return {'SS': eachToString(val)};
case 'BOOL': return {'BOOL': val ? true: false};
case 'L': return {L: val.map(wrap1)};
case 'M': return {'M': wrap(val)};
case 'NULL': return {'NULL': true};
default: return;
}
}
/**
* Wrap object properties into DynamoDB's AttributeValue data type.
* @param {Object} obj The object to wrap.
* @return {Object} A DynamoDb AttributeValue.
*/
function wrap(obj) {
var result = {};
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
var wrapped = wrap1(obj[key]);
if (typeof wrapped !== 'undefined')
result[key] = wrapped;
}
}
return result;
}
var unwrapFns = {
'B': undefined,
'BS': undefined,
'N': function (o) { return Number(o); },
'NS':function (arr) { return arr.map(function(o) {return Number(o);}); },
'S': undefined,
'SS': undefined,
'BOOL': undefined,
'L': function(val) { return val.map(unwrap1); },
'M': function (val) { return unwrap(val); },
'NULL': function() { return null; }
};
/**
* Unwrap a single DynamoDB's AttributeValue to a value of the appropriate
* javascript type.
* @param {Object} attributeValue The DynamoDB AttributeValue.
* @return {String|Number|Array} The javascript value.
*/
function unwrap1(dynamoData) {
var keys = Object.keys(dynamoData);
if (keys.length !== 1)
throw new Error('Unexpected DynamoDB AttributeValue');
var typeStr = keys[0];
if (!unwrapFns.hasOwnProperty(typeStr))
throw errs.NoDatatype;
var val = dynamoData[typeStr];
return unwrapFns[typeStr] ? unwrapFns[typeStr](val) : val;
}
/**
* Unwrap DynamoDB AttributeValues to values of the appropriate types.
* @param {Object} attributeValue The DynamoDb AttributeValue to unwrap.
* @return {Object} Unwrapped object with properties.
*/
function unwrap(attrVal) {
var result = {};
for (var key in attrVal) {
if(attrVal.hasOwnProperty(key)) {
var value = attrVal[key];
if (value !== null && typeof value !== 'undefined')
result[key] = unwrap1(attrVal[key]);
}
}
return result;
}
module.exports = {
wrap: wrap,
unwrap: unwrap,
wrap1: wrap1,
unwrap1: unwrap1
};
| JavaScript | 0 | @@ -63,16 +63,36 @@
rrs');%0A%0A
+var DEBUG = false;%0A%0A
function
@@ -3626,16 +3626,552 @@
ult;%0A%7D%0A%0A
+function printData(input, result, title) %7B%0A if (DEBUG) %7B%0A console.log(title + ' input:');%0A console.log(JSON.stringify(input, undefined, 2));%0A console.log(title + ' result:');%0A console.log(JSON.stringify(result, undefined, 2));%0A %7D%0A return result;%0A%7D%0A%0Afunction wrapDebug(obj) %7B%0A var wrapped = wrap(obj);%0A if (DEBUG)%0A printData(obj, wrapped, 'wrap');%0A return wrapped;%0A%7D%0A%0Afunction unwrapDebug(attrVal) %7B%0A var unwrapped = unwrap(attrVal);%0A if (DEBUG)%0A printData(attrVal, unwrapped, 'unwrap');%0A return unwrapped;%0A%7D%0A%0A
module.e
@@ -4189,24 +4189,29 @@
wrap: wrap
+Debug
,%0A unwrap:
@@ -4216,16 +4216,21 @@
: unwrap
+Debug
,%0A wrap
|
9808a6114f1b5d7580e52c6eebd35a75a9f5be5f | fix seek and update from master | modules/KalturaSupport/components/video360.js | modules/KalturaSupport/components/video360.js | (function (mw, $, THREE) {
"use strict";
mw.PluginManager.add('video360', mw.KBasePlugin.extend({
defaultConfig: {
manualControl:false
},
setup: function() {
mw.setConfig("disableOnScreenClick",true);
var renderer;
var _this = this;
this.bind("playing play pause seek" , function(){
$(_this.getPlayer().getPlayerElement() ).hide();
});
this.bind("updateLayout", function(){
renderer.setSize(window.innerWidth, window.innerHeight);
});
this.bind("playerReady sourcesReplaced" , function(){
_this.getPlayer().layoutBuilder.removePlayerClickBindings();
var player = _this.getPlayer();
var video = player.getPlayerElement();
var container = player.getVideoDisplay();
var manualControl = _this.getConfig("manualControl");
var longitude = 0;
var latitude = 0;
var savedX;
var savedY;
var savedLongitude;
var savedLatitude;
var texture;
// setting up the renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.append(renderer.domElement);
video.setAttribute('crossorigin', 'anonymous');
// creating a new scene
var scene = new THREE.Scene();
// adding a camera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.target = new THREE.Vector3(0, 0, 0);
// creation of a big sphere geometry
var sphere = new THREE.SphereGeometry(100, 100, 40);
sphere.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
texture = new THREE.Texture(video);
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
// creation of the sphere material
var sphereMaterial = new THREE.MeshBasicMaterial();
sphereMaterial.map = texture;
// geometry + material = mesh (actual object)
var sphereMesh = new THREE.Mesh(sphere, sphereMaterial);
scene.add(sphereMesh);
function render(){
if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
if ( texture ) texture.needsUpdate = true;
}
requestAnimationFrame(render);
if(!manualControl){
longitude += 0.1;
}
// limiting latitude from -85 to 85 (cannot point to the sky or under your feet)
latitude = Math.max(-85, Math.min(85, latitude));
// moving the camera according to current latitude (vertical movement) and longitude (horizontal movement)
camera.target.x = 500 * Math.sin(THREE.Math.degToRad(90 - latitude)) * Math.cos(THREE.Math.degToRad(longitude));
camera.target.y = 500 * Math.cos(THREE.Math.degToRad(90 - latitude));
camera.target.z = 500 * Math.sin(THREE.Math.degToRad(90 - latitude)) * Math.sin(THREE.Math.degToRad(longitude));
camera.lookAt(camera.target);
// calling again render function
renderer.render(scene, camera);
}
// when the mouse is pressed, we switch to manual control and save current coordinates
function onDocumentMouseDown(event){
event.preventDefault();
manualControl = true;
savedX = event.clientX;
savedY = event.clientY;
savedLongitude = longitude;
savedLatitude = latitude;
}
// when the mouse moves, if in manual contro we adjust coordinates
function onDocumentMouseMove(event){
if(manualControl){
longitude = (savedX - event.clientX) * 0.1 + savedLongitude;
latitude = (event.clientY - savedY) * 0.1 + savedLatitude;
}
}
// when the mouse is released, we turn manual control off
function onDocumentMouseUp(event){
manualControl = false;
}
// listeners
document.addEventListener("mousedown", onDocumentMouseDown, false);
document.addEventListener("mousemove", onDocumentMouseMove, false);
document.addEventListener("mouseup", onDocumentMouseUp, false);
render();
});
}
}));
})(window.mw, window.jQuery, THREE); | JavaScript | 0 | @@ -285,16 +285,23 @@
use seek
+ seeked
%22 , func
@@ -915,32 +915,97 @@
%09%09%09var texture;%0A
+%09%09%09%09$(_this.getPlayer().getPlayerElement() ).css('z-index','-1');
%0A%09%09%09%09// setting
|
00375133fc147554e5de7f7e4b05e089de667c1a | Use direct link to editor scene in tutorials | lib/tutorials/index.js | lib/tutorials/index.js | var handlebars = require("handlebars");
var request = require("request");
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
var tags;
var generateSlug = function (title) {
var slug = '';
var allowed = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -';
for (var i = 0; i < title.length; i++) {
var ch = title[i];
if (allowed.indexOf(ch) >= 0) {
slug += ch;
}
}
slug = slug.toLowerCase().replaceAll(' ', '-');
return slug;
};
// Get tagged projects from the public API
var getTaggedProjects = function (done) {
var tagged = {};
var skip=0;
var get = function (cb) {
request('http://playcanvas.com/api/apps?limit=32&tags=tutorial&skip='+skip, function (err, response, body) {
if (err) {
console.error(err);
return;
}
var samples = JSON.parse(body).result;
for (var i = 0; i < samples.length; i++) {
var appUrl = samples[i].url;
var editorUrl = 'https://playcanvas.com/editor/project/'+samples[i].project_id;
var projectUrl = 'https://playcanvas.com/project/'+samples[i].project_id+'/overview';
var thumbUrl = samples[i].thumbnails.m;
var name = samples[i].name;
var tags = samples[i].tags || [];
var slug = generateSlug(name);
// var path = 'en/tutorials/'+slug;
var url = '/tutorials/'+slug;
var path = 'en'+url;
tagged[path] = {
title: name,
url: url,
path: path,
tags: tags,
slug: slug,
appUrl: appUrl,
editorUrl: editorUrl,
projectUrl: projectUrl,
thumbUrl: thumbUrl
};
}
if (samples.length === 32) {
skip+=32;
get(function () {
cb();
});
} else {
cb();
}
});
};
get(function () {
done(tagged);
});
};
var getTags = function (done) {
request('https://playcanvas.com/api/tags', function (err, response, body) {
var json = JSON.parse(body).result;
var tags = json.filter(function (tag) {
if (['skype', 'tutorial', 'challenge'].indexOf(tag.id) >= 0) return false;
return tag.kind === 'app'
});
done(tags);
});
}
module.exports = function makePlugin(dir) {
// compile the template used to generate pages for tagged projects
handlebars.registerPartial("template-tagged-project", fs.readFileSync("templates/partials/tutorial-tagged-project.tmpl.html", "utf-8"));
taggedProjectTemplate = handlebars.compile(handlebars.partials["template-tagged-project"]);
return function (opts) {
return function (files, metalsmith, done) {
var langs = ['en', 'ru', 'ja', 'zh'];
var index = {}; // index object of tutorials
var tags = [];
var tagSet = {};
for (var i = 0; i < langs.length; i++) {
var lang = langs[i];
index[lang] = {};
// get all tutorials and insert into index
for (var filepath in files) {
if (filepath.indexOf('.DS_Store') >= 0) continue;
var file = files[filepath];
if (filepath.startsWith(lang+'/'+dir)) {
if (filepath.endsWith('tutorials/index.html')) continue; // skip main index page
// separate tags
var tags = file.tags || '';
file.tags = tags.split(',').filter(function (tag) {return !!tag;}).map(function (tag) {return tag.trim()}) || [];
// file.tags.forEach(function (tag) {tagSet[tag]=true;});
index[lang][filepath] = {
title: file.title,
url: filepath.replace(lang, '').replace('index.html',''),
tags: file.tags,
thumbUrl: file.thumb
}
}
}
}
getTags(function (tags) {
getTaggedProjects(function (tagged) {
// add tagged projects into main index
for (var key in tagged) {
for (var i = 0; i < langs.length; i++) {
var lang = langs[i];
// insert tagged project into index
index[lang][key] = tagged[key];
// create a new output file for each tagged project
var file = {
title: tagged[key].title,
template: 'tutorial-page.tmpl.html',
tags: tagged[key].tags,
mode: '0644',
path: lang + tagged[key].url,
locale: lang,
en: true,
contents: new Buffer(taggedProjectTemplate(tagged[key]))
}
// add tags
// file.tags.forEach(function (tag) {tagSet[tag]=true;});
files[file.path+'/index.html'] = file;
}
}
var context = {
pages: {},
tags: tags
};
for (var lang in index) {
context.pages[lang] = [];
for (var key in index[lang]) {
context.pages[lang].push(index[lang][key]);
}
context.pages[lang].sort(function (a,b) {
if (a.title && b.title) {
var _a = a.title.toLowerCase();
var _b = b.title.toLowerCase();
if (_a < _b) return -1;
if (_a > _b) return 1;
}
return 0;
});
}
// tutorial main page filters
// render a new template using the template's template(!) and the content from the file tree
var contentsTemplatePartialName = 'template-tutorial-contents';
handlebars.registerPartial(contentsTemplatePartialName, fs.readFileSync("templates/partials/tutorial-contents.tmpl.html", "utf-8"));
var contentsTemplate = handlebars.compile(handlebars.partials[contentsTemplatePartialName])
var contents = contentsTemplate(context);
// registry the generated contents template as the partial used in the tutorial pages
handlebars.registerPartial('tutorials-navigation', contents);
// render a new template used to template the tag selection on a tutorial page
var contentsLinksTemplatePartialName = 'template-tutorial-contents-links';
handlebars.registerPartial(contentsLinksTemplatePartialName, fs.readFileSync("templates/partials/tutorial-contents-links.tmpl.html", "utf-8"));
var contentsTemplate = handlebars.compile(handlebars.partials[contentsLinksTemplatePartialName])
var contents = contentsTemplate(context);
handlebars.registerPartial('tutorials-navigation-links', contents);
// tutorial navigation
// render a new template using the template's template(!) and the content from the file tree
var listTemplatePartialName = 'template-tutorial-list';
handlebars.registerPartial(listTemplatePartialName, fs.readFileSync("templates/partials/tutorial-list.tmpl.html", "utf-8"));
var listTemplate = handlebars.compile(handlebars.partials[listTemplatePartialName])
var contents = listTemplate(context);
// generate pages for tagged projects
// registry the generated list template as the partial used in the tutorial pages
handlebars.registerPartial('tutorials-list', contents);;
done();
});
});
};
};
};
| JavaScript | 0 | @@ -1892,23 +1892,21 @@
/editor/
-project
+scene
/'+sampl
@@ -1913,24 +1913,26 @@
es%5Bi%5D.pr
-oject_id
+imary_pack
;%0A
|
d3c8a51c5e7d1b4324b0f43076f5d9c66aeac395 | Add uncaughtException handler | src/server/node/server.js | src/server/node/server.js | /*!
* OS.js - JavaScript Cloud/Web Desktop Platform
*
* Copyright (c) 2011-2016, Anders Evenrud <andersevenrud@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Anders Evenrud <andersevenrud@gmail.com>
* @licence Simplified BSD License
*/
(function(_path, _server) {
'use strict';
var DIST = (process && process.argv.length > 2) ? process.argv[2] : 'dist';
var ROOT = _path.join(__dirname, '/../../../');
var PORT = null;
var NOLOG = false;
(function() {
var i, arg;
for ( i = 0; i < process.argv.length; i++ ) {
arg = process.argv[i];
if ( ['-nl', '--no-log'].indexOf(arg) >= 0 ) {
NOLOG = true;
} else if ( ['-p', '--port'].indexOf(arg) >= 0 ) {
i++;
PORT = process.argv[i];
} else if ( ['-r', '--root'].indexOf(arg) >= 0 ) {
i++;
ROOT = process.argv[i];
}
}
})();
if ( DIST === 'x11' ) {
DIST = 'dist';
ROOT = _path.dirname(__dirname);
} else {
if ( (process.argv[1] || '').match(/(mocha|grunt)$/) ) {
DIST = 'dist-dev';
}
}
/////////////////////////////////////////////////////////////////////////////
// MAIN
/////////////////////////////////////////////////////////////////////////////
process.chdir(ROOT);
process.on('exit', function() {
_server.close();
});
_server.listen({
port: PORT,
dirname: __dirname,
root: ROOT,
dist: DIST,
logging: !NOLOG,
nw: false
});
})(require('path'), require('./http.js'));
| JavaScript | 0.000001 | @@ -2613,16 +2613,135 @@
%0A %7D);%0A%0A
+ process.on('uncaughtException', function (error) %7B%0A console.log('UNCAUGHT EXCEPTION', error, error.stack);%0A %7D);%0A%0A
_serve
|
dfe4129726474be7d61520a4e17e277d8c96b188 | move menu content to the left | bitrepository-webclient/src/main/webapp/menu.js | bitrepository-webclient/src/main/webapp/menu.js |
var pages = [{page : "alarm-service.jsp", title : "Alarm"},
{page : "integrity-service.jsp", title : "Integrity"},
{page : "audit-trail-service.jsp", title : "Audit trail"},
{page : "status-service.jsp", title : "Status"}];
function makeMenu(page, element) {
var menuHtml = "";
menuHtml += "<div class=\"navbar navbar-inverse navbar-static-top\">";
menuHtml += "<div class=\"navbar-inner\">";
menuHtml += "<div class=\"container\">";
menuHtml += "<a class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\">";
menuHtml += "<span class=\"icon-bar\"></span>";
menuHtml += "<span class=\"icon-bar\"></span>";
menuHtml += "<span class=\"icon-bar\"></span>";
menuHtml += "</a>";
menuHtml += "<a class=\"brand\" href=\"bitrepository-frontpage.jsp\">Bitrepository</a>";
menuHtml += "<div class=\"nav-collapse collapse\">";
menuHtml += "<ul class=\"nav\">";
for(var i=0; i<pages.length; i++) {
linkClass="";
if(pages[i].page == page) {
linkClass="class=\"active\"";
}
menuHtml += "<li " + linkClass +"><a href=\"" + pages[i].page + "\">"+ pages[i].title + "</a></li>";
}
menuHtml += "</ul>";
menuHtml += "</div><!--/.nav-collapse -->";
menuHtml += "</div>";
menuHtml += "</div>";
menuHtml += "</div>";
$(element).html(menuHtml);
}
| JavaScript | 0 | @@ -545,16 +545,22 @@
ontainer
+-fluid
%5C%22%3E%22;%0A
|
cbb90a3520d469bcff1622b9a2ae1817903a5001 | remove logs | plugins/typescript.js | plugins/typescript.js | "use strict";
const ts = require('typescript');
module.exports = function () {
const host = {
getScriptVersion: () => +new Date,
getCompilationSettings: () => ({}),
getCurrentDirectory: () => '',
getScriptSnapshot: (path) => {
console.log('111getScriptSnapshot', cache['$' + path]);
return ts.ScriptSnapshot.fromString(cache['$' + path] || '');
},
};
const cache = {
};
const langService = ts.createLanguageService(host);
return function (f, enc, cb) {
const code = f.contents.toString();
const res = {path: f.path, contents: code};
const lineLengths = code.split('\n').map(line => line.length);
function getLoc(span) {
let pos = span.start;
const result = {};
let chars = 0;
for (var i = 0; i < lineLengths.length; i++) {
const charsAtlineStart = chars;
chars += lineLengths[i] + 1;
if (chars > pos) {
if (!result.start) {
result.start = {
line: i + 1,
column: pos - charsAtlineStart,
};
pos += span.length;
}
else {
result.end = {
line: i + 1,
column: pos - charsAtlineStart,
};
return result;
}
}
}
}
cache['$' + f.path] = f.contents.toString();
const navigationItems = langService.getNavigationBarItems(f.path);
console.log("BAR ITEMS", navigationItems);
const items = navigationItems.map(item => {
let res = {type: item.kind, name: item.text};
res.loc = getLoc(item.spans[0]);
if (item.kind == 'class') {
res.functions = item.childItems.filter(
item => item.kind == 'method'
).map(item =>
({type: 'function', name: item.text, loc: getLoc(item.spans[0])})
);
}
return res;
})
res.metadata = items;
cb(null, res);
}
}
| JavaScript | 0.000001 | @@ -263,76 +263,8 @@
%3E %7B%0A
- console.log('111getScriptSnapshot', cache%5B'$' + path%5D);%0A
@@ -1676,59 +1676,8 @@
h);%0A
- console.log(%22BAR ITEMS%22, navigationItems);%0A
%0A%0A
|
d54b3df3d54bd7bcee22d5d45a296745fcf68b5d | Update exercise.js | derekmma/exercise.js | derekmma/exercise.js | var input = require('./digits.js');
var exercise = {};
exercise.one = function(){
//-------------------
//---- Your Code ----
//-------------------
return 'Error: 1st function not implemented 1028';
};
exercise.two = function(data){
//-------------------
//---- Your Code ----
//-------------------
return 'Error: 2nd function not implemented';
};
exercise.three = function(data){
//-------------------
//---- Your Code ----
//-------------------
return 'Error: 3rd function not implemented';
};
exercise.four = function(data){
//-------------------
//---- Your Code ----
//-------------------
return 'Error: 4th function not implemented';
};
exercise.five = function(data){
//-------------------
//---- Your Code ----
//-------------------
return 'Error: 5th function not implemented';
};
module.exports = exercise;
| JavaScript | 0.000001 | @@ -211,10 +211,10 @@
d 10
-28
+30
';%0A%7D
|
67bf62177b0cff325db21f7647755e11b8e8eb47 | comment out move in the chrome app | chrome-app/src/js/maze/game.js | chrome-app/src/js/maze/game.js | var Packed24 = Packed24 || {};
Packed24.Game = function(){};
var map;
var layer;
var cursors;
var player;
var puzzle_pieces = [
'puzzle-piece-0',
'puzzle-piece-1',
'puzzle-piece-2',
'puzzle-piece-3',
'puzzle-piece-4',
'puzzle-piece-5',
'puzzle-piece-6',
'puzzle-piece-7',
'puzzle-piece-8'
];
var pieces;
var player_speed = 500;
Packed24.Game.prototype = {
init: function () {
},
create: function() {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.stage.backgroundColor = '#787878';
this.game.stage.backgroundImage =
this.game.add.sprite(0, 0, 'background');
sizeGameToWindow(this.game);
map = this.game.add.tilemap('map');
// Now add in the tileset
map.addTilesetImage('council', 'tiles');
// Create our layer
layer = map.createLayer('Collision');
map.setCollision([4]);
// Resize the world
layer.resizeWorld();
// Un-comment this on to see the collision tiles
layer.debug = true;
// Player
this.createPlayer();
// pieces
this.createPieces();
cursors = this.game.input.keyboard.createCursorKeys();
window.cursors = cursors;
//var help = game.add.text(16, 16, 'Arrows to move', { font: '14px Arial', fill: '#ffffff' });
//help.fixedToCamera = true;
},
update: function() {
this.game.physics.arcade.collide(player, layer);
this.game.physics.arcade.overlap(player, pieces, collectPiece, null, this);
player.body.velocity.set(0);
if (cursors.left.isDown) {
movePlayer(player, 'left');
}
else if (cursors.right.isDown) {
movePlayer(player, 'right');
}
else {
player.animations.stop('left');
player.animations.stop('right');
//player.animations.stop();
}
if (cursors.up.isDown) {
movePlayer(player, 'up');
}
else if (cursors.down.isDown) {
movePlayer(player, 'down');
}
else {
player.animations.stop('up');
player.animations.stop('down');
//player.animations.stop();
}
},
createPieces: function () {
pieces = this.game.add.group();
//enable physics in them
pieces.enableBody = true;
pieces.physicsBodyType = Phaser.Physics.ARCADE;
gs.onPlaceMazePiece = function (id, position, x, y) {
// this.asteroids.create(this.game.world.randomX, this.game.world.randomY, 'rock');
var piece = pieces.create((x * 128) + 3, (y * 128) + 3, puzzle_pieces[position]);
piece.scale.setTo(0.34, 0.5);
piece.meta = {
id: id
}
};
},
createPlayer: function () {
player = this.game.add.sprite(100, 100, 'player', 1);
player.animations.add('left', [8, 9], 10, true);
player.animations.add('right', [1, 2], 10, true);
player.animations.add('up', [11, 12, 13], 10, true);
player.animations.add('down', [4, 5, 6], 10, true);
this.game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.collideWorldBounds = true;
player.body.setSize(120, 120, 0, 0);
}
};
function movePlayer(playerObj, direction) {
switch (direction) {
case 'up':
playerObj.body.velocity.y = -player_speed;
playerObj.play('up');
break;
case 'down':
playerObj.body.velocity.y = player_speed;
playerObj.play('down');
break;
case 'left':
playerObj.body.velocity.x = -player_speed;
playerObj.play('left');
break;
case 'right':
playerObj.body.velocity.x = player_speed;
playerObj.play('right');
break;
}
gs.moved(Math.floor((playerObj.position.x / 128)), Math.floor((playerObj.position.y / 128)));
}
function collectPiece(player, piece) {
piece.kill();
gs.collect(piece.meta.id);
}
function render() {
this.game.debug.body(player);
}
function sizeGameToWindow(game) {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
}
/*
chrome.runtime.onMessage.addListener(function (msg, sender) {
if (msg.name === "keyup") {
cursors.up.isDown = false;
cursors.down.isDown = false;
cursors.right.isDown = false;
cursors.left.isDown = false;
return;
}
switch (msg.keyCode) {
case 37:
cursors.up.isDown = false;
cursors.down.isDown = false;
cursors.right.isDown = false;
cursors.left.isDown = true;
break;
case 38:
cursors.up.isDown = true;
cursors.down.isDown = false;
cursors.right.isDown = false;
cursors.left.isDown = false;
break;
case 39:
cursors.up.isDown = false;
cursors.down.isDown = false;
cursors.right.isDown = true;
cursors.left.isDown = false;
break;
case 40:
cursors.up.isDown = false;
cursors.down.isDown = true;
cursors.right.isDown = false;
cursors.left.isDown = false;
break;
}
if (msg.keyCode === 39) {
}
$.event.trigger({ type: 'keypress', which: 39 });
});
*/
$(window).bind('resize', function (e) {
window.resizeEvt;
$(window).resize(function () {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function () {
sizeGameToWindow();
}, 250);
});
}); | JavaScript | 0 | @@ -3801,24 +3801,27 @@
;%0A %7D%0A%0A
+ //
gs.moved(Ma
|
3ef4315612b29370ccc55abeacb1af95e96ad5bf | Fix PhantomJS test (remove 'class' from Array) | detects/phantomjs.js | detects/phantomjs.js | /*!
* PhantomJS
*/
conditionizr.add('phantomjs', ['class'], function () {
return /\sPhantomJS\/[[0-9]+\]/.test(navigator.userAgent);
});
| JavaScript | 0 | @@ -49,15 +49,8 @@
', %5B
-'class'
%5D, f
|
cc85ab9c984cc974300f05a064722088b03240a8 | disable scroll bounc in ios | app/bootstrap/app.run.js | app/bootstrap/app.run.js | LessonsApp.run(function () {
$document.on('touchmove', function (event) {
event.preventDefault()
})
}); | JavaScript | 0 | @@ -18,16 +18,25 @@
nction (
+$document
) %7B%0A%09$do
|
b6103ff5e15e9daab6ca3785f680c32de928f740 | Add Function to Format Times For Display | chrome-extension/background.js | chrome-extension/background.js | var user1, user2, currentSession, startTime, endTime, currentInterval,pairingDurationMs, timer, popup, currentView, totalSession;
var sessions = [];
var totalTimeWorking = 0;
function PairingSession(user1, user2){
this.drive = user1;
this.navigate = user2;
this.timeWorked = 0;
this.timePaused = 0;
}
function getPopup(){
var views = chrome.extension.getViews({ type: "popup" });
popup = views[0];
}
function setTimeInterval(interval){
currentInterval = interval * 60000;
pairingDurationMs = currentInterval * 60000;
}
function pause(){
if(timer){
stopTimer();
return true;
} else {
startTimerCount();
return false;
}
}
function endPairingSession(){
if(currentSession.timeWorked === 0){
endSession();
}
stopTimer();
currentView = null;
sendInfoToDatabase();
}
function startPairing(){
updateTimerCountdown();
var date = new Date();
startTime = date.getTime();
currentSession = new PairingSession(user1, user2);
sessions.push(currentSession);
startTimerCount();
}
function startTimerCount(){
timer = setTimeout(function(){
totalTimeWorking += 1000;
currentInterval -= 1000;
checkDuration();
updateTimerCountdown();
clearTimeout(timer);
startTimerCount();
}, 1000);
}
function stopTimer(){
clearInterval(timer);
timer = null;
}
function checkDuration(){
if(currentInterval === 0){
endSession();
alert('Switch it ^');
startPairing();
}
}
function endSession(){
var date = new Date();
endTime = date.getTime();
currentSession.timeWorked = (pairingDurationMs / 60000) - currentInterval;
currentInterval = pairingDurationMs / 60000;
currentSession.timePaused = (endTime - startTime - (totalTimeWorking)) / 60000;
if(currentSession.timePaused == null || currentSession.timePaused <= .5 ){
currentSession.timePaused = 0;
};
totalTimeWorking = 0;
}
function updateTimerCountdown(){
popup.document.getElementsByClassName('countdown')[0].innerHTML = formatCurrentInterval();
}
function sendInfoToDatabase(){
console.log('session', sessions);
$.ajax({
url: 'http://localhost:9393/session/data',
type: 'post',
data: {session: sessions}
})
.done(function(data){
console.log('hello');
sessions = [];
// chrome.tabs.create({url: data['url']})
});
};
| JavaScript | 0 | @@ -2309,8 +2309,451 @@
%7D);%0A%7D;%0A
+%0Afunction formatCurrentInterval()%7B%0A var timeLeft = currentInterval;%0A var hours = Math.floor(timeLeft / 3600000);%0A var minutes = Math.floor((timeLeft %25 3600000) / 60000);%0A var seconds = Math.floor(((timeLeft %25 360000) %25 60000) / 1000);%0A if(hours %3E 0)%7B%0A return hours + %22:%22 + minutes + %22:%22 + seconds;%0A %7D else %7B%0A if(seconds %3E= 10)%7B%0A return minutes + %22:%22 + seconds;%0A %7D else %7B%0A return minutes + %22:0%22 + seconds;%0A %7D%0A %7D%0A%7D;%0A
|
2241397546db1bbe4e4d259220835d7c9ca76199 | add missing punctuation | node_modules/oae-config/lib/restmodel.js | node_modules/oae-config/lib/restmodel.js | /*!
* Copyright 2014 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-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.
*/
/**
* @RESTModel Config
*
* @Required []
* @Property {ModuleConfig} {module} Configuration for named module (e.g. "oae-activity"); may appear multiple times
*/
/**
* @RESTModel ConfigFields
*
* @Required [{configField}]
* @Property {string[]} configFields Config values in the form `oae-authentication/twitter/enabled`; may be single string
*/
/**
* @RESTModel ConfigSchema
*
* @Required []
* @Property {ModuleConfigSchema} {module} Configuration schema for named module (e.g. "oae-activity"); may appear multiple times
*/
/**
* @RESTModel ConfigValue
*
* @Required [{name}]
* @Property {string} {name} Value of the named config element; may also be boolean
*/
/**
* @RESTModel ConfigValues
*
* @Required [{configField}]
* @Property {string} {configField} Value(s) for config keys in the form `oae-authentication/twitter/enabled`; may occur mutiple times for different keys
*/
/**
* @RESTModel ElementConfigItem
*
* @Required [name,value]
* @Property {string} name Name of configuration item
* @Property {string} value Value of configuration item
*/
/**
* @RESTModel ElementConfigSchema
*
* @Required [defaultValue,description,globalAdminname,suppress,tenantOverride,type]
* @Property {string} defaultValue Default value for element (use "" for false)
* @Property {string} description Description of element
* @Property {boolean} globalAdminOnly Is element restricted to global adminstrators
* @Property {ElementConfigItem[]} group Possible values for group elements
* @Property {ElementConfigItem[]} list Possible values for list elements
* @Property {string} name Name of element
* @Property {boolean} suppress Allow presentation of element in adminstrative user interface
* @Property {boolean} tenantOverride Can tenants override global values
* @Property {string} type Type of element [boolean,internationalizableText,list,radio,text]
*/
/**
* @RESTModel ElementsConfigSchema
*
* @Required [{elementName}]
* @Property {ElementConfigSchema} {elementName} Configuration schema for named element; may appear multiple times
*/
/**
* @RESTModel FeatureConfig
*
* @Required [{element}]
* @Property {ConfigValue[]} {element} Configuration for named element; may appear multiple times
*/
/**
* @RESTModel FeatureConfigSchema
*
* @Required [description,elements,name]
* @Property {string} description Description of module
* @Property {ElementsConfigSchema} elements Elements of the module
* @Property {string} name Name of module
* @Property {boolean} tenantOverride Can tenants override global values
*/
/**
* @RESTModel ModuleConfig
*
* @Required [title]
* @Property {FeatureConfig} {feature} Configuration for named feature; may appear multiple times
* @Property {string} title Name of configuration module; not currently used
*/
/**
* @RESTModel ModuleConfigSchema
*
* @Required [title]
* @Property {FeatureConfigSchema} {feature} Configuration schema for named feature; may appear multiple times
* @Property {ConfigTitle} title Name of configuration module
*/
| JavaScript | 1 | @@ -2076,16 +2076,17 @@
balAdmin
+,
name,sup
|
d6a11f69228568aece7026038e2051d88674b738 | fix countdown | web/js/functions.js | web/js/functions.js | $(document).ready(function() {
var lock = false;
var count = 1200;
var min = 0;
var secs = 0;
var progress = 0;
var w = $(window).width();
// a mettre a partir du slide 2
// $("#slide2").hide();
// $("#slide3").hide();
// $("#slide4").hide();
$("#start").click(function() {
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
next();
})
var i = 0;
$(".next").click(function(){
if($(this).hasClass('finish')) {
return;
}
if($('input:checked').length == i) {
i++;
} else {
return;
}
next();
})
var test = 0;
function next(){
if(lock){
return;
}
test++;
lock = true;
progress = progress + 33;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#quests").animate({
marginLeft : -w*test
}, 1000,
function(){
// $("#slide .element:last").after($("#slide .element:first"));
// $("#slide").css("margin-left", "0px");
lock = false;
});
}
function timer()
{
count = count-1;
min = getMinutes(count);
secs = getSecondes(count);
if (count <= 0)
{
clearInterval(counter);
// stopQuiz();
return;
}
document.getElementById("timer").innerHTML = min+":" +secs;
}
function getMinutes(count)
{
if (count >= 60) {
var modulo = count % 60;
min = (count - modulo) / 60
} else {
min = 0;
}
return min;
}
function getSecondes(count)
{
if (count <= 60) {
secs = count;
} else {
secs = count % 60;
}
if(secs >= 0 && secs < 10) {
return "0"+secs;
} else {
return secs;
}
}
// Submit QCM action
$('.finish').on('click', function () {
var answers = new Array();
$('input:checked').each(function () {
answers.push($(this).val());
});
if (answers.length != $('.intitule').length) {
return;
}
$.ajax({
url : '/post/ajax/correctAnswers',
type : 'POST',
data : {
'answers' : answers
},
dataType:'json',
success : function(data) {
if (data.success) {
// Animate Popup
$('#popup-overlay').fadeIn('fast');
$('#popup').fadeIn('slow');
$('.content-success').fadeIn('slow');
} else {
// Animate Popup
$('#popup-overlay').fadeIn('fast');
$('#popup').fadeIn('slow');
$('.content-fail').fadeIn('slow'); }
},
error : function(request,error)
{
$('.alert-info').show();
}
});
});
// RDV SUBMIT BUTTON
$('#submitRdv').on('click', function () {
var meets = new Array();
$('.content-success input:checked').each(function() {
meets.push($(this).attr('value'));
});
if(!meets.length) {
return
}
$.ajax({
url : '/post/ajax/saveMeetAction',
type : 'POST',
data : {
'meets' : meets
},
dataType:'json',
success : function(data) {
$('.content-success').fadeOut('fast');
$('.content-rdv-success').fadeIn('slow');
},
error : function(request,error)
{
}
});
});
})
| JavaScript | 0.009717 | @@ -335,17 +335,19 @@
counter
-=
+ =
setInter
@@ -1178,24 +1178,23 @@
+if (
count
+%3C
=
-count-1;
+0)
%0A
@@ -1202,77 +1202,54 @@
-min = getMinutes(count);%0A secs = getSecondes
+%7B%0A clearInterval
(count
+er
);%0A
-%0A
if (
@@ -1240,39 +1240,36 @@
r);%0A
-if (count %3C= 0)
+ min = 0;
%0A %7B%0A
@@ -1269,44 +1269,92 @@
-%7B%0A clearInterval(counter)
+ secs = 0;%0A document.getElementById(%22timer%22).innerHTML = min+%22:%22 +secs
;%0A
@@ -1367,21 +1367,14 @@
-// stopQuiz()
+return
;%0A
@@ -1379,37 +1379,111 @@
+%7D%0A%0A
-return;%0A %7D
+ count = count-1;%0A min = getMinutes(count);%0A secs = getSecondes(count);
%0A%0A
@@ -1580,32 +1580,114 @@
es(count)%0A %7B%0A
+ if (count === 0) %7B%0A min = 0;%0A return min;%0A %7D%0A
if (coun
@@ -1880,32 +1880,116 @@
es(count)%0A %7B%0A
+ if (count === 0) %7B%0A secs = 0;%0A return secs;%0A %7D%0A
if (coun
|
374e001774bfd13fb0725b9ebf996fed03e99e96 | Remove trailing spaces | remoteappmanager/static/js/home/configurables.js | remoteappmanager/static/js/home/configurables.js | define([
"jquery",
"handlebars",
"utils"
], function($, hb, utils) {
"use strict";
var view_template = hb.compile(
'<div class="form-group">' +
'<label for="resolution-model-{{index}}">Resolution</label>' +
'<select class="form-control" id="resolution-model-{{ index }}">' +
'{{#each options}}' +
'<option value="{{this}}">{{this}}</option>' +
'{{/each}}' +
'</div>'
);
var ResolutionModel = function () {
// Model for the resolution configurable.
var self = this;
this.resolution = "Window";
this.resolution_options = ["Window", "1920x1080", "1280x1024", "1280x800", "1024x768"];
self.view = function (index) {
// Creates the View to add to the application entry.
var widget = $(view_template({
options: self.resolution_options,
index: index
}));
widget.find("select").change(function() {
if (this.selectedIndex) {
self.resolution = this.options[this.selectedIndex].value;
}
});
return widget;
};
};
ResolutionModel.prototype.tag = "resolution";
ResolutionModel.prototype.as_config_dict = function() {
// Returns the configuration dict to hand over to the API request.
// e.g.
// {
// "resolution" : "1024x768"
// }
// The returned dictionary must be added to the configurable
// parameter under the key given by the tag member.
var resolution = this.resolution;
if (resolution === 'Window') {
var max_size = utils.max_iframe_size();
resolution = max_size[0]+"x"+max_size[1];
}
return {
"resolution": resolution
};
};
// Define all your configurables here.
var configurables = {
ResolutionModel: ResolutionModel
};
var from_tag = function (tag) {
// Given a tag, lookup the appropriate configurable and
// return it. If the tag matches no configurable, returns null
for (var conf in configurables) {
if (configurables[conf].prototype.tag === tag) {
return configurables[conf];
}
}
return null;
};
var ns = {
from_tag: from_tag
};
return $.extend(ns, configurables);
});
| JavaScript | 0.981252 | @@ -695,24 +695,17 @@
x768%22%5D;%0A
-
%0A
+
@@ -939,29 +939,17 @@
%7D));%0A
-
%0A
+
@@ -1152,21 +1152,9 @@
%7D);%0A
-
%0A
+
@@ -1190,29 +1190,25 @@
%7D;%0A %7D;%0A
-
%0A
+
Resoluti
@@ -1245,20 +1245,17 @@
ution%22;%0A
-
%0A
+
Reso
@@ -1396,17 +1396,16 @@
// e.g.
-
%0A
@@ -1591,17 +1591,16 @@
member.
-
%0A
@@ -1634,25 +1634,17 @@
lution;%0A
-
%0A
+
@@ -1794,17 +1794,9 @@
%7D%0A
-
%0A
+
@@ -1863,20 +1863,17 @@
%0A %7D;%0A
-
%0A
+
// D
@@ -1981,21 +1981,17 @@
%0A %7D;%0A
-
%0A
+
var
@@ -2344,17 +2344,16 @@
rn null;
-
%0A %7D;%0A
@@ -2443,17 +2443,13 @@
ables);%0A
-
%0A%7D);%0A
|
11b0db3786abd214895429016d229a514527ec9e | remove extra logging | browser/test/integration/pluginDocs.js | browser/test/integration/pluginDocs.js | var assert = require('assert');
const fs = require('fs')
const vm = require('vm')
const createVizorSandbox = require('../../../lib/sandbox')
const pluginsPath = 'browser/plugins'
var sandbox = createVizorSandbox()
var context = new vm.createContext(sandbox)
var engineSource = fs.readFileSync('browser/dist/engine.js')
engineSource += ';\nE2.core = new Core();\n'
engineSource += ';\nE2.app = { player: { core: E2.core }};\n'
engineSource += 'E2.core.root_graph = new Graph();\n'
console.error(engineSource)
var engineScript = new vm.Script(engineSource, { filename: 'engine.js' })
engineScript.runInContext(context)
var plugins = JSON.parse(fs.readFileSync(pluginsPath + '/plugins.json'))
var pluginCats = Object.keys(plugins)
var DocumentationController = require('../../../controllers/documentationController');
var docsPath = 'documentation/browser/plugins/'
function jsonChecker(pluginId, inputSlots, outputSlots, finishCallback) {
return function (data) {
function slotMapper(docSlots) {
return function (slot) {
for (var i = 0, len = docSlots.length; i < len; ++i) {
if (docSlots[i].name === slot.name) {
return
}
}
console.error(pluginId + '.' + slot.name, 'missing markdown documentation in', docsPath + pluginId + '.md')
assert.ok(false, 'no slot for ' + pluginId + '.' + slot.name)
}
}
inputSlots.slice().map(slotMapper(data.inputs))
outputSlots.slice().map(slotMapper(data.outputs))
finishCallback()
}
}
describe('plugin docs', function() {
var dc
beforeEach(function() {
dc = new DocumentationController()
})
it('has entries for all plugins', function(done) {
var todo = 0
// count plugins
pluginCats.map(function(cat) {
var pluginNames = Object.keys(plugins[cat])
pluginNames.map(function() {
++todo
})
})
assert.ok(todo > 200)
// process plugins
pluginCats.map(function(cat) {
var pluginNames = Object.keys(plugins[cat])
pluginNames.map(function (pluginName) {
var pluginId = plugins[cat][pluginName]
var pluginSourcePath = pluginsPath + '/' + pluginId + '.plugin.js'
var pluginSource = fs.readFileSync(pluginSourcePath)
pluginSource += ';\n'
pluginSource += 'var fakeNode = new Node(E2.core.root_graph, "' + pluginId + '");\n'
pluginSource += 'var plugin' + pluginId + ' = new E2.plugins.' + pluginId + '(E2.core, fakeNode);\n'
script = new vm.Script(pluginSource, {filename: pluginId})
script.runInContext(context)
var res = {}
dc.getPluginDocumentation({
params: {
pluginName: pluginId
}
}, {
json: jsonChecker(pluginId, context['plugin' + pluginId].input_slots, context['plugin' + pluginId].output_slots, function() {
--todo
if (!todo) {
done()
}
})
})
})
})
})
})
| JavaScript | 0 | @@ -482,37 +482,8 @@
n'%0A%0A
-console.error(engineSource)%0A%0A
var
|
f636d42cffd77ec6f9c91a02a4a19ecf33ac3afb | add dark class to mapbox logo container so logo is white, refs #44 | app/components/Header.js | app/components/Header.js | import React from 'react';
import Modal from 'react-modal';
var modalStyle = {
overlay: {
backgroundColor:'rgba(0,0,0,0.5)',
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0
},
content: {
background: '#fff',
position: 'absolute',
top: '0',
right: '0',
left: '0',
padding: '20px',
bottom: 'auto',
width: '400px',
border: 'none',
overflow: 'hidden',
WebkitOverflowScrolling: 'touch',
borderRadius: '3px',
outline: 'none',
marginTop: '40px',
marginLeft: 'auto',
marginRight: 'auto'
}
};
var Header = React.createClass({
getInitialState: function() {
return { aboutModalIsOpen: false };
},
openAboutModal: function(e) {
e.preventDefault();
this.setState({aboutModalIsOpen: true});
},
closeAboutModal: function(e) {
e.preventDefault();
this.setState({aboutModalIsOpen: false});
},
render: function() {
return (
<div>
<header className="col12 pad2y fill-navy-dark clearfix">
<div className="limiter contain">
<a className="inline mb-logo" href=".">Mapbox</a>
</div>
<div className="limiter contain">
<a href="" onClick={this.openAboutModal}>About</a>
</div>
</header>
<Modal
isOpen={this.state.aboutModalIsOpen}
onRequestClose={this.closeAboutModal}
style={modalStyle}
>
<span className="icon close pin-right pad1" href="" onClick={this.closeAboutModal}></span>
<h2>About</h2>
<p>
OSM Comments was developed to help the Mapbox Data Team track conversations
in OpenStreetMap. And it's built for anyone to search notes and changeset
discussions involving any OpenStreetMap user.
</p>
<p>
Add "users:" in the search bar to find other discussions.
For example, "users:geohacker,Planemad" will find notes and
changeset discussions only for these users.
</p>
<p>
Read more on <a href="https://www.mapbox.com/blog/osm-comments/" target="_blank">our blog</a>.
</p>
<p>
<a href="http://www.openstreetmap.org/copyright" target="_blank">
Data © OpenStreetMap contributors
</a>
<br />
Code on <a href="https://github.com/mapbox/osm-comments" target="_blank">GitHub</a>
</p>
</Modal>
</div>
)
}
});
export default Header; | JavaScript | 0 | @@ -1117,32 +1117,37 @@
%22limiter contain
+ dark
%22%3E%0A
|
029ea1c42ed734f36daa3ff2b2367ee803d09ee3 | Improve cellHelpers.qualifiedId() | src/shared/cellHelpers.js | src/shared/cellHelpers.js | import { isNumber } from 'substance'
import { type } from '../value'
import { parseSymbol } from './expressionHelpers'
export function getCellState(cell) {
// FIXME: we should make sure that cellState is
// initialized as early as possible
return cell.state
}
export function isExpression(source) {
return /^\s*=/.exec(source)
}
export function getCellValue(cell) {
if (!cell) return undefined
if (cell.state) {
return cell.state.value
} else {
let sheet = cell.getDocument()
let type = sheet.getCellType(cell)
return valueFromText(type, cell.text())
}
}
export function valueFromText(preferredType, text) {
const data = _parseText(preferredType, text)
const type_ = type(data)
return { type: type_, data }
}
function _parseText(preferredType, text) {
switch (preferredType) {
case 'any': {
// guess value
if (text === 'false') {
return false
} else if (text === 'true') {
return true
} else if (!isNaN(text)) {
let _int = Number.parseInt(text, 10)
if (_int == text) { // eslint-disable-line
return _int
} else {
return Number.parseFloat(text)
}
} else {
return text
}
}
case 'integer': {
return Number.parseInt(text, 10)
}
case 'number': {
return Number.parseFloat(text)
}
case 'string': {
return text
}
case 'boolean': {
if (text) {
return text !== 'false'
} else {
return false
}
}
default: {
console.warn('FIXME: need to cast to type', preferredType)
return text
}
}
}
export const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
export function getColumnLabel(colIdx) {
if (!isNumber(colIdx)) {
throw new Error('Illegal argument.')
}
var label = ""
while(true) { // eslint-disable-line
var mod = colIdx % ALPHABET.length
colIdx = Math.floor(colIdx/ALPHABET.length)
label = ALPHABET[mod] + label
if (colIdx > 0) colIdx--
else if (colIdx === 0) break
}
return label
}
export function getCellLabel(rowIdx, colIdx) {
let colLabel = getColumnLabel(colIdx)
let rowLabel = rowIdx + 1
return colLabel + rowLabel
}
export function getColumnIndex(colStr) {
let index = 0
let rank = 1
for (let i = 0; i < colStr.length; i++) {
let letter = colStr[i]
index += rank * ALPHABET.indexOf(letter)
rank++
}
return index
}
export function getRowCol(cellId) {
var match = /^([A-Z]+)([1-9][0-9]*)$/.exec(cellId)
return [
parseInt(match[2], 10)-1,
getColumnIndex(match[1])
]
}
export function getError(cell) {
let cellState = getCellState(cell)
return cellState.errors[0]
}
export function getFrameSize(layout) {
// WORKAROUND, this should be solved in libcore functions
const defaultSizes = {
'width': '400',
'height': '400'
}
const sizes = layout.width ? layout : defaultSizes
return sizes
}
// This is useful for writing tests, to use queries such as 'A1:A10'
export function queryCells(cells, query) {
let { type, name } = parseSymbol(query)
switch (type) {
case 'cell': {
const [row, col] = getRowCol(name)
return cells[row][col]
}
case 'range': {
let [anchor, focus] = name.split(':')
const [anchorRow, anchorCol] = getRowCol(anchor)
const [focusRow, focusCol] = getRowCol(focus)
if (anchorRow === focusRow && anchorCol === focusCol) {
return cells[anchorCol][focusCol]
}
if (anchorRow === focusRow) {
return cells[anchorRow].slice(anchorCol, focusCol+1)
}
if (anchorCol === focusCol) {
let res = []
for (let i = anchorRow; i <= focusRow; i++) {
res.push(cells[i][anchorCol])
}
return res
}
throw new Error('Unsupported query')
}
default:
throw new Error('Unsupported query')
}
}
export function qualifiedId(doc, cell) {
if (doc) return `${cell.getDocument().id}_${cell.id}`
return cell.id
}
| JavaScript | 0.000001 | @@ -10,16 +10,26 @@
isNumber
+, isString
%7D from
@@ -3954,62 +3954,156 @@
%7B%0A
-if (doc) return %60$%7Bcell.getDocument().id%7D_
+let cellId = isString(cell) ? cell : cell.id%0A if (doc) %7B%0A let docId = isString(doc) ? doc : doc.id%0A return %60$%7BdocId%7D!
$%7Bcell
-.i
+I
d%7D%60%0A
+ %7D else %7B%0A
re
@@ -4111,14 +4111,17 @@
urn cell
-.id
+Id%0A %7D
%0A%7D%0A
|
6540961601c2f27f649117516c6e3c03f976d8e3 | Fix semver sorting | lib/CoreDataSchema.js | lib/CoreDataSchema.js | const fs = require("fs");
const path = require("path");
const semver = require("semver");
const ManagedObject = require("./ManagedObject");
class CoreDataSchema {
constructor(coredata) {
this.coredata = coredata;
}
async load(schemaPath) {
const database = this.coredata;
let files = [];
let folders = [];
fs.readdirSync(schemaPath).forEach(item => {
let stat = fs.statSync(path.join(schemaPath, item));
if (stat.isDirectory()) {
folders.push(item);
} else {
files.push(item);
}
});
files = files.sort((a, b) => {
return semver.gt(
this._createModelVersionName(a),
this._createModelVersionName(b)
);
});
files.forEach(file => {
const version = this._createModelVersionName(file);
let model = database.createModelFromYaml(
fs.readFileSync(path.join(schemaPath, file)),
{},
version
);
if (~folders.indexOf(model.version)) {
this._loadClassesForModel(schemaPath, model);
}
});
let latestVersion = this._createModelVersionName(files[files.length - 1]);
database.setModelVersion(latestVersion);
if (~folders.indexOf("latest")) {
this._loadClassesForModel(schemaPath, database.model, "latest");
}
}
_createModelVersionName(filePath) {
return path.basename(filePath).replace(/\.ya?ml/, "");
}
_loadClassesForModel(schemaPath, model, version = null) {
let classesFolder = path.join(schemaPath, version || model.version);
let files = fs.readdirSync(classesFolder);
for (let file of files) {
let filename = path.join(classesFolder, file);
let entityName = file.replace(path.extname(file), "");
let entity = model.getEntity(entityName);
if (!entity)
throw new Error(
`Entity ${entityName} not found for custom class at path ${filename}`
);
let customClass = require(filename);
customClass = customClass.default || customClass;
if (!(customClass.prototype instanceof ManagedObject))
throw new Error(
`Unable to load ${filename}, exported class isn't instance of ManagedObject`
);
entity.objectClass = customClass;
}
}
}
module.exports = CoreDataSchema;
| JavaScript | 0.000001 | @@ -16,12 +16,12 @@
ire(
-%22fs%22
+'fs'
);%0Ac
@@ -44,14 +44,14 @@
ire(
-%22
+'
path
-%22
+'
);%0Ac
@@ -76,16 +76,16 @@
ire(
-%22
+'
semver
-%22
+'
);%0A%0A
@@ -114,17 +114,17 @@
require(
-%22
+'
./Manage
@@ -130,17 +130,17 @@
edObject
-%22
+'
);%0A%0Aclas
@@ -697,16 +697,41 @@
%0A )
+%0A ? 1%0A : -1
;%0A %7D)
@@ -1224,24 +1224,24 @@
indexOf(
-%22
+'
latest
-%22
+'
)) %7B%0A
@@ -1301,16 +1301,16 @@
el,
-%22
+'
latest
-%22
+'
);%0A
@@ -1411,18 +1411,18 @@
ya?ml/,
-%22%22
+''
);%0A %7D%0A%0A
@@ -1745,10 +1745,10 @@
e),
-%22%22
+''
);%0A%0A
|
0a6f36e90ff2a4cb9f80efcfd43352e7419bfee1 | check that sequence is sequential, and timestamp is increasing | validation.js | validation.js | 'use strict';
var isRef = require('ssb-ref')
var isHash = isRef.isHash
var isFeedId = isRef.isFeedId
var contpara = require('cont').para
var explain = require('explain-error')
// make a validation stream?
// read the latest record in the database
// check it against the incoming data,
// and then read through
function clone (obj) {
var o = {}
for(var k in obj) o[k] = obj[k];
return o
}
function get (db, key) {
return function (cb) {
return db.get(key, cb)
}
}
function isString (s) {
return 'string' === typeof s
}
function isInteger (n) {
return ~~n === n
}
function isObject (o) {
return o && 'object' === typeof o
}
module.exports = function (ssb, opts) {
var lastDB = ssb.sublevel('lst')
var clockDB = ssb.sublevel('clk')
var hash = opts.hash
var zeros = undefined
var verify = opts.keys.verify
var encode = opts.codec.encode
var validators = {}
function validateSync (msg, prev, pub) {
// :TODO: is there a faster way to measure the size of this message?
var asJson = JSON.stringify(msg)
if (asJson.length > 8192) { // 8kb
validateSync.reason = 'encoded message must not be larger than 8192 bytes'
return false
}
var type = msg.content.type
if(!isString(type)) {
validateSync.reason = 'type property must be string'
return false
}
if(52 < type.length || type.length < 3) {
validateSync.reason = 'type must be 3 < length <= 52, but was:' + type.length
return false
}
if(prev) {
if(msg.previous !== hash(encode(prev))) {
validateSync.reason = 'expected previous: '
+ hash(encode(prev)).toString('base64')
return false
}
if(msg.sequence !== prev.sequence + 1
&& msg.timestamp <= prev.timestamp) {
validateSync.reason = 'out of order'
return false
}
}
else {
if(!(msg.previous == null
&& msg.sequence === 1 && msg.timestamp > 0)) {
validateSync.reason = 'expected initial message'
return false
}
}
var _pub = pub.public || pub
if(!(msg.author === _pub || msg.author === hash(_pub))) {
validateSync.reason = 'expected different author:'+
hash(pub.public || pub).toString('base64') +
'but found:' +
msg.author.toString('base64')
return false
}
var _msg = clone(msg)
delete _msg.signature
if(!verify(pub, msg.signature, hash(encode(_msg)))) {
validateSync.reason = 'signature was invalid'
return false
}
validateSync.reason = ''
return true
}
function getLatest (id, cb) {
var pub
contpara([
ssb.getPublicKey(id),
get(lastDB, id)
])(function (err, results) {
//get PUBLIC KEY out of FIRST MESSAGE.
pub = err ? null : results[0]
var expected = err ? 0 : results[1]
if(!expected) {
return cb(null, {
key: null, value: null, type: 'put',
public: pub, ready: true
})
}
get(clockDB, [id, expected]) (function (err, key) {
if(err) throw explain(err, 'this should never happen')
get(ssb, key) (function (err, _prev) {
if(err) throw explain(err, 'this should never happen')
cb(null, {
key: key, value: _prev, type: 'put',
public: pub, ready: true
})
})
})
})
}
var latest = {}, authors = {}
var queue = [], batch = []
function setLatest(id) {
if(latest[id]) return
latest[id] = {
key: null, value: null, type: 'put',
public: null, ready: false
}
getLatest(id, function (_, obj) {
latest[id] = obj
validate()
})
}
var batch = [], writing = false
function drain () {
writing = true
var _batch = batch
batch = []
ssb.batch(_batch, function () {
writing = false
if(batch.length) drain()
_batch.forEach(function (op) {
op.cb(null, op.value, op.key)
})
validate()
})
}
function write (op) {
batch.push(op)
if(!writing) drain()
}
function validate() {
if(!queue.length) return
var next = queue[0]
var id = next.value.author
//todo, validate as many feeds as possible
//in parallel. this code currently will wait
//to get the latest key when necessary
//which will slow validation when that happens.
//I will leave it like this currently,
//because it's hard to test all the edgecases here
//so optimize for simplicity.
if(!latest[id]) setLatest(id)
else if(latest[id].ready) {
var op = queue.shift()
var next = op.value
var l = latest[id]
var pub = l.public
var prev = l.value
if(!pub && !prev && next.content.type === 'init') {
l.key = op.key
l.value = op.value
l.public = next.content.public
write(op)
}
else if(prev.sequence + 1 === next.sequence) {
if(validateSync(next, prev, pub)) {
l.key = op.key
l.value = op.value
write(op)
}
else {
op.cb(new Error(validateSync.reason))
drain()
}
}
else if(prev.sequence >= next.sequence) {
ssb.get(op.key, op.cb)
} else {
op.cb(new Error('seq too high'))
drain()
}
}
}
function createValidator (id, done) {
return function (msg, cb) {
queue.push({
key: hash(encode(msg)),
value: msg, type: 'put', cb: cb
})
validate()
}
}
var v
return v = {
validateSync: validateSync,
getLatest: getLatest,
validate: function (msg, cb) {
if(
!isObject(msg) ||
!isInteger(msg.sequence) ||
!isFeedId(msg.author) ||
!isObject(msg.content)
)
return cb(new Error('invalid message'))
var id = msg.author
var validator = validators[id] =
validators[id] || createValidator(id)
return validator(msg, cb)
}
}
}
| JavaScript | 0.021757 | @@ -1733,27 +1733,26 @@
+ 1%0A
- &&
+%7C%7C
msg.timesta
|
38a16605f1ac45d4823617c979fc070520dc1844 | remove container div | app/components/Navbar.js | app/components/Navbar.js | import React from 'react';
import {Link} from 'react-router';
import NavbarStore from '../stores/NavbarStore';
import NavbarActions from '../actions/NavbarActions';
class Navbar extends React.Component {
constructor(props) {
super(props);
this.state = NavbarStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
NavbarStore.listen(this.onChange);
}
componentWillUnmount() {
NavbarStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
handleClick() {
document.getElementByClassName('container').classList.remove('fadeIn animated');
document.getElementByClassName('container').classList.add('fadeOut animated');
}
render() {
return (
<nav className="navbar fadeIn animated">
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-2">
<span className='navbar-header shake animated'>
<Link to='/' className="navbar-brand">
<img id='name-brand' className=' col-xs-12 shake animated-8' src='/img/nameBrand.png'/>
</Link>
</span>
</div>
<div className='col-xs-12 col-sm-6 col-md-4 col-md-offset-2'>
<div className='col-xs-4 col-sm-4 col-md-4 no-margin'>
<span role="presentation">
<Link to='/resume' className='nav-links' id='resume'>
<img className='shake animated-5' src='/img/newRes.png'/>
</Link>
</span>
</div>
<div className='col-xs-4 col-sm-4 col-md-4 no-margin'>
<span role="presentation">
<Link to='/projects' className='nav-links' id='projects'>
<img className='shake animated-6' src='/img/newProj.png'/>
</Link>
</span>
</div>
<div className='col-xs-4 col-sm-4 col-md-4 no-margin'>
<span role="presentation">
<Link to='/technologies' className='nav-links' id='technologies'>
<img className='shake animated-7' src='/img/newTech.png'/>
</Link>
</span>
</div>
</div>
</div>
</div>
</nav>
);
}
}
Navbar.contextTypes = {
router: React.PropTypes.func.isRequired
};
export default Navbar;
| JavaScript | 0.000002 | @@ -792,46 +792,8 @@
d%22%3E%0A
- %3Cdiv className=%22container%22%3E%0A
@@ -876,16 +876,25 @@
col-md-2
+ xmargbot
%22%3E%0A
@@ -2319,31 +2319,16 @@
%3C/div%3E%0A
- %3C/div%3E%0A
%3C/
|
f0fb551f0e7e6d67afb8f9df3148eb0c43223112 | update SprkInputElement to use additional setAriaDescribedBy function | react/src/base/inputs/components/SprkInputElement/SprkInputElement.js | react/src/base/inputs/components/SprkInputElement/SprkInputElement.js | import React, { Component } from 'react';
import classNames from 'classnames';
import propTypes from 'prop-types';
class SprkInputElement extends Component {
constructor(props) {
const { value } = props;
const { defaultValue } = props;
super(props);
if (value || defaultValue) {
this.state = {
hasValue: true,
};
} else {
this.state = {
hasValue: false,
};
}
this.calculateAriaDescribedBy = this.calculateAriaDescribedBy.bind(this);
}
componentDidMount() {
this.setState({
calculatedAriaDescribedBy: this.calculateAriaDescribedBy(),
});
}
componentDidUpdate(prevProps) {
const { errorContainerId, ariaDescribedBy } = this.props;
if (
errorContainerId !== prevProps.errorContainerId ||
ariaDescribedBy !== prevProps.ariaDescribedBy
) {
this.setState({
calculatedAriaDescribedBy: this.calculateAriaDescribedBy(),
});
}
}
calculateAriaDescribedBy() {
const { errorContainerId, ariaDescribedBy } = this.props;
if (errorContainerId && ariaDescribedBy) {
return `${errorContainerId} ${ariaDescribedBy}`;
}
if (ariaDescribedBy) return ariaDescribedBy;
if (errorContainerId) return errorContainerId;
return undefined;
}
render() {
const {
analyticsString,
children,
errorContainerId,
type,
id,
formatter,
forwardedRef,
iconRight,
idString,
leadingIcon,
value,
textIcon,
hiddenLabel,
disabled,
valid,
ariaDescribedBy,
...rest
} = this.props;
const { hasValue, calculatedAriaDescribedBy } = this.state;
const Element = type === 'textarea' ? 'textarea' : 'input';
// Adds class for IE and Edge
const handleOnBlur = (e) => {
if (e.target.value.length > 0) {
this.setState({ hasValue: true });
} else {
this.setState({ hasValue: false });
}
};
return (
<Element
className={classNames('sprk-u-Width-100', {
'sprk-b-TextArea': type === 'textarea',
'sprk-b-TextInput sprk-b-InputContainer__input': type !== 'textarea',
'sprk-b-TextInput--label-hidden':
type === 'hugeTextInput' && hiddenLabel,
'sprk-b-TextInput--error': type !== 'textarea' && !valid,
'sprk-b-TextInput--has-svg-icon':
type !== 'textarea' && leadingIcon.length > 0,
'sprk-b-TextInput--has-text-icon': type !== 'textarea' && textIcon,
'sprk-b-Input--has-floating-label':
hasValue && type === 'hugeTextInput',
'sprk-b-InputContainer__input--has-icon-right': iconRight,
})}
type={type}
id={id}
disabled={disabled}
ref={forwardedRef}
data-id={idString}
data-analytics={analyticsString}
aria-invalid={!valid}
aria-describedby={calculatedAriaDescribedBy}
value={valid && formatter ? formatter(value) : value}
onBlur={(e) => handleOnBlur(e)}
{...rest}
>
{children}
</Element>
);
}
}
SprkInputElement.propTypes = {
/**
* Assigned to the `data-analytics` attribute serving as a unique selector
* for outside libraries to capture data.
*/
analyticsString: propTypes.string,
/**
* Configured by parent and included in the `aria-describedby` attribute.
*/
errorContainerId: propTypes.string,
/**
* A function supplied will be passed the value of the input and then
* executed, if the valid prop is true. The value returned will be
* assigned to the value of the input.
*/
formatter: propTypes.func,
/**
* Determines type of Input.
*/
type: propTypes.string,
/**
* Positions the leadingIcon inside of the input to the right.
*/
iconRight: propTypes.bool,
/**
* Configured by parent and assigned to the `id` attribute.
*/
id: propTypes.string,
/**
* Assigned to the `data-id` attribute serving as a unique selector for
* automated tools.
*/
idString: propTypes.string,
/**
* The name of the icon, when supplied,
* will be rendered inside the input element.
*/
leadingIcon: propTypes.string,
/**
* If true, will render the currency icon inside the input element.
*/
textIcon: propTypes.bool,
/**
* Determines whether to render the
* component in the valid or the error state.
*/
valid: propTypes.bool,
/**
* A space-separated string of valid HTML Ids to add to the aria-describedby
* attribute on the Input.
*/
ariaDescribedBy: propTypes.string,
};
export default SprkInputElement;
| JavaScript | 0 | @@ -505,102 +505,113 @@
;%0A
-%7D%0A%0A componentDidMount() %7B%0A this.setState(%7B%0A calculatedAriaDescribedBy: this.calculate
+ this.setAriaDescribedBy = this.setAriaDescribedBy.bind(this);%0A %7D%0A%0A componentDidMount() %7B%0A this.set
Aria
@@ -627,16 +627,8 @@
By()
-,%0A %7D)
;%0A
@@ -851,24 +851,91 @@
y%0A ) %7B%0A
+ this.setAriaDescribedBy();%0A %7D%0A %7D%0A%0A setAriaDescribedBy() %7B%0A
this.set
@@ -942,18 +942,16 @@
State(%7B%0A
-
ca
@@ -1016,20 +1016,12 @@
-
%7D);%0A
- %7D%0A
%7D%0A
@@ -4681,16 +4681,199 @@
string,%0A
+ children: propTypes.node,%0A disabled: propTypes.bool,%0A hiddenLabel: propTypes.bool,%0A forwardedRef: propTypes.shape(),%0A value: propTypes.string,%0A defaultValue: propTypes.string,%0A
%7D;%0A%0Aexpo
|
f90b25cece21c618fbbfee0783a6f5f216cf8e8f | fix bug for drill through on cubes that have blanks etc in name (encoding issue) | js/saiku/views/DrillthroughModal.js | js/saiku/views/DrillthroughModal.js | /**
* Dialog for member selections
*/
var DrillthroughModal = Modal.extend({
type: "drillthrough",
buttons: [
{ text: "Ok", method: "ok" },
{ text: "Cancel", method: "close" }
],
events: {
'click .collapsed': 'select',
'click .expand': 'select',
'click .folder_collapsed': 'select',
'click .folder_expanded': 'select',
'click .dialog_footer a:' : 'call',
'click .parent_dimension input' : 'select_dimension',
'click .measure_tree input' : 'select_measure'
},
initialize: function(args) {
// Initialize properties
_.extend(this, args);
this.options.title = args.title;
this.query = args.workspace.query;
this.position = args.position;
this.action = args.action;
Saiku.ui.unblock();
_.bindAll(this, "ok", "drilled");
// Resize when rendered
this.bind('open', this.post_render);
this.render();
// Load template
$(this.el).find('.dialog_body')
.html(_.template($("#template-drillthrough").html())(this));
// Show dialog
$(this.el).find('.maxrows').val(this.maxrows);
var schema = this.query.get('schema');
var key = this.query.get('connection') + "/" +
this.query.get('catalog') + "/"
+ ((schema == "" || schema == null) ? "null" : schema)
+ "/" + this.query.get('cube');
var dimensions = Saiku.session.sessionworkspace.dimensions[key].get('data');
var measures = Saiku.session.sessionworkspace.measures[key].get('data');
var container = $("#template-drillthrough-list").html();
var templ_dim =_.template($("#template-drillthrough-dimensions").html())({dimensions: dimensions});
var templ_measure =_.template($("#template-drillthrough-measures").html())({measures: measures});
$(container).appendTo($(this.el).find('.dialog_body'));
$(this.el).find('.sidebar').height(($("body").height() / 2) + ($("body").height() / 6) );
$(this.el).find('.sidebar').width(380);
$(this.el).find('.dimension_tree').html('').append($(templ_dim));
$(this.el).find('.measure_tree').html('').append($(templ_measure));
},
select: function(event) {
var $target = $(event.target).hasClass('root')
? $(event.target) : $(event.target).parent().find('span');
if ($target.hasClass('root')) {
$target.find('a').toggleClass('folder_collapsed').toggleClass('folder_expand');
$target.toggleClass('collapsed').toggleClass('expand');
$target.parents('li').find('ul').children('li').toggle();
}
return false;
},
select_dimension: function(event) {
var $target = $(event.target);
var checked = $target.is(':checked');
$target.parent().find('input').attr('checked', checked);
},
select_measure: function(event) {
var $target = $(event.target);
var checked = $target.is(':checked');
if(checked) {
$target.parent().siblings().find('input').attr('checked', false);
}
},
post_render: function(args) {
$(args.modal.el).parents('.ui-dialog').css({ width: "150px" });
},
ok: function() {
// Notify user that updates are in progress
var $loading = $("<div>Drilling through...</div>");
$(this.el).find('.dialog_body').children().hide();
$(this.el).find('.dialog_body').prepend($loading);
var selections = ""
$(this.el).find('.check_level:checked').each( function(index) {
if (index > 0) {
selections += ", ";
}
selections += $(this).val();
});
var maxrows = $(this.el).find('.maxrows').val();
var params = "?maxrows=" + maxrows;
params = params + (typeof this.position !== "undefined" ? "&position=" + this.position : "" );
params += "&returns=" + selections;
if (this.action == "export") {
var location = Settings.REST_URL +
Saiku.session.username + "/query/" +
this.query.id + "/drillthrough/export/csv" + params;
this.close();
window.open(location);
} else if (this.action == "table") {
Saiku.ui.block("Executing drillthrough...");
this.query.action.get("/drillthrough", { data: { position: this.position, maxrows: maxrows , returns: selections}, success: this.drilled } );
this.close();
}
return false;
},
drilled: function(model, response) {
var table = new Table({ workspace: this.workspace });
table.render({ data: response }, true);
Saiku.ui.unblock();
var html = '<div id="fancy_results" class="workspace_results" style="overflow:visible"><table>' + $(table.el).html() + '</table></div>';
this.remove();
table.remove();
$.fancybox(html
,
{
'autoDimensions' : false,
'autoScale' : false,
'height' : ($("body").height() - 100),
'width' : ($("body").width() - 100),
'transitionIn' : 'none',
'transitionOut' : 'none'
}
);
},
finished: function() {
$(this.el).dialog('destroy').remove();
this.query.run();
}
}); | JavaScript | 0 | @@ -1485,24 +1485,43 @@
+ %22/%22 +
+encodeURIComponent(
this.query.g
@@ -1530,16 +1530,17 @@
('cube')
+)
;%0A%0A
|
5f8877feed276531a664d1f41dcc1ca2022ca411 | change safari download to `application/octet-stream' | src/snapshot/filesaver.js | src/snapshot/filesaver.js | /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
* License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160328
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
'use strict';
var fileSaver = function(url, name) {
var saveLink = document.createElement('a');
var canUseSaveLink = 'download' in saveLink;
var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
var promise = new Promise(function(resolve, reject) {
// IE <10 is explicitly unsupported
if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
reject(new Error('IE < 10 unsupported'));
}
// First try a.download, then web filesystem, then object URLs
if(isSafari) {
// Safari doesn't allow downloading of blob urls
document.location.href = 'data:attachment/file' + url.slice(url.search(/[,;]/));
resolve(name);
}
if(!name) {
name = 'download';
}
if(canUseSaveLink) {
saveLink.href = url;
saveLink.download = name;
document.body.appendChild(saveLink);
saveLink.click();
document.body.removeChild(saveLink);
resolve(name);
}
// IE 10+ (native saveAs)
if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
navigator.msSaveBlob(new Blob([url]), name);
resolve(name);
}
reject(new Error('download error'));
});
return promise;
};
module.exports = fileSaver;
| JavaScript | 0 | @@ -1238,22 +1238,31 @@
ta:a
-ttachment/file
+pplication/octet-stream
' +
|
43f0129554c57e5259465d04db4fc7f26eec1140 | Update active_cname.js (#21) | main/active_cname.js | main/active_cname.js | /*
***** 已使用的子域名
* ***********************
*
* 目前以下子域名已经启用
* 提交一个 PR, 添加你想使用的的域名
*
*
**** 说明
* ***********
*
* KEY: 你提交的域名(如:`foo` 表示自定义子域名为 `foo.js.cool`)
*
* VALUE: 以 Github 为例,`foo.github.io` 表示用户/组织的主页,
* 或 `foo.github.io/bar` 表示项目主页,也可以绑定 Gitee、 CODING.NET 等其它开源托管服务商。
*
* CLOUDFLARE: 目前 JS.COOL 使用的 DNS 服务商为 CloudFlare。默认情况下代理状态为自动(支持 SSL),
* 通过 HTTPS 链接(如: https://foo.js.cool )进行访问。
* 但如果你不希望通过 CloudFlare 加速,可以选择 `仅限 DNS` 选项,
* 只需要在你提交的代码后面添加 `// noCF` 注释即可。
*/
module.exports = {
// 请在此处区域内添加自定义域名
'cnchar': 'theajack.github.io',
'leader': 'willin.github.io',
'codewars': 'js-cool.github.io',
'dataloader': 'shiwangme.github.io',
'hyperapp': 'willin.github.io',
'anime': 'js-cool.github.io',
'learn': 'hosting.gitbook.com',
'vchart': 'willin.github.io',
'graphql': 'willin.github.io',
'speech': 'willin.github.io',
'antiadblock': 'js-cool.github.io',
'noho': 'willin.github.io',
'jen': 'dirkhe1051931999.github.io',
'uiw': 'uiwjs.github.io',
'xrkffgg': 'xrkffgg.github.io',
'interview': 'front-end-interview.netlify.app',
'xiaomeiwu':'xiaomeiwu.github.io/vue-admin',
'ip': 'ipip.vercel.app', // noCF
'mingyan': 'lehs8n.coding-pages.com', //noCf
'na':'qq.mcust.cn',
'bbx': 'appser.gitee.io',
// 请在此行之上新增一行并提交 Pull Request
// 示例:
// 'youarname': 'username.github.io' // noCF
// 以下为已启用的保留域名,请勿修改
'@': 'js-cool.github.io',
'www': 'kv6xcc.coding-pages.com', // 国内镜像
'logo': 'js-cool.github.io'
};
| JavaScript | 0 | @@ -1325,16 +1325,51 @@
ee.io',%0A
+ 'mengd': 'cname.vercel-dns.com',%0A
// %E8%AF%B7%E5%9C%A8%E6%AD%A4
|
060e8ce6c394c62c365618a140241522cc0b798b | Remove commented out sections | oabutton/static/public/js/bookmarklet.js | oabutton/static/public/js/bookmarklet.js | (function() {
var detectDOI = function() {
var nodes, node, childNode, matches, i, j;
// match DOI: test on http://t.co/eIJciunBRJ
var doi_re = /10\.\d{4,}(?:\.\d+)*\/\S+/;
// look for meta[name=citation_doi][content]
nodes = document.getElementsByTagName("meta");
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.getAttribute("name") == "citation_doi") {
return node.getAttribute("content").replace(/^doi:/, "");
}
}
// look in all text nodes for a DOI
nodes = document.getElementsByTagName("*");
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
if (!node.hasChildNodes()) {
continue;
}
if (node.nodeName == "SCRIPT") {
continue;
}
for (j = 0; j < node.childNodes.length; j++) {
childNode = node.childNodes[j];
// only text nodes
if (childNode.nodeType !== 3) {
continue;
}
if (matches = doi_re.exec(childNode.nodeValue)) {
return matches[0];
}
}
}
return null;
};
// ascertain if the bookmarklet has already been called
var exists = document.getElementById("OAButton");
if(exists == null)
{
// get the base URL
var loader = document.body.lastChild;
var base = loader.getAttribute("src").match(/^https?:\/\/[^/]+/)[0];
loader.parentNode.removeChild(loader);
// build the iframe URL
var url = base + "/api/add/?url=" + encodeURIComponent(window.location);
var doi = detectDOI();
if(doi !== null) {
url += "&doi=" + encodeURIComponent(doi);
}
// build the control div
var div = document.createElement("div");
div.setAttribute("allowTransparency", "true");
div.setAttribute("id", "OAButton");
div.style.position = "fixed";
div.style.zIndex = "2147483640";
div.style.boxSizing = "border-box";
div.style.MozBoxSizing = "border-box";
div.style.padding = "15px";
div.style.background = "white";
div.style.height = "100%";
div.style.width = "350px";
div.style.top = "0";
div.style.right = "0";
div.style.overflow = "scroll";
div.style.overflowX = "hidden";
document.body.appendChild(div);
// add the close button
var closeButton = document.createElement("a");
closeButton.setAttribute("href", "javascript:document.getElementById('OAButton').setAttribute('style', 'display:none')");
closeButton.setAttribute("id", "closeButton");
closeButton.appendChild(document.createTextNode("X"));
closeButton.style.zIndex = "2147483641";
closeButton.style.position = "relative";
closeButton.style.top = "0";
div.appendChild(closeButton);
// add the iframe
var iframe = document.createElement("iframe");
iframe.setAttribute("allowTransparency", "true");
iframe.setAttribute("src", url);
iframe.style.position = "fixed";
iframe.style.zIndex = "2147483640";
iframe.style.boxSizing = "border-box";
iframe.style.MozBoxSizing = "border-box";
iframe.style.padding = "15px";
iframe.style.borderLeft = "2px #555 dashed";
iframe.style.background = "white";
iframe.style.height = "100%";
iframe.style.width = "350px";
iframe.style.bottom = "0";
iframe.style.right = "0";
div.appendChild(iframe);
} else {
var div = exists;
div.setAttribute("allowTransparency", "true");
div.setAttribute("id", "OAButton");
div.style.position = "fixed";
div.style.zIndex = "2147483640";
div.style.boxSizing = "border-box";
div.style.MozBoxSizing = "border-box";
div.style.padding = "15px";
div.style.background = "white";
div.style.height = "100%";
div.style.width = "350px";
div.style.top = "0";
div.style.right = "0";
div.style.overflow = "scroll";
div.style.overflowX = "hidden";
div.style.display = "block";
//closeButton = document.getElementById("closeButton");
//closeButton.style.position = "relative";
//closeButton.style.top = "0";
//closeButton.style.right = "330px";
}
})();
| JavaScript | 0 | @@ -3754,183 +3754,8 @@
%22;%0A%0A
-%09%09//closeButton = document.getElementById(%22closeButton%22);%0A%09%09//closeButton.style.position = %22relative%22;%0A%09%09//closeButton.style.top = %220%22;%0A%09%09//closeButton.style.right = %22330px%22;%0A
%09%7D%0A%7D
|
fda15702bc1c769e9d96e71d98c8d3e05026bd3b | Fix error | erpnext/hr/doctype/employee_advance/employee_advance.js | erpnext/hr/doctype/employee_advance/employee_advance.js | // Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Employee Advance', {
setup: function(frm) {
frm.add_fetch("employee", "company", "company");
frm.add_fetch("company", "default_employee_advance_account", "advance_account");
frm.set_query("employee", function() {
return {
filters: {
"status": "Active"
}
};
});
frm.set_query("advance_account", function() {
return {
filters: {
"root_type": "Asset",
"is_group": 0,
"company": frm.doc.company
}
};
});
},
refresh: function(frm) {
if (frm.doc.docstatus===1
&& (flt(frm.doc.paid_amount) < flt(frm.doc.advance_amount))
&& frappe.model.can_create("Payment Entry")) {
frm.add_custom_button(__('Payment'),
function() { frm.events.make_payment_entry(frm); }, __("Make"));
}
else if (
frm.doc.docstatus === 1
&& flt(frm.doc.claimed_amount) < flt(frm.doc.paid_amount)
&& frappe.model.can_create("Expense Claim")
) {
frm.add_custom_button(
__("Expense Claim"),
function() {
frm.events.make_expense_claim(frm);
},
__("Make")
);
}
},
make_payment_entry: function(frm) {
var method = "erpnext.accounts.doctype.payment_entry.payment_entry.get_payment_entry";
if(frm.doc.__onload && frm.doc.__onload.make_payment_via_journal_entry) {
method = "erpnext.hr.doctype.employee_advance.employee_advance.make_bank_entry"
}
return frappe.call({
method: method,
args: {
"dt": frm.doc.doctype,
"dn": frm.doc.name
},
callback: function(r) {
var doclist = frappe.model.sync(r.message);
frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
}
});
},
make_expense_claim: function(frm) {
return frappe.call({
method: "erpnext.hr.doctype.expense_claim.expense_claim.get_expense_claim",
args: {
"employee_name": frm.doc.employee,
"company": frm.doc.company,
"employee_advance_name": frm.doc.name,
"posting_date": frm.doc.posting_date,
"paid_amount": frm.doc.paid_amount,
"claimed_amount": frm.doc.claimed_amount
},
callback: function(r) {
const doclist = frappe.model.sync(r.message);
frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
}
});
},
employee: function (frm) {
return frappe.call({
method: "erpnext.hr.doctype.employee_advance.employee_advance.get_due_advance_amount",
args: {
"employee": frm.doc.employee,
"posting_date": frm.doc.posting_date
},
callback: function(r) {
frm.set_value("due_advance_amount",r.message);
}
});
}
});
| JavaScript | 0.000004 | @@ -2314,32 +2314,59 @@
unction (frm) %7B%0A
+%09%09if (frm.doc.employee) %7B%0A%09
%09%09return frappe.
@@ -2364,32 +2364,33 @@
n frappe.call(%7B%0A
+%09
%09%09%09method: %22erpn
@@ -2462,32 +2462,33 @@
amount%22,%0A%09%09%09
+%09
args: %7B%0A
%09%09%09%09%22employe
@@ -2467,32 +2467,33 @@
t%22,%0A%09%09%09%09args: %7B%0A
+%09
%09%09%09%09%22employee%22:
@@ -2510,24 +2510,25 @@
ployee,%0A%09%09%09%09
+%09
%22posting_dat
@@ -2551,27 +2551,29 @@
ing_date%0A%09%09%09
+%09
%7D,%0A
+%09
%09%09%09callback:
@@ -2587,24 +2587,25 @@
on(r) %7B%0A%09%09%09%09
+%09
frm.set_valu
@@ -2639,26 +2639,32 @@
ssage);%0A
+%09
%09%09%09%7D%0A%09%09
+%09
%7D);%0A
+%09%09%7D%0A
%09%7D%0A%7D);%0A
|
61248d29e73f41c606efca4235ee636218a75e99 | replace resource with offering | src/wirecloud/fiware/static/js/wirecloud/FiWare/FiWareCatalogue.js | src/wirecloud/fiware/static/js/wirecloud/FiWare/FiWareCatalogue.js | /*
* (C) Copyright 2012 Universidad Politécnica de Madrid
*
* This file is part of Wirecloud Platform.
*
* Wirecloud Platform is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Wirecloud is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Wirecloud Platform. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
/*global Constants, gettext, LayoutManagerFactory, LogManagerFactory, Wirecloud */
(function () {
"use strict";
var FiWareCatalogue, _onSearchSuccess, _onSearchError;
_onSearchSuccess = function _onSearchSuccess(transport) {
var raw_data = JSON.parse(transport.responseText);
this.onSuccess(raw_data);
};
_onSearchError = function _onSearchError(transport) {
this.onError();
};
FiWareCatalogue = function FiWareCatalogue(options) {
if (options.user != null) {
this.market_user = options.user;
} else {
this.market_user = 'public';
}
this.market_name = options.name;
Object.defineProperty(this, 'permissions', {'value': options.permissions});
};
FiWareCatalogue.prototype.isAllow = function isAllow(action) {
if (action in this.permissions) {
return this.permissions[action];
} else {
return false;
}
};
FiWareCatalogue.prototype.search = function search(onSuccess, onError, options) {
var url, context;
if (options.search_criteria === '' && options.store === 'All stores') {
url = Wirecloud.URLs.FIWARE_RESOURCES_COLLECTION.evaluate({market_user: this.market_user, market_name: this.market_name});
} else if (options.search_criteria !== '' && options.store === 'All stores') {
url = Wirecloud.URLs.FIWARE_FULL_SEARCH.evaluate({market_user: this.market_user, market_name: this.market_name, search_string: options.search_criteria});
} else if (options.search_criteria === '' && options.store !== 'All stores') {
url = Wirecloud.URLs.FIWARE_STORE_RESOURCES_COLLECTION.evaluate({market_user: this.market_user, market_name: this.market_name, store: options.store});
} else {
url = Wirecloud.URLs.FIWARE_STORE_SEARCH.evaluate({market_user: this.market_user, market_name: this.market_name, store: options.store, search_string: options.search_criteria});
}
context = {
'onSuccess': onSuccess,
'onError': onError
};
Wirecloud.io.makeRequest(url, {
method: 'GET',
onSuccess: _onSearchSuccess.bind(context),
onFailure: _onSearchError.bind(context)
});
};
FiWareCatalogue.prototype.is_purchased = function is_purchased(resource) {
return resource.state === 'purchased' || resource.state === 'rated';
};
FiWareCatalogue.prototype.start_purchase = function start_purchase(resource, options) {
if (options == null) {
options = {};
}
var url = Wirecloud.URLs.FIWARE_STORE_START_PURCHASE.evaluate({market_user: this.market_user, market_name: this.market_name, store: resource.store});
Wirecloud.io.makeRequest(
url,
{
contentType: 'application/json',
postBody: JSON.stringify({offering_url: resource.usdl_url}),
onSuccess: function (transport) {
var data = JSON.parse(transport.responseText);
if (typeof options.onSuccess === 'function') {
options.onSuccess(data);
}
}.bind(this),
}
);
};
FiWareCatalogue.prototype.getStores = function getStores(onSuccess, onError) {
var context, url = Wirecloud.URLs.FIWARE_STORE_COLLECTION.evaluate({market_user: this.market_user, market_name: this.market_name});
context = {
onSuccess: onSuccess,
onError: onError
};
Wirecloud.io.makeRequest(url, {
method: 'GET',
onSuccess: _onSearchSuccess.bind(context),
onFailure: _onSearchError.bind(context)
});
};
Wirecloud.FiWare.FiWareCatalogue = FiWareCatalogue;
})();
| JavaScript | 0 | @@ -3235,24 +3235,24 @@
rchased(
-resource
+offering
) %7B%0A
@@ -3262,24 +3262,24 @@
return
-resource
+offering
.state =
@@ -3296,24 +3296,24 @@
sed' %7C%7C
-resource
+offering
.state =
|
0158bf348b570453fc103d605d528dead3215428 | Remove jQuery from safari windows print | source/assets/javascripts/core.js | source/assets/javascripts/core.js | $(document).ready(function() {
$('.print-link a').attr('target', '_blank');
// header search toggle
$('.js-header-toggle').on('click', function(e) {
e.preventDefault();
$($(e.target).attr('href')).toggleClass('js-visible');
$(this).toggleClass('js-hidden');
});
var $searchFocus = $('.js-search-focus');
$searchFocus.each(function(i, el){
if($(el).val() !== ''){
$(el).addClass('focus');
}
});
$searchFocus.on('focus', function(e){
$(e.target).addClass('focus');
});
$searchFocus.on('blur', function(e){
if($(e.target).val() === ''){
$(e.target).removeClass('focus');
}
});
// fix for printing bug in Windows Safari
(function () {
var windows_safari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
$new_styles;
if (windows_safari) {
// set the New Transport font to Arial for printing
$new_styles = $("<style type='text/css' media='print'>" +
"@font-face {" +
"font-family: nta !important;" +
"src: local('Arial') !important;" +
"}" +
"</style>");
document.getElementsByTagName('head')[0].appendChild($new_styles[0]);
}
}());
if (window.GOVUK && GOVUK.addCookieMessage) {
GOVUK.addCookieMessage();
}
});
| JavaScript | 0.000001 | @@ -684,27 +684,8 @@
ari%0A
- (function () %7B%0A
va
@@ -689,26 +689,25 @@
var windows
-_s
+S
afari = (win
@@ -837,26 +837,16 @@
- $new_
style
-s
;%0A%0A
-
if
@@ -854,18 +854,17 @@
(windows
-_s
+S
afari) %7B
@@ -864,18 +864,16 @@
fari) %7B%0A
-
// s
@@ -928,39 +928,80 @@
- $new_styles = $(%22%3Cstyle
+style = document.createElement('style');%0A style.setAttribute('
type
-=
+',
'tex
@@ -1010,89 +1010,89 @@
css'
-
+);%0A style.setAttribute('
media
-=
+',
'print'
-%3E%22 +
+);
%0A
- %22@font-face %7B%22 +%0A %22
+style.innerHTML = '@font-face %7B
font
@@ -1119,35 +1119,9 @@
ant;
-%22 +%0A %22
+
src:
@@ -1131,15 +1131,15 @@
cal(
-'
+%22
Arial
-'
+%22
) !i
@@ -1151,77 +1151,13 @@
ant;
-%22 +%0A %22%7D%22 +%0A %22%3C/style%3E%22);%0A
+ %7D';%0A
@@ -1213,38 +1213,19 @@
ild(
-$new_
style
-s%5B0%5D
);%0A
-
- %7D%0A %7D());
+%7D
%0A%0A
|
1883d07020a4415d16ae06cb850b64155297a06c | change test URL to enable debagging by real devices | app/controllers/index.js | app/controllers/index.js | function login(){
var url = 'http://127.0.0.1/wp/texchange/wp-login.php';
var loginClient = Ti.Network.createHTTPClient({
onload: function(e){
if(this.responseText.match('login_error')){
alert('IDとパスワードの組合せが不正です。');
}else{
var mainWin = Alloy.createController('main',{
loginId: $.userId.value
}).getView();
mainWin.open();
}
},
onerror: function(e){
alert('通信エラーが発生しました。電波状況を確認してください。');
Ti.API.debug("error:" + e.error);
},
timeout: 5000
});
loginClient.open("POST", url);
loginClient.send({
'log': $.userId.value,
'pwd': $.password.value
});
}
$.index.open();
| JavaScript | 0 | @@ -34,43 +34,36 @@
p://
-127.0.0.1/wp/texchange/wp-login.php
+beak.sakura.ne.jp/freecycle/
';%0A%09
|
a6ed47d8d20403fe5fb2f43134fa756e87d1186a | Change user dashboard title | app/controllers/users.js | app/controllers/users.js | var mongoose = require('mongoose')
, User = mongoose.model('User')
//Set up the log in
var login = function (req, res) {
if (req.session.returnTo) {
res.redirect(req.session.returnTo)
delete req.session.returnTo
return
}
res.redirect('/')
}
exports.authCallback = login
exports.session = login
exports.login = function (req, res) {
res.render("users/login", {
title: 'Login',
message: req.flash('error')
})
}
exports.logout = function (req, res) {
req.logout()
user=""
res.redirect("login")
}
exports.display = function (req, res) {
var user = req.user
console.log(req.user)
res.render('users/index', {
title: user,
user: user
})
}
//set up the signup
exports.signup = function (req, res) {
res.render('users/signup', {
title: 'Sign up',
user: new User()
})
}
exports.create = function (req, res) {
var user = new User(req.body)
user.provider = 'local'
user.save(function (err) {
if (err) {
return res.render('users/signup', {
errors: (err.errors),
user: user,
title: 'Sign up'
})
}
// manually login the user once successfully signed up
req.logIn(user, function(err) {
if (err) return next(err)
return res.redirect('/')
})
})
}
exports.user = function (req, res, next, id) {
User
.findOne({ _id : id })
.exec(function (err, user) {
if (err) return next(err)
if (!user) return next(new Error('Failed to load User ' + id))
req.profile = user
next()
})
}
| JavaScript | 0.000015 | @@ -697,24 +697,60 @@
title: user
+.username + %22's Dashboard - Bridges%22
,%0A user
|
ad55e14fbb2f4631009cb6e4c9ff53a973310065 | update TableExamples | examples/containers/app/modules/layout/TableExamples.js | examples/containers/app/modules/layout/TableExamples.js | import React, {Component, Fragment} from 'react';
import round from 'lodash/round';
import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';
import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';
import 'scss/containers/app/modules/layout/TableExamples.scss';
class TableExamples extends Component {
constructor(props) {
super(props);
this.state = {
data: this.generateData(),
sort: null
};
this.columns = [{
headRenderer: 'ID',
bodyRenderer: 'id',
sortable: true,
sortingProp: 'id'
}, {
headRenderer: 'Name',
bodyRenderer: '${firstName} ${lastName}',
sortable: true,
sortingProp: 'firstName'
}, {
headRenderer: 'Age',
headAlign: Table.Align.RIGHT,
bodyRenderer: 'age',
bodyAlign: Table.Align.RIGHT,
footAlign: Table.Align.RIGHT,
sortable: true,
sortingProp: 'age',
footRenderer: () => {
const {data} = this.state;
return (
<Fragment>
<div>Average</div>
<div>{data.reduce((a, b) => a + b.age, 0) / data.length}</div>
</Fragment>
);
}
}, {
headRenderer: 'Deposit',
headAlign: Table.Align.RIGHT,
bodyRenderer: '$ ${deposit}',
bodyAlign: Table.Align.RIGHT,
footAlign: Table.Align.RIGHT,
sortable: true,
sortingProp: 'deposit',
footRenderer: () => {
const {data} = this.state;
return (
<Fragment>
<div>Sum</div>
<div>{data.reduce((a, b) => round(a + b.deposit, 2), 0)}</div>
</Fragment>
);
}
}, {
headerRenderer: 'Status',
bodyRenderer: rowData =>
<Switcher value={!rowData.disabled}
size="small"
onClick={e => e.stopPropagation()}/>
}];
this.pageSizes = [{
value: 10,
text: '10 / page'
}, {
value: 20,
text: '20 / page'
}, {
value: 30,
text: '30 / page'
}, {
value: 40,
text: '40 / page'
}, {
value: 50,
text: '50 / page'
}];
}
generateData = (size = 100) => {
let data = [];
for (let i = 0; i < size; i++) {
data.push({
id: i,
firstName: `firstName${i}`,
lastName: `lastName${i}`,
age: Math.floor(Math.random() * 100),
deposit: round(Math.random() * 1000000, 2),
childrenNum: i === 0 ? 9 : 0
});
}
return data;
};
deleteRow = id => {
const {data} = this.state,
newData = data.filter(item => item.id !== id);
this.setState({
data: newData
});
};
sortHandler = sort => {
this.setState({
sort
});
console.log('Sort Change Value: ', sort);
};
pageChangeHandler = (page, pageSize) => {
console.log(`page: ${page}, pageSize: ${pageSize}`);
};
dataUpdateHandler = currentPageData => {
console.log('Data Update Value: ', currentPageData);
};
selectHandler = (rowData, rowIndex, value) => {
console.log('Select Value: ', rowData);
};
deselectHandler = (rowData, rowIndex, value) => {
console.log('Deselect Value: ', rowData);
};
selectAllHandler = value => {
console.log('Select All Value: ', value);
};
deselectAllHandler = value => {
console.log('Deselect All Value: ', value);
};
changeHandler = value => {
console.log('Changed Value: ', value);
};
clearSort = () => {
this.setState({
sort: null
});
};
render() {
const {data, sort} = this.state;
return (
<div className="example table-examples">
<h2 className="example-title">Table</h2>
<p>
<span>Tables</span>
are used to display data and to organize it.
</p>
<h2 className="example-title">Examples</h2>
<Widget>
<WidgetHeader className="example-header" title="With isPagging"/>
<div className="widget-content">
<div className="example-content">
<p>A simple <code>Table</code> example.</p>
<RaisedButton className="table-action"
theme={RaisedButton.Theme.PRIMARY}
value="Clear Table Sort"
onClick={this.clearSort}/>
<Table data={data}
columns={[...this.columns, {
headerRenderer: 'Action',
bodyRenderer: rowData =>
<IconButton iconCls="fas fa-trash-alt"
onClick={() => this.deleteRow(rowData.id)}/>
}]}
sort={sort}
isHeadFixed={true}
isFootFixed={true}
paggingCountRenderer={count => <span>Self Defined Total Count: {count}</span>}
onSortChange={this.sortHandler}
onPageChange={this.pageChangeHandler}
onDataUpdate={this.dataUpdateHandler}/>
</div>
</div>
</Widget>
{/*<Widget>*/}
{/*<WidgetHeader className="example-header" title="With hasLineNumber and isMultiSelect"/>*/}
{/*<div className="widget-content">*/}
{/*<div className="example-content">*/}
{/*<p>A more complex example.Set the <code>hasLineNumber</code> and <code>isMultiSelect</code>*/}
{/*to true for showLineNumber and checkbox.</p>*/}
{/*<Table data={data}*/}
{/*columns={this.columns}*/}
{/*selectMode={Table.SelectMode.MULTI_SELECT}*/}
{/*selectAllMode={Table.SelectAllMode.CURRENT_PAGE}*/}
{/*paggingSelectedCountVisible={true}*/}
{/*defaultPageSize={20}*/}
{/*pageSizes={this.pageSizes}*/}
{/*useFullPagging={true}*/}
{/*sortingAscIconCls="fas fa-caret-up"*/}
{/*sortingDescIconCls="fas fa-caret-down"*/}
{/*onPageChange={this.pageChangeHandler}*/}
{/*onSelect={this.selectHandler}*/}
{/*onDeselect={this.deselectHandler}*/}
{/*onSelectAll={this.selectAllHandler}*/}
{/*onDeselectAll={this.deselectAllHandler}*/}
{/*onChange={this.changeHandler}/>*/}
{/*</div>*/}
{/*</div>*/}
{/*</Widget>*/}
{/*<Widget>*/}
{/*<WidgetHeader className="example-header" title="Empty"/>*/}
{/*<div className="widget-content">*/}
{/*<div className="example-content">*/}
{/*<Table columns={this.columns}*/}
{/*data={[]}/>*/}
{/*</div>*/}
{/*</div>*/}
{/*</Widget>*/}
<h2 className="example-title">Properties</h2>
<PropTypeDescTable data={doc}/>
</div>
);
}
};
export default TableExamples;
| JavaScript | 0 | @@ -2207,34 +2207,32 @@
head
-er
Renderer: 'Statu
@@ -5527,18 +5527,16 @@
head
-er
Renderer
|
259c14e2432ddf3756fa758f776aaa75502d7ba5 | Make reporting tool use standard input. | utils/report.js | utils/report.js | var commandLineArguments;
// SpiderMonkey
if (typeof scriptArgs === "undefined") {
commandLineArguments = arguments;
} else {
commandLineArguments = scriptArgs;
}
var fileCount = 0;
var passCount = 0;
var finishedCount = 0;
var zeroHashCount = 0;
var histogramNames = ["Not Implemented", "somewhatImplemented", "Uncaught VM-internal", "AVM1 error", "AVM1 warning", "Tag not handled by the parser", "Unable to resolve"]
var histograms = {};
commandLineArguments.forEach(function (file) {
var file = commandLineArguments[0];
read(file).toString().split("\n").forEach(function (k) {
if (k.indexOf("RUNNING:") === 0) {
fileCount++;
} else if (k.indexOf("HASHCODE:") === 0) {
if (k.indexOf(': 0x00000000') > 0) {
zeroHashCount++
} else {
passCount++
}
finishedCount++;
}
for (var i = 0; i < histogramNames.length; i++) {
var n = histogramNames[i];
if (k.indexOf(n) >= 0) {
if (!histograms[n]) histograms[n] = [];
histograms[n].push(k);
}
}
// print(k);
});
});
function histogram(array, min) {
min = min || 0;
var o = Object.create(null);
array.forEach(function (k) {
o[k] || (o[k] = 0);
o[k]++;
});
var a = [];
for (var k in o) {
a.push([k, o[k]]);
}
a = a.filter(function (x) {
return x[1] > min;
});
return a.sort(function (a, b) {
return b[1] - a[1];
});
}
var failCount = fileCount - passCount;
print("File Count: " + fileCount);
print("Pass Count: " + passCount);
print("Fail Count: " + failCount);
print("Zero Hash Count: " + zeroHashCount);
print("Finished Count: " + finishedCount);
histogramNames.forEach(function (n) {
var h = histograms[n];
if (!h) return;
print();
print(n + " Count: " + h.length);
print();
histogram(h, 10).forEach(function (v) {
print(v[1] + ": " + v[0]);
});
}); | JavaScript | 0 | @@ -1,172 +1,4 @@
-var commandLineArguments;%0A// SpiderMonkey%0Aif (typeof scriptArgs === %22undefined%22) %7B%0A commandLineArguments = arguments;%0A%7D else %7B%0A commandLineArguments = scriptArgs;%0A%7D%0A%0A
var
@@ -276,163 +276,96 @@
%7D;%0A%0A
-commandLineArguments.forEach(function (fil
+while (tru
e) %7B%0A
-%0A
var
-file = commandLineArguments%5B0%5D;%0A%0A read(file).toString().split(%22%5Cn%22).forEach(function (k) %7B%0A if (k
+line = readline();%0A if (line === null) %7B%0A break;%0A %7D%0A if (line
.ind
@@ -394,18 +394,16 @@
) %7B%0A
-
fileCoun
@@ -407,18 +407,16 @@
ount++;%0A
-
%7D else
@@ -416,25 +416,28 @@
%7D else if (
-k
+line
.indexOf(%22HA
@@ -455,31 +455,32 @@
== 0) %7B%0A
-
if (
-k
+line
.indexOf(':
@@ -505,18 +505,16 @@
%7B%0A
-
zeroHash
@@ -525,18 +525,16 @@
t++%0A
-
%7D else %7B
@@ -534,18 +534,16 @@
else %7B%0A
-
pa
@@ -556,22 +556,18 @@
t++%0A
- %7D%0A
+%7D%0A
fini
@@ -579,26 +579,22 @@
ount++;%0A
-
%7D%0A
-
for (var
@@ -639,18 +639,16 @@
) %7B%0A
-
var n =
@@ -674,15 +674,16 @@
-
if (
-k
+line
.ind
@@ -694,26 +694,24 @@
(n) %3E= 0) %7B%0A
-
if (!h
@@ -750,18 +750,16 @@
;%0A
-
histogra
@@ -773,22 +773,23 @@
ush(
-k
+line
);%0A
-
%7D%0A
%7D%0A
@@ -788,38 +788,11 @@
%7D%0A
- %7D%0A // print(k);%0A %7D);%0A%7D);
+%7D%0A%7D
%0A%0Afu
|
9e6f2b62f907f4da6966c9c848fbb23b250c7e22 | Use Infrequently Accessed storage class | backup/src/s3.js | backup/src/s3.js | 'use strict'
const aws = require('aws-sdk')
const fs = require('fs')
const S3 = function(options) {
this.s3 = new aws.S3(options)
}
S3.prototype.uploadArchive = function(bucket, path, description, hints) {
const stream = fs.createReadStream(path)
const params = {
'Bucket': bucket,
'Body': stream,
'Key': description,
'ACL': 'private'
}
return new Promise((resolve, reject) => {
this.s3.putObject(params, (err, data) => {
if(err !== null) {
return reject(err, null)
}
return resolve(null, description)
})
})
}
S3.prototype.getInventory = function(bucket) {
return new Promise((resolve, reject) => {
this.s3.listObjects({'Bucket': bucket}, (err, data) => {
if(err !== null) {
return reject(err, null)
}
const results = []
data.Contents.forEach(function(archive) {
results.push({
'id': archive.Key,
'description': archive.Key
})
})
return resolve(null, results)
})
})
}
S3.prototype.getArchive = function(bucket, archiveID) {
return new Promise((resolve, reject) => {
this.s3.getObject({'Bucket': bucket, 'Key': archiveID}, (err, data) => {
if(err !== null) {
return reject(err, null)
}
return resolve(null, {
'key': archiveID,
'description': archiveID,
'body': data.Body
})
})
})
}
S3.prototype.removeArchives = function(bucket, keys) {
const keyObjects = keys.map((key) => { return {'Key': key} })
return new Promise((resolve, reject) => {
this.s3.deleteObjects({'Bucket': bucket,
'Delete': {'Objects': keyObjects}}, (err, data) => {
if(err !== null) {
return resolve(err, null)
}
return resolve(null, data)
})
})
}
exports.S3 = S3
| JavaScript | 0 | @@ -351,16 +351,55 @@
iption,%0A
+ 'StorageClass': 'STANDARD_IA',%0A
|
c4c3efcecd7d96862d8e0f1a3d86654966803118 | Update theme | app/config/index.js | app/config/index.js | angular
.module('DynamoGUI')
.config(config);
config.$inject = ['$mdThemingProvider'];
function config($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue', {
'default': '400', // by default use shade 400 from the pink palette for primary intentions
'hue-1': '100', // use shade 100 for the <code>md-hue-1</code> class
'hue-2': '600', // use shade 600 for the <code>md-hue-2</code> class
'hue-3': 'A100' // use shade A100 for the <code>md-hue-3</code> class
})
// If you specify less than all of the keys, it will inherit from the
// default shades
.accentPalette('blue', {
'default': '200' // use shade 200 for default, and keep all other shades the same
});
}
| JavaScript | 0 | @@ -149,16 +149,25 @@
Provider
+%0A
.theme('
@@ -205,615 +205,45 @@
te('
-blue', %7B%0A 'default': '400', // by default use shade 400 from the pink palette for primary intentions%0A 'hue-1': '100', // use shade 100 for the %3Ccode%3Emd-hue-1%3C/code%3E class%0A 'hue-2': '600', // use shade 600 for the %3Ccode%3Emd-hue-2%3C/code%3E class%0A 'hue-3': 'A100' // use shade A100 for the %3Ccode%3Emd-hue-3%3C/code%3E class%0A %7D)%0A // If you specify less than all of the keys, it will inherit from the%0A // default shades%0A .accentPalette('blue', %7B%0A 'default': '200' // use shade 200 for default, and keep all other shades the same%0A %7D
+red')%0A .accentPalette('orange'
);%0A%7D
|
81ad42b3fcb82e8e1064c41c6efabbda668d14d1 | Disable InsertInlineNodeCommand in certain scenarios. | packages/inline-node/InsertInlineNodeCommand.js | packages/inline-node/InsertInlineNodeCommand.js | import Command from '../../ui/Command'
/**
Reusable command implementation for inserting inline nodes.
@class InsertInlineNodeCommand
@example
Define a custom command.
```
class AddXRefCommand extends InsertInlineNodeCommand {
createNodeData() {
return {
attributes: {'ref-type': 'bibr'},
targets: [],
label: '???',
type: 'xref'
}
}
}
```
Register it in your app using the configurator.
```
config.addCommand('add-xref', AddXRefCommand, {nodeType: 'xref'})
```
*/
class InsertInlineNodeCommand extends Command {
/**
@param config Takes a config object, provided on registration in configurator
*/
constructor(...args) {
super(...args)
if (!this.config.nodeType) {
throw new Error('Every InlineInlineNodeCommand must have a nodeType')
}
}
/**
Determine command state for inline node insertion. Command is enabled
if selection is a property selection.
*/
getCommandState(params) {
let sel = params.selection
let newState = {
disabled: !sel.isPropertySelection(),
active: false
}
return newState
}
/**
Insert new inline node at the current selection
*/
execute(params) {
let state = this.getCommandState(params)
if (state.disabled) return
let editorSession = this._getEditorSession(params)
editorSession.transaction((tx)=>{
let nodeData = this.createNodeData(tx, params)
tx.insertInlineNode(nodeData)
})
}
createNodeData(tx) { // eslint-disable-line
return {
type: this.config.nodeType
}
}
}
export default InsertInlineNodeCommand
| JavaScript | 0 | @@ -1014,68 +1014,241 @@
let
-sel = params.selection%0A let newState = %7B%0A disabled:
+newState = %7B%0A disabled: this.isDisabled(params),%0A active: false%0A %7D%0A return newState%0A %7D%0A%0A isDisabled(params) %7B%0A let sel = params.selection%0A let selectionState = params.editorSession.getSelectionState()%0A if (
!sel
@@ -1273,36 +1273,127 @@
on()
-,
+) %7B
%0A
-active: fals
+return true%0A %7D%0A if (this.config.disableCollapsedCursor && sel.isCollapsed()) %7B%0A return tru
e%0A %7D%0A
@@ -1388,34 +1388,195 @@
e%0A %7D%0A
+%0A
-return newStat
+// We don't allow inserting an inline node on top of an existing inline%0A // node.%0A if (selectionState.isInlineNodeSelection()) %7B%0A return true%0A %7D%0A return fals
e%0A %7D%0A%0A
@@ -1826,10 +1826,12 @@
(tx)
+
=%3E
+
%7B%0A
|
c692d88c11a8c5557c65632d9e59d32666fab070 | add line endings to fake console in ff | mini/pilot/console.js | mini/pilot/console.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
// These are the functions that are available in Chrome 4/5, Safari 4
// and Firefox 3.6. Don't add to this list without checking browser support
var NAMES = [
"assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd",
"info", "log", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"
];
if ('console' in this) {
// For each of the console functions, copy them if they exist, stub if not
NAMES.forEach(function(name) {
exports[name] = Function.prototype.bind.call(console[name], console);
});
}
else {
NAMES.forEach(function(name) {
exports[name] = function() {
dump(Array.prototype.join.apply(arguments, [ ', ' ]));
};
});
}
});
| JavaScript | 0 | @@ -2442,16 +2442,23 @@
', ' %5D)
+ + '%5Cn'
);%0A
|
8b62f58b690fcd2373cfe5e9ef3ebdc0c2f03985 | Fix optional options | plugins/c9.ide.dialog.common/alert_internal.js | plugins/c9.ide.dialog.common/alert_internal.js | define(function(require, module, exports) {
main.consumes = ["Dialog", "util", "dialog.alert", "metrics"];
main.provides = ["dialog.alert_internal"];
return main;
function main(options, imports, register) {
var Dialog = imports.Dialog;
var util = imports.util;
var metrics = imports.metrics;
var alertWrapper = imports["dialog.alert"];
/***** Initialization *****/
var plugin = new Dialog("Ajax.org", main.consumes, {
name: "dialog.alert_internal",
allowClose: true,
modal: true,
elements: [
{ type: "checkbox", id: "dontshow", caption: "Don't show again", visible: false },
{ type: "filler" },
{ type: "button", id: "ok", caption: "OK", "default": true, onclick: function(){ plugin.hide() } }
]
});
alertWrapper.alertInternal = plugin;
/***** Methods *****/
function show(title, header, msg, onhide, options) {
metrics.increment("dialog.error");
return plugin.queue(function(){
if (header === undefined) {
plugin.title = "Notice";
header = title;
msg = msg || "";
}
else {
plugin.title = title;
}
plugin.heading = options && options.isHTML ? header : util.escapeXml(header);
plugin.body = options && options.isHTML ? msg : (util.escapeXml(msg) || "")
.replace(/\n/g, "<br />")
.replace(/(https?:\/\/[^\s]*\b)/g, "<a href='$1' target='_blank'>$1</a>");
plugin.getElement("ok").setCaption(options.yes || "OK");
plugin.update([
{ id: "dontshow", visible: options && options.showDontShow }
]);
plugin.once("hide", function(){
onhide && onhide();
});
});
}
/***** Register *****/
/**
* @internal Use dialog.alert instead
* @ignore
*/
plugin.freezePublicAPI({
/**
* @readonly
*/
get dontShow(){
return plugin.getElement("dontshow").value;
},
/**
* Show an alert dialog.
*
* @param {String} [title] The title to display
* @param {String} header The header to display
* @param {String} [msg] The message to display
* @param {Function} [onhide] The function to call after it's closed.
*/
show: show
});
register("", {
"dialog.alert_internal": plugin
});
}
}); | JavaScript | 0.000338 | @@ -1046,24 +1046,74 @@
options) %7B%0A
+ options = options %7C%7C %7B%7D;%0A %0A
@@ -1143,24 +1143,24 @@
og.error%22);%0A
-
@@ -1499,27 +1499,16 @@
eading =
- options &&
options
@@ -1579,27 +1579,16 @@
n.body =
- options &&
options
@@ -1911,16 +1911,16 @@
pdate(%5B%0A
+
@@ -1961,19 +1961,8 @@
ble:
- options &&
opt
|
0fff202f5c64f47a78bf7faa834a53f5adc59b7a | Remove junk code and comments. | libs/runway-browser.js | libs/runway-browser.js |
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goForward(href)
doRoute(href)
return false
}
return true
}
function doRoute(href){
var ctrl = runway.finder(href)
if (ctrl) ctrl()
}
function goForward(url){
var title = Math.random().toString().split('.')[1]
if (history.pushState) history.pushState({url:url, title:title}, null, url)
else location.assign(url)
}
window.addEventListener('popstate',function(event){
doRoute(event.state.url)
})
window.onpopstate = function(event){
// doRoute(event.state.url)
// console.log( event )
// window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){
history.replaceState( {url:location.pathname}, null, location.pathname )
var ctrl = runway.finder(location.pathname)
if (ctrl) ctrl()
}
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
| JavaScript | 0 | @@ -646,61 +646,8 @@
l)%7B%0A
- var title = Math.random().toString().split('.')%5B1%5D%0A
if
@@ -697,21 +697,8 @@
:url
-, title:title
%7D, n
@@ -742,91 +742,8 @@
%0A%7D%0A%0A
-window.addEventListener('popstate',function(event)%7B%0A doRoute(event.state.url)%0A%7D)%0A%0A
wind
@@ -774,21 +774,16 @@
(event)%7B
-%0A //
doRoute
@@ -803,131 +803,9 @@
url)
-%0A // console.log( event )%0A // window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))%0A
+
%7D%0A%0Af
@@ -821,16 +821,19 @@
nit()%7B%0A
+ //
history
@@ -904,96 +904,37 @@
)%0A
-var ctrl = runway.finder(location.pathname)%0A if (ctrl) ctrl()%0A%7D%0A// setTimeout(init,100)
+doRoute(location.pathname)%0A%7D%0A
%0Awin
|
13773f8c87885bb4c60c0fca6f5dd8bd21351eaa | Remove useless property. | app/entity/proxy.js | app/entity/proxy.js | 'use strict';
module.exports = (function () {
var _ = require('../lib/helper')._,
Q = require('q'),
path = require('path'),
spawn = require('child_process').spawn,
// running = require('is-running'),
binPath = path.join(process.env.PWD, 'bin'),
db = require('./../lib/db'),
eventEmitter_ = new (require('events').EventEmitter)(),
proxyChilds = {},
mockChilds = {};
var Proxy = function (properties) {
var self = this;
this._id =
this._port =
this._target =
this._status =
this._isRecording;
_.privateMerge(this, properties);
// set to true if some childs are started
this._isRunning = _.has(proxyChilds, this._id);
this._isMocked = _.has(mockChilds, this._id);
// enable the proxy if proxy or mock is running
this._isEnabled = this._isRunning || this._isMocked;
// update the disable flag in DB
db.model('Proxy').get(this._id, function (err, Proxy) {
if (Proxy) {
Proxy.isEnabled = self._isEnabled;
Proxy.save(db.log);
}
});
};
/**
* Add a proxy in DB.
*/
Proxy.prototype.add = function (callback) {
db.model('Proxy').create([_.publicProperties(this)], callback);
};
/**
* Stop all child processes and remove a proxy from DB.
*/
Proxy.prototype.remove = function (callback) {
var self = this;
this.stopAll().then(function () {
db.model('Proxy').find({id: self._id}).remove(callback);
});
};
/**
* Start the proxy.
*/
Proxy.prototype.startProxy = function () {
proxyChilds[this._id] = spawn('node', [
path.join(binPath, 'proxy.js'),
'--target=' + this._target,
'--port=' + this._port,
'--proxyId=' + this._id
]);
this.bindEvent('Proxy', proxyChilds, this._id);
};
/**
* Stop the child process.
*/
Proxy.prototype.stopProxy = function () {
var deferred = Q.defer();
if (proxyChilds[this._id]) {
proxyChilds[this._id].kill('SIGHUP');
proxyChilds[this._id].on('exit', function () {
deferred.resolve();
});
}
return deferred.promise;
};
/**
* Start the mock
*/
Proxy.prototype.startMock = function () {
mockChilds[this._id] = spawn('node', [
path.join(binPath, 'mock.js'),
'--port=' + this._port,
'--proxyId=' + this._id
]);
this.bindEvent('Mock', mockChilds, this._id);
};
/**
* Stop the child process.
*/
Proxy.prototype.stopMock = function () {
var deferred = Q.defer();
if (mockChilds[this._id]) {
mockChilds[this._id].kill('SIGHUP');
mockChilds[this._id].on('exit', function () {
deferred.resolve();
});
}
return deferred.promise;
};
/**
* Stop all processes.
*/
Proxy.prototype.stopAll = function () {
var promises = [];
if (this._isMocked) {
promises.push(this.stopMock());
}
if (this._isRunning) {
promises.push(this.stopProxy());
}
return Q.all(promises);
};
/**
* Bind child events to websocket / logging.
*/
Proxy.prototype.bindEvent = function (label, childs, id) {
var self = this,
child = childs[id];
console.log(label + ' PID', child.pid);
child.on('exit', function () {
delete childs[self._id];
self['_log' + label](label + ' has been stopped.');
});
child.on('error', function () {
console.log('error', arguments);
});
// log stdout
child.stdout.on('data', function (data) {
self['_log' + label](data);
});
// log stderr
child.stderr.on('data', function (data) {
self['_log' + label](data, 'error');
});
};
/**
* Disable/enable the recording for the proxy.
*/
Proxy.prototype.toggleRecording = function (callback) {
var self = this;
db.model('Proxy').get(this._id, function (err, Proxy) {
Proxy.isRecording = self._isRecording;
Proxy.save(function (err) {
callback(err);
});
});
};
/**
* Disable/enable the mock for the proxy.
*/
Proxy.prototype.toggleMock = function () {
var self = this,
promises = [];
if (this._isMocked) {
promises.push(
this.stopMock().then(function () {
self.startProxy();
})
);
}
if (this._isRunning) {
promises.push(
this.stopProxy().then(function () {
self.startMock();
})
);
}
return Q.all(promises);
};
/**
* Enable/disable the proxy.
*/
Proxy.prototype.toggleEnable = function (callback) {
var self = this;
db.model('Proxy').get(this._id, function (err, Proxy) {
Proxy.isEnabled = self._isEnabled;
// when adding a proxy, we don't run the proxy by default,
// we run the mock => the proxy is "mocked" by default.
if (!Proxy.isEnabled) {
self.startMock();
} else {
// when disabling the Proxy, we stop all
self.stopAll();
}
Proxy.save(function (err) {
callback(err);
});
});
};
/**
* Log proxy event.
*/
Proxy.prototype._logProxy = function (message, type) {
this._log(message, type || 'infoProxy');
};
/**
* Log mock event.
*/
Proxy.prototype._logMock = function (message, type) {
this._log(message, type || 'infoMock');
};
/**
* Log error.
* Prefix the message by "Error:" to pass the filter in Angular.
* See LogsCtrl.
*/
Proxy.prototype._logError = function (message) {
this._log('Error: ' + message, 'error');
};
/**
* Emit an event for mock logging.
* @param {String|Buffer} message Message
* @param {String} type A choice between ['info', 'error']
*/
Proxy.prototype._log = function (message, type) {
if (message instanceof Buffer) {
message = message.toString('utf8');
}
eventEmitter_.emit('log', {
message: message,
type: (type || 'info')
});
};
/**
* Return the event emitter for the outside communication.
*/
Proxy.eventEmitter = function () {
return eventEmitter_;
};
/**
* List all proxies from DB.
*/
Proxy.list = function (callback) {
db.model('Proxy').find({}, function (err, proxies) {
callback(err, _.map(proxies, function (properties) {
return new Proxy(properties);
}));
});
};
return Proxy;
})();
| JavaScript | 0 | @@ -600,27 +600,8 @@
t =%0A
- this._status =%0A
|
7332cf5135f96132eab846dca4438545ffd5dbdc | Fix tests for restricted labelling | spec/shared/common/views/spec.module.js | spec/shared/common/views/spec.module.js | define([
'common/views/module',
'extensions/collections/collection',
'extensions/models/model',
'extensions/views/view'
],
function (ModuleView, Collection, Model, View) {
describe("ModuleView", function () {
var moduleView, model;
var getContent = function () {
return moduleView.$el[0].outerHTML.replace(/>\s+?</g, '><');
};
beforeEach(function() {
var Visualisation = View.extend({
render: function () {
this.$el.html('test content');
}
});
model = new Model({
title: 'Title'
});
var collection = new Collection();
moduleView = new ModuleView({
visualisationClass: Visualisation,
className: 'testclass',
collection: collection,
model: model
});
});
it("renders a module", function () {
moduleView.render();
expect(getContent()).toEqual('<section class="testclass"><h1>Title</h1><div class="visualisation">test content</div></section>');
});
it("renders a module with description", function () {
model.set('description', 'Description');
moduleView.render();
expect(getContent()).toEqual('<section class="testclass"><h1>Title</h1><h2>Description</h2><div class="visualisation">test content</div></section>');
});
it("renders a module with description and info", function () {
model.set('description', 'Description');
model.set('info', ['Info line 1', 'Info line 2']);
moduleView.render();
expect(getContent()).toEqual('<section class="testclass"><h1>Title</h1><aside class="more-info"><span class="more-info-link">more info</span><ul><li>Info line 1</li><li>Info line 2</li></ul></aside><h2>Description</h2><div class="visualisation">test content</div></section>');
});
it("renders an SVG-based module as a fallback element on the server", function () {
jasmine.serverOnly(function () {
moduleView.requiresSvg = true;
moduleView.url = '/test/url';
moduleView.render();
// normalise jsdom and phantomjs output
var content = getContent()
.replace('<', '<')
.replace('>', '>')
.replace(' />', '/>');
expect(content).toEqual('<section class="testclass"><h1>Title</h1><div class="visualisation-fallback" data-src="/test/url.png"><noscript><img src="/test/url.png"/></noscript></div></section>');
});
});
it("renders an SVG-based module as normal on the client", function () {
jasmine.clientOnly(function () {
moduleView.requiresSvg = true;
moduleView.render();
expect(getContent()).toEqual('<section class="testclass"><h1>Title</h1><div class="visualisation">test content</div></section>');
});
});
it("renders a module with classes module-banner and restricted-data-banner when Stagecraft sets restricted_data to true", function () {
model.set('restricted_data', true);
moduleView.render();
expect(getContent()).toEqual('<section class="testclass module-banner restricted-data-banner"><div class="module-banner-text"><p>This section contains <strong>commercially licensed data</strong>. Do not share or redistribute.</p></div><h1>Title</h1><div class="visualisation">test content</div></section>');
});
it("renders a module without classes module-banner and restricted-data-banner when Stagecraft returns restricted_data false", function () {
model.set('restricted_data', false);
moduleView.render();
expect(getContent()).toEqual('<section class="testclass"><h1>Title</h1><div class="visualisation">test content</div></section>');
});
});
});
| JavaScript | 0.000042 | @@ -3208,16 +3208,35 @@
stribute
+ outside government
.%3C/p%3E%3C/d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.