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 |
|---|---|---|---|---|---|---|---|
084df32bd81f32b8bf082a2c7353242f505e9e8f | Fix SSL WebSockets in dev server | server/proxies/api.js | server/proxies/api.js | module.exports = function(app, options) {
var path = require('path');
var ForeverAgent = require('forever-agent');
var HttpProxy = require('http-proxy');
var httpServer = options.httpServer;
var config = require('../../config/environment')().APP;
var proxy = HttpProxy.createProxyServer({
ws: true,
xfwd: false,
target: config.apiServer,
});
proxy.on('error', onProxyError);
httpServer.on('upgrade', function proxyWsRequest(req, socket, head) {
console.log('WS Proxy', req.method, 'to', req.url);
proxy.ws(req, socket, head);
});
console.log('Proxying Rancher to', config.apiServer);
var apiPath = config.apiEndpoint;
app.use(apiPath, function(req, res, next) {
// include root path in proxied request
req.url = path.join(apiPath, req.url);
req.headers['X-Forwarded-Proto'] = req.protocol;
console.log('API Proxy', req.method, 'to', req.url);
proxy.web(req, res);
});
var catalogPath = config.catalogEndpoint;
// Default catalog to the regular API
var server = config.catalogServer || config.apiServer;
console.log('Proxying Catalog to', server);
app.use(catalogPath, function(req, res, next) {
var catalogProxy = HttpProxy.createProxyServer({
xfwd: false,
target: server
});
catalogProxy.on('error', onProxyError);
// include root path in proxied request
req.url = path.join(catalogPath, req.url);
console.log('Catalog Proxy', req.method, 'to', req.url);
catalogProxy.web(req, res);
});
};
function onProxyError(err, req, res) {
console.log('Proxy Error: on', req.method,'to', req.url,':', err);
var error = {
type: 'error',
status: 500,
code: 'ProxyError',
message: 'Error connecting to proxy',
detail: err.toString()
}
if ( req.upgrade )
{
res.end();
}
else
{
res.writeHead(500, {'Content-Type': 'application/json'});
res.end(JSON.stringify(error));
}
}
| JavaScript | 0.00021 | @@ -519,32 +519,112 @@
'to', req.url);%0A
+ if ( socket.ssl ) %7B%0A req.headers%5B'X-Forwarded-Proto'%5D = 'https';%0A %7D%0A
proxy.ws(req
|
a4978d9284288031cb83e55e562bcf8af6b0dfe5 | Update main.js | assets/js/main.js | assets/js/main.js | JavaScript | 0.000001 | @@ -0,0 +1,29 @@
+var React = require('react');
| |
4827f18c6b47929696184cd5feaafe52947135a4 | Update core.js | server/public/core.js | server/public/core.js | var LOGNS = 'DeezerKids:';
var APP_ID = '236482';
var CHANNEL_URL = 'http://www.beup2date.com/DeezerKids/channel.html';
var DeezerKids = angular.module('DeezerKids', []);
DeezerKids.controller("AppController", function($scope, $route, $routeParams, $location, $rootScope, $http) {
// Init config
$scope.login = false;
// when landing on the page, get all accounts and show them
$http.get('/api/accounts')
.success(function(data) {
if (data.length == 1) {
$scope.account = data[0];
$scope.login = true;
} else {
$scope.login = false;
}
console.log(LOGNS, data);
})
.error(function(data) {
console.log(LOGNS, 'Error: ' + data);
});
// Global for test purpose
rootScope = $rootScope;
scope = $scope;
DZ.init({
appId: APP_ID,
channelUrl: CHANNEL_URL
});
// --------------------------------------------------- Methods
$scope.login = function() {
console.log(LOGNS, 'login clicked');
DZ.login(function(response) {
if (response.authResponse) {
console.log(LOGNS, 'successfully logged in with Token ', response.authResponse.accessToken);
$scope.account.accessToken = response.authResponse.accessToken;
$scope.account.expire = response.authResponse.expire;
$scope.account.userID = response.userID;
createAccount();
} else {
console.log(LOGNS, 'login aborded by user');
$scope.login = false;
}
}, {scope: 'basic_access,email,offline_access,manage_library'});
};
$scope.logout = function() {
console.log(LOGNS, 'logout clicked');
};
// save the account after login
function createAccount() {
$http.post('/api/accounts', $scope.account)
.success(function(data) {
console.log(LOGNS, 'Account saved to database', data);
$scope.login = true;
})
.error(function(data) {
console.log(LOGNS, 'Error while saving account: ' + data);
$scope.login = false;
});
};
// delete the account after logout
function deleteAccount(id) {
$http.delete('/api/accounts/' + id)
.success(function(data) {
$scope.account = { };
console.log(LOGNS, 'Account successfully deleted', data);
$scope.login = false;
})
.error(function(data) {
console.log(LOGNS, 'Error while deleting account: ' + data);
});
};
});
| JavaScript | 0.000001 | @@ -461,24 +461,76 @@
gth == 1) %7B%0A
+%09%09%09%09console.log(LOGNS, 'Account already loggedin');%0A
%09%09%09%09$scope.a
@@ -580,24 +580,76 @@
%09%09%09%7D else %7B%0A
+%09%09%09%09console.log(LOGNS, 'Account not loggedin yet');%0A
%09%09%09%09$scope.l
@@ -900,16 +900,78 @@
NEL_URL%0A
+%09%09console.log(LOGNS, 'Deezer-API initialiazed successfully');%0A
%09%7D);%0A%0A%09/
|
cbb0d7c620526c85a696d5127adc8b3f90cfd027 | Update core.js | server/public/core.js | server/public/core.js | var LOGNS = 'DeezerKids:';
var APP_ID = '236482';
var CHANNEL_URL = 'http://www.beup2date.com/DeezerKids/channel.html';
var DeezerKids = angular.module('DeezerKids', []);
DeezerKids.controller('AppController', function($scope, $rootScope, $http) {
//////////////////////////////////////////////////////
// STEP1: check if device setup already completed
//////////////////////////////////////////////////////
$scope.completed = false;
$scope.step = 1;
$http.get('/api/account')
.success(function(data) {
if (data) {
console.log(LOGNS, 'DeezerKids setup already completed');
$scope.account = data;
$scope.completed = true;
} else {
console.log(LOGNS, 'Starting DeezerKids setup');
$scope.completed = false;
$scope.step = 2;
}
console.log(LOGNS, data);
})
.error(function(data) {
console.log(LOGNS, 'Error: ' + data);
});
//////////////////////////////////////////////////////
// STEP2: setup WLAN connection
//////////////////////////////////////////////////////
$scope.setupWLAN = function() {
};
//////////////////////////////////////////////////////
// STEP3: connect to Deezer account
//////////////////////////////////////////////////////
$scope.connectAccount = function() {
$http.get('http://beup2date.com/DeezerKids/devices/123')
.success(function(data) {
console.log(LOGNS, data);
})
.error(function(data) {
console.log(LOGNS, 'Error: ' + data);
});
};
//////////////////////////////////////////////////////
// STEP4: select playlist from Deezer account
//////////////////////////////////////////////////////
$scope.selectPlaylist = function() {
DZ.init({
appId: APP_ID,
channelUrl: CHANNEL_URL
});
console.log(LOGNS, 'Deezer-API initialiazed successfully');
console.log(LOGNS, 'login clicked');
};
//////////////////////////////////////////////////////
// STEP5: save account data to mongodb
//////////////////////////////////////////////////////
$scope.saveAccount = function() {
$http.post('/api/accounts', $scope.account)
.success(function(data) {
console.log(LOGNS, 'Account saved to database', data);
$scope.login = true;
})
.error(function(data) {
console.log(LOGNS, 'Error while saving account: ' + data);
$scope.login = false;
});
};
//////////////////////////////////////////////////////
// COMPLETED: setup already completed
//////////////////////////////////////////////////////
$scope.deleteAccount = function deleteAccount() {
$http.delete('/api/account')
.success(function(data) {
$scope.account = { };
console.log(LOGNS, 'Account successfully deleted', data);
$scope.login = false;
})
.error(function(data) {
console.log(LOGNS, 'Error while deleting account: ' + data);
});
};
// --------------------------------------------------- Methods
$scope.doLogin = function() {
console.log(LOGNS, 'login clicked');
DZ.login(function(response) {
if (response.authResponse) {
console.log(LOGNS, 'successfully logged in with Token ', response.authResponse.accessToken);
$scope.account.accessToken = response.authResponse.accessToken;
$scope.account.expire = response.authResponse.expire;
$scope.account.userID = response.userID;
createAccount();
} else {
console.log(LOGNS, 'login aborded by user');
$scope.login = false;
}
}, {scope: 'basic_access,email,offline_access,manage_library'});
};
});
| JavaScript | 0.000001 | @@ -483,20 +483,17 @@
nt')
-%0A%09%09.success(
+.then(%0A%09%09
func
@@ -795,19 +795,12 @@
%0A%09%09%7D
-)
+,
%0A%09%09
-.error(
func
|
adc12791f253b68dfc4438f8550f9064fc1591c0 | Remove unnecessary comment from Javascript file | assets/js/main.js | assets/js/main.js | /**
* Project: masterroot24.github.io
*/
$(document).ready(function () {
/* Add the current year to the footer */
function getYear() {
var d = new Date();
var n = d.getFullYear();
return n.toString();
}
$('#year').html(getYear());
/* Enable Bootstrap tooltips */
$("body").tooltip({ selector: '[data-toggle=tooltip]' });
/* Avatar Hover Zoom */
$("#about-avatar").hover(function () {
$(this).switchClass('avatar-md', 'avatar-lg');
},
function () {
$(this).switchClass('avatar-lg', 'avatar-md');
}
);
/* goBack() function */
function goBack() {
window.history.back()
}
});
| JavaScript | 0 | @@ -1,48 +1,4 @@
-/**%0A * Project: masterroot24.github.io%0A */%0A%0A
$(do
|
859f161280414413e794108412f6fb06daac08e9 | make debugbar index page load in iframe | assets/toolbar.js | assets/toolbar.js | (function () {
'use strict';
var findToolbar = function () {
return document.querySelector('#yii-debug-toolbar');
},
ajax = function (url, settings) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
settings = settings || {};
xhr.open(settings.method || 'GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Accept', 'text/html');
xhr.onreadystatechange = function (state) {
if (xhr.readyState === 4) {
if (xhr.status === 200 && settings.success) {
settings.success(xhr);
} else if (xhr.status != 200 && settings.error) {
settings.error(xhr);
}
}
};
xhr.send(settings.data || '');
},
url,
div,
toolbarEl = findToolbar(),
barSelector = '.yii-debug-toolbar__bar',
viewSelector = '.yii-debug-toolbar__view',
blockSelector = '.yii-debug-toolbar__block',
toggleSelector = '.yii-debug-toolbar__toggle',
externalSelector = '.yii-debug-toolbar__external',
CACHE_KEY = 'yii-debug-toolbar',
ACTIVE_STATE = 'active',
activeClass = 'yii-debug-toolbar_active',
iframeActiveClass = 'yii-debug-toolbar_iframe_active',
titleClass = 'yii-debug-toolbar__title',
blockClass = 'yii-debug-toolbar__block',
blockActiveClass = 'yii-debug-toolbar__block_active';
if (toolbarEl) {
url = toolbarEl.getAttribute('data-url');
ajax(url, {
success: function (xhr) {
div = document.createElement('div');
div.innerHTML = xhr.responseText;
toolbarEl.parentNode.replaceChild(div, toolbarEl);
showToolbar(findToolbar());
},
error: function (xhr) {
toolbarEl.innerHTML = xhr.responseText;
}
});
}
function showToolbar(toolbarEl) {
var barEl = toolbarEl.querySelector(barSelector),
viewEl = toolbarEl.querySelector(viewSelector),
toggleEl = toolbarEl.querySelector(toggleSelector),
externalEl = toolbarEl.querySelector(externalSelector),
blockEls = barEl.querySelectorAll(blockSelector),
iframeEl = viewEl.querySelector('iframe'),
iframeHeight = function () {
return (window.innerHeight * 0.7) + 'px';
},
isIframeActive = function () {
return toolbarEl.classList.contains(iframeActiveClass);
},
showIframe = function (href) {
toolbarEl.classList.add(iframeActiveClass);
iframeEl.src = externalEl.href = href;
viewEl.style.height = iframeHeight();
},
hideIframe = function () {
toolbarEl.classList.remove(iframeActiveClass);
removeActiveBlocksCls();
externalEl.href = '#';
viewEl.style.height = '';
},
removeActiveBlocksCls = function () {
[].forEach.call(blockEls, function (el) {
el.classList.remove(blockActiveClass);
});
},
toggleToolbarClass = function (className) {
if (toolbarEl.classList.contains(className)) {
toolbarEl.classList.remove(className);
} else {
toolbarEl.classList.add(className);
}
},
toggleStorageState = function (key, value) {
if (window.localStorage) {
var item = localStorage.getItem(key);
if (item) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, value);
}
}
},
restoreStorageState = function (key) {
if (window.localStorage) {
return localStorage.getItem(key);
}
},
togglePosition = function () {
if (isIframeActive()) {
hideIframe();
} else {
toggleToolbarClass(activeClass);
toggleStorageState(CACHE_KEY, ACTIVE_STATE);
}
};
toolbarEl.style.display = 'block';
if (restoreStorageState(CACHE_KEY) == ACTIVE_STATE) {
toolbarEl.classList.add(activeClass);
}
window.onresize = function () {
if (toolbarEl.classList.contains(iframeActiveClass)) {
viewEl.style.height = iframeHeight();
}
};
barEl.onclick = function (e) {
var target = e.target,
block = findAncestor(target, blockClass);
if (block && !block.classList.contains(titleClass)
&& e.which !== 2 && !e.ctrlKey // not mouse wheel and not ctrl+click
) {
while (target !== this) {
if (target.href) {
removeActiveBlocksCls();
block.classList.add(blockActiveClass);
showIframe(target.href);
}
target = target.parentNode;
}
e.preventDefault();
}
};
toggleEl.onclick = togglePosition;
}
function findAncestor(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
})();
| JavaScript | 0 | @@ -5103,49 +5103,8 @@
lock
- && !block.classList.contains(titleClass)
%0A
|
e5d50892ccf34dc573f1f95b1e9a497e3eef2042 | Add moisture sensor | app/views/room-compositeview.js | app/views/room-compositeview.js | SensorCollection = require('models/sensor-collection');
module.exports = RoomView = Backbone.Marionette.CompositeView.extend({
template : 'views/templates/room',
getItemView : function(sensor){
console.log("Getting itemView");
if(sensor.get('model') == 'temperature') return TemperatureView;
if(sensor.get('model') == 'door') return DoorView;
},
//itemViewContainer : 'div.sensors',
appendHtml: function(collectionView, itemView, index){
console.log(itemView.el);
collectionView.$("div.sensors.row").append(itemView.el);
},
initialize : function(){
this.collection = new SensorCollection(this.model.get('sensors'));
console.log("Collection :" );
console.log(this.collection);
}
});
| JavaScript | 0.000001 | @@ -49,16 +49,17 @@
tion');%0A
+%0A
module.e
@@ -347,16 +347,80 @@
orView;%0A
+%09%09if(sensor.get('model') == 'moisture')%09%09%09return MoistureView;%0A%0A
%09%7D,%0A%09//i
|
9d1e3c21f49a6a78127fd560ddd214c0949687a8 | use transformed tex coords for roughness map | systems/renderer/pex-shaders/shaders/chunks/metallic-roughness.glsl.js | systems/renderer/pex-shaders/shaders/chunks/metallic-roughness.glsl.js | export default /* glsl */ `
#ifdef USE_METALLIC_ROUGHNESS_WORKFLOW
uniform float uMetallic;
uniform float uRoughness;
// Source: Google/Filament/Overview/4.8.3.3 Roughness remapping and clamping, 07/2019
// Minimum roughness to avoid division by zerio when 1/a^2 and to limit specular aliasing
// This could be 0.045 when using single precision float fp32
#define MIN_ROUGHNESS 0.089
#ifdef USE_METALLIC_ROUGHNESS_MAP
// R = ?, G = roughness, B = metallic
uniform sampler2D uMetallicRoughnessMap;
#ifdef USE_METALLIC_ROUGHNESS_MAP_TEX_COORD_TRANSFORM
uniform mat3 uMetallicRoughnessMapTexCoordTransform;
#endif
// TODO: sampling the same texture twice
void getMetallic(inout PBRData data) {
#ifdef USE_METALLIC_ROUGHNESS_MAP_TEX_COORD_TRANSFORM
vec2 texCoord = getTextureCoordinates(data, METALLIC_ROUGHNESS_MAP_TEX_COORD_INDEX, uMetallicRoughnessMapTexCoordTransform);
#else
vec2 texCoord = getTextureCoordinates(data, METALLIC_ROUGHNESS_MAP_TEX_COORD_INDEX);
#endif
vec4 texelColor = texture2D(uMetallicRoughnessMap, texCoord);
data.metallic = uMetallic * texelColor.b;
data.roughness = uRoughness * texelColor.g;
}
void getRoughness(inout PBRData data) {
// NOP, already read in getMetallic
}
#else
#ifdef USE_METALLIC_MAP
uniform sampler2D uMetallicMap; //assumes linear, TODO: check gltf
#ifdef USE_METALLIC_MAP_TEX_COORD_TRANSFORM
uniform mat3 uMetallicMapTexCoordTransform;
#endif
void getMetallic(inout PBRData data) {
#ifdef USE_METALLIC_MAP_TEX_COORD_TRANSFORM
vec2 texCoord = getTextureCoordinates(data, METALLIC_MAP_TEX_COORD_INDEX, uMetallicMapTexCoordTransform);
#else
vec2 texCoord = getTextureCoordinates(data, METALLIC_MAP_TEX_COORD_INDEX);
#endif
data.metallic = uMetallic * texture2D(uMetallicMap, texCoord).r;
}
#else
void getMetallic(inout PBRData data) {
data.metallic = uMetallic;
}
#endif
#ifdef USE_ROUGHNESS_MAP
uniform sampler2D uRoughnessMap; //assumes linear, TODO: check glTF
#ifdef USE_ROUGHNESS_MAP_TEX_COORD_TRANSFORM
uniform mat3 uRoughnessMapTexCoordTransform;
#endif
void getRoughness(inout PBRData data) {
#ifdef USE_ROUGHNESS_MAP_TEX_COORD_TRANSFORM
vec2 texCoord = getTextureCoordinates(data, ROUGHNESS_MAP_TEX_COORD_INDEX, uRoughnessMapTexCoordTransform);
#else
vec2 texCoord = getTextureCoordinates(data, ROUGHNESS_MAP_TEX_COORD_INDEX);
#endif
data.roughness = uRoughness * texture2D(uRoughnessMap, getTextureCoordinates(data, ROUGHNESS_MAP_TEX_COORD_INDEX)).r + 0.01;
}
#else
void getRoughness(inout PBRData data) {
data.roughness = uRoughness + 0.01;
}
#endif
#endif
#endif
`;
| JavaScript | 0 | @@ -2312,32 +2312,33 @@
PBRData data) %7B%0A
+%0A
#ifdef U
@@ -2674,66 +2674,16 @@
ap,
-getTextureCoordinates(data, ROUGHNESS_MAP_TEX_COORD_INDEX)
+texCoord
).r
|
5ebe08b0eb943506efbc19b65c6a376d7120927e | Make the suggestion colorbox a square (increased the height) | templates/system/modules/ph7cms-helper/themes/base/js/suggestionbox.js | templates/system/modules/ph7cms-helper/themes/base/js/suggestionbox.js | /*
* Author: Pierre-Henry Soria <hello@ph7cms.com>
* Copyright: (c) 2015-2019, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
var $suggestionBox = (function () {
$.get(pH7Url.base + 'ph7cms-helper/main/suggestionbox', function (oData) {
$.colorbox({
width: '240px',
height: '235px',
speed: 500,
scrolling: false,
html: $(oData).find('#box_block')
})
})
});
var $amendBoxBgColor = (function () {
var aHexColors = [
'#ffffff',
'#eceff1',
'#ffdcd8',
'#d1dce5',
'#f9fbe7',
'#ffe0b2',
'#ffecb3',
'#fff9c4',
'#ffccbc',
'#e0f7fa',
'#fce4ec',
'#b2dfdb'
];
var sRandomHexColor = aHexColors[Math.floor((Math.random() * aHexColors.length))];
$('#cboxContent').css('background-color', sRandomHexColor + ' !important')
});
$(document).ready(function () {
$suggestionBox();
$amendBoxBgColor();
});
| JavaScript | 0.000003 | @@ -85,10 +85,10 @@
5-20
-19
+20
, Pi
@@ -432,10 +432,10 @@
: '2
-35
+40
px',
|
b5708438033f59ec562050fe3d54ed3b4fdcb3b6 | correct paths | assets/angular/directives.js | assets/angular/directives.js | console.log("directives loaded");
angular.module('loadmaster', [])
.directive('ngUser', function() {
return {
controller:userCtrl,
link:function(scope,element,attrs){
scope.init();
}
}
})
.directive('ngTrip', function() {
return {
controller:tripCtrl,
link:function(scope,element,attrs){
}
}
})
.directive('ngMapStart', function() {
return {
replace: true,
templateUrl: '/www/src/loadmaster_assets/assets/angular/templates/map_start.html',
controller:mapCtrl,
link:function(scope,element,attrs){
scope.map_id="map-container"
scope.map_set_position="setstart_location"
$('#home').bind( "pageshow", function( event ) {
scope.initialize();
scope.startWatchPosition()
})
$('.gpsnotfound').trigger("create");
}
}
})
.directive('ngMapEnd', function() {
return {
replace: true,
templateUrl: '/www/src/loadmaster_assets/assets/angular/templates/map_end.html',
link:function(scope,element,attrs){
var geo_el = document.getElementById('geoTemp');
$('geoTemp').html('Ready...')
scope.map_id="map-container-end"
scope.map_set_position="setend_location"
$('#two').bind( "pageshow", function( event ) {
scope.initialize();
scope.startWatchPosition()
})
$('.gpsnotfound').trigger("create");
}
};
})
.directive('ngMapFinish', function() {
return {
replace: true,
templateUrl: '/www/src/loadmaster_assets/assets/angular/templates/map_finish.html',
link:function(scope,element,attrs){
var geo_el = document.getElementById('geoTemp');
$('geoTemp').html('Ready...')
scope.map_id="map-container-finish"
$('#three').bind( "pageshow", function( event ) {
if(!!scope.startlocation && !!scope.endlocation){
scope.initialize();
scope.savebounds = true;
scope.addMarkerToMap(scope.startlocation[0],scope.startlocation[1]);
scope.addMarkerToMap(scope.endlocation[0],scope.endlocation[1]);
scope.centerOnMarkers();
}
$('.gpsnotfound').trigger("create");
})
}
}
})
| JavaScript | 0.000341 | @@ -425,37 +425,32 @@
templateUrl: '
-/www/
src/loadmaster_a
@@ -898,37 +898,32 @@
templateUrl: '
-/www/
src/loadmaster_a
@@ -1454,13 +1454,8 @@
l: '
-/www/
src/
|
6ef978c45596d54c44011f3e91eba86cd41b7e80 | fix broken Stack tests | specs/Stack.spec.js | specs/Stack.spec.js | import expect, { spyOn } from 'expect';
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Chart, Stack } from '../src/';
describe('<Stack>', function () {
this.timeout(10000);
let node;
beforeEach(() => {
node = document.createElement('div');
document.body.appendChild(node);
});
afterEach(() => {
document.body.removeChild(node);
});
const data = [
[{ x: 10, y: 10 }, { x: 20, y: 20 }, { x: 20, y: 30 }],
[{ x: 10, y: 10 }, { x: 20, y: 20 }, { x: 20, y: 30 }],
[{ x: 10, y: 10 }, { x: 20, y: 20 }, { x: 20, y: 30 }]
];
['zero', 'wiggle', 'silhouette', 'expand'].forEach(offsetMode => {
it(`should support "${offsetMode}" offset mode`, done => {
render((
<div style={{ width: 200, height: 200 }}>
<Chart>
<Stack
layers={data}
offset={offsetMode}
colors="nivo"
transitionDuration={0}
/>
</Chart>
</div>
), node, () => {
setTimeout(() => {
const areas = node.getElementsByClassName('nivo_stack_area');
expect(areas).toNotBe(null);
expect(areas.length).toBe(data.length);
done();
}, 400);
});
});
});
});
| JavaScript | 0.001916 | @@ -961,14 +961,12 @@
-layers
+data
=%7Bda
|
47f7b9ff2aa4f533d7c7d51b08fadff6dfbc7b2f | remove deprecated func | src/needUpdate.js | src/needUpdate.js | import isNil from 'lodash.isnil';
import pick from 'lodash.pick';
import isPlainObject from 'lodash.isplainobject';
import Native from './native';
import {
getLatestVersion,
defaultOption as defaultOptionForLatestVersion,
} from './getLatestVersion';
function getVersionNumberArray(version, depth, delimiter) {
version = String(version);
if (version.indexOf(delimiter) === -1) {
return [version];
} else {
version = version.split(delimiter);
const result = [];
for (let i = 0, d = Math.min(depth, version.length); i < d; i++) {
result.push(version[i]);
}
return result;
}
}
export function needUpdate(option) {
if (arguments.length && !isPlainObject(option)) {
console.warn(
'[DEPRECATED] Use object type option instead. https://github.com/kimxogus/react-native-version-check#needUpdate'
);
needUpdateDeprecated.apply(null, arguments);
}
option = {
currentVersion: Native.getCurrentVersion(),
latestVersion: null,
depth: Infinity,
semantic: false,
delimiter: '.',
...defaultOptionForLatestVersion,
...option,
};
if (isNil(option.latestVersion)) {
return getLatestVersion(
pick(option, Object.keys(defaultOptionForLatestVersion))
).then(latestVersion =>
checkIfUpdateNeeded(
option.currentVersion,
latestVersion,
pick(option, ['depth', 'delimiter', 'semantic'])
)
);
}
return checkIfUpdateNeeded(
option.currentVersion,
option.latestVersion,
pick(option, ['depth', 'delimiter', 'semantic'])
);
}
/**
* @see https://github.com/kimxogus/react-native-version-check#needUpdate
* @deprecated Use object type option instead.
* @since 1.0
*/
function needUpdateDeprecated(depth = Infinity, delimiter = '.') {
if (typeof depth === 'string') {
delimiter = depth;
depth = Infinity;
}
return getLatestVersion().then(latestVersion =>
checkIfUpdateNeeded(Native.getCurrentVersion(), latestVersion, {
depth,
delimiter,
})
);
}
function checkIfUpdateNeeded(currentVersion, latestVersion, option) {
const currentVersionArr = getVersionNumberArray(
currentVersion,
option.depth,
option.delimiter
);
const latestVersionArr = getVersionNumberArray(
latestVersion,
option.depth,
option.delimiter
);
const needed = {
isNeeded: true,
currentVersion,
latestVersion,
};
const notNeeded = {
isNeeded: false,
currentVersion,
latestVersion,
};
for (let i = 0; i < option.depth; i++) {
const latestVersionToken = latestVersionArr[i];
const currentVersionToken = currentVersionArr[i];
if (!latestVersionToken && !currentVersionToken) {
return Promise.resolve(notNeeded);
}
if (!currentVersionToken && +latestVersionToken !== 0) {
return Promise.resolve(needed);
}
if (!isNaN(+latestVersionToken) && !isNaN(+currentVersionToken) && +latestVersionToken > +currentVersionToken) {
return Promise.resolve(needed);
}
if (latestVersionToken > currentVersionToken) {
return Promise.resolve(needed);
}
if (option.semantic && latestVersionToken < currentVersionToken) {
return Promise.resolve(notNeeded);
}
}
return Promise.resolve(notNeeded);
}
| JavaScript | 0.001262 | @@ -656,258 +656,8 @@
) %7B%0A
- if (arguments.length && !isPlainObject(option)) %7B%0A console.warn(%0A '%5BDEPRECATED%5D Use object type option instead. https://github.com/kimxogus/react-native-version-check#needUpdate'%0A );%0A needUpdateDeprecated.apply(null, arguments);%0A %7D%0A%0A
op
@@ -661,24 +661,24 @@
option = %7B%0A
+
currentV
@@ -1322,467 +1322,8 @@
%0A%7D%0A%0A
-/**%0A * @see https://github.com/kimxogus/react-native-version-check#needUpdate%0A * @deprecated Use object type option instead.%0A * @since 1.0%0A */%0Afunction needUpdateDeprecated(depth = Infinity, delimiter = '.') %7B%0A if (typeof depth === 'string') %7B%0A delimiter = depth;%0A depth = Infinity;%0A %7D%0A%0A return getLatestVersion().then(latestVersion =%3E%0A checkIfUpdateNeeded(Native.getCurrentVersion(), latestVersion, %7B%0A depth,%0A delimiter,%0A %7D)%0A );%0A%7D%0A%0A
func
@@ -1786,13 +1786,12 @@
on,%0A
+
%7D;
-
%0A%0A
|
cdeecf750f8a3f781459ed817815a537392993c1 | Change handling of the |visitedRules| array | lib/compiler/passes/report-left-recursion.js | lib/compiler/passes/report-left-recursion.js | "use strict";
var arrays = require("../../utils/arrays"),
GrammarError = require("../../grammar-error"),
asts = require("../asts"),
visitor = require("../visitor");
/*
* Reports left recursion in the grammar, which prevents infinite recursion in
* the generated parser.
*
* Both direct and indirect recursion is detected. The pass also correctly
* reports cases like this:
*
* start = "a"? start
*
* In general, if a rule reference can be reached without consuming any input,
* it can lead to left recursion.
*/
function reportLeftRecursion(ast) {
var check = visitor.build({
rule: function(node, visitedRules) {
check(node.expression, visitedRules.concat(node.name));
},
sequence: function(node, visitedRules) {
arrays.every(node.elements, function(element) {
if (element.type === "rule_ref") {
check(element, visitedRules);
}
return !asts.alwaysAdvancesOnSuccess(ast, element);
});
},
rule_ref: function(node, visitedRules) {
if (arrays.contains(visitedRules, node.name)) {
throw new GrammarError(
"Left recursion detected for rule \"" + node.name + "\".",
node.location
);
}
check(asts.findRule(ast, node.name), visitedRules);
}
});
check(ast, []);
}
module.exports = reportLeftRecursion;
| JavaScript | 0.000001 | @@ -587,16 +587,42 @@
(ast) %7B%0A
+ var visitedRules = %5B%5D;%0A%0A
var ch
@@ -658,33 +658,41 @@
e: function(node
-,
+) %7B%0A
visitedRules) %7B
@@ -684,27 +684,41 @@
visitedRules
-) %7B
+.push(node.name);
%0A check
@@ -733,17 +733,24 @@
pression
-,
+);%0A
visited
@@ -759,14 +759,11 @@
les.
-concat
+pop
(nod
@@ -769,17 +769,16 @@
de.name)
-)
;%0A %7D,
@@ -802,38 +802,24 @@
unction(node
-, visitedRules
) %7B%0A ar
@@ -930,30 +930,16 @@
(element
-, visitedRules
);%0A
@@ -1049,30 +1049,16 @@
ion(node
-, visitedRules
) %7B%0A
@@ -1297,22 +1297,8 @@
ame)
-, visitedRules
);%0A
@@ -1324,12 +1324,8 @@
(ast
-, %5B%5D
);%0A%7D
|
12542d7b0e45a8ad78b88cc43e0473b5e6712eea | Fix build.js | @types/jdk/build.js | @types/jdk/build.js | var fs = require("fs")
var path = require("path")
var parse = require("../../jar/parse")
var jars = [
"jre/lib/charsets.jar",
"jre/lib/ext/cldrdata.jar",
"jre/lib/ext/dnsns.jar",
"jre/lib/ext/icedtea-sound.jar",
"jre/lib/ext/jaccess.jar",
"jre/lib/ext/localedata.jar",
"jre/lib/ext/nashorn.jar",
"jre/lib/ext/sunec.jar",
"jre/lib/ext/sunjce_provider.jar",
"jre/lib/ext/sunpkcs11.jar",
"jre/lib/ext/zipfs.jar",
"jre/lib/jce.jar",
"jre/lib/jsse.jar",
"jre/lib/management-agent.jar",
"jre/lib/resources.jar",
"jre/lib/rt.jar",
"jre/lib/security/US_export_policy.jar",
"jre/lib/security/local_policy.jar",
]
for (var i = 0; i < jars.length; i++) {
var jar = process.env.JAVA_HOME + "/" + jars[i]
var content = parse(jar)
fs.writeFileSync(path.basename(jar).replace(".jar", ".d.ts"), content)
}
| JavaScript | 0.000002 | @@ -52,16 +52,19 @@
ar parse
+JAR
= requi
@@ -77,17 +77,29 @@
/../
-ja
+src/compile
r/parse
+JAR
%22)%0A%0A
@@ -260,32 +260,72 @@
t/jaccess.jar%22,%0A
+ %22jre/lib/ext/java-atk-wrapper.jar%22,%0A
%22jre/lib/ext
@@ -629,32 +629,73 @@
re/lib/rt.jar%22,%0A
+ %22jre/lib/security/local_policy.jar%22,%0A
%22jre/lib/sec
@@ -732,91 +732,127 @@
%22
-jre/lib/security/local_policy.jar%22,%0A%5D%0A%0Afor (var i = 0; i %3C jars.length; i++
+lib/dt.jar%22,%0A %22lib/jconsole.jar%22,%0A %22lib/sa-jdi.jar%22,%0A %22lib/tools.jar%22,%0A%5D%0A%0Ajars.forEach(function(jar, i
) %7B%0A
var
@@ -847,23 +847,23 @@
) %7B%0A
-var jar
+jars%5Bi%5D
= proce
@@ -903,32 +903,147 @@
-var content = parse
+if (!fs.existsSync(jars%5Bi%5D)) %7B%0A console.error(jars%5Bi%5D + %22 not found%22)%0A process.exit(1)%0A %7D%0A%7D)%0A%0Ajars.forEach(function
(jar)
+ %7B
%0A
@@ -1109,15 +1109,22 @@
%22),
-content
+parseJAR(jar)
)%0A%7D
+)
%0A
|
3a35c3dc4ee03cb1ae0d35a28732a1f6ca607b18 | Fix typo | packages/bpk-docs/src/pages/MobileScrollContainerPage/MobileScrollContainerPage.js | packages/bpk-docs/src/pages/MobileScrollContainerPage/MobileScrollContainerPage.js | /*
* Backpack - Skyscanner's Design System
*
* Copyright 2016-2019 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* @flow */
import React from 'react';
import mobileScrollContainerReadme from 'bpk-component-mobile-scroll-container/README.md';
import IntroBlurb from '../../components/IntroBlurb';
import DocsPageBuilder from '../../components/DocsPageBuilder';
import DocsPageWrapper from '../../components/DocsPageWrapper';
import BlockExample from './BlockExample';
const components = [
{
id: 'example',
title: 'Example',
examples: [<BlockExample />],
},
];
const blurb = [
<IntroBlurb>
The mobile scroll container component will hide overflowing content in fixed
with situations and will enable horizontal scrolling.
</IntroBlurb>,
];
const MobileScrollContainerSubPage = ({ ...rest }: { [string]: any }) => (
<DocsPageBuilder
title="Mobile scroll container"
components={components}
readme={mobileScrollContainerReadme}
{...rest}
/>
);
const MobileScrollContainerPage = () => (
<DocsPageWrapper
title="Mobile scroll container"
blurb={blurb}
webSubpage={<MobileScrollContainerSubPage wrapped />}
/>
);
export default MobileScrollContainerPage;
| JavaScript | 0.999995 | @@ -1225,16 +1225,17 @@
d%0A wi
+d
th situa
|
d717243e4c1fd7ccba08ee4bf21c9a94b2b88de9 | Resolve that path! | test/basic.js | test/basic.js | var test = require('tap').test
var MF = require('../multi-fs.js')
var path = require('path')
var fs = require('fs')
var base = path.resolve(__dirname, 'fixtures')
var cwd = process.cwd()
var locshort = base
if (cwd && base.indexOf(cwd) === 0)
locshort = base.substr(cwd.length).replace(/^\/+/, '')
var home = process.env.HOME
var homeshort = base
if (home && base.indexOf(home) === 0)
homeshort = base.substr(home.length).replace(/^\/+/, '')
var mf
test('make mf', function(t) {
var targets = [
{ type: 'fs', path: base + '/0' },
{ type: 'fs', path: locshort + '/1' },
base + '/2',
locshort + '/3',
'~/' + homeshort + '/4',
'ssh://localhost:' + homeshort + '/5',
'ssh://localhost' + base + '/6',
{
type: 'ssh',
agent: process.env.SSH_AUTH_SOCK,
path: homeshort + '/7'
},
{
type: 'ssh',
agent: process.env.SSH_AUTH_SOCK,
path: base + '/8'
},
'~~/stor/multi-fs-testing/9',
'manta:/' + process.env.MANTA_USER + '/stor/multi-fs-testing/10',
{
path: '~~/stor/multi-fs-testing/11',
type: 'manta',
env: {},
argv: [
'-a', process.env.MANTA_USER,
'-k', process.env.MANTA_KEY_ID,
'-u', process.env.MANTA_URL
]
},
{
path: '~~/stor/multi-fs-testing/12',
type: 'manta',
argv: [],
env: {
MANTA_USER: process.env.MANTA_USER,
MANTA_KEY_ID: process.env.MANTA_KEY_ID,
MANTA_URL: process.env.MANTA_URL
}
}
]
mf = new MF(targets)
t.pass('made mf')
t.end()
})
test('mkdirp', function(t) {
mf.mkdirp('a/b/c/d/e/f', function(er, res, data) {
if (er)
throw er
t.equal(res, undefined)
t.end()
})
})
test('rmr', function(t) {
mf.rmr('a/b/c/d', function(er, res, data) {
if (er)
throw er
t.equal(res, undefined)
t.end()
})
})
test('writeFilep', function(t) {
mf.writeFilep('a/x/y/z/foo', 'bar\n', 'ascii', function(er, res, data) {
if (er)
throw er
t.equal(res, undefined)
t.end()
})
})
test('writeFile', function(t) {
mf.writeFile('a/b/c/foo', 'bar\n', 'ascii', function(er, res, data) {
if (er)
throw er
t.equal(res, undefined)
t.end()
})
})
test('writeFile stream input', function(t) {
var source = fs.createReadStream('./cat_in_a_box.jpg', 'binary')
mf.writeFile('/a/b/c/stream', source, 'binary', function(er, res, data) {
if (er) throw er
t.equal(res, undefined)
t.end()
})
})
test('stat', function(t) {
var n = 2
mf.stat('a/b/c/foo', function(er, res, data) {
if (er) {
console.error(er, res, data)
throw er
}
t.same(res, { isFile: true, isDirectory: false })
if (--n === 0)
t.end()
})
mf.stat('a/b/c', function(er, res, data) {
if (er) {
console.error(er, res, data)
throw er
}
t.same(res, { isFile: false, isDirectory: true })
if (--n === 0)
t.end()
})
})
test('readFile', function(t) {
mf.readFile('a/b/c/foo', 'ascii', function(er, res, data) {
if (er)
throw er
t.equal(res, 'bar\n')
mf.readFile('a/x/y/z/foo', 'ascii', function(er, res, data) {
if (er)
throw er
t.equal(res, 'bar\n')
t.end()
})
})
})
test('md5', function(t) {
mf.md5('a/b/c/foo', function(er, res, data) {
if (er)
throw er
t.equal(res, 'c157a79031e1c40f85931829bc5fc552')
t.end()
})
})
test('unlink', function(t) {
console.error('unlink')
mf.unlink('a/b/c/foo', function(er, res, data) {
if (er)
throw er
t.equal(res, undefined)
t.end()
})
})
test('close', function(t) {
mf.destroy()
t.pass('destroyed')
t.end()
})
| JavaScript | 0.000002 | @@ -439,24 +439,79 @@
%5E%5C/+/, '')%0A%0A
+%0Aconsole.error('ssh://localhost:' + homeshort + '/5')%0A%0A
var mf%0A%0Atest
@@ -2375,11 +2375,33 @@
eam(
-'./
+path.resolve(__dirname, '
cat_
@@ -2413,16 +2413,17 @@
box.jpg'
+)
, 'binar
|
4dfd6df4229cfa8638991be3eca8abf9a5d8eeb1 | test that args are handled properly | test/basic.js | test/basic.js | var test = require('tap').test
var dz = require('../dezalgo.js')
test('the dark pony', function(t) {
var n = 0
function foo(cb) {
cb = dz(cb)
if (++n % 2) cb()
else process.nextTick(cb)
}
var called = 0
for (var i = 0; i < 10; i++) {
foo(function() {
called++
})
t.equal(called, 0)
}
setTimeout(function() {
t.equal(called, 10)
t.end()
})
})
| JavaScript | 0.000001 | @@ -123,16 +123,19 @@
ion foo(
+i,
cb) %7B%0A
@@ -168,16 +168,23 @@
%25 2) cb(
+true, i
)%0A el
@@ -205,16 +205,37 @@
tTick(cb
+.bind(null, false, i)
)%0A %7D%0A%0A
@@ -250,16 +250,73 @@
led = 0%0A
+ var order = %5B0, 2, 4, 6, 8, 1, 3, 5, 7, 9%5D%0A var o = 0%0A
for (v
@@ -348,16 +348,19 @@
foo(
+i,
function
@@ -356,27 +356,102 @@
i, function(
-) %7B
+cached, i) %7B%0A t.equal(i, order%5Bo++%5D)%0A t.equal(i %25 2, cached ? 0 : 1)
%0A calle
|
6f0ca2ef87703112bde5c19c8f9c208fcda71c0c | Fix delayed load and capital image extension | assets/javascripts/banner.js | assets/javascripts/banner.js | var banner = $("#homepage-banner");
var imageNames = ['bot', 'soccer', 'teamCrop', 'working'];
var imageIndex = Math.floor((Math.random() * imageNames.length));
var imageUrl = "assets/images/homepage-banners/" + imageNames[imageIndex] + ".JPG";
$( document ).ready(function(){
banner.css('background-image', 'url(' + imageUrl + ')');
});
| JavaScript | 0.000001 | @@ -237,49 +237,16 @@
+ %22.
-JPG
+jpg
%22;%0A%0A
-$( document ).ready(function()%7B%0A
+%0A
bann
@@ -302,8 +302,4 @@
');%0A
-%7D);%0A
|
61db2458f4e9b2b610dab9fa03bf24d47f0a2bb7 | Update metrics | assets/javascripts/graphs.js | assets/javascripts/graphs.js |
defaults = {
"chart": {
chart: {
type: 'spline'
},
"plotOptions": {
"spline": {
"marker": {
"enabled": false
}
}
},
"tooltip": {
"crosshairs": true
}
}
}
graphs = [
/*
{
chart: {
chart: {
type: 'column'
},
title: 'Example graph',
yAxis: {
title: {
text: 'Essence'
},
min: -10,
max: 50
},
tooltip: {
crosshairs: true,
valueSuffix: ' EX'
},
plotOptions: {
series: {
marker: {
symbol: 'diamond',
enabled: 'true'
}
}
}
},
select: {
fields: ["field1", "field2"],
mac: /18FE349B/
}
},
*/
{
chart: {
chart: {
type: 'line'
},
title: 'Uptime & Connections',
yAxis: {
title: {
text: 'sec'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' sec'
},
plotOptions: {
spline: {
marker: {
symbol: 'diamond',
enabled: 'true'
}
}
}
},
select: {
fields: ["uptime"]
}
},
{
chart: {
title: 'Free Memory',
yAxis: {
title: {
text: 'bytes'
}
},
tooltip: {
crosshairs: true,
valueSuffix: ' bytes'
}
},
select: {
fields: ["freemem"]
}
},
{
chart: {
title: 'Power Voltage',
yAxis: {
title: {
text: 'mV'
}
},
tooltip: {
crosshairs: true,
valueSuffix: ' mV'
}
},
select: {
fields: ["vdd"]
}
},
{
chart: {
title: 'RSSI level',
yAxis: {
title: {
text: 'dBm'
},
},
tooltip: {
crosshairs: true,
valueSuffix: ' dBm'
}
},
select: {
fields: ["rssi"]
}
},
{
chart: {
title: 'Temperature',
yAxis: {
title: {
text: '°C'
},
plotLines: [{
value: 0,
color: 'orange',
dashStyle: 'shortdash',
width: 1,
label: {
text: 'Null'
}
}],
},
tooltip: {
crosshairs: true,
valueSuffix: ' °C'
}
},
select: {
fields: ["amt", "bmpt", "bmet", "dhtt1", "dhtt2", "ds", "dsw1", "dsw2", "dsw3", "dsw4", "dsw5", "dsw6", "dsw7", "dsw8", "dsw9", "dsw10", "dsw11", "dsw12", "dsw13", "dsw14", "dsw15", "nrf1t1", "nrf2t1", "nrf3t1", "nrf1t2", "nrf2t2", "nrf3t2"]
}
},
{
chart: {
title: 'Humidity',
yAxis: {
title: {
text: '%'
},
min: 0,
plotLines: [{
value: 20,
color: 'green',
dashStyle: 'shortdash',
width: 1,
label: {
text: 'Critical low'
}
}, {
value: 90,
color: 'red',
dashStyle: 'shortdash',
width: 1,
label: {
text: 'Critical high'
}
}],
},
tooltip: {
crosshairs: true,
valueSuffix: ' %'
}
},
select: {
fields: ["amh", "dhth1", "dhth2", "bmeh", "nrf1h1", "nrf2h1", "nrf3h1", "nrf1h2", "nrf2h2", "nrf3h2"]
}
},
{
chart: {
title: 'Atmospheric pressure',
yAxis: {
title: {
text: 'mmHg'
}
},
tooltip: {
crosshairs: true,
valueSuffix: ' mmHg'
}
},
select: {
fields: ["bmpp", "bmep"]
}
},
{
chart: {
title: 'Brightness',
yAxis: {
title: {
text: 'Lux'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' Lux'
}
},
select: {
fields: ["light"]
}
},
{
chart: {
title: 'Analog-to-digital converter',
yAxis: {
title: {
text: 'points'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' points'
}
},
select: {
fields: ["adc", "adc0", "adc1", "adc2", "adc3" ]
}
},
{
chart: {
title: 'Pulse-Width Modulation status',
yAxis: {
title: {
text: 'points'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' points'
}
},
select: {
fields: ["pwm", "pwm0", "pwm1", "pwm2" ]
}
},
{
chart: {
title: 'GPIO Input Monitor',
yAxis: {
title: {
text: 'status'
},
min: 0,
max: 1
},
tooltip: {
crosshairs: true,
valueSuffix: ' status'
}
},
select: {
fields: ["gpioint", "gpio1", "gpio2", "gpio3", "gpio4", "gpio5", "gpio13", "gpiout13"]
}
},
{
chart: {
title: 'Counter',
yAxis: {
title: {
text: 'ps'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' ps'
}
},
select: {
fields: ["counter", "countrst", "nrf1c1", "nrf2c1", "nrf3c1", "nrf1c2", "nrf2c2", "nrf3c2"]
}
},
{
chart: {
title: 'Counter v.2 (derivative)',
yAxis: {
title: {
text: 'ps'
},
min: 0
},
tooltip: {
crosshairs: true,
valueSuffix: ' ps'
}
},
select: {
fields: {counter: "DERIVATIVE(counter)"}
}
},
];
| JavaScript | 0.000001 | @@ -4777,16 +4777,76 @@
, %22adc3%22
+, %22nrf1a1%22, %22nrf2a1%22, %22nrf3a1%22, %22nrf1a2%22, %22nrf2a2%22, %22nrf3a2%22
%5D%0A
@@ -5601,16 +5601,76 @@
piout13%22
+, %22nrf1g1%22, %22nrf2g1%22, %22nrf3g1%22, %22nrf1g2%22, %22nrf2g2%22, %22nrf3g2%22
%5D%0A
|
20377faa0d45e23612686729a39dd7e9cd6dd128 | clean old code | test/fetch.js | test/fetch.js | import fetch from '../src/fetch'
import Headers from '../src/Headers'
import isFunction from 'lodash/isFunction'
import chai, { expect, should, assert } from 'chai';
should();
import chaiAsPromised from "chai-as-promised";
import 'babel-polyfill';
chai.use(chaiAsPromised);
describe('fetch', () => {
it('expect to receive successfull response', async () => {
let fetchOptions = {
method: 'GET'
}
let headers = new Headers().add().acceptApplicationJson().use()
try{
const res = await fetch('http://localhost:3000/get-success', {parseResponse: false, headers: headers})
const resJson = await res.json()
expect(resJson).to.deep.equal({a: 1});
} catch(errRes){
throw new Error(errRes)
}
})
it('expect to receive error response', async () => {
let fetchOptions = {
method: 'GET'
}
let headers = new Headers().add().acceptApplicationJson().use()
try{
const res = await fetch('http://localhost:3000/get-error', {parseResponse: false, headers: headers})
const resJson = await res.json()
expect(resJson).to.deep.equal({code: 'UNSUPPORTED_MEDIA_TYPE'});
} catch(errRes){
expect(errRes.name).to.be.equal('FetchError');
}
})
it('expect to parse response by defaultParser with isJson flag to true', async () => {
let fetchOptions = {
method: 'GET'
}
let headers = new Headers().add().acceptApplicationJson().use()
try{
const res = await fetch('http://localhost:3000/get-success', {parseResponse: true, headers: headers})
const jsonRes = await res.json()
expect(res.isJson).to.be.equal(true)
expect(jsonRes).to.be.deep.equal({a: 1})
} catch(errRes){
if (errRes.name !== undefined){
throw new Error(errRes)
expect(errRes.name).to.be.equal('FetchError');
}
if (errRes.code !== undefined){
expect(errRes.code).to.be.equal('GENERIC_TIMEOUT');
}
}
})
it('expect to parse response by defaultParser with server error response', async () => {
let fetchOptions = {
method: 'GET'
}
let headers = new Headers().add().acceptApplicationJson().use()
try{
const res = await fetch('http://localhost:3000/get-server-error', {parseResponse: true, headers: headers})
const jsonRes = await res.json()
expect(res.isJson).to.be.equal(true)
expect(jsonRes).to.be.deep.equal({a: 1})
} catch(errRes){
if (errRes.name !== undefined){
//throw new Error(errRes)
expect(errRes.name).to.be.equal('FetchError');
}
if (errRes.code !== undefined){
expect(errRes.code).to.be.equal('GENERIC_TIMEOUT');
}
}
})
it('expect to handle timeout', async function(){
this.timeout(2500)
let fetchOptions = {
method: 'GET'
}
let headers = new Headers().add().acceptApplicationJson().use()
try{
const res = await fetch('http://localhost:3000/get-with-timeout', {parseResponse: false, headers: headers, timeout: 2000})
assert.ok(false)
} catch(errRes){
if (errRes.name !== undefined){
expect(errRes.name).to.be.equal('FetchError');
}
if (errRes.code !== undefined){
expect(errRes.code).to.be.equal('GENERIC_TIMEOUT');
}
}
})
})
| JavaScript | 0.000096 | @@ -2507,44 +2507,8 @@
d)%7B%0A
- //throw new Error(errRes)%0A
@@ -2572,114 +2572,8 @@
%7D%0A
- if (errRes.code !== undefined)%7B%0A expect(errRes.code).to.be.equal('GENERIC_TIMEOUT');%0A %7D%0A
|
75ee470bd377689d2c1d811f5352ecd50e24e120 | Debug failing test on Travis | test/hooks.js | test/hooks.js | "use strict";
var should = require('should')
, Post = require('./model/post')
, HistoryPost = Post.historyModel();
require('./config/mongoose');
describe('History plugin', function() {
var post = null;
function createAndUpdatePostWithHistory(post, callback) {
post.save(function(err) {
if(err) return callback(err);
Post.findOne(function(err, post) {
if(err) return callback(err);
post.updatedFor = 'another_user@test.com';
post.title = "Title changed";
post.save(function(err) {
if(err) return callback(err);
HistoryPost.findOne({'d.title': 'Title changed'}, function(err, hpost) {
callback(err, post, hpost);
});
});
});
});
};
function updatePostWithHistory(post, callback) {
post.save(function(err) {
if(err) return callback(err);
post.title = 'Updated title';
Post.update({title: 'Title test'}, post, function(err){
if(err) return callback(err);
HistoryPost.findOne({'d.title': 'Updated title'}, function(err, hpost) {
callback(err, post, hpost);
});
});
});
};
var post = null;
beforeEach(function(done) {
post = new Post({
updatedFor: 'mail@test.com',
title: 'Title test',
message: 'message lorem ipsum test'
});
done();
});
afterEach(function(done) {
Post.remove({}, function(err) {
should.not.exists(err);
Post.clearHistory(function(err) {
should.not.exists(err);
done();
});
});
});
it('should keep insert in history', function(done) {
post.save(function(err) {
should.not.exists(err);
HistoryPost.findOne({'d.title': 'Title test'}, function(err, hpost) {
should.not.exists(err);
hpost.o.should.eql('i');
post.should.have.property('updatedFor', hpost.d.updatedFor);
post.title.should.be.equal(hpost.d.title);
post.should.have.property('message', hpost.d.message);
done();
});
});
});
it('should keep update in history', function(done) {
createAndUpdatePostWithHistory(post, function(err, post, hpost) {
should.not.exists(err);
hpost.o.should.eql('u');
post.updatedFor.should.be.equal(hpost.d.updatedFor);
post.title.should.be.equal(hpost.d.title);
post.message.should.be.equal(hpost.d.message);
done();
});
});
it('should keep update on Model in history', function(done) {
updatePostWithHistory(post, function (err, post, hpost) {
should.not.exists(err);
hpost.o.should.eql('u');
post.updatedFor.should.be.equal(hpost.d.updatedFor);
post.title.should.be.equal(hpost.d.title);
post.message.should.be.equal(hpost.d.message);
done();
})
});
it('should keep remove in history', function(done) {
createAndUpdatePostWithHistory(post, function(err, post, hpost) {
should.not.exists(err);
post.remove(function(err) {
should.not.exists(err);
HistoryPost.find({o: 'r'}).select('d').exec(function(err, historyWithRemove) {
historyWithRemove.should.not.be.empty;
done();
});
});
});
});
}); | JavaScript | 0 | @@ -893,36 +893,227 @@
-post.title = 'Updated title'
+console.log('=== * Post * ===');%0A console.log(post);%0A var post = post.toObject();%0A post.title = 'Updated title';%0A delete post._id;%0A%0A console.log('=== * POST POST * ===');%0A console.log(post)
;%0A%0A
|
113616d7a0f3522e6c51fbaaf081170106a67ec6 | add more tests | test/index.js | test/index.js | (function() {
module('DLV', {
setup: function() {
},
teardown: function() {
}
});
test('initialize with nothing', 1, function() {
var dlv = new DLV();
ok(!dlv.listeners, 'no constructor instance listeners');
});
test('initialize with listeners', 1, function() {
var listeners = {};
var dlv = new DLV({
listeners: listeners
});
strictEqual(dlv.listeners, listeners, 'constructor instance listeners');
});
test('single event listener entry', 1, function() {
var View = DLV.extend({
listeners: {
'change model': 'handler'
},
handler: function() {}
});
var model = new Backbone.Model();
var view = new View({
model: model
});
var spy = sinon.spy(view.handler);
model.set('foo', 'bar');
ok(spy.calledOnce, 'listener called');
});
test('single multi-event listener entry', 1, function() {
var View = DLV.extend({
listeners: {
'change:foo change:bar model': 'handler'
},
handler: function() {}
});
var model = new Backbone.Model();
var view = new View({
model: model
});
var spy = sinon.spy(view.handler);
model.set('foo', 'bar');
model.set('bar', 'foo');
ok(spy.calledTwice, 'listener called');
});
test('many event listener entries', 1, function() {
var View = DLV.extend({
listeners: {
'change:foo': 'fooHandler',
'change:bar': 'barHandler',
},
fooHandler: function() {},
barHandler: function() {}
});
var model = new Backbone.Model();
var view = new View({
model: model
});
var fooHandlerSpy = sinon.spy(view.fooHandler);
var barHandlerSpy = sinon.spy(view.barHandler);
model.set('foo', 'bar');
model.set('bar', 'foo');
ok(fooHandlerSpy.calledOnce, 'foo listener called');
ok(barHandlerSpy.calledOnce, 'bar listener called');
});
})();
| JavaScript | 0 | @@ -882,32 +882,35 @@
non.spy(view
-.
+, '
handler
+'
);%0A m
@@ -1371,16 +1371,19 @@
view
-.
+, '
handler
+'
);%0A
@@ -1959,17 +1959,19 @@
spy(view
-.
+, '
fooHandl
@@ -1968,24 +1968,25 @@
'fooHandler
+'
);%0A v
@@ -2018,17 +2018,19 @@
spy(view
-.
+, '
barHandl
@@ -2031,16 +2031,17 @@
rHandler
+'
);%0A
|
61c613c6e9ee4bf50d0aab65a2eea7c36c7b9b70 | test click on introduction | test/index.js | test/index.js | /* global describe, it */
var Nightmare = require('nightmare');
var join = require('path').join;
describe('index page', function () {
it('should have global jQuery', function (done) {
new Nightmare()
.goto(join(__dirname, '../dist/index.html'))
.evaluate(function() {
/* global jQuery */
return jQuery;
}, function (res) {
if (res === null) {
return done('jQuery is not found on page');
}
done();
})
.run(function (err) {
if (err) { done(err); }
});
});
});
| JavaScript | 0 | @@ -652,13 +652,344 @@
%0A %7D);
+%0A%0A it('should have link to introduction', function (done) %7B%0A new Nightmare()%0A .goto(join(__dirname, '../dist/index.html'))%0A .click('.nav__link%5Bhref=%22introduction.html%22%5D')%0A .run(function (err) %7B%0A if (err) %7B return done(err); %7D%0A done();%0A %7D);%0A %7D);
%0A%7D);%0A
|
a15175dd9647d3684fd6dd3462929be03ea612c5 | improve test for tabbed entry | test/index.js | test/index.js | 'use strict';
const Proxyquire = require('proxyquire');
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const beforeEach = lab.beforeEach;
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const internals = { stub: { fs: {} } };
internals.stub.fs.readdir = function (path, next) {
return next(internals.readdirErr, internals.list);
};
internals.stub.fs.readFile = function (path, encoding, next) {
return next(internals.readFileErr, internals.content);
};
internals.stub.fs.writeFile = function (path, data, next) {
internals.data.push(data);
if (path.endsWith('.txt')) {
return next(internals.writeFileTxtErr);
}
if (path.endsWith('.json')) {
return next(internals.writeFileJsonErr);
}
};
internals.stub.itlog = function (message) {
internals.messages.push(message);
return;
};
internals.collator = Proxyquire('..', internals.stub);
beforeEach((done) => {
internals.readdirErr = null;
internals.readFileErr = null;
internals.writeFileTxtErr = null;
internals.writeFileJsonErr = null;
internals.list = ['filename.txt', 'filename.abc'];
internals.data = [];
internals.messages = [];
internals.content = `
stopword
b
d
c a
the
The
is
iS`;
return done();
});
describe('start()', () => {
it('returns usage info on -h or missing -s and -o', (done) => {
internals.collator.start({ args: ['-h'] });
expect(internals.messages[0]).to.contain('Usage: stopwords-collator');
internals.messages = [];
internals.collator.start({ args: ['-s', 'source'] });
expect(internals.messages[0]).to.contain('Usage: stopwords-collator');
internals.messages = [];
internals.collator.start({ args: ['-o', 'output'] });
expect(internals.messages[0]).to.contain('Usage: stopwords-collator');
internals.messages = [];
return done();
});
it('returns directory error', (done) => {
internals.readdirErr = new Error();
internals.collator.start({ args: ['-s', 'source', '-o', 'stopwords'] });
expect(internals.messages[0]).to.contain(':: directory error -');
return done();
});
it('returns file error', (done) => {
internals.readFileErr = new Error();
internals.collator.start({ args: ['-s', 'source', '-o', 'stopwords'] });
expect(internals.messages[2]).to.contain(':: file error -');
return done();
});
it('returns txt file error', (done) => {
internals.writeFileTxtErr = new Error();
internals.collator.start({ args: ['-s', 'source', '-o', 'stopwords'] });
expect(internals.messages[3]).to.contain(':: saving txt error -');
return done();
});
it('returns json file error', (done) => {
internals.writeFileJsonErr = new Error();
internals.collator.start({ args: ['-s', 'source', '-o', 'stopwords'] });
expect(internals.messages[3]).to.contain(':: saving json error -');
return done();
});
it('collates', (done) => {
internals.collator.start({ args: ['-s', 'source', '-o', 'stopwords'] });
expect(internals.data[0]).to.equal('a\nb\nc\nd\nis\nstopword\nthe');
expect(internals.data[1]).to.equal('["a","b","c","d","is","stopword","the"]');
expect(internals.messages[internals.messages.length - 1]).to.equal(':: collation complete');
return done();
});
});
| JavaScript | 0 | @@ -1312,17 +1312,17 @@
e%0AThe%0Ais
-%0A
+%09
iS%60;%0A%0A
|
a035629a75be43c166b13e276fc6c6f528086212 | add test code | test/index.js | test/index.js | var styleGuide = require('../')
var fs = require('fs')
var postcss = require('postcss')
var test = require('tape')
var css = fs.readFileSync('test/fixture.css', 'utf-8')
var options = {
name: 'Default theme',
}
var res = postcss().use(styleGuide(options)).process(css).css.trim()
var mdParse = require('../lib/md_parse')
test('md_parse', function (t) {
var expected = '<p>/*</p>\n<h1 id="write-the-explanatory-text-of-the-bellow-rule-set-">Write the explanatory text of the bellow rule set.</h1>\n<p>Basic blue button.</p>\n<pre><code><span class="hljs-tag"><<span class="hljs-title">button</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"btn-blue"</span>></span>Button<span class="hljs-tag"></<span class="hljs-title">button</span>></span>\n</code></pre><p>*/</p>\n<p>.button-blue {\n color: white;\n background-color: var(--blue);\n border-radius: var(--border-radius);\n}</p>'
var actual = mdParse(css);
t.same(actual, expected)
t.end()
})
var highlight = require('../lib/css_highlight')
test('css_highlight', function (t) {
var expected = '<span class="hljs-comment">/*\n# Write the explanatory text of the bellow rule set.\n\nBasic blue button.\n\n <button class="btn-blue">Button</button>\n*/</span>\n\n<span class="hljs-class">.button-blue</span> <span class="hljs-rules">{\n <span class="hljs-rule"><span class="hljs-attribute">color</span>:<span class="hljs-value"> white</span></span>;\n <span class="hljs-rule"><span class="hljs-attribute">background-color</span>:<span class="hljs-value"> <span class="hljs-function">var</span>(--blue)</span></span>;\n <span class="hljs-rule"><span class="hljs-attribute">border-radius</span>:<span class="hljs-value"> <span class="hljs-function">var</span>(--border-radius)</span></span>;\n}</span>\n'
var actual = highlight(css)
t.same(actual, expected)
t.end()
})
| JavaScript | 0.000003 | @@ -213,17 +213,58 @@
,%0A%7D%0A
-var res =
+%0A%0Atest('exist styleguide.html', function (t) %7B%0A
pos
@@ -319,16 +319,106 @@
.trim()%0A
+ var actual = fs.existsSync('styleguide.html')%0A%0A t.same(actual, true)%0A t.end()%0A%7D)
%0A%0Avar md
@@ -452,21 +452,16 @@
parse')%0A
-
test('md
@@ -476,33 +476,32 @@
function (t) %7B%0A
-
var expected
@@ -1057,25 +1057,24 @@
n%7D%3C/p%3E'%0A
-
var actual =
@@ -1088,17 +1088,16 @@
e(css);%0A
-
t.sa
@@ -1113,33 +1113,32 @@
, expected)%0A
-
t.end()%0A%7D)%0A%0Avar
@@ -1181,21 +1181,16 @@
light')%0A
-
test('cs
@@ -1218,17 +1218,16 @@
n (t) %7B%0A
-
var
@@ -1965,17 +1965,16 @@
%5Cn'%0A
-
var actu
@@ -1997,17 +1997,16 @@
ss)%0A
-
t.same(a
@@ -2022,17 +2022,16 @@
pected)%0A
-
t.en
|
a1d4ca54e5d0abe038a2dbac863ae873a51f9a1d | Fix agent not finding address of app err. | test/index.js | test/index.js | import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
import createApplication from '../src';
const setup = () => {
return agent(createApplication());
};
test('GET /', (sub) => {
sub.test('responds with OK status code', co.wrap(function* (assert) {
const app = setup();
yield app
.get('/')
.expect((response) => {
assert.equal(response.statusCode, 200, 'status code should be 200');
})
.end();
}));
});
| JavaScript | 0 | @@ -183,16 +183,27 @@
cation()
+.callback()
);%0A%7D;%0A%0At
|
0045306aadfc62b55f40a8c07c613f9fc599eb5a | Add test for stringification with invalid bullet option | test/index.js | test/index.js | 'use strict';
var mdast,
assert,
fixtures,
chalk,
diff;
mdast = require('..');
assert = require('assert');
fixtures = require('./fixtures.js');
chalk = require('chalk');
diff = require('diff');
/*
* Settings.
*/
var INDENT;
INDENT = 2;
/*
* Tests.
*/
describe('mdast', function () {
it('should be of type `object`', function () {
assert(typeof mdast === 'object');
});
});
describe('mdast.parse()', function () {
it('should be of type `function`', function () {
assert(typeof mdast.parse === 'function');
});
});
describe('mdast.stringify()', function () {
it('should be of type `function`', function () {
assert(typeof mdast.stringify === 'function');
});
});
var validateToken,
validateTokens;
/**
* Validate `children`.
*
* @param {Array.<Object>} children
*/
validateTokens = function (children) {
children.forEach(validateToken);
};
/**
* Validate `context`.
*
* @param {Object} context
*/
validateToken = function (context) {
var keys = Object.keys(context),
type = context.type,
key;
assert('type' in context);
if ('children' in context) {
assert(Array.isArray(context.children));
validateTokens(context.children);
}
if ('value' in context) {
assert(typeof context.value === 'string');
}
if (type === 'root') {
assert('children' in context);
if (context.footnotes) {
for (key in context.footnotes) {
validateTokens(context.footnotes[key]);
}
}
return;
}
if (
type === 'paragraph' ||
type === 'blockquote' ||
type === 'tableHeader' ||
type === 'tableRow' ||
type === 'tableCell' ||
type === 'strong' ||
type === 'emphasis' ||
type === 'delete'
) {
assert(keys.length === 2);
assert('children' in context);
return;
}
if (type === 'listItem') {
assert(keys.length === 3);
assert('children' in context);
assert('loose' in context);
return;
}
if (type === 'footnote') {
assert(keys.length === 2);
assert('id' in context);
return;
}
if (type === 'heading') {
assert(keys.length === 3);
assert(context.depth > 0);
assert(context.depth <= 6);
assert('children' in context);
return;
}
if (type === 'inlineCode') {
assert(keys.length === 2);
assert('value' in context);
return;
}
if (type === 'code') {
assert(keys.length === 3);
assert('value' in context);
assert(
context.lang === null ||
typeof context.lang === 'string'
);
return;
}
if (type === 'horizontalRule' || type === 'break') {
assert(keys.length === 1);
return;
}
if (type === 'list') {
assert('children' in context);
assert(typeof context.ordered === 'boolean');
assert(keys.length === 3);
return;
}
if (type === 'text') {
assert(keys.length === 2);
assert('value' in context);
return;
}
if (type === 'link') {
assert('children' in context);
assert(
context.title === null ||
typeof context.title === 'string'
);
assert(typeof context.href === 'string');
assert(keys.length === 4);
return;
}
if (type === 'image') {
assert(
context.title === null ||
typeof context.title === 'string'
);
assert(
context.alt === null ||
typeof context.alt === 'string'
);
assert(typeof context.src === 'string');
assert(keys.length === 4);
return;
}
if (type === 'table') {
assert(keys.length === 3);
assert('children' in context);
assert(Array.isArray(context.align));
context.align.forEach(function (align) {
assert(
align === null ||
align === 'left' ||
align === 'right' ||
align === 'center'
);
});
return;
}
/* This is the last possible type. If more types are added, they
* should be added before this block, or the type:html tests should
* be wrapped in an if statement. */
assert(type === 'html');
assert(keys.length === 2);
assert('value' in context);
};
var stringify;
stringify = JSON.stringify;
describe('fixtures', function () {
fixtures.forEach(function (fixture) {
var baseline = JSON.parse(fixture.tree),
node,
markdown;
it('should parse `' + fixture.name + '` correctly', function () {
node = mdast.parse(fixture.input, fixture.options);
validateToken(node);
try {
assert(stringify(node) === stringify(baseline));
} catch (error) {
/* istanbul ignore next */
logDifference(
stringify(baseline, null, INDENT),
stringify(node, null, INDENT)
);
/* istanbul ignore next */
throw error;
}
});
it('should stringify `' + fixture.name + '` correctly', function () {
var generatedNode;
markdown = mdast.stringify(node, fixture.options);
generatedNode = mdast.parse(markdown, fixture.options);
try {
assert(stringify(node) === stringify(generatedNode));
} catch (error) {
/* istanbul ignore next */
logDifference(
stringify(node, null, INDENT),
stringify(generatedNode, null, INDENT)
);
/* istanbul ignore next */
throw error;
}
});
if (fixture.output) {
it('should stringify `' + fixture.name + '` to its input',
function () {
try {
assert(fixture.input === markdown);
} catch (error) {
/* istanbul ignore next */
logDifference(fixture.input, markdown);
/* istanbul ignore next */
throw error;
}
}
);
}
});
});
/* istanbul ignore next */
/**
* Log the difference between `value` and `alternative`.
*
* @param {string} value
* @param {string} alternative
*/
function logDifference(value, alternative) {
var difference;
difference = diff.diffLines(value, alternative);
if (difference && difference.length) {
difference.forEach(function (change) {
var colour;
colour = change.added ? 'green' : change.removed ? 'red' : 'dim';
process.stdout.write(chalk[colour](change.value));
});
}
}
| JavaScript | 0.000005 | @@ -432,16 +432,30 @@
t.parse(
+value, options
)', func
@@ -456,32 +456,32 @@
, function () %7B%0A
-
it('should b
@@ -607,16 +607,28 @@
ringify(
+ast, options
)', func
@@ -741,31 +741,306 @@
function');%0A
-
%7D);
+%0A%0A it('should throw when %60options.bullet%60 is not a valid bullet',%0A function () %7B%0A assert.throws(function () %7B%0A mdast.stringify(%7B%7D, %7B%0A 'bullet': true%0A %7D);%0A %7D, /options%5C.bullet/);%0A %7D%0A );
%0A%7D);%0A%0Avar va
|
23a9349c33e78a545e6903deafa05721bd0c1ba3 | change mocha default timeout again | test/index.js | test/index.js | 'use strict';
var should = require('should');
var path = require('path');
var fs = require('fs');
var rewire = require('rewire');
var pngdefry = rewire('../lib/index');
var Magic = require('mmmagic').Magic;
var magic = new Magic();
describe('Index', function() {
describe('#pngdefry()', function() {
it('should repair png success', function(done) {
this.timeout(5000);
var input = path.join(__dirname, 'img', 'icon.png');
var output = path.join(__dirname, 'img', 'icon-new.png');
pngdefry(input, output, function(err) {
if (err) {
return;
}
magic.detectFile(output, function(err, result) {
if (err) {
throw err;
}
// result=>PNG image data, 60 x 60, 8-bit/color RGBA, non-interlaced
result.should.match(/non-interlaced/);
fs.unlinkSync(output);
done();
});
});
});
});
describe('#getOutputDir()', function() {
it('should return a path that not contain the file name', function() {
var output = path.join('Users', 'forsigner', 'repos', 'icon-new.png');
var ouputDir = pngdefry.__get__('getOutputDir')(output);
ouputDir.should.equal(path.join('Users', 'forsigner', 'repos'));
});
});
describe('#getOutputFilePath()', function() {
it('should return a path that not contain the file name', function() {
var input = path.join('Users', 'forsigner', 'repos', 'icon.png');
var outputDir = path.join('Users', 'forsigner', 'repos');
var suffix = '-new';
var outputFilePath = pngdefry.__get__('getOutputFilePath')(input, outputDir, suffix);
outputFilePath.should.equal(path.join('Users', 'forsigner', 'repos', 'icon-new.png'));
});
});
});
| JavaScript | 0 | @@ -374,16 +374,17 @@
out(5000
+0
);%0A
|
7df05e77dd6510fde3d3186db377b1291335e6a4 | test for var arrays | test/index.js | test/index.js | var tape = require('tape')
var crypto = require('crypto')
var b = require('../')
tape('simple', function (t) {
var byte = b.int8
var double = b.DoubleBE
t.equal(byte.decode(byte.encode(9)), 9)
var r = Math.random()
t.equal(double.decode(double.encode(r)), r)
t.end()
})
tape('vector', function (t) {
var double = b.DoubleBE
var vector = b({
x: double,
y: double,
z: double
})
var v = {x: 1, y: 2, z: 3}
var buffer = vector.encode(v)
console.log(buffer)
t.equal(buffer.length, vector.length)
t.deepEqual(vector.decode(buffer), v)
t.end()
})
tape('buffer', function (t) {
var sha256 = b.array(32) //a fixed length buffer
var message = b({
num : b.int8,
hash: sha256
})
t.equal(message.length, 33)
var expected = {
num: 25,
hash: crypto.createHash('sha256').digest()
}
var buffer = message.encode(expected)
t.equal(buffer.length, 33)
t.deepEqual(message.decode(buffer), expected)
t.end()
})
tape('varbuf', function (t) {
var slice = b.varbuf(b.int8)
var expected = new Buffer([1, 2, 3, 4, 5])
var buffer = slice.encode(expected)
t.deepEqual(buffer, new Buffer([5, 1, 2, 3, 4, 5]))
t.deepEqual(slice.decode(buffer), expected)
t.end()
})
tape('varbuf + static', function (t) {
var sha256 = b.array(32)
var message = b({
prev: sha256,
author: sha256,
sequence: b.UInt32BE,
type: sha256,
message: b.varbuf(b.int8)
})
var empty = crypto.createHash('sha256').digest()
var zeros = new Buffer(32); zeros.fill()
var expected = {
prev : empty, author : empty,
sequence : 0, type : zeros,
message : new Buffer('hello there this is the first message', 'utf8')
}
var buffer = message.encode(expected)
console.log(buffer)
t.deepEqual(message.decode(buffer), expected)
t.end()
})
tape('varint buffer', function (t) {
var buf = b.varbuf(b.varint)
var buffer = buf.encode(new Buffer('hello'))
console.log('out', buffer)
t.deepEqual(new Buffer([0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f]), buffer)
var expected = new Buffer(
'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
+ 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
)
var buffer = buf.encode(expected)
console.log(buffer)
t.equal(buffer.length, expected.length + 2)
t.deepEqual(buf.decode(buffer), expected)
t.end()
})
| JavaScript | 0.000003 | @@ -2713,28 +2713,558 @@
er), expected)%0A t.end()%0A%7D)%0A
+%0Atape('vararray', function (t) %7B%0A%0A var array = b.vararray(b.byte, b.DoubleBE)%0A var expected = %5B%0A Math.random(), Math.random(), Math.random(), Math.random(),%0A Math.random(), Math.random(), Math.random(), Math.random(),%0A Math.random(), Math.random(), Math.random(), Math.random(),%0A Math.random(), Math.random(), Math.random(), Math.random(),%0A %5D%0A%0A t.equal(array.dynamicLength(expected), 1 + 8*4*4)%0A var buffer = array.encode(expected)%0A console.log(buffer)%0A t.deepEqual(array.decode(buffer), expected)%0A t.end()%0A%7D)%0A
|
4e3d017aaa59222864a5268886d1b7d92c2321d0 | add constructor tests | test/index.js | test/index.js | (function() {
module('DLV', {
setup: function() {
},
teardown: function() {
}
});
test('initialize', 0, function() {
});
})();
| JavaScript | 0 | @@ -139,12 +139,25 @@
lize
+ with nothing
',
-0
+1
, fu
@@ -163,24 +163,372 @@
unction() %7B%0A
+ var dlv = new DLV();%0A ok(!dlv.listeners, 'no constructor instance listeners'); %0A %7D);%0A test('initialize with listeners', 1, function() %7B%0A var listeners = %7B%7D;%0A var dlv = new DLV(%7B%0A listeners: listeners%0A %7D);%0A strictEqual(dlv.listeners, listeners, 'constructor instance listeners');
%0A %7D);
|
e8141353210b4c2867d010a93b3249a34b0e15e9 | move dependency | test/index.js | test/index.js | var _ = require('lodash')
, path = require('path')
, should = require('chai').should()
, speech = require('../index')
, en = path.join(__dirname, 'fixtures/en.mp3')
, es = path.join(__dirname, 'fixtures/es.mp3')
, lengthy = path.join(__dirname, 'fixtures/lengthy.mp3')
, natural = require('natural')
, profanity = path.join(__dirname, 'fixtures/profanity.mp3');
function combine(utterance, res) {
var space = utterance ? ' ' : '';
return utterance + space + res.hypotheses[0].utterance;
}
function check(text, done) {
return function (err, res) {
if (err) throw err;
res.should.be.an('array');
res[0].should.be.an('object');
res[0].status.should.equal(0);
res[0].hypotheses.should.be.an('array');
res[0].hypotheses[0].should.be.an('object');
var sentence = _.reduce(res, combine, '');
var distance = natural.JaroWinklerDistance(sentence, text);
distance.should.be.at.least(.8);
done();
};
}
describe('speech', function () {
it('should be a function', function () {
speech.should.be.a('function');
});
it('should take a string', function (done) {
this.timeout(2000);
speech(en, check('thank you very much', done));
});
it('should take an object', function (done) {
this.timeout(2000);
var opts = {file: en};
speech(opts, check('thank you very much', done));
});
it('should work in another language', function (done) {
this.timeout(2000);
var opts = {file: es, lang: 'es'};
speech(opts, check('muchas gracias', done));
});
it('should censor profanity', function (done) {
this.timeout(3000);
var opts = {file: profanity, pfilter: true};
speech(opts, check('f*** you', done));
});
it('should not censor profanity', function (done) {
this.timeout(3000);
var opts = {file: profanity, pfilter: false};
speech(opts, check('fuck you', done));
});
it('should clip long audio', function (done) {
this.timeout(12000);
var opts = {file: lengthy};
speech(opts, check('1 of the Iliad of Homer rendered into English flag vs spy Edward Earl of Derby this is a liberal Vox recording recordings are in the public domain for more information or to volunteer please visit fox.org', done));
});
}); | JavaScript | 0.000001 | @@ -15,24 +15,57 @@
e('lodash')%0A
+ , natural = require('natural')%0A
, path = r
@@ -311,41 +311,8 @@
3')%0A
- , natural = require('natural')%0A
,
|
2561548c82272cb4948f45d1fc7588d42dbe3c52 | Remove test | test/index.js | test/index.js | var assert = require("assert");
var lune = require('../lib/lune');
describe('lune', function() {
describe('#phase()', function() {
it('should return expected values for feb 17th data', function() {
var feb17 = {
phase: 0.5616632223402672,
illuminated: 0.9629393807872504,
age: 16.586245595613818,
distance: 396868.3763643785,
angular_diameter: 0.5018242066159135,
sun_distance: 147816061.66410872,
sun_angular_diameter: 0.5395080276270386
};
var lunedata = lune.phase(new Date(2014, 1, 17));
assert.equal(JSON.stringify(feb17), JSON.stringify(lunedata));
});
});
describe('#phase_hunt()', function() {
it('should return expected values for feb 17th data', function() {
var feb17phasehunt = {
new_date: '2014-01-31T02:40:35.000Z',
q1_date: '2014-02-07T00:22:34.000Z',
full_date: '2014-02-15T04:54:47.000Z',
q3_date: '2014-02-22T22:16:56.000Z',
nextnew_date: '2014-03-01T13:02:42.000Z'
};
var lunedata = lune.phase_hunt(new Date("2014-02-17"));
assert.equal(JSON.stringify(feb17phasehunt), JSON.stringify(lunedata));
});
});
});
| JavaScript | 0.000001 | @@ -655,548 +655,8 @@
%7D);
-%0A%0A describe('#phase_hunt()', function() %7B%0A it('should return expected values for feb 17th data', function() %7B%0A%0A var feb17phasehunt = %7B%0A new_date: '2014-01-31T02:40:35.000Z',%0A q1_date: '2014-02-07T00:22:34.000Z',%0A full_date: '2014-02-15T04:54:47.000Z',%0A q3_date: '2014-02-22T22:16:56.000Z',%0A nextnew_date: '2014-03-01T13:02:42.000Z'%0A %7D;%0A%0A var lunedata = lune.phase_hunt(new Date(%222014-02-17%22));%0A%0A assert.equal(JSON.stringify(feb17phasehunt), JSON.stringify(lunedata));%0A %7D);%0A %7D);
%0A%7D);
|
59b726c1fee0b9c2dd3cf0c7c79541f287389818 | Fix support for ember-3.4.0-beta.1 | addon/record-array.js | addon/record-array.js | import { get } from '@ember/object';
import { RecordArray } from 'ember-data/-private';
import { A } from '@ember/array';
export default class extends RecordArray {
// TODO: implement more of RecordArray but make this not an arrayproxy
replace(idx, removeAmt, newModels) {
this.replaceContent(idx, removeAmt, newModels);
}
replaceContent(idx, removeAmt, newModels) {
let _newModels = A(newModels);
let addAmt = get(_newModels, 'length');
let newInternalModels = new Array(addAmt);
for (let i = 0; i < newInternalModels.length; ++i) {
newInternalModels[i] = _newModels.objectAt(i)._internalModel;
}
this.content.replace(idx, removeAmt, newInternalModels);
this._registerWithInternalModels(newInternalModels);
}
_update() {
if (!this.query) {
throw new Error(`Can't update RecordArray without a query`);
}
let { url, params, method, cacheKey } = this.query;
return this.queryCache.queryURL(url, { params, method, cacheKey }, this);
}
_setInternalModels(internalModels /*, payload */) {
this.content.setObjects(internalModels);
this.setProperties({
isLoaded: true,
isUpdating: false,
});
this._registerWithInternalModels(internalModels);
}
_registerWithInternalModels(internalModels) {
for (let i = 0, l = internalModels.length; i < l; i++) {
let internalModel = internalModels[i];
internalModel._recordArrays.add(this);
}
}
get length() {
return this.content && this.content.length !== undefined ? this.content.length : 0;
}
}
| JavaScript | 0 | @@ -1458,16 +1458,247 @@
%7D%0A %7D%0A%0A
+ // The length property can be removed entirely once our ember-source peer dep%0A // is %3E= 3.1.0.%0A //%0A // It is not safe to override a getter on a superclass that specifies a%0A // setter as a matter of OO + es6 class semantics.%0A%0A
get le
@@ -1797,11 +1797,31 @@
: 0;%0A %7D
+%0A%0A set length(v) %7B%7D
%0A%7D%0A
|
47081a744e933404e06a3c395fc84da61a3ff18e | test index | test/index.js | test/index.js | require('./utils.test.js');
require('./otherplugins.test.js');
require('./candidateplugins.test.js');
require('./clientplugins.test.js');
require('./adminplugins.test.js');
require('./harensstalent.test.js');
require('./redis.test.js');
//require('./interview.test.js');
//require('./agencyplugins.test.js');
require('./redis.test.js');
| JavaScript | 0.000002 | @@ -222,34 +222,32 @@
edis.test.js');%0A
-//
require('./inter
@@ -266,10 +266,8 @@
');%0A
-//
requ
|
aaaa1c3d8fd0161bdc8b78b35e730e7de2bb3b03 | add deprecation warning for suggest.js (closes #7355) | trac/htdocs/js/suggest.js | trac/htdocs/js/suggest.js |
(function($){
/*
Text field auto-completion plugin for jQuery.
Based on http://www.dyve.net/jquery/?autocomplete by Dylan Verheul.
*/
$.suggest = function(input, url, paramName, minChars, delay) {
var input = $(input).addClass("suggest").attr("autocomplete", "off");
var timeout = null;
var prev = "";
var selectedIndex = -1;
var results = null;
input.keydown(function(e) {
switch(e.keyCode) {
case 27: // escape
hide();
break;
case 38: // up
case 40: // down
e.preventDefault();
if (results) {
var items = $("li", results);
if (!items) return;
var index = selectedIndex + (e.keyCode == 38 ? -1 : 1);
if (index >= 0 && index < items.length) {
move(index);
}
} else {
show();
}
break;
case 9: // tab
case 13: // return
case 39: // right
if (results) {
var li = $("li.selected", results);
if (li.length) {
select(li);
e.preventDefault();
}
}
break;
default:
if (timeout) clearTimeout(timeout);
timeout = setTimeout(show, delay);
break;
}
});
input.blur(function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(hide, 200);
});
function hide() {
if (timeout) clearTimeout(timeout);
input.removeClass("loading");
if (results) {
results.fadeOut("fast").remove();
results = null;
}
$("iframe.iefix").remove();
selectedIndex = -1;
}
function move(index) {
if (!results) return;
items = $("li", results);
items.removeClass("selected");
$(items[index]).addClass("selected");
selectedIndex = index;
}
function select(li) {
if (!li) li = $("<li>");
else li = $(li);
var val = $.trim(li.text());
prev = val;
input.val(val);
hide();
selectedIndex = -1;
}
function show() {
var val = input.val();
if (val == prev) return;
prev = val;
if (val.length < minChars) { hide(); return; }
input.addClass("loading");
var params = {};
params[paramName] = val;
$.get(url, params, function(data) {
if (!data) { hide(); return; }
if (!results) {
var offset = input.offset();
results = $("<div>").addClass("suggestions").css({
position: "absolute",
minWidth: input.get(0).offsetWidth + "px",
top: (offset.top + input.get(0).offsetHeight) + "px",
left: offset.left + "px",
zIndex: 2
}).appendTo("body");
if ($.browser.msie) {
var iframe = $("<iframe style='display:none;position:absolute;" +
"filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);'" +
" class='iefix' src='javascript:false;' frameborder='0'" +
" scrolling='no'></iframe>").insertAfter(results);
setTimeout(function() {
var offset = $(results).offset();
iframe.css({
top: offset.top + "px",
right: (offset.left + results.get(0).offsetWidth) + "px",
bottom: (offset.top + results.get(0).offsetHeight) + "px",
left: offset.left + "px",
zIndex: 1
});
iframe.show();
}, 10);
}
}
results.html(data).fadeTo("fast", 0.92);
items = $("li", results);
items
.hover(function() { move(items.index(this)) },
function() { $(this).removeClass("selected") })
.click(function() { select(this); input.get(0).focus() });
move(0);
}, 'html');
}
}
$.fn.suggest = function(url, paramName, minChars, delay) {
url = url || window.location.pathname;
paramName = paramName || 'q';
minChars = minChars || 1;
delay = delay || 400;
return this.each(function() {
new $.suggest(this, url, paramName, minChars, delay);
});
}
})(jQuery);
| JavaScript | 0.000001 | @@ -1,8 +1,226 @@
+/* Warning: this module is deprecated and will be removed in Trac 1.1.x%0A *%0A * Don't use $.suggest in your own plugins, rather look into jquery-ui's%0A * autocomplete features (http://docs.jquery.com/UI/Autocomplete).%0A */
%0A(functi
|
46fdc14f70f0911f27ed7eeca14515cb70ae57eb | add test for preid | test/index.js | test/index.js | 'use strict';
var gutil = require('gulp-util');
var should = require('should');
var bump = require('..');
require('mocha');
describe('gulp-bump: JSON comparison fixtures', function() {
it('should bump patch version by default', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{ "version": "0.0.9" }'),
path: 'test/fixtures/test.json'
});
var bumpS = bump();
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).version.should.equal('0.0.10');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
it('should bump patch version as default and a key=appversion', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{ "appversion": "0.0.1" }'),
path: 'test/fixtures/test.json'
});
var bumpS = bump({key: 'appversion'});
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).appversion.should.equal('0.0.2');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
it('should ignore invalid type and use type=patch', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{ "version": "0.0.1" }'),
path: 'test/fixtures/test.json'
});
var bumpS = bump({type: 'invalidType'});
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).version.should.equal('0.0.2');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
it('should set the correct version when supplied', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{ "version": "0.0.1" }'),
path: 'test/fixtures/test.json'
});
var bumpS = bump({version: '0.0.2'});
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).version.should.equal('0.0.2');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
it('should set the correct version when supplied even if key did not exist', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{}'),
path: 'test/fixtures/test.json'
});
var bumpS = bump({version: '0.0.2'});
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).version.should.equal('0.0.2');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
it('should bump prerelease version', function(done) {
var fakeFile = new gutil.File({
contents: new Buffer('{ "version": "0.0.1-0"}'),
path: 'test/fixtures/test.json'
});
var bumpS = bump({type: 'prerelease'});
bumpS.once('data', function(newFile) {
should.exist(newFile);
should.exist(newFile.contents);
JSON.parse(newFile.contents.toString()).version.should.equal('0.0.1-1');
return done();
});
bumpS.write(fakeFile);
bumpS.end();
});
});
| JavaScript | 0 | @@ -3279,13 +3279,1160 @@
);%0A %7D);
+%0A%0A it('should add and bump preid version', function(done) %7B%0A var fakeFile = new gutil.File(%7B%0A contents: new Buffer('%7B %22version%22: %220.1.0%22%7D'),%0A path: 'test/fixtures/test.json'%0A %7D);%0A%0A var bumpS = bump(%7Btype: 'prerelease', preid: 'beta'%7D);%0A%0A bumpS.once('data', function(newFile) %7B%0A should.exist(newFile);%0A should.exist(newFile.contents);%0A console.log(String(newFile.contents));%0A JSON.parse(newFile.contents.toString()).version.should.equal('0.1.1-beta.0');%0A return done();%0A %7D);%0A bumpS.write(fakeFile);%0A bumpS.end();%0A %7D);%0A%0A it('should bump preid version', function(done) %7B%0A var fakeFile = new gutil.File(%7B%0A contents: new Buffer('%7B %22version%22: %220.1.0-zeta.1%22%7D'),%0A path: 'test/fixtures/test.json'%0A %7D);%0A%0A var bumpS = bump(%7Btype: 'prerelease', preid: 'zeta'%7D);%0A%0A bumpS.once('data', function(newFile) %7B%0A should.exist(newFile);%0A should.exist(newFile.contents);%0A console.log(String(newFile.contents));%0A JSON.parse(newFile.contents.toString()).version.should.equal('0.1.0-zeta.2');%0A return done();%0A %7D);%0A bumpS.write(fakeFile);%0A bumpS.end();%0A %7D);
%0A%7D);%0A
|
e8de9dcb206afd9556b4a0ac8f00d341a50e5f83 | Update test to use Apiary mock server. | test/index.js | test/index.js | /**
* test/index.js
* Contains tests for client entry point.
*
* @author Francis Brito <fr.br94@gmail.com>
* @license MIT
*/
/* global describe, it, before */
/* jshint expr:true */
'use strict';
require('should');
var Client = require('../').Client;
var LOCAL_TEST_SERVER = 'http://localhost:3000';
describe('Client', function () {
describe('constructor', function () {
it('should throw if no API key is provided.', function () {
(function () {
new Client();
}).should.throw('No API key provided.');
});
it('should use default API endpoint if none is provided.', function () {
var client = new Client('some api key');
// NOTE: Accessing client's private API, so sort of breaking the rules here.
client._endpoint.should.eql(Client.DEFAULT_API_URL);
});
it('should use latest API version if none is specified.', function () {
var client = new Client('some api key');
client._version.should.eql(Client.DEFAULT_API_VERSION);
});
});
describe('#getProducts', function () {
before(function () {
this.client = new Client('some api token', {
endpoint: LOCAL_TEST_SERVER
});
});
it('should filter products by `filter` parameter.', function (next) {
var filter = {
kind: 'Canvas'
};
this.client.getProducts(filter, function (err, products) {
every(products, isACanvas).should.be.true;
next();
});
});
it('should not require `filter` parameter.', function (next) {
var self = this;
(function () {
// Note: try/catch is required so Mocha.js doesn't stop test execution upon receiving type error.
try {
self.client.getProducts(function (err, products) {
products.should.be.ok.and.be.an.Array;
next();
});
} catch(err) {
throw err;
}
}).should.not.throw();
});
it('should throw if API endpoint is not reachable.', function (next) {
this.timeout(5 * 1000);
var client = new Client('some api token', {
endpoint: 'http://not-reachable:3001'
});
client.getProducts(function (err) {
err.should.be.ok;
err.message.should.eql('Endpoint "http://not-reachable:3001" not reachable.');
next();
});
});
it('should throw if API endpoint responds with a server error.', function (next) {
var client = new Client('some api token', {
endpoint: 'http://localhost:3000/server-error'
});
client.getProducts(function (err) {
(err !== null).should.be.true;
err.message.should.eql('Server responded with an error.');
err.inner.should.eql('Cannot GET /server-error/1/products?');
next();
});
});
});
describe('#getProductById', function () {
before(function () {
this.client = new Client('some api token', {
endpoint: LOCAL_TEST_SERVER
});
});
it('should throw if no product with id `id` is found.', function (next) {
this.client.getProductById('unexistent', function (err) {
(!!err).should.be.true;
err.message.should.eql('Could not find product with id "unexistent"');
next();
});
});
it('should throw if no `id` field is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#getPrintFiles', function () {
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#getPrintFileById', function () {
it('should throw if no print file with id `id` is found.');
it('should throw if no `id` field is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#createPrintFile', function () {
it('should throw if no `fields` parameter is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#getOrders', function () {
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#getOrderById', function () {
it('should throw if no order with id `id` is found.');
it('should throw if no `id` field is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#createOrder', function () {
it('should throw if no `fields` parameter is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#updateOrder', function () {
it('should throw if no order with id `id` is found.');
it('should throw if no `id` field is provided.');
it('should throw if order has already being confirmed.');
it('should throw if no `fields` parameter is provided.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
describe('#confirmOrder', function () {
it('should throw if no order with id `id` is found.');
it('should throw if no `id` field is provided.');
it('should throw if order was already confirmed.');
it('should throw if API endpoint is not reachable.');
it('should throw if API endpoint responds with a server error.');
});
});
/*
* Helpers
*/
function isACanvas(c) { return c.kind === 'Canvas'; }
function every(array, predicate) { return array.every(predicate); }
| JavaScript | 0 | @@ -257,21 +257,18 @@
t;%0A%0Avar
-LOCAL
+PH
_TEST_SE
@@ -282,30 +282,61 @@
'http://
-localhost:3000
+private-50d6dc-printhouse.apiary-mock.com/api
';%0A%0Adesc
@@ -1268,37 +1268,34 @@
endpoint:
-LOCAL
+PH
_TEST_SERVER%0A
@@ -3413,13 +3413,10 @@
nt:
-LOCAL
+PH
_TES
|
ae6edf624bb53789796b5e0568791461d8cb6d94 | test that abort works correctly, even with a null item | test/index.js | test/index.js |
var pull = require('pull-stream')
var cat = require('../')
require('tape')('cat', function (t) {
cat([pull.values([1,2,3]), pull.values([4,5,6])])
.pipe(pull.collect(function (err, ary) {
console.log(err, ary)
t.notOk(err)
t.deepEqual(ary, [1,2,3,4,5,6])
t.end()
}))
})
require('tape')('cat - with empty', function (t) {
cat([pull.values([1,2,3]), null, pull.values([4,5,6])])
.pipe(pull.collect(function (err, ary) {
console.log(err, ary)
t.notOk(err)
t.deepEqual(ary, [1,2,3,4,5,6])
t.end()
}))
})
require('tape')('cat - with empty stream', function (t) {
var ended = false
var justEnd = function (err, cb) { ended = true; cb(true) }
cat([pull.values([1,2,3]), justEnd, pull.values([4,5,6])])
.pipe(pull.collect(function (err, ary) {
console.log(err, ary)
t.ok(ended)
t.notOk(err)
t.deepEqual(ary, [1,2,3,4,5,6])
t.end()
}))
})
| JavaScript | 0 | @@ -54,17 +54,27 @@
('../')%0A
-%0A
+var test =
require(
@@ -76,24 +76,30 @@
uire('tape')
+%0A%0Atest
('cat', func
@@ -303,39 +303,28 @@
%0A %7D))%0A%0A%7D)%0A%0A
-require('tape')
+test
('cat - with
@@ -551,31 +551,20 @@
))%0A%0A%7D)%0A%0A
-require('tape')
+test
('cat -
@@ -881,28 +881,245 @@
5,6%5D)%0A t.end()%0A %7D))%0A
-%0A
%7D)%0A
+%0A%0A%0Atest('abort - with empty', function (t) %7B%0A%0A cat(%5Bpull.values(%5B1,2,3%5D), null, pull.values(%5B4,5,6%5D)%5D)%0A .pipe(function (read) %7B%0A read(true, function (err) %7B%0A t.equal(err, true)%0A t.end()%0A %7D)%0A %7D)%0A%0A%7D)%0A%0A
|
fb1b96f20fada2cb9382e3ac12b0ec95ae1d08a1 | Test getDocumentById & getDocumentByIdentifier | test/index.js | test/index.js | 'use strict';
var should = require('should');
var Anyfetch = require('../lib/index.js');
var configuration = require('../config/configuration.js');
// Tests to write:
// getStatus()
// getCompany()
// getSubcompanyById()
// postUser()
// postCompanyUpdate()
// getDocumentById(123).getRaw()
// getDocumentById(123, cb)
var testEndpoint = function(name){
describe(name, function(){
describe('the request', function(){
var expected = configuration.apiDescriptors[name];
var r = null;
before(function(done){
// TODO: support id, identifier
Anyfetch[name](function(err, res) {
r = res;
done(err);
});
});
it('should use the correct verb', function(){
r.req.method.should.equal(expected.verb);
});
it('should target the correct endpoint', function(){
r.req.path.should.equal(expected.endpoint);
});
it('should have the expected return code', function(){
r.res.statusCode.should.equal(expected.expectedStatus);
});
});
});
};
testEndpoint('getStatus');
testEndpoint('getIndex');
testEndpoint('getCompany');
testEndpoint('postCompanyUpdate');
testEndpoint('getDocuments');
testEndpoint('getUsers');
describe('getDocumentById', function(){
describe('subfunctions', function(){
it('should return synchronously an object containing only functions', function(){
var ret = Anyfetch.getDocumentById(123);
// TODO: Test that `ret` is an object of functions
});
});
}); | JavaScript | 0 | @@ -142,16 +142,75 @@
on.js');
+%0Avar isFunction = require('../lib/helpers/is-function.js');
%0A%0A// Tes
@@ -1381,193 +1381,1153 @@
-it('should return synchronously an object containing only functions', function()%7B%0A var ret = Anyfetch.getDocumentById(123);%0A // TODO: Test that %60ret%60 is an object of functions
+var subFunctions = Anyfetch.getDocumentById(123);%0A var subFunctionsByIdentifier = Anyfetch.getDocumentByIdentifier('aze');%0A%0A it('should return synchronously an object containing only functions', function()%7B%0A for(var i in subFunctions) %7B%0A isFunction(subFunctions%5Bi%5D).should.be.ok;%0A %7D%0A %7D);%0A%0A it('should only accept mongo-style ids', function()%7B%0A Anyfetch.getDocumentById('aze').getRelated(function(err)%7B%0A err.message.toLowerCase().should.include('argument error');%0A %7D);%0A %7D);%0A%0A describe('getDocumentByIdentifier', function()%7B%0A it('should offer the same functions as byId', function()%7B%0A Object.keys(subFunctionsByIdentifier).length.should.equal(Object.keys(subFunctions).length);%0A%0A for(var i in subFunctionsByIdentifier) %7B%0A isFunction(subFunctionsByIdentifier%5Bi%5D).should.be.ok;%0A subFunctions%5Bi%5D.should.be.ok;%0A %7D%0A %7D);%0A%0A it('should accept any kind of identifier', function()%7B%0A Anyfetch.getDocumentByIdentifier('aze').getRelated(function(err)%7B%0A err.message.toLowerCase().should.not.include('argument error');%0A %7D);%0A %7D);
%0A
@@ -2527,21 +2527,22 @@
%7D);%0A %7D);%0A
+%0A
%7D);%0A%7D);
|
aea37f9ea9029ce23ec0e7502ed66c598caaa31e | add unit test purchase order | test/index.js | test/index.js | function test(name, path) {
describe(name, function () {
require(path);
});
}
describe('#dl-module', function (done) {
this.timeout(2 * 60000);
// Auth
test('@AUTH/ACCOUNT', './auth/account');
test('@AUTH/ROLE', './auth/role');
test('@AUTH/API-ENDPOINT', './auth/api-endpoint');
//Etl
test('@ETL/DIM-BUYER', './etl/dim/dim-buyer');
test('@ETL/DIM-CATEGORY', './etl/dim/dim-category');
test('@ETL/DIM-DIVISION', './etl/dim/dim-division');
test('@ETL/DIM-SUPPLIER', './etl/dim/dim-supplier');
test('@ETL/DIM-MACHINE', './etl/dim/dim-machine');
test('@ETL/DIM-UNIT', './etl/dim/dim-unit');
test('@ETL/DIM-PROCESS-TYPE', './etl/dim/dim-process-type');
test('@ETL/DIM-ORDER-TYPE', './etl/dim/dim-order-type');
test('@ETL/DIM-PRODUCT', './etl/dim/dim-product');
test('@ETL/DIM-STORAGE', './etl/dim/dim-storage');
test('@ETL/FACT-TOTAL-HUTANG', './etl/purchasing/fact-total-hutang');
test('@ETL/FACT-PURCHASING', './etl/purchasing/fact-purchasing');
test('@ETL/FACT-MONITORING-EVENT', './etl/production/fact-monitoring-event');
test('@ETL/FACT-PRODUCTION-ORDER', './etl/production/fact-production-order');
test('@ETL/FACT-PRODUCTION-ORDER-STATUS', './etl/sales/fact-production-order-status');
test('@ETL/FACT-WEAVING-SALES-CONTRACT', './etl/sales/fact-weaving-sales-contract');
test('@ETL/FACT-FINISHING-PRINTING-SALES-CONTRACT', './etl/sales/fact-finishing-printing-sales-contract');
test('@ETL/FACT-SPINNING-SALES-CONTRACT', './etl/sales/fact-spinning-sales-contract');
test('@ETL/FACT-DAILY-OPERATIONS', './etl/production/fact-daily-operations');
test('@ETL/FACT-KANBAN', './etl/production/fact-kanban');
test('@ETL/FACT-QUALITY-CONTROL', './etl/production/fact-fabric-quality-control');
test('@ETL/FACT-INVENTORY-MOVEMENT', './etl/inventory/fact-inventory-movement');
test('@ETL/FACT-INVENTORY-SUMMARY', './etl/inventory/fact-inventory-summary');
// Master
test('@MASTER/ACCOUNT-BANK', './master/account-bank');
test('@MASTER/BUDGET', './master/budget');
test('@MASTER/BUYER', './master/buyer');
test('@MASTER/CATEGORY', './master/category');
test('@MASTER/CURRENCY', './master/currency');
test('@MASTER/DIVISION', './master/division');
test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
test('@MASTER/LOT-MACHINE', './master/lot-machine');
test('@MASTER/MACHINE', './master/machine');
test('@MASTER/PRODUCT', './master/product');
test('@MASTER/GARMENT-PRODUCT', './master/garment-product');
test('@MASTER/SUPPLIER', './master/supplier');
test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
test('@MASTER/UNIT', './master/unit');
test('@MASTER/UOM', './master/uom');
test('@MASTER/USTER', './master/uster');
test('@MASTER/VAT', './master/vat');
test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
test('@MASTER/ORDER-TYPE', './master/order-type');
test('@MASTER/PROCESS-TYPE', './master/process-type');
test('@MASTER/COLOR-TYPE', './master/color-type');
test('@MASTER/INSTRUCTION', './master/instruction');
// test('@MASTER/MONITORING-EVENT-TYPE', './master/monitoring-event-type');
test('@MASTER/STEP', './master/step');
//test('@MASTER/MACHINE-TYPE', './master/machine-type');
test('@MASTER/MACHINE-SPESIFICATION-STANDARD', './master/machine-spesification-standard');
test('@MASTER/MATERIAL-CONSTRUCTION', './master/material-construction');
test('@MASTER/YARN-MATERIAL', './master/yarn-material');
test('@MASTER/STANDARD-TEST', './master/standard-test');
test('@MASTER/FINISH-TYPE', './master/finish-type');
test('@MASTER/COMODITY', './master/comodity');
test('@MASTER/QUALITY', './master/quality');
test('@MASTER/TERM OF PAYMENT', './master/term-of-payment');
test('@MASTER/DESIGN-MOTIVE', './master/design-motive');
test('@MASTER/STORAGE', './master/storage');
//Purchasing
test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');
test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');
test('@purchasing/purchase-order/report', './purchasing/duration-report');
//Garmet Purchasing
test('@GARMENT PURCHASING/PURCHASE REQUEST', './garment-purchasing/purchase-request');
//Sales
test('@SALES/PRODUCTION-ORDER', './sales/production-order');
test('@SALES/FINISHING PRINTING SALES CONTRACT', './sales/finishing-printing-sales-contract');
test('@SALES/SPINNING SALES CONTRACT', './sales/spinning-sales-contract');
test('@SALES/WEAVING SALES CONTRACT', './sales/weaving-sales-contract');
//Production
test('@PRODUCTION/FINISHING-PRINTING/KANBAN', './production/finishing-printing/kanban');
test('@PRODUCTION/FINISHING-PRINTING/FABRIC-QUALITY-CONTROL', './production/finishing-printing/fabric-quality-control');
test('@PRODUCTION/FINISHING-PRINTING/PACKING', './production/finishing-printing/packing');
test('@PRODUCTION/DAILY OPERATION', './production/finishing-printing/daily-operation');
test('@PRODUCTION/FINISHING-PRINTING/MONITORING-SPECIFICATION-MACHINE', './production/finishing-printing/monitoring-specification-machine');
test('@PRODUCTION/FINISHING-PRINTING/MONITORING-EVENT', './production/finishing-printing/monitoring-event');
test('@PRODUCTION/INSPECTION LOT COLOR', './production/finishing-printing/inspection-lot-color');
// test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
// test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');
test('@INVENTORY/FINISHING-PRINTING/PACKING-RECEIPT', './inventory/finishing-printing/packing-receipt');
test('@INVENTORY/INVENTORY-SUMMARY', './inventory/inventory-summary');
test('@INVENTORY/INVENTORY-MOVEMENT', './inventory/inventory-movement');
test('@INVENTORY/INVENTORY-DOCUMENT', './inventory/inventory-document');
}); | JavaScript | 0 | @@ -4974,24 +4974,120 @@
e-request');
+%0A test('@GARMENT PURCHASING/PURCHASE ORDER INTERNAL', './garment-purchasing/purchase-order');
%0A%0A //Sale
|
fa8ce405bfefe8fd962248dab2a1c1927fa7525a | Add job in cron | crontab-gen.js | crontab-gen.js | /* -----------------------------------------------------------
*
* PayWhich Currency Bot - Crontab Script Generator
* Author: Jeremy Yen (jeremy5189@gmail.com)
* License: MIT
* Repo: https://github.com/jeremy5189/payWhich
* Production: http://paywhich.pw
*
* -----------------------------------------------------------
*/
var config = require('./config.json'),
min = 0,
_headless = false,
_cron = true;
if( process.argv[2] == '--help') {
console.log('node crontab-gen.js [--headless] [--nocron]');
process.exit(0);
}
if( process.argv[2] == '--headless') {
_headless = true;
}
if( process.argv[3] == '--nocron' ) {
_cron = false;
}
for( var cur in config.map.visa) {
var cron = '';
if( _cron ) {
cron = min + ' 0,6,12,18 * * * ';
}
console.log('\n# PayWhich ' + cur);
console.log(cron + config.node_bin + ' ' + config.path + 'master.js 1 ' + cur);
if( _headless) {
cron = min + ' 0,12 * * * ';
console.log(cron + config.phantomjs_bin + ' ' + config.path + 'visa-headless.js 0 ' + cur);
}
else {
console.log(cron + config.node_bin + ' ' + config.path + 'visa.js 0 ' + cur);
}
min++;
}
| JavaScript | 0.000009 | @@ -671,16 +671,32 @@
lse;%0A%7D%0A%0A
+var cron = '';%0A%0A
for( var
@@ -727,27 +727,8 @@
%7B%0A%0A
- var cron = '';%0A
@@ -1197,8 +1197,103 @@
n++;%0A %7D%0A
+%0Aconsole.log('%5Cn# JCB');%0Aconsole.log(cron + config.node_bin + ' ' + config.path + 'jcb.js 1');%0A
|
37ab86ee77ee87404fc66c558dc581fe373e0c8f | Remove bluebird | db/seeds/create_albums.js | db/seeds/create_albums.js | // Create demo albums for 'admin' user and moderators in first forum section
//
'use strict';
const Promise = require('bluebird');
const Charlatan = require('charlatan');
const path = require('path');
const glob = require('glob').sync;
const _ = require('lodash');
const numCPUs = require('os').cpus().length;
const statuses = require('../../server/users/_lib/statuses.js');
const ALBUMS_COUNT = 7;
const MIN_ALBUM_PHOTOS = 0;
const MAX_ALBUM_PHOTOS = 5;
const MIN_COMMENTS = 3;
const MAX_COMMENTS = 15;
let fixt_root = path.join(__dirname, 'fixtures', 'create_albums');
const PHOTOS = glob('**', {
cwd: fixt_root
}).map(name => path.join(fixt_root, name));
let models;
let settings;
// Creates random photos to album from test fixtures
//
function createMedia(userId, album) {
return models.users.MediaInfo.createFile({
album_id: album,
user_id: userId,
path: PHOTOS[Charlatan.Helpers.rand(0, PHOTOS.length)]
});
}
// Creates one album
//
async function createAlbum(userId) {
var album = new models.users.Album();
album.user = userId;
album.title = Charlatan.Name.name();
await album.save();
let repeat = Charlatan.Helpers.rand(MIN_ALBUM_PHOTOS, MAX_ALBUM_PHOTOS);
for (let i = 0; i < repeat; i++) {
await createMedia(userId, album);
}
await models.users.Album.updateInfo(album._id, true);
}
// Creates multiple albums
//
// userId - albums owner
//
async function createMultipleAlbums(userId) {
for (let i = 0; i < ALBUMS_COUNT; i++) {
await createAlbum(userId);
}
}
async function createAlbums() {
let user_ids = [];
// Collect users from administrators group
// Get administrators group _id
let group = await models.users.UserGroup
.findOne({ short_name: 'administrators' })
.select('_id')
.lean(true);
let users = await models.users.User
.find({ usergroups: group._id })
.select('_id')
.lean(true);
if (users) {
user_ids = user_ids.concat(_.map(users, '_id'));
}
// Collect moderators in first forum section
// Fetch all sections
let sections = await models.forum.Section.getChildren(null, 2);
let SectionModeratorStore = settings.getStore('section_moderator');
// sections might not exist if forum seed hasn't been loaded yet
if (sections.length) {
let moderators = (await SectionModeratorStore.getModeratorsInfo(sections[0]._id))
.filter(moderator => moderator.visible)
.map(moderator => moderator._id);
user_ids = user_ids.concat(moderators);
}
user_ids = _.uniq(user_ids.map(String));
// Create albums for prepared user list
await Promise.map(user_ids, uid => createMultipleAlbums(uid), { concurrency: numCPUs });
}
// Creates random comments to media
//
function createComment(mediaId, userId) {
let comment = new models.users.Comment();
comment.user = userId;
comment.media_id = mediaId;
comment.ts = new Date();
comment.text = Charlatan.Lorem.paragraph(Charlatan.Helpers.rand(1, 2));
comment.st = statuses.comment.VISIBLE;
return comment.save();
}
// Creates multiple comments
//
async function createMultipleComments(mediaId, usersId) {
var commentsCount = Charlatan.Helpers.rand(MIN_COMMENTS, MAX_COMMENTS);
for (let i = 0; i < commentsCount; i++) {
await createComment(mediaId, usersId[Charlatan.Helpers.rand(0, usersId.length - 1)]);
}
await models.users.MediaInfo.updateOne(
{ media_id: mediaId },
{ $inc: { comments_count: commentsCount } }
);
}
async function createComments() {
let results = await models.users.MediaInfo.find().lean(true);
let usersId = _.uniq(_.map(results, 'user'));
let mediasId = _.map(results, 'media_id');
// Create comments for prepared media and user list
await Promise.map(
mediasId,
mid => createMultipleComments(mid, usersId),
{ concurrency: numCPUs }
);
}
module.exports = async function (N) {
models = N.models;
settings = N.settings;
await createAlbums();
await createComments();
};
| JavaScript | 0.000024 | @@ -93,47 +93,8 @@
;%0A%0A%0A
-const Promise = require('bluebird');%0A
cons
@@ -245,55 +245,8 @@
');%0A
-const numCPUs = require('os').cpus().length;%0A
cons
@@ -2694,19 +2694,19 @@
Promise.
-map
+all
(user_id
@@ -2706,18 +2706,21 @@
user_ids
-,
+.map(
uid =%3E c
@@ -2747,34 +2747,9 @@
uid)
-, %7B concurrency: numCPUs %7D
+)
);%0A%7D
@@ -3798,19 +3798,19 @@
Promise.
-map
+all
(%0A me
@@ -3815,22 +3815,21 @@
mediasId
-,%0A
+.map(
mid =%3E c
@@ -3867,38 +3867,9 @@
sId)
-,%0A %7B concurrency: numCPUs %7D
+)
%0A )
|
ca32895c7d4e26aff241d86a37d177dbb25499b6 | Update angleTool.js | src/imageTools/angleTool.js | src/imageTools/angleTool.js | import external from '../externalModules.js';
import mouseButtonTool from './mouseButtonTool.js';
import touchTool from './touchTool.js';
import drawTextBox from '../util/drawTextBox.js';
import roundToDecimal from '../util/roundToDecimal.js';
import toolColors from '../stateManagement/toolColors.js';
import drawHandles from '../manipulators/drawHandles.js';
import { getToolState } from '../stateManagement/toolState.js';
import lineSegDistance from '../util/lineSegDistance.js';
import { getNewContext, draw, setShadow, drawJoinedLines } from '../util/drawing.js';
const toolType = 'angle';
// /////// BEGIN ACTIVE TOOL ///////
function createNewMeasurement (mouseEventData) {
// Create the measurement data for this tool with the end handle activated
const angleData = {
visible: true,
active: true,
color: undefined,
handles: {
start: {
x: mouseEventData.currentPoints.image.x - 20,
y: mouseEventData.currentPoints.image.y + 10,
highlight: true,
active: false
},
end: {
x: mouseEventData.currentPoints.image.x,
y: mouseEventData.currentPoints.image.y,
highlight: true,
active: true
},
start2: {
x: mouseEventData.currentPoints.image.x - 20,
y: mouseEventData.currentPoints.image.y + 10,
highlight: true,
active: false
},
end2: {
x: mouseEventData.currentPoints.image.x,
y: mouseEventData.currentPoints.image.y + 20,
highlight: true,
active: false
}
}
};
return angleData;
}
// /////// END ACTIVE TOOL ///////
function pointNearTool (element, data, coords) {
if (data.visible === false) {
return false;
}
return lineSegDistance(element, data.handles.start, data.handles.end, coords) < 5 ||
lineSegDistance(element, data.handles.start2, data.handles.end2, coords) < 5;
}
// /////// BEGIN IMAGE RENDERING ///////
function onImageRendered (e) {
const eventData = e.detail;
// If we have no toolData for this element, return immediately as there is nothing to do
const toolData = getToolState(e.currentTarget, toolType);
if (toolData === undefined) {
return;
}
// We have tool data for this element - iterate over each one and draw it
const context = getNewContext(eventData.canvasContext.canvas);
const config = angle.getConfiguration();
const cornerstone = external.cornerstone;
for (let i = 0; i < toolData.data.length; i++) {
const data = toolData.data[i];
if (data.visible === false) {
continue;
}
draw(context, (context) => {
// Configurable shadow
setShadow(context, config);
// Differentiate the color of activation tool
const color = toolColors.getColorIfActive(data);
drawJoinedLines(context, eventData.element, data.handles.end, [data.handles.start, data.handles.end2], { color });
// Draw the handles
drawHandles(context, eventData, data.handles);
// Need to work on correct angle to measure. This is a cobb angle and we need to determine
// Where lines cross to measure angle. For now it will show smallest angle.
const dx1 = (Math.ceil(data.handles.start.x) - Math.ceil(data.handles.end.x)) * eventData.image.columnPixelSpacing;
const dy1 = (Math.ceil(data.handles.start.y) - Math.ceil(data.handles.end.y)) * eventData.image.rowPixelSpacing;
const dx2 = (Math.ceil(data.handles.start2.x) - Math.ceil(data.handles.end2.x)) * eventData.image.columnPixelSpacing;
const dy2 = (Math.ceil(data.handles.start2.y) - Math.ceil(data.handles.end2.y)) * eventData.image.rowPixelSpacing;
let angle = Math.acos(Math.abs(((dx1 * dx2) + (dy1 * dy2)) / (Math.sqrt((dx1 * dx1) + (dy1 * dy1)) * Math.sqrt((dx2 * dx2) + (dy2 * dy2)))));
angle *= (180 / Math.PI);
const rAngle = roundToDecimal(angle, 2);
const str = '00B0'; // Degrees symbol
const text = rAngle.toString() + String.fromCharCode(parseInt(str, 16));
const handleStartCanvas = cornerstone.pixelToCanvas(eventData.element, data.handles.start2);
const handleEndCanvas = cornerstone.pixelToCanvas(eventData.element, data.handles.end2);
const textX = (handleStartCanvas.x + handleEndCanvas.x) / 2;
const textY = (handleStartCanvas.y + handleEndCanvas.y) / 2;
drawTextBox(context, text, textX, textY, color);
});
}
}
// /////// END IMAGE RENDERING ///////
// Module exports
const angle = mouseButtonTool({
createNewMeasurement,
onImageRendered,
pointNearTool,
toolType
});
const angleTouch = touchTool({
createNewMeasurement,
onImageRendered,
pointNearTool,
toolType
});
export {
angle,
angleTouch
};
| JavaScript | 0.000001 | @@ -3157,16 +3157,158 @@
angle.%0A
+ const columnPixelSpacing = eventData.image.columnPixelSpacing %7C%7C 1;%0A const rowPixelSpacing = eventData.image.rowPixelSpacing %7C%7C 1;%0A
co
@@ -3385,32 +3385,16 @@
d.x)) *
-eventData.image.
columnPi
@@ -3491,32 +3491,16 @@
d.y)) *
-eventData.image.
rowPixel
@@ -3596,32 +3596,16 @@
2.x)) *
-eventData.image.
columnPi
@@ -3704,32 +3704,16 @@
2.y)) *
-eventData.image.
rowPixel
|
55f04c2615d8348af9f58f83772f205a0d42fe1a | Update quotes daily | backend/server.js | backend/server.js | const express = require('express');
const app = express();
const shuffle = require('shuffle-array');
const host = '127.0.0.1';
const port = 3000;
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017/dailyquote';
MongoClient.connect(url, (err, database) => {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
res.send("db error")
} else {
console.log('Connection established to', url);
db = database;
app.listen(port);
console.log("Listening on port 3000");
}
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
/**
* Return a random quote.
*/
app.get('/quote', (req, res) => {
db.collection('quotes').find({}).toArray(function(err, result) {
if (err) {
console.log(err);
res.send("db error")
} else if (result.length) {
console.log('Select random quote');
res.send(shuffle.pick(result));
} else {
console.log('No documents found')
res.send("Empty set");
}
});
})
| JavaScript | 0 | @@ -931,14 +931,21 @@
on('
+current_
quote
-s
').f
@@ -1031,222 +1031,855 @@
- res.send(%22db error%22)%0A %7D else if (result.length) %7B%0A console.log('Select random
+%7D else %7B%0A var d = new Date();%0A if (result%5B0%5D.weekday === d.getDay()) %7B%0A res.send(result%5B0%5D.quote);%0A %7D else %7B%0A getNewQuote(function(response) %7B%0A res.send(response);%0A console.log(response);%0A %7D);%0A %7D%0A %7D%0A %7D);%0A%7D)%0A%0Afunction getNewQuote(callback) %7B%0A db.collection('
quote
+s
')
-;%0A res.send(shuffle.pick(result));%0A %7D else %7B%0A console.log('No documents found')%0A res.send(%22Empty set%22
+.find(%7B%7D).toArray(function(err, result) %7B%0A if (err) %7B%0A callback(%22db error%22);%0A console.log(err);%0A %7D else if (result.length) %7B%0A var newQuote = shuffle.pick(result);%0A var d = new Date();%0A db.collection('current_quote').update(%7B%7D, %7B$set: %7Bquote: newQuote%7D%7D);%0A db.collection('current_quote').update(%7B%7D, %7B$set: %7Bweekday: d.getDay()%7D%7D);%0A callback(newQuote);%0A console.log('Select new random quote');%0A %7D else %7B%0A callback(%22Empty set%22);%0A console.log('No documents found'
);%0A
@@ -1878,22 +1878,21 @@
und');%0A %7D%0A %7D);%0A%7D
-)
%0A
|
311c994ec373e421adaeb2cce4c9741b1097cc15 | make instance delegate method read-only | src/instance/constructor.js | src/instance/constructor.js | import defaults from './defaults'
import noop from './noop'
import clean from './methods/clean'
import destroy from './methods/destroy'
import reveal from './methods/reveal'
import sync from './methods/sync'
import delegate from './functions/delegate'
import { isMobile, transformSupported, transitionSupported } from '../utils/browser'
import { getNode, logger } from '../utils/core'
import { deepAssign } from '../utils/generic'
import { version } from '../../package.json'
export default function ScrollReveal (options = {}) {
/**
* Support instantiation without the `new` keyword.
*/
if (typeof this === 'undefined' || Object.getPrototypeOf(this) !== ScrollReveal.prototype) {
return new ScrollReveal(options)
}
if (!ScrollReveal.isSupported()) {
logger('Instantiation aborted.', 'This browser is not supported.')
return noop
}
try {
Object.defineProperty(this, 'defaults', {
get: (() => {
const config = {}
deepAssign(config, defaults, options)
return () => config
})(),
})
} catch (error) {
logger('Instantiation failed.', 'Invalid configuration provided.', error.message)
return noop
}
const container = getNode(this.defaults.container)
if (!container) {
logger('Instantiation failed.', 'Invalid or missing container.')
return noop
}
if (this.defaults.mobile === isMobile() || this.defaults.desktop === !isMobile()) {
document.documentElement.classList.add('sr')
}
this.store = {
containers: {},
elements: {},
history: [],
sequences: {},
}
this.pristine = true
this.delegate = delegate.bind(this)
Object.defineProperty(this, 'version', {
get: () => version,
})
Object.defineProperty(this, 'noop', {
get: () => false,
})
}
ScrollReveal.isSupported = () => transformSupported() && transitionSupported()
ScrollReveal.prototype.clean = clean
ScrollReveal.prototype.destroy = destroy
ScrollReveal.prototype.reveal = reveal
ScrollReveal.prototype.sync = sync
| JavaScript | 0.000001 | @@ -1544,22 +1544,47 @@
rue%0A
-%09
+%0A%09Object.defineProperty(
this
-.
+, '
delegate
= d
@@ -1579,18 +1579,31 @@
delegate
+', %7B get: ()
=
+%3E
delegat
@@ -1614,17 +1614,19 @@
nd(this)
-%0A
+ %7D)
%0A%09Object
@@ -1655,27 +1655,25 @@
'version', %7B
-%0A%09%09
+
get: () =%3E v
@@ -1682,15 +1682,12 @@
sion
-,%0A%09
+
%7D)%0A
-%0A
%09Obj
@@ -1720,19 +1720,17 @@
noop', %7B
-%0A%09%09
+
get: ()
@@ -1737,19 +1737,17 @@
=%3E false
-,%0A%09
+
%7D)%0A%7D%0A%0ASc
|
ed3b02def9ebf33f4513dc123be8b9a85a54bd1a | refactor tests a bit; add failing tests to cover 0.1.1 | test/model.js | test/model.js | /* global describe, it, beforeEach */
'use strict';
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var Joi = require('joi');
var model = require('../src/model');
describe('AveryModel', function() {
describe('#factory', function() {
it('throws with invalid params', function() {
expect(model).to.throw();
});
it('throws with missing name', function() {
expect(model.bind(null, {})).to.throw();
});
it('throws with invalid validate object', function() {
var params = {
name : 'Test',
defaults : {},
validate : 'test'
};
expect(model.bind(null, params)).to.throw();
});
it('throws with a conflicting virtual', function() {
var params = {
name : 'Test',
defaults : { id : null },
virtuals : { id : function() {} }
};
expect(model.bind(null, params)).to.throw();
});
it('throws with a non-function virtual', function() {
var params = {
name : 'Test',
defaults : { id : null },
virtuals : { value : 'test' }
};
expect(model.bind(null, params)).to.throw();
});
});
describe('Instance', function() {
var Model;
var idValueVirtSpy;
var nameValueVirtSpy;
beforeEach(function() {
idValueVirtSpy = sinon.spy(function() {
return '' + this.get('id') + this.get('value');
});
nameValueVirtSpy = sinon.spy(function() {
return '' + this.get('name') + this.get('value');
});
Model = model({
name : 'TheModel',
defaults : {
id : null,
name : null,
value : null,
},
validate : Joi.object().keys({
id : Joi.number().integer(),
name : Joi.string(),
value : Joi.any(),
}),
virtuals : {
idValue : idValueVirtSpy,
nameValue : nameValueVirtSpy,
}
});
});
it('sets and gets', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue',
});
expect(model.get('id')).to.equal(1);
expect(model.get('name')).to.equal('Name');
expect(model.get('value')).to.equal('MyValue');
});
it('isValid returns correctly', function() {
var valid = new Model({
id : 1,
name : 'Name',
value : 'MyValue'
});
expect(valid.isValid()).to.be.true;
var invalid = new Model({
id : 1,
name : 5,
value : 4
});
expect(invalid.isValid()).to.be.false;
});
it('virtuals return correct values', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue'
});
expect(model.get('idValue')).to.equal('1MyValue');
});
it('virtuals are only called once', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue',
});
expect(idValueVirtSpy.called).to.equal(false);
expect(nameValueVirtSpy.called).to.equal(false);
expect(model.get('idValue')).to.equal('1MyValue');
expect(idValueVirtSpy.callCount).to.equal(1);
expect(nameValueVirtSpy.called).to.equal(false);
expect(model.get('nameValue')).to.equal('NameMyValue');
expect(idValueVirtSpy.callCount).to.equal(1);
expect(nameValueVirtSpy.callCount).to.equal(1);
expect(model.get('idValue')).to.equal('1MyValue');
expect(model.get('nameValue')).to.equal('NameMyValue');
expect(idValueVirtSpy.callCount).to.equal(1);
expect(nameValueVirtSpy.callCount).to.equal(1);
model.set('id', 2);
model.get('idValue');
expect(idValueVirtSpy.callCount).to.equal(1);
expect(nameValueVirtSpy.callCount).to.equal(1);
});
it('throws when trying to set a virtual', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue',
});
expect(model.set.bind(model, 'idValue', 2)).to.throw();
});
it('throws when trying to remove a virtual', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue',
});
expect(model.remove.bind(model, 'idValue')).to.throw();
});
it('is immutable', function() {
var model = new Model({
id : 1,
name : 'Name',
value : 'MyValue',
});
var model2 = model.set('name', 'not name');
expect(model.get('name')).to.equal('Name');
expect(model).to.not.equal(model2);
var model3 = model.remove('name');
expect(model.get('name')).to.equal('Name');
expect(model).to.not.equal(model3);
});
});
});
| JavaScript | 0.000002 | @@ -157,25 +157,30 @@
joi');%0A%0Avar
-m
+averyM
odel = requi
@@ -327,33 +327,38 @@
%7B%0A expect(
-m
+averyM
odel).to.throw()
@@ -421,33 +421,38 @@
%7B%0A expect(
-m
+averyM
odel.bind(null,
@@ -644,33 +644,38 @@
;%0A%0A expect(
-m
+averyM
odel.bind(null,
@@ -896,33 +896,38 @@
;%0A%0A expect(
-m
+averyM
odel.bind(null,
@@ -1149,25 +1149,30 @@
expect(
-m
+averyM
odel.bind(nu
@@ -1586,17 +1586,22 @@
Model =
-m
+averyM
odel(%7B%0A
@@ -4778,23 +4778,469 @@
l3);%0A %7D);
+%0A%0A it('works with no optional config items defined', function() %7B%0A var Model2 = averyModel(%7B%0A name : 'TheModel',%0A defaults : %7B%0A id : null,%0A name : null,%0A value : null,%0A %7D,%0A %7D);%0A%0A var model = new Model2(%7B%0A id : 1,%0A name : 'Name',%0A value : 'value'%0A %7D);%0A%0A expect(model.get('name')).to.equal('Name');%0A expect(model.has('value')).to.be.true;%0A %7D);
%0A %7D);%0A%7D);%0A
|
62877a00929c488d2ee5a902c2635616792aff74 | check for presence of phone_number and area_code before formatting | app/scripts/models/address.js | app/scripts/models/address.js | define([
'underscore',
'backbone'
], function (_, Backbone) {
'use strict';
var AddressModel = Backbone.Model.extend({
urlRoot: 'http://localhost:3000/rez/addresses',
defaults: {
building_number: '',
street_name: '',
secondary_address: '',
city: '',
state: '',
zip_code: '',
county: '',
country: '',
area_code: '',
phone_number: ''
},
parse: function(response) {
if (response.address) {
return response.address;
} else {
return response;
}
},
toJSON: function() {
return {
address: this.attributes
};
},
lineOne: function() {
return this.get('building_number') + ' ' + this.get('street_name');
},
lineTwo: function() {
return this.get('city') + ', ' + this.get('state') + ' ' + this.get('zip_code');
},
lineThree: function() {
return this.formattedPhoneNumber();
},
formattedPhoneNumber: function() {
return this.get('area_code') + '.' + this.get('phone_number').insert(3, '.');
}
});
return AddressModel;
});
| JavaScript | 0 | @@ -992,32 +992,97 @@
r: function() %7B%0A
+ if (this.get('area_code') && this.get('phone_number')) %7B%0A
return thi
@@ -1145,24 +1145,32 @@
rt(3, '.');%0A
+ %7D%0A
%7D%0A %7D);%0A
|
04517caf36265055505c6dbec085c34aa0e14b33 | Add missing semicolon | atom/common/api/lib/shell.js | atom/common/api/lib/shell.js | 'use strict';
const bindings = process.atomBinding('shell');
exports.beep = bindings.beep;
exports.moveItemToTrash = bindings.moveItemToTrash;
exports.openItem = bindings.openItem;
exports.showItemInFolder = bindings.showItemInFolder;
exports.openExternal = (url, options) => {
var activate = true;
if (options != null && options.activate != null) {
activate = !!options.activate;
}
return bindings._openExternal(url, activate);
}
| JavaScript | 0.999999 | @@ -439,9 +439,10 @@
vate);%0A%7D
+;
%0A
|
0756707a421d44c4071a18bb9004aa8960337fe3 | fix typo | redef/patron-client/src/frontend/store/index.js | redef/patron-client/src/frontend/store/index.js | import { browserHistory } from 'react-router'
import thunkMiddleware from 'redux-thunk'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import createLogger from 'redux-logger'
import persistState from 'redux-localstorage'
import adapter from 'redux-localstorage/lib/adapters/localStorage'
import filter from 'redux-localstorage-filter'
import rootReducer from '../reducers'
import * as types from '../constants/ActionTypes'
const storage = compose(
filter([ 'application.locale' ])
)(adapter(window.localStorage))
// Add events we want to broadcast to Google Tag Manager to this array:
const broadcastableEvents = [types.REGISTRAION_SUCCESS, types.REGISTRAION_FAILURE]
const analytics = () => next => action => {
if (broadcastableEvents.includes(action.type)) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
event: action.type,
payload: action.payload
})
}
return next(action)
}
const reduxRouterMiddleware = routerMiddleware(browserHistory)
const middleware = [ thunkMiddleware, analytics, reduxRouterMiddleware ]
if (process.env.NODE_ENV !== 'production') {
const loggerMiddleware = createLogger()
middleware.push(loggerMiddleware)
}
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose
export default (initialState) => {
const store = createStore(
rootReducer,
initialState,
composeEnhancers(
applyMiddleware(...middleware),
persistState(storage, 'patron-client')
))
if (module.hot) {
module.hot.accept('../reducers', () => {
store.replaceReducer(require('../reducers').default)
})
}
return store
}
| JavaScript | 0.998906 | @@ -690,24 +690,25 @@
pes.REGISTRA
+T
ION_SUCCESS,
@@ -722,16 +722,17 @@
REGISTRA
+T
ION_FAIL
|
fb2c20c8626db50953b364004711e69024a240ae | remove all graphs when you close menu | web-app/numeter_webapp/static/js/angular/numeter.js | web-app/numeter_webapp/static/js/angular/numeter.js | /*global window, angular, console*/
(function (angular) {
'use strict';
angular.module('numeter', ['ui.bootstrap', 'ngCookies'])
.run( function run( $http, $cookies ){
// For CSRF token compatibility with Django
//$http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken'];
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
$http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken;
})
.directive('graph', ['$http', function ($http) {
return {
scope: {
resolution: '=',
url: '=',
graphname: '=',
hostid: '='
},
templateUrl: '/media/templates/graph.html',
link: function ($scope, $element) {
numeter.get_graph($scope.url, $element[0], $scope.resolution);
},
controller: ['$scope', '$http', function ($scope, $http) {
console.log($scope.url);
}]
};
}])
.directive('menu', ['$http', function ($http) {
return {
templateUrl: '/media/templates/hosttree.html',
scope: {
showGraphs: '&'
},
link: function ($scope) {
$http.get('rest/hosts/').
success(function (data) {
$scope.hosts = data.results;
});
},
controller: ['$scope', '$http', function ($scope, $http) {
// LOAD HOST'S PLUGINS AND SORT BY CATEGORY
$scope.loadCategories = function (host) {
$http.get('/wide-storage/list?host=' + host.hostid).
success(function (data) {
host.categories = {};
angular.forEach(data, function (plugin) {
var category = plugin.Category;
if (! host.categories[category]) host.categories[category] = {plugins: [], open: false, name: category};
host.categories[category].plugins.push(plugin);
});
});
};
$scope.loadPlugins = function (host, chosen_category) {
var plugins = angular.forEach(host.categories[chosen_category.name].plugins, function () {});
// $scope.$emit('displayGraph', host.id, plugins);
$scope.showGraphs({id: host.id, plugins: plugins});
};
$scope.displayGraph = function (host_id, plugins, open) {
if (open) {
return;
}
// $scope.$emit('displayGraph', host_id, plugins);
$scope.showGraphs({id: host_id, plugins: plugins});
};
}]
};
}])
.controller('graphCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
$scope.resolution = $location.search().resolution || 'Daily';
$scope.graphs = [];
$scope.showGraphs = function(hostID, plugins) {
$scope.graphs.length = 0;
angular.forEach(plugins, function (plugin) {
$scope.graphs.push({
url: "/rest/hosts/" + hostID + "/plugin_extended_data/?plugin=" + plugin.Plugin,
graphname: plugin.Plugin,
hostid: '' + hostID, //force string conversion
resolution: $scope.resolution
});
});
};
$scope.changeRes = function (resolution) {
$scope.resolution = resolution;
//copy old graphs in order to render them again
var old_graphs = angular.copy($scope.graphs);
$scope.graphs.length = 0;
angular.forEach(old_graphs, function (graph) {
$scope.graphs.push({
url: graph.url,
graphname: graph.graphname,
hostid: graph.hostid,
resolution: $scope.resolution
});
})
}
var plugins = $location.search().plugins;
var host = $location.search().host;
if (plugins && host){
$scope.showGraphs(host, [{Plugin: plugins}]);
}
}])
.config(['$routeProvider', '$locationProvider', function AppConfig($routeProvider, $locationProvider) {
// enable html5Mode for pushstate ('#'-less URLs)
$locationProvider.html5Mode(true);
}]);
}(angular));
| JavaScript | 0 | @@ -2483,32 +2483,266 @@
var
+plugins;%0A if (chosen_category.open) %7B%0A //console.log('Close remove all graphs');%0A plugins = %5B%5D;%0A %7D else %7B%0A
plugins = angula
@@ -2843,58 +2843,9 @@
-// $scope.$emit('displayGraph', host.id, plugins);
+%7D
%0A
|
0db37a708e0ca34db1025a0a15ac1171ca9b74ef | Rely on string for statut_marital Enum | lib/simulation/openfisca/mapping/individu.js | lib/simulation/openfisca/mapping/individu.js | var moment = require('moment');
var _ = require('lodash');
function formatDate(date) {
return moment(date).format('YYYY-MM-DD');
}
module.exports = {
date_naissance: {
src: 'dateDeNaissance',
fn: formatDate
},
age: {
src: 'dateDeNaissance',
fn: function (dateDeNaissance, individu, situation) {
return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years');
}
},
age_en_mois: {
src: 'dateDeNaissance',
fn: function (dateDeNaissance, individu, situation) {
return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months');
}
},
statut_marital: {
src: 'statutMarital',
values: {
seul: 2,
mariage: 1,
pacs: 5,
union_libre: 2
}
},
id: {
src: 'id',
copyTo3PreviousMonths: false
},
enceinte: 'enceinte',
ass_precondition_remplie: 'assPreconditionRemplie',
date_arret_de_travail: {
src: 'dateArretDeTravail',
fn: formatDate
},
activite: {
src: 'specificSituations',
fn: function(value) {
var returnValue;
_.forEach({
demandeur_emploi: 1,
etudiant: 2,
retraite: 3
}, function(situationIndex, situation) {
if (value.indexOf(situation) >= 0) {
returnValue = situationIndex;
}
});
return returnValue;
}
},
handicap: {
src: 'specificSituations',
fn: function(specificSituations) {
return specificSituations.indexOf('handicap') >= 0;
}
},
taux_incapacite: {
fn: function(individu) {
var handicap = individu.specificSituations.indexOf('handicap') >= 0;
var tauxMap = {
moins50: 0.3,
moins80: 0.7,
plus80: 0.9
};
return handicap && tauxMap[individu.tauxIncapacite];
}
},
inapte_travail: {
src: 'specificSituations',
fn: function(specificSituations) {
return specificSituations.indexOf('inapte_travail') >= 0;
}
},
perte_autonomie: 'perteAutonomie',
etudiant: {
src: 'specificSituations',
fn: function(specificSituations) {
return specificSituations.indexOf('etudiant') >= 0;
}
},
boursier: {
fn: function(individu) {
return individu.boursier || individu.echelonBourse >= 0; // backward compatibility for boursier; cannot write a migration because the exact echelon is not known
}
},
echelon_bourse: 'echelonBourse',
scolarite: {
fn: function(individu) {
var values = {
'inconnue': 0,
'college': 1,
'lycee': 2
};
return values[individu.scolarite];
}
},
enfant_a_charge: {
// variable liée à l'année fiscale : on la définit sur l'année
fn: function(individu, situation) {
var year = situation.dateDeValeur.getFullYear();
var result = {};
result[year] = individu.aCharge || (! individu.fiscalementIndependant);
return result;
},
copyTo3PreviousMonths: false,
},
enfant_place: 'place',
garde_alternee: 'gardeAlternee',
habite_chez_parents: 'habiteChezParents',
/* Revenus du patrimoine */
interets_epargne_sur_livrets: {
src: 'epargneSurLivret',
fn: function(value) {
return {
'2012-01': 0.01 * value || 0
};
},
copyTo3PreviousMonths: false,
},
epargne_non_remuneree: {
src: 'epargneSansRevenus',
fn: function (value) {
return {
'2012-01': value || 0
};
},
copyTo3PreviousMonths: false
},
valeur_locative_immo_non_loue: {
src: 'valeurLocativeImmoNonLoue',
fn: function (value) {
return {
'2012-01': value || 0
};
},
copyTo3PreviousMonths: false,
},
valeur_locative_terrains_non_loue: {
src: 'valeurLocativeTerrainNonLoue',
fn: function (value) {
return {
'2012-01': value || 0
};
},
copyTo3PreviousMonths: false,
},
/* Activités non-salarié */
tns_autres_revenus_type_activite: 'tns_autres_revenus_type_activite',
tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType',
tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType',
};
| JavaScript | 0.999967 | @@ -759,82 +759,234 @@
ul:
-2,%0A mariage: 1,%0A pacs: 5,%0A union_libre: 2
+'C%C3%A9libataire', // Enum value 2 in OpenFisca%0A mariage: 'Mari%C3%A9',// Enum value 1 in OpenFisca%0A pacs: 'Pacs%C3%A9', // Enum value 5 in OpenFisca%0A union_libre: 'C%C3%A9libataire', // Enum value 2 in OpenFisca
%0A
|
44fac46f87257f6582df422f648989d12762b30c | create messages in loadFixture | apps/api/test/fixtures/index.js | apps/api/test/fixtures/index.js | /**
* Bootstrap the test database
* before running tests
*/
/**
* npm dependencies
*/
var async = require('async');
/**
* models
*/
var Account = require('../../api/models/Account');
var App = require('../../api/models/App');
var accounts = {
first: {
name: 'Prateek',
email: 'test@userjoy.co',
password: 'testtest'
},
second: {
name: 'Savinay',
email: 'savinay@example.com',
password: 'newapptest'
},
},
apps = {
first: {
name: 'First App',
domain: 'firstapp.co'
},
second: {
name: 'Second App',
domain: 'secondapp.co'
}
};
function createAccount(account, fn) {
var rawPassword = account.password;
Account.create(account, function (err, acc) {
if (err) return fn(err);
acc.password = rawPassword;
fn(null, acc);
});
}
function createApp(accId, app, fn) {
app.admin = accId;
App.create(app, fn);
}
module.exports = function loadFixtures(callback) {
async.series({
createFirstAccount: function (cb) {
createAccount(accounts.first, function (err, acc) {
if (err) return cb(err);
accounts.first = acc;
cb();
});
},
createSecondAccount: function (cb) {
createAccount(accounts.second, function (err, acc) {
if (err) return cb(err);
accounts.second = acc;
cb();
});
},
createFirstApp: function (cb) {
createApp(accounts.first._id, apps.first, function (err, app) {
if (err) return cb(err);
apps.first = app;
cb();
});
},
createSecondApp: function (cb) {
createApp(accounts.second._id, apps.second, function (err, app) {
if (err) return cb(err);
apps.second = app;
cb();
});
},
}, function (err) {
callback(err, {
accounts: accounts,
apps: apps
});
});
}
| JavaScript | 0 | @@ -117,16 +117,70 @@
sync');%0A
+var ObjectId = require('mongoose')%0A .Types.ObjectId;%0A
%0A%0A/**%0A *
@@ -286,16 +286,67 @@
/App');%0A
+var Message = require('../../api/models/Message');%0A
%0A%0Avar ac
@@ -714,16 +714,383 @@
'%0A %7D%0A
+ %7D,%0A%0A messages = %7B%0A%0A first: %7B%0A accid: null,%0A aid: null,%0A coId: ObjectId(),%0A from: 'user',%0A text: 'Hello World',%0A type: 'email',%0A uid: ObjectId(),%0A %7D,%0A%0A second: %7B%0A accid: null,%0A aid: null,%0A coId: ObjectId(),%0A from: 'user',%0A text: 'Hello World 2',%0A type: 'email',%0A uid: ObjectId(),%0A %7D%0A
%7D;%0A%0A%0Af
@@ -1389,16 +1389,148 @@
n);%0A%0A%7D%0A%0A
+function createMessage(accId, aid, message, fn) %7B%0A%0A message.accid = accId;%0A message.aid = aid;%0A Message.create(message, fn);%0A%0A%7D%0A%0A
%0Amodule.
@@ -2387,16 +2387,633 @@
%7D,%0A%0A
+ createFirstMessage: function (cb) %7B%0A%0A var aid = apps.first._id;%0A var accId = accounts.first._id;%0A var message = messages.first;%0A%0A createMessage(accId, aid, message, function (err, msg) %7B%0A if (err) return cb(err);%0A messages.first = msg;%0A cb();%0A %7D);%0A%0A %7D,%0A%0A createSecondMessage: function (cb) %7B%0A%0A var aid = apps.first._id;%0A var accId = accounts.first._id;%0A var message = messages.second;%0A%0A createMessage(accId, aid, message, function (err, msg) %7B%0A if (err) return cb(err);%0A messages.second = msg;%0A cb();%0A %7D);%0A%0A %7D,%0A%0A
%7D, fun
@@ -3073,16 +3073,16 @@
counts,%0A
-
ap
@@ -3089,16 +3089,42 @@
ps: apps
+,%0A messages: messages
%0A %7D);
|
7f5b0b66c8a581e51d2d8842b74d078bd4be5bb3 | update again databrowser.js 25-2-2016 6:47 | assets/core/page-databrowser.js | assets/core/page-databrowser.js | app.section("databrowser");
viewModel.databrowser ={}; var br = viewModel.databrowser;
br.templateConfigDataBrowser= {
_id: "",
BrowserNmame: ""
}
br.confirBrowser = ko.mapping.fromJS(br.templateConfigDataBrowser);
br.dataBrowser = ko.observableArray([]);
br.searchfield = ko.observable("");
br.pageVisible = ko.observable("");
br.browserColumns = ko.observableArray([
{title: "<center><input type='checkbox' id='selectall'></center>", width: 5, attributes: { style: "text-align: center;" }, template: function (d) {
return [
"<input type='checkbox' id='select' class='selecting' name='select[]' value=" + d._id + ">"
].join(" ");
}},
{field:"_id", title: "ID", width: 80},
{field:"BrowserName", title: "Name", width: 130},
{title: "", width: 40, attributes:{class:"align-center"}, template: function(d){
return[
"<a href='#'>Design</a>"
].join(" ");
}}
]);
br.getDataBrowser = function(){
app.ajaxPost("/databrowser/getbrowser", {search: br.searchfield()}, function(res){
if(!app.isFine(res)){
return;
}
if (!res.data) {
res.data = [];
}
br.dataBrowser(res.data);
});
}
br.OpenBrowserForm = function(ID){
br.pageVisible("editor");
// app.ajaxPost("/databrowser/gobrowser", {id: ID}, function (){
// if (!app.isFine) {
// return;
// }
// })
}
br.getAllbrowser = function(){
$("#selectall").change(function () {
$("input:checkbox[name='select[]']").prop('checked', $(this).prop("checked"));
});
}
var vals = [];
br.DeleteBrowser = function(){
if ($('input:checkbox[name="select[]"]').is(':checked') == false) {
swal({
title: "",
text: 'You havent choose any application to delete',
type: "warning",
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: true
});
} else {
vals = $('input:checkbox[name="select[]"]').filter(':checked').map(function () {
return this.value;
}).get();
swal({
title: "Are you sure?",
text: 'Application with id "' + vals + '" will be deleted',
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete",
closeOnConfirm: true
},
function() {
setTimeout(function () {
app.ajaxPost("/databrowser/deletebrowser", vals, function () {
if (!app.isFine) {
return;
}
swal({title: "Application successfully deleted", type: "success"});
});
},1000);
});
}
}
//SELECTING ON GRID
br.selectBrowser = function(e){
app.wrapGridSelect(".grid-application", ".btn", function (d) {
console.log(d._id);
});
}
br.saveAndBack = function (){
br.getDataBrowser();
br.pageVisible("");
}
$(function (){
br.getDataBrowser();
br.getAllbrowser();
}); | JavaScript | 0 | @@ -2206,21 +2206,27 @@
rowser%22,
+%7B_id:
vals
+%7D
, functi
|
54145f3f25d2ab2f703f144c40b0923c4b4e971b | Remove extra debug statement | models/accountsApiHandler.js | models/accountsApiHandler.js | var extend = require('extend');
var response = require('response');
var JSONStream = require('JSONStream');
var jsonBody = require('body/json');
var through = require('through2');
var filter = require('filter-object');
module.exports = AccountsApiHandler;
function AccountsApiHandler (server) {
if (!(this instanceof AccountsApiHandler)) {
return new AccountsApiHandler(server);
}
this.server = server;
}
/*
* GET: return all accounts
* POST: create a new account (admins only)
*/
AccountsApiHandler.prototype.accounts = function (req, res) {
var self = this;
this.server.permissions.authorize(req, res, function (authError, authAccount, session) {
var notAuthorized = (authError || !authAccount);
if (req.method === 'GET') {
if (notAuthorized) return response().status('401').json({error: 'Not Authorized'}).pipe(res);
return self.server.accountdown.list({keys: false})
.pipe(filterAccountDetails())
.pipe(JSONStream.stringify())
.pipe(res);
}
else if (req.method === 'POST') {
if (notAuthorized) return response().status('401').json({error: 'Not Authorized'}).pipe(res);
if (!authAccount.admin) return response().status('401').json({error: 'Must be admin to create new accounts'}).pipe(res);
jsonBody(req, res, function (err, body) {
if (err) return response().status(500).json({ error: err }).pipe(res);
var opts = {
login: { basic: { username: body.username, password: body.password } },
value: filter(body, '!password')
};
self.server.accountdown.create(body.username, opts, function (err) {
if (err) return response().status(500).json({ error: 'Unable to create new user' }).pipe(res);
self.server.accountdown.get(body.username, function (err, account) {
if (err) return response().status(500).json({ error: 'Server error' }).pipe(res);
response().json(account).pipe(res)
})
})
});
}
});
};
/*
* GET: return an account
* PUT: update an account (admins only)
* DELETE: remove an account (admins only)
*/
AccountsApiHandler.prototype.accountFromUsername = function (req, res, opts) {
debugger;
var self = this;
this.server.permissions.authorize(req, res, function (authError, authAccount, session) {
var notAuthorized = (authError || !authAccount);
if (req.method === 'GET') {
self.server.accountdown.get(opts.params.username, function (err, account) {
if (err) return response().status('500').json({error: 'Could not retrieve the account'}).pipe(res);
if (notAuthorized) {
account = filter(account, ['*', '!email', '!admin']);
}
return response().json(account).pipe(res)
});
}
if (req.method === 'PUT') {
if (notAuthorized) return response().status('401').json({error: 'Not Authorized'}).pipe(res);
if (!authAccount.admin) return response().status('401').json({error: 'Must be admin to update accounts'}).pipe(res);
jsonBody(req, res, opts, function (err, body) {
if (err) return response().status(500).json({ error:'Could not parse the request\'s body' }).pipe(res);
self.server.accountdown.get(opts.params.username, function (err, account){
if (err) return response().status(500).json({ error:'Username does not exist' }).pipe(res);
account = extend(account, body);
self.server.accountdown.put(opts.params.username, account, function (err) {
if (err) return response().status(500).json({ error:'Server error' }).pipe(res);
response().json(account).pipe(res);
});
});
});
}
if (req.method === 'DELETE') {
if (notAuthorized) return response().status('401').json({ error: 'Not Authorized'}).pipe(res);
if (!authAccount.admin) return response().status('401').json({error: 'Must be admin to delete accounts'}).pipe(res);
self.server.accountdown.remove(opts.params.username, function (err, account) {
if (err) return response().status(500).json({ error:'Username does not exist' }).pipe(res);
return response().json(account).pipe(res);
})
}
});
};
/*
* Helper functions
*/
function filterAccountDetails () {
return through.obj(function iterator(chunk, enc, next) {
this.push(filter(chunk, ['*', '!email', '!admin']));
next();
});
}
| JavaScript | 0.000007 | @@ -2209,20 +2209,8 @@
) %7B%0A
- debugger;%0A
va
|
6f456a68c6a748d9aa2a9a7b887a8311874177ab | Update scoring 2.2.5 | dev-scripts/config.get.js | dev-scripts/config.get.js | 'use strict'
const { getMhub } = require('./.get/get-mhub')
const { getCaddy } = require('./.get/get-caddy')
const { getMongo } = require('./.get/get-mongo')
const { getNpmModule } = require('./.get/get-npm-module')
const { getByHttp } = require('./.get/get-by-http')
// eslint-disable-next-line node/exports-style
module.exports = {
modules: {
caddy: {
internal: true,
get: getCaddy
},
mongo: {
internal: true,
get: getMongo
},
mhub: {
internal: true,
get: getMhub,
options: {
package: 'mhub',
version: '0.9.1'
}
},
'identity-provider': {
get: getNpmModule,
options: {
version: 'FirstLegoLeague/identity-provider#c93abf808d44a90d06da945212cb19b45d5923d2'
}
},
display: {
get: getNpmModule,
options: {
package: '@first-lego-league/display',
version: '2.3.1'
}
},
tournament: {
get: getNpmModule,
options: {
package: '@first-lego-league/tournament',
version: '1.9.6'
}
},
scoring: {
get: getNpmModule,
options: {
package: '@first-lego-league/scoring',
version: '2.2.4'
}
},
rankings: {
get: getNpmModule,
options: {
version: 'FirstLegoLeague/rankings#ecac223c4821760ffdd4cf97692d910c3ad34ca6'
}
},
clock: {
get: getNpmModule,
options: {
package: '@first-lego-league/clock',
version: '2.2.5'
}
}
},
custom: {
npm: getNpmModule,
http: getByHttp
}
}
| JavaScript | 0.000009 | @@ -1200,17 +1200,17 @@
n: '2.2.
-4
+5
'%0A
|
2e7cc5f8aa68bf476b88154d8bf4cb9a2d7ee6f8 | Load immediately instead of on channel switch | slack-hacks-loader.js | slack-hacks-loader.js | (function() {
console.log("Slack hacks loader loading...");
url_regex = new RegExp("^" + "(?:(?:https?|)://)" + "(?:\\S+(?::\\S*)?@)?" + "(?:" + "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + "\\.?" + ")" + "(?::\\d{2,5})?" + "(?:[/?#]\\S*)?" + "$", "i");
window.loadUrl = insertUrl = function(url) {
var css, s;
console.log(url);
if (url.match(/\.css$/)) {
css = document.createElement('link');
css.setAttribute('href', url);
css.setAttribute('type', 'text/css');
css.setAttribute('rel', 'stylesheet');
return document.head.appendChild(css);
} else if (url.match(/\.js$/)) {
s = document.createElement('script');
s.setAttribute('src', url);
return document.head.appendChild(s);
}
};
slackHacksLoader = function() {
var channel_purpose, i, j, len, len1, results, url, urls, word, words;
channel = TS.channels.getChannelByName("#slack-hacks-dev");
if (channel != null && typeof channel != 'undefined') {
channel_purpose = channel.purpose.value;
console.log(channel_purpose);
}
if (channel_purpose === null || typeof channel_purpose === 'undefined') {
channel = TS.channels.getChannelByName("#slack-hacks");
channel_purpose = channel.purpose.value;
}
words = channel_purpose.split(/\s+/);
urls = [];
for (i = 0, len = words.length; i < len; i++) {
word = words[i];
if (word.match(url_regex)) {
urls.push(word);
}
}
console.log(words);
console.log(urls);
results = [];
for (j = 0, len1 = urls.length; j < len1; j++) {
url = urls[j];
results.push(insertUrl(url));
}
return results;
};
TS.channels.switched_sig.addOnce(slackHacksLoader);
}).call(this);
| JavaScript | 0 | @@ -1197,24 +1197,87 @@
unction() %7B%0A
+ if (window.slackHacksLoaded === true) %7B%0A return%0A %7D%0A
var chan
@@ -1339,16 +1339,16 @@
words;%0A
-
chan
@@ -1514,44 +1514,8 @@
ue;%0A
- console.log(channel_purpose);%0A
@@ -1707,24 +1707,136 @@
lue;%0A %7D%0A%0A
+ console.log(channel_purpose);%0A if (channel_purpose != null) %7B%0A window.slackHacksLoaded = true%0A %7D%0A
words =
@@ -2242,28 +2242,147 @@
%0A%0A
-TS.channels.switched
+slackHacksLoader()%0A if (window.slackHacksLoaded != true) %7B%0A TS.channels.data_updated_sig.addOnce(slackHacksLoader);%0A TS.client.login
_sig
@@ -2408,16 +2408,20 @@
Loader);
+%0A %7D
%0A%0A%7D).cal
|
510a210471b69e71151ac843c230fbbbe9a6a8d0 | add tokenTypes: Null, Boolean, RegularExpression | acorn-to-esprima.js | acorn-to-esprima.js | var traverse = require("babel-core").traverse;
var tt = require("babel-core").acorn.tokTypes;
var t = require("babel-core").types;
exports.toToken = function (token) {
var type = token.type;
if (type === tt.name) {
token.type = "Identifier";
} else if (type === tt.semi || type === tt.comma ||
type === tt.parenL || type === tt.parenR ||
type === tt.braceL || type === tt.braceR ||
type === tt.slash || type === tt.dot ||
type === tt.bracketL || type === tt.bracketR ||
type === tt.ellipsis || type === tt.arrow ||
type === tt.star || type === tt.incDec ||
type === tt.colon || type === tt.question ||
type === tt.template || type === tt.backQuote ||
type === tt.dollarBraceL || type === tt.at ||
type === tt.logicalOR || type === tt.logicalAND ||
type === tt.bitwiseOR || type === tt.bitwiseXOR ||
type === tt.bitwiseAND || type === tt.equality ||
type === tt.relational || type === tt.bitShift ||
type === tt.plusMin || type === tt.modulo ||
type === tt.exponent || type === tt.prefix ||
type.isAssign) {
token.type = "Punctuator";
if (!token.value) token.value = type.label;
} else if (type === tt.jsxTagStart) {
token.type = "Punctuator";
token.value = "<";
} else if (type === tt.jsxTagEnd) {
token.type = "Punctuator";
token.value = ">";
} else if (type === tt.jsxName) {
token.type = "JSXIdentifier";
} else if (type.keyword) {
token.type = "Keyword";
} else if (type === tt.num) {
token.type = "Numeric";
token.value = String(token.value);
} else if (type === tt.string) {
token.type = "String";
token.value = JSON.stringify(token.value);
}
return token;
};
exports.toAST = function (ast) {
ast.sourceType = "module";
traverse(ast, astTransformVisitor);
};
function isCompatTag(tagName) {
return tagName && /^[a-z]|\-/.test(tagName);
}
var astTransformVisitor = {
noScope: true,
exit: function (node, parent) {
if (t.isSpreadProperty(node)) {
node.type = "Property";
node.kind = "init";
node.computed = true;
node.key = node.value = node.argument;
delete node.argument;
}
if (t.isFlow(node)) {
return this.remove();
}
if (t.isRestElement(node)) {
return node.argument;
}
// modules
if (t.isImportDeclaration(node)) {
delete node.isType;
}
if (t.isExportDeclaration(node)) {
if (t.isClassExpression(node.declaration)) {
node.declaration.type = "ClassDeclaration";
} else if (t.isFunctionExpression(node.declaration)) {
node.declaration.type = "FunctionDeclaration";
}
}
// classes
if (t.isReferencedIdentifier(node, parent, { name: "super" })) {
return t.inherits(t.thisExpression(), node);
}
if (t.isClassProperty(node)) {
delete node.key;
}
// functions
if (t.isFunction(node)) {
if (node.async) node.generator = true;
delete node.async;
}
if (t.isAwaitExpression(node)) {
node.type = "YieldExpression";
node.delegate = node.all;
delete node.all;
}
}
};
| JavaScript | 0.002468 | @@ -1560,32 +1560,194 @@
JSXIdentifier%22;%0A
+ %7D else if (type.keyword === %22null%22) %7B%0A token.type = %22Null%22;%0A %7D else if (type.keyword === %22false%22 %7C%7C token.keyword === %22true%22) %7B%0A token.type = %22Boolean%22;%0A
%7D else if (typ
@@ -1998,16 +1998,89 @@
ue);%0A %7D
+ else if (type === tt.regexp) %7B%0A token.type = %22RegularExpression%22;%0A %7D
%0A%0A retu
|
df221d554fedc8e4068462e92ea10ebdea8c4991 | fix bug | packages/westore-cloud/store.js | packages/westore-cloud/store.js | export default {
data: {
//user 对应 db 的 collectionName
'user':[],
//其他 collection 可以继续添加
'product': []
},
methods:{
//这里可以扩展 collection 每项的方法
'product':{
'agentString':function(){
return this.agent.join('-')
}
}
},
env:'test-06eb2e'
}
| JavaScript | 0.000001 | @@ -69,12 +69,13 @@
er':
+
%5B%5D,%0A
-
@@ -130,16 +130,17 @@
methods:
+
%7B%0A //
@@ -177,16 +177,17 @@
roduct':
+
%7B%0A
@@ -204,16 +204,17 @@
ng':
+
function
()%7B%0A
@@ -213,10 +213,12 @@
tion
+
()
+
%7B%0A
@@ -276,16 +276,17 @@
,%0A env:
+
'test-06
@@ -290,13 +290,32 @@
-06eb2e'
+,%0A updateAll: true
%0A%0A%7D%0A%0A
|
14f5b219f74afc15a70d9127f4754fbe87949e81 | Fix an error | assets/javascripts/greetings.js | assets/javascripts/greetings.js | $(function() {
if (DATA.type != 'schedule') {
return;
}
var tabs = [
{
hash: 'timetable',
tabElement: $('#timetable-tab'),
contentElement: $('#timetable')
},
{
hash: 'character',
tabElement: $('#character-tab'),
contentElement: $('#character')
}
];
var twitterTab = {
hash: 'twitter',
tabElement: $('#twitter-tab'),
contentElement: $('#twitter')
};
if (twitterTab.tabElement.size() !== 0) {
tabs.push(twitterTab);
}
var updateTab = function(hash) {
var tab = (function() {
var i, n = tabs.length;
for (i = 0; i < n; ++i) {
if (hash.indexOf('#' + tabs[i].hash + '/') === 0) {
return tabs[i];
}
}
})();
if (tab === undefined) {
tab = tabs[0];
}
tabs.filter(function(t) { return t.hash != tab.hash; }).forEach(function(t) {
t.tabElement.removeClass('active');
t.contentElement.hide();
});
tab.tabElement.addClass('active');
tab.contentElement.show();
};
var hashchange = function() {
updateTab(location.hash);
};
$(window).on('hashchange', hashchange).triggerHandler('hashchange');
$(document).on('click', 'a[href^="#"]', function() {
var hash = $(this).attr('href');
updateTab(hash);
$(window).off('hashchange', hashchange);
location.hash = hash;
$(window).on('hashchange', hashchange);
var target = $('*[name="' + decodeURI(hash.substring(1)) + '"]');
if (target.size() > 0) {
$.scrollTo(target);
}
return false;
});
Vue.filter('to_time', function(value) {
return moment(value).format('HH:mm');
});
var groupGreetings = function(greetings) {
var table = {};
_.each(greetings, function(greeting) {
if (!(greeting.end_at in table)) {
table[greeting.end_at] = {};
}
if (!(greeting.start_at in table[greeting.end_at])) {
table[greeting.end_at][greeting.start_at] = [];
}
table[greeting.end_at][greeting.start_at].push(greeting);
});
var result = [];
_.chain(table).keys().sort().each(function(end_at) {
_.chain(table[end_at]).keys().sort().each(function(start_at) {
result.push({
start_at: start_at,
end_at: end_at,
greetings: _.sortBy(table[end_at][start_at], function(greeting) {
return greeting.place.name;
})
});
});
});
return result;
};
var vm = new Vue({
el: '#contents',
data: {
rawGreetings: DATA.greetings,
epoch: +new Date()
},
created: function() {
setInterval(function() {
if (moment().format('YYYY-MM-DD') == DATA.date) {
$.ajax({
url: '/api/schedule/' + moment(DATA.date).format('YYYY/MM/DD') + '/',
dataType: 'json'
}).done(function(data) {
vm.$set('rawGreetings', data);
});
}
}, 5 * 60 * 1000);
setInterval(function() {
var date = new Date();
date.setMinutes(Math.floor(date.getMinutes() / 5) * 5);
vm.$set('epoch', +date);
}, 1000);
},
computed: {
groupedGreetingsDeleted: function() {
var epoch = this.epoch;
return groupGreetings(_.filter(this.rawGreetings, function(greeting) {
return greeting.deleted;
}));
},
groupedGreetingsBeforeTheStart: function() {
var epoch = this.epoch;
return groupGreetings(_.filter(this.rawGreetings, function(greeting) {
return !greeting.deleted && epoch < (+new Date(greeting.start_at));
}));
},
groupedGreetingsInSession: function() {
var epoch = this.epoch;
return groupGreetings(_.filter(this.rawGreetings, function(greeting) {
return !greeting.deleted && epoch >= (+new Date(greeting.start_at)) && epoch <= (+new Date(greeting.end_at));
}));
},
groupedGreetingsAfterTheEnd: function() {
var epoch = this.epoch;
return groupGreetings(_.filter(this.rawGreetings, function(greeting) {
return !greeting.deleted && epoch > (+new Date(greeting.end_at));
}));
},
groupedGreetingsByCharacter: function() {
var grouped = {};
_.chain(this.rawGreetings).filter(function(greeting) {
return !greeting.deleted;
}).each(function(greeting) {
_.each(greeting.characters, function(character) {
if (!(character.name in grouped)) {
grouped[character.name] = [];
}
grouped[character.name].push(greeting);
});
});
return _.chain(grouped).pairs().sortBy(function(pair) {
return pair[0];
}).map(function(pair) {
return {
character: _.find(pair[1][0].characters, function(character) {
return character.name == pair[0];
}),
greetings: pair[1]
};
}).value();
}
}
});
});
| JavaScript | 0.998142 | @@ -18,16 +18,38 @@
if (DATA
+ !== undefined && DATA
.type !=
|
c0b5f5c8f7dc7f30b0264e0f7e0de24ba11cef57 | Stop dragging on mouse leave | src/DraggableDiv.js | src/DraggableDiv.js | import React from 'react';
// A div that tracks its own dragging and calls its onMove
// callback with preprocessed drag events.
export default class DraggableDiv extends React.Component {
constructor(props) {
super(props);
this.state = {
prevMousePos: [0, 0],
mouseDown: false,
dragStarted: false
};
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onClick = this.onClick.bind(this);
}
onMouseDown(event) {
this.setState({
mouseDown: true,
dragStarted: false,
prevMousePos: [event.pageX, event.pageY]
});
}
onMouseUp(event) {
this.setState({mouseDown: false});
}
onMouseMove(event) {
let s = this.state;
if (!s.mouseDown) {
return;
}
let x = event.pageX;
let y = event.pageY;
let dx = x - s.prevMousePos[0];
let dy = y - s.prevMousePos[1];
// Mousemove can occur during a legitimate click too.
// To account for that we let some limited mousemove
// before considering the gesture as a dragging.
// If this is a dragging, call the onMove handler
// and update our pixel tracking.
if (s.dragStarted) {
this.props.onMove({dx, dy});
this.setState({
prevMousePos: [x, y]
});
}
// If the "gesture" is not yet qualified as dragging,
// see if it already qualifies by looking if the mouse
// has travalled far enough.
else {
if (Math.abs(dx) >= 5 || Math.abs(dy) >= 5) {
this.setState({dragStarted: true});
}
}
}
onClick(event) {
if (this.state.dragStarted) {
return;
}
this.props.onClick(event);
}
render() {
let otherProps = Object.assign({}, this.props);
delete otherProps.onClick;
delete otherProps.onMove;
return (
<div
onMouseDown={this.onMouseDown}
onMouseUp={this.onMouseUp}
onMouseMove={this.onMouseMove}
onClick={this.onClick}
onDragStart={(e) => e.preventDefault()}
{...otherProps}>{this.props.children}</div>
);
}
}
| JavaScript | 0.000001 | @@ -1855,16 +1855,50 @@
seMove%7D%0A
+%09%09%09%09onMouseLeave=%7Bthis.onMouseUp%7D%0A
%09%09%09%09onCl
|
6237ad04730159a75bdcb16cf4bab501387bcce7 | Fix incorrect count | ui/src/dashboards/containers/DashboardsPage.js | ui/src/dashboards/containers/DashboardsPage.js | import React, {PropTypes} from 'react'
import {Link, withRouter} from 'react-router'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import SourceIndicator from 'shared/components/SourceIndicator'
import DeleteConfirmTableCell from 'shared/components/DeleteConfirmTableCell'
import {createDashboard} from 'src/dashboards/apis'
import {getDashboardsAsync, deleteDashboardAsync} from 'src/dashboards/actions'
import {NEW_DASHBOARD} from 'src/dashboards/constants'
const {arrayOf, func, string, shape} = PropTypes
const DashboardsPage = React.createClass({
propTypes: {
source: shape({
id: string.isRequired,
name: string.isRequired,
type: string,
links: shape({
proxy: string.isRequired,
}).isRequired,
telegraf: string.isRequired,
}),
router: shape({
push: func.isRequired,
}).isRequired,
handleGetDashboards: func.isRequired,
handleDeleteDashboard: func.isRequired,
dashboards: arrayOf(shape()),
},
componentDidMount() {
this.props.handleGetDashboards()
},
async handleCreateDashbord() {
const {source: {id}, router: {push}} = this.props
const {data} = await createDashboard(NEW_DASHBOARD)
push(`/sources/${id}/dashboards/${data.id}`)
},
handleDeleteDashboard(dashboard) {
this.props.handleDeleteDashboard(dashboard)
},
render() {
const {dashboards} = this.props
const dashboardLink = `/sources/${this.props.source.id}`
let tableHeader
if (dashboards === null) {
tableHeader = 'Loading Dashboards...'
} else if (dashboards.length === 0) {
tableHeader = '1 Dashboard'
} else {
tableHeader = `${dashboards.length + 1} Dashboards`
}
return (
<div className="page">
<div className="page-header">
<div className="page-header__container">
<div className="page-header__left">
<h1>
Dashboards
</h1>
</div>
<div className="page-header__right">
<SourceIndicator sourceName={this.props.source.name} />
</div>
</div>
</div>
<div className="page-contents">
<div className="container-fluid">
<div className="row">
<div className="col-md-12">
<div className="panel panel-minimal">
<div className="panel-heading u-flex u-ai-center u-jc-space-between">
<h2 className="panel-title">{tableHeader}</h2>
<button
className="btn btn-sm btn-primary"
onClick={this.handleCreateDashbord}
>
Create Dashboard
</button>
</div>
<div className="panel-body">
<table className="table v-center admin-table">
<thead>
<tr>
<th>Name</th>
<th />
</tr>
</thead>
<tbody>
{dashboards && dashboards.length
? dashboards.map(dashboard => {
return (
<tr key={dashboard.id} className="">
<td className="monotype">
<Link
to={`${dashboardLink}/dashboards/${dashboard.id}`}
>
{dashboard.name}
</Link>
</td>
<DeleteConfirmTableCell
onDelete={this.handleDeleteDashboard}
item={dashboard}
/>
</tr>
)
})
: null}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
},
})
const mapStateToProps = ({dashboardUI: {dashboards, dashboard}}) => ({
dashboards,
dashboard,
})
const mapDispatchToProps = dispatch => ({
handleGetDashboards: bindActionCreators(getDashboardsAsync, dispatch),
handleDeleteDashboard: bindActionCreators(deleteDashboardAsync, dispatch),
})
export default connect(mapStateToProps, mapDispatchToProps)(
withRouter(DashboardsPage)
)
| JavaScript | 0.999999 | @@ -1611,9 +1611,9 @@
===
-0
+1
) %7B%0A
@@ -1703,12 +1703,8 @@
ngth
- + 1
%7D Da
|
a6e59d9210ba37567adcd4007f9a526a6143ea82 | Add some tests | test/suite.js | test/suite.js | var inspector = require('..');
var expect = require('expect.js');
describe("url-inspector", function suite() {
it("should inspect large file without downloading it entirely", function(done) {
this.timeout(3000);
inspector('https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.3.3.tar.xz', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.title).to.be.ok();
expect(meta.type).to.be('archive');
done();
});
});
it("should return meta with width and height", function(done) {
this.timeout(5000);
inspector('https://upload.wikimedia.org/wikipedia/commons/b/bd/1110_desktop_visual.jpg', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.type).to.be('image');
expect(meta.title).to.be.ok();
expect(meta.width).to.be.ok();
expect(meta.height).to.be.ok();
done();
});
});
it("should return meta with thumbnail for a youtube video", function(done) {
this.timeout(5000);
inspector('https://www.youtube.com/watch?v=CtP8VABF5pk', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.type).to.be('video');
expect(meta.thumbnail).to.be.ok();
expect(meta.title).to.be.ok();
expect(meta.embed).to.be.ok();
expect(meta.width).to.be.ok();
expect(meta.height).to.be.ok();
expect(meta.duration).to.be.ok();
done();
});
});
it("should just work with github.com", function(done) {
this.timeout(5000);
inspector('https://github.com/kapouer/url-inspector', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.type).to.be('link');
expect(meta.title).to.be.ok();
expect(meta.size).to.not.be.ok();
done();
});
});
it("should error out with a message", function(done) {
this.timeout(5000);
inspector('https://ubnhiryuklu.tar/ctalo', function(err, meta) {
expect(err).to.be.ok();
expect(meta).to.not.be.ok();
done();
});
});
it("should error out with a 404", function(done) {
this.timeout(5000);
inspector('https://google.com/ctalo', function(err, meta) {
expect(err).to.be(404);
expect(meta).to.not.be.ok();
done();
});
});
it("should redirect properly", function(done) {
this.timeout(5000);
inspector('https://github.com/Stuk/jszip/archive/master.zip', function(err, meta) {
expect(err).to.not.be.ok();
expect(meta.type).to.be('archive');
expect(meta.title).to.be.ok();
done();
});
});
});
| JavaScript | 0.000008 | @@ -414,16 +414,49 @@
hive');%0A
+%09%09%09expect(meta.ext).to.be('xz');%0A
%09%09%09done(
@@ -733,24 +733,58 @@
e('image');%0A
+%09%09%09expect(meta.ext).to.be('jpg');%0A
%09%09%09expect(me
@@ -1243,32 +1243,67 @@
ed).to.be.ok();%0A
+%09%09%09expect(meta.ext).to.be('html');%0A
%09%09%09expect(meta.w
|
b7be14952119491fb076a0c0219e80fc24ea8e1b | Update imp-models.js | bin/imp-models.js | bin/imp-models.js | #! /usr/bin/env node
// Get a list of models in the user's account
var program = require("commander");
var prompt = require("cli-prompt");
var Table = require("cli-table");
var colors = require("colors");
var fs = require("fs");
var ImpConfig = require("../lib/impConfig.js");
var config = new ImpConfig();
program
.option("-a, --active", "Lists only active models (those with assigned devices)")
.option("-i, --inactive", "Lists only inactive models (those with no assigned devices)")
.option("-d, --device <deviceID/deviceName>", "Lists the model to which the device is assigned (if any)")
program.parse(process.argv);
config.init(["apiKey"], function(err, success) {
if (err) {
console.log("ERROR: Global Build API key is not set. Run 'imp setup' then try 'imp models' again");
return;
}
imp = config.createImpWithConfig();
if ("active" in program && "inactive" in program) {
console.log("ERROR: You cannot specify the options --active and --inactive");
return;
}
if ("inactive" in program && "device" in program) {
console.log("ERROR: You cannot specify the options --device and --inactive");
return;
}
var activeState = null;
if ("active" in program) activeState = true;
if ("inactive" in program) activeState = false;
if ("device" in program) activeState = null;
imp.getModels(null, function(err, modelData) {
if (err) {
console.log("ERROR: " + err.message_short);
return;
}
imp.getDevices(null, function(err, deviceData) {
if (err) {
console.log("ERROR: " + err.message_short);
return;
}
var filteredModels = [];
modelData.models.some(function(model) {
if (activeState == null) {
// Not filtering models by state (active/inactive)
if ("device" in program) {
// We have a device specified - is it specified by an ID?
deviceData.devices.some(function(device) {
if (device.id == program.device) {
if (device.model_id == model.id) filteredModels.push(model);
return true;
}
});
// The passed device specifier didn't match any device ID,
// so perhaps was it a device name? Match on lower case
deviceData.devices.some(function(device) {
if (device.name.toLowerCase() == program.device.toLowerCase()) {
if (device.model_id == model.id) filteredModels.push(model);
return true;
}
});
} else {
// Listing all models so just push this model to the list
filteredModels.push(model);
}
} else if (activeState) {
// Filtering by state == active, so check for device associations
deviceData.devices.some(function(device) {
if (device.model_id == model.id) {
// At least one device is listing this as its model,
// so this model is active - push it to the list
filteredModels.push(model);
return true;
}
});
} else {
// Filtering by state == inactive
var found = false;
deviceData.devices.some(function(device) {
if (device.model_id == model.id) {
found = true;
return true;
}
});
// Model is not associated with any device (found == false)
// ie. it's inactive, so push it to the list
if (!found) filteredModels.push(model);
}
});
if (filteredModels.length > 0) {
// We have model(s) to display
if ("device" in program) {
// A device can only have one model, so display that
console.log("Device '" + program.device + "' is assigned to model '" + filteredModels[0].name + "' (ID: " + filteredModels[0].id + ")");
return;
}
var header = ['Model Name', 'Model ID'];
for (var index in header) {
// Set the header colour
header[index] = header[index].cyan;
}
var table = new Table({
head: header
, colWidths: [30, 20]
});
filteredModels.forEach(function(model) {
table.push([model.name, model.id]);
})
console.log(table.toString());
} else {
// Report there are no found models
var message = "There are no models ";
if (activeState != null) {
message += (activeState) ? "that are active " : "that are inactive ";
if (program.device) message += "and ";
}
if (program.device) message += "assigned to '" + program.device + "'";
console.log(message);
}
});
});
});
| JavaScript | 0.000001 | @@ -5594,16 +5594,23 @@
gned to
+device
'%22 + pro
|
a19b2193682dacf0e850bf68ce8584fa21d2d5d4 | make master slider icons clickable | material-ui/modules/mixer.js | material-ui/modules/mixer.js | import React from 'react'
import Channel from './channel'
import Master from './master'
import { connect }
from 'react-redux'
class Mixer extends React.Component {
constructor(props) {
super(props)
}
render() {
const { mixer : { channelList }, sendMessage } = this.props
return (
<div>
<Master />
<div style={{maxWidth: '900px', margin: '0 auto'}}>
{channelList.map(channel => (
<Channel {...channel}
key = {channel.id}
sendMessage = {sendMessage}
/>
))}
</div>
</div>
)
}
}
export default connect(state => ({
mixer : state.mixer,
}))(Mixer)
| JavaScript | 0 | @@ -329,16 +329,42 @@
%3CMaster
+ sendMessage=%7BsendMessage%7D
/%3E%0A
|
404f5901a66342fd28a242161cee6194711fcca0 | FIX sidebar loading visibility | lib/ui/src/components/sidebar/SidebarItem.js | lib/ui/src/components/sidebar/SidebarItem.js | import React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { opacify, transparentize } from 'polished';
import { Icons } from '@storybook/components';
const Expander = styled.span(
({ theme }) => ({
display: 'block',
width: 0,
height: 0,
marginRight: 6,
borderTop: '3.5px solid transparent',
borderBottom: '3.5px solid transparent',
borderLeft: `3.5px solid ${opacify(0.2, theme.appBorderColor)}`,
transition: 'transform .1s ease-out',
}),
({ isExpandable }) => (!isExpandable ? { borderLeftColor: 'transparent' } : {}),
({ isExpanded = false }) =>
isExpanded
? {
transform: 'rotateZ(90deg)',
}
: {}
);
const Icon = styled(Icons)(
{
flex: 'none',
width: 10,
height: 10,
marginRight: 6,
},
({ icon }) => {
if (icon === 'folder') {
return { color: '#774dd7' };
}
if (icon === 'component') {
return { color: '#1ea7fd' };
}
if (icon === 'bookmarkhollow') {
return { color: '#37d5d3' };
}
return {};
},
({ isSelected }) => (isSelected ? { color: 'inherit' } : {})
);
export const Item = styled.div(
{
fontSize: 13,
lineHeight: '16px',
paddingTop: 4,
paddingBottom: 4,
paddingRight: 20,
display: 'flex',
alignItems: 'center',
flex: 1,
background: 'transparent',
},
({ depth }) => ({
paddingLeft: depth * 15 + 9,
}),
({ theme, isSelected, loading }) =>
!loading &&
(isSelected
? {
cursor: 'default',
background: theme.color.secondary,
color: theme.color.lightest,
fontWeight: theme.typography.weight.bold,
}
: {
cursor: 'pointer',
color:
theme.base === 'light'
? theme.color.defaultText
: transparentize(0.2, theme.color.defaultText),
'&:hover': {
color: theme.color.defaultText,
background: theme.background.hoverable,
},
}),
({ theme, loading }) =>
loading && {
'&& > *': theme.animation.inlineGlow,
'&& > span': { borderColor: 'transparent' },
}
);
export default function SidebarItem({
name,
depth,
isComponent,
isLeaf,
isExpanded,
isSelected,
loading,
...props
}) {
let iconName;
if (isLeaf) {
iconName = 'bookmarkhollow';
} else if (isComponent) {
iconName = 'component';
} else {
iconName = 'folder';
}
return (
<Item
isSelected={isSelected}
depth={depth}
loading={loading}
{...props}
className={isSelected ? 'sidebar-item selected' : 'sidebar-item'}
>
<Expander
className="sidebar-expander"
isExpandable={!isLeaf}
isExpanded={isExpanded ? true : undefined}
/>
<Icon className="sidebar-svg-icon" icon={iconName} isSelected={isSelected} />
<span>{name}</span>
</Item>
);
}
SidebarItem.propTypes = {
name: PropTypes.node,
depth: PropTypes.number,
isComponent: PropTypes.bool,
isLeaf: PropTypes.bool,
isExpanded: PropTypes.bool,
isSelected: PropTypes.bool,
loading: PropTypes.bool,
};
SidebarItem.defaultProps = {
name: 'loading story',
depth: 0,
isComponent: false,
isLeaf: false,
isExpanded: false,
isSelected: false,
loading: false,
};
| JavaScript | 0 | @@ -2094,16 +2094,77 @@
ng && %7B%0A
+ '&& %3E svg + span': %7B background: theme.color.medium %7D,%0A
'&
@@ -2199,16 +2199,16 @@
neGlow,%0A
-
'&
@@ -2310,17 +2310,8 @@
me,%0A
- depth,%0A
is
@@ -2363,19 +2363,8 @@
ed,%0A
- loading,%0A
..
@@ -2558,16 +2558,16 @@
%3CItem%0A
+
is
@@ -2592,52 +2592,8 @@
ed%7D%0A
- depth=%7Bdepth%7D%0A loading=%7Bloading%7D%0A
|
fc3b88fa553627e3ef697a9058e474092a3b8de1 | Add getVariantUrl to content node. | src/models/ContentNode.js | src/models/ContentNode.js | 'use strict';
const ContentNode = function (context) {
const self = this;
const api = require('../api');
const config = require('../config');
this.uuid = context.content.uuid;
this.document = context.content;
this.children = [];
if (this.document.children && this.document.children.length === this.document.itemCount) {
this.document.children.forEach(child => {
self.children.push(new ContentNode({ content: child }));
});
}
this.getChildren = () => {
if (this.document.itemCount != this.children.length) {
return api.getContentNode(this.uuid)
.then(that => {
self.document = that.document;
self.children = that.children;
return self.children;
});
} else {
return Promise.resolve(this.children);
}
};
this.getUrl = () => {
return config.host + '/api/delivery' + escape(this.document.path);
};
};
module.exports = ContentNode;
| JavaScript | 0 | @@ -897,16 +897,192 @@
;%0A %7D;%0A%0A
+ this.getVariantUrl = name =%3E %7B%0A const query = '?variant=' + encodeURIComponent(name);%0A return config.host + '/api/delivery' + escape(this.document.path) + query;%0A %7D;%0A%0A
%7D;%0A%0Amodu
|
73684b6489078ce2a725fc591c31249ef8c4019b | Make Serializer work with nest API | addon/serializer.js | addon/serializer.js | import DS from "ember-data";
import Ember from 'ember';
var singularize = Ember.String.singularize;
var camelize = Ember.String.camelize;
export default DS.RESTSerializer.extend({
normalize: function(type, hash, prop) {
var links = hash.links;
for (var key in links) {
var linkedData = links[key];
if (linkedData.href) {
hash[key] = linkedData.href;
} else if (linkedData.ids) {
hash[key] = linkedData.ids;
} else {
hash[key + '_id'] = linkedData.id;
}
}
delete hash.links;
return this._super(type, hash, prop);
},
normalizePayload: function(payload) {
if (payload.linked) {
var store = Ember.get(this, 'store');
this.pushPayload(store, payload.linked);
delete payload.linked;
}
return this._super(payload);
},
keyForRelationship: function(key, relationship) {
if (relationship === 'belongsTo') {
return key + '_id';
}
return key;
}
});
| JavaScript | 0 | @@ -54,23 +54,21 @@
';%0A%0Avar
-singula
+dashe
rize = E
@@ -83,15 +83,13 @@
ing.
-singula
+dashe
rize
@@ -94,20 +94,21 @@
ze;%0Avar
-came
+plura
lize = E
@@ -123,12 +123,13 @@
ing.
-came
+plura
lize
@@ -959,16 +959,184 @@
rn key;%0A
+ %7D,%0A%0A serializeIntoHash: function(data, type, record, options) %7B%0A var root = dasherize(pluralize(type.typeKey));%0A data%5Broot%5D = this.serialize(record, options);%0A
%7D%0A%7D);%0A
|
b4a619e71f15508d8843ebb5a3bf408f5f155c2e | Remove Unuse Code In Number Component | src/js/components/number.js | src/js/components/number.js | import React from 'react'
import cx from 'classnames'
import Numeral from 'numeral'
import InputErrorList from './input_error_list'
import Saved from './saved'
import Label from './label'
import { sizeClassNames, formGroupCx } from '../util.js'
import defaultProps from '../default_props.js'
import defaultPropTypes from '../default_prop_types.js'
export default class Number extends React.Component {
static displayName = 'FriggingBootstrap.Number'
static defaultProps = Object.assign(defaultProps, {
format: '0,0[.][00]',
})
static propTypes = Object.assign({},
defaultPropTypes, {
format: React.PropTypes.string,
}
)
state = {
formattedValue: '',
}
_formatNumber(currentNumber) {
if (!this.props.format) return currentNumber
return currentNumber ? currentNumber.format(this.props.format) : ''
}
_onBlur() {
let value = this.props.valueLink.value
value = value.toString().replace(/,/g, '')
value = this._toNumeral(value) || ''
value = this._formatNumber(value)
this.setState({ formattedValue: value })
}
_onChange(value) {
this.setState({ formattedValue: value })
this.props.valueLink.requestChange(value.replace(/,/g, ''))
}
_inputCx() {
return cx(
this.props.inputHtml.className,
'form-control',
)
}
_input() {
const inputProps = Object.assign({}, this.props.inputHtml, {
className: this._inputCx(),
onBlur: this._onBlur.bind(this),
valueLink: {
value: (this.state.formattedValue || this._formatNumber(
this._toNumeral(this.props.valueLink.value) || '')
),
requestChange: this._onChange.bind(this),
},
})
return <input {...inputProps} />
}
_isNumber(value) {
const number = parseFloat(value)
return !Number.isNaN(parseFloat(number)) && Number.isFinite(number)
}
_toNumeral(value) {
const n = Numeral(value) // eslint-disable-line new-cap
// numeral.js converts empty strings into 0 for no reason, so if given
// value was not '0' or 0, treat it as null.
// or
// numeral.js can sometimes convert values (like '4.5.2') into NaN
// and we would rather null than NaN.
if (n.value() === 0 && (value !== 0 && value !== '0') || isNaN(n.value())) {
return null
}
return n
}
render() {
return (
<div className={cx(sizeClassNames(this.props))}>
<div className={formGroupCx(this.props)}>
<div>
<Label {...this.props} />
</div>
{this._input()}
<Saved saved={this.props.saved} />
<InputErrorList errors={this.props.errors} />
</div>
</div>
)
}
}
| JavaScript | 0.000001 | @@ -725,58 +725,8 @@
) %7B%0A
- if (!this.props.format) return currentNumber%0A%0A
@@ -1689,143 +1689,8 @@
%7D%0A%0A
- _isNumber(value) %7B%0A const number = parseFloat(value)%0A return !Number.isNaN(parseFloat(number)) && Number.isFinite(number)%0A %7D%0A%0A
_t
|
b72c07ad8decc7ec809a2e566bb9bfd524a38d4f | Add eslint disable for no-unused-vars to core/interfaces/i_metrics_manager.js | core/interfaces/i_metrics_manager.js | core/interfaces/i_metrics_manager.js | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview The interface for a metrics manager.
* @author aschmiedt@google.com (Abby Schmiedt)
*/
'use strict';
goog.module('Blockly.IMetricsManager');
goog.module.declareLegacyNamespace();
const Metrics = goog.requireType('Blockly.utils.Metrics');
const Size = goog.requireType('Blockly.utils.Size');
const {AbsoluteMetrics, ContainerRegion, ToolboxMetrics} = goog.requireType('Blockly.MetricsManager');
/**
* Interface for a metrics manager.
* @interface
*/
const IMetricsManager = function() {};
/**
* Returns whether the scroll area has fixed edges.
* @return {boolean} Whether the scroll area has fixed edges.
* @package
*/
IMetricsManager.prototype.hasFixedEdges;
/**
* Returns the metrics for the scroll area of the workspace.
* @param {boolean=} opt_getWorkspaceCoordinates True to get the scroll metrics
* in workspace coordinates, false to get them in pixel coordinates.
* @param {!ContainerRegion=} opt_viewMetrics The view
* metrics if they have been previously computed. Passing in null may cause
* the view metrics to be computed again, if it is needed.
* @param {!ContainerRegion=} opt_contentMetrics The
* content metrics if they have been previously computed. Passing in null
* may cause the content metrics to be computed again, if it is needed.
* @return {!ContainerRegion} The metrics for the scroll
* container
*/
IMetricsManager.prototype.getScrollMetrics;
/**
* Gets the width and the height of the flyout on the workspace in pixel
* coordinates. Returns 0 for the width and height if the workspace has a
* category toolbox instead of a simple toolbox.
* @param {boolean=} opt_own Whether to only return the workspace's own flyout.
* @return {!ToolboxMetrics} The width and height of the
* flyout.
* @public
*/
IMetricsManager.prototype.getFlyoutMetrics;
/**
* Gets the width, height and position of the toolbox on the workspace in pixel
* coordinates. Returns 0 for the width and height if the workspace has a simple
* toolbox instead of a category toolbox. To get the width and height of a
* simple toolbox @see {@link getFlyoutMetrics}.
* @return {!ToolboxMetrics} The object with the width,
* height and position of the toolbox.
* @public
*/
IMetricsManager.prototype.getToolboxMetrics;
/**
* Gets the width and height of the workspace's parent SVG element in pixel
* coordinates. This area includes the toolbox and the visible workspace area.
* @return {!Size} The width and height of the workspace's parent
* SVG element.
* @public
*/
IMetricsManager.prototype.getSvgMetrics;
/**
* Gets the absolute left and absolute top in pixel coordinates.
* This is where the visible workspace starts in relation to the SVG container.
* @return {!AbsoluteMetrics} The absolute metrics for
* the workspace.
* @public
*/
IMetricsManager.prototype.getAbsoluteMetrics;
/**
* Gets the metrics for the visible workspace in either pixel or workspace
* coordinates. The visible workspace does not include the toolbox or flyout.
* @param {boolean=} opt_getWorkspaceCoordinates True to get the view metrics in
* workspace coordinates, false to get them in pixel coordinates.
* @return {!ContainerRegion} The width, height, top and
* left of the viewport in either workspace coordinates or pixel
* coordinates.
* @public
*/
IMetricsManager.prototype.getViewMetrics;
/**
* Gets content metrics in either pixel or workspace coordinates.
* The content area is a rectangle around all the top bounded elements on the
* workspace (workspace comments and blocks).
* @param {boolean=} opt_getWorkspaceCoordinates True to get the content metrics
* in workspace coordinates, false to get them in pixel coordinates.
* @return {!ContainerRegion} The
* metrics for the content container.
* @public
*/
IMetricsManager.prototype.getContentMetrics;
/**
* Returns an object with all the metrics required to size scrollbars for a
* top level workspace. The following properties are computed:
* Coordinate system: pixel coordinates, -left, -up, +right, +down
* .viewHeight: Height of the visible portion of the workspace.
* .viewWidth: Width of the visible portion of the workspace.
* .contentHeight: Height of the content.
* .contentWidth: Width of the content.
* .svgHeight: Height of the Blockly div (the view + the toolbox,
* simple or otherwise),
* .svgWidth: Width of the Blockly div (the view + the toolbox,
* simple or otherwise),
* .viewTop: Top-edge of the visible portion of the workspace, relative to
* the workspace origin.
* .viewLeft: Left-edge of the visible portion of the workspace, relative to
* the workspace origin.
* .contentTop: Top-edge of the content, relative to the workspace origin.
* .contentLeft: Left-edge of the content relative to the workspace origin.
* .absoluteTop: Top-edge of the visible portion of the workspace, relative
* to the blocklyDiv.
* .absoluteLeft: Left-edge of the visible portion of the workspace, relative
* to the blocklyDiv.
* .toolboxWidth: Width of the toolbox, if it exists. Otherwise zero.
* .toolboxHeight: Height of the toolbox, if it exists. Otherwise zero.
* .flyoutWidth: Width of the flyout if it is always open. Otherwise zero.
* .flyoutHeight: Height of the flyout if it is always open. Otherwise zero.
* .toolboxPosition: Top, bottom, left or right. Use TOOLBOX_AT constants to
* compare.
* @return {!Metrics} Contains size and position metrics of a top
* level workspace.
* @public
*/
IMetricsManager.prototype.getMetrics;
exports = IMetricsManager;
| JavaScript | 0 | @@ -287,16 +287,62 @@
ace();%0A%0A
+/* eslint-disable-next-line no-unused-vars */%0A
const Me
@@ -388,24 +388,70 @@
.Metrics');%0A
+/* eslint-disable-next-line no-unused-vars */%0A
const Size =
@@ -491,16 +491,62 @@
Size');%0A
+/* eslint-disable-next-line no-unused-vars */%0A
const %7BA
|
4d7145ff21f7191cd0eba60595d4cc97fe158ff2 | Return after flushing the database | routes/messages.js | routes/messages.js | var messenger = require('../lib/messenger');
var session = require('../lib/session');
module.exports = function (server) {
server.post('/messages', function (req, res, next) {
var phoneNumber = req.params.From;
var message = req.params.Body.toLowerCase();
if (message === 'flush') {
session.flushall(function () {
messenger.send(phoneNumber, 'The database has been flushed.');
});
}
session.get(phoneNumber, function(err, user) {
if (err) {
messenger.fail(phoneNumber);
res.send(500);
}
if (user) {
messenger.send(phoneNumber, 'Hello, old friend. (' + user + ')' );
} else {
session.set(phoneNumber, 'initial', function () {
messenger.send(phoneNumber, 'Nice to meet you.');
});
}
});
res.send(200, {status: 'ok'});
});
} | JavaScript | 0.000008 | @@ -411,24 +411,59 @@
;%0A %7D);%0A
+ res.send(200);%0A return;%0A
%7D%0A %0A
|
b8120565bac8020d5b45f7f100e6e9051b7a1852 | include expo in the init error message (#873) | src/GoogleSignin.js | src/GoogleSignin.js | import { NativeModules, Platform } from 'react-native';
const { RNGoogleSignin } = NativeModules;
const IS_IOS = Platform.OS === 'ios';
class GoogleSignin {
configPromise;
constructor() {
if (__DEV__ && !RNGoogleSignin) {
console.error(
'RN GoogleSignin native module is not correctly linked. Please read the readme, setup and troubleshooting instructions carefully or try manual linking.'
);
}
}
async signIn() {
await this.configPromise;
return await RNGoogleSignin.signIn();
}
async hasPlayServices(options = { showPlayServicesUpdateDialog: true }) {
if (IS_IOS) {
return true;
} else {
if (options && options.showPlayServicesUpdateDialog === undefined) {
throw new Error(
'RNGoogleSignin: Missing property `showPlayServicesUpdateDialog` in options object for `hasPlayServices`'
);
}
return RNGoogleSignin.playServicesAvailable(options.showPlayServicesUpdateDialog);
}
}
configure(options = {}) {
if (options.offlineAccess && !options.webClientId) {
throw new Error('RNGoogleSignin: offline use requires server web ClientID');
}
this.configPromise = RNGoogleSignin.configure(options);
}
async signInSilently() {
await this.configPromise;
return RNGoogleSignin.signInSilently();
}
async signOut() {
return RNGoogleSignin.signOut();
}
async revokeAccess() {
return RNGoogleSignin.revokeAccess();
}
async isSignedIn() {
return RNGoogleSignin.isSignedIn();
}
async getCurrentUser() {
return RNGoogleSignin.getCurrentUser();
}
async clearCachedAccessToken(tokenString) {
if (!tokenString || typeof tokenString !== 'string') {
return Promise.reject('GoogleSignIn: clearCachedAccessToken() expects a string token.');
}
return IS_IOS ? null : await RNGoogleSignin.clearCachedAccessToken(tokenString);
}
async getTokens() {
if (IS_IOS) {
const tokens = await RNGoogleSignin.getTokens();
return tokens;
} else {
const userObject = await RNGoogleSignin.getTokens();
return {
idToken: userObject.idToken,
accessToken: userObject.accessToken,
};
}
}
}
export const GoogleSigninSingleton = new GoogleSignin();
export const statusCodes = {
SIGN_IN_CANCELLED: RNGoogleSignin.SIGN_IN_CANCELLED,
IN_PROGRESS: RNGoogleSignin.IN_PROGRESS,
PLAY_SERVICES_NOT_AVAILABLE: RNGoogleSignin.PLAY_SERVICES_NOT_AVAILABLE,
SIGN_IN_REQUIRED: RNGoogleSignin.SIGN_IN_REQUIRED,
};
| JavaScript | 0 | @@ -256,17 +256,17 @@
-'
+%60
RN Googl
@@ -407,17 +407,132 @@
linking.
-'
+ If you're using Expo, please use expo-google-sign-in. This is because Expo does not support custom native modules.%60
%0A )
|
1d73b2050bc3fb2ee67f20868c7f75cd8f08b90d | Refactor rendering method in EndingView | src/modules/EndingView.js | src/modules/EndingView.js | /*
View that is shown at the end of application.
When speech ends or the speech bubble is closed, user is moved to home page
*/
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import SpeechBubble from '../components/SpeechBubble';
import Hemmo from '../components/Hemmo';
import {getSizeByHeight, getImage} from '../services/graphics';
import * as NavigationState from './navigation/NavigationState';
import {
StyleSheet,
View,
Image
} from 'react-native';
const EndingView = React.createClass({
propTypes: {
dispatch: PropTypes.func.isRequired
},
getInitialState() {
return {
showBubble: true
};
},
hideBubble() {
this.props.dispatch(NavigationState.resetRoute());
},
restartAudioAndText() {
this.setState({showBubble: true});
},
render() {
if (this.state.showBubble === true) {
var speechBubble = (
<SpeechBubble
text={'ending'}
hideBubble={this.hideBubble}
bubbleType={'puhekupla_oikea'}
style={{top: 40, left: 40, margin: 45, fontSize: 14, size: 0.5}}/>
);
}
return (
<Image source={getImage('tausta_perus')} style={styles.container}>
<View style={styles.hemmo}>
<Hemmo image={'hemmo_keski'} size={0.8} restartAudioAndText={this.restartAudioAndText}/>
</View>
<Image
source={getImage('lopetusteksti')}
style={[styles.info, getSizeByHeight('lopetusteksti', 0.4)]}/>
{speechBubble}
</Image>
);
}
});
const styles = StyleSheet.create({
container: {
flex: 1,
width: null,
height: null
},
info: {
position: 'absolute',
left: 20,
bottom: 20
},
hemmo: {
position: 'absolute',
bottom: 50,
right: 20
}
});
export default connect()(EndingView);
| JavaScript | 0 | @@ -821,22 +821,36 @@
nder
+SpeechBubble
() %7B%0A
-%0A
-if (
+return
this
@@ -871,49 +871,12 @@
ble
-=== true) %7B%0A var speechBubble =
+?
(%0A
-
@@ -899,18 +899,16 @@
-
-
text=%7B'e
@@ -915,18 +915,16 @@
nding'%7D%0A
-
@@ -960,18 +960,16 @@
-
bubbleTy
@@ -995,26 +995,24 @@
a'%7D%0A
-
-
style=%7B%7Btop:
@@ -1067,25 +1067,50 @@
.5%7D%7D
-/%3E%0A );%0A %7D
+%0A /%3E%0A ) : null;%0A %7D,%0A%0A render() %7B
%0A
@@ -1485,17 +1485,28 @@
%7B
-s
+this.renderS
peechBub
@@ -1504,24 +1504,26 @@
SpeechBubble
+()
%7D%0A %3C/Im
|
a1150feab29d6e59c52ade2e9d6731d3f961b37d | Add package version to clientProperties, as well as started date, and last connection date Fixes #35 | src/modules/connection.js | src/modules/connection.js | var amqp = require('amqplib'),
assert = require('assert');
var connections = {};
/**
* Connect to the broker. We keep only 1 connection for each connection string provided in config, as advised by RabbitMQ
* @return {Promise} A promise that resolve with an amqp.node connection object
*/
function getConnection() {
let url = this.config.url;
let hostname = this.config.hostname;
let connection = connections[url];
//cache handling, if connection already opened, return it
if (connection && connection.conn) {
return Promise.resolve(connection.conn);
}
//prepare the connection internal object, and reset channel if connection has been closed
connection = connections[url] = { conn: null, channel: null };
connection.conn = amqp.connect(url, { clientProperties: { hostname: hostname } })
.then((conn) => {
//on connection close, delete connection
conn.on('close', () => { delete connection.conn; });
conn.on('error', this.config.transport.error);
connection.conn = conn;
return conn;
})
.catch(() => {
connection.conn = null;
});
return connection.conn;
}
/**
* Create the channel on the broker, once connection is succesfuly opened.
* Since RabbitMQ advise to open one channel by process and node is mono-core, we keep only 1 channel for the whole connection.
* @return {Promise} A promise that resolve with an amqp.node channel object
*/
function getChannel() {
let url = this.config.url;
let prefetch = this.config.prefetch;
let connection = connections[url];
//cache handling, if channel already opened, return it
if (connection && connection.chann) {
return Promise.resolve(connection.chann);
}
connection.chann = connection.conn.createChannel()
.then((channel) => {
channel.prefetch(prefetch);
//on error we remove the channel so the next call will recreate it (auto-reconnect are handled by connection users)
channel.on('close', () => { delete connection.chann; });
channel.on('error', this.config.transport.error);
connection.chann = channel;
return channel;
});
return connection.chann;
}
/**
* Connect to AMQP and create channel
* @return {Promise} A promise that resolve with an amqp.node channel object
*/
function get() {
return getConnection.call(this)
.then(() => {
return getChannel.call(this);
});
}
/**
* Register an event on the amqp.node channel
* @param {string} on the channel event name to be binded with
* @param {function} func the callback function to execute when the event is called
*/
function addListener(on, func) {
this.get().then((channel) => {
channel.on(on, func);
});
}
module.exports = (config) => {
assert(config.hostname);
assert(config.hostname);
return {
config: config,
get: get,
addListener: addListener
};
};
| JavaScript | 0 | @@ -52,16 +52,100 @@
assert')
+,%0A packageVersion = require('../../package.json').version,%0A startedAt = new Date()
;%0A%0Avar c
@@ -868,16 +868,22 @@
perties:
+%0A
%7B hostn
@@ -899,18 +899,89 @@
name
- %7D %7D)
+, bunnymq: packageVersion, startedAt: startedAt, connectedAt: new Date() %7D
%0A
+%7D)
.the
|
d2a69515488823caab54cd3ea2a996b3ac308895 | Update .npmignore generation | bin/npm-create.js | bin/npm-create.js | #!/usr/bin/env node
var path = require( 'path' )
var fs = require( 'fs' )
var prompt = require( 'inquirer' ).prompt
var readdir = require( 'readdirp' )
var config = require( 'npmconf' )
var lookup = require( 'dotty' )
var target = process.cwd()
function render( template, data ) {
return template.replace(
/\{\{([^\}]+)\}\}/g,
function( _, selector ) {
selector = selector.replace( /^\s+|\s+$/g, '' )
return lookup.get( data, selector ) || ''
}
).replace( /^\s+|\s+$/, '' ) + '\n'
}
function askQuestions( data, callback ) {
var questions = prompt([{
name: 'name',
message: 'Module name',
default: data.module.name
},{
name: 'prefix',
type: 'input',
message: 'Repository prefix',
default: '',
filter: function( input ) {
return input && input.length ?
input + '-' : ''
},
},{
name: 'version',
type: 'input',
message: 'Version',
default: data.module.version,
},{
name: 'description',
type: 'input',
message: 'Description',
default: '',
},{
name: 'keywords',
type: 'input',
message: 'Keywords',
default: '',
filter: function( input ) {
var words = !input || !input.length ? [] :
input.replace( /^\s+|\s+$/g, '' ).split( /[,\s]+/g )
return JSON.stringify( words )
},
},{
name: 'license',
type: 'list',
message: 'License',
default: data.module.licenseType,
choices: [
'MIT',
'ISC',
'BSD-3-Clause',
'BSD-2-Clause',
'GPL-3.0',
'Apache-2.0',
'Unlicense',
],
filter: function( input ) {
var filename = __dirname + '/../licenses/' + input + '.md'
return {
type: input,
text: fs.readFileSync( filename, 'utf8' )
}
}
},{
name: 'main',
type: 'input',
message: 'Entry point',
default: 'lib/'+data.module.name,
},{
name: 'test',
type: 'input',
message: 'Tests',
default: 'echo \\"Error: no test specified\\" && exit 1',
}])
questions.then( function( results ) {
data.module.name = results.name
data.repo.prefix = results.prefix
data.module.version = results.version
data.module.description = results.description
data.module.keywords = results.keywords
data.module.licenseType = results.license.type
data.module.main = results.main
data.module.test = results.test
data.module.license = render( results.license.text, data )
callback( data )
})
}
function writePackage( data, callback ) {
var dirstream = readdir({
root: __dirname + '/../templates',
})
dirstream.on( 'data', function( file ) {
var dest = path.resolve( target, file.path )
if( fs.existsSync( dest ) )
return console.log( 'IGNORING', file.path )
fs.readFile( file.fullPath, 'utf8', function( error, content ) {
if( error != null )
throw error
content = render( content, data )
if( /\.json$/i.test( file.name ) ) {
content = JSON.stringify( JSON.parse( content ), null, 2 )
}
fs.writeFile( dest, content, function( error ) {
if( error != null )
throw error
})
})
})
// Write out .npmignore manually here,
// because having it in the templates folder
// causes dotfiles to be ignored (issue #1)
dirstream.on( 'end', function() {
var dest = path.resolve( target, '.npmignore' )
// TODO: Add CI config files, such as 'appveyor.yml' (?)
var npmignore = [
'.*',
'*.md',
'*.log',
'doc',
'docs',
'test',
'example',
'benchmark',
].join( '\n' ) + '\n'
// Don't overwrite existing .npmignore
try { fs.statSync( dest ) } catch( error ) {
fs.writeFileSync( dest, npmignore )
}
})
}
config.load( {}, function( error, npm ) {
if( error != null )
throw error
var data = {
date: {
year: new Date().getFullYear()
},
author: {
name: npm.get( 'init.author.name' ),
url: npm.get( 'init.author.url' ),
email: npm.get( 'init.author.email' ),
github: npm.get( 'init.author.github' ),
},
module: {
name: path.basename( target ),
version: npm.get( 'init.version' ),
licenseType: npm.get( 'init.license' ),
license: '',
},
repo: {
prefix: '',
}
}
console.log( '' )
askQuestions( data, writePackage )
})
| JavaScript | 0.000001 | @@ -3544,19 +3544,16 @@
%0A '
-doc
',%0A
@@ -3558,12 +3558,17 @@
'
-docs
+benchmark
',%0A
@@ -3573,20 +3573,19 @@
%0A '
-test
+doc
',%0A
@@ -3599,33 +3599,28 @@
le',%0A '
-benchmark
+test
',%0A %5D.joi
|
0b1330c1fdc3827c5a75cbaf06a187441ebe7bdc | remove some unnecessary white space to simplify diffs | src/js/media/types/Audio.js | src/js/media/types/Audio.js | import { Media } from "../Media";
import { transformMediaURL } from "../../core/Util";
import * as Browser from "../../core/Browser"
import { trace } from "../../core/Util";
export default class Audio extends Media {
_loadMedia() {
// Loading Message
this.loadingMessage();
// Create media?
if (!this.options.background) {
this.createMedia();
}
// After loaded
this.onLoaded();
}
createMedia() {
//Transform URL for Dropbox
var url = transformMediaURL(this.data.url),
self = this;
var self = this,
audio_class = "tl-media-item tl-media-audio tl-media-shadow";
// Link
if (this.data.link) {
this._el.content_link = this.domCreate("a", "", this._el.content);
this._el.content_link.href = this.data.link;
this._el.content_link.target = "_blank";
this._el.content_link.setAttribute('rel', 'noopener');
this._el.content_item = this.domCreate("audio", audio_class, this._el.content_link);
} else {
this._el.content_item = this.domCreate("audio", audio_class, this._el.content);
}
this._el.content_item.controls = true;
this._el.source_item = this.domCreate("source", "", this._el.content_item);
// Media Loaded Event
this._el.content_item.addEventListener('load', function(e) {
self.onMediaLoaded();
});
this._el.source_item.src = url;
this._el.source_item.type = this._getType(this.data.url, this.data.mediatype.match_str);
this._el.content_item.innerHTML += "Your browser doesn't support HTML5 audio with " + this._el.source_item.type;
this.player_element = this._el.content_item
}
_updateMediaDisplay(layout) {
if (Browser.firefox) {
this._el.content_item.style.width = "auto";
}
}
_stopMedia() {
if (this.player_element) {
this.player_element.pause()
}
}
_getType(url, reg) {
var ext = url.match(reg);
var type = "audio/"
switch (ext[1]) {
case "mp3":
type += "mpeg";
break;
case "wav":
type += "wav";
break;
case "m4a":
type += "mp4";
break;
default:
type = "audio";
break;
}
return type
}
} | JavaScript | 0.000005 | @@ -234,13 +234,8 @@
) %7B%0A
- %0A
@@ -585,17 +585,16 @@
= this;
-
%0A%0A
|
e59a51ecd1b809f189c4b0f318ee1fafd07d4987 | Fix jshint errors. | src/pat/toggle.js | src/pat/toggle.js | /**
* Patterns toggle - toggle class on click
*
* Copyright 2012-2014 Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"pat-registry",
"pat-logger",
"pat-parser",
"pat-store"
], function($, patterns, logger, Parser, store) {
var log = logger.getLogger("pat.toggle"),
parser = new Parser("toggle");
parser.add_argument("selector");
parser.add_argument("attr", "class");
parser.add_argument("value");
parser.add_argument("store", "none", ["none", "session", "local"]);
function ClassToggler(values) {
this.values=values.slice(0);
if (this.values.length>1)
this.values.push(values[0]);
}
ClassToggler.prototype = {
toggle: function Toggler_toggle(el) {
var current = this.get(el),
next = this.next(current);
this.set(el, next);
return next;
},
get: function Toggler_get(el) {
var classes = el.className.split(/\s+/);
for (var i=0; i<this.values.length;i++)
if (classes.indexOf(this.values[i])!==-1)
return this.values[i];
return null;
},
set: function Toggler_set(el, value) {
var classes = el.className.split(/\s+/),
values = this.values;
classes=classes.filter(function(v) { return v.length && values.indexOf(v)===-1;});
if (value)
classes.push(value);
el.className=classes.join(" ");
},
next: function Toggler_next(current) {
if (this.values.length===1)
return current ? null : this.values[0];
for (var i=0; i<(this.values.length-1); i++)
if (this.values[i]===current)
return this.values[i+1];
return this.values[0];
}
};
function AttributeToggler(attribute) {
this.attribute=attribute;
}
AttributeToggler.prototype = new ClassToggler([]);
AttributeToggler.prototype.get=function AttributeToggler_get(el) {
return !!el[this.attribute];
};
AttributeToggler.prototype.set=function AttributeToggler_set(el, value) {
if (value)
el[this.attribute]=value;
else
el.removeAttribute(this.attribute);
};
AttributeToggler.prototype.next=function AttributeToggler_next(value) {
return !value;
};
var toggle = {
name: "toggle",
trigger: ".pat-toggle",
// Hook for testing
_ClassToggler: ClassToggler,
_AttributeToggler: AttributeToggler,
init: function toggle_init($el) {
return $el.each(function toggle_init_el() {
var $trigger = $(this),
options = toggle._validateOptions(this, parser.parse($trigger, true));
if (!options.length)
return;
for (var i=0; i<options.length; i++)
if (options[i].value_storage) {
var victims, state, last_state;
victims=document.querySelectorAll(options[i].selector);
if (!victims.length)
continue;
state=options[i].toggler.get(victims[0]),
last_state=options[i].store_value.get();
if (state!==last_state)
for (var j=0; j<victims.length; j++)
options[i].toggler.set(victims[j], last_state);
}
$trigger
.off(".toggle")
.on("click.toggle", null, options, toggle._onClick)
.on("keypress.toggle", null, options, toggle._onKeyPress);
});
},
_makeToggler: function toggle_makeToggler(options) {
if (options.attr==="class") {
var values = options.value.split(/\s+/);
values=values.filter(function(v) { return v.length; });
return new this._ClassToggler(values);
} else
return new this._AttributeToggler(options.attr);
},
_validateOptions: function toggle_validateOptions(trigger, options) {
var correct=[],
i, option, store_error;
if (!options.length)
return correct;
for (i=0; i<options.length; i++) {
option=options[i];
if (!option.selector) {
log.error("Toggle pattern requires a selector.");
continue;
}
if (option.attr!=="class" && option.value) {
log.warn("Values are not supported attributes other than class.");
continue;
}
if (option.attr==="class" && !option.value) {
log.error("Toggle pattern needs values for class attributes.");
continue;
}
if (i && option.store!=="none") {
log.warn("store option can only be set on first argument");
option.store="none";
}
if (option.store!=="none") {
if (!trigger.id) {
log.warn("state persistance requested, but element has no id");
option.store="none";
} else if (!store.supported) {
store_error="browser does not support webstorage";
log.warn("state persistance requested, but browser does not support webstorage");
option.store="none";
} else {
var storage = (option.store==="local" ? store.local : store.session)(toggle.name);
option.value_storage = store.ValueStore(storage, (trigger.id+"-"+i));
}
}
option.toggler=this._makeToggler(option);
correct.push(option);
}
return correct;
},
_onClick: function toggle_onClick(event) {
var options = event.data,
victims, toggler, next_state, j;
for (var i=0; i<options.length; i++) {
victims=document.querySelectorAll(options[i].selector);
if (!victims.length)
continue;
toggler=options[i].toggler;
next_state=toggler.toggle(victims[0]);
for (j=1; j<victims.length; j++)
toggler.set(victims[j], next_state);
}
event.preventDefault();
},
_onKeyPress : function toggle_onKeyPress(event) {
var keycode = event.keyCode ? event.keyCode : event.which;
if (keycode==="13")
$(this).trigger('click', event);
},
};
patterns.register(toggle);
return toggle;
});
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -6958,15 +6958,15 @@
ger(
-'
+%22
click
-'
+%22
, ev
@@ -6980,17 +6980,16 @@
%7D
-,
%0A %7D;%0A
|
95b56029ad2a69f09b9e991bc113900f4b2d08d9 | remove abi insert from register | routes/register.js | routes/register.js | let express = require('express');
let router = express.Router();
let knexConfig = require('../knex/knexfile');
let knex = require('knex')(knexConfig[process.env.NODE_ENV || "development"]);
let web3Handler = require("../public/javascripts/Web3Handler.js");
router.get("/register", (req, res, next) => {
res.render('register', {
// status:"Register your dApp by filling out the form below"
});
});
router.get("/register/:error", (req,res,next) => {
let error = req.params.error;
res.render('register', {
status: "Error registering dApp: " + error
});
});
//on submit
router.get('/register/:dappname/:contractaddress', (req,res,next) =>
{
let dappName = req.params.dappname;
let contractAddress = req.params.contractaddress;
//web3Handler.checkContractValidity(res,contractAddress, abi);
web3Handler.checkIfContractIsVerified(contractAddress, (err,data) => {
if(data.body.message !== "NOTOK")
{
//verified
let abi = data.body.result;
knex.table("dapptable").insert({dappname: dappName, abi:abi, contractaddress:contractAddress})
.then((data) => {
console.log(data);
res.render('register', {
status:"dApp registration successful"
});
})
.catch((err) =>
{
if(err) throw err;
});
}
else
{
res.render('register', {
status: "dApp source code is not verified on etherscan, please verify it then try again"
})
}
});
});
module.exports = router;
| JavaScript | 0 | @@ -1089,17 +1089,8 @@
ame,
- abi:abi,
con
|
dd3f656d58c7623668cb6a8e0728163b3ec9ccc1 | Add default text for switcher | src/js/switcher/switcher.js | src/js/switcher/switcher.js | const Joomla = window.Joomla || {};
/** Include the relative styles */
if (!document.head.querySelector('#joomla-switcher-style')) {
const style = document.createElement('style');
style.id = 'joomla-switcher-style';
style.innerHTML = '{{stylesheet}}';
document.head.appendChild(style);
}
class JoomlaSwitcherElement extends HTMLElement {
/* Attributes to monitor */
static get observedAttributes() { return ['type', 'offText', 'onText']; }
get type() { return this.getAttribute('type'); }
set type(value) { return this.setAttribute('type', value); }
get offText() { return this.getAttribute('offText'); }
get onText() { return this.getAttribute('onText'); }
/* Lifecycle, element appended to the DOM */
connectedCallback() {
const self = this;
// Create the markup
this.createMarkup(self);
// Add the initial active class
const inputs = [].slice.call(self.querySelectorAll('input'));
const container = self.querySelector('span.switcher');
const next = inputs[1].parentNode.nextElementSibling;
// Add tab focus
container.setAttribute('tabindex', 0);
if (inputs[1].checked) {
inputs[1].parentNode.classList.add('active');
next.querySelector(`.switcher-label-${inputs[1].value}`).classList.add('active');
} else {
next.querySelector(`.switcher-label-${inputs[0].value}`).classList.add('active');
}
inputs.forEach((switchEl) => {
// Add the required accessibility tags
if (switchEl.id) {
const parent = switchEl.parentNode;
const relatedSpan = parent.nextElementSibling.querySelector(`span.switcher-label-${switchEl.value}`);
relatedSpan.id = `${switchEl.id}-label`;
switchEl.setAttribute('aria-labelledby', relatedSpan.id);
}
// Remove the tab focus from the inputs
switchEl.setAttribute('tabindex', '-1');
// Add the active class on click
switchEl.addEventListener('click', () => {
self.switch();
});
});
container.addEventListener('keydown', (event) => {
if (event.keyCode === 13 || event.keyCode === 32) {
event.preventDefault();
const element = container.querySelector('input:not(.active)');
element.click();
}
});
}
/* Lifecycle, element removed from the DOM */
disconnectedCallback() {
this.removeEventListener('joomla.switcher.toggle', this);
this.removeEventListener('joomla.switcher.on', this);
this.removeEventListener('joomla.switcher.off', this);
this.removeEventListener('click', this);
}
/* Method to dispatch events. Internal */
dispatchCustomEvent(eventName) {
const OriginalCustomEvent = new CustomEvent(eventName, { bubbles: true, cancelable: true });
OriginalCustomEvent.relatedTarget = this;
this.dispatchEvent(OriginalCustomEvent);
this.removeEventListener(eventName, this);
}
/** Method to build the switch. Internal */
createMarkup(switcher) {
const inputs = [].slice.call(switcher.querySelectorAll('input'));
let checked = 0;
// Create the first 'span' wrapper
const spanFirst = document.createElement('span');
spanFirst.classList.add('switcher');
// If no type has been defined, the default as "success"
if (!this.type) {
this.setAttribute('type', 'success');
}
const switchEl = document.createElement('span');
switchEl.classList.add('switch');
inputs.forEach((input, index) => {
input.setAttribute('role', 'switch');
if (input.checked) {
input.setAttribute('aria-checked', true);
}
spanFirst.appendChild(input);
if (index === 1 && input.checked) {
checked = 1;
}
});
spanFirst.appendChild(switchEl);
// Create the second 'span' wrapper
const spanSecond = document.createElement('span');
spanSecond.classList.add('switcher-labels');
const labelFirst = document.createElement('span');
labelFirst.classList.add('switcher-label-0');
labelFirst.innerText = this.offText;
const labelSecond = document.createElement('span');
labelSecond.classList.add('switcher-label-1');
labelSecond.innerText = this.onText;
if (checked === 0) {
labelFirst.classList.add('active');
} else {
labelSecond.classList.add('active');
}
spanSecond.appendChild(labelFirst);
spanSecond.appendChild(labelSecond);
// Remove all child nodes from the switcher
while (switcher.firstChild) {
switcher.removeChild(switcher.firstChild);
}
// Append everything back to the main element
switcher.appendChild(spanFirst);
switcher.appendChild(spanSecond);
return switcher;
}
/** Method to toggle the switch. Internal */
switch() {
const parent = this.firstChild;
const inputs = [].slice.call(parent.querySelectorAll('input'));
const spans = [].slice.call(parent.nextElementSibling.querySelectorAll('span'));
const newActive = this.querySelector('input:not(.active)');
spans.forEach((span) => {
span.classList.remove('active');
});
if (parent.classList.contains('active')) {
parent.classList.remove('active');
} else {
parent.classList.add('active');
}
if (!newActive.classList.contains('active')) {
inputs.forEach((input) => {
input.classList.remove('active');
input.removeAttribute('checked');
input.setAttribute('aria-checked', false);
});
newActive.classList.add('active');
this.dispatchCustomEvent('joomla.switcher.on');
} else {
inputs.forEach((input) => {
input.classList.remove('active');
input.removeAttribute('checked');
input.setAttribute('aria-checked', false);
});
this.dispatchCustomEvent('joomla.switcher.off');
}
newActive.setAttribute('checked', '');
newActive.setAttribute('aria-checked', true);
parent.nextElementSibling.querySelector(`.switcher-label-${newActive.value}`).classList.add('active');
}
/** Method to toggle the switch */
toggle() {
const newActive = this.querySelector('input:not(.active)');
newActive.click();
}
}
customElements.define('joomla-switcher', JoomlaSwitcherElement);
| JavaScript | 0.000001 | @@ -610,24 +610,33 @@
e('offText')
+ %7C%7C 'Off'
; %7D%0A get on
@@ -678,16 +678,24 @@
onText')
+ %7C%7C 'On'
; %7D%0A%0A /
|
2ec7eaa89e90108c2de46f83e3fb23cfa28b6065 | Update movies.js | application/actions/movies.js | application/actions/movies.js | import 'whatwg-fetch'
import { API_URL, API_KEY } from '../config'
import types from '../constants/actionTypes'
const fetchMoviesByGenre = (genreId) => {
const apiUrl = API_URL
const apiKey = API_KEY
let api_endpoint = `${apiUrl}/genre/${genreId}/movies?api_key=${apiKey}&language=en-US`
return {
type: types.FETCH_MOVIES,
payload: new Promise((resolve, reject) => {
fetch(api_endpoint).then(r => resolve(r.json())).catch(reject)
})
}
}
export { fetchMoviesByGenre }
| JavaScript | 0.000001 | @@ -160,57 +160,8 @@
nst
-apiUrl = API_URL%0A const apiKey = API_KEY%0A%0A let
api_
@@ -178,14 +178,15 @@
%60$%7B
-apiUrl
+API_URL
%7D/ge
@@ -221,14 +221,15 @@
y=$%7B
-apiKey
+API_KEY
%7D&la
|
4d68812b6539fac45648dd7c69873acd467f21b6 | Fix usage description | bin/pegjs-main.js | bin/pegjs-main.js | importPackage(java.io);
importPackage(java.lang);
/*
* Rhino does not have __FILE__ or anything similar so we have to pass the
* script path from the outside.
*/
load(arguments[0] + "/../lib/peg.js");
var FILE_STDIN = "-";
var FILE_STDOUT = "-";
function readFile(file) {
var f = new BufferedReader(new InputStreamReader(
file === FILE_STDIN ? System["in"] : new FileInputStream(file)
));
var result = "";
var line = "";
try {
while ((line = f.readLine()) !== null) {
result += line + "\n";
}
} finally {
f.close();
}
return result;
}
function writeFile(file, text) {
var f = new BufferedWriter(new OutputStreamWriter(
file === FILE_STDOUT ? System.out : new FileOutputStream(file)
));
try {
f.write(text);
} finally {
f.close();
}
}
function isOption(arg) {
return /-.+/.test(arg);
}
function printVersion() {
print("PEG.js " + PEG.VERSION);
}
function printHelp() {
print("Usage: pegjs [options] [--] <parser_var> [<input_file>] [<output_file>]");
print("");
print("Generates a parser from the PEG grammar specified in the <input_file> and");
print("writes it to the <output_file>.");
print("");
print("If the <output_file> is omitted, its name is generated by changing the");
print("<input_file> extension to \".js\". If both <input_file> and <output_file> are");
print("omitted, standard input and output are used.");
print("");
print("Options:");
print(" -e, --export-var <variable> name of the variable where the parser object");
print(" will be stored (default: \"exports.parser\")");
print(" -v, --version print version information and exit");
print(" -h, --help print help and exit");
}
function nextArg() {
args.shift();
}
function exitSuccess() {
quit(0);
}
function exitFailure() {
quit(1);
}
function abort(message) {
System.out.println(message);
exitFailure();
}
/* This makes the generated parser a CommonJS module by default. */
var exportVar = "exports.parser";
/*
* The trimmed first argument is the script path -- see the beginning of this
* file.
*/
var args = Array.prototype.slice.call(arguments, 1);
while (args.length > 0 && isOption(args[0])) {
switch (args[0]) {
case "-e":
case "--export-var":
nextArg();
exportVar = args[0];
break;
case "--version":
printVersion();
exitSuccess();
break;
case "-v":
case "--version":
printVersion();
exitSuccess();
break;
case "-h":
case "--help":
printHelp();
exitSuccess();
break;
case "--":
nextArg();
break;
default:
abort("Unknown option: " + args[0] + ".");
}
nextArg();
}
switch (args.length) {
case 0:
var inputFile = FILE_STDIN;
var outputFile = FILE_STDOUT;
break;
case 1:
var inputFile = args[0];
var outputFile = args[0].replace(/\.[^.]*$/, ".js");
break;
case 2:
var inputFile = args[0];
var outputFile = args[1];
break;
default:
abort("Too many arguments.");
}
var input = readFile(inputFile);
try {
var parser = PEG.buildParser(input);
} catch (e) {
if (e.line !== undefined && e.column !== undefined) {
abort(e.line + ":" + e.column + ": " + e.message);
} else {
abort(e.message);
}
}
writeFile(outputFile, exportVar + " = " + parser.toSource() + ";\n");
| JavaScript | 0.002393 | @@ -979,21 +979,8 @@
%5B--%5D
- %3Cparser_var%3E
%5B%3Ci
|
d9d5bd29e4eade28d46c38ef4256bf2a224c599d | fix whitespace | src/languages/powershell.js | src/languages/powershell.js | /*
Language: PowerShell
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>
*/
function(hljs) {
var backtickEscape = {
begin: '`[\\s\\S]',
relevance: 0
};
var VAR = {
className: 'variable',
variants: [
{begin: /\$[\w\d][\w\d_:]*/}
]
};
var LITERAL = {
className: 'literal',
begin: /\$(null|true|false)\b/
};
var QUOTE_STRING = {
className: 'string',
begin: /"/, end: /"/,
contains: [
backtickEscape,
VAR,
{
className: 'variable',
begin: /\$[A-z]/, end: /[^A-z]/
}
]
};
var APOS_STRING = {
className: 'string',
begin: /'/, end: /'/
};
var MULTILINE_COMMENT = {
className: 'comment',
begin: /<#/, end: /#>/
}
return {
aliases: ['ps'],
lexemes: /-?[A-z\.\-]+/,
case_insensitive: true,
keywords: {
keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
built_in: 'Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning',
nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
},
contains: [
hljs.HASH_COMMENT_MODE,
hljs.NUMBER_MODE,
QUOTE_STRING,
APOS_STRING,
LITERAL,
VAR,
MULTILINE_COMMENT
]
};
}
| JavaScript | 0.999999 | @@ -3163,9 +3163,12 @@
AR,%0A
-%09
+
MU
|
c048f4651723366e7b163c8335567feedc2362a9 | Make ngModel for hidden input field work with parent scope | angular-uploadcare.js | angular-uploadcare.js | 'use strict';
/**
* @ngdoc directive
* @name angular-uploadcare.directive:UploadCare
* @description Provides a directive for the Uploadcare widget.
* # UploadCare
*/
angular.module('ng-uploadcare', [])
.directive('uploadcareWidget', function () {
return {
restrict: 'E',
replace: true,
require: 'ngModel',
template: '<input type="hidden" role="ng-uploadcare-uploader" />',
scope: {
onWidgetReady: '&',
onUploadComplete: '&',
onChange: '&',
},
controller: ['$scope', '$element', '$log', function($scope, $element, $log) {
if(!uploadcare) {
$log.error('Uploadcare script has not been loaded!.');
return;
}
$scope.widget = uploadcare.Widget($element);
$scope.onWidgetReady({widget: $scope.widget});
$scope.widget.onUploadComplete(function(info) {
$scope.onUploadComplete({info: info});
});
$scope.widget.onChange(function(file) {
$scope.onChange({file: file});
})
}]
};
});
| JavaScript | 0 | @@ -980,24 +980,151 @@
ion(file) %7B%0A
+ $scope.$apply(function () %7B%0A $parse($attrs.ngModel).assign($scope.$parent, $element.val());%0A %7D);%0A
$s
|
5790b884a769437289c9bb4d05d4e04a7bf13341 | Fix for node v6 | admin/app/static.js | admin/app/static.js | /**
* Returns an Express Router with bindings for the Admin UI static resources,
* i.e files, less and browserified scripts.
*
* Should be included before other middleware (e.g. session management,
* logging, etc) for reduced overhead.
*/
var browserify = require('./browserify');
var express = require('express');
var glob = require('glob');
var less = require('less-middleware');
var path = require('path');
var minify = require('express-minify');
var router = express.Router();
/* Browersify all Tiny-MCE React-based plugins */
var mapPlugin = function(file, pluckNameReg) {
var nameMatch = pluckNameReg.exec(file);
if (!nameMatch) throw new Error('Unexpected name format for TinyMCE plugin ' + file);
return {
file: path.relative(__dirname, file).replace(/\\/g, '/'),
fileRoot: '/' + path.relative(__dirname + '/../', file).replace(/\\/g, '/'),
path: nameMatch[1],
pathRoot: '/' + path.relative(__dirname + '/../', nameMatch[1]).replace(/\\/g, '/'),
pathRootNoPublic: path.normalize('/' + path.relative(__dirname + '/../', nameMatch[1]).replace('public' + path.sep, '')).replace(/\\/g, '/'),
name: nameMatch[2],
filename: nameMatch[3]
};
};
var basePluginFolder = '/../public/js/lib/tinymce/plugins/';
var pluckReactPluginName = /(.*tinymce\/plugins\/([^\/]+)\/)(renderPlugin)\.js$/i;
var tinyReactPlugins = glob.sync(__dirname + basePluginFolder + '**/renderPlugin.js')
.map(function(file) { return mapPlugin(file, pluckReactPluginName); });
/* Browserify all Tiny-MCE plugins - plugin js vs. any React-based renderPlugin js */
var pluckPluginName = /(.*tinymce\/plugins\/([^\/]+)\/)([^\.]+)\.js$/i;
var tinyPlugins = glob.sync(__dirname + basePluginFolder + '**/plugin.js')
.map(function(file) { return mapPlugin(file, pluckPluginName); });
// var allTinyPlugins = tinyPlugins.slice();
// Array.prototype.push.apply(allTinyPlugins, tinyReactPlugins);
/* Prepare browserify bundles */
var bundles = {
fields: browserify('fields.js', 'FieldTypes'),
home: browserify('views/home.js'),
item: browserify('views/item.js'),
list: browserify('views/list.js')
};
tinyReactPlugins.forEach(function(p) { bundles[p.name] = browserify(p.file); });
router.prebuild = function() {
bundles.fields.build();
bundles.home.build();
bundles.item.build();
bundles.list.build();
};
tinyReactPlugins.forEach(function(p) { router.prebuild[p.name] = bundles[p.name].build(); });
/* Prepare LESS options */
var reactSelectPath = path.join(path.dirname(require.resolve('react-select')), '..');
var lessOptions = {
render: {
modifyVars: {
reactSelectPath: JSON.stringify(reactSelectPath)
}
}
};
/* Configure router */
router.use('/styles', less(__dirname + '../../public/styles', lessOptions));
router.use(express.static(__dirname + '../../public'));
/* TinyMCE plugin Skins */
router.use('/js/lib/tinymce/skins', less(__dirname + '/../public/js/lib/tinymce/skins', lessOptions));
router.use('/js/lib/tinymce/skins/', express.static(__dirname + '/../public/js/lib/tinymce/skins'));
router.use('/styles/elemental', less(__dirname + '/../../node_modules/elemental/less', lessOptions));
router.use('/styles/elemental/', express.static(__dirname + '/../../node_modules/elemental/less'));
router.use('/public/images/', express.static(__dirname + '/../../node_modules/elemental/public/images'));
router.get('/js/fields.js', bundles.fields.serve);
router.get('/js/home.js', bundles.home.serve);
router.get('/js/item.js', bundles.item.serve);
router.get('/js/list.js', bundles.list.serve);
tinyPlugins.forEach(function(p) {
if (p.name !== 'cloudinarybrowser') {
router.get(p.pathRootNoPublic + '/', minify());
router.use(p.pathRootNoPublic + '/' + p.filename + '.min.js', express.static(path.resolve(__dirname + '/' + p.file)));
} else {
//cloudinarybrowser functions as two plugins
router.get(p.pathRootNoPublic + 'images/', minify());
router.use(p.pathRootNoPublic + 'images/' + p.filename + '.min.js', express.static(path.resolve(__dirname + '/' + p.file)));
router.get(p.pathRootNoPublic + 'files/', minify());
router.use(p.pathRootNoPublic + 'files/' + p.filename + '.min.js', express.static(path.resolve(__dirname + '/' + p.file)));
}
});
tinyReactPlugins.forEach(function(p) {
router.get('/js/tiny-mce-plugins/' + p.name + '.js', bundles[p.name].serve);
router.use('/styles/tiny-mce-plugins/' + p.name, less(p.path, lessOptions));
});
router.use('/styles/tiny-mce-plugins/', express.static(__dirname + basePluginFolder));
module.exports = router;
| JavaScript | 0.000001 | @@ -2643,24 +2643,27 @@
e router */%0A
+//
router.use('
@@ -2731,60 +2731,329 @@
));%0A
-router.use(express.static(__dirname + '../../public'
+console.log(__dirname + '../../public/styles');%0Aconsole.info(path.resolve(__dirname + '/../public/styles'));%0Arouter.use('/styles', less(path.resolve(__dirname + '/../public/styles'), lessOptions));%0A// router.use(express.static(__dirname + '../../public'));%0Arouter.use(express.static(path.resolve(__dirname + '/../public')
));%0A
|
7e3b64690d1b7e125f7f25f24c0a3fbe4a4b134b | Update prop type definition for subheader | resources/assets/components/MultiValueFilter/index.js | resources/assets/components/MultiValueFilter/index.js | import React from 'react';
import { map } from 'lodash';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import '../Tags/tags.scss';
class MultiValueFilter extends React.Component {
constructor() {
super();
this.state = {};
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
const type = this.props.options.type;
const values = this.props.options.values;
const options = {
[type]: values,
};
this.setState({ ...options });
}
componentDidUpdate() {
this.props.updateFilters(this.state);
}
shouldComponentUpdate(nextProps, nextState) {
return nextState !== this.state;
}
handleClick(key, activeFilter, type) {
const values = {
active: !activeFilter,
label: this.state[type][key].label,
};
this.setState(previousState => {
const newState = { ...previousState };
newState[type][key] = values;
return newState;
});
}
render() {
return (
<div className="container__block -third">
{this.props.header ? (
<div className="multi-value-filter__header">
<b>{this.props.header}</b> {this.props.subheader}
</div>
) : null}
<ul className="aligned-actions">
{map(Object.values(this.state)[0], (option, key) => (
<li key={key}>
{Object.values(this.state)[0] ? (
<button
className={classnames('tag', { 'is-active': option.active })}
onClick={() =>
this.handleClick(
key,
option.active,
this.props.options.type,
)
}
>
{option.label}
</button>
) : null}
</li>
))}
</ul>
</div>
);
}
}
MultiValueFilter.propTypes = {
options: PropTypes.shape({
type: PropTypes.string,
values: PropTypes.object,
}).isRequired,
updateFilters: PropTypes.func,
header: PropTypes.string,
subheader: PropTypes.string,
};
MultiValueFilter.defaultProps = {
header: null,
subheader: null,
updateFilters: null,
};
export default MultiValueFilter;
| JavaScript | 0 | @@ -2144,22 +2144,59 @@
opTypes.
-string
+arrayOf(%5BPropTypes.string, PropTypes.node%5D)
,%0A%7D;%0A%0AMu
|
07da4db81317130321a8889d943839e433ef06aa | Fix lint suggestions | src/selectors/index.js | src/selectors/index.js | import { createSelector } from 'reselect';
import { joinEvents, transformData, calculateYearRange } from 'd3-bumps-chart';
import { calculateNumYearsToview } from '../util';
const pickEvents = (events, gender, set, yearRange = [-Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]) => {
const transformedEvents = events
.filter(e => e.gender.toLowerCase() === gender.toLowerCase())
.filter(e => e.set === set)
.filter(e => e.year >= yearRange[0] && e.year <= yearRange[1])
.sort((a, b) => a.year - b.year)
.map(event => transformData(event));
return joinEvents(transformedEvents, set, gender);
};
const getEvents = (state, props) =>
state.ui.events;
export const getSet = (state, props) => {
const setMap = {
mays: 'May Bumps',
lents: 'Lent Bumps',
town: 'Town Bumps',
torpids: 'Torpids',
eights: 'Summer Eights',
};
let set = 'Town Bumps';
if (props.params.eventId !== undefined) {
const paramSet = props.params.eventId.toLowerCase();
if (paramSet in setMap) {
set = setMap[paramSet];
}
}
return set;
};
export const getGender = (state, props) => {
const genderMap = {
women: 'Women',
men: 'Men',
};
let gender = 'Women';
if (props.params.genderId !== undefined) {
const paramGender = props.params.genderId.toLowerCase();
if (paramGender in genderMap) {
gender = genderMap[paramGender];
}
}
return gender;
};
export const getSelectedCrews = (state, props) => {
let selectedCrews = new Set();
if (props.params.crewId !== undefined) {
selectedCrews = new Set(props.params.crewId.split(',').map(crew => crew.replace(/_/g, ' ')));
}
return selectedCrews;
};
export const getResults = createSelector(
[getEvents, getSet, getGender],
(events, set, gender) => pickEvents(events, gender, set)
);
export const getClubs = (state, props) => {
let numClubs = 8;
const numYears = calculateNumYearsToview(state.ui.width);
const fullData = getResults(state, props);
const restrictedData = pickEvents(state.ui.events, getGender(state, props), getSet(state, props), [fullData.endYear - numYears, fullData.endYear]);
const rawClubs = restrictedData.crews.map(crew => crew.name.replace(/[0-9]+$/, '').trim());
const uniqueClubs = new Set(restrictedData.crews.map(crew => crew.name.replace(/[0-9]+$/, '').trim()));
const histogram = [...uniqueClubs.values()].map(club => ({ club, count: rawClubs.filter(c => c === club).length }));
const sortedHistogram = histogram.sort((a, b) => b.count - a.count);
if (props.params.set !== 'Town Bumps') {
numClubs = sortedHistogram.length;
}
const topNClubs = sortedHistogram.slice(0, numClubs).map(c => c.club);
return topNClubs.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
};
export const getYear = (state, props) => {
return state.ui.year;
}
| JavaScript | 0.000006 | @@ -74,28 +74,8 @@
Data
-, calculateYearRange
%7D f
@@ -620,27 +620,16 @@
s =
-(
state
-, props)
=%3E
-%0A
sta
@@ -2811,36 +2811,16 @@
r =
-(
state
-, props) =%3E %7B%0A return
+ =%3E
sta
@@ -2831,10 +2831,8 @@
i.year;%0A
-%7D%0A
|
025438c7e305ca060fe61cde93572e711135b167 | Fix semester name | migrations/1469038260014-AddSemesters2017.js | migrations/1469038260014-AddSemesters2017.js | 'use strict'
var db = require('../app/db');
exports.up = function(next) {
db.Semester.create([
{
name: 'סתיו תשע"ו', year: 2017, semester: 1,
startDate: new Date("2016-10-29T00:00:00.000Z"),
endDate: new Date("2017-01-26T00:00:00.000Z"),
examsStart: new Date("2017-01-28T00:00:00.000Z"),
examsEnd: new Date("2017-03-09T00:00:00.000Z")
},
{
name: 'אביב תשע"ו', year: 2017, semester: 2,
startDate: new Date("2017-03-11T00:00:00.000Z"),
endDate: new Date("2017-06-29T00:00:00.000Z"),
examsStart: new Date("2017-07-01T00:00:00.000Z"),
}
], function(err) {
if (err)
throw err;
next();
});
};
exports.down = function(next) {
next();
};
| JavaScript | 0.999889 | @@ -114,15 +114,15 @@
'%D7%A1%D7%AA%D7%99
-%D7%95
+%D7%96
%D7%AA%D7%A9%D7%A2%22
-%D7%95
+%D7%96
', y
@@ -388,9 +388,9 @@
%D7%AA%D7%A9%D7%A2%22
-%D7%95
+%D7%96
',
|
fecc1e9026d90fd68e6fafaf6859ef5644fc7c75 | add ~boxmein to nickometer | modules/module-nickometer.js | modules/module-nickometer.js | /*
Nickometer module for this bot
*/
var nickometer = require('./nickometer');
exports.type = 'command';
exports.listAll = function() {
return ['*'];
};
exports.getHelp = function() {
return {
'*': '`nickometer [nick]` - return how lame your / someone else\'s nickname is'
};
};
exports.listener = function(line, words, respond) {
if (words.length > 1) {
var nick = words[1];
var your = false;
}
else {
var nick = line.nick;
var your = true;
}
var score = nickometer(nick);
if (your) {
return respond('Your nickname gets a lameness score of ' + score + '!');
}
respond('The nickname `' + nick + '` gets a lameness score of ' + score + '!');
};
exports.init = function(config, myconfig, alias) {};
| JavaScript | 0 | @@ -29,16 +29,27 @@
his bot%0A
+ ~boxmein%0A
*/%0Avar n
|
df28fb75392c0dc1127a455e2579a82524e4da67 | remove duplicated track() test | test/track.js | test/track.js | var Mixpanel = require('../lib/mixpanel-node'),
Sinon = require('sinon'),
mock_now_time = new Date(2016, 1, 1).getTime();;
exports.track = {
setUp: function(next) {
this.mixpanel = Mixpanel.init('token');
this.clock = Sinon.useFakeTimers(mock_now_time);
Sinon.stub(this.mixpanel, 'send_request');
next();
},
tearDown: function(next) {
this.mixpanel.send_request.restore();
this.clock.restore();
next();
},
"calls send_request with correct endpoint and data": function(test) {
var event = "test",
props = { key1: 'val1' },
expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
key1: 'val1',
token: 'token'
}
};
this.mixpanel.track(event, props);
test.ok(
this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),
"track didn't call send_request with correct arguments"
);
test.done();
},
"can be called with optional properties": function(test) {
var expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
token: 'token'
}
};
this.mixpanel.track("test");
test.ok(
this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),
"track didn't call send_request with correct arguments"
);
test.done();
},
"can be called with optional callback": function(test) {
var expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
token: 'token'
}
};
this.mixpanel.send_request.callsArgWith(2, undefined);
test.expect(1);
this.mixpanel.track("test", function(e) {
test.equal(e, undefined, "error should be undefined");
test.done();
});
},
"calls `track` endpoint if within last 5 days": function(test) {
var event = 'test',
time = mock_now_time / 1000,
props = { time: time },
expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
token: 'token',
time: time,
mp_lib: 'node'
}
};
this.mixpanel.track(event, props);
test.ok(
this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),
"track didn't call send_request with correct arguments"
);
test.done();
},
"throws error if older than 5 days": function(test) {
var event = 'test',
time = (mock_now_time - 1000 * 60 * 60 * 24 * 6) / 1000,
props = { time: time };
test.throws(this.mixpanel.track.bind(this, event, props));
test.done();
},
"supports Date object for time": function(test) {
var event = 'test',
time = new Date(mock_now_time),
props = { time: time },
expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
token: 'token',
time: time.getTime() / 1000,
mp_lib: 'node'
}
};
this.mixpanel.track(event, props);
test.ok(
this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),
"track didn't call send_request with correct arguments"
);
test.done();
},
"supports unix timestamp for time": function(test) {
var event = 'test',
time = mock_now_time / 1000,
props = { time: time },
expected_endpoint = "/track",
expected_data = {
event: 'test',
properties: {
token: 'token',
time: time,
mp_lib: 'node'
}
};
this.mixpanel.track(event, props);
test.ok(
this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),
"track didn't call send_request with correct arguments"
);
test.done();
},
"throws error if time is not a number or Date": function(test) {
var event = 'test',
props = { time: 'not a number or Date' };
test.throws(this.mixpanel.track.bind(this, event, props));
test.done();
},
"does not require time property": function(test) {
var event = 'test',
props = {};
test.doesNotThrow(this.mixpanel.track.bind(this, event, props));
test.done();
}
};
| JavaScript | 0.000007 | @@ -2165,999 +2165,8 @@
%7D,%0A%0A
- %22calls %60track%60 endpoint if within last 5 days%22: function(test) %7B%0A var event = 'test',%0A time = mock_now_time / 1000,%0A props = %7B time: time %7D,%0A expected_endpoint = %22/track%22,%0A expected_data = %7B%0A event: 'test',%0A properties: %7B%0A token: 'token',%0A time: time,%0A mp_lib: 'node'%0A %7D%0A %7D;%0A%0A this.mixpanel.track(event, props);%0A%0A test.ok(%0A this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data),%0A %22track didn't call send_request with correct arguments%22%0A );%0A test.done();%0A %7D,%0A%0A %22throws error if older than 5 days%22: function(test) %7B%0A var event = 'test',%0A time = (mock_now_time - 1000 * 60 * 60 * 24 * 6) / 1000,%0A props = %7B time: time %7D;%0A%0A test.throws(this.mixpanel.track.bind(this, event, props));%0A test.done();%0A %7D,%0A%0A
@@ -3556,24 +3556,329 @@
();%0A %7D,%0A%0A
+ %22throws error if time property is older than 5 days%22: function(test) %7B%0A var event = 'test',%0A time = (mock_now_time - 1000 * 60 * 60 * 24 * 6) / 1000,%0A props = %7B time: time %7D;%0A%0A test.throws(this.mixpanel.track.bind(this, event, props));%0A test.done();%0A %7D,%0A%0A
%22throws
|
f416b77a1fd12b76eda629dc45cc57c6166f9f94 | add some failing tests that have method encodings present | test/types.js | test/types.js | var types = require('../lib/types')
, assert = require('assert')
, inspect = require('util').inspect
test('v@:'
, [ 'v', [ '@', ':' ] ]
, [ 'void', [ 'pointer', 'pointer' ] ]
)
// test types.map()
//assert.equal(types.map('r^^{__CFData}'), 'pointer')
assert.equal(types.map('^^{__CFData}'), 'pointer')
test('Q40@0:8^{?=Q^@^Q[5Q]}16^@24Q32'
, [ 'Q', [ '@', ':', '^{?=Q^@^Q[5Q]}', '^@', 'Q' ] ]
, [ 'ulonglong', [ 'pointer', 'pointer', 'pointer', 'pointer', 'ulonglong'] ]
)
test('@68@0:8{CGRect={CGPoint=dd}{CGSize=dd}}16Q48Q56c64'
, [ '@', [ '@', ':', '{CGRect={CGPoint=dd}{CGSize=dd}}', 'Q', 'Q', 'c' ] ]
)
function test (type, rtn, ffi) {
//console.log('Input:\t%s', type)
var parsed = types.parse(type)
//console.log('Output:\t'+inspect(parsed, true, 10, true)+'\n')
assert.deepEqual(parsed, rtn)
if (!ffi) return
var f = types.mapArray(parsed)
//console.log('FFI Types:\t'+inspect(f, true, 10, true)+'\n')
assert.deepEqual(f, ffi)
}
| JavaScript | 0 | @@ -200,18 +200,58 @@
s.map()%0A
-//
+assert.equal(types.map('r%5Ev'), 'pointer')%0A
assert.e
|
9f5a7355e31b9ec64016e308edc5e090b1fe949d | fix import-export functional tests - fixed js test | src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/action/export-action.js | src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/action/export-action.js | define([
'jquery',
'underscore',
'./abstract-action',
'orotranslation/js/translator',
'oroui/js/mediator'
], function($, _, AbstractAction, __, mediator) {
'use strict';
var ExportAction;
/**
* Allows to export grid data
*
* @export oro/datagrid/action/export-action
* @class oro.datagrid.action.ExportAction
* @extends oro.datagrid.action.AbstractAction
*/
ExportAction = AbstractAction.extend({
/** @property oro.PageableCollection */
collection: undefined,
/** @property {Boolean} */
isModalBinded: false,
messages: {
success: 'oro.datagrid.export.success.message',
fail: 'oro.datagrid.export.fail.message',
},
/** @property {Object} */
defaultMessages: {
confirm_title: 'Export Confirmation',
confirm_ok: 'Yes',
confirm_cancel: 'Cancel'
},
/**
* {@inheritdoc}
*/
initialize: function(options) {
this.route = 'oro_datagrid_export_action';
this.route_parameters = {
gridName: options.datagrid.name
};
this.collection = options.datagrid.collection;
this.reloadData = false;
this.frontend_handle = 'ajax';
this.on('preExecute', _.bind(this._preExecuteSubscriber, this));
ExportAction.__super__.initialize.apply(this, arguments);
},
/**
* {@inheritdoc}
*/
createLauncher: function(options) {
var launcher = ExportAction.__super__.createLauncher.apply(this, arguments);
// update 'href' attribute for each export type
this.listenTo(launcher, 'expand', function(launcher) {
var fetchData = this.collection.getFetchData();
_.each(launcher.$el.find('.dropdown-menu a'), function(el) {
var $el = $(el);
if (!this.isModalBinded) {
this.createWarningModalForMaxRecords($el, launcher);
}
$el.attr('href', this.getLink(_.extend({format: $el.data('key')}, fetchData)));
}, this);
this.isModalBinded = true;
});
return launcher;
},
/**
* {@inheritdoc}
*/
getActionParameters: function() {
return _.extend({format: this.actionKey}, this.collection.getFetchData());
},
/**
* {@inheritdoc}
*/
_onAjaxError: function(jqXHR) {
mediator.execute('showFlashMessage', 'error', this.messages.fail);
ExportAction.__super__._onAjaxError.apply(this, arguments);
},
createWarningModalForMaxRecords: function($el, launcher) {
var linkData = _.findWhere(launcher.links, {key: $el.data('key')});
var state = this.collection.state || {};
var totalRecords = state.totalRecords || 0;
var self = this;
if (linkData.show_max_export_records_dialog &&
linkData.max_export_records &&
totalRecords >= linkData.max_export_records) {
$el.on('click', function(e) {
e.stopPropagation();
e.preventDefault();
var link = $el;
self.confirmModal = (new self.confirmModalConstructor({
title: __(self.messages.confirm_title),
content: __(
'oro.datagrid.export.max_limit_message',
{max_limit: linkData.max_export_records, total: totalRecords}
),
okText: __(self.messages.confirm_ok),
cancelText: __(self.messages.confirm_cancel),
allowOk: self.allowOk
}));
self.confirmModal.on('ok', function() {
window.location.href = link.attr('href');
self.confirmModal.off();
});
self.confirmModal.open();
});
}
}
});
return ExportAction;
});
| JavaScript | 0 | @@ -1334,86 +1334,8 @@
';%0A%0A
- this.on('preExecute', _.bind(this._preExecuteSubscriber, this));%0A%0A
|
defc1c09ed79f2e9518d8f8385197bb04f083244 | Fix object assign | src/Rules/BibTeX.js | src/Rules/BibTeX.js | /* @flow */
import path from 'path'
import BuildState from '../BuildState'
import File from '../File'
import Rule from '../Rule'
import type { Message } from '../types'
export default class BibTeX extends Rule {
static fileTypes: Set<string> = new Set(['ParsedLaTeXAuxilary'])
static description: string = 'Runs BibTeX to process bibliography files (bib) when need is detected.'
input: ?File
static async appliesToFile (buildState: BuildState, jobName: ?string, file: File): Promise<boolean> {
if (!await super.appliesToFile(buildState, jobName, file)) return false
return !!file.value && !!file.value.bibdata
}
async initialize () {
await this.getResolvedInput('.log-ParsedLaTeXLog')
this.input = await this.getResolvedInput('.aux')
}
async addInputFileActions (file: File): Promise<void> {
if (!this.constructor.commands.has(this.command) || !this.constructor.phases.has(this.phase)) {
return
}
switch (file.type) {
case 'ParsedLaTeXLog':
if (file.value && file.value.messages.some((message: Message) => /run BibTeX/.test(message.text))) {
this.addAction(file)
}
break
case 'ParsedLaTeXAuxilary':
break
default:
await super.addInputFileActions(file)
break
}
}
async preEvaluate () {
if (!this.input) this.actions.delete('run')
}
constructProcessOptions () {
const options: Object = {
cwd: this.rootPath
}
if (this.options.outputDirectory) {
options.env = Object.assign({}, process.env, { BIBINPUTS: ['.', this.options.outputDirectory}].join(path.delimeter) })
}
return options
}
constructCommand () {
return ['bibtex', this.input ? this.input.normalizedFilePath : '']
}
async processOutput (stdout: string, stderr: string): Promise<boolean> {
const databasePattern = /^Database file #\d+: (.*)$/mg
let match
await this.getResolvedOutputs(['.bbl', '.blg'])
while ((match = databasePattern.exec(stdout)) !== null) {
await this.getInput(path.resolve(this.rootPath, match[1]))
if (this.options.outputDirectory) {
await this.getInput(path.resolve(this.rootPath, this.options.outputDirectory, match[1]))
}
}
return true
}
}
| JavaScript | 0.000004 | @@ -1606,17 +1606,16 @@
irectory
-%7D
%5D.join(p
|
6fe5e224bcfd64074a8ea5bca83c2f7d7790b705 | remove require | runParse.js | runParse.js | var request = require('request');
var cp = require('child_process');
var ndjson = require('ndjson');
var spawn = cp.spawn;
var progress = require('request-progress');
var processAllPlayers = require('./processAllPlayers');
var processTeamfights = require('./processTeamfights');
var processCreateParsedData = require('./processCreateParsedData');
var processReduce = require('./processReduce');
var processMetadata = require('./processMetadata');
var processExpand = require('./processExpand');
module.exports = function runParse(match, cb)
{
var url = match.url;
var inStream;
var parseStream;
var bz;
var parser;
var entries = [];
inStream = progress(request(
{
url: url,
encoding: null,
timeout: 30000
})).on('progress', function(state)
{
console.log(JSON.stringify(
{
url: url,
state: state
}));
}).on('response', function(response)
{
if (response.statusCode === 200)
{
//TODO replace domain with something that can handle exceptions with context
parser = spawn("java", ["-jar",
"-Xmx64m",
"java_parser/target/stats-0.1.0.jar"
],
{
//we may want to ignore stderr so the child doesn't stay open
stdio: ['pipe', 'pipe', 'pipe'],
encoding: 'utf8'
});
parseStream = ndjson.parse();
if (url.slice(-3) === "bz2")
{
bz = spawn("bunzip2");
inStream.pipe(bz.stdin);
bz.stdout.pipe(parser.stdin);
}
else
{
inStream.pipe(parser.stdin);
}
parser.stdout.pipe(parseStream);
parser.stderr.on('data', function(data)
{
console.log(data.toString());
});
parseStream.on('data', handleStream);
parseStream.on('end', exit);
parseStream.on('error', exit);
}
else
{
exit(response.statusCode.toString());
}
}).on('error', exit);
function exit(err)
{
if (!err)
{
var message = "time spent on post-processing match ";
console.time(message);
var meta = processMetadata(entries);
var res = processExpand(entries, meta, populate);
var parsed_data = res.parsed_data;
parsed_data.teamfights = processTeamfights(res.tf_data, meta, populate);
var ap = processAllPlayers(res.int_data);
parsed_data.radiant_gold_adv = ap.radiant_gold_adv;
parsed_data.radiant_xp_adv = ap.radiant_xp_adv;
//processMultiKillStreaks();
//processReduce(res.expanded);
console.timeEnd(message);
}
return cb(err, parsed_data);
}
//callback when the JSON stream encounters a JSON object (event)
function handleStream(e)
{
entries.push(e);
}
function populate(e, container)
{
switch (e.type)
{
case 'interval':
//don't need to store interval objects (broken into subtypes)
break;
case 'player_slot':
container.players[e.key].player_slot = e.value;
break;
case 'match_id':
container.match_id = e.value;
break;
case 'chat':
container.chat.push(JSON.parse(JSON.stringify(e)));
break;
case 'CHAT_MESSAGE_TOWER_KILL':
case 'CHAT_MESSAGE_TOWER_DENY':
case 'CHAT_MESSAGE_BARRACKS_KILL':
case 'CHAT_MESSAGE_FIRSTBLOOD':
case 'CHAT_MESSAGE_AEGIS':
case 'CHAT_MESSAGE_AEGIS':
case 'CHAT_MESSAGE_AEGIS_STOLEN':
case 'CHAT_MESSAGE_AEGIS_DENIED':
case 'CHAT_MESSAGE_ROSHAN_KILL':
container.objectives.push(JSON.parse(JSON.stringify(e)));
break;
default:
if (!container.players[e.slot])
{
//couldn't associate with a player, probably attributed to a creep/tower/necro unit
//console.log(e);
return;
}
var t = container.players[e.slot][e.type];
if (typeof t === "undefined")
{
//container.players[0] doesn't have a type for this event
console.log("no field in parsed_data.players for %s", e.type);
return;
}
else if (e.posData)
{
//fill 2d hash with x,y values
var x = e.key[0];
var y = e.key[1];
if (!t[x])
{
t[x] = {};
}
if (!t[x][y])
{
t[x][y] = 0;
}
t[x][y] += 1;
}
else if (e.max)
{
//check if value is greater than what was stored
if (e.value > t.value)
{
container.players[e.slot][e.type] = e;
}
}
else if (t.constructor === Array)
{
//determine whether we want the value only (interval) or the time and key (log)
//either way this creates a new value so e can be mutated later
var arrEntry = (e.interval) ? e.value :
{
time: e.time,
key: e.key
};
t.push(arrEntry);
}
else if (typeof t === "object")
{
//add it to hash of counts
e.value = e.value || 1;
t[e.key] ? t[e.key] += e.value : t[e.key] = e.value;
}
else if (typeof t === "string")
{
//string, used for steam id
container.players[e.slot][e.type] = e.key;
}
else
{
//we must use the full reference since this is a primitive type
//use the value most of the time, but key when stuns since value only holds Integers in Java
//replace the value directly
container.players[e.slot][e.type] = e.value || Number(e.key);
}
break;
}
}
};
| JavaScript | 0.000005 | @@ -276,76 +276,8 @@
');%0A
-var processCreateParsedData = require('./processCreateParsedData');%0A
var
|
be0b3e1393ee260d48c65ecf6467bdb99ec9efa5 | add missing 'module' to function in scoreMatches.js | workers/processMatches/scoreMatches/scoreMatches.js | workers/processMatches/scoreMatches/scoreMatches.js | var Promise = require('bluebird');
var request = require('request');
var tradesController = require('./../../../server/db/dbcontrollers/tradesController');
module.exports = function (knex) {
var module = {};
tradesController = tradesController(knex);
//Decides who was the winner of the match
//-------------------------------------------------
module.scoreMatches = function (providedDate) {
console.log('kicking off match scoring job');
//formulate the date to look for
var today = new Date();
var date = providedDate || new Date(today.getFullYear(), today.getMonth(), today.getDate(), 21);
//get all matches that are active and ending on the provided date
return module.selectCompletingMatches( date )
.then( function (matches) {
return determineWinners(matches);
})
.catch( function ( err ) {
console.error(err);
});
};
//Find all matches where end date is today
module.selectCompletingMatches = function (date) {
console.log('grabbing matches to evaluate');
return knex('matches')
.where('status', 'active')
.then( function(matches) {
return matches.filter(function(match) {
return Date.parse(match.enddate) <= Date.parse(date);
});
});
};
//Determine the winner
module.determineWinners = function (matches) {
return Promise.map(matches, function (match) {
if( match.creator_id === match.challengee ) {
return recordWinner(match.m_id, match.creator_id);
} else {
//get creator's portfolio
return module.getPortfolio(match.creator_id, match.m_id)
.then (function (creatorPortfolio) {
//get challengee's portfolio
return module.getPortfolio(match.challengee, match.m_id)
.then (function (challengeePortfolio) {
//evaluate portfolio values against each other
if( creatorPortfolio.totalValue > challengeePortfolio.totalValue ) {
return module.recordWinner(match.m_id, match.creator_id);
} else if ( challengeePortfolio.totalValue > creatorPortfolio.totalValue ) {
return module.recordWinner(match.m_id, match.challengee);
} else {
//if there's a tie, we will leave winner null
return module.recordWinner(match.m_id, null);
}
});
});
}
});
};
//calls the get portfolio controller and returns the users portfolio
module.getPortfolio = function (userId, matchId) {
return tradesController.getPortfolio(userId, matchId);
};
//updates the matches table with the id of who won
module.recordWinner = function (matchId, userId) {
return knex('matches')
.where('m_id', '=', matchId)
.update({
status: 'complete',
winner: userId
}, '*')
.then(function (match) {
console.log('winner recorded');
return match[0];
});
};
return module;
};
if(require.main === module) {
var knex = require('./../db/index');
module.exports(knex).scoreMatches()
.then(function(){
knex.destroy();
});
}
| JavaScript | 0.000002 | @@ -785,16 +785,23 @@
return
+module.
determin
|
74976ad7bd6d4544cfd38619f2908d5a8b274096 | add animation | src/objects/MapManager.js | src/objects/MapManager.js | import { CursorLength } from '../Constants.js';
class MapManager {
constructor(map, mapLayer) {
this.removedBlock = [];
this.map = map;
this.maxMapLayer = mapLayer;
}
findLayerToDestroy(x, y, lengthX, lengthY) {
let layerIndex = this.maxMapLayer;
for(let index = this.maxMapLayer; index >= 1; index--) {
if( this.map.getTile(x, y, index) === null &&
this.map.getTile(x + lengthX-1, y + lengthY-1, index) === null) {
layerIndex--;
} else {
break;
}
}
return layerIndex;
}
setUpCollisionLayer(colissionLayer) {
colissionLayer.layer.data.forEach(column => {
column.forEach(tile => {
if(tile.properties.layer_index == 1) {
tile.isVisible = true;
} else {
tile.isVisible = false;
}
tile.alpha = 0;
});
});
}
eraseBlock(x, y) {
const lengthY = CursorLength;
const lengthX = CursorLength;
//check the layers associated to the deletion;
let objectsRemoves = []
const layerIndex = this.findLayerToDestroy(x, y, lengthX, lengthY);
for(let xAxis = x; xAxis < x + lengthX; xAxis++) {
for(let yAxis = y; yAxis < y + lengthY; yAxis++) {
let collidedTile = this.map.getTile(xAxis, yAxis, "colissionLayer");
if(collidedTile) {
collidedTile.isVisible = collidedTile.isVisible ? false : true;
}
const tile = this.map.removeTile(xAxis, yAxis, layerIndex);
objectsRemoves.push(tile);
}
}
this.removedBlock.push({tiles: objectsRemoves, layerIndex: layerIndex, x, y});
this.removedBlock.sort(this.sortByLayerIndex);
}
sortByLayerIndex(a, b) {
return a.layerIndex > b.layerIndex;
}
undoBlock(x, y) {
const lengthX = CursorLength;
const lengthY = CursorLength;
const redoElements = this.removedBlock.find(list => list.x === x && list.y === y );
if(redoElements) {
redoElements.tiles.forEach(tile => {
let collidedTile = this.map.getTile(tile.x, tile.y, "colissionLayer");
if(collidedTile) {
collidedTile.isVisible = collidedTile.isVisible ? false : true;
}
this.map.putTile(tile, tile.x, tile.y, redoElements.layerIndex);
});
//remove the element after
const newArray = this.removedBlock.filter(elmt => elmt !== redoElements);
this.removedBlock = newArray.sort(this.sortByLayerIndex);
}
}
}
export default MapManager; | JavaScript | 0.000001 | @@ -42,16 +42,46 @@
s.js';%0A%0A
+const LengthAnimation = 100;%0A%0A
class Ma
@@ -91,16 +91,16 @@
nager %7B%0A
-
%0A const
@@ -1058,16 +1058,43 @@
ves = %5B%5D
+;%0A let indexRemoval = 0;
%0A con
@@ -1450,32 +1450,61 @@
true;%0A %7D%0A
+ const fn = () =%3E %7B%0A
const ti
@@ -1563,16 +1563,18 @@
+
objectsR
@@ -1592,16 +1592,186 @@
(tile);%0A
+ %7D%0A setTimeout(fn, indexRemoval * LengthAnimation);%0A indexRemoval++;%0A if(indexRemoval %3E CursorLength) %7B%0A indexRemoval = 0;%0A %7D%0A
%7D%0A
@@ -2182,24 +2182,63 @@
Elements) %7B%0A
+ let indexRemoval = CursorLength;%0A
redoEl
@@ -2450,32 +2450,61 @@
true;%0A %7D%0A
+ const fn = () =%3E %7B%0A
this.map
@@ -2556,24 +2556,195 @@
ayerIndex);%0A
+ %7D;%0A setTimeout(fn, indexRemoval * LengthAnimation);%0A indexRemoval--;%0A if(indexRemoval %3C 0) %7B%0A indexRemoval = CursorLength;%0A %7D%0A
%7D);%0A
|
2ce2038c01f38826cc35da0e0e70e23c9feb11b8 | use new signup urls | public/javascripts/facebook-app.js | public/javascripts/facebook-app.js | var CobotFb = {
renderPlans: function(){
var $plans = $('#plans');
var space_id = $plans.data('space-id');
var planTemplate = $('#planTemplate').html();
var space_url = "https://www.cobot.me/api/spaces/" + space_id;
var plans_url = "https://" + space_id + ".cobot.me/api/plans";
var plans_req = $.getJSON(plans_url);
var space_req = $.getJSON(space_url);
$.when(space_req)
.fail(function(space_error){console.log('Error getting space', space_error);})
.done(function(space){
// welcome text
if($.trim(space.description).length > 0){
$('#welcome').html(marked(space.description));
}
});
$.when(space_req, plans_req)
.fail(function(){console.log('Error getting plans');})
.done(function(space_resp, plans_resp){
var space = space_resp[0];
var plans = plans_resp[0];
var display_gross = function(){
return space.price_display == "gross";
};
var gross_price = function(price){
var tax_multiplier = (1 + parseFloat(space.tax_rate) / 100);
return (Math.round(tax_multiplier * parseFloat(price)) * 100) / 100.0;
};
var price_to_display_price = function(price){
if(display_gross()){
return gross_price(price);
} else {
return price;
}
};
var has_cycle_costs = function(plan){
return parseFloat(plan.price_per_cycle) > 0;
};
$.each(plans, function(){
this.time_passes = this.time_passes.sort(function(a, b){
return parseFloat(a.price_in_cents) > parseFloat(b.price_in_cents) ? 1 : -1;
});
this.cycle_costs = function(){
return has_cycle_costs(this);
};
this.extra_display_price = function(){
var price = price_to_display_price(this.price_in_cents / 100);
return(price);
};
this.discounts_available = function(){
return this.discounts.lenght > 0;
};
this.html_description = function(){
if($.trim(this.description).length > 0){
return marked(this.description);
}
};
this.display_day_pass_price = price_to_display_price(this.day_pass_price);
this.display_price_per_cycle = price_to_display_price(this.price_per_cycle);
this.url = space.url + '/users/new?plan_id='+ this.id;
var planHtml = Mustache.to_html(planTemplate, this);
$plans.append(planHtml);
if(typeof FB != 'undefined'){
FB.Canvas.setSize();
}
});
});
}
};
$(CobotFb.renderPlans); | JavaScript | 0.000001 | @@ -2358,13 +2358,25 @@
+ '/
-users
+membership_signup
/new
|
2335fbdcfdc6470470d45313d1d67698ed9e245a | stop adding alpacas every time you load the home page | public/js/controllers/home-ctrl.js | public/js/controllers/home-ctrl.js | define(['./index'], function (controllers) {
'use strict';
controllers.controller('homeCtrl', ['$scope', '$rootScope', '$location', 'alpacaService', function ($scope, $rootScope, $location, alpacaService) {
var alpacaMarkers = [];
$scope.alpacas = alpacaService;
$scope.seedAlpacas = function() {
var names = ["Ted", "Chris", "Fred"];
for(var i = 0; i < names.length; i++) {
$scope.alpacas.$add(
{
name: names[i],
lat: 44.89+(i*0.01),
lng: -68.67+(i*0.01)
}
);
}
$scope.placeAlpacas($scope.alpacas);
};
$scope.clearAlpacas = function() {
var markersLength = alpacaMarkers.length;
$scope.alpacas.$remove();
$scope.focusedAlpaca = null;
// remove markers from map
while(markersLength--) {
alpacaMarkers[markersLength].marker.setMap(null);
alpacaMarkers.splice(markersLength, 1);
}
};
$scope.mapOptions = {
center: new google.maps.LatLng(44.89, -68.67),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
disableDoubleClickZoom: false,
draggable: true,
scrollwheel: true,
panControl: true,
streetViewControl: false
};
$scope.placeAlpacas = function(alpacas) {
var keys = alpacas.$getIndex();
for(var i = 0; i < keys.length; i++) {
var alpaca = alpacas[keys[i]],
marker = new google.maps.Marker({
title: alpaca.name,
position: new google.maps.LatLng(alpaca.lat, alpaca.lng),
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
}),
contentString = '<h5>' + alpaca.name + '</h5>',
infowindow = new google.maps.InfoWindow({
content: contentString
});
// focus on corresponding alpaca when marker is clicked
(function (_marker) {
google.maps.event.addListener(_marker, 'click', function() {
$scope.focusAlpaca(_marker.title);
});
})(marker);
alpacaMarkers.push({
marker: marker,
infowindow: infowindow
});
marker.setMap($scope.alpacaMap);
}
};
$scope.mapLoaded = function() {
$scope.seedAlpacas();
$scope.$watch('alpacas', function() {
$scope.placeAlpacas($scope.alpacas);
});
};
$scope.focusAlpaca = function(alpacaName) {
alpacaName = alpacaName.toLowerCase();
var keys = $scope.alpacas.$getIndex();
// focus on corresponding alpaca
for(var i = 0; i < keys.length; i++) {
if($scope.alpacas[keys[i]].name.toLowerCase() === alpacaName) {
$scope.focusedAlpaca = $scope.alpacas[keys[i]];
break;
}
}
// change color of corresponding map marker and open its infowindow
for(var j = 0; j < alpacaMarkers.length; j++) {
if(alpacaMarkers[j].marker.title.toLowerCase() === alpacaName) {
alpacaMarkers[j].marker.setIcon('http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png');
alpacaMarkers[j].infowindow.open($scope.alpacaMap, alpacaMarkers[j].marker);
}
else {
alpacaMarkers[j].marker.setIcon('http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png');
alpacaMarkers[j].infowindow.close();
}
}
};
$scope.isFocusedAlpaca = function(alpaca) {
if($scope.focusedAlpaca) {
return alpaca.name.toLowerCase() === $scope.focusedAlpaca.name.toLowerCase();
}
return false;
};
}]);
}); | JavaScript | 0 | @@ -2772,42 +2772,8 @@
) %7B%0A
- $scope.seedAlpacas();%0A
|
eb72ba94ebfc4444d2f13a4e46e8a53e9cac1e48 | add size to localStorage state | src/singleton/cache.js | src/singleton/cache.js | /* global
global, document, demand, provide, queue, processor, settings, setTimeout, clearTimeout, storage,
DEMAND_ID, FUNCTION_EMPTY, EVENT_POST_REQUEST, EVENT_POST_PROCESS, EVENT_CACHE_HIT, EVENT_CACHE_MISS, EVENT_CACHE_EXCEED, EVENT_CACHE_CLEAR, EVENT_PRE_CACHE, EVENT_PRE_CACHE, EVENT_POST_CACHE, STRING_STRING, NULL, FALSE, TRUE,
validatorIsTypeOf,
functionGetTimestamp, functionEscapeRegex, functionIterate, functionDefer, functionResolveId,
ClassDependency,
singletonEvent
*/
//=require constants.js
//=require validator/isTypeOf.js
//=require function/getTimestamp.js
//=require function/escapeRegex.js
//=require function/iterate.js
//=require function/defer.js
//=require function/resolveId.js
//=require singleton/event.js
var singletonCache = (function(JSON) {
var STORAGE_PREFIX = '[' + DEMAND_ID + ']',
STORAGE_SUFFIX_STATE = '[state]',
STORAGE_SUFFIX_VALUE = '[value]',
regexMatchState = new RegExp('^' + functionEscapeRegex(STORAGE_PREFIX) + '\\[(.+?)\\]' + functionEscapeRegex(STORAGE_SUFFIX_STATE) + '$'),
supportsLocalStorage = (function() { try { return 'localStorage' in global && global.localStorage; } catch(exception) { return FALSE; } }()),
localStorage = supportsLocalStorage ? global.localStorage : NULL,
supportsRemainingSpace = supportsLocalStorage && 'remainingSpace' in localStorage,
storage = {},
cache;
singletonEvent
.on(EVENT_CACHE_MISS, function(dependency) {
functionDefer(function() {
cache.clear.path(dependency.id);
});
})
.on(EVENT_POST_REQUEST, function(dependency) {
if(dependency.source && enabled(dependency)) {
storage[dependency.id] = TRUE;
}
})
.after(EVENT_POST_PROCESS, function(dependency) {
if(storage[dependency.id]) {
functionDefer(function() {
cache.set(dependency);
});
}
});
function enabled(dependency) {
var match;
if(dependency.cache !== NULL) {
return dependency.cache;
}
functionIterate(settings.cache, function(property, value) {
if(dependency.path.indexOf(property) === 0 && (!match || value.weight > match.weight)) {
match = value;
}
});
return match ? match.state : FALSE;
}
function getKey(key) {
return localStorage.getItem(key);
}
function setKey(key, value) {
localStorage[value ? 'setItem' : 'removeItem'](key, value);
}
function getState(key) {
return JSON.parse(getKey(key));
}
function setState(key, state) {
state.access = functionGetTimestamp();
setKey(key, JSON.stringify(state));
}
function emit(event, dependency, state) {
singletonEvent.emit(event, dependency.id, dependency, state);
}
function Cache() {
functionDefer(this.clear.expired.bind(this.clear));
}
Cache.prototype = {
get: (function() {
if(supportsLocalStorage) {
return function get(dependency) {
var id, state;
if(enabled(dependency)) {
id = STORAGE_PREFIX + '[' + dependency.id + ']';
state = getState(id + STORAGE_SUFFIX_STATE);
if(state && state.version === dependency.version && ((!state.expires && !dependency.lifetime) || state.expires > functionGetTimestamp())) {
dependency.source = getKey(id + STORAGE_SUFFIX_VALUE);
functionDefer(function() {
setState(id + STORAGE_SUFFIX_STATE, state);
});
return TRUE;
}
}
};
} else {
return FUNCTION_EMPTY;
}
}()),
resolve: (function() {
if(supportsLocalStorage) {
return function resolve(dependency) {
var self = this;
if(self.get(dependency)) {
emit(EVENT_CACHE_HIT, dependency);
} else {
emit(EVENT_CACHE_MISS, dependency);
}
};
} else {
return function resolve(dependency) {
emit(EVENT_CACHE_MISS, dependency);
};
}
}()),
set: (function() {
if(supportsLocalStorage) {
return function set(dependency) {
var state, id, spaceBefore;
if(enabled(dependency)) {
state = { version: dependency.version, demand: demand.version, expires: dependency.lifetime ? functionGetTimestamp() + dependency.lifetime : dependency.lifetime };
id = STORAGE_PREFIX + '[' + dependency.id + ']';
emit(EVENT_PRE_CACHE, dependency, state);
try {
spaceBefore = supportsRemainingSpace ? localStorage.remainingSpace : NULL;
setKey(id + STORAGE_SUFFIX_VALUE, dependency.source);
setState(id + STORAGE_SUFFIX_STATE, state);
// strict equality check with "===" is required due to spaceBefore might be "0"
if(spaceBefore !== NULL && localStorage.remainingSpace === spaceBefore) {
throw new Error('QUOTA_EXCEEDED_ERR');
}
emit(EVENT_POST_CACHE, dependency, state);
} catch(error) {
emit(EVENT_CACHE_EXCEED, dependency);
}
}
};
} else {
return FUNCTION_EMPTY;
}
}()),
clear: {
path: (function() {
if(supportsLocalStorage) {
return function path(path) {
var id = functionResolveId(path),
key = STORAGE_PREFIX + '[' + id + ']';
if(getKey(key + STORAGE_SUFFIX_STATE)) {
setKey(key + STORAGE_SUFFIX_STATE);
setKey(key + STORAGE_SUFFIX_VALUE);
emit(EVENT_CACHE_CLEAR, ClassDependency.get(id) || new ClassDependency(id, NULL, FALSE));
}
}
} else {
return FUNCTION_EMPTY;
}
}()),
all: (function() {
if(supportsLocalStorage) {
return function all() {
var match;
functionIterate(localStorage, function(property) {
match = property.match(regexMatchState);
match && this.path(match[1]);
}, this);
}
} else {
return FUNCTION_EMPTY;
}
}()),
expired: (function() {
if(supportsLocalStorage) {
return function expired() {
var self = this,
match, state;
functionIterate(localStorage, function(property) {
match = property.match(regexMatchState);
if(match) {
state = getState(STORAGE_PREFIX + '[' + match[1] + ']' + STORAGE_SUFFIX_STATE);
if(state && state.expires > 0 && state.expires <= functionGetTimestamp()) {
self.path(match[1]);
}
}
}, this);
}
} else {
return FUNCTION_EMPTY;
}
}())
}
};
return (cache = new Cache());
}(JSON)); | JavaScript | 0.000001 | @@ -2453,16 +2453,49 @@
tate) %7B%0A
+%09%09state.demand = demand.version;%0A
%09%09state.
@@ -2527,18 +2527,16 @@
tamp();%0A
-%09%09
%0A%09%09setKe
@@ -4030,32 +4030,8 @@
ion,
- demand: demand.version,
exp
@@ -4124,16 +4124,48 @@
lifetime
+, size: dependency.source.length
%7D;%0A%09%09%09%09
|
34a0b0f73a4b8d45688b300e1a8cd5de98f512bc | Make sure constant name is not renamed | c2corg_ui/static/js/constants.js | c2corg_ui/static/js/constants.js | goog.require('app');
goog.provide('app.constants');
/**
* @const
* Constants for the module.
* Access them like app.constants.SCREEN
*/
app.module.constant('constants', app.constants);
app.constants = {
SCREEN : {
SMARTPHONE : 620,
TABLET : 1099,
DEKTOP : 1400
},
STEPS : {
'climbing_outdoor' : 4,
'climbing_indoor' : 4,
'hut' : 4,
'gite' : 4,
'shelter' : 4,
'access' : 4,
'camp_site' : 4,
'local_product' : 4,
'paragliding_takeoff' : 4,
'paragliding_landing' : 4,
'webcam': 4
},
REQUIRED_FIELDS : {
waypoints: ['title' , 'lang', 'waypoint_type', 'elevation', 'longitude', 'latitude'],
routes : ['title' , 'lang', 'activities', 'waypoints'],
outings : ['title' , 'lang', 'date_start', 'routes', 'activities'],
images: ['image_type']
},
documentEditing: {
FORM_PROJ: 'EPSG:4326',
DATA_PROJ: 'EPSG:3857'
}
};
| JavaScript | 0.000573 | @@ -211,21 +211,20 @@
SCREEN
-
: %7B%0A
+
SMAR
@@ -286,17 +286,16 @@
%0A STEPS
-
: %7B%0A
@@ -564,17 +564,16 @@
ELDS
-
: %7B%0A
wayp
@@ -568,16 +568,17 @@
: %7B%0A
+'
waypoint
@@ -578,16 +578,17 @@
aypoints
+'
: %5B'titl
@@ -660,22 +660,24 @@
'%5D,%0A
+'
routes
+'
: %5B'tit
@@ -726,15 +726,17 @@
+'
outings
+'
: %5B
@@ -800,14 +800,16 @@
+'
images
+'
: %5B'
|
220ae58f981fad8050667fe5fcc0a1be6cabbb33 | Update app.js | alpresidente/app.js | alpresidente/app.js | // Code goes here
var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);
function MyController($scope, $http) {
$scope.currentPage = 1;
$scope.pageSize = 20;
$scope.cart = [{
"Name" : "Demo Riga 1",
"Price" : 10
},
{
"Name" : "Demo Riga 2",
"Price" : 5
}];
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.cart.length; i++){
var product = $scope.cart[i];
total += (product.Price);
}
return total;
}
$scope.addItem = function() {
console.log('test');
}
$http.get("entity.json")
.then(function(response) {
$scope.entity = response.data;
});
$scope.pageChangeHandler = function(num) {
};
}
function OtherController($scope) {
$scope.pageChangeHandler = function(num) {
};
}
myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
| JavaScript | 0.000002 | @@ -556,16 +556,17 @@
tal;%0A%7D%0A%0A
+
$scope.a
@@ -586,37 +586,106 @@
tion
+
() %7B%0A
-%09console.log('test');%0A%7D
+%0A $scope.cart.push(%7B%0A Name: 'DEMO',%0A name: 0%0A %7D);%0A %7D;
%0A%0A $
|
a9dc1d71658718579ee0541b5dfe5d12e2480262 | Refactor using es6 syntax | server/migrations/20170622145849-create-user.js | server/migrations/20170622145849-create-user.js | module.exports = {
up(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
| JavaScript | 0 | @@ -591,32 +591,36 @@
n(queryInterface
+ /*
, Sequelize) %7B%0A
@@ -606,32 +606,35 @@
e /* , Sequelize
+ */
) %7B%0A return q
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.