commit
stringlengths 40
40
| subject
stringlengths 1
1.49k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| new_contents
stringlengths 1
29.8k
| old_contents
stringlengths 0
9.9k
| lang
stringclasses 3
values | proba
float64 0
1
|
---|---|---|---|---|---|---|---|
91ac5fed5244ec328d1a47e95f244b839f9a74ae | extract logic into separate method | spec/js/test-color-splash-playground.js | spec/js/test-color-splash-playground.js | describe('CSPlayground', function() {
var $playgroundElement;
var playground;
beforeEach(function() {
$playgroundElement = $(document.createElement('table'));
});
describe('.initialize(4)', function() {
// given
var colors = [ 'red', 'blue', 'green' ];
var size = 4;
beforeEach(function() {
playground = new CSPlayground($playgroundElement, colors);
// when
playground.initialize(size);
});
it('should create ' + (size * size) + ' cells', function() {
// then
var expectedCells = (size * size);
var cells = $('td', $playgroundElement);
expect(cells.length).toEqual(expectedCells);
});
it('should add a color to each cell', function() {
// then
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var color = cell.attr('data-color');
expect(color).not.toBe(null);
});
});
it('should add the color of start-cell (0,3) to no other cell', function() {
var startCell = getCellByPosition($playgroundElement, 0, 3);
var startCellColor = startCell.attr('data-color');
expect(startCellColor).not.toBe(null);
// then
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == '0' && yIndex == '3') {
return true; // continue;
}
var color = cell.attr('data-color');
expect(color).not.toBe(startCellColor);
});
});
it('cells (0,2) and (1,3) should have different color', function() {
fail('not yet implemented');
});
});
});
function getCellByPosition($playgroundElement, x, y) {
var expectedCell = null;
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == x && yIndex == y) {
expectedCell = cell;
return false; // break the loop
}
});
return expectedCell;
} | describe('CSPlayground', function() {
var $playgroundElement;
var playground;
beforeEach(function() {
$playgroundElement = $(document.createElement('table'));
});
describe('.initialize(4)', function() {
// given
var colors = [ 'red', 'blue', 'green' ];
var size = 4;
beforeEach(function() {
playground = new CSPlayground($playgroundElement, colors);
// when
playground.initialize(size);
});
it('should create ' + (size * size) + ' cells', function() {
// then
var expectedCells = (size * size);
var cells = $('td', $playgroundElement);
expect(cells.length).toEqual(expectedCells);
});
it('should add a color to each cell', function() {
// then
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var color = cell.attr('data-color');
expect(color).not.toBe(null);
});
});
it('should add the color of start-cell (0,3) to no other cell', function() {
var startCellColor = null;
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == '0' && yIndex == '3') {
startCellColor = cell.attr('data-color');
return false; // break the loop
}
});
expect(startCellColor).not.toBe(null);
// then
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == '0' && yIndex == '3') {
return true; // continue;
}
var color = cell.attr('data-color');
expect(color).not.toBe(startCellColor);
});
});
it('cells (0,2) and (1,3) should have different color', function() {
fail('not yet implemented');
});
});
}); | JavaScript | 0.999899 |
e15be8c0811a8a80808df6b3a053a748e4ed284b | add desc | Algorithms/JS/linkedList/addTwoNumbers.js | Algorithms/JS/linkedList/addTwoNumbers.js | // You are given two linked lists representing two non-negative numbers.
// The digits are stored in reverse order and each of their nodes contain a single digit.
// Add the two numbers and return it as a linked list.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
| addTwoNumbers.js
| JavaScript | 0.000001 |
e7d933646c63735fb7871023c18af3facc8a2ce9 | add desc | Algorithms/JS/strings/longestSubstring.js | Algorithms/JS/strings/longestSubstring.js | // Given a string, find the length of the longest substring without repeating characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
| longestSubstring.js
| JavaScript | 0.000001 |
55b7cd5be3e7485eb2d01d7b8f7e1cffe8587b42 | Remove dead code | core/actions/slackPreviewRelease.js | core/actions/slackPreviewRelease.js | 'use strict';
const { waterfall, mapSeries } = require('async');
const previewReleaseTemplate = require('./slack-views/slack-preview-release');
module.exports = function createPreviewRelease(getReleasePreview, slack, repos) {
return (cb) => {
const reposBranches = repos.map(repo => ({ repo }));
waterfall([
(next) => getReleasePreview(reposBranches, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, next)
], cb);
};
function notifyPreviewInSlack(reposInfo, cb) {
const msg = previewReleaseTemplate(reposInfo);
slack.send(msg, cb);
}
};
| 'use strict';
const { waterfall, mapSeries } = require('async');
const previewReleaseTemplate = require('./slack-views/slack-preview-release');
module.exports = function createPreviewRelease(getReleasePreview, slack, repos) {
return (cb) => {
const reposBranches = repos.map(repo => ({ repo }));
waterfall([
(next) => getReleasePreview(reposBranches, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, next)
], cb);
};
function getPRsFromChangesForEachRepo(repos, cb) {
mapSeries(repos, (repo, nextRepo) => {
pullRequestsFromChanges({ repo }, (err, prIds) => {
if (err) return nextRepo(null, { repo, failReason: err.message });
nextRepo(null, { repo, prIds });
});
}, cb);
}
function getDeployInfoForEachRepo(reposInfo, cb) {
mapSeries(reposInfo, (repoInfo, nextRepo) => {
if (repoInfo.prIds.length === 0) {
return nextRepo(null, Object.assign({ failReason: 'NO_CHANGES' }, repoInfo));
}
deployInfoFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, deployInfo) => {
let failReason;
if (err) {
failReason = err.message;
}
else if (deployInfo.deployNotes) {
failReason = 'DEPLOY_NOTES';
}
else if (deployInfo.services.length === 0) {
failReason = 'NO_SERVICES';
}
nextRepo(null, Object.assign({ failReason, services: deployInfo.services }, repoInfo));
});
}, cb);
}
function getIssuesToReleaseForEachRepo(reposInfo, cb) {
mapSeries(reposInfo, (repoInfo, nextRepo) => {
issuesFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, issues) => {
if (err) return nextRepo(null, Object.assign({ failReason: err.message }, repoInfo));
nextRepo(null, Object.assign({ issues }, repoInfo));
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, cb) {
const msg = previewReleaseTemplate(reposInfo);
slack.send(msg, cb);
}
};
| JavaScript | 0.001497 |
90d1711ca365c040e249c9297ede437492d4495b | fix some supid typos | src/rules/no-unsupported-elements-use-aria.js | src/rules/no-unsupported-elements-use-aria.js | import {
DOM
, aria
, hasProp
} from '../util'
export default [{
msg: 'This element does not support ARIA roles, states and properties.'
, AX: 'AX_ARIA_12'
, test (tagName, props) {
const reserved = DOM[tagName].reserved || false
const prop = hasProp(props, Object.keys(aria).concat('role'))
return !reserved || !prop
}
}]
export const description = `
Certain reserved DOM elements do not support ARIA roles, states and properties.
This is often because they are not visible, for example \`meta\`, \`html\`, \`script\`,
\`style\`. This rule enforces that these DOM elements do not contain the \`role\` and/or
\`aria-*\` props.
`
export const fail = [{
when: 'the element should not be given any ARIA attributes'
, render: React => <meta charset="UTF-8" aria-hidden="false" />
}]
export const pass = [{
when: 'the reserver element is not given an illegal prop'
, render: React => <meta charset="UTF-8" />
}, {
when: 'an illegal props is given to a non-reserved elemeent'
, render: React => <div aria-hidden={true} />
}]
| import {
DOM
, aria
} from '../util'
export default [{
msg: 'This element does not support ARIA roles, states and properties.'
, AX: 'AX_ARIA_12'
, test (tagName, props) {
const reserved = DOM[tagName].reserved || false
const hasProp = hasProp(props, Object.keys(aria).concat('role'))
return !reserved || !hasProp
}
}]
export const description = `
Certain reserved DOM elements do not support ARIA roles, states and properties.
This is often because they are not visible, for example \`meta\`, \`html\`, \`script\`,
\`style\`. This rule enforces that these DOM elements do not contain the \`role\` and/or
\`aria-*\` props.
`
const fail = [{
when: 'the element should not be given any ARIA attributes'
, render: React => <meta charset="UTF-8" aria-hidden="false" />
}]
const pass = [{
when: 'the reserver element is not given an illegal prop'
, render: React => <meta charset="UTF-8" />
}, {
when: 'an illegal props is given to a non-reserved elemeent'
, render: React => <div aria-hidden={true} />
}]
| JavaScript | 0.999999 |
1b83980e263668f31347d2f658161069bf9989d8 | update function to es6/7 | Challenges/DashInsert.js | Challenges/DashInsert.js | const assert = require('assert');
const DashInsert = str => {
const arr = str.split('');
for (let i = 0; i < str.length - 1; i += 1) {
if (arr[i] % 2 !== 0 && arr[i + 1] % 2 !== 0) {
arr[i] = `${arr[i]}-`;
}
}
// console.log('123');
console.log(str);
return arr.join('');
};
const in1 = '1234567'; // input
const expect1 = '1234567'; // output
const test1 = DashInsert(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log('works');
| const assert = require('assert');
function DashInsert(str) {
const arr = str.split('');
for (let i = 0; i < str.length - 1; i += 1) {
if (arr[i] % 2 !== 0 && arr[i + 1] % 2 !== 0) {
arr[i] = `${arr[i]}-`;
}
}
// console.log('123');
console.log(str);
return arr.join('');
}
const in1 = '1234567'; // input
const expect1 = '1234567'; // output
const test1 = DashInsert(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log('works');
| JavaScript | 0 |
9a9957df4ec7a5dca7d2bfa21c9e2013db99d691 | make sure parseError is receiving an Error | src/modules/support/parseError.js | src/modules/support/parseError.js | function parseStack(e) {
var concatStack = e.stack.replace(/\n +/g, '|');
if (e.stack.includes(e.message)) {
return concatStack;
}
return e.message + '|' + concatStack;
}
function isError(e) {
if (e.stack) {return parseStack(e);}
if (e.message) {return e.message;}
return String(e);
}
export default function parseError(e) {
if (e instanceof Error) {return isError(e);}
return String(e);
}
| function parseStack(e) {
var concatStack = e.stack.replace(/\n +/g, '|');
if (e.stack.includes(e.message)) {
return concatStack;
}
return e.message + '|' + concatStack;
}
export default function parseError(e) {
if (e.stack) {return parseStack(e);}
if (e.message) {return e.message;}
return String(e);
}
| JavaScript | 0.000067 |
d28f7b13bdc449a8b2ab39e8aa41a5be0c63a692 | Set currentPath in init lifecycle hook. | addon/components/search-help-modal/component.js | addon/components/search-help-modal/component.js | import Ember from 'ember';
import layout from './template';
/**
* Modal that provides examples and explanation of Lucene Search syntax
*
* ```handlebars
* {{search-help-modal
* isOpen=isOpen
* }}
* ```
* @class search-help-modal
*/
export default Ember.Component.extend({
layout,
isOpen: false,
init() {
this._super(...arguments);
this.set('currentPath', `${window.location.origin}${window.location.pathname}`);
},
actions: {
close() {
this.set('isOpen', false);
},
toggleHelpModal() {
this.toggleProperty('isOpen');
},
}
});
| import Ember from 'ember';
import layout from './template';
/**
* Modal that provides examples and explanation of Lucene Search syntax
*
* ```handlebars
* {{search-help-modal
* isOpen=isOpen
* }}
* ```
* @class search-help-modal
*/
export default Ember.Component.extend({
layout,
isOpen: false,
currentPath: Ember.computed(function() {
return window.location.origin + window.location.pathname;
}),
actions: {
close() {
this.set('isOpen', false);
},
toggleHelpModal() {
this.toggleProperty('isOpen');
},
}
});
| JavaScript | 0 |
dd6e67fa527d013d88d9b8fbc29c7b5d023fae7d | fix done callback invocations | test/helpers.js | test/helpers.js | "use strict";
const expect = require("expect.js");
exports.successResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
expect(res.headers["content-type"]).to.be("text/javascript; charset=utf-8");
expect(res.headers["cache-control"]).to.be("no-cache");
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.not.be.empty();
});
res.on("end", () => {
if (close) close();
cb();
});
};
};
exports.failureResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.contain("Cannot require");
});
res.on("end", () => {
if (close) close();
cb();
});
};
};
| "use strict";
const expect = require("expect.js");
exports.successResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
expect(res.headers["content-type"]).to.be("text/javascript; charset=utf-8");
expect(res.headers["cache-control"]).to.be("no-cache");
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.not.be.empty();
});
res.on("close", cb);
res.on("end", () => {
if (close) close(cb);
else cb();
});
};
};
exports.failureResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.contain("Cannot require");
});
res.on("close", cb);
res.on("end", () => {
if (close) close(cb);
else cb();
});
};
};
| JavaScript | 0.000003 |
9c666da48463b6b7745ad8882d85a40921976d7c | fix practice server crash | practiceserver.js | practiceserver.js | var port = 1340;
// Downgrade from root
if (process.getuid() === 0)
require('fs').stat(__filename, function(err, stats) {
if (err)
return console.log(err);
process.setuid(stats.uid);
});
console.log("Started practice server");
var io = require('socket.io').listen(port);
var games = {},
gameBySocketId = {},
gamesPerProcess = 32;
io.sockets.on('connection',function(socket){
socket.on('subscribe',function(type,gameId){
var g = games[gameId];
if(typeof g == 'undefined'){
if(gamesPerProcess > 0){
games[gameId] = new PGame(gameId,socket);
gamesPerProcess--;
}else{
socket.emit('error','No more practice rooms available');
return;
}
}else{
if(type == 'controller'){
if(g.c0 === null){
g.connect(0,socket);
}else if(g.c1 === null){
g.connect(1,socket);
}else{
socket.emit('error','This room already has two controllers');
}
}else{
socket.emit('error','This id is taken');
}
}
});
socket.on('disconnect',function(){
var g = gameBySocketId[socket.id];
if(g.host.id == socket.id){
if(g.c0){
g.c0.emit('disconnect');
delete gameBySocketId[g.c0.id];
}
if(g.c1){
g.c1.emit('disconnect');
delete gameBySocketId[g.c1.id];
}
delete gameBySocketId[g.host.id];
delete games[g.gid];
}else if(g.c0.id == socket.id){
g.c0 = null;
}else if(g.c1.id == socket.id){
g.c1 = null;
}
});
});
PGame = function(id,host){
this.host = host;
this.gid = id;
this.c0 = null;
this.c1 = null;
gameBySocketId[host.id] = this;
};
PGame.prototype.connect = function(id,socket){
if(id == 0){
this.c0 = socket;
}
if(id == 1){
this.c1 = socket;
}
(function(pgame){
socket.on('paddle',function(point){
pgame.host.emit('paddle',id,point);
});
socket.on('dbl',function(){
pgame.host.emit('dlb',id);
});
})(this);
socket.emit('connected',id);
gameBySocketId[socket.id] = this;
};
| var port = 1340;
// Downgrade from root
if (process.getuid() === 0)
require('fs').stat(__filename, function(err, stats) {
if (err)
return console.log(err);
process.setuid(stats.uid);
});
console.log("Started practice server");
var io = require('socket.io').listen(port);
var games = {},
gameBySocketId = {},
gamesPerProcess = 32;
io.sockets.on('connection',function(socket){
socket.on('subscribe',function(type,gameId){
var g = games[gameId];
if(typeof g == 'undefined'){
if(gamesPerProcess > 0){
games[gameId] = new PGame(gameId,socket);
gamesPerProcess--;
}else{
socket.emit('error','No more practice rooms available');
return;
}
}else{
if(type == 'controller'){
if(g.c0 === null){
g.connect(0,socket);
}else if(g.c1 === null){
g.connect(1,socket);
}else{
socket.emit('error','This room already has two controllers');
}
}else{
socket.emit('error','This id is taken');
}
}
});
socket.on('disconnect',function(){
var g = gameBySocketId[socket.id];
if(g.host.id == socket.id){
g.c0.emit('disconnect');
g.c1.emit('disconnect');
delete gameBySocketId[g.c0.id];
delete gameBySocketId[g.c1.id];
delete gameBySocketId[g.host.id];
delete games[g.gid];
}else if(g.c0.id == socket.id){
g.c0 = null;
}else if(g.c1.id == socket.id){
g.c1 = null;
}
});
});
PGame = function(id,host){
this.host = host;
this.gid = id;
this.c0 = null;
this.c1 = null;
gameBySocketId[host.id] = this;
};
PGame.prototype.connect = function(id,socket){
if(id == 0){
this.c0 = socket;
}
if(id == 1){
this.c1 = socket;
}
(function(pgame){
socket.on('paddle',function(point){
pgame.host.emit('paddle',id,point);
});
socket.on('dbl',function(){
pgame.host.emit('dlb',id);
});
})(this);
socket.emit('connected',id);
gameBySocketId[socket.id] = this;
};
| JavaScript | 0 |
1ef8cac00a044ead6075ff3c7d271a881ee0b092 | Add js | app/assets/javascripts/trip.js | app/assets/javascripts/trip.js | $(document).ready(function(){
$('#expense_form').hide();
$('#trip_form').on('click', 'input[type=submit]', function(event){
$('#trip_form').hide();
$('#expense_form').show();
});
// $('input#expense_location_id').geocomplete();
$('form').on('click','.add_fields', function(event){
event.preventDefault();
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
});
// $('#add-location').click(function(e){
// e.preventDefault();
// addLegForm();
// })
$('body').on('click','.location',function(e){
// $(this).geocomplete();
});
$('#expenses_grid').on('click','#add-expense', function(e){
e.preventDefault();
console.log("clicked");
$('#new_expense').show();
$('#add-expense').hide();
});
$('#expenses_grid').on('submit','#new_expense',function(e){
e.preventDefault();
$.ajax ({
url: $(e.target).attr('action'),
type: 'POST',
data: $(e.target).serialize()
}).done(function(data){
$('#expenses_grid').append(data);
clearInputs();
});
});
});
clearInputs = function(){
$("input[name='expense[usd_cost]'").val("");
$("input[name='expense[location_id]'").val("");
$("input[name='expense[cost]'").val("");
$("input[name='expense[category_id]'").val("");
};
| $(document).ready(function(){
$('#expense_form').hide();
$('#trip_form').on('click', 'input[type=submit]', function(event){
$('#trip_form').hide();
$('#expense_form').show();
});
$('input#expense_location_id').geocomplete();
$('form').on('click','.add_fields', function(event){
event.preventDefault();
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
});
// $('#add-location').click(function(e){
// e.preventDefault();
// addLegForm();
// })
$('body').on('click','.location',function(e){
$(this).geocomplete();
});
$('#expenses_grid').on('click','#add-expense',function(e){
console.log("clicked");
$('#new_expense').show();
$('#add-expense').hide();
});
$('#expenses_grid').on('submit','#new_expense',function(e){
e.preventDefault();
$.ajax ({
url: $(e.target).attr('action'),
type: 'POST',
data: $(e.target).serialize()
}).done(function(data){
$('#expenses_grid').append(data);
clearInputs();
});
});
});
clearInputs = function(){
$("input[name='expense[usd_cost]'").val("");
$("input[name='expense[location_id]'").val("");
$("input[name='expense[cost]'").val("");
$("input[name='expense[category_id]'").val("");
};
| JavaScript | 0.000022 |
c537305921b6c17e71a236243d0f703d6cd9f4da | Fix typo | test/library.js | test/library.js |
var expect = require('expect.js')
, ffi = require('../')
, Library = ffi.Library
describe('Library', function () {
afterEach(gc)
it('should be a function', function () {
expect(Library).to.be.a('function')
})
it('should work with the `new` operator', function () {
var l = new Library()
expect(l).to.be.an('object')
})
it('should accept `null` as a first argument', function () {
var thisFuncs = new Library(null, {
'printf': [ 'void', [ 'string' ] ]
})
var test = thisFuncs.printf instanceof Function
expect(test).to.be(true)
})
it('should accept a lib name as a first argument', function () {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ] ]
})
var test = libm.ceil instanceof Function
expect(test).to.be(true)
expect(libm.ceil(1.1)).to.equal(2)
})
it('should throw when an invalid function name is used', function () {
expect(function () {
new Library(null, {
'doesnotexist__': [ 'void', [] ]
})
}).to.throwException()
})
it('should work with "strcpy" and a 128 length string', function () {
var ZEROS_128 = Array(128 + 1).join('0')
var buf = new ffi.Pointer(256)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_128)
expect(buf.getCString()).to.equal(ZEROS_128)
})
it('should work with "strcpy" and a 2k length string', function () {
var ZEROS_2K = Array(2e3 + 1).join('0')
var buf = new ffi.Pointer(4096)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_2K)
expect(buf.getCString()).to.equal(ZEROS_2K)
})
if (process.platform == 'win32') {
// TODO: Add GetTimeOfDay() with FILETIME struct test
} else {
it('should work with "gettimeofday" and a "timeval" Struct pointer', function () {
var timeval = new ffi.Struct([
['long','tv_sec']
, ['long','tv_usec']
])
var l = new Library(null, {
'gettimeofday': ['int', ['pointer', 'pointer']]
})
var tv = new timeval()
l.gettimeofday(tv.ref(), null)
expect(tv.tv_sec == Math.floor(Date.now() / 1000)).to.be(true)
})
}
describe('async', function () {
it('should call a function asynchronously', function (done) {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ], { async: true } ]
})
libm.ceil(1.1).on('success', function (res) {
expect(res).to.equal(2)
done()
})
})
})
})
|
var expect = require('expect.js')
, ffi = require('../')
, Library = ffi.Library
describe('Library', function () {
afterEach(gc)
it('should be a function', function () {
expect(Library).to.be.a('function')
})
it('should work with the `new` operator', function () {
var l = new Library()
expect(l).to.be.an('object')
})
it('should accept `null` as a first argument', function () {
var thisFuncs = new Library(null, {
'printf': [ 'void', [ 'string' ] ]
})
var test = thisFuncs.printf instanceof Function
expect(test).to.be(true)
})
it('should accept a lib name as a first argument', function () {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ] ]
})
var test = libm.ceil instanceof Function
expect(test).to.be(true)
expect(libm.ceil(1.1)).to.equal(2)
})
it('should throw when an invalid function name is used', function () {
expect(function () {
new Library(null, {
'doesnotexist__': [ 'void', [] ]
})
}).to.throwException()
})
it('should work with "strcpy" and a 128 length string', function () {
var ZEROS_128 = Array(128 + 1).join('0')
var buf = new ffi.Pointer(256)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_128)
expect(buf.getCString()).to.equal(ZEROS_128)
})
it('should work with "strcpy" and a 2k length string', function () {
var ZEROS_2K = Array(2e3 + 1).join('0')
var buf = new ffi.Pointer(4096)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_2K)
expect(buf.getCString()).to.equal(ZEROS_2K)
})
if (process.plaform == 'win32') {
// TODO: Add GetTimeOfDay() with FILETIME struct test
} else {
it('should work with "gettimeofday" and a "timeval" Struct pointer', function () {
var timeval = new ffi.Struct([
['long','tv_sec']
, ['long','tv_usec']
])
var l = new Library(null, {
'gettimeofday': ['int', ['pointer', 'pointer']]
})
var tv = new timeval()
l.gettimeofday(tv.ref(), null)
expect(tv.tv_sec == Math.floor(Date.now() / 1000)).to.be(true)
})
}
describe('async', function () {
it('should call a function asynchronously', function (done) {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ], { async: true } ]
})
libm.ceil(1.1).on('success', function (res) {
expect(res).to.equal(2)
done()
})
})
})
})
| JavaScript | 0.999999 |
6a3bc5559ed2ba290ec34c8c690bf67847836be3 | Add pageCount to instance via usePagination hook | src/hooks/usePagination.js | src/hooks/usePagination.js | import { useMemo, useLayoutEffect } from 'react'
import PropTypes from 'prop-types'
//
import { addActions, actions } from '../actions'
import { defaultState } from './useTableState'
defaultState.pageSize = 10
defaultState.pageIndex = 0
addActions({
pageChange: '__pageChange__',
})
const propTypes = {
// General
manualPagination: PropTypes.bool,
}
export const usePagination = props => {
PropTypes.checkPropTypes(propTypes, props, 'property', 'usePagination')
const {
rows,
manualPagination,
disablePageResetOnDataChange,
debug,
state: [
{
pageSize,
pageIndex,
pageCount: userPageCount,
filters,
groupBy,
sortBy,
},
setState,
],
} = props
const pageOptions = useMemo(
() => [...new Array(userPageCount)].map((d, i) => i),
[userPageCount]
)
const rowDep = disablePageResetOnDataChange ? null : rows
useLayoutEffect(() => {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}, [setState, rowDep, filters, groupBy, sortBy])
const { pages, pageCount } = useMemo(() => {
if (manualPagination) {
return {
pages: [rows],
pageCount: userPageCount,
}
}
if (debug) console.info('getPages')
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
const pageCount = pages.length
return {
pages,
pageCount,
pageOptions,
}
}, [manualPagination, debug, rows, pageOptions, userPageCount, pageSize])
const page = manualPagination ? rows : pages[pageIndex] || []
const canPreviousPage = pageIndex > 0
const canNextPage = pageIndex < pageCount - 1
const gotoPage = pageIndex => {
if (debug) console.info('gotoPage')
return setState(old => {
if (pageIndex < 0 || pageIndex > pageCount - 1) {
return old
}
return {
...old,
pageIndex,
}
}, actions.pageChange)
}
const previousPage = () => {
return gotoPage(pageIndex - 1)
}
const nextPage = () => {
return gotoPage(pageIndex + 1)
}
const setPageSize = pageSize => {
setState(old => {
const topRowIndex = old.pageSize * old.pageIndex
const pageIndex = Math.floor(topRowIndex / pageSize)
return {
...old,
pageIndex,
pageSize,
}
}, actions.setPageSize)
}
return {
...props,
pages,
pageOptions,
pageCount,
page,
canPreviousPage,
canNextPage,
gotoPage,
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
}
| import { useMemo, useLayoutEffect } from 'react'
import PropTypes from 'prop-types'
//
import { addActions, actions } from '../actions'
import { defaultState } from './useTableState'
defaultState.pageSize = 10
defaultState.pageIndex = 0
addActions({
pageChange: '__pageChange__',
})
const propTypes = {
// General
manualPagination: PropTypes.bool,
}
export const usePagination = props => {
PropTypes.checkPropTypes(propTypes, props, 'property', 'usePagination')
const {
rows,
manualPagination,
disablePageResetOnDataChange,
debug,
state: [
{
pageSize,
pageIndex,
pageCount: userPageCount,
filters,
groupBy,
sortBy,
},
setState,
],
} = props
const pageOptions = useMemo(
() => [...new Array(userPageCount)].map((d, i) => i),
[userPageCount]
)
const rowDep = disablePageResetOnDataChange ? null : rows
useLayoutEffect(() => {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}, [setState, rowDep, filters, groupBy, sortBy])
const { pages, pageCount } = useMemo(() => {
if (manualPagination) {
return {
pages: [rows],
pageCount: userPageCount,
}
}
if (debug) console.info('getPages')
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
const pageCount = pages.length
return {
pages,
pageCount,
pageOptions,
}
}, [manualPagination, debug, rows, pageOptions, userPageCount, pageSize])
const page = manualPagination ? rows : pages[pageIndex] || []
const canPreviousPage = pageIndex > 0
const canNextPage = pageIndex < pageCount - 1
const gotoPage = pageIndex => {
if (debug) console.info('gotoPage')
return setState(old => {
if (pageIndex < 0 || pageIndex > pageCount - 1) {
return old
}
return {
...old,
pageIndex,
}
}, actions.pageChange)
}
const previousPage = () => {
return gotoPage(pageIndex - 1)
}
const nextPage = () => {
return gotoPage(pageIndex + 1)
}
const setPageSize = pageSize => {
setState(old => {
const topRowIndex = old.pageSize * old.pageIndex
const pageIndex = Math.floor(topRowIndex / pageSize)
return {
...old,
pageIndex,
pageSize,
}
}, actions.setPageSize)
}
return {
...props,
pages,
pageOptions,
page,
canPreviousPage,
canNextPage,
gotoPage,
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
}
| JavaScript | 0 |
65fc3b2ffc6440db110ed097e827918538a50b61 | debug fetcher | src/node_modules/fetcher/index.js | src/node_modules/fetcher/index.js | var collections = require('collections');
var debug = require('debug')("craftodex:ui:fetcher")
module.exports = function fetcher (route, callback) {
var collection = collections[route.collection];
var Model = collection.Model;
debug(Model)
var model = new Model({
'@id': route.id
});
if (callback) {
model.fetch({
success: function (model, response, options) {
return callback(null, model);
},
error: function (model, response, options) {
return callback(response);
},
});
} else {
model.fetch();
}
return model;
}
| var collections = require('collections');
module.exports = function fetcher (route, callback) {
var collection = collections[route.collection];
var Model = collection.Model;
var model = new Model({
'@id': route.id
});
if (callback) {
model.fetch({
success: function (model, response, options) {
return callback(null, model);
},
error: function (model, response, options) {
return callback(response);
},
});
} else {
model.fetch();
}
return model;
}
| JavaScript | 0.000001 |
e6fcab08e699baa8fd2d9480c66e4ea85bd33447 | fix remove of global matchq; | functions/match/match.js | functions/match/match.js | var events = require("events");
var async = require("async");
var _ = require("lodash");
var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var ShGame = require(global.gBaseDir + "/src/shgame.js");
var match = exports;
match.desc = "match players to the desired game and start them in it";
match.functions = {
add: {desc: "add caller to the game matcher", params: {name: {dtype: "string"}}, security: []},
remove: {desc: "remove caller from the game matcher", params: {name: {dtype: "string"}}, security: []},
counts: {desc: "list the match counts for all games", params: {}, security: []},
list: {desc: "list the match players for all games", params: {}, security: []}
};
// SWD: just init a global game queue for now
//if (_.isUndefined(global.matchq)) {
// global.matchq = {};
// global.matchq.tictactoe = {};
//}
var gMatchq = {};
gMatchq.tictactoe = {};
var gInfo = {};
gInfo.tictactoe = {minPlayers: 2, maxPlayers: 2};
match.add = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
if (_.isUndefined(gMatchq[name])) {
cb(1, sh.error("bad_game", "unknown game", {name: name}));
}
if (!_.isUndefined(gMatchq[name][uid])) {
cb(1, sh.error("match_added", "player is already being matched", {uid: uid, name: name}));
return;
}
var keys = Object.keys(gMatchq[name]);
if (keys.length + 1 >= gInfo[name].maxPlayers) {
req.params.cmd = "game.create"; // change the command, req.param.name is already set
req.params.players = keys.slice(0, gInfo[name].maxPlayers);
req.params.players.push(uid); // add the current user
sh.call("game.create", req, res, function (error, data) {
if (error) {
cb(error, data);
return;
}
var matchInfo = {};
matchInfo.gameId = data.data.gameId;
_.each(req.params.players, function (playerId) {
delete gMatchq[name][playerId];
matchInfo[playerId] = {};
});
_.each(req.params.players, function (playerId) {
global.socket.notifyUser(playerId, sh.event("event.match.made", matchInfo));
});
cb(0, sh.event("event.match", matchInfo));
return;
});
}
// just add the user
var ts = new Date().getTime();
var playerInfo = {uid: uid, posted: ts};
gMatchq[name][uid] = playerInfo;
cb(0, sh.event("event.match.add", playerInfo));
};
match.remove = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
delete gMatchq[name][uid];
cb(0, sh.event("event.match.remove"));
};
match.counts = function (req, res, cb) {
var counts = {};
_.forOwn(gMatchq, function (gameq, idx) {
counts[idx] = Object.keys(gameq).length;
});
cb(0, sh.event("event.match.counts", counts));
};
match.list = function (req, res, cb) {
cb(0, sh.event("event.match.list", gMatchq));
}; | var events = require("events");
var async = require("async");
var _ = require("lodash");
var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var ShGame = require(global.gBaseDir + "/src/shgame.js");
var match = exports;
match.desc = "match players to the desired game and start them in it";
match.functions = {
add: {desc: "add caller to the game matcher", params: {name: {dtype: "string"}}, security: []},
remove: {desc: "remove caller from the game matcher", params: {name: {dtype: "string"}}, security: []},
counts: {desc: "list the match counts for all games", params: {}, security: []},
list: {desc: "list the match players for all games", params: {}, security: []}
};
// SWD: just init a global game queue for now
//if (_.isUndefined(global.matchq)) {
// global.matchq = {};
// global.matchq.tictactoe = {};
//}
var matchq = {};
matchq.tictactoe = {};
var info = {};
info.tictactoe = {minPlayers: 2, maxPlayers: 2};
match.add = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
if (_.isUndefined(global.matchq[name])) {
cb(1, sh.error("bad_game", "unknown game", {name: name}));
}
if (!_.isUndefined(global.matchq[name][uid])) {
cb(1, sh.error("match_added", "player is already being matched", {uid: uid, name: name}));
return;
}
var keys = Object.keys(global.matchq[name]);
if (keys.length + 1 >= info[name].maxPlayers) {
req.params.cmd = "game.create"; // change the command, req.param.name is already set
req.params.players = keys.slice(0, info[name].maxPlayers);
req.params.players.push(uid); // add the current user
sh.call("game.create", req, res, function (error, data) {
if (error) {
cb(error, data);
return;
}
var matchInfo = {};
matchInfo.gameId = data.data.gameId;
_.each(req.params.players, function (playerId) {
delete global.matchq[name][playerId];
matchInfo[playerId] = {};
});
_.each(req.params.players, function (playerId) {
global.socket.notifyUser(playerId, sh.event("event.match.made", matchInfo));
});
cb(0, sh.event("event.match", matchInfo));
return;
});
}
// just add the user
var ts = new Date().getTime();
var playerInfo = {uid: uid, posted: ts};
global.matchq[name][uid] = playerInfo;
cb(0, sh.event("event.match.add", playerInfo));
};
match.remove = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
delete global.matchq[name][uid];
cb(0, sh.event("event.match.remove"));
};
match.counts = function (req, res, cb) {
var counts = {};
_.forOwn(global.matchq, function (gameq, idx) {
counts[idx] = Object.keys(gameq).length;
});
cb(0, sh.event("event.match.counts", counts));
};
match.list = function (req, res, cb) {
cb(0, sh.event("event.match.list", global.matchq));
}; | JavaScript | 0 |
adb336ce92bed67f1aae6047974fb1632bdb11c0 | Display notifications when creating a new database | app/modules/databases/views.js | app/modules/databases/views.js | define([
"app",
"api"
],
function(app, FauxtonAPI) {
var Views = {};
Views.Item = FauxtonAPI.View.extend({
template: "templates/databases/item",
tagName: "tr",
serialize: function() {
return {
database: this.model
};
}
});
Views.List = FauxtonAPI.View.extend({
dbLimit: 10,
template: "templates/databases/list",
events: {
"click button.all": "selectAll",
"submit form.database-search": "switchDatabase"
},
initialize: function(options) {
this.collection.on("add", this.render, this);
},
serialize: function() {
return {
databases: this.collection
};
},
switchDatabase: function(event) {
event.preventDefault();
var dbname = this.$el.find("input.search-query").val();
if (dbname) {
// TODO: switch to using a model, or Databases.databaseUrl()
// Neither of which are in scope right now
// var db = new Database.Model({id: dbname});
var url = ["/database/", dbname, "/_all_docs?limit=10"].join('');
FauxtonAPI.navigate(url);
}
},
beforeRender: function() {
this.collection.each(function(database) {
this.insertView("table.databases tbody", new Views.Item({
model: database
}));
}, this);
},
afterRender: function() {
var dbLimit = this.dbLimit;
var ajaxReq;
this.$el.find("input.search-query").typeahead({
source: function(query, process) {
var url = [
app.host,
"/_all_dbs?startkey=%22",
query,
"%22&endkey=%22",
query,
"\u9999%22&limit=",
dbLimit
].join('');
if (ajaxReq) ajaxReq.abort();
ajaxReq = $.ajax({
url: url,
dataType: 'json',
success: function(data) {
process(data);
}
});
}
});
},
selectAll: function(evt){
$("input:checkbox").attr('checked', !$(evt.target).hasClass('active'));
}
});
Views.Sidebar = FauxtonAPI.View.extend({
template: "templates/databases/sidebar",
events: {
"click a#new": "newDatabase",
"click a#owned": "showMine",
"click a#shared": "showShared"
},
newDatabase: function() {
// TODO: use a modal here instead of the prompt
var name = prompt('Name of database', 'newdatabase');
var db = new this.collection.model({
id: encodeURIComponent(name),
name: name
});
var notification = FauxtonAPI.addNotification({msg: "Creating database."});
db.save().done(function() {
notification = FauxtonAPI.addNotification({
msg: "Database created successfully",
type: "success",
clear: true
});
var route = "#/database/" + name + "/_all_docs?limit=100";
app.router.navigate(route, { trigger: true });
}
).error(function(xhr) {
var responseText = JSON.parse(xhr.responseText).reason;
notification = FauxtonAPI.addNotification({
msg: "Create database failed: " + responseText,
type: "error",
clear: true
});
}
);
},
showMine: function(){
console.log('will show users databases and hide shared');
},
showShared: function(){
console.log('will show shared databases and hide the users');
alert('Support for shared databases coming soon');
}
});
return Views;
});
| define([
"app",
"api"
],
function(app, FauxtonAPI) {
var Views = {};
Views.Item = FauxtonAPI.View.extend({
template: "templates/databases/item",
tagName: "tr",
serialize: function() {
return {
database: this.model
};
}
});
Views.List = FauxtonAPI.View.extend({
dbLimit: 10,
template: "templates/databases/list",
events: {
"click button.all": "selectAll",
"submit form.database-search": "switchDatabase"
},
initialize: function(options) {
this.collection.on("add", this.render, this);
},
serialize: function() {
return {
databases: this.collection
};
},
switchDatabase: function(event) {
event.preventDefault();
var dbname = this.$el.find("input.search-query").val();
if (dbname) {
// TODO: switch to using a model, or Databases.databaseUrl()
// Neither of which are in scope right now
// var db = new Database.Model({id: dbname});
var url = ["/database/", dbname, "/_all_docs?limit=10"].join('');
FauxtonAPI.navigate(url);
}
},
beforeRender: function() {
this.collection.each(function(database) {
this.insertView("table.databases tbody", new Views.Item({
model: database
}));
}, this);
},
afterRender: function() {
var dbLimit = this.dbLimit;
var ajaxReq;
this.$el.find("input.search-query").typeahead({
source: function(query, process) {
var url = [
app.host,
"/_all_dbs?startkey=%22",
query,
"%22&endkey=%22",
query,
"\u9999%22&limit=",
dbLimit
].join('');
if (ajaxReq) ajaxReq.abort();
ajaxReq = $.ajax({
url: url,
dataType: 'json',
success: function(data) {
process(data);
}
});
}
});
},
selectAll: function(evt){
$("input:checkbox").attr('checked', !$(evt.target).hasClass('active'));
}
});
Views.Sidebar = FauxtonAPI.View.extend({
template: "templates/databases/sidebar",
events: {
"click a#new": "newDatabase",
"click a#owned": "showMine",
"click a#shared": "showShared"
},
newDatabase: function() {
// TODO: use a modal here instead of the prompt
var name = prompt('Name of database', 'newdatabase');
var db = new this.collection.model({
id: encodeURIComponent(name),
name: name
});
db.save().done(function() {
var route = "#/database/" + name + "/_all_docs?limit=100";
app.router.navigate(route, { trigger: true });
}
);
},
showMine: function(){
console.log('will show users databases and hide shared');
},
showShared: function(){
console.log('will show shared databases and hide the users');
alert('Support for shared databases coming soon');
}
});
return Views;
});
| JavaScript | 0.996626 |
17ed9829d5042340f67eeca7b8231a08fa35f941 | Modify reducer for function purity | app/reducers/editEventModal.js | app/reducers/editEventModal.js | 'use strict';
import { TOGGLE_EVENT_MODAL } from '../actions/index';
export default function eventEditingModalState(state = false, action) {
switch (action.type) {
case TOGGLE_EVENT_MODAL:
console.log(`Action ${action.type} executed with empty payload!`);
state = !state;
default:
return state;
}
};
| 'use strict';
import { TOGGLE_EVENT_MODAL } from '../actions/index';
export default function eventEditingModal(state = false, action) {
switch (action.type) {
case TOGGLE_EVENT_MODAL:
console.log(`Action ${action.type} executed with empty payload!`);
state = !state;
default:
return state;
}
};
| JavaScript | 0.000014 |
552857d00f5101824709575a812b159b0798eb60 | remove left over code | phobos/source/package.js | phobos/source/package.js | enyo.depends(
"Phobos.js",
"AutoComplete.js",
"FindPopup.js",
"ProjectCtrl.js",
"AceScroller.js",
"AceWrapper.js"
);
| enyo.depends(
"Phobos.js",
"AutoComplete.js",
"FindPopup.js",
"ProjectCtrl.js",
"EditorSettings.js",
"AceScroller.js",
"AceWrapper.js"
);
| JavaScript | 0.000001 |
34dc80d91cdc2c996654aaf721a56d40d5e6422d | Add logging | app/serviceworkers/sw-cache.js | app/serviceworkers/sw-cache.js | var CURRENT_VERSION = 'v2';
var CACHE_URLS = {
'https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects?bustcache=true': 2
};
function cacheOpen (event, response) {
return function (cache) {
cache
.put(event.request, response.clone())
.then(function () {
console.info('successfully cached', event.request.url, response);
})
.catch(function (err) {
console.error('cache error', err);
});
return response;
}
}
function fetchSuccess (event) {
return function (response) {
console.info('fetch success', event.request.url);
return caches
.open(CURRENT_VERSION)
.then(cacheOpen(event, response));
}
}
function noCache (event) {
return function () {
console.info('no cache', event.request.url);
return fetch(event.request)
.then(fetchSuccess(event));
}
}
function checkCacheResponse (response) {
if (!response) {
console.info('no cache response');
throw new Error();
}
// console.info('cache response', response);
return response;
}
this.addEventListener('fetch', function (event) {
var cacheType = CACHE_URLS[event.request.url];
if (!cacheType) return;
// console.info('fetch', event.request.url);
if (cacheType === 1) {
event.respondWith(
caches
.match(event.request)
.then(checkCacheResponse)
.catch(noCache(event))
.catch(function noCacheFail () {
console.error('no cache fail');
})
);
} else {
var bustRequest = new Request('https://api.cosmicjs.com/v1/blog-cb/objects');
fetch(bustRequest).then(fetchSuccess({
request: bustRequest
}));
}
});
this.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CURRENT_VERSION) {
return caches.delete(key);
}
}));
})
);
});
| var CURRENT_VERSION = 'v2';
var CACHE_URLS = {
'https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects?bustcache=true': 2
};
function cacheOpen (event, response) {
return function (cache) {
cache
.put(event.request, response.clone())
.then(function () {
console.info('successfully cached');
})
.catch(function (err) {
console.error('cache error', err);
});
return response;
}
}
function fetchSuccess (event) {
return function (response) {
console.info('fetch success');
return caches
.open(CURRENT_VERSION)
.then(cacheOpen(event, response));
}
}
function noCache (event) {
return function () {
console.info('no cache', event.request.url);
return fetch(event.request)
.then(fetchSuccess(event));
}
}
function checkCacheResponse (response) {
if (!response) {
console.info('no cache response');
throw new Error();
}
// console.info('cache response', response);
return response;
}
this.addEventListener('fetch', function (event) {
var cacheType = CACHE_URLS[event.request.url];
if (!cacheType) return;
// console.info('fetch', event.request.url);
if (cacheType === 1) {
event.respondWith(
caches
.match(event.request)
.then(checkCacheResponse)
.catch(noCache(event))
.catch(function noCacheFail () {
console.error('no cache fail');
})
);
} else {
var bustRequest = new Request('https://api.cosmicjs.com/v1/blog-cb/objects');
fetch(bustRequest).then(fetchSuccess({
request: bustRequest
}));
}
});
this.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CURRENT_VERSION) {
return caches.delete(key);
}
}));
})
);
});
| JavaScript | 0.000002 |
6414a91b594e04474ad4074425ff1e9a03ad8ddf | add uses in misc | public/js/Data.js | public/js/Data.js |
var data = angular.module('data',[]);
data.factory("HopForm",function() {
return {
query: function() {
return [
{
name:'Pellet',
utilization: 1
},{
name:'Whole Leaf',
utilization: 0.9
},{
name:'Plug',
utilization: 0.92
}];
}
};
});
data.factory("HopUse",function() {
return {
query: function() {
return [
{
name:'Boil',
utilization: 1
},{
name:'First Wort',
utilization: 1.1
},{
name:'Dry Hop',
utilization: 0
},{
name:'Aroma',
utilization: 0.5
},{
name:'Mash',
utilization: 0.2
}
];
}
};
});
data.factory("FermentableUses",function() {
return {
defaultValue: 'Mash',
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].name ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{
name:'Mash',
mash: true
},{
name:'Recirculating',
mash: true
},{
name:'Boil',
mash: false
},{
name:'Fermentation',
mash: false
}
];
}
};
});
data.factory("MiscType",function() {
return {
query: function() {
return ['Fining',
'Water Agent',
'Spice',
'Other',
'Herb',
'Flavor'];
}
};
});
data.factory("MiscUse",function() {
return {
query: function() {
return ['Boil',
'Mash',
'Licor',
'Primary',
'Secondary'];
}
};
});
data.factory('PitchRate', function() {
return {
query: function() {
return [
{value:0.35, name:'MFG Recomendado 0.35 (Ale, levadura fresca)'},
{value:0.5, name:'MFG Recommendado+ 0.5 (Ale, levadura fresca)'},
{value:0.75 , name:'Pro Brewer 0.75 (Ale)'},
{value:1.0, name:'Pro Brewer 1.0 (Ale, Alta densidad)'},
{value:1.25, name:'Pro Brewer 1.25 (Ale, or Alta densidad)'},
{value:1.5, name:'Pro Brewer 1.5 (Lager)'},
{value:1.75, name:'Pro Brewer 1.75 (Lager)'},
{value:2.0, name:'Pro Brewer 2.0 (Lager alta densidad)'}
];
}
};
});
data.factory('State', function() {
return {
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].value ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{value:'wish', name:'Deseo'},
{value:'draft', name:'Borrador'},
{value:'ready', name:'Lista'},
{value:'running', name:'En Curso'},
{value:'finished', name:'Finalizada'},
{value:'archived', name:'Archivada'}
];
}
};
});
|
var data = angular.module('data',[]);
data.factory("HopForm",function() {
return {
query: function() {
return [
{
name:'Pellet',
utilization: 1
},{
name:'Whole Leaf',
utilization: 0.9
},{
name:'Plug',
utilization: 0.92
}];
}
};
});
data.factory("HopUse",function() {
return {
query: function() {
return [
{
name:'Boil',
utilization: 1
},{
name:'First Wort',
utilization: 1.1
},{
name:'Dry Hop',
utilization: 0
},{
name:'Aroma',
utilization: 0.5
},{
name:'Mash',
utilization: 0.2
}
];
}
};
});
data.factory("FermentableUses",function() {
return {
defaultValue: 'Mash',
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].name ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{
name:'Mash',
mash: true
},{
name:'Recirculating',
mash: true
},{
name:'Boil',
mash: false
},{
name:'Fermentation',
mash: false
}
];
}
};
});
data.factory("MiscType",function() {
return {
query: function() {
return ['Fining',
'Water Agent',
'Spice',
'Other',
'Herb',
'Flavor'];
}
};
});
data.factory("MiscUse",function() {
return {
query: function() {
return ['Boil',
'Mash',
'Secondary'];
}
};
});
data.factory('PitchRate', function() {
return {
query: function() {
return [
{value:0.35, name:'MFG Recomendado 0.35 (Ale, levadura fresca)'},
{value:0.5, name:'MFG Recommendado+ 0.5 (Ale, levadura fresca)'},
{value:0.75 , name:'Pro Brewer 0.75 (Ale)'},
{value:1.0, name:'Pro Brewer 1.0 (Ale, Alta densidad)'},
{value:1.25, name:'Pro Brewer 1.25 (Ale, or Alta densidad)'},
{value:1.5, name:'Pro Brewer 1.5 (Lager)'},
{value:1.75, name:'Pro Brewer 1.75 (Lager)'},
{value:2.0, name:'Pro Brewer 2.0 (Lager alta densidad)'}
];
}
};
});
data.factory('State', function() {
return {
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].value ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{value:'wish', name:'Deseo'},
{value:'draft', name:'Borrador'},
{value:'ready', name:'Lista'},
{value:'running', name:'En Curso'},
{value:'finished', name:'Finalizada'},
{value:'archived', name:'Archivada'}
];
}
};
});
| JavaScript | 0 |
7b78a9d1173b96bcc0e9bf7acb97ef077509cf2f | Switch from false property to eql for IE 8 & lower | polyfills/Array/prototype/fill/tests.js | polyfills/Array/prototype/fill/tests.js | it('exists', function () {
expect(Array.prototype).to.have.property('fill');
});
it('has correct instance', function () {
expect(Array.prototype.fill).to.be.a(Function);
});
it('has correct name', function () {
function nameOf(fn) {
return Function.prototype.toString.call(fn).match(/function\s*([^\s]*)\(/)[1];
}
expect(nameOf(Array.prototype.fill)).to.be('fill');
});
it('has correct argument length', function () {
expect(Array.prototype.fill.length).to.be(1);
});
it('is not enumerable', function () {
expect(Array.prototype.propertyIsEnumerable('fill')).to.eql(false);
});
it('fills whole array when using only one argument', function () {
expect([1, 2, 3].fill(0)).to.eql([0, 0, 0]);
});
it('starts filling from the start index given by second argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 3)).to.eql([1, 2, 3, 0, 0, 0]);
});
it('can use a negative start index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, -2)).to.eql([1, 2, 3, 4, 0, 0]);
});
it('stops filling at the end index given by third argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 0, 2)).to.eql([0, 0, 3, 4, 5, 6]);
});
it('can use a negative end index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 1, -2)).to.eql([1, 0, 0, 0, 5, 6]);
});
it('does not fill if start index is larger than array', function () {
expect([1, 2, 3].fill(0, 5)).to.eql([1, 2, 3]);
});
it('does fill if start index is not a number', function () {
expect([1, 2, 3].fill(0, NaN)).to.eql([0, 0, 0]);
expect([1, 2, 3].fill(1, '')).to.eql([1, 1, 1]);
expect([1, 2, 3].fill(2, {})).to.eql([2, 2, 2]);
});
it('does not fill if end index is not a number', function () {
expect([1, 2, 3].fill(0, 0, NaN)).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(1, 0, '')).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(2, 0, {})).to.eql([1, 2, 3]);
});
it('works on array-like objects', function () {
expect([].fill.call({ length: 3 }, 4)).to.eql({0: 4, 1: 4, 2: 4, length: 3});
});
| it('exists', function () {
expect(Array.prototype).to.have.property('fill');
});
it('has correct instance', function () {
expect(Array.prototype.fill).to.be.a(Function);
});
it('has correct name', function () {
function nameOf(fn) {
return Function.prototype.toString.call(fn).match(/function\s*([^\s]*)\(/)[1];
}
expect(nameOf(Array.prototype.fill)).to.be('fill');
});
it('has correct argument length', function () {
expect(Array.prototype.fill.length).to.be(1);
});
it('is not enumerable', function () {
expect(Array.prototype.propertyIsEnumerable('fill')).to.be.false;
});
it('fills whole array when using only one argument', function () {
expect([1, 2, 3].fill(0)).to.eql([0, 0, 0]);
});
it('starts filling from the start index given by second argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 3)).to.eql([1, 2, 3, 0, 0, 0]);
});
it('can use a negative start index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, -2)).to.eql([1, 2, 3, 4, 0, 0]);
});
it('stops filling at the end index given by third argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 0, 2)).to.eql([0, 0, 3, 4, 5, 6]);
});
it('can use a negative end index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 1, -2)).to.eql([1, 0, 0, 0, 5, 6]);
});
it('does not fill if start index is larger than array', function () {
expect([1, 2, 3].fill(0, 5)).to.eql([1, 2, 3]);
});
it('does fill if start index is not a number', function () {
expect([1, 2, 3].fill(0, NaN)).to.eql([0, 0, 0]);
expect([1, 2, 3].fill(1, '')).to.eql([1, 1, 1]);
expect([1, 2, 3].fill(2, {})).to.eql([2, 2, 2]);
});
it('does not fill if end index is not a number', function () {
expect([1, 2, 3].fill(0, 0, NaN)).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(1, 0, '')).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(2, 0, {})).to.eql([1, 2, 3]);
});
it('works on array-like objects', function () {
expect([].fill.call({ length: 3 }, 4)).to.eql({0: 4, 1: 4, 2: 4, length: 3});
});
| JavaScript | 0 |
a9641a03a7c0c11ab48d174ace527aa58a177ed9 | support language tables | scraper.js | scraper.js | var request = require('request'),
cheerio = require('cheerio'),
dateFormat = require('dateformat');
var Menu = {
date: dateFormat(new Date(), 'yyyy-mm-dd, hh:MM:ss TT'),
dining_halls: {
atwater: {
breakfast: null,
lunch: null
},
proctor: {
breakfast: null,
lunch: null,
dinner: null
},
ross: {
breakfast: null,
lunch: null,
dinner: null
},
language_tables: {
lunch: null
}
}
}
function requestMenu(callback) {
var menuURL = 'https://menus.middlebury.edu';
request({
method: 'GET',
url: menuURL
}, callback);
}
function parseMenu(err, res, body) {
if (err || res.statusCode !== 200) throw err;
var $ = cheerio.load(body),
diningNodes = {
atwater: null,
proctor: null,
ross: null
language_tables: null
},
parseMeal = function(location, meal, $node) {
var itemsArr = $node.find('.views-field-body').text().trim().split('\n');
Menu.diningHalls[location][meal] = itemsArr;
};
// Separate Atwater, Proctor, Ross
$('div.view-content h3').each(function(i, elem) {
var $this = $(elem);
switch ($this.text()) {
case 'Atwater':
diningNodes.atwater = $this.next();
break;
case 'Proctor':
diningNodes.proctor = $this.next();
break;
case 'Ross':
diningNodes.ross = $this.next();
break;
case 'Language Tables':
diningNodes.language_tables = $this.next();
break;
}
});
// Separate meals
for (var node in diningNodes) {
$(diningNodes[node]).find('td').each(function(i, elem) {
var $this = $(this);
switch ($this.find('span.views-field-field-meal').text().trim()) {
case 'Breakfast':
parseMeal(node, 'breakfast', $this);
break;
case 'Lunch':
parseMeal(node, 'lunch', $this);
break;
case 'Dinner':
parseMeal(node, 'dinner', $this);
break;
}
});
};
}
function scrapeMenu() {
requestMenu(parseMenu);
return Menu;
}
exports.scrapeMenu = scrapeMenu; | var request = require('request'),
cheerio = require('cheerio'),
dateFormat = require('dateformat');
var Menu = {
date: dateFormat(new Date(), 'yyyy-mm-dd, hh:MM:ss TT'),
diningHalls: {
atwater: {
breakfast: null,
lunch: null
},
proctor: {
breakfast: null,
lunch: null,
dinner: null
},
ross: {
breakfast: null,
lunch: null,
dinner: null
}
}
}
function requestMenu(callback) {
var menuURL = 'https://menus.middlebury.edu';
request({
method: 'GET',
url: menuURL
}, callback);
}
function parseMenu(err, res, body) {
if (err || res.statusCode !== 200) throw err;
var $ = cheerio.load(body),
diningNodes = {
atwater: null,
proctor: null,
ross: null
},
parseMeal = function(location, meal, $node) {
var itemsArr = $node.find('.views-field-body').text().trim().split('\n');
Menu.diningHalls[location][meal] = itemsArr;
};
// Separate Atwater, Proctor, Ross
$('div.view-content h3').each(function(i, elem) {
var $this = $(elem);
switch ($this.text()) {
case 'Atwater':
diningNodes.atwater = $this.next();
break;
case 'Proctor':
diningNodes.proctor = $this.next();
break;
case 'Ross':
diningNodes.ross = $this.next();
break;
}
});
// Separate meals
for (var node in diningNodes) {
$(diningNodes[node]).find('td').each(function(i, elem) {
var $this = $(this);
switch ($this.find('span.views-field-field-meal').text().trim()) {
case 'Breakfast':
parseMeal(node, 'breakfast', $this);
break;
case 'Lunch':
parseMeal(node, 'lunch', $this);
break;
case 'Dinner':
parseMeal(node, 'dinner', $this);
break;
}
});
};
// return {
// 'date': date,
// 'atwater': diningHalls.atwater || [noInfoMessage],
// 'proctor': diningHalls.proctor || [noInfoMessage],
// 'ross': diningHalls.ross || [noInfoMessage],
// };
}
function scrapeMenu() {
requestMenu(parseMenu);
return Menu;
}
exports.scrapeMenu = scrapeMenu; | JavaScript | 0 |
6378f2926622488449c839ce9de38916b4fbfb8d | Add LICENSE in the javascript source | src/pre.js | src/pre.js | /*
Copyright (c) 2012 Chris Pettitt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function() {
dig = {};
| (function() {
dig = {};
| JavaScript | 0.000001 |
c9311a54bcb12cc88096681fb5eaff60223c6b22 | Fix incorrect merge introduced in a9fa4fc. (Validations weren't running in Responses#new) | Resources/ui/common/responses/ResponsesNewView.js | Resources/ui/common/responses/ResponsesNewView.js | //All the questoin in a survey
function ResponsesNewView(surveyID) {
var _ = require('lib/underscore')._;
var Question = require('models/question');
var Survey = require('models/survey');
var Response = require('models/response');
var QuestionView = require('ui/common/questions/QuestionView');
var ResponseViewHelper = require('ui/common/responses/ResponseViewHelper');
var responseViewHelper = new ResponseViewHelper;
var self = Ti.UI.createView({
layout : 'vertical'
})
var scrollableView = Ti.UI.createScrollableView({
showPagingControl : true
});
self.add(scrollableView);
var survey = Survey.findOneById(surveyID);
var questions = survey.firstLevelQuestions();
var allQuestionViews = Ti.UI.createView();
var saveButton = Ti.UI.createButton({
title : 'Save',
width : '48%'
});
var completeButton = Ti.UI.createButton({
title : 'Complete',
width : '48%'
});
responseViewHelper.paginate(questions, allQuestionViews, scrollableView, [saveButton, completeButton]);
var getCurrentLocation = function() {
var location = {};
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.info("Error getting location");
return;
}
location.longitude = e.coords.longitude;
location.latitude = e.coords.latitude;
Ti.API.info("longitude = " + e.coords.longitude);
Ti.API.info("latitude = " + e.coords.latitude);
});
return location;
};
var validateAndSaveAnswers = function(e, status) {
var questionViews = responseViewHelper.getQuestionViews(allQuestionViews);
var answersData = _(questionViews).map(function(fields, questionID) {
Ti.API.info("questionid:" + questionID);
Ti.API.info("content:" + fields['valueField'].getValue());
return {
'question_id' : questionID,
'content' : fields.valueField.getValue()
}
});
var responseLocation = getCurrentLocation();
responseErrors = Response.validate(answersData, status);
if (!_.isEmpty(responseErrors)) {
responseViewHelper.displayErrors(responseErrors, questionViews);
alert("There were some errors in the response.");
} else {
Response.createRecord(surveyID, status, answersData);
self.fireEvent('ResponsesNewView:savedResponse');
}
};
completeButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "complete");
});
saveButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "incomplete");
});
return self;
}
module.exports = ResponsesNewView;
| //All the questoin in a survey
function ResponsesNewView(surveyID) {
var _ = require('lib/underscore')._;
var Question = require('models/question');
var Survey = require('models/survey');
var Response = require('models/response');
var QuestionView = require('ui/common/questions/QuestionView');
var ResponseViewHelper = require('ui/common/responses/ResponseViewHelper');
var responseViewHelper = new ResponseViewHelper;
var self = Ti.UI.createView({
layout : 'vertical'
})
var scrollableView = Ti.UI.createScrollableView({
showPagingControl : true
});
self.add(scrollableView);
var survey = Survey.findOneById(surveyID);
var questions = survey.firstLevelQuestions();
var allQuestionViews = Ti.UI.createView();
var saveButton = Ti.UI.createButton({
title : 'Save',
width : '48%'
});
var completeButton = Ti.UI.createButton({
title : 'Complete',
width : '48%'
});
responseViewHelper.paginate(questions, allQuestionViews, scrollableView, [saveButton, completeButton]);
var getCurrentLocation = function() {
var location = {};
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.info("Error getting location");
return;
}
location.longitude = e.coords.longitude;
location.latitude = e.coords.latitude;
Ti.API.info("longitude = " + e.coords.longitude);
Ti.API.info("latitude = " + e.coords.latitude);
});
return location;
};
var validateAndSaveAnswers = function(e, status) {
var questionViews = responseViewHelper.getQuestionViews(self);
var answersData = _(questionViews).map(function(fields, questionID) {
Ti.API.info("questionid:" + questionID);
Ti.API.info("content:" + fields['valueField'].getValue());
return {
'question_id' : questionID,
'content' : fields.valueField.getValue()
}
});
var responseLocation = getCurrentLocation();
responseErrors = Response.validate(answersData, status);
if (!_.isEmpty(responseErrors)) {
responseViewHelper.displayErrors(responseErrors, questionViews);
alert("There were some errors in the response.");
} else {
Response.createRecord(surveyID, status, answersData);
self.fireEvent('ResponsesNewView:savedResponse');
}
};
completeButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "complete");
});
saveButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "incomplete");
});
return self;
}
module.exports = ResponsesNewView;
| JavaScript | 0 |
142c7d5144b2ef2fc230ddb9b1d4cae29048d1e5 | output ultrasonic reading to ros | examples/sensor-to-ros/index.js | examples/sensor-to-ros/index.js | const Board = require('firmata');
const Sonar = require('./lib/sonar');
const Motor = require('./lib/motor');
const pwait = require('./lib/util').pwait;
const rosnodejs = require('rosnodejs');
const std_msgs = rosnodejs.require('std_msgs');
const PIN_SONAR = 8;
const PIN_SERVO = 3;
let STEP = 20;
const MIN = 0, MAX = 180;
let servoPos = MIN;
rosnodejs.initNode('sensor_to_ros', {messages: ['std_msgs/Float32']})
.then( (nodeHandle) => {
distance_publisher = nodeHandle.advertise('/distance', 'std_msgs/Float32');
const sonarBoard = new Board('/dev/ttyACM0', err => {
if (err) {
throw new Error(err);
}
console.log('SONAR READY');
const sonar = new Sonar(sonarBoard, PIN_SONAR);
sonarBoard.servoConfig(PIN_SERVO, 660, 1300);
const servoTo = sonarBoard.servoWrite.bind(sonarBoard, PIN_SERVO);
servoTo(servoPos);
const nextPos = () => {
const tmp = servoPos + STEP;
if (tmp > MAX || tmp < MIN) {
// change servo direction
STEP *= -1;
}
return servoPos += STEP;
};
const scan = () => {
// execute 4 pings
return sonar.multiPing(1)
// select the reading with the smallest distance
.then(arr => arr.reduce((c, p) => p.value < c.value ? p : c, { value: Infinity }))
// add current servo position to the data object
.then(data => Object.assign({angle: servoPos}, data))
// send new data to web server
.then(data => {
console.log(`${data.value}(${data.index}) @ ${data.angle}°`);
// publish the distance to ros
msg = new std_msgs.msg.Float32();
msg.data = data.value;
distance_publisher.publish(msg);
})
// move to next position
.then(() => servoTo(nextPos()))
// wait 20ms for servo to move
.then(pwait.bind(null, 80))
// trigger next scan
.then(scan);
}
// start scanning
scan();
})
});
| const Board = require('firmata');
const Sonar = require('./lib/sonar');
const Motor = require('./lib/motor');
const pwait = require('./lib/util').pwait;
const PIN_SONAR = 8;
const PIN_SERVO = 3;
let STEP = 20;
const MIN = 0, MAX = 180;
let servoPos = MIN;
const sonarBoard = new Board('/dev/ttyACM0', err => {
if (err) {
throw new Error(err);
}
console.log('SONAR READY');
const sonar = new Sonar(sonarBoard, PIN_SONAR);
sonarBoard.servoConfig(PIN_SERVO, 660, 1300);
const servoTo = sonarBoard.servoWrite.bind(sonarBoard, PIN_SERVO);
servoTo(servoPos);
const nextPos = () => {
const tmp = servoPos + STEP;
if (tmp > MAX || tmp < MIN) {
// change servo direction
STEP *= -1;
}
return servoPos += STEP;
};
const scan = () => {
// execute 4 pings
return sonar.multiPing(1)
// select the reading with the smallest distance
.then(arr => arr.reduce((c, p) => p.value < c.value ? p : c, { value: Infinity }))
// add current servo position to the data object
.then(data => Object.assign({angle: servoPos}, data))
// send new data to web server
.then(data => {
console.log(`${data.value}(${data.index}) @ ${data.angle}°`);
})
// move to next position
.then(() => servoTo(nextPos()))
// wait 20ms for servo to move
.then(pwait.bind(null, 80))
// trigger next scan
.then(scan);
}
// start scanning
scan();
})
| JavaScript | 0.999999 |
87374dd5e6e48b3a4a96bac9e845664ce0c330c7 | Add saga for generating me data | app/containers/App/sagas.js | app/containers/App/sagas.js | import { call, put, takeLatest } from 'redux-saga/effects';
import {
ME_FROM_TOKEN,
} from './constants';
import {
meRequestFailed,
meRequestSuccess,
} from './actions';
function* getMeFromToken(action) {
// TODO: placeholder for request
const request = {};
try {
const me = yield call(request.fetch, action.username);
yield put(meRequestSuccess(me));
} catch (err) {
yield put(meRequestFailed(err.message));
}
}
function* meData() {
yield takeLatest(ME_FROM_TOKEN, getMeFromToken);
}
export default [
meData,
];
| import { takeLatest } from 'redux-saga/effects';
import {
ME_FROM_TOKEN,
} from './constants';
function* getMeFromToken() {
}
function* meData() {
yield takeLatest(ME_FROM_TOKEN, getMeFromToken);
}
export default [
meData,
];
| JavaScript | 0.000238 |
6fb1f05949e8ca5e1d9e692348535c7bf1f0186e | words plugin: links inherit color. default link color is annoying | plugins/popcorn.words.js | plugins/popcorn.words.js | // PLUGIN: words
(function (Popcorn) {
"use strict";
var styleSheet;
Popcorn.basePlugin( 'words' , function(options, base) {
var popcorn,
video,
classes,
container,
textContainer,
text, node, i;
if (!base.target || !options.text) {
return;
}
popcorn = this;
video = popcorn.media;
//todo: add stylesheet with basePlugin
if (!styleSheet) {
styleSheet = document.createElement('style');
styleSheet.setAttribute('type', 'text/css');
styleSheet.appendChild(
document.createTextNode(
'.popcorn-words { display: none; }\n' +
'.popcorn-words > a { color: inherit; }\n' +
'.popcorn-words.active { display: block; }\n'
));
document.head.appendChild(styleSheet);
}
container = base.makeContainer();
container.style.cssText = options.style || '';
//todo: do all of this positioning stuff with basePlugin
i = options.top;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.top = i;
container.style.position = 'absolute';
}
i = options.left;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.left = i;
container.style.position = 'absolute';
}
i = options.right;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.right = i;
container.style.position = 'absolute';
}
i = options.bottom;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.bottom = i;
container.style.position = 'absolute';
}
base.animate('top', function(val) {
container.style.top = val;
});
base.animate('left', function(val) {
container.style.left = val;
});
base.animate('right', function(val) {
container.style.right = val;
});
base.animate('bottom', function(val) {
container.style.bottom = val;
});
if (options.align) {
container.style.textAlign = options.align;
}
if (options.classes) {
base.addClass(container, options.classes);
}
if (options.link) {
//todo: localize link
textContainer = document.createElement('a');
textContainer.setAttribute('href', options.link);
if (options.linkTarget) {
textContainer.setAttribute('target', options.linkTarget);
} else {
textContainer.setAttribute('target', '_new');
}
//pause video when link is clicked
textContainer.addEventListener('click', function() {
video.pause();
}, false);
container.appendChild(textContainer);
} else {
textContainer = container;
}
//todo: localize
text = base.toArray(options.text, /[\n\r]/);
for (i = 0; i < text.length; i++) {
if (i) {
textContainer.appendChild(document.createElement('br'));
}
textContainer.appendChild(document.createTextNode(text[i]));
}
if (typeof options.onLoad === 'function') {
options.onLoad(options);
}
return {
start: function( event, options ) {
base.addClass(base.container, 'active');
},
end: function( event, options ) {
base.removeClass(base.container, 'active');
}
};
});
}( Popcorn ));
| // PLUGIN: words
(function (Popcorn) {
"use strict";
var styleSheet;
Popcorn.basePlugin( 'words' , function(options, base) {
var popcorn,
video,
classes,
container,
textContainer,
text, node, i;
if (!base.target || !options.text) {
return;
}
popcorn = this;
video = popcorn.media;
//todo: add stylesheet with basePlugin
if (!styleSheet) {
styleSheet = document.createElement('style');
styleSheet.setAttribute('type', 'text/css');
styleSheet.appendChild(
document.createTextNode(
'.popcorn-words { display: none; }\n' +
'.popcorn-words.active { display: block; }\n'
));
document.head.appendChild(styleSheet);
}
container = base.makeContainer();
container.style.cssText = options.style || '';
//todo: do all of this positioning stuff with basePlugin
i = options.top;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.top = i;
container.style.position = 'absolute';
}
i = options.left;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.left = i;
container.style.position = 'absolute';
}
i = options.right;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.right = i;
container.style.position = 'absolute';
}
i = options.bottom;
if (i || i === 0) {
if (!isNaN(i)) {
i += 'px';
}
container.style.bottom = i;
container.style.position = 'absolute';
}
base.animate('top', function(val) {
container.style.top = val;
});
base.animate('left', function(val) {
container.style.left = val;
});
base.animate('right', function(val) {
container.style.right = val;
});
base.animate('bottom', function(val) {
container.style.bottom = val;
});
if (options.align) {
container.style.textAlign = options.align;
}
if (options.classes) {
base.addClass(container, options.classes);
}
if (options.link) {
//todo: localize link
textContainer = document.createElement('a');
textContainer.setAttribute('href', options.link);
if (options.linkTarget) {
textContainer.setAttribute('target', options.linkTarget);
} else {
textContainer.setAttribute('target', '_new');
}
//pause video when link is clicked
textContainer.addEventListener('click', function() {
video.pause();
}, false);
container.appendChild(textContainer);
} else {
textContainer = container;
}
//todo: localize
text = base.toArray(options.text, /[\n\r]/);
for (i = 0; i < text.length; i++) {
if (i) {
textContainer.appendChild(document.createElement('br'));
}
textContainer.appendChild(document.createTextNode(text[i]));
}
if (typeof options.onLoad === 'function') {
options.onLoad(options);
}
return {
start: function( event, options ) {
base.addClass(base.container, 'active');
},
end: function( event, options ) {
base.removeClass(base.container, 'active');
}
};
});
}( Popcorn ));
| JavaScript | 0.999987 |
01761e0d9f10362d2a681b2bcb1c51c78b39d2d9 | increase test timeout | index.test.js | index.test.js | const execa = require('execa');
const fs = require('fs');
afterEach(done => {
fs.access('sitemap.xml', err => {
if (!err) {
fs.unlink('sitemap.xml', done);
}
});
});
test(
'should create sitemap file',
() => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
]).then(() => {
expect(() => fs.accessSync('sitemap.xml')).not.toThrow();
});
},
20000
);
test(
'should write to stdout in verbose mode',
() => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
'--verbose',
]).then(result => {
expect(result.stdout).not.toBe('');
});
},
20000
);
| const execa = require('execa');
const fs = require('fs');
afterEach(done => {
fs.access('sitemap.xml', err => {
if (!err) {
fs.unlink('sitemap.xml', done);
}
});
});
test('should create sitemap file', () => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
]).then(() => {
expect(() => fs.accessSync('sitemap.xml')).not.toThrow();
});
});
test('should write to stdout in verbose mode', () => {
expect.assertions(1);
return execa('node', [
'index.js',
'https://larsgraubner.com',
'sitemap.xml',
'--verbose',
]).then(result => {
expect(result.stdout).not.toBe('');
});
});
| JavaScript | 0.000002 |
e27fb513a6887b400b8a6089f7fa2059a6fac528 | Fix require bug | app/lib/backgroundLoader.js | app/lib/backgroundLoader.js | import getAndInitNewEpisodes from "./getAndInitNewEpisodes";
import forEach from "./forEach";
import episodesToString from "./episodesToString";
var ipc = nRequire("ipc");
export default function(controller) {
var store = controller.get("store");
var checkForEp = function(){
if(controller.get("isUpdating")) { return; }
controller.set("isUpdating", true);
getAndInitNewEpisodes(controller.currentUser, store).then(function(episodes) {
controller.model.unshiftObjects(episodes);
forEach(episodes.toArray(), function(episode, next) {
episode.loading(next, next);
}, function(){
controller.set("isUpdating", false);
if(episodes.get("length")){
new Notification("New episodes", {
body: episodesToString(episodes)
});
ipc.send("newBackgroundEpisodes", 1);
}
});
}).catch(function(err){
console.info("err1", err)
controller.currentUser.logout();
controller.transitionToRoute("login");
}).finally(function(){
controller.set("isUpdating", false);
});
}
var deleteOld = function() {
var deleteOnTerm = function(term) {
store.query("episode", term).then(function(episodes) {
episodes.forEach(function(episode) {
if(episode.isOlderThenDays(30)){
episode.destroyRecord();
}
});
});
}
deleteOnTerm({ removed: true });
deleteOnTerm({ seen: true });
};
var checkForNewMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false,
magnet: null
}).then(function(episodes) {
forEach(episodes.toArray(), function(episode, next){
episode.loading(next, next);
}, function() {
// Remove all episodes which doesn't have a magnet link
var filteredEps = episodes.reject(function(episode) {
return ! episode.get("magnet");
});
if(filteredEps.length){
new Notification("New magnet links", {
body: episodesToString(filteredEps)
});
ipc.send("newBackgroundEpisodes", 1);
}
controller.set("isReloading", false);
}, function() {
controller.set("isReloading", false);
});
}, function(err) {
controller.set("isReloading", false);
});
}
var updateMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false
}).then(function(episodes) {
forEach(episodes.toArray().reverse(), function(episode, next){
episode.loading(next, next);
}, function(){
controller.set("isReloading", false);
});
});
}
var minute = 1000 * 60;
var ids = []
// Update releases every 60 min
ids.push(setInterval(checkForEp, 60 * minute));
// Find new magnets every 30 min
ids.push(setInterval(checkForNewMagnets, 30 * minute));
// Update magnets every 40 min
ids.push(setInterval(updateMagnets, 40 * minute));
// Delete old episodes once every hour
ids.push(setInterval(deleteOld, 60 * minute));
var check = function() {
checkForEp();
checkForNewMagnets();
updateMagnets();
deleteOld();
};
var online = function() {
// Wait 5 sec to ensure connectivity
setTimeout(check, 5000);
}
var down = function() {
window.removeEventListener("online", online);
ids.forEach(function(id) {
clearInterval(id);
});
};
// Check when online
window.addEventListener("online", online);
// Check all on start up
check();
return down;
}; | import getAndInitNewEpisodes from "./getAndInitNewEpisodes";
import forEach from "./forEach";
import episodesToString from "./episodesToString";
var ipc = require("ipc");
export default function(controller) {
var store = controller.get("store");
var checkForEp = function(){
if(controller.get("isUpdating")) { return; }
controller.set("isUpdating", true);
getAndInitNewEpisodes(controller.currentUser, store).then(function(episodes) {
controller.model.unshiftObjects(episodes);
forEach(episodes.toArray(), function(episode, next) {
episode.loading(next, next);
}, function(){
controller.set("isUpdating", false);
if(episodes.get("length")){
new Notification("New episodes", {
body: episodesToString(episodes)
});
ipc.send("newBackgroundEpisodes", 1);
}
});
}).catch(function(err){
console.info("err1", err)
controller.currentUser.logout();
controller.transitionToRoute("login");
}).finally(function(){
controller.set("isUpdating", false);
});
}
var deleteOld = function() {
var deleteOnTerm = function(term) {
store.query("episode", term).then(function(episodes) {
episodes.forEach(function(episode) {
if(episode.isOlderThenDays(30)){
episode.destroyRecord();
}
});
});
}
deleteOnTerm({ removed: true });
deleteOnTerm({ seen: true });
};
var checkForNewMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false,
magnet: null
}).then(function(episodes) {
forEach(episodes.toArray(), function(episode, next){
episode.loading(next, next);
}, function() {
// Remove all episodes which doesn't have a magnet link
var filteredEps = episodes.reject(function(episode) {
return ! episode.get("magnet");
});
if(filteredEps.length){
new Notification("New magnet links", {
body: episodesToString(filteredEps)
});
ipc.send("newBackgroundEpisodes", 1);
}
controller.set("isReloading", false);
}, function() {
controller.set("isReloading", false);
});
}, function(err) {
controller.set("isReloading", false);
});
}
var updateMagnets = function(){
controller.set("isReloading", true);
store.query("episode", {
seen: false,
removed: false
}).then(function(episodes) {
forEach(episodes.toArray().reverse(), function(episode, next){
episode.loading(next, next);
}, function(){
controller.set("isReloading", false);
});
});
}
var minute = 1000 * 60;
var ids = []
// Update releases every 60 min
ids.push(setInterval(checkForEp, 60 * minute));
// Find new magnets every 30 min
ids.push(setInterval(checkForNewMagnets, 30 * minute));
// Update magnets every 40 min
ids.push(setInterval(updateMagnets, 40 * minute));
// Delete old episodes once every hour
ids.push(setInterval(deleteOld, 60 * minute));
var check = function() {
checkForEp();
checkForNewMagnets();
updateMagnets();
deleteOld();
};
var online = function() {
// Wait 5 sec to ensure connectivity
setTimeout(check, 5000);
}
var down = function() {
window.removeEventListener("online", online);
ids.forEach(function(id) {
clearInterval(id);
});
};
// Check when online
window.addEventListener("online", online);
// Check all on start up
check();
return down;
}; | JavaScript | 0.000001 |
72817bdb9f571075b2d0020ccba95bef68f9758e | use separate escape/non-escape toString functions for fragments - easier for browsers to optimise | src/virtualdom/Fragment/prototype/toString.js | src/virtualdom/Fragment/prototype/toString.js | export default function Fragment$toString ( escape ) {
if ( !this.items ) {
return '';
}
return this.items.map( escape ? toEscapedString : toString ).join( '' );
}
function toString ( item ) {
return item.toString();
}
function toEscapedString ( item ) {
return item.toString( true );
} | export default function Fragment$toString ( escape ) {
if ( !this.items ) {
return '';
}
return this.items.map( function ( item ) {
return item.toString( escape );
}).join( '' );
}
| JavaScript | 0 |
ec375d715289fc0726efcf2c34c97ad3b6e89e3a | Complete sensors list | sensors.js | sensors.js | const gpio = require('pi-gpio');
const client = require('prom-client');
const Promise = require('bluebird');
Promise.promisifyAll(gpio);
const sensors = [{
gpioPin: 11,
sensorId: '0',
sensorDescription: '',
}, {
gpioPin: 12,
sensorId: '1',
sensorDescription: '',
}, {
gpioPin: 13,
sensorId: '2',
sensorDescription: '',
}, {
gpioPin: 15,
sensorId: '3',
sensorDescription: '',
}, {
gpioPin: 16,
sensorId: '4',
sensorDescription: '',
}, {
gpioPin: 18,
sensorId: '5',
sensorDescription: '',
}];
const airTempGauge = new client.Gauge('air_temperature', 'Air Temperature in a room', ['sensorId', 'sensorDescription']);
const relHumidityGauge = new client.Gauge('humidity_relative', 'Relative humidity in a room', ['sensorId', 'sensorDescription']);
function readSensorData(sensor) {
gpio.readAsync(sensor.gpioPin)
.then((value) => {
console.log(`${sensorId} ${value}`);
//tempGauge.set(parseFloat(data));
});
}
Promise.map(sensors, (sensor) => {
return gpio.openAsync(sensor.gpioPin, 'input');
})
.then(Promise.map(sensors, (sensor) => {
return readSensorData(sensor);
});
| const gpio = require('pi-gpio');
const client = require('prom-client');
const Promise = require('bluebird');
Promise.promisifyAll(gpio);
const sensors = [{
gpioPin: 0,
sensorId: '',
sensorDescription: '',
}];
const airTempGauge = new client.Gauge('air_temperature', 'Air Temperature in a room', ['sensorId', 'sensorDescription']);
const relHumidityGauge = new client.Gauge('humidity_relative', 'Relative humidity in a room', ['sensorId', 'sensorDescription']);
function readSensorData(sensor) {
gpio.readAsync(sensor.gpioPin)
.then((value) => {
console.log(value);
//tempGauge.set(parseFloat(data));
});
}
Promise.map(sensors, (sensor) => gpio.openAsync(sensor.gpioPin, 'input'))
.then(() => Promise.map(sensors, (sensor) => readSensor(sensor));
| JavaScript | 0.000005 |
1708171858ce97ec2e5e7f7681e5b8cf2c6ca901 | Move the directive link function to a function definition. | app/common/directives/bubble-chart.directive.js | app/common/directives/bubble-chart.directive.js | (function () {
'use strict';
angular
.module('gmailHistogramApp')
.directive('d3BubbleChart', d3BubbleChartDirective);
d3BubbleChartDirective.$inject = ['$window'];
function d3BubbleChartDirective($window) {
return {
restrict: 'EA',
scope: {
data: '='
},
link: link
};
function link(scope, element, attrs) {
var diameter = 450;
var svg = d3.select(element[0]).append('svg');
svg.attr({
'width': diameter,
'height': diameter,
'class': 'bubble'
});
$window.onresize = function () {
scope.$apply();
};
scope.$watch(
function () {
return angular.element($window)[0].innerWidth;
},
function () {
draw(svg, diameter, scope.data);
});
scope.$watch('data',
function () {
draw(svg, diameter, scope.data);
});
};
};
function flattenData(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function (child) { recurse(node.name, child); });
else classes.push({ packageName: name, className: node.name, value: node.size });
}
recurse(null, root);
return { children: classes };
};
function draw(svg, diameter, inputData) {
var format = d3.format(",d");
var color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var flatData = bubble.nodes(flattenData(inputData)).filter(function (d) { return !d.children; });
var node = svg.selectAll("g").data(flatData);
var appendedNode = node.enter().append("g").attr("class", "node");
appendedNode.append("circle");
appendedNode.append("text").attr("dy", ".3em").style("text-anchor", "middle");
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
node.select("circle")
.attr("r", function (d) { return d.r; })
.style("fill", function (d) { return color(d.packageName); });
node.select("text").text(function (d) { return d.className.toUpperCase(); });
node.exit().remove();
};
} ()); | (function () {
'use strict';
angular
.module('gmailHistogramApp')
.directive('d3BubbleChart', d3BubbleChartDirective);
d3BubbleChartDirective.$inject = ['$window'];
function d3BubbleChartDirective($window) {
return {
restrict: 'EA',
scope: {
data: '='
},
link: function (scope, element, attrs) {
var diameter = 450;
var svg = d3.select(element[0]).append('svg');
svg.attr({
'width': diameter,
'height': diameter,
'class': 'bubble'
});
$window.onresize = function () {
scope.$apply();
};
scope.$watch(
function () {
return angular.element($window)[0].innerWidth;
},
function () {
draw(svg, diameter, scope.data);
});
scope.$watch('data',
function () {
draw(svg, diameter, scope.data);
});
}
};
};
function flattenData(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function (child) { recurse(node.name, child); });
else classes.push({ packageName: name, className: node.name, value: node.size });
}
recurse(null, root);
return { children: classes };
};
function draw(svg, diameter, inputData) {
var format = d3.format(",d");
var color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var flatData = bubble.nodes(flattenData(inputData)).filter(function (d) { return !d.children; });
var node = svg.selectAll("g").data(flatData);
var appendedNode = node.enter().append("g").attr("class", "node");
appendedNode.append("circle");
appendedNode.append("text").attr("dy", ".3em").style("text-anchor", "middle");
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
node.select("circle")
.attr("r", function (d) { return d.r; })
.style("fill", function (d) { return color(d.packageName); });
node.select("text").text(function (d) { return d.className.toUpperCase(); });
node.exit().remove();
};
} ()); | JavaScript | 0 |
4327db9cd4d507c15dfb4afe66d81653d1dadef6 | Set theme field to full size | app/components/forms/settings/base/component.js | app/components/forms/settings/base/component.js | import React from 'react';
import { RaisedButton, MenuItem } from 'material-ui';
import {
TextField,
SelectField
} from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';
import BaseComponent from 'lex/libs/base/component';
import BaseContainer from 'lex/libs/container';
import { I18n } from 'react-redux-i18n';
import { connect } from 'react-redux';
import { pullData } from 'lex/actions/form-setup';
import fillData from 'lex/utils/object-fill-from-data';
import themes from 'lex/constants/menu-themes';
const validate = values => {
const errors = {};
const { hitSize } = values;
if (!hitSize) {
errors.hitSize = I18n.t('components.forms.required');
} else if (isNaN(Number(hitSize))) {
errors.hitSize = I18n.t('components.forms.mustBeNumber');
} else if (Number(hitSize) <= 0) {
errors.hitSize = I18n.t('components.forms.mustBeGreaterZero');
}
return errors;
};
const ThemeSelect = () => {
const items = themes.map((item, index) => {
return (
<MenuItem
primaryText={item.label}
value={item.code}
key={index}
/>
);
});
return (
<Field
floatingLabelText="Theme"
component={SelectField}
hintText="Theme"
fullWidth={true}
name="theme"
>
{items}
</Field>
);
};
class SettingsBaseForm extends BaseComponent {
componentDidMount() {
const { data, load, form } = this.props;
if (form, data) {
const fields = fillData(data);
Object.keys(fields).forEach((item) => {
const value = fields[item];
if (value) {
load('settings-base', item, value);
}
});
}
}
render() {
this.decorateStyle();
const { handleSubmit, invalid } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>
<Field
placeholder={I18n.t('components.forms.settings.placeholders.hitSize')}
component={TextField}
fullWidth={true}
name="hitSize"
/>
</div>
<div>
<ThemeSelect />
</div>
<div>
<RaisedButton
disabled={invalid}
label='Save'
secondary={true}
type="submit"
/>
</div>
</form>
);
}
}
SettingsBaseForm = reduxForm({
form: 'settings-base',
validate,
})(SettingsBaseForm);
SettingsBaseForm = connect(null, {
load: pullData
})(SettingsBaseForm);
export default BaseContainer(SettingsBaseForm);
| import React from 'react';
import { RaisedButton, MenuItem } from 'material-ui';
import {
TextField,
SelectField
} from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';
import BaseComponent from 'lex/libs/base/component';
import BaseContainer from 'lex/libs/container';
import { I18n } from 'react-redux-i18n';
import { connect } from 'react-redux';
import { pullData } from 'lex/actions/form-setup';
import fillData from 'lex/utils/object-fill-from-data';
import themes from 'lex/constants/menu-themes';
const validate = values => {
const errors = {};
const { hitSize } = values;
if (!hitSize) {
errors.hitSize = I18n.t('components.forms.required');
} else if (isNaN(Number(hitSize))) {
errors.hitSize = I18n.t('components.forms.mustBeNumber');
} else if (Number(hitSize) <= 0) {
errors.hitSize = I18n.t('components.forms.mustBeGreaterZero');
}
return errors;
};
const ThemeSelect = () => {
const items = themes.map((item, index) => {
return (
<MenuItem
primaryText={item.label}
value={item.code}
key={index}
/>
);
});
return (
<Field
name="theme"
component={SelectField}
hintText="Theme"
floatingLabelText="Theme"
>
{items}
</Field>
);
};
class SettingsBaseForm extends BaseComponent {
componentDidMount() {
const { data, load, form } = this.props;
if (form, data) {
const fields = fillData(data);
Object.keys(fields).forEach((item) => {
const value = fields[item];
if (value) {
load('settings-base', item, value);
}
});
}
}
render() {
this.decorateStyle();
const { handleSubmit, invalid } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>
<Field
placeholder={I18n.t('components.forms.settings.placeholders.hitSize')}
component={TextField}
fullWidth={true}
name="hitSize"
/>
</div>
<div>
<ThemeSelect />
</div>
<div>
<RaisedButton
disabled={invalid}
label='Save'
secondary={true}
type="submit"
/>
</div>
</form>
);
}
}
SettingsBaseForm = reduxForm({
form: 'settings-base',
validate,
})(SettingsBaseForm);
SettingsBaseForm = connect(null, {
load: pullData
})(SettingsBaseForm);
export default BaseContainer(SettingsBaseForm);
| JavaScript | 0 |
e85b1a2f3f73a975b6570e0dd2a8a93735e30f24 | fix c boolean formatter | app/components/logic/lib/formatter/c-boolean.js | app/components/logic/lib/formatter/c-boolean.js | const operators = {
AND: '&&',
OR: '||',
NOT: '!',
XOR: '!=',
};
const tryFetch = (map, key) =>
map[key] || key
;
const whitspace = new RegExp('\s+', 'g');
const sanitizeName = (name) =>
name.replace(whitspace, '_');
const formatter = {
name: "C Boolean",
formatBinary: (op, lhs, rhs/*, depth*/) => {
return formatter.formatBinaryChain(op, lhs, rhs);
},
formatBinaryChain: (op, ...operands) => {
return `(${operands.join(` ${tryFetch(operators, op)} `)})`;
},
formatUnary: (op, content/*, depth*/) => {
return `(${formatter.formatUnarySimple(op, content)})`;
},
formatUnarySimple: (op, content/*, depth*/) => {
return `${tryFetch(operators, op)}${content}`;
},
formatGroup: (content/*, depth*/) => {
return content;
},
formatName: (name) => {
return sanitizeName(name);
},
formatValue: (value) => {
if (value === true) {
return 'true';
} else if (value === false) {
return 'false';
} else {
return 'void';
}
},
formatVector: (identifiers, values) => {
return `<${
identifiers.map((i) => i.name).join(',')
}:${
values.map(formatter.formatVectorValue).join('')
}>`;
},
formatVectorValue: (value) => {
if (value === true) {
return '1';
} else if (value === false) {
return '0';
} else {
return '*';
}
},
formatLabel: (name, body) => {
return `${name}=${body}`;
},
formatExpressions: (expressions) => {
return expressions.join(', ');
},
};
export default formatter;
| const operators = {
AND: '&&',
OR: '||',
NOT: '!',
XOR: '^',
};
const tryFetch = (map, key) =>
map[key] || key
;
const whitspace = new RegExp('\s+', 'g');
const sanitizeName = (name) =>
name.replace(whitspace, '_');
const formatter = {
name: "C Boolean",
formatBinary: (op, lhs, rhs/*, depth*/) => {
return formatter.formatBinaryChain(op, lhs, rhs);
},
formatBinaryChain: (op, ...operands) => {
return `(${operands.join(` ${tryFetch(operators, op)} `)})`;
},
formatUnary: (op, content/*, depth*/) => {
return `(${formatter.formatUnarySimple(op, content)})`;
},
formatUnarySimple: (op, content/*, depth*/) => {
return `${tryFetch(operators, op)}${content}`;
},
formatGroup: (content/*, depth*/) => {
return content;
},
formatName: (name) => {
return sanitizeName(name);
},
formatValue: (value) => {
if (value === true) {
return 'true';
} else if (value === false) {
return 'false';
} else {
return 'void';
}
},
formatVector: (identifiers, values) => {
return `<${
identifiers.map((i) => i.name).join(',')
}:${
values.map(formatter.formatVectorValue).join('')
}>`;
},
formatVectorValue: (value) => {
if (value === true) {
return '1';
} else if (value === false) {
return '0';
} else {
return '*';
}
},
formatLabel: (name, body) => {
return `${name}=${body}`;
},
formatExpressions: (expressions) => {
return expressions.join(', ');
},
};
export default formatter;
| JavaScript | 0.999246 |
400e1b221d277175d8d3656f7e5f146ce20f0a6e | refresh based on notifications | app/controllers/facebook-realtime-controller.js | app/controllers/facebook-realtime-controller.js | var User = mongoose.model("User")
, ImageList = mongoose.model("ImageList")
, util = require('util')
, _ = require('underscore')
, PuSHHelper = require('node-push-helper').PuSHHelper;
module.exports = function (app) {
// a GET request will be a challenge query
app.get('/facebook/realtime', function(req, res){
PuSHHelper.handshake(req, res);
});
// this is where Instagram will send updates (using POST)
app.post('/facebook/realtime', PuSHHelper.check_signature, function(req, res){
console.log("Data is " + util.inspect(req.body, false, null));
var notifications = req.body;
if (notifications['object'] == 'user') {
var seen_in_this_batch = {};
var entries = notifications.entry;
for (var i=0; i < entries.length; i++) {
var message = entries[i];
// check if we already processed this user in this batch
// since we're just pulling the latest batch of public photos,
// we don't need to do this multiple times in one notification
// push.
if (seen_in_this_batch[message.uid] === undefined) {
seen_in_this_batch[message.uid] = true;
User.findOne({"tokens.facebook.account_id": message["uid"]}, function(err, user){
if (err == null) {
if (user !== null) {
ImageList.refreshFeedForUserProvider(user, "facebook", function(err, imageList) {
if (err) {
console.log("ERROR: Flickr notification had an error refreshing the feed: " + err);
} else {
console.log("SUCCESS: Flickr notification successfully refreshed feed. New timestamp is: " + moment(imageList.updated_at).format('MM/DD/YYYY h:mm:ss a'));
}
});
} else {
console.log("ERROR: facebook uid from realtime notification not found: " + message["uid"]);
}
} else {
// failed
console.log("ERROR handling notification: " + err);
}
});
}
};
}
// don't wait for refreshes to finish.
res.send({meta: 200, message: "Received and understood."}, 200);
});
}
| var User = mongoose.model("User")
, ImageList = mongoose.model("ImageList")
, util = require('util')
, PuSHHelper = require('node-push-helper').PuSHHelper;
module.exports = function (app) {
// a GET request will be a challenge query
app.get('/facebook/realtime', function(req, res){
PuSHHelper.handshake(req, res);
});
// this is where Instagram will send updates (using POST)
app.post('/facebook/realtime', PuSHHelper.check_signature, function(req, res){
console.log("Data is " + util.inspect(req.body, false, null));
res.send({meta: 200, message: "Received and understood."}, 200);
});
}
| JavaScript | 0.000002 |
b544e1f33c824b6fe2f60143d503df1bd606ba73 | declare connectGaiaHub in proptypes | app/js/welcome/components/ConnectStorageView.js | app/js/welcome/components/ConnectStorageView.js | import React, { PropTypes } from 'react'
const ConnectStorageView = (props) =>
(
<div>
<h3 className="modal-heading m-t-15 p-b-20">
Connect a storage provider to store app data in a place you control
</h3>
<img
role="presentation"
src="/images/blockstack-logo-vertical.svg"
className="m-b-20"
style={{ width: '210px', display: 'block', marginRight: 'auto', marginLeft: 'auto' }}
/>
<div className="m-t-40">
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectGaiaHub}>
Connect Gaia Hub
</button>
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectDropbox}>
Connect Dropbox
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect IPFS
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect Self-hosted Drive
</button>
</div>
</div>
)
ConnectStorageView.propTypes = {
connectDropbox: PropTypes.func.isRequired,
connectGaiaHub: PropTypes.func.isRequired
}
export default ConnectStorageView
| import React, { PropTypes } from 'react'
const ConnectStorageView = (props) =>
(
<div>
<h3 className="modal-heading m-t-15 p-b-20">
Connect a storage provider to store app data in a place you control
</h3>
<img
role="presentation"
src="/images/blockstack-logo-vertical.svg"
className="m-b-20"
style={{ width: '210px', display: 'block', marginRight: 'auto', marginLeft: 'auto' }}
/>
<div className="m-t-40">
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectGaiaHub}>
Connect Gaia Hub
</button>
<button className="btn btn-primary btn-block m-b-20" onClick={props.connectDropbox}>
Connect Dropbox
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect IPFS
</button>
<button className="btn btn-primary btn-block m-b-20" disabled title="Coming soon!">
Connect Self-hosted Drive
</button>
</div>
</div>
)
ConnectStorageView.propTypes = {
connectDropbox: PropTypes.func.isRequired
}
export default ConnectStorageView
| JavaScript | 0.000001 |
0af482b4e11e885956f8ee32eb0dad2df0f9e8fb | Update zh_cn.js | vendor/assets/javascripts/redactor-rails/langs/zh_cn.js | vendor/assets/javascripts/redactor-rails/langs/zh_cn.js | //@chen1706@gmail.com
(function ($) {
$.Redactor.opts.langs['zh_cn'] = {
html: 'HTML代码',
video: '视频',
image: '图片',
table: '表格',
link: '链接',
link_insert: '插入链接',
link_edit: '编辑链接',
unlink: '取消链接',
formatting: '样式',
paragraph: '段落',
quote: '引用',
code: '代码',
header1: '一级标题',
header2: '二级标题',
header3: '三级标题',
header4: '四级标题',
header5: '五级标题'
bold: '粗体',
italic: '斜体',
fontcolor: '字体颜色',
backcolor: '背景颜色',
unorderedlist: '项目编号',
orderedlist: '数字编号',
outdent: '减少缩进',
indent: '增加缩进',
cancel: '取消',
insert: '插入',
save: '保存',
_delete: '删除',
insert_table: '插入表格',
insert_row_above: '在上方插入',
insert_row_below: '在下方插入',
insert_column_left: '在左侧插入',
insert_column_right: '在右侧插入',
delete_column: '删除整列',
delete_row: '删除整行',
delete_table: '删除表格',
rows: '行',
columns: '列',
add_head: '添加标题',
delete_head: '删除标题',
title: '标题',
image_position: '位置',
none: '无',
left: '左',
right: '右',
image_web_link: '图片网页链接',
text: '文本',
mailto: '邮箱',
web: '网址',
video_html_code: '视频嵌入代码',
file: '文件',
upload: '上传',
download: '下载',
choose: '选择',
or_choose: '或选择',
drop_file_here: '将文件拖拽至此区域',
align_left: '左对齐',
align_center: '居中',
align_right: '右对齐',
align_justify: '两端对齐',
horizontalrule: '水平线',
fullscreen: '全屏',
deleted: '删除',
anchor: '锚点',
link_new_tab: '在新窗口打开',
underline: '下划线',
alignment: '对齐方式',
filename: '文件名 (可选)',
edit: '编辑'
};
})( jQuery );
| //@chen1706@gmail.com
(function ($) {
$.Redactor.opts.langs['zh_cn'] = {
html: 'HTML代码',
video: '视频',
image: '图片',
table: '表格',
link: '链接',
link_insert: '插入链接',
unlink: '取消链接',
formatting: '样式',
paragraph: '段落',
quote: '引用',
code: '代码',
header1: '一级标题',
header2: '二级标题',
header3: '三级标题',
header4: '四级标题',
bold: '粗体',
italic: '斜体',
fontcolor: '字体颜色',
backcolor: '背景颜色',
unorderedlist: '项目编号',
orderedlist: '数字编号',
outdent: '减少缩进',
indent: '增加缩进',
cancel: '取消',
insert: '插入',
save: '保存',
_delete: '删除',
insert_table: '插入表格',
insert_row_above: '在上方插入',
insert_row_below: '在下方插入',
insert_column_left: '在左侧插入',
insert_column_right: '在右侧插入',
delete_column: '删除整列',
delete_row: '删除整行',
delete_table: '删除表格',
rows: '行',
columns: '列',
add_head: '添加标题',
delete_head: '删除标题',
title: '标题',
image_position: '位置',
none: '无',
left: '左',
right: '右',
image_web_link: '图片网页链接',
text: '文本',
mailto: '邮箱',
web: '网址',
video_html_code: '视频嵌入代码',
file: '文件',
upload: '上传',
download: '下载',
choose: '选择',
or_choose: '或选择',
drop_file_here: '将文件拖拽至此区域',
align_left: '左对齐',
align_center: '居中',
align_right: '右对齐',
align_justify: '两端对齐',
horizontalrule: '水平线',
fullscreen: '全屏',
deleted: '删除',
anchor: '锚点',
link_new_tab: '在新窗口打开',
underline: '下划线',
alignment: '对齐方式'
};
})( jQuery ); | JavaScript | 0.000005 |
954ab95f680a2b1cd2dc30b189a0a0e03234a7e4 | Add getVersions | src/spm.js | src/spm.js | import co from "co";
import { EventEmitter } from "events";
import map from "lodash/collection/map";
import zipObject from "lodash/array/zipObject";
import Config from "./config";
import { getJSON, getJSONProp } from "./utils";
import Package from "./package";
class SPM extends EventEmitter {
constructor (config={}) {
super();
this.config = new Config(config);
this._currentPackage = null;
}
// Getters & setters
get currentPackage () {
if (this._currentPackage === null)
throw Error("No package loaded");
else
return this._currentPackage.toJSON();
}
// Public methods
getVersions (pkgName) {
if (!pkgName)
throw new Error("No package name passed");
return co(
this._getVersions.bind(this, pkgName)
).catch(
this.emit.bind(this, "error")
);
}
load (rootUrl="") {
return co(
this._loadPackage.bind(this, rootUrl)
).then(
pkg => {
this._setPackage(pkg);
this.emit("load", pkg);
}
).catch(
this.emit.bind(this, "error")
);
}
// Private methods
*_getVersions (pkgName) {
let
{registries} = this.config,
versions = map(registries, registry => {
return getJSONProp(`${ registry }/${ pkgName }`, "versions")
});
return yield zipObject(registries, versions);
}
*_loadPackage (rootUrl) {
let
{CONFIG_FILE} = this.config,
url = `${ rootUrl }/${ CONFIG_FILE }`,
pkg = yield getJSON(url);
return pkg;
}
_setPackage (pkg) {
this._currentPackage = new Package(pkg);
}
}
export default SPM;
| import co from "co";
import { EventEmitter } from "events";
import Config from "./config";
import { getJSON } from "./utils";
import Package from "./package";
class SPM extends EventEmitter {
constructor () {
super();
this.config = new Config;
this._currentPackage = null;
}
// Public methods
get currentPackage () {
if (this._currentPackage === null)
throw Error("No package loaded");
else
return this._currentPackage.toJSON();
}
load (rootUrl="") {
return co(
this._loadPackage.bind(this, rootUrl)
).then(
pkg => {
this._setPackage(pkg);
this.emit("load", pkg);
}
).catch(
this.emit.bind(this, "error")
);
}
// Public methods
_setPackage (pkg) {
this._currentPackage = new Package(pkg);
}
*_loadPackage (rootUrl) {
let
{CONFIG_FILE} = this.config,
url = `${ rootUrl }/${ CONFIG_FILE }`,
pkg = yield getJSON(url);
return pkg;
}
}
export default SPM;
| JavaScript | 0 |
1c445ca6378aa1725dd16a074963229ec5c5f17f | add chrome API check | plugins/sidebar/index.js | plugins/sidebar/index.js | 'use strict';
const React = require('react');
const ListItem = require('react-material/components/ListItem');
const Sidebar = require('./sidebar');
const FileList = require('./file-list');
const File = require('./file');
const FileOperations = require('./file-operations');
const ProjectOperations = require('./project-operations');
const deviceStore = require('../../src/stores/device');
const fileStore = require('../../src/stores/file');
const transmissionStore = require('../../src/stores/transmission');
const { loadFile } = require('../../src/actions/file');
function sidebar(app, opts, done){
const space = app.workspace;
const userConfig = app.userConfig;
const getBoard = app.getBoard.bind(app);
const scanBoards = app.scanBoards.bind(app);
// TODO: move into frylord?
if(typeof chrome !== 'undefined' && typeof chrome.syncFileSystem !== 'undefined'){
chrome.syncFileSystem.onFileStatusChanged.addListener(function(detail){
if(detail.direction === 'remote_to_local'){
space.refreshDirectory();
}
});
chrome.syncFileSystem.onServiceStatusChanged.addListener(function(){
space.refreshDirectory();
});
}
app.view('sidebar', function(el, cb){
console.log('sidebar render');
const { cwd, directory } = space.getState();
var Component = (
<Sidebar>
<ProjectOperations />
<FileList workspace={space} loadFile={loadFile}>
<ListItem icon="folder" disableRipple>{cwd}</ListItem>
{directory.map(({ name, temp }) => <File key={name} filename={name} temp={temp} loadFile={loadFile} />)}
</FileList>
<FileOperations />
</Sidebar>
);
React.render(Component, el, cb);
});
space.subscribe(() => {
app.render();
});
// Store bindings
deviceStore.workspace = space;
deviceStore.getBoard = getBoard;
deviceStore.scanBoards = scanBoards;
fileStore.workspace = space;
fileStore.userConfig = userConfig;
transmissionStore.getBoard = getBoard;
done();
}
module.exports = sidebar;
| 'use strict';
const React = require('react');
const ListItem = require('react-material/components/ListItem');
const Sidebar = require('./sidebar');
const FileList = require('./file-list');
const File = require('./file');
const FileOperations = require('./file-operations');
const ProjectOperations = require('./project-operations');
const deviceStore = require('../../src/stores/device');
const fileStore = require('../../src/stores/file');
const transmissionStore = require('../../src/stores/transmission');
const { loadFile } = require('../../src/actions/file');
function sidebar(app, opts, done){
const space = app.workspace;
const userConfig = app.userConfig;
const getBoard = app.getBoard.bind(app);
const scanBoards = app.scanBoards.bind(app);
// TODO: move into frylord?
chrome.syncFileSystem.onFileStatusChanged.addListener(function(detail){
if(detail.direction === 'remote_to_local'){
space.refreshDirectory();
}
});
chrome.syncFileSystem.onServiceStatusChanged.addListener(function(){
space.refreshDirectory();
});
app.view('sidebar', function(el, cb){
console.log('sidebar render');
const { cwd, directory } = space.getState();
var Component = (
<Sidebar>
<ProjectOperations />
<FileList workspace={space} loadFile={loadFile}>
<ListItem icon="folder" disableRipple>{cwd}</ListItem>
{directory.map(({ name, temp }) => <File key={name} filename={name} temp={temp} loadFile={loadFile} />)}
</FileList>
<FileOperations />
</Sidebar>
);
React.render(Component, el, cb);
});
space.subscribe(() => {
app.render();
});
// Store bindings
deviceStore.workspace = space;
deviceStore.getBoard = getBoard;
deviceStore.scanBoards = scanBoards;
fileStore.workspace = space;
fileStore.userConfig = userConfig;
transmissionStore.getBoard = getBoard;
done();
}
module.exports = sidebar;
| JavaScript | 0 |
3896605bec916d4cf00d586d64aede700481dfbd | fix typo | createjson.js | createjson.js | const fs = require('fs');
const path = require('path');
const codelabsPath = '_posts/codelabs/';
const indexJson = [];
function readDir(dirPath) {
fs.readdir(dirPath, (err, files) => {
if (err) {
console.log(err);
throw err;
}
files
.map((file) => {
if (fs.statSync(path.join(dirPath, file)).isDirectory()) {
readDir(path.join(dirPath, file));
}
return path.join(dirPath, file);
})
.filter((file) => fs.statSync(file).isFile())
.forEach((file) => {
if (path.extname(file) === '.json' && file !== '_posts/codelabs/index.json') {
const obj = JSON.parse(fs.readFileSync(file, 'utf8'));
indexJson.push(obj);
const json = JSON.stringify(indexJson);
fs.writeFileSync('_posts/codelabs/index.json', json, 'utf8');
}
});
});
}
readDir(codelabsPath);
| const fs = require('fs');
const path = require('path');
const codelabsPath = '_posts/codelabs/';
const indexJson = [];
function readDir(lolPath) {
fs.readdir(lolPath, (err, files) => {
if (err) {
console.log(err);
throw err;
}
files
.map((file) => {
if (fs.statSync(path.join(lolPath, file)).isDirectory()) {
readDir(path.join(lolPath, file));
}
return path.join(lolPath, file);
})
.filter((file) => fs.statSync(file).isFile())
.forEach((file) => {
if (path.extname(file) === '.json' && file !== '_posts/codelabs/index.json') {
const obj = JSON.parse(fs.readFileSync(file, 'utf8'));
indexJson.push(obj);
const json = JSON.stringify(indexJson);
fs.writeFileSync('_posts/codelabs/index.json', json, 'utf8');
}
});
});
}
readDir(codelabsPath);
| JavaScript | 0.999991 |
401c7b04ace9311ca51264f2a68c9fc09560224c | Remove bar timer | src/js/round/clock/view.js | src/js/round/clock/view.js | var m = require('mithril');
var classSet = require('chessground').util.classSet;
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
function bold(x) {
return '<b>' + x + '</b>';
}
function formatClockTime(ctrl, time) {
var date = new Date(time);
var minutes = prefixInteger(date.getUTCMinutes(), 2);
var seconds = prefixInteger(date.getSeconds(), 2);
var tenths;
if (ctrl.data.showTenths && time < 10000) {
tenths = Math.floor(date.getMilliseconds() / 100);
return bold(minutes) + ':' + bold(seconds) + '<span>.' + bold(tenths) + '</span>';
} else if (time >= 3600000) {
var hours = prefixInteger(date.getUTCHours(), 2);
return bold(hours) + ':' + bold(minutes) + ':' + bold(seconds);
} else {
return bold(minutes) + ':' + bold(seconds);
}
}
module.exports = function(ctrl, color, runningColor) {
var time = ctrl.data[color];
return m('div', {
class: 'clock clock_' + color + ' ' + classSet({
'outoftime': !time,
'running': runningColor === color,
'emerg': time < ctrl.data.emerg
})
}, [
m('div.time', m.trust(formatClockTime(ctrl, time * 1000)))
]);
};
| var m = require('mithril');
var classSet = require('chessground').util.classSet;
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
function bold(x) {
return '<b>' + x + '</b>';
}
function formatClockTime(ctrl, time) {
var date = new Date(time);
var minutes = prefixInteger(date.getUTCMinutes(), 2);
var seconds = prefixInteger(date.getSeconds(), 2);
var tenths;
if (ctrl.data.showTenths && time < 10000) {
tenths = Math.floor(date.getMilliseconds() / 100);
return bold(minutes) + ':' + bold(seconds) + '<span>.' + bold(tenths) + '</span>';
} else if (time >= 3600000) {
var hours = prefixInteger(date.getUTCHours(), 2);
return bold(hours) + ':' + bold(minutes) + ':' + bold(seconds);
} else {
return bold(minutes) + ':' + bold(seconds);
}
}
module.exports = function(ctrl, color, runningColor) {
var time = ctrl.data[color];
return m('div', {
class: 'clock clock_' + color + ' ' + classSet({
'outoftime': !time,
'running': runningColor === color,
'emerg': time < ctrl.data.emerg
})
}, [
m('div.timer.before', {
style: {
width: Math.max(0, Math.min(100, (time / ctrl.data.initial) * 100)) + '%'
}
}),
m('div.time', m.trust(formatClockTime(ctrl, time * 1000)))
]);
};
| JavaScript | 0.000001 |
762a8d35db181f2f1c58415675b8f1c32eb61567 | Fix docs link | app/pages/HomePage/index.js | app/pages/HomePage/index.js | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import shouldPureComponentUpdate from 'react-pure-render/function';
import Button from 'Button';
import GettingStarted from 'GettingStarted';
import Features from 'Features';
import Contribute from 'Contribute';
import Logo from './react-boilerplate-logo.svg'
import styles from './styles.css';
export class HomePage extends React.Component {
shouldComponentUpdate = shouldPureComponentUpdate;
/**
* Changes the route
*
* @param {string} route The route we want to go to
*/
openRoute = (route) => {
this.props.changeRoute(route);
};
render() {
return (
<main className={ styles.homePage }>
<nav className={ styles.nav } >
<Button icon="download" outlined collapsable href="https://github.com/mxstbr/react-boilerplate/archive/master.zip">Download</Button>
<Button icon="book" href="https://github.com/mxstbr/react-boilerplate/tree/master/docs">Docs</Button>
<Button icon="github-logo" outlined collapsable href="https://github.com/mxstbr/react-boilerplate">Source</Button>
</nav>
<header className={ styles.header }>
<Logo className={ styles.logo }/>
<p>Quick setup for new performance orientated, offline–first React.js applications</p>
</header>
<article className={ styles.content }>
<GettingStarted />
<Features />
</article>
<Contribute />
</main>
);
}
}
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url)),
dispatch,
};
}
// Wrap the component to inject dispatch and state into it
export default connect(null, mapDispatchToProps)(HomePage);
| /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import shouldPureComponentUpdate from 'react-pure-render/function';
import Button from 'Button';
import GettingStarted from 'GettingStarted';
import Features from 'Features';
import Contribute from 'Contribute';
import Logo from './react-boilerplate-logo.svg'
import styles from './styles.css';
export class HomePage extends React.Component {
shouldComponentUpdate = shouldPureComponentUpdate;
/**
* Changes the route
*
* @param {string} route The route we want to go to
*/
openRoute = (route) => {
this.props.changeRoute(route);
};
render() {
return (
<main className={ styles.homePage }>
<nav className={ styles.nav } >
<Button icon="download" outlined collapsable href="https://github.com/mxstbr/react-boilerplate/archive/master.zip">Download</Button>
<Button icon="book">Docs</Button>
<Button icon="github-logo" outlined collapsable href="https://github.com/mxstbr/react-boilerplate">Source</Button>
</nav>
<header className={ styles.header }>
<Logo className={ styles.logo }/>
<p>Quick setup for new performance orientated, offline–first React.js applications</p>
</header>
<article className={ styles.content }>
<GettingStarted />
<Features />
</article>
<Contribute />
</main>
);
}
}
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url)),
dispatch,
};
}
// Wrap the component to inject dispatch and state into it
export default connect(null, mapDispatchToProps)(HomePage);
| JavaScript | 0 |
da9fe41e74a64eff77134979745b2081fd22155a | Clean up lint errors for ProSignup | client/src/components/Signup/ProSignup.js | client/src/components/Signup/ProSignup.js | import React, { Component } from 'react';
import { Button, Form, Grid, Header, Icon } from 'semantic-ui-react';
export default class ProSignup extends Component {
constructor() {
super();
}
render() {
return (
<div>
<div className="signup-buttons">
<Header textAlign="center"><Icon name="travel" />Professional Signup</Header>
</div>
<Grid width={16}>
<Grid.Column width={5} />
<Grid.Column width={11}>
<Form>
<Form.Field width="8">
<label htmlFor="password">First Name</label>
<input placeholder="First Name" />
</Form.Field>
<Form.Field width="8">
<label htmlFor="password">Last Name</label>
<input placeholder="Last Name" />
</Form.Field>
<Form.Field width="8">
<label htmlFor="password">Email</label>
<input placeholder="Email" />
</Form.Field>
<Form.Field width="8">
<label htmlFor="password">Password</label>
<input placeholder="Password" />
</Form.Field>
<Form.Field width="8">
<label htmlFor="password">Confirm Password</label>
<input placeholder="Confirm Password" />
</Form.Field>
<Form.Field width="8">
<Button type="submit">Sign Up</Button>
</Form.Field>
</Form>
</Grid.Column>
</Grid>
</div>
);
}
}
| import React, { Component } from 'react';
import { Button, Form, Grid, Header, Icon } from 'semantic-ui-react';
export default class ProSignup extends Component {
constructor() {
super()
}
render() {
return(
<div>
<div className="signup-buttons">
<Header textAlign='center'><Icon name="travel"/>Professional Signup</Header>
</div>
<Grid width={16}>
<Grid.Column width={5}>
</Grid.Column>
<Grid.Column width={11}>
<Form>
<Form.Field width="8">
<label>First Name</label>
<input placeholder='First Name' />
</Form.Field>
<Form.Field width="8">
<label>Last Name</label>
<input placeholder='Last Name' />
</Form.Field>
<Form.Field width="8">
<label>Email</label>
<input placeholder='Email' />
</Form.Field>
<Form.Field width="8">
<label>Password</label>
<input placeholder='Password' />
</Form.Field>
<Form.Field width="8">
<label>Confirm Password</label>
<input placeholder='Confirm Password' />
</Form.Field>
<Form.Field width="8">
<Button type='submit'>Sign Up</Button>
</Form.Field>
</Form>
</Grid.Column>
</Grid>
</div>
)
}
}
| JavaScript | 0 |
3ef8e6f1c4374320a25d9a3da5dbccc5a7d7f0d3 | Call initialize on original L.Map instead | src/leaflet.dataoptions.js | src/leaflet.dataoptions.js | //
// leaflet.dataoptions
//
// A Leaflet plugin that makes it easy to configure a Leaflet map using data
// attributes on the map's DOM element.
//
(function () {
function defineDataOptions(L) {
var LMapOrig = L.Map;
L.Map = L.Map.extend({
// Override the default constructor to get options from data
// attributes
initialize: function (id, options) {
// Get the data prefix for attribute names
var prefix = 'data-l-';
if (options !== undefined && options.dataOptionsPrefix !== undefined) {
prefix = options.dataOptionsPrefix;
}
// Find options given by data attribute, add to existing options
var dataAttributeOptions = this.loadDataAttributeOptions(id, prefix);
options = L.extend(dataAttributeOptions, options);
// Carry on as usual
LMapOrig.prototype.initialize.call(this, id, options);
},
loadDataAttributeOptions: function (id, prefix) {
var element = L.DomUtil.get(id),
attributes = element.attributes,
length = attributes.length,
newOptions = {};
for (var i = 0; i < length; i++) {
var attribute = attributes[i];
if (attribute.name.search(prefix) === 0) {
var name = attribute.name.slice(prefix.length),
camelCaseName = this.camelCaseDataAttributeName(name),
value = this.parseDataAttributeValue(attribute.value);
newOptions[camelCaseName] = newOptions[name] = value;
}
}
return newOptions;
},
camelCaseDataAttributeName: function (name) {
var nameParts = name.split('-'),
camelCaseName = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
camelCaseName += nameParts[i][0].toUpperCase();
camelCaseName += nameParts[i].slice(1);
}
return camelCaseName;
},
parseDataAttributeValue: function (value) {
try {
return JSON.parse(value);
}
catch (e) {
// If parsing as JSON fails, return original string
return value;
}
}
});
}
if (typeof define === 'function' && define.amd) {
// Try to add dataoptions to Leaflet using AMD
define(['leaflet'], function (L) {
defineDataOptions(L);
});
}
else {
// Else use the global L
defineDataOptions(L);
}
})();
| //
// leaflet.dataoptions
//
// A Leaflet plugin that makes it easy to configure a Leaflet map using data
// attributes on the map's DOM element.
//
(function () {
function defineDataOptions(L) {
L.Map = L.Map.extend({
// Override the default constructor to get options from data
// attributes
initialize: function (id, options) {
// Get the data prefix for attribute names
var prefix = 'data-l-';
if (options !== undefined && options.dataOptionsPrefix !== undefined) {
prefix = options.dataOptionsPrefix;
}
// Find options given by data attribute, add to existing options
var dataAttributeOptions = this.loadDataAttributeOptions(id, prefix);
options = L.extend(dataAttributeOptions, options);
// Carry on as usual
L.Map.__super__.initialize.call(this, id, options);
},
loadDataAttributeOptions: function (id, prefix) {
var element = L.DomUtil.get(id),
attributes = element.attributes,
length = attributes.length,
newOptions = {};
for (var i = 0; i < length; i++) {
var attribute = attributes[i];
if (attribute.name.search(prefix) === 0) {
var name = attribute.name.slice(prefix.length),
camelCaseName = this.camelCaseDataAttributeName(name),
value = this.parseDataAttributeValue(attribute.value);
newOptions[camelCaseName] = newOptions[name] = value;
}
}
return newOptions;
},
camelCaseDataAttributeName: function (name) {
var nameParts = name.split('-'),
camelCaseName = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
camelCaseName += nameParts[i][0].toUpperCase();
camelCaseName += nameParts[i].slice(1);
}
return camelCaseName;
},
parseDataAttributeValue: function (value) {
try {
return JSON.parse(value);
}
catch (e) {
// If parsing as JSON fails, return original string
return value;
}
}
});
}
if (typeof define === 'function' && define.amd) {
// Try to add dataoptions to Leaflet using AMD
define(['leaflet'], function (L) {
defineDataOptions(L);
});
}
else {
// Else use the global L
defineDataOptions(L);
}
})();
| JavaScript | 0 |
e769dbab4fd867d8b76f6bdf5061600f964e0db9 | Fix myCounterparts tests | client/tests/webdriver/pages/home.page.js | client/tests/webdriver/pages/home.page.js | import Page from "./page"
class Home extends Page {
get topbar() {
return browser.$("#topbar")
}
get ie11BannerText() {
const ieBanner = browser.$("#ieBanner")
ieBanner.waitForExist()
ieBanner.waitForDisplayed()
return browser.$("#ieBanner > div:nth-child(2)").getText()
}
get securityBanner() {
const banner = browser.$("#topbar .banner")
banner.waitForExist()
banner.waitForDisplayed()
return banner
}
get searchBar() {
return browser.$("#searchBarInput")
}
get homeTilesContainer() {
return browser.$("fieldset.home-tile-row")
}
get pendingMyApprovalOfCount() {
return browser
.$('//button[contains(text(), "Reports pending my approval")]')
.$("h1")
}
get submitSearch() {
return browser.$("#topbar #searchBarSubmit")
}
get linksMenuButton() {
return browser.$('//a[text()="My Work"]')
}
get myOrgLink() {
return browser.$("#my-organization")
}
get myTasksLink() {
return browser.$("#my-tasks-nav")
}
get myCounterpartsLink() {
return browser.$('//a//span[text()="My Counterparts"]')
}
get myCounterpartsNotifications() {
return this.myCounterpartsLink.$("span:last-child")
}
get myTasksNotifications() {
return this.myTasksLink.$("span:last-child")
}
get onboardingPopover() {
return browser.$(".hopscotch-bubble-container")
}
waitForSecurityBannerValue(value) {
this.securityBanner.waitForExist()
this.securityBanner.waitForDisplayed()
return browser.waitUntil(
() => {
return this.securityBanner.getText() === value
},
{ timeout: 5000, timeoutMsg: "Expected different banner text after 5s" }
)
}
}
export default new Home()
| import Page from "./page"
class Home extends Page {
get topbar() {
return browser.$("#topbar")
}
get ie11BannerText() {
const ieBanner = browser.$("#ieBanner")
ieBanner.waitForExist()
ieBanner.waitForDisplayed()
return browser.$("#ieBanner > div:nth-child(2)").getText()
}
get securityBanner() {
const banner = browser.$("#topbar .banner")
banner.waitForExist()
banner.waitForDisplayed()
return banner
}
get searchBar() {
return browser.$("#searchBarInput")
}
get homeTilesContainer() {
return browser.$("fieldset.home-tile-row")
}
get pendingMyApprovalOfCount() {
return browser
.$('//button[contains(text(), "Reports pending my approval")]')
.$("h1")
}
get submitSearch() {
return browser.$("#topbar #searchBarSubmit")
}
get linksMenuButton() {
return browser.$("#nav-links-button")
}
get myOrgLink() {
return browser.$("#my-organization")
}
get myTasksLink() {
return browser.$("#my-tasks-nav")
}
get myCounterpartsLink() {
return browser.$("#my-counterparts-nav")
}
get myCounterpartsNotifications() {
return this.myCounterpartsLink.$("span:last-child")
}
get myTasksNotifications() {
return this.myTasksLink.$("span:last-child")
}
get onboardingPopover() {
return browser.$(".hopscotch-bubble-container")
}
waitForSecurityBannerValue(value) {
this.securityBanner.waitForExist()
this.securityBanner.waitForDisplayed()
return browser.waitUntil(
() => {
return this.securityBanner.getText() === value
},
{ timeout: 5000, timeoutMsg: "Expected different banner text after 5s" }
)
}
}
export default new Home()
| JavaScript | 0 |
a09eae7d085e53a5e0e9f60e6becbcf3e3e45515 | combine routing reducer | app/store/configureStore.js | app/store/configureStore.js | import { combineReducers, createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { routeReducer } from 'redux-simple-router'
import rootReducer from '../reducers'
import DevTools from '../components/DevTools' // make it NODE_ENV-dependent
// let redux store the current URL
const reducer = combineReducers(Object.assign({}, rootReducer, {
routing: routeReducer
}))
const finalCreateStore = getCreateStoreModifier()(createStore)
export default (initialState) => finalCreateStore(reducer, initialState)
function getCreateStoreModifier () {
if (process.env.NODE_ENV === 'development') {
return compose(
applyMiddleware(thunk),
DevTools.instrument()
)
} else {
return applyMiddleware(thunk)
}
}
| import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
import DevTools from '../components/DevTools' // make it NODE_ENV-dependent
const finalCreateStore = getCreateStoreModifier()(createStore)
export default (initialState) => finalCreateStore(rootReducer, initialState)
function getCreateStoreModifier () {
if (process.env.NODE_ENV === 'development') {
return compose(
applyMiddleware(thunk),
DevTools.instrument()
)
} else {
return applyMiddleware(thunk)
}
}
| JavaScript | 0.000001 |
dfcafb7b0037abc6bb4cbff5639bdb836c6a62d0 | update analytics code | public/javascripts/analytics_lib.js | public/javascripts/analytics_lib.js | /*------------------------------------------------------------------+
| Utilizes event tracking in Google Analytics to track |
| clicks on outbound, document, and email links. |
| Requires jQuery |
+-------------------------------------------------------------------*/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31505617-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
_trackClickEventWithGA = function (category, action, label) {
if (typeof(_gaq) != 'undefined')
_gaq.push(['_setAccount', 'UA-31505617-1']);
_gaq.push(['_trackEvent', category, action, label]);
};
jQuery(function () {
jQuery('a').click(function () {
var $a = jQuery(this);
var href = $a.attr("href");
//links going to outside sites
if (href.match(/^http/i) && !href.match(document.domain)) {
_trackClickEventWithGA("Outgoing", "Click", href);
}
//direct links to files
if (href.match(/\.(avi|css|doc|docx|exe|gif|js|jpg|mov|mp3|pdf|png|ppt|pptx|rar|txt|vsd|vxd|wma|wmv|xls|xlsx|zip)$/i)) {
_trackClickEventWithGA("Downloads", "Click", href);
}
//email links
if (href.match(/^mailto:/i)) {
_trackClickEventWithGA("Emails", "Click", href);
}
});
});
| /*------------------------------------------------------------------+
| Utilizes event tracking in Google Analytics to track |
| clicks on outbound, document, and email links. |
| Requires jQuery |
+-------------------------------------------------------------------*/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31505617-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
_trackClickEventWithGA = function (category, action, label) {
if (typeof(_gaq) != 'undefined')
_gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);
_gaq.push(['_trackEvent', category, action, label]);
};
jQuery(function () {
jQuery('a').click(function () {
var $a = jQuery(this);
var href = $a.attr("href");
//links going to outside sites
if (href.match(/^http/i) && !href.match(document.domain)) {
_trackClickEventWithGA("Outgoing", "Click", href);
}
//direct links to files
if (href.match(/\.(avi|css|doc|docx|exe|gif|js|jpg|mov|mp3|pdf|png|ppt|pptx|rar|txt|vsd|vxd|wma|wmv|xls|xlsx|zip)$/i)) {
_trackClickEventWithGA("Downloads", "Click", href);
}
//email links
if (href.match(/^mailto:/i)) {
_trackClickEventWithGA("Emails", "Click", href);
}
});
});
| JavaScript | 0 |
df21ff82b5e2c460cc71571a1cfaf7487c8c5e28 | add new line | dashboard/test/unit/test_refresh.js | dashboard/test/unit/test_refresh.js | /*
* Copyright 2015 Telefónica I+D
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
'use strict';
var assert = require('assert'),
sinon = require('sinon'),
http = require('http'),
common = require('../../lib/routes/common'),
refresh = require('../../lib/routes/refresh');
/* jshint multistr: true */
suite('refresh', function () {
test('test_get_refresh', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = "Admin";
var request_stub = sinon.stub();
var http_stub = sinon.stub(http, 'request').returns(request_stub);
request_stub.on = sinon.stub();
request_stub.write = sinon.stub();
request_stub.end = sinon.stub();
//when
refresh.get_refresh(req, res);
//then
assert(request_stub.on.calledOnce);
assert(request_stub.write.calledOnce);
assert(request_stub.end.calledOnce);
http_stub.restore();
});
test('test_get_refresh_with_undefined_role', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = undefined;
var common_stub = sinon.stub(common, 'notAuthorized');
//when
refresh.get_refresh(req, res);
//then
assert(common_stub.calledOnce);
common_stub.restore();
});
});
| /*
* Copyright 2015 Telefónica I+D
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
'use strict';
var assert = require('assert'),
sinon = require('sinon'),
http = require('http'),
common = require('../../lib/routes/common'),
refresh = require('../../lib/routes/refresh');
/* jshint multistr: true */
suite('refresh', function () {
test('test_get_refresh', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = "Admin";
var request_stub = sinon.stub();
var http_stub = sinon.stub(http, 'request').returns(request_stub);
request_stub.on = sinon.stub();
request_stub.write = sinon.stub();
request_stub.end = sinon.stub();
//when
refresh.get_refresh(req, res);
//then
assert(request_stub.on.calledOnce);
assert(request_stub.write.calledOnce);
assert(request_stub.end.calledOnce);
http_stub.restore();
});
test('test_get_refresh_with_undefined_role', function () {
//given
var req = sinon.stub(),
res = sinon.stub();
req.param = sinon.stub().returns("region1");
req.session = sinon.stub();
req.session.role = undefined;
var common_stub = sinon.stub(common, 'notAuthorized');
//when
refresh.get_refresh(req, res);
//then
assert(common_stub.calledOnce);
common_stub.restore();
});
});
| JavaScript | 0.002414 |
69f21295477743d5be7b191c4bae5e15db081315 | Remove the toLowerCase function call as it doesn't work on this object, and it's going to be lower case anyway | generators/aws/lib/s3.js | generators/aws/lib/s3.js | const fs = require('fs');
const FILE_EXTENSION = '.original';
const S3_STANDARD_REGION = 'us-east-1';
let Progressbar;
const S3 = module.exports = function S3(Aws, generator) {
this.Aws = Aws;
try {
Progressbar = require('progress'); // eslint-disable-line
} catch (e) {
generator.error(`Something went wrong while running jhipster:aws:\n${e}`);
}
};
S3.prototype.createBucket = function createBucket(params, callback) {
const bucket = params.bucket;
const region = this.Aws.config.region;
const s3Params = {
Bucket: bucket,
CreateBucketConfiguration: { LocationConstraint: region }
};
if (region === S3_STANDARD_REGION) {
s3Params.CreateBucketConfiguration = undefined;
}
const s3 = new this.Aws.S3({
params: s3Params,
signatureVersion: 'v4'
});
s3.headBucket((err) => {
if (err && err.statusCode === 404) {
s3.createBucket((err) => {
if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} created successfully`, callback);
}
});
} else if (err && err.statusCode === 301) {
error(`Bucket ${bucket} is already in use`, callback);
} else if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} already exists`, callback);
}
});
};
S3.prototype.uploadWar = function uploadWar(params, callback) {
const bucket = params.bucket;
const buildTool = params.buildTool;
let buildFolder;
if (buildTool === 'gradle') {
buildFolder = 'build/libs/';
} else {
buildFolder = 'target/';
}
findWarFilename(buildFolder, (err, warFilename) => {
if (err) {
error(err, callback);
} else {
const warKey = warFilename.slice(0, -FILE_EXTENSION.length);
const s3 = new this.Aws.S3({
params: {
Bucket: bucket,
Key: warKey
},
signatureVersion: 'v4',
httpOptions: { timeout: 600000 }
});
const filePath = buildFolder + warFilename;
const body = fs.createReadStream(filePath);
uploadToS3(s3, body, (err, message) => {
if (err) {
error(err.message, callback);
} else {
callback(null, { message, warKey });
}
});
}
});
};
function findWarFilename(buildFolder, callback) {
let warFilename = '';
fs.readdir(buildFolder, (err, files) => {
if (err) {
error(err, callback);
}
files
.filter(file => file.substr(-FILE_EXTENSION.length) === FILE_EXTENSION)
.forEach((file) => {
warFilename = file;
});
callback(null, warFilename);
});
}
function uploadToS3(s3, body, callback) {
let bar;
s3.waitFor('bucketExists', (err) => {
if (err) {
callback(err, null);
} else {
s3.upload({ Body: body }).on('httpUploadProgress', (evt) => {
if (bar === undefined && evt.total) {
const total = evt.total / 1000000;
bar = new Progressbar('uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 20,
total,
clear: true
});
}
const curr = evt.loaded / 1000000;
bar.tick(curr - bar.curr);
}).send((err) => {
if (err) {
callback(err, null);
} else {
callback(null, 'War uploaded successful');
}
});
}
});
}
function success(message, callback) {
callback(null, { message });
}
function error(message, callback) {
callback({ message }, null);
}
| const fs = require('fs');
const FILE_EXTENSION = '.original';
const S3_STANDARD_REGION = 'us-east-1';
let Progressbar;
const S3 = module.exports = function S3(Aws, generator) {
this.Aws = Aws;
try {
Progressbar = require('progress'); // eslint-disable-line
} catch (e) {
generator.error(`Something went wrong while running jhipster:aws:\n${e}`);
}
};
S3.prototype.createBucket = function createBucket(params, callback) {
const bucket = params.bucket;
const region = this.Aws.config.region;
const s3Params = {
Bucket: bucket,
CreateBucketConfiguration: { LocationConstraint: region }
};
if (region.toLowerCase() === S3_STANDARD_REGION) {
s3Params.CreateBucketConfiguration = undefined;
}
const s3 = new this.Aws.S3({
params: s3Params,
signatureVersion: 'v4'
});
s3.headBucket((err) => {
if (err && err.statusCode === 404) {
s3.createBucket((err) => {
if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} created successfully`, callback);
}
});
} else if (err && err.statusCode === 301) {
error(`Bucket ${bucket} is already in use`, callback);
} else if (err) {
error(err.message, callback);
} else {
success(`Bucket ${bucket} already exists`, callback);
}
});
};
S3.prototype.uploadWar = function uploadWar(params, callback) {
const bucket = params.bucket;
const buildTool = params.buildTool;
let buildFolder;
if (buildTool === 'gradle') {
buildFolder = 'build/libs/';
} else {
buildFolder = 'target/';
}
findWarFilename(buildFolder, (err, warFilename) => {
if (err) {
error(err, callback);
} else {
const warKey = warFilename.slice(0, -FILE_EXTENSION.length);
const s3 = new this.Aws.S3({
params: {
Bucket: bucket,
Key: warKey
},
signatureVersion: 'v4',
httpOptions: { timeout: 600000 }
});
const filePath = buildFolder + warFilename;
const body = fs.createReadStream(filePath);
uploadToS3(s3, body, (err, message) => {
if (err) {
error(err.message, callback);
} else {
callback(null, { message, warKey });
}
});
}
});
};
function findWarFilename(buildFolder, callback) {
let warFilename = '';
fs.readdir(buildFolder, (err, files) => {
if (err) {
error(err, callback);
}
files
.filter(file => file.substr(-FILE_EXTENSION.length) === FILE_EXTENSION)
.forEach((file) => {
warFilename = file;
});
callback(null, warFilename);
});
}
function uploadToS3(s3, body, callback) {
let bar;
s3.waitFor('bucketExists', (err) => {
if (err) {
callback(err, null);
} else {
s3.upload({ Body: body }).on('httpUploadProgress', (evt) => {
if (bar === undefined && evt.total) {
const total = evt.total / 1000000;
bar = new Progressbar('uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 20,
total,
clear: true
});
}
const curr = evt.loaded / 1000000;
bar.tick(curr - bar.curr);
}).send((err) => {
if (err) {
callback(err, null);
} else {
callback(null, 'War uploaded successful');
}
});
}
});
}
function success(message, callback) {
callback(null, { message });
}
function error(message, callback) {
callback({ message }, null);
}
| JavaScript | 0.000008 |
ebbbb7a7721f62bfa9580199ce4af29c41d91daa | Add jsdoc. | common/models/member.js | common/models/member.js | var loopback = require('loopback');
var path = require('path');
var debug = require('debug')('freecoder:member');
module.exports = function (Member) {
// send verification email after registration
// refer to http://docs.strongloop.com/display/public/LB/Remote+hooks
Member.afterRemote('create', function (context, member, next) {
debug('> Member.afterRemote("create") triggered');
var options = {
type: 'email',
to: member.email,
from: 'support@freecoder.net', //TODO: read from configuration
subject: 'Thanks for registering.',
template: path.resolve(__dirname, '../../server/email_templates/registration_verify.ejs'),
redirect: encodeURIComponent('/#/dashboard')
};
member.verify(options, function (err, response) {
if (err) {
next(err);
return;
}
debug('>> verification email sent:', response);
next();
});
});
/**
* Change user password by verify old password first.
* @param access_token
* @param options
* @param cb
*/
Member.changePassword = function (access_token, options, cb) {
debug('> Member.changePassword().', access_token, options);
Member.validatePassword(options.oldPass);
Member.validatePassword(options.newPass);
var ctx = loopback.getCurrentContext();
var accessToken = ctx.get('accessToken');
var userId = accessToken.userId;
this.findById(userId, function (err, user) {
if (err) {
cb(err);
}
debug(">> get User:", user);
user.hasPassword(options.oldPass, function (err, isMatch) {
if (err) {
debug('>> verify old password failed: ', err);
cb(err);
}
if (isMatch) {
user.password = Member.hashPassword(options.newPass);
user.save(function (err) {
if (err) {
cb(err);
} else {
debug('>> change password successful.');
cb();
}
});
} else {
cb('Invalid password.');
}
});
});
};
/**
* Define REST API for change password.
*/
Member.remoteMethod('changePassword', {
description: "Change password by verify current password.",
http: {verb: 'post', path: '/changePassword'},
accepts: [
{
arg: 'access_token', type: 'string', required: true, http: function (ctx) {
var req = ctx && ctx.req;
var accessToken = req && req.accessToken;
var tokenID = accessToken && accessToken.id;
return tokenID;
}
},
{arg: 'options', type: 'object', required: true, http: {source: 'body'}}
],
returns: {}
})
};
| var loopback = require('loopback');
var path = require('path');
var debug = require('debug')('freecoder:member');
module.exports = function (Member) {
// send verification email after registration
// refer to http://docs.strongloop.com/display/public/LB/Remote+hooks
Member.afterRemote('create', function (context, member, next) {
debug('> Member.afterRemote("create") triggered');
var options = {
type: 'email',
to: member.email,
from: 'support@freecoder.net', //TODO: read from configuration
subject: 'Thanks for registering.',
template: path.resolve(__dirname, '../../server/email_templates/registration_verify.ejs'),
redirect: encodeURIComponent('/#/dashboard')
};
member.verify(options, function (err, response) {
if (err) {
next(err);
return;
}
debug('>> verification email sent:', response);
next();
});
});
Member.changePassword = function (access_token, options, cb) {
debug('> Member.changePassword().', access_token, options);
Member.validatePassword(options.oldPass);
Member.validatePassword(options.newPass);
//if (!options.oldPass || !options.newPass) {
// var msg = 'oldPass or newPass is invalid.';
// debug(msg);
// cb(msg)
//}
var ctx = loopback.getCurrentContext();
var accessToken = ctx.get('accessToken');
var userId = accessToken.userId;
this.findById(userId, function (err, user) {
if (err) {
cb(err);
}
debug(">> get User:", user);
user.hasPassword(options.oldPass, function (err, isMatch) {
if (err) {
debug('>> verify old password failed: ', err);
cb(err);
}
if (isMatch) {
user.password = Member.hashPassword(options.newPass);
user.save(function (err) {
if (err) {
cb(err);
} else {
debug('>> change password successful.');
cb();
}
});
} else {
cb('Invalid password.');
}
});
});
};
Member.remoteMethod('changePassword', {
description: "Change password by verify current password.",
http: {verb: 'post', path: '/changePassword'},
accepts: [
{
arg: 'access_token', type: 'string', required: true, http: function (ctx) {
var req = ctx && ctx.req;
var accessToken = req && req.accessToken;
var tokenID = accessToken && accessToken.id;
return tokenID;
}
},
{arg: 'options', type: 'object', required: true, http: {source: 'body'}}
],
returns: {}
})
};
| JavaScript | 0 |
8585bda908d0e675841c992686be2dd1ab63e415 | Update items.js | data/items.js | data/items.js | items =
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
"35.179436",
"31.763183"
]
},
"type": "Feature",
"properties": {
"text": "פרג זיפני",
"image": "data/photos/1.JPG"
}
},
{
"geometry": {
"type": "Point",
"coordinates": [
"35.178672",
"31.765298"
]
},
"type": "Feature",
"properties": {
"text": "זעחן פרחוני",
"image": "data/photos/2.JPG"
}
},
]
}
| items =
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
"35.179436",
"31.763183"
]
},
"type": "Feature",
"properties": {
"text": "פרג זיפני",
"image": "data/photos/1.JPG"
}
},
]
} | JavaScript | 0.000001 |
ca5eb976d37fe3870dd2cfbdea33ef05e70b0f13 | handle synchronous exceptions in indexedDB openDatabase method | src/lib/store/indexedDb.js | src/lib/store/indexedDb.js | define(['../util', './pending'], function(util, pendingAdapter) {
var DB_NAME = 'remoteStorage';
var DB_VERSION = 1;
var OBJECT_STORE_NAME = 'nodes';
var logger = util.getLogger('store::indexed_db');
var adapter = function(indexedDB) {
if(! indexedDB) {
throw new Error("Not supported: indexedDB not found");
}
var DB = undefined;
function removeDatabase() {
return util.makePromise(function(promise) {
if(DB) {
try {
DB.close();
} catch(exc) {
// ignored.
};
DB = undefined;
}
var request = indexedDB.deleteDatabase(DB_NAME);
request.onsuccess = function() {
promise.fulfill();
};
request.onerror = function() {
promise.fail();
};
});
}
function openDatabase() {
logger.info("Opening database " + DB_NAME + '@' + DB_VERSION);
return util.makePromise(function(promise) {
var dbRequest = indexedDB.open(DB_NAME, DB_VERSION);
function upgrade(db) {
db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'key' });
}
dbRequest.onupgradeneeded = function(event) {
upgrade(event.target.result);
};
dbRequest.onsuccess = function(event) {
try {
var database = event.target.result;
if(typeof(database.setVersion) === 'function') {
if(database.version != DB_VERSION) {
var versionRequest = database.setVersion(DB_VERSION);
versionRequest.onsuccess = function(event) {
upgrade(database);
event.target.transaction.oncomplete = function() {
promise.fulfill(database);
};
};
} else {
promise.fulfill(database);
}
} else {
// assume onupgradeneeded is supported.
promise.fulfill(database);
}
} catch(exc) {
promise.fail(exc);
};
};
dbRequest.onerror = function(event) {
logger.error("indexedDB.open failed: ", event);
promise.fail(new Error("Failed to open database!"));
};
});
}
function storeRequest(methodName) {
var args = Array.prototype.slice.call(arguments, 1);
return util.makePromise(function(promise) {
var store = DB.transaction(OBJECT_STORE_NAME, 'readwrite').
objectStore(OBJECT_STORE_NAME);
var request = store[methodName].apply(store, args);
request.onsuccess = function() {
promise.fulfill(request.result);
};
request.onerror = function(event) {
promise.fail(event.error);
};
});
}
var indexedDbStore = {
on: function(eventName, handler) {
logger.debug("WARNING: indexedDB event handling not implemented");
},
get: function(key) {
logger.debug("GET " + key);
return storeRequest('get', key);
},
set: function(key, value) {
logger.debug("SET " + key);
var node = value;
node.key = key;
return storeRequest('put', node);
},
remove: function(key) {
logger.debug("REMOVE " + key);
return storeRequest('delete', key);
},
forgetAll: function() {
logger.debug("FORGET ALL");
return removeDatabase().then(doOpenDatabase);
}
};
var tempStore = pendingAdapter();
function replaceAdapter() {
if(tempStore.flush) {
tempStore.flush(indexedDbStore);
util.extend(tempStore, indexedDbStore);
}
}
function doOpenDatabase() {
openDatabase().
then(function(db) {
logger.info("Database opened.");
DB = db;
replaceAdapter();
});
}
doOpenDatabase();
return tempStore;
};
adapter.detect = function() {
var indexedDB = undefined;
if(typeof(window) !== 'undefined') {
indexedDB = (window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.msIndexedDB);
}
return indexedDB;
}
return adapter;
});
| define(['../util', './pending'], function(util, pendingAdapter) {
var DB_NAME = 'remoteStorage';
var DB_VERSION = 1;
var OBJECT_STORE_NAME = 'nodes';
var logger = util.getLogger('store::indexed_db');
var adapter = function(indexedDB) {
if(! indexedDB) {
throw new Error("Not supported: indexedDB not found");
}
var DB = undefined;
function removeDatabase() {
return util.makePromise(function(promise) {
if(DB) {
try {
DB.close();
} catch(exc) {
// ignored.
};
DB = undefined;
}
var request = indexedDB.deleteDatabase(DB_NAME);
request.onsuccess = function() {
promise.fulfill();
};
request.onerror = function() {
promise.fail();
};
});
}
function openDatabase() {
logger.info("Opening database " + DB_NAME + '@' + DB_VERSION);
return util.makePromise(function(promise) {
var dbRequest = indexedDB.open(DB_NAME, DB_VERSION);
function upgrade(db) {
db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'key' });
}
dbRequest.onupgradeneeded = function(event) {
upgrade(event.target.result);
};
dbRequest.onsuccess = function(event) {
var database = event.target.result;
if(typeof(database.setVersion) === 'function') {
if(database.version != DB_VERSION) {
var versionRequest = database.setVersion(DB_VERSION);
versionRequest.onsuccess = function(event) {
upgrade(database);
event.target.transaction.oncomplete = function() {
promise.fulfill(database);
};
};
} else {
promise.fulfill(database);
}
} else {
// assume onupgradeneeded is supported.
promise.fulfill(database);
}
};
dbRequest.onerror = function(event) {
logger.error("indexedDB.open failed: ", event);
promise.fail(new Error("Failed to open database!"));
};
});
}
function storeRequest(methodName) {
var args = Array.prototype.slice.call(arguments, 1);
return util.makePromise(function(promise) {
var store = DB.transaction(OBJECT_STORE_NAME, 'readwrite').
objectStore(OBJECT_STORE_NAME);
var request = store[methodName].apply(store, args);
request.onsuccess = function() {
promise.fulfill(request.result);
};
request.onerror = function(event) {
promise.fail(event.error);
};
});
}
var indexedDbStore = {
on: function(eventName, handler) {
logger.debug("WARNING: indexedDB event handling not implemented");
},
get: function(key) {
logger.debug("GET " + key);
return storeRequest('get', key);
},
set: function(key, value) {
logger.debug("SET " + key);
var node = value;
node.key = key;
return storeRequest('put', node);
},
remove: function(key) {
logger.debug("REMOVE " + key);
return storeRequest('delete', key);
},
forgetAll: function() {
logger.debug("FORGET ALL");
return removeDatabase().then(doOpenDatabase);
}
};
var tempStore = pendingAdapter();
function replaceAdapter() {
if(tempStore.flush) {
tempStore.flush(indexedDbStore);
util.extend(tempStore, indexedDbStore);
}
}
function doOpenDatabase() {
openDatabase().
then(function(db) {
logger.info("Database opened.");
DB = db;
replaceAdapter();
});
}
doOpenDatabase();
return tempStore;
};
adapter.detect = function() {
var indexedDB = undefined;
if(typeof(window) !== 'undefined') {
indexedDB = (window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB || window.msIndexedDB);
}
return indexedDB;
}
return adapter;
});
| JavaScript | 0.000001 |
d403669be0f6cf25ee198e3dfc34b7182dea8470 | Update index.js | projects/acc/js/index.js | projects/acc/js/index.js | if ('Accelerometer' in window && 'Gyroscope' in window) {
//document.getElementById('moApi').innerHTML = 'Generic Sensor API';
let accelerometer = new Accelerometer();
accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
accelerometer.start();
let accelerometerWithGravity = new Accelerometer({includeGravity: true});
accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
accelerometerWithGravity.start();
let gyroscope = new Gyroscope();
gyroscope.addEventListener('reading', e => rotationHandler({
alpha: gyroscope.x,
beta: gyroscope.y,
gamma: gyroscope.z
}));
gyroscope.start();
intervalHandler('Not available in Generic Sensor API');
} else if ('DeviceMotionEvent' in window) {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'Device Motion API';
window.addEventListener('devicemotion', function (eventData) {
accelerationHandler(eventData.acceleration, 'moAccel');
MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
rotationHandler(eventData.rotationRate);
intervalHandler(eventData.interval);
}, false);
} else {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}
function accelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
//document.getElementById(targetId).innerHTML = info;
}
function MaccelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
var zz = (acceleration.z && acceleration.z.toFixed(3));
if (zz>10) {
x = 1;
var timer = setInterval(function change() {
if (x === 1) {
color = "#ffffff";
x = 2;
} else {
color = "#000000";
x = 1;
}
document.body.style.background = color;
}, 50);
setTimeout(function() {
clearInterval(timer);
}, 1000);
}
}
function rotationHandler(rotation) {
var info, xyz = "[X, Y, Z]";
//info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
//info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
//info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
var xx = (rotation.alpha && rotation.alpha.toFixed(3));
var yy = (rotation.beta && rotation.beta.toFixed(3));
var zz = (rotation.gamma && rotation.gamma.toFixed(3));
var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
//document.getElementById("mean").innerHTML = mean;
//document.getElementById("moRotation").innerHTML = info;
}
function intervalHandler(interval) {
//document.getElementById("moInterval").innerHTML = interval;
}
if (location.href.indexOf('debug') !== -1) {
//document.getElementById('alert').style.display = 'none';
}
| if ('Accelerometer' in window && 'Gyroscope' in window) {
//document.getElementById('moApi').innerHTML = 'Generic Sensor API';
let accelerometer = new Accelerometer();
accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
accelerometer.start();
let accelerometerWithGravity = new Accelerometer({includeGravity: true});
accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
accelerometerWithGravity.start();
let gyroscope = new Gyroscope();
gyroscope.addEventListener('reading', e => rotationHandler({
alpha: gyroscope.x,
beta: gyroscope.y,
gamma: gyroscope.z
}));
gyroscope.start();
intervalHandler('Not available in Generic Sensor API');
} else if ('DeviceMotionEvent' in window) {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'Device Motion API';
window.addEventListener('devicemotion', function (eventData) {
accelerationHandler(eventData.acceleration, 'moAccel');
MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
rotationHandler(eventData.rotationRate);
intervalHandler(eventData.interval);
}, false);
} else {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}
function accelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
//document.getElementById(targetId).innerHTML = info;
}
function MaccelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
var zz = (acceleration.z && acceleration.z.toFixed(3));
if (zz>10) {
x = 1;
var timer = setInterval(function change() {
if (x === 1) {
color = "#ffffff";
x = 2;
} else {
color = "#000000";
x = 1;
}
document.body.style.background = color;
}, 50);
setTimeout(function() {
clearInterval(timer);
}, 1000);
document.body.style.background = #000000;
}
}
function rotationHandler(rotation) {
var info, xyz = "[X, Y, Z]";
//info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
//info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
//info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
var xx = (rotation.alpha && rotation.alpha.toFixed(3));
var yy = (rotation.beta && rotation.beta.toFixed(3));
var zz = (rotation.gamma && rotation.gamma.toFixed(3));
var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
//document.getElementById("mean").innerHTML = mean;
//document.getElementById("moRotation").innerHTML = info;
}
function intervalHandler(interval) {
//document.getElementById("moInterval").innerHTML = interval;
}
if (location.href.indexOf('debug') !== -1) {
//document.getElementById('alert').style.display = 'none';
}
| JavaScript | 0.000002 |
ae7402422a690d9e34ae9fb07eb1b42f95b77c03 | remove e2e files in karma | app/templates/karma.conf.js | app/templates/karma.conf.js | 'use strict';
module.exports = function (config) {
config.set({
basePath: 'client',
frameworks: ['jasmine'],
preprocessors: {
'**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/',
moduleName: 'templates'
},
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',<% if (filters.ngAnimate) { %>
'bower_components/angular-animate/angular-animate.js',<% } if (filters.ngSanitize) { %>
'bower_components/angular-sanitize/angular-sanitize.js',<% } if (filters.ngCookies) { %>
'bower_components/angular-cookies/angular-cookies.js',<% } if (filters.ngResource) { %>
'bower_components/angular-resource/angular-resource.js',<% } if (filters.sockets) { %>
'bower_components/angular-socket-io/socket.min.js',<% } %>
'app.js',
'views/**/*.js',
'services/**/*.js',
'directives/**/*.js',
'directives/**/*.html',
'filters/**/*.js'
],
exclude: [
'views/**/*.e2e.js'<% if (filters.sockets) { %>,
'services/socket/socket.service.js'<% } %>
],
reporters: ['progress'],
port: 9876,
colors: true,
// possible values:
// config.LOG_DISABLE
// config.LOG_ERROR
// config.LOG_WARN
// config.LOG_INFO
// config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
| 'use strict';
module.exports = function (config) {
config.set({
basePath: 'client',
frameworks: ['jasmine'],
preprocessors: {
'**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/',
moduleName: 'templates'
},
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',<% if (filters.ngAnimate) { %>
'bower_components/angular-animate/angular-animate.js',<% } if (filters.ngSanitize) { %>
'bower_components/angular-sanitize/angular-sanitize.js',<% } if (filters.ngCookies) { %>
'bower_components/angular-cookies/angular-cookies.js',<% } if (filters.ngResource) { %>
'bower_components/angular-resource/angular-resource.js',<% } if (filters.sockets) { %>
'bower_components/angular-socket-io/socket.min.js',<% } %>
'app.js',
'views/**/*.js',
'services/**/*.js',
'directives/**/*.js',
'directives/**/*.html',
'filters/**/*.js'
],<% if (filters.sockets) { %>
exclude: [
'services/socket/socket.service.js',
],<% } %>
reporters: ['progress'],
port: 9876,
colors: true,
// possible values:
// config.LOG_DISABLE
// config.LOG_ERROR
// config.LOG_WARN
// config.LOG_INFO
// config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
| JavaScript | 0 |
0c5e03f8245ff12f8e81d7f784083f75062aa734 | call to Places Details API working; need to incorporate it into map initialization and remove calls to Geocoding API | public/scripts/models/google_map.js | public/scripts/models/google_map.js | 'use strict';
const GOOGLE_GEOCODE_API_KEY = 'AIzaSyB3ds8lw9KjCDvLxfBCj5EpU52-5nGUe_Q';
const GOOGLE_PLACES_API_KEY = 'AIzaSyABR5dsVE6XNT0UOAKI_qmSC4_p0jPShQM';
const locations = [
{
title: 'Fly Awake Tea'
},
{
title: 'Tao of Tea'
},
{
title: 'Heavens Tea, School of Tea Arts'
}
];
//this is how we ping the google geocode API with a shop name and it returns the latLng
function geocodeUrl(title) {
return `https://maps.googleapis.com/maps/api/geocode/json?address=${title}&key=${GOOGLE_GEOCODE_API_KEY}`;
}
function placesUrl(title) {
return `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${title}&key=${GOOGLE_PLACES_API_KEY}`
}
function placeDetailsUrl(id) {
return `https://maps.googleapis.com/maps/api/place/details/json?placeid=${id}&key=${GOOGLE_PLACES_API_KEY}`
}
function initMap() {
//initialize map and center it
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 45.549863, lng: -122.675790},
scrollwheel: false
});
//loop through locations array and convert title to latLng
for (let i = 0; i < locations.length; i++) {
let url = geocodeUrl(locations[i].title);
//set marker for each shop
$.get(url).done(function (response) {
// console.log('Geocode response: ', response);
//create marker for shop
let marker = new google.maps.Marker({
position: response.results[0].geometry.location,
map: map,
});
//create info window for marker
let infoWindow = new google.maps.InfoWindow({
content: `<p>${locations[i].title}</p>
<p>${response.results[0].formatted_address}</p>`,
maxWidth: 120
});
//click handler to open info windows
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
});
}
//re-center map upon window resize
google.maps.event.addDomListener(window, 'resize', function() {
const center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
//working, now need to incorporate this into the for loop and replace geocoding API
let place = placesUrl(locations[0].title);
$.get(`https://crossorigin.me/${place}`).done(function(response) {
let placeId = response.results[0].place_id;
let placeIdUrl = placeDetailsUrl(placeId);
$.get(`https://crossorigin.me/${placeIdUrl}`).done(function(response) {
console.log('Place Details response: ', response);
});
});
}
| 'use strict';
const GOOGLE_GEOCODE_API_KEY = 'AIzaSyB3ds8lw9KjCDvLxfBCj5EpU52-5nGUe_Q';
const GOOGLE_PLACES_API_KEY = 'AIzaSyABR5dsVE6XNT0UOAKI_qmSC4_p0jPShQM';
const locations = [
{
title: 'Fly Awake Tea'
},
{
title: 'Tao of Tea'
},
{
title: 'Heavens Tea, School of Tea Arts'
}
];
//this is how we ping the google geocode API with a shop name and it returns the latLng
function geocodeUrl(title) {
return `https://maps.googleapis.com/maps/api/geocode/json?address=${title}&key=${GOOGLE_GEOCODE_API_KEY}`;
}
function placesUrl(title) {
return `https://maps.googleapis.com/maps/api/place/textsearch/xml?query=${title}&key=${GOOGLE_PLACES_API_KEY}`
}
function initMap() {
//initialize map and center it
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 45.549863, lng: -122.675790},
scrollwheel: false
});
//loop through locations array and convert title to latLng
for (let i = 0; i < locations.length; i++) {
let url = geocodeUrl(locations[i].title);
//set marker for each shop
$.get(url).done(function (response) {
//create marker for shop
let marker = new google.maps.Marker({
position: response.results[0].geometry.location,
map: map,
});
//create info window for marker
let infoWindow = new google.maps.InfoWindow({
content: `<p>${locations[i].title}</p>
<p>${response.results[0].formatted_address}</p>`,
maxWidth: 120
});
//click handler to open info windows
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
});
}
//re-center map upon window resize
google.maps.event.addDomListener(window, 'resize', function() {
const center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
let place = placesUrl(locations[0].title);
$.get(place).done(function(response) {
console.log(response);
});
}
| JavaScript | 0 |
8dd3dc991f5895d3cc511d2db4f88e44cddd8b62 | add special variable test cases for rename.js | rename.js | rename.js | "use strict";
class Env {
constructor(outer, k, v) {
this.outer = outer;
this.k = k;
this.v = v;
}
get(key) {
return (key == this.k) ? this.v : this.outer.get(key);
}
static empty() { return new Env(new Map()); }
}
class NextVar {
constructor() { this.nextVar = 0; }
next() { return "_" + (this.nextVar++); }
}
function rename0(exp, env, nextVar) {
if (exp[0] == "var") {
var v = env.get(exp[1]);
return ["var", (v == undefined) ? nextVar.next() : v];
} else if (exp[0] == "lam") {
var v = nextVar.next();
var newEnv = new Env(env, exp[1], v);
return ["lam", v, rename0(exp[2], newEnv, nextVar)];
} else if (exp[0] == "app") {
return ["app", rename0(exp[1], env, nextVar), rename0(exp[2], env, nextVar)];
}
}
function rename(exp) { return rename0(exp, Env.empty(), new NextVar()); }
// TODO: es6 import
exports.rename = rename;
/*
var _parse = require("./parse.js"),
parse = _parse.parse, unparse = _parse.unparse;
var testData = [
//["x", "_0"],
//["y", "_0"],
//["(λv u)", "(λ_0 _1)"],
// what about (v v) ?!
["(λv v)", "(λ_0 _0)"],
["(λv (v v))", "(λ_0 (_0 _0))"],
["(λv (λv v))", "(λ_0 (λ_1 _1))"],
["((λv v) (λv v))", "((λ_0 _0) (λ_1 _1))"],
["((λy y) (λx x))", "((λ_0 _0) (λ_1 _1))"],
["(λ_1 (_1 _1))", "(λ_0 (_0 _0))"],
["(λ_0 (_0 _0))", "(λ_0 (_0 _0))"],
["(λ_1 (λ_0 _0))", "(λ_0 (λ_1 _1))"],
];
for (let [orig, expected] of testData) {
const actualExp = rename(parse(orig));
const actual = unparse(actualExp);
console.assert(actual == expected, `\nactual: ${actual}\nexpected: ${expected}`);
}
*/
| "use strict";
class Env {
constructor(outer, k, v) {
this.outer = outer;
this.k = k;
this.v = v;
}
get(key) {
return (key == this.k) ? this.v : this.outer.get(key);
}
static empty() { return new Env(new Map()); }
}
class NextVar {
constructor() { this.nextVar = 0; }
next() { return "_" + (this.nextVar++); }
}
function rename0(exp, env, nextVar) {
if (exp[0] == "var") {
var v = env.get(exp[1]);
return ["var", (v == undefined) ? nextVar.next() : v];
} else if (exp[0] == "lam") {
var v = nextVar.next();
var newEnv = new Env(env, exp[1], v);
return ["lam", v, rename0(exp[2], newEnv, nextVar)];
} else if (exp[0] == "app") {
return ["app", rename0(exp[1], env, nextVar), rename0(exp[2], env, nextVar)];
}
}
function rename(exp) { return rename0(exp, Env.empty(), new NextVar()); }
// TODO: es6 import
exports.rename = rename;
/*
var _parse = require("./parse.js"),
parse = _parse.parse, unparse = _parse.unparse;
var testData = [
//["x", "_0"],
//["y", "_0"],
//["(λv u)", "(λ_0 _1)"],
// what about (v v) ?!
["(λv v)", "(λ_0 _0)"],
["(λv (v v))", "(λ_0 (_0 _0))"],
["(λv (λv v))", "(λ_0 (λ_1 _1))"],
["((λv v) (λv v))", "((λ_0 _0) (λ_1 _1))"],
["((λy y) (λx x))", "((λ_0 _0) (λ_1 _1))"],
];
for (let [orig, expected] of testData) {
const actualExp = rename(parse(orig));
const actual = unparse(actualExp);
console.assert(actual == expected, `\nactual: ${actual}\nexpected: ${expected}`);
}
*/
| JavaScript | 0.000001 |
608215c5bca4a64b667970968c8344c54e7a78f2 | update get new notifications logic | files/public/we.notification.js | files/public/we.notification.js | /**
* Notifications client side lib
*/
(function (we) {
we.notification = {
count: 0,
countDisplay: null,
link: null,
init: function() {
this.countDisplay = $('.main-menu-link-notification-count');
this.link = $('.main-menu-notification-link');
// only start if both elements is found
if (this.countDisplay && this.link) this.getNewNotificationCount();
},
notificationsCountCheckDelay: 60000,// check every 1 min
lastCheckData: null,
registerNewCheck: function registerNewCheck() {
setTimeout(
this.getNewNotificationCount.bind(this),
this.notificationsCountCheckDelay
);
},
getNewNotificationCount: function getNewNotificationCount() {
var self = this;
$.ajax({
url: '/api/v1/current-user/notification-count'
}).then(function (data){
self.count = Number(data.count);
self.updateNotificationsDisplay();
// update last check time
self.lastCheckData = new Date().toISOString();
}).fail(function (err) {
console.error('we.notification.js:error in getNewNotificationCount:', err);
}).always(function () {
self.registerNewCheck();
});
},
updateNotificationsDisplay: function updateNotificationsDisplay() {
if (this.count) {
this.countDisplay.text(this.count);
this.link.addClass('have-notifications');
} else {
this.countDisplay.text('');
this.link.removeClass('have-notifications');
}
}
};
we.notification.init();
})(window.we); | /**
* Notifications client side lib
*/
(function (we) {
we.notification = {
count: 0,
countDisplay: null,
link: null,
init: function() {
this.countDisplay = $('.main-menu-link-notification-count');
this.link = $('.main-menu-notification-link');
// only start if both elements is found
if (this.countDisplay && this.link) this.registerNewCheck();
},
notificationsCountCheckDelay: 60000,// check every 1 min
lastCheckData: null,
registerNewCheck: function registerNewCheck() {
setTimeout(
this.getNewNotificationCount.bind(this),
this.notificationsCountCheckDelay
);
},
getNewNotificationCount: function getNewNotificationCount() {
var self = this;
$.ajax({
url: '/api/v1/current-user/notification-count'
}).then(function (data){
self.count = Number(data.count);
self.updateNotificationsDisplay();
// update last check time
self.lastCheckData = new Date().toISOString();
}).fail(function (err) {
console.error('we.post.js:error in getNewsPosts:', err);
}).always(function () {
self.registerNewCheck();
});
},
updateNotificationsDisplay: function updateNotificationsDisplay() {
if (this.count) {
this.countDisplay.text(this.count);
this.link.addClass('have-notifications');
} else {
this.countDisplay.text('');
this.link.removeClass('have-notifications');
}
}
};
we.notification.init();
})(window.we); | JavaScript | 0 |
19af6710d339b3d156971fa3a3a95607de161b55 | fix remaining cases on reduce | special.js | special.js | var u = require('./util')
var compare = require('typewiselite')
var search = require('binary-search')
function is$ (obj) {
for(var k in obj)
if(k[0] === '$') return true
return false
}
//rawpaths, reducedpaths, reduce
function arrayGroup (set, get, reduce) {
//we can use a different lookup path on the right hand object
//is always the "needle"
function _compare (hay, needle) {
for(var i in set) {
var x = u.get(hay, set[i]), y = needle[i]
if(x !== y) return compare(x, y)
}
return 0
}
return function (a, b) {
if(a && !Array.isArray(a)) a = reduce([], a)
var A = a = a || []
var i = search(A, get.map(function (fn) { return fn(b) }), _compare)
if(i >= 0) A[i] = reduce(A[i], b)
else A.splice(~i, 0, reduce(undefined, b))
return a
}
}
module.exports = function (make) {
return {
filter: function makeFilter (rule) {
if(u.isContainer(rule) && !is$(rule)) {
rule = u.map(rule, makeFilter)
return function (value) {
if(value == null) return false
for(var k in rule)
if(!rule[k](value[k])) return false
return true
}
}
if(u.isBasic(rule))
return function (v) { return rule === v }
//now only values at the end...
return make(rule)
},
map: function makeMap (rule) {
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeMap)
return function (value) {
if(value == null) return undefined
var keys = 0
var ret = u.map(rules, function (fn, key) {
if(rule[key] === true) {
keys ++
return value && value[key]
}
keys ++
return fn(value)
})
return keys ? ret : undefined
}
}
return make(rule)
},
reduce: function (rule) {
//this traverses the rule THREE TIMES!
//surely I can do this in one go.
function makeReduce (rule) {
if(u.isObject(rule) && !is$(rule) && !u.isArray(rule))
return u.map(rule, makeReduce)
return make(rule)
}
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeReduce)
var getPaths = []
var setPaths = u.paths(rules, function (maybeMap) {
if(u.isFunction(maybeMap) && maybeMap.length === 1) {
return getPaths.push(maybeMap), true
}
})
var reduce = (function createReduce(rule) {
if(u.isObject(rule)) {
var rules = u.map(rule, createReduce)
return function (a, b) {
if(!a) a = {}
return u.map(rules, function (reduce, key) {
return a[key] = reduce(a[key], b)
})
}
}
else if(u.isFunction(rule)) {
if(rule.length === 2) return rule
else return function (a, b) { return rule(b) }
}
else
throw new Error('could not process:'+JSON.stringify(rule))
})(rules)
return getPaths.length
? arrayGroup(setPaths, getPaths, reduce) : reduce
}
return make(rule)
}
}
}
| var u = require('./util')
var compare = require('typewiselite')
var search = require('binary-search')
function is$ (obj) {
for(var k in obj)
if(k[0] === '$') return true
return false
}
//rawpaths, reducedpaths, reduce
function arrayGroup (set, get, reduce) {
//we can use a different lookup path on the right hand object
//is always the "needle"
function _compare (hay, needle) {
for(var i in set) {
var x = u.get(hay, set[i]), y = needle[i]
if(x !== y) return compare(x, y)
}
return 0
}
return function (a, b) {
if(a && !Array.isArray(a)) a = reduce([], a)
var A = a = a || []
var i = search(A, get.map(function (fn) { return fn(b) }), _compare)
if(i >= 0) A[i] = reduce(A[i], b)
else A.splice(~i, 0, reduce(undefined, b))
return a
}
}
module.exports = function (make) {
return {
filter: function makeFilter (rule) {
if(u.isContainer(rule) && !is$(rule)) {
rule = u.map(rule, makeFilter)
return function (value) {
if(value == null) return false
for(var k in rule)
if(!rule[k](value[k])) return false
return true
}
}
if(u.isBasic(rule))
return function (v) { return rule === v }
//now only values at the end...
return make(rule)
},
map: function makeMap (rule) {
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeMap)
return function (value) {
if(value == null) return undefined
var keys = 0
var ret = u.map(rules, function (fn, key) {
if(rule[key] === true) {
keys ++
return value && value[key]
}
keys ++
return fn(value)
})
return keys ? ret : undefined
}
}
return make(rule)
},
reduce: function (rule) {
function makeReduce (rule) {
if(u.isObject(rule) && !is$(rule) && !u.isArray(rule))
return u.map(rule, makeReduce)
return make(rule)
}
if(u.isObject(rule) && !is$(rule)) {
var rules = u.map(rule, makeReduce)
var getPaths = []
var setPaths = u.paths(rules, function (maybeMap) {
if(u.isFunction(maybeMap) && maybeMap.length === 1) {
return getPaths.push(maybeMap), true
}
})
function reduce (a, b) {
return u.map(rules, function (reduce, key) {
//handle maps as reduces (skip aggregator arg)
return reduce.length === 1 ? reduce(b) : reduce(a && a[key], b)
})
}
if(getPaths.length) return arrayGroup(setPaths, getPaths, reduce)
return reduce
}
return make(rule)
}
}
}
| JavaScript | 0.000002 |
dd471a697d821b88245e9d7d0a3259becba5f484 | Add userGuess() | src/App.js | src/App.js | import React, { Component } from 'react';
import './App.css';
import ReactSVG from 'react-svg'
class App extends Component {
constructor(){
this.alphabet = []
this.word = []
this.guessesLeft = 8
}
function newGame() {
newGameView()
this.alphabet =
["A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
this.word = ["c", "a", "t"]
this.guessesLeft = 8
setBlanks( "___" )
}
userGuess( event ) {
letter = event.value
if(!this.alphabet.includes(letter.toUpperCase)) {
// You already guessed that! Do nothing (no penalty).
Console.log("You already guessed that!")
return
}
else {
this.guessesLeft--
if (this.word.includes(letter)) {
for (i = 0; i < this.word.length; i ++) {
if ( this.hint[i] === "_" && this.word.charAt(i) === letter)
this.hint[i] === letter.toUpperCase()
}
}
else {
// add to hangman
}
this.alphabet.splice(this.alphabet.indexOf(letter.toUpperCase()), 1)
}
}
render() {
return (
<div className="App">
<div className="header">
<h2>Hangman Game</h2>
</div>
<div className="intro">
<p>To get started, edit <code>src/App.js</code> and save to reload.</p>
<p>There are some placeholder elements setup that need implementation.</p>
</div>
<div className="main">
<ReactSVG path="hangman.svg"/>
<div className="game-controls">
<button onClick={this.newGame}>New Game</button>
<div className="remaining-alphabet">{this.alphabet}</div>
<div className="guess-left">{this.guessesLeft}</div>
<input type="text" onChange={this.userGuess} placeholder="Guess a letter..."/>
<div className="puzzle-word">_ _ _ _ _ _ _ _ _ _</div>
</div>
</div>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import './App.css';
import ReactSVG from 'react-svg'
class App extends Component {
constructor(){
this.alphabet = []
this.word = []
this.guessesLeft = 8
}
function newGame() {
newGameView()
this.alphabet =
["A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
this.word = ["c", "a", "t"]
this.guessesLeft = 8
setBlanks( "___" )
}
render() {
return (
<div className="App">
<div className="header">
<h2>Hangman Game</h2>
</div>
<div className="intro">
<p>To get started, edit <code>src/App.js</code> and save to reload.</p>
<p>There are some placeholder elements setup that need implementation.</p>
</div>
<div className="main">
<ReactSVG path="hangman.svg"/>
<div className="game-controls">
<button onClick={this.newGame}>New Game</button>
<div className="remaining-alphabet">{this.alphabet}</div>
<div className="guess-left">{this.guessesLeft}</div>
<input type="text" onChange={this.userGuess} placeholder="Guess a letter..."/>
<div className="puzzle-word">_ _ _ _ _ _ _ _ _ _</div>
</div>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0.000001 |
d6a7f211850f9b1b6c6a3a0ab17d72dfce38568a | Substitute static content with the state object | src/App.js | src/App.js | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
//list of todos in state object
todos: [
{ id: 1, name: 'Learn React', isComplete: true },
{ id: 2, name: 'Build a React App', isComplete: false },
{ id: 3, name: 'Evaluate the end result', isComplete: false }
]
}
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>React Todos</h2>
</div>
<div className="Todo-App">
<form>
<input type="text" />
</form>
<div className="Todo-List">
<ul>
{this.state.todos.map(todo =>
<li key={todo.id}>
<input type="checkbox" defaultChecked={todo.isComplete} />{todo.name}
</li>
)}
</ul>
</div>
</div>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>React Todos</h2>
</div>
<div className="Todo-App">
<form>
<input type="text" />
</form>
<div className="Todo-List">
<ul>
<li><input type="checkbox" />Learn React</li>
<li><input type="checkbox" />Build a React App</li>
<li><input type="checkbox" />Evaluate the end result</li>
</ul>
</div>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0.000084 |
7028afe0153202364f428eb1761968a5f747c724 | Add more locations. | src/App.js | src/App.js | import React, { Component } from 'react';
import './App.css';
import ErrorMsg from './ErrorMsg.js';
import LoadingMsg from './LoadingMsg.js';
import TimeTable from './TimeTable.js';
import UserLocation from './UserLocation.js';
import MapView from './MapView.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
var self = this;
var currentURL = window.location.href;
if (/niemi/.exec(currentURL)) {
self.setState({
//lat:60.183692, lon:24.827744
lat:60.186269 ,lon:24.830909, maxDistance:1000, filterOut:'Otaniemi'
});
} else if (/kara/.exec(currentURL)) {
self.setState({
lat:[60.224655, 60.215923],
lon:[24.759257, 24.753498],
maxDistance:[300, 100]
});
} else if (/sello/.exec(currentURL)) {
self.setState({
lat:60.219378, lon:24.815121, maxDistance:325, filterOut:'Leppävaara'
});
} else if (/keskusta/.exec(currentURL)) {
self.setState({
lat:60.170508, lon:24.941104, maxDistance:300, filterOut:'Leppävaara'
});
} else if (/kamppi/.exec(currentURL)) {
self.setState({
lat:60.169038, lon:24.932908, maxDistance:100, filterOut:'Leppävaara'
});
}
//if (/location/.exec(currentURL)) {
else {
UserLocation.getUserLocation((loc) => {
console.log(String(loc.coords.latitude) + ', ' + String(loc.coords.longitude));
self.setState({
lat:loc.coords.latitude, lon:loc.coords.longitude, maxDistance:500
});
}, (e) => {
this.setState({error: {
name: 'User location not available.',
message: e.toString()
}});
});
}
}
render() {
if (this.state.hasOwnProperty('error')) {
return (
<div className='app'>
<ErrorMsg name={this.state.error.name} message={this.state.error.message}/>
</div>
);
}
if ((!this.state.hasOwnProperty('lat') || !this.state.hasOwnProperty('lon')) && !this.state.hasOwnProperty('stopCode')) {
return (
<div className='app'>
<LoadingMsg name='User location' message={UserLocation.waitingForUserLocation}/>
</div>
);
}
//<TimeTable stopCode='E2036' />;
//Alvarin aukio 60.186269, 24.830909
//console.log('render: ' + String(this.state.lat) + ', ' + String(this.state.lon) + ', ' + String(this.state.maxDistance))
return (
<div className='app'>
<div className='foreground'>
<TimeTable lat={this.state.lat} lon={this.state.lon} maxDistance={this.state.maxDistance} maxResults={15} filterOut={this.state.filterOut}/>
</div>
<div className='background'>
<MapView
lat={Array.isArray(this.state.lat) ? this.state.lat[0] : this.state.lat}
lon={Array.isArray(this.state.lon) ? this.state.lon[0] : this.state.lon}
/>
</div>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import './App.css';
import ErrorMsg from './ErrorMsg.js';
import LoadingMsg from './LoadingMsg.js';
import TimeTable from './TimeTable.js';
import UserLocation from './UserLocation.js';
import MapView from './MapView.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
var self = this;
var currentURL = window.location.href;
if (/niemi/.exec(currentURL)) {
self.setState({
//lat:60.183692, lon:24.827744
lat:60.186269 ,lon:24.830909, maxDistance:1000
});
} else if (/kara/.exec(currentURL)) {
self.setState({
lat:[60.224655, 60.215923],
lon:[24.759257, 24.753498],
maxDistance:[300, 100]
});
}
//if (/location/.exec(currentURL)) {
else {
UserLocation.getUserLocation((loc) => {
self.setState({
lat:loc.coords.latitude, lon:loc.coords.longitude
});
}, (e) => {
this.setState({error: {
name: 'User location not available.',
message: e.toString()
}});
});
}
}
render() {
if (this.state.hasOwnProperty('error')) {
return (
<div className='app'>
<ErrorMsg name={this.state.error.name} message={this.state.error.message}/>
</div>
);
}
if ((!this.state.hasOwnProperty('lat') || !this.state.hasOwnProperty('lon')) && !this.state.hasOwnProperty('stopCode')) {
return (
<div className='app'>
<LoadingMsg name='User location' message={UserLocation.waitingForUserLocation}/>
</div>
);
}
//<TimeTable stopCode='E2036' />;
//Alvarin aukio 60.186269, 24.830909
return (
<div className='app'>
<div className='foreground'>
<TimeTable lat={this.state.lat} lon={this.state.lon} maxDistance={this.state.maxDistance} maxResults={15}/>
</div>
<div className='background'>
<MapView
lat={Array.isArray(this.state.lat) ? this.state.lat[0] : this.state.lat}
lon={Array.isArray(this.state.lon) ? this.state.lon[0] : this.state.lon}
/>
</div>
</div>
);
}
}
export default App;
| JavaScript | 0 |
0988c6e3d216f019a08bc9cfdf864a9e4af5caa2 | Update order of lessons. | src/App.js | src/App.js | import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { withRouter } from 'react-router'
import { Panel, ListGroup, ListGroupItem, Navbar, Col, Clearfix } from 'react-bootstrap'
import * as Lessons from './lessons/index.js'
const lessons = [
{ key: 'StateAsProps', displayName: 'State as props' },
{ key: 'RenderStates', displayName: 'Render states' },
{ key: 'PureRenderFunctions', displayName: 'Pure render functions' },
]
const LessonRoute = ({ lessonKey, lessonName, incr }) => (
<ListGroupItem>
<Col sm={10}>
<span>{incr + 1}. {lessonName}</span>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/exercise`}>Exercise</Link>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/solution`}>Solution</Link>
</Col>
<Clearfix />
</ListGroupItem>
)
const Routes = () => (
<div className="container">
{lessons.map(lesson => (
<div key={lesson.key}>
<Route path={`/${lesson.key}/exercise`} component={Lessons[`${lesson.key}Exercise`]} />
<Route path={`/${lesson.key}/solution`} component={Lessons[`${lesson.key}Solution`]} />
</div>
))}
</div>
)
const Home = () => (
<main>
<Panel header="Workshop lessons">
<ListGroup fill>
{lessons.map((lesson, key) => (
<LessonRoute
key={lesson.key}
lessonKey={lesson.key}
lessonName={lesson.displayName}
incr={key}
/>
))}
</ListGroup>
</Panel>
</main>
)
const Header = withRouter(({ location }) => (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Learning Recompose</Link>
</Navbar.Brand>
</Navbar.Header>
{location.pathname !== '/' &&
<span>
{location.pathname.includes('solution') &&
<Navbar.Text pullRight>
<Link to={`./exercise`}>Got to exercise</Link>
</Navbar.Text>}
{location.pathname.includes('exercise') &&
<Navbar.Text pullRight>
<Link to={`./solution`}>Go to solution</Link>
</Navbar.Text>}
</span>}
</Navbar>
))
const App = () => (
<Router>
<div className="app">
<Header />
<Routes />
<div className="container">
<Route path="/" exact component={Home} />
</div>
</div>
</Router>
)
export default App
| import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { withRouter } from 'react-router'
import { Panel, ListGroup, ListGroupItem, Navbar, Col, Clearfix } from 'react-bootstrap'
import * as Lessons from './lessons/index.js'
const lessons = [
{ key: 'StateAsProps', displayName: 'State as props' },
{ key: 'PureRenderFunctions', displayName: 'Pure render functions' },
{ key: 'RenderStates', displayName: 'Render states' },
]
const LessonRoute = ({ lessonKey, lessonName, incr }) => (
<ListGroupItem>
<Col sm={10}>
<span>{incr + 1}. {lessonName}</span>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/exercise`}>Exercise</Link>
</Col>
<Col sm={1}>
<Link to={`/${lessonKey}/solution`}>Solution</Link>
</Col>
<Clearfix />
</ListGroupItem>
)
const Routes = () => (
<div className="container">
{lessons.map(lesson => (
<div key={lesson.key}>
<Route path={`/${lesson.key}/exercise`} component={Lessons[`${lesson.key}Exercise`]} />
<Route path={`/${lesson.key}/solution`} component={Lessons[`${lesson.key}Solution`]} />
</div>
))}
</div>
)
const Home = () => (
<main>
<Panel header="Workshop lessons">
<ListGroup fill>
{lessons.map((lesson, key) => (
<LessonRoute
key={lesson.key}
lessonKey={lesson.key}
lessonName={lesson.displayName}
incr={key}
/>
))}
</ListGroup>
</Panel>
</main>
)
const Header = withRouter(({ location }) => (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Learning Recompose</Link>
</Navbar.Brand>
</Navbar.Header>
{location.pathname !== '/' &&
<span>
{location.pathname.includes('solution') &&
<Navbar.Text pullRight>
<Link to={`./exercise`}>Got to exercise</Link>
</Navbar.Text>}
{location.pathname.includes('exercise') &&
<Navbar.Text pullRight>
<Link to={`./solution`}>Go to solution</Link>
</Navbar.Text>}
</span>}
</Navbar>
))
const App = () => (
<Router>
<div className="app">
<Header />
<Routes />
<div className="container">
<Route path="/" exact component={Home} />
</div>
</div>
</Router>
)
export default App
| JavaScript | 0 |
7ce48514893ffdaed2a7cb8d5c553ca723a7b193 | Enable smart typographic punctuation in markdown plugin. | tasks/build.js | tasks/build.js | var gulp = require('gulp');
var Metalsmith = require('metalsmith');
var collections = require('metalsmith-collections');
var ignore = require('metalsmith-ignore');
var permalinks = require('metalsmith-permalinks');
// Content
var fileMetadata = require('metalsmith-filemetadata');
var metadata = require('metalsmith-metadata');
var markdown = require('metalsmith-markdown');
var templates = require('metalsmith-templates');
// CSS
var less = require('metalsmith-less');
var fingerprint = require('metalsmith-fingerprint');
var autoprefixer = require('metalsmith-autoprefixer');
var Handlebars = require('handlebars');
var moment = require('handlebars-helper-moment')();
Handlebars.registerHelper('moment', moment.moment);
Handlebars.registerHelper('log', function(content) {
console.log(content);
});
gulp.task('build', function(callback) {
Metalsmith('./')
// CSS
.use(less({
pattern: '**/main.less'
}))
.use(autoprefixer())
.use(fingerprint({
pattern: '**/*.css'
}))
.use(ignore([
'**/*.less',
'**/main.css',
'**/.DS_Store'
]))
// Content
.use(metadata({
site: 'site.yaml'
}))
.use(fileMetadata([
{
pattern: '**/*.md',
metadata: {
template: 'default.html'
},
preserve: true
}
]))
.use(collections({
pages: {
pattern: '*.md',
sortBy: 'order'
},
articles: {
pattern: 'articles/*.md',
sortBy: 'date',
reverse: true
}
}))
.use(markdown({
smartypants: true
}))
.use(permalinks({
relative: false
}))
.use(templates('handlebars'))
.build(function(err, files) {
if (err) {
return callback(err);
}
callback();
});
});
| var gulp = require('gulp');
var Metalsmith = require('metalsmith');
var collections = require('metalsmith-collections');
var ignore = require('metalsmith-ignore');
var permalinks = require('metalsmith-permalinks');
// Content
var fileMetadata = require('metalsmith-filemetadata');
var metadata = require('metalsmith-metadata');
var markdown = require('metalsmith-markdown');
var templates = require('metalsmith-templates');
// CSS
var less = require('metalsmith-less');
var fingerprint = require('metalsmith-fingerprint');
var autoprefixer = require('metalsmith-autoprefixer');
var Handlebars = require('handlebars');
var moment = require('handlebars-helper-moment')();
Handlebars.registerHelper('moment', moment.moment);
Handlebars.registerHelper('log', function(content) {
console.log(content);
});
gulp.task('build', function(callback) {
Metalsmith('./')
// CSS
.use(less({
pattern: '**/main.less'
}))
.use(autoprefixer())
.use(fingerprint({
pattern: '**/*.css'
}))
.use(ignore([
'**/*.less',
'**/main.css',
'**/.DS_Store'
]))
// Content
.use(metadata({
site: 'site.yaml'
}))
.use(fileMetadata([
{
pattern: '**/*.md',
metadata: {
template: 'default.html'
},
preserve: true
}
]))
.use(collections({
pages: {
pattern: '*.md',
sortBy: 'order'
},
articles: {
pattern: 'articles/*.md',
sortBy: 'date',
reverse: true
}
}))
.use(markdown())
.use(permalinks({
relative: false
}))
.use(templates('handlebars'))
.build(function(err, files) {
if (err) {
return callback(err);
}
callback();
});
});
| JavaScript | 0 |
ed6abbc49f74022e7ac2a93012509ee02fe85598 | Increase maxBuffer to 1000 * 1024, was having problems with the `xcodebuild archive` exceeding buffer | tasks/xcode.js | tasks/xcode.js | /*
* grunt-xcode
* https://github.com/matiassingers/grunt-xcode
*
* Copyright (c) 2014 Matias Singers
* Licensed under the MIT license.
*/
'use strict';
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
var temporary = require('temporary');
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
formatted = formatted.replace(
RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
}
return formatted;
};
module.exports = function(grunt) {
function executeCommand(command){
grunt.verbose.writeln('Running command: {0}'.format(command));
return exec(command, {maxBuffer: 1000*1024})
.catch(handleCommandError);
}
function handleCommandError(error){
if (error){
grunt.warn(error);
}
}
grunt.registerMultiTask('xcode', 'Build and export Xcode projects with Grunt', function() {
var done = this.async();
var options = this.options({
clean: true,
export: true,
project: '',
scheme: '',
archivePath: '',
exportPath: process.cwd(),
exportFilename: 'export.ipa'
});
if(!options.project){
throw new Error('`options.project` is required');
}
if(!options.archivePath){
var temporaryDirectory = new temporary.Dir();
options.archivePath = temporaryDirectory.path;
}
runCleanCommand()
.then(runArchiveCommand)
.then(runExportCommand)
.finally(cleanUp);
function runCleanCommand(){
if(!options.clean){
return Promise.resolve();
}
var command = 'xcodebuild clean -project "{0}"'.format(options.project);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild clean` was successful');
});
}
function runArchiveCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild archive';
command += ' -project "{0}"'.format(options.project);
command += ' -scheme "{0}"'.format(options.scheme);
command += ' -archivePath "{0}"'.format(options.archivePath);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild archive` was successful');
});
}
function runExportCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild';
command += ' -exportArchive';
command += ' -exportFormat ipa';
command += ' -project "{0}"'.format(options.project);
command += ' -archivePath "{0}.xcarchive"'.format(options.archivePath);
command += ' -exportPath "{0}/{1}"'.format(options.exportPath, options.exportFilename);
command += ' -exportWithOriginalSigningIdentity';
executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild export` was successful');
});
}
function cleanUp(){
if(temporaryDirectory){
temporaryDirectory.rmdir();
}
if(options.export){
grunt.log.ok('Built and exported product to: {0}/{1}'.format(options.exportPath, options.exportFilename));
}
done();
}
});
};
| /*
* grunt-xcode
* https://github.com/matiassingers/grunt-xcode
*
* Copyright (c) 2014 Matias Singers
* Licensed under the MIT license.
*/
'use strict';
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
var temporary = require('temporary');
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
formatted = formatted.replace(
RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
}
return formatted;
};
module.exports = function(grunt) {
function executeCommand(command){
grunt.verbose.writeln('Running command: {0}'.format(command));
return exec(command)
.catch(handleCommandError);
}
function handleCommandError(error){
if (error){
grunt.warn(error);
}
}
grunt.registerMultiTask('xcode', 'Build and export Xcode projects with Grunt', function() {
var done = this.async();
var options = this.options({
clean: true,
export: true,
project: '',
scheme: '',
archivePath: '',
exportPath: process.cwd(),
exportFilename: 'export.ipa'
});
if(!options.project){
throw new Error('`options.project` is required');
}
if(!options.archivePath){
var temporaryDirectory = new temporary.Dir();
options.archivePath = temporaryDirectory.path;
}
runCleanCommand()
.then(runArchiveCommand)
.then(runExportCommand)
.finally(cleanUp);
function runCleanCommand(){
if(!options.clean){
return Promise.resolve();
}
var command = 'xcodebuild clean -project "{0}"'.format(options.project);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild clean` was successful');
});
}
function runArchiveCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild archive';
command += ' -project "{0}"'.format(options.project);
command += ' -scheme "{0}"'.format(options.scheme);
command += ' -archivePath "{0}"'.format(options.archivePath);
return executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild archive` was successful');
});
}
function runExportCommand(){
if(!options.export) {
return Promise.resolve();
}
var command = 'xcodebuild';
command += ' -exportArchive';
command += ' -exportFormat ipa';
command += ' -project "{0}"'.format(options.project);
command += ' -archivePath "{0}.xcarchive"'.format(options.archivePath);
command += ' -exportPath "{0}/{1}"'.format(options.exportPath, options.exportFilename);
command += ' -exportWithOriginalSigningIdentity';
executeCommand(command)
.then(function(){
grunt.verbose.ok('`xcodebuild export` was successful');
});
}
function cleanUp(){
if(temporaryDirectory){
temporaryDirectory.rmdir();
}
if(options.export){
grunt.log.ok('Built and exported product to: {0}/{1}'.format(options.exportPath, options.exportFilename));
}
done();
}
});
};
| JavaScript | 0.000001 |
d590014bb6377979afaf738b23ce5d4895903c43 | load correctly lowercased findone.js blueprint | blueprints/find.js | blueprints/find.js | /**
* Module dependencies
*/
var util = require( 'util' ),
actionUtil = require( './_util/actionUtil' ),
pluralize = require( 'pluralize' );
/**
* Find Records
*
* get /:modelIdentity
* * /:modelIdentity/find
*
* An API call to find and return model instances from the data adapter
* using the specified criteria. If an id was specified, just the instance
* with that unique id will be returned.
*
* Optional:
* @param {Object} where - the find criteria (passed directly to the ORM)
* @param {Integer} limit - the maximum number of records to send back (useful for pagination)
* @param {Integer} skip - the number of records to skip (useful for pagination)
* @param {String} sort - the order of returned records, e.g. `name ASC` or `age DESC`
* @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
*/
module.exports = function findRecords( req, res ) {
// Look up the model
var Model = actionUtil.parseModel( req );
// root level element in JSON api
var documentIdentifier = pluralize( Model.identity );
// We could use the JSON API URL shorthand template style, if the client supported it
// var documentLinks = actionUtil.asyncAssociationToplevelLinks( documentIdentifier, Model, req.options.associations );
// If an `id` param was specified, use the findOne blueprint action
// to grab the particular instance with its primary key === the value
// of the `id` param. (mainly here for compatibility for 0.9, where
// there was no separate `findOne` action)
if ( actionUtil.parsePk( req ) ) {
return require( './findone' )( req, res );
}
// Lookup for records that match the specified criteria
var query = Model.find()
.where( actionUtil.parseCriteria( req ) )
.limit( actionUtil.parseLimit( req ) )
.skip( actionUtil.parseSkip( req ) )
.sort( actionUtil.parseSort( req ) );
// TODO: .populateEach(req.options);
query = actionUtil.populateEach( query, req.options );
query.exec( function found( err, matchingRecords ) {
if ( err ) return res.serverError( err );
// Only `.watch()` for new instances of the model if
// `autoWatch` is enabled.
if ( req._sails.hooks.pubsub && req.isSocket ) {
Model.subscribe( req, matchingRecords );
if ( req.options.autoWatch ) {
Model.watch( req );
}
// Also subscribe to instances of all associated models
_.each( matchingRecords, function ( record ) {
actionUtil.subscribeDeep( req, record );
} );
}
matchingRecords = actionUtil.asyncAssociationLinks( Model, matchingRecords, req.options.associations );
var jsonAPI = {};
jsonAPI[ documentIdentifier ] = matchingRecords;
// jsonAPI = actionUtil.sideloadAssociations( jsonAPI, documentIdentifier, req.options.associations );
// res.set( 'Content-Type', 'application/vnd.api+json' );
res.ok( jsonAPI );
} );
};
| /**
* Module dependencies
*/
var util = require( 'util' ),
actionUtil = require( './_util/actionUtil' ),
pluralize = require( 'pluralize' );
/**
* Find Records
*
* get /:modelIdentity
* * /:modelIdentity/find
*
* An API call to find and return model instances from the data adapter
* using the specified criteria. If an id was specified, just the instance
* with that unique id will be returned.
*
* Optional:
* @param {Object} where - the find criteria (passed directly to the ORM)
* @param {Integer} limit - the maximum number of records to send back (useful for pagination)
* @param {Integer} skip - the number of records to skip (useful for pagination)
* @param {String} sort - the order of returned records, e.g. `name ASC` or `age DESC`
* @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
*/
module.exports = function findRecords( req, res ) {
// Look up the model
var Model = actionUtil.parseModel( req );
// root level element in JSON api
var documentIdentifier = pluralize( Model.identity );
// We could use the JSON API URL shorthand template style, if the client supported it
// var documentLinks = actionUtil.asyncAssociationToplevelLinks( documentIdentifier, Model, req.options.associations );
// If an `id` param was specified, use the findOne blueprint action
// to grab the particular instance with its primary key === the value
// of the `id` param. (mainly here for compatibility for 0.9, where
// there was no separate `findOne` action)
if ( actionUtil.parsePk( req ) ) {
return require( './findOne' )( req, res );
}
// Lookup for records that match the specified criteria
var query = Model.find()
.where( actionUtil.parseCriteria( req ) )
.limit( actionUtil.parseLimit( req ) )
.skip( actionUtil.parseSkip( req ) )
.sort( actionUtil.parseSort( req ) );
// TODO: .populateEach(req.options);
query = actionUtil.populateEach( query, req.options );
query.exec( function found( err, matchingRecords ) {
if ( err ) return res.serverError( err );
// Only `.watch()` for new instances of the model if
// `autoWatch` is enabled.
if ( req._sails.hooks.pubsub && req.isSocket ) {
Model.subscribe( req, matchingRecords );
if ( req.options.autoWatch ) {
Model.watch( req );
}
// Also subscribe to instances of all associated models
_.each( matchingRecords, function ( record ) {
actionUtil.subscribeDeep( req, record );
} );
}
matchingRecords = actionUtil.asyncAssociationLinks( Model, matchingRecords, req.options.associations );
var jsonAPI = {};
jsonAPI[ documentIdentifier ] = matchingRecords;
// jsonAPI = actionUtil.sideloadAssociations( jsonAPI, documentIdentifier, req.options.associations );
// res.set( 'Content-Type', 'application/vnd.api+json' );
res.ok( jsonAPI );
} );
};
| JavaScript | 0.00004 |
fbea2335c0a71d71dc27788281ed97a28e3855e8 | Fix time lost if opponent was disconnected. | frontend/js/controllers/play.js | frontend/js/controllers/play.js | /**
* Created by stas on 30.01.16.
*/
'use strict';
playzoneControllers.controller('PlayCtrl', function ($scope, $rootScope, $routeParams, GameRest, WebRTCService, WebsocketService, $interval, dateFilter) {
$scope.boardConfig = {
pieceType: 'leipzig'
};
$scope.gameConfig = {
zeitnotLimit: 28000
};
$scope.game = GameRest.get(
{
id: $routeParams.gameId
}
);
$scope.game.$promise.then(
function () {
if ($scope.game.color === 'b') {
$scope.my_move = $rootScope.user.id === $scope.game.user_to_move.id;
} else {
$scope.my_move = $scope.game.user_white.id === $scope.game.user_to_move.id;
}
$scope.my_time = $scope.game.color === 'w' ? $scope.game.time_white : $scope.game.time_black;
$scope.opponent_time = $scope.game.color === 'b' ? $scope.game.time_white : $scope.game.time_black;
switch ($scope.game.color) {
case 'w':
WebRTCService.createGameRoom($scope.game.id);
break;
case 'b':
WebRTCService.joinGameRoom($scope.game.id);
WebRTCService.addCallBackLeaveRoom($scope.game.id, function () {
$scope.game.$savePgn();
});
break;
default:
WebsocketService.subscribeToGame($scope.game.id);
}
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
$scope.timer = $interval(function() {
$scope.game.status != 'play' && $interval.cancel($scope.timer);
if ($scope.my_move) {
$scope.my_time -= 100;
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.my_time <= 0 && $interval.cancel($scope.timer) && $scope.timeLost();
} else {
$scope.opponent_time -= 100;
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
if ($scope.opponent_time <= 0) {
$interval.cancel($scope.timer);
$scope.savePgnAndTime();
}
}
}, 100);
}
);
$scope.resign = function () {
$scope.game.$resign().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.timeLost = function () {
$scope.game.$timeLost().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.savePgnAndTime = function () {
$scope.game.time_white = $scope.game.color === 'w' ? $scope.my_time : $scope.opponent_time;
$scope.game.time_black = $scope.game.color === 'b' ? $scope.my_time : $scope.opponent_time;
$scope.game.$savePgn().then(
function () {
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
}); | /**
* Created by stas on 30.01.16.
*/
'use strict';
playzoneControllers.controller('PlayCtrl', function ($scope, $rootScope, $routeParams, GameRest, WebRTCService, WebsocketService, $interval, dateFilter) {
$scope.boardConfig = {
pieceType: 'leipzig'
};
$scope.gameConfig = {
zeitnotLimit: 28000
};
$scope.game = GameRest.get(
{
id: $routeParams.gameId
}
);
$scope.game.$promise.then(
function () {
if ($scope.game.color === 'b') {
$scope.my_move = $rootScope.user.id === $scope.game.user_to_move.id;
} else {
$scope.my_move = $scope.game.user_white.id === $scope.game.user_to_move.id;
}
$scope.my_time = $scope.game.color === 'w' ? $scope.game.time_white : $scope.game.time_black;
$scope.opponent_time = $scope.game.color === 'b' ? $scope.game.time_white : $scope.game.time_black;
switch ($scope.game.color) {
case 'w':
WebRTCService.createGameRoom($scope.game.id);
break;
case 'b':
WebRTCService.joinGameRoom($scope.game.id);
WebRTCService.addCallBackLeaveRoom($scope.game.id, function () {
$scope.game.$savePgn();
});
break;
default:
WebsocketService.subscribeToGame($scope.game.id);
}
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
$scope.timer = $interval(function() {
$scope.game.status != 'play' && $interval.cancel($scope.timer);
if ($scope.my_move) {
$scope.my_time -= 100;
$scope.my_time_format = formatTime($scope.my_time, dateFilter);
$scope.my_time <= 0 && $interval.cancel($scope.timer) && $scope.timeLost();
} else {
$scope.opponent_time -= 100;
$scope.opponent_time_format = formatTime($scope.opponent_time, dateFilter);
if ($scope.opponent_time <= 0) {
$interval.cancel($scope.timer);
$scope.savePgnAndTime();
}
}
}, 100);
}
);
$scope.resign = function () {
$scope.game.$resign().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.timeLost = function () {
$scope.game.$timeLost().then(
function () {
WebRTCService.sendMessage({
gameId: $scope.game.id,
resign: true
});
WebsocketService.sendGameToObservers($scope.game.id);
}
);
};
$scope.savePgnAndTime = function () {
$scope.game.time_white = $scope.game.color === 'w' ? $scope.my_time : $scope.opponent_time;
$scope.game.time_black = $scope.game.color === 'b' ? $scope.my_time : $scope.opponent_time;
$scope.game.$savePgn();
};
}); | JavaScript | 0 |
7178296aa07088e152e38e852cda00e7ce85f0c6 | Update rest_api.js | app/assets/javascripts/codelation_ui/std/interfaces/rest_api.js | app/assets/javascripts/codelation_ui/std/interfaces/rest_api.js | (function(){
"use strict";
// Config options
App.vue.config.rest_api = {
'options': {},
'version': null
};
function url() {
if (App.vue.config.rest_api.version === null) {
return '/api';
}else{
return '/api/v' + App.vue.config.rest_api.version;
}
}
function toPath(model) {
var pluralModel = App.vue.interfaces.string.methods._pluralize(model);
var modelPath = App.vue.interfaces.string.methods._dasherize(pluralModel);
return url() + '/' + modelPath;
}
function queryStringFromOptions(options_arg, defaultOptions_arg) {
var queries = [];
var options = options_arg || {};
var defaultOptions = defaultOptions_arg || {};
Object.keys(options).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + options[key]);
});
Object.keys(defaultOptions).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + defaultOptions[key]);
});
if (queries.length > 0) {
return '?'+queries.join('&');
} else {
return '';
}
}
App.vue.interfaces.rest_api = {
methods: {
_sendRequest: function(url, method, data) {
return $.ajax({
url: url,
type: method || 'GET',
data: data || {}
});
},
_restfulGet: function(model, id, options) {
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
return this.RestfulGetAll(model, options);
}else{
var url = toPath(model);
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulGetAll: function(model, options) {
var requestUrl = toPath(model) + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulCreate: function(model, id, data, options) {
var url = toPath(model);
var path = url;
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'POST', data);
},
_restfulUpdate: function(model, id, data, options) {
var url = toPath(model);
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
var path = url + '/';
}else{
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'PATCH', data);
},
_restfulDelete: function(model, id, options) {
var url = toPath(model);
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
var path = url + '/';
}else{
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'DELETE');
}
}
}
})();
| (function(){
"use strict";
// Config options
App.vue.config.rest_api = {
'options': {},
'version': null
};
function url() {
if (App.vue.config.rest_api.version === null) {
return '/api';
}else{
return '/api/v' + App.vue.config.rest_api.version;
}
}
function toPath(model) {
var pluralModel = App.vue.interfaces.string.methods._pluralize(model);
var modelPath = App.vue.interfaces.string.methods._dasherize(pluralModel);
return url() + '/' + modelPath;
}
function queryStringFromOptions(options_arg, defaultOptions_arg) {
var queries = [];
var options = options_arg || {};
var defaultOptions = defaultOptions_arg || {};
Object.keys(options).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + options[key]);
});
Object.keys(defaultOptions).forEach(function(key) {
queries.push(App.vue.interfaces.string.methods._underscore(key) + "=" + defaultOptions[key]);
});
if (queries.length > 0) {
return '?'+queries.join('&');
} else {
return '';
}
}
App.vue.interfaces.rest_api = {
methods: {
_sendRequest: function(url, method, data) {
return $.ajax({
url: url,
type: method || 'GET',
data: data || {}
});
},
_restfulGet: function(model, id, options) {
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
return this.RestfulGetAll(model, options);
}else{
var url = toPath(model);
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulGetAll: function(model, options) {
var requestUrl = toPath(model) + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'GET');
},
_restfulCreate: function(model, id, data, options) {
var url = toPath(model);
var path = url;
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'POST', data);
},
_restfulUpdate: function(model, id, data, options) {
var url = toPath(model);
if (App.vue.interfaces.contentValidators.methods._valueIsEmpty(id)) {
var path = url + '/';
}else{
var path = url + '/' + id;
}
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'PATCH', data);
},
_restfulDelete: function(model, id, options) {
var url = toPath(model);
var path = url + '/' + id;
var requestUrl = path + queryStringFromOptions(options, App.vue.config.rest_api.options);
return this._sendRequest(requestUrl, 'DELETE');
}
}
}
})();
| JavaScript | 0.000001 |
3f854bd6a0d4d0e5e363e1fc38dbdf6ba6693b2c | edit playground | src/app.js | src/app.js | var React = require('react')
var Hello = React.createClass({
render: function() {
return <div>Hello, {this.props.name}</div>
}
})
React.render(<Hello name="dian"/>, document.body)
| document.write('Hello Frontend Masters!')
var React = require('react')
var Hello = React.createClass({
render: function() {
return <div>Hello, {this.props.name}</div>
}
})
React.render(<Hello name="dian"/>, document.body) | JavaScript | 0.000001 |
96064ca82c38e6248a5f5f851b9046fc40776444 | fix cart | app/assets/javascripts/controllers/trade/my/carts/show-ready.js | app/assets/javascripts/controllers/trade/my/carts/show-ready.js | import { Controller } from 'stimulus'
class CartController extends Controller {
static targets = [ 'number' ];
connect() {
console.log(this.numberTarget.value)
}
update() {
var data = new FormData();
data.set(this.numberTarget.name, this.numberTarget.value);
Rails.ajax({ url: this.numberTarget.dataset.url, type: 'PATCH', dataType: 'script', data: data })
}
increase() {
this.numberTarget.value = this.numberTarget.valueAsNumber + 1;
this.update()
}
decrease() {
this.numberTarget.value = this.numberTarget.valueAsNumber - 1;
this.update()
}
}
application.register('cart', CartController);
| class CartController extends Stimulus.Controller {
//static targets = [ 'number' ];
connect() {
console.log(this.numberTarget.value)
}
update() {
var data = new FormData();
data.set(this.numberTarget.name, this.numberTarget.value);
Rails.ajax({ url: this.numberTarget.dataset.url, type: 'PATCH', dataType: 'script', data: data })
}
increase() {
this.numberTarget.value = this.numberTarget.valueAsNumber + 1;
this.update()
}
decrease() {
this.numberTarget.value = this.numberTarget.valueAsNumber - 1;
this.update()
}
}
application.register('cart', CartController);
| JavaScript | 0.000001 |
37f2ced956641f948101ebdd4fb0b26a63113c2b | Edit the verification base url to avoid strange anchor behavior and separate path and token | frontend/views/provider-form.js | frontend/views/provider-form.js | var Backbone = require('backbone'),
template = require("../templates/provider-form.hbs"),
i18n = require('i18next-client');
var config = require('../config');
module.exports = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function() {
var $el = this.$el;
$el.html(template({
}));
config.load('providertypes', function(e, data) {
$typeSel = $el.find('select[name=type]');
$.each(data, function() {
$option = $('<option></option>');
$option.attr({
value: this.url,
});
$option.text(this['name_' + config.get('lang')]);
$typeSel.append($option)
})
console.log($typeSel);
})
console.log($el);
},
events: {
"click .form-btn-submit": function() {
var data = {};
var $el = this.$el;
$el.find('[name]').each(function() {
var $field = $(this);
var value = $field.val();
var name = $field.attr('name');
var ml = typeof $field.data('i18n-field')==="undefined" ? false : true;
if (ml) {
var cur_lang = localStorage['lang'];
name = name + '_' + cur_lang;
}
data[name] = value;
// console.log(name + ': ' + value);
});
$el.find('.error').text('');
var errors = {};
// Password Handling
if (data['password1'].length === 0) {
errors['password1'] = ["Password must not be blank"];
}
if (data['password2'].length === 0) {
errors['password2'] = ["Password must be repeated"];
} else if (data['password1'] != data['password2']) {
errors['password2'] = ["Passwords must match"];
}
if (!errors['password1'] && !errors['password2']) {
data['password'] = data['password1'];
delete data.password1;
delete data.password2;
}
// Base Activation Link
data["base_activation_link"] = location.protocol+'//'+location.host+location.pathname+'?#/register/verify/';
$.ajax('//localhost:4005/api/providers/create_provider/', {
method: 'POST',
data: data,
error: function(e) {
$.extend(errors, e.responseJSON);
$.each(errors, function(k) {
console.log(k + ' (error): ' + this[0]);
var $error = $el.find('[for='+k+'] .error');
if ($error) {
$error.text(this[0]);
}
})
},
success: function(data) {
window.location = '#/register/confirm';
},
});
return false;
},
"click .form-btn-clear": function() {
this.$el.find('[name]').each(function() {
var $field = $(this);
$field.val('');
});
return false;
},
},
})
| var Backbone = require('backbone'),
template = require("../templates/provider-form.hbs"),
i18n = require('i18next-client');
var config = require('../config');
module.exports = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function() {
var $el = this.$el;
$el.html(template({
}));
config.load('providertypes', function(e, data) {
$typeSel = $el.find('select[name=type]');
$.each(data, function() {
$option = $('<option></option>');
$option.attr({
value: this.url,
});
$option.text(this['name_' + config.get('lang')]);
$typeSel.append($option)
})
console.log($typeSel);
})
console.log($el);
},
events: {
"click .form-btn-submit": function() {
var data = {};
var $el = this.$el;
$el.find('[name]').each(function() {
var $field = $(this);
var value = $field.val();
var name = $field.attr('name');
var ml = typeof $field.data('i18n-field')==="undefined" ? false : true;
if (ml) {
var cur_lang = localStorage['lang'];
name = name + '_' + cur_lang;
}
data[name] = value;
// console.log(name + ': ' + value);
});
$el.find('.error').text('');
var errors = {};
// Password Handling
if (data['password1'].length === 0) {
errors['password1'] = ["Password must not be blank"];
}
if (data['password2'].length === 0) {
errors['password2'] = ["Password must be repeated"];
} else if (data['password1'] != data['password2']) {
errors['password2'] = ["Passwords must match"];
}
if (!errors['password1'] && !errors['password2']) {
data['password'] = data['password1'];
delete data.password1;
delete data.password2;
}
// Base Activation Link
data["base_activation_link"] = location.protocol+'//'+location.host+location.pathname+'#/register/verify';
$.ajax('//localhost:4005/api/providers/create_provider/', {
method: 'POST',
data: data,
error: function(e) {
$.extend(errors, e.responseJSON);
$.each(errors, function(k) {
console.log(k + ' (error): ' + this[0]);
var $error = $el.find('[for='+k+'] .error');
if ($error) {
$error.text(this[0]);
}
})
},
success: function(data) {
window.location = '#/register/confirm';
},
});
return false;
},
"click .form-btn-clear": function() {
this.$el.find('[name]').each(function() {
var $field = $(this);
$field.val('');
});
return false;
},
},
})
| JavaScript | 0 |
0230a79eb937ed562c42124cdeaa6da25c874394 | add docstring to app.js | src/app.js | src/app.js | /**
* app.js
*
* This module is somewhat superfluous at the moment, its only being used to
* expose certain interfaces for debugging purposes. Perhaps it will evolve down
* the road to a more useful construct.
*/
define('app',
['vent', 'db', 'util', 'template'],
function( vent, db, util, tmpl ){
'use strict';
var app = window.app = {};
app.vent = vent;
app.db = db;
app.util = util;
app.tmpl = tmpl;
return app;
});
| define('app',
['vent', 'db', 'util', 'template'],
function( vent, db, util, tmpl ){
'use strict';
var app = window.app = {};
app.vent = vent;
app.db = db;
app.util = util;
app.tmpl = tmpl;
return app;
});
| JavaScript | 0.000001 |
532558b47ba9055c04301e69a201faef765d96dd | Refactor email page to use new textarea | app/scripts/Widget/plugins/PressureWidget/settings/EmailPage.js | app/scripts/Widget/plugins/PressureWidget/settings/EmailPage.js | import React, { Component, PropTypes } from 'react'
import { reduxForm } from 'redux-form'
import * as WidgetActions from '../../../actions'
import { FormFooter, InputTag } from '../../../components'
import {
FormRedux,
FormGroup,
ControlLabel,
FormControl
} from '../../../../Dashboard/Forms'
import { Base as PressureBase } from '../components/settings'
// Regex to validate Target (Ex.: Igor Santos <igor@nossascidades.org>)
const patternTarget = /[\w]+[ ]*<(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>/
class EmailPage extends Component {
constructor(props) {
super(props)
this.state = { targets: this.getTargetList() || [] }
}
getTargetString() {
const { targets } = this.state
return targets.join(';')
}
getTargetList() {
const { targets } = this.props
return targets && targets.split(';')
}
handleSubmit(values, dispatch) {
const { widget, credentials, editWidget, ...props } = this.props
const targets = this.getTargetString()
const settings = widget.settings || {}
const data = { ...widget, settings: { ...settings, ...values, targets } }
const params = { credentials, mobilization_id: props.mobilization.id }
return dispatch(editWidget(data, params))
}
render() {
const { fields: { pressure_subject, pressure_body }, ...props } = this.props
return (
<PressureBase location={props.location} mobilization={props.mobilization} widget={props.widget}>
<FormRedux onSubmit={::this.handleSubmit} {...props}>
<InputTag
label="Alvos"
values={this.state.targets}
onInsertTag={value => this.setState({ targets: [...this.state.targets, value] })}
onRemoveTag={value => this.setState({ targets: this.state.targets.filter(tag => tag !== value) })}
validate={value => {
const errors = { valid: true }
if (!value.match(patternTarget)) {
errors.valid = false
errors.message = 'Alvo fora do formato padrão. Ex.: Nome do alvo <alvo@provedor.com>'
}
return errors
}}
/>
<FormGroup controlId="email-subject-id" {...pressure_subject}>
<ControlLabel>Assunto do email</ControlLabel>
<FormControl type="text" />
</FormGroup>
<FormGroup controlId="email-body-id" {...pressure_body}>
<ControlLabel>Corpo do email que será enviado</ControlLabel>
<FormControl type="text" componentClass="textarea" />
</FormGroup>
</FormRedux>
</PressureBase>
)
}
}
EmailPage.propTypes = {
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
credentials: PropTypes.object.isRequired,
editWidget: PropTypes.func.isRequired,
// Redux form
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired
}
const fields = ['pressure_subject', 'pressure_body', 'targets']
const validate = values => {
const errors = {}
if (!values.pressure_subject) {
errors.pressure_subject = 'Preenchimento obrigatório'
}
if (!values.pressure_body) {
errors.pressure_body = 'Preenchimento obrigatório'
}
return errors
}
const parseTargetList = (targets = '') => targets.split(';')
export default reduxForm({
form: 'widgetForm',
fields,
validate
},
(state, ownProps) => ({
initialValues: {
...ownProps.widget.settings || {},
targets: parseTargetList(ownProps.widget.settings && ownProps.widget.settings.targets)
},
credentials: state.auth.credentials,
}), { ...WidgetActions })(EmailPage)
| import React, { Component, PropTypes } from 'react'
import { reduxForm } from 'redux-form'
import * as WidgetActions from '../../../actions'
import { FormFooter, InputTag } from '../../../components'
import {
FormRedux,
FormGroup,
ControlLabel,
FormControl
} from '../../../../Dashboard/Forms'
import { Base as PressureBase } from '../components/settings'
// Regex to validate Target (Ex.: Igor Santos <igor@nossascidades.org>)
const patternTarget = /[\w]+[ ]*<(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>/
class EmailPage extends Component {
constructor(props) {
super(props)
this.state = { targets: this.getTargetList() || [] }
}
getTargetString() {
const { targets } = this.state
return targets.join(';')
}
getTargetList() {
const { targets } = this.props
return targets && targets.split(';')
}
handleSubmit(values, dispatch) {
const { widget, credentials, editWidget, ...props } = this.props
const targets = this.getTargetString()
const settings = widget.settings || {}
const data = { ...widget, settings: { ...settings, ...values, targets } }
const params = { credentials, mobilization_id: props.mobilization.id }
return dispatch(editWidget(data, params))
}
render() {
const { fields: { pressure_subject, pressure_body }, ...props } = this.props
return (
<PressureBase location={props.location} mobilization={props.mobilization} widget={props.widget}>
<FormRedux onSubmit={::this.handleSubmit} {...props}>
<InputTag
label="Alvos"
values={this.state.targets}
onInsertTag={value => this.setState({ targets: [...this.state.targets, value] })}
onRemoveTag={value => this.setState({ targets: this.state.targets.filter(tag => tag !== value) })}
validate={value => {
const errors = { valid: true }
if (!value.match(patternTarget)) {
errors.valid = false
errors.message = 'Alvo fora do formato padrão. Ex.: Nome do alvo <alvo@provedor.com>'
}
return errors
}}
/>
<FormGroup controlId="email-subject-id" {...pressure_subject}>
<ControlLabel>Assunto do email</ControlLabel>
<FormControl type="text" />
</FormGroup>
<FormGroup controlId="email-body-id" {...pressure_body}>
<ControlLabel>Corpo do email que será enviado</ControlLabel>
<FormControl type="text" style={{height: '20rem'}} componentClass="textarea" />
</FormGroup>
</FormRedux>
</PressureBase>
)
}
}
EmailPage.propTypes = {
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
credentials: PropTypes.object.isRequired,
editWidget: PropTypes.func.isRequired,
// Redux form
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired
}
const fields = ['pressure_subject', 'pressure_body', 'targets']
const validate = values => {
const errors = {}
if (!values.pressure_subject) {
errors.pressure_subject = 'Preenchimento obrigatório'
}
if (!values.pressure_body) {
errors.pressure_body = 'Preenchimento obrigatório'
}
return errors
}
const parseTargetList = (targets = '') => targets.split(';')
export default reduxForm({
form: 'widgetForm',
fields,
validate
},
(state, ownProps) => ({
initialValues: {
...ownProps.widget.settings || {},
targets: parseTargetList(ownProps.widget.settings && ownProps.widget.settings.targets)
},
credentials: state.auth.credentials,
}), { ...WidgetActions })(EmailPage)
| JavaScript | 0 |
c7761e26070c3e4bcd8d6a7016f0bdc18257a39b | clean up naming | analysis/test/js/spec/directives/sumaCsvHourly.js | analysis/test/js/spec/directives/sumaCsvHourly.js | 'use strict';
describe('Directive: sumaCsvHourly', function () {
// load the directive's module
beforeEach(module('sumaAnalysis'));
beforeEach(module('csvHourlyMock'));
// load the directive's template
beforeEach(module('views/directives/csv.html'));
var element,
scope,
MockLink,
Ctrlscope;
beforeEach(inject(function ($rootScope, $compile, mockData, mockLink) {
element = angular.element('<span data-suma-csv-hourly data-data="data"></span>');
MockLink = mockLink;
scope = $rootScope.$new();
scope.data = mockData;
element = $compile(element)(scope);
scope.$digest();
Ctrlscope = element.isolateScope();
}));
it('should attach a data url to the element', function () {
Ctrlscope.download(scope.data);
expect(Ctrlscope.href).to.equal(MockLink);
});
});
| 'use strict';
describe('Directive: sumaCsvHourly', function () {
// load the directive's module
beforeEach(module('sumaAnalysis'));
beforeEach(module('csvHourlyMock'));
// load the directive's template
beforeEach(module('views/directives/csv.html'));
var element,
scope,
testLink,
Ctrlscope;
beforeEach(inject(function ($rootScope, $compile, mockData, mockLink) {
element = angular.element('<span data-suma-csv-hourly data-data="data"></span>');
testLink = mockLink;
scope = $rootScope.$new();
scope.data = mockData;
element = $compile(element)(scope);
scope.$digest();
Ctrlscope = element.isolateScope();
}));
it('should attach a data url to the element', function () {
Ctrlscope.download(scope.data);
expect(Ctrlscope.href).to.equal(testLink);
});
});
| JavaScript | 0.003219 |
1d7ea9c960b3d914158142a25cebfb76dd7f0473 | Remove VariablesAreInputTypesRule | packages/relay-compiler/core/RelayValidator.js | packages/relay-compiler/core/RelayValidator.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const Profiler = require('./GraphQLCompilerProfiler');
const util = require('util');
const {
NoUnusedVariablesRule,
PossibleFragmentSpreadsRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
formatError,
} = require('graphql');
import type {Schema} from './Schema';
import type {
DocumentNode,
FieldNode,
ValidationRule,
ValidationContext,
} from 'graphql';
function validateOrThrow(
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
): void {
const validationErrors = schema.DEPRECATED__validate(document, rules);
if (validationErrors && validationErrors.length > 0) {
const formattedErrors = validationErrors.map(formatError);
const errorMessages = validationErrors.map(e => e.toString());
const error = new Error(
util.format(
'You supplied a GraphQL document with validation errors:\n%s',
errorMessages.join('\n'),
),
);
(error: $FlowFixMe).validationErrors = formattedErrors;
throw error;
}
}
function DisallowIdAsAliasValidationRule(
context: ValidationContext,
): $TEMPORARY$object<{|Field: (field: FieldNode) => void|}> {
return {
Field(field: FieldNode): void {
if (
field.alias &&
field.alias.value === 'id' &&
field.name.value !== 'id'
) {
throw new Error(
'RelayValidator: Relay does not allow aliasing fields to `id`. ' +
'This name is reserved for the globally unique `id` field on ' +
'`Node`.',
);
}
},
};
}
module.exports = {
GLOBAL_RULES: [
/* Some rules are not enabled (potentially non-exhaustive)
*
* - KnownFragmentNamesRule: RelayClassic generates fragments at runtime,
* so RelayCompat queries might reference fragments unknown in build time.
* - NoFragmentCyclesRule: Because of @argumentDefinitions, this validation
* incorrectly flags a subset of fragments using @include/@skip as
* recursive.
* - NoUndefinedVariablesRule: Because of @argumentDefinitions, this
* validation incorrectly marks some fragment variables as undefined.
* - NoUnusedFragmentsRule: Queries generated dynamically with RelayCompat
* might use unused fragments.
* - OverlappingFieldsCanBeMergedRule: RelayClassic auto-resolves
* overlapping fields by generating aliases.
*/
NoUnusedVariablesRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
],
LOCAL_RULES: [
/*
* GraphQL built-in rules: a subset of these rules are enabled, some of the
* default rules conflict with Relays-specific features:
* - FieldsOnCorrectTypeRule: is not aware of @fixme_fat_interface.
* - KnownDirectivesRule: doesn't pass with @arguments and other Relay
* directives.
* - ScalarLeafsRule: is violated by the @match directive since these rules
* run before any transform steps.
* - VariablesInAllowedPositionRule: violated by the @arguments directive,
* since @arguments is not defined in the schema. relay-compiler does its
* own type-checking for variable/argument usage that is aware of fragment
* variables.
*/
PossibleFragmentSpreadsRule,
// Relay-specific validation
DisallowIdAsAliasValidationRule,
],
validate: (Profiler.instrument(validateOrThrow, 'RelayValidator.validate'): (
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
) => void),
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const Profiler = require('./GraphQLCompilerProfiler');
const util = require('util');
const {
NoUnusedVariablesRule,
PossibleFragmentSpreadsRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
VariablesAreInputTypesRule,
formatError,
} = require('graphql');
import type {Schema} from './Schema';
import type {
DocumentNode,
FieldNode,
ValidationRule,
ValidationContext,
} from 'graphql';
function validateOrThrow(
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
): void {
const validationErrors = schema.DEPRECATED__validate(document, rules);
if (validationErrors && validationErrors.length > 0) {
const formattedErrors = validationErrors.map(formatError);
const errorMessages = validationErrors.map(e => e.toString());
const error = new Error(
util.format(
'You supplied a GraphQL document with validation errors:\n%s',
errorMessages.join('\n'),
),
);
(error: $FlowFixMe).validationErrors = formattedErrors;
throw error;
}
}
function DisallowIdAsAliasValidationRule(
context: ValidationContext,
): $TEMPORARY$object<{|Field: (field: FieldNode) => void|}> {
return {
Field(field: FieldNode): void {
if (
field.alias &&
field.alias.value === 'id' &&
field.name.value !== 'id'
) {
throw new Error(
'RelayValidator: Relay does not allow aliasing fields to `id`. ' +
'This name is reserved for the globally unique `id` field on ' +
'`Node`.',
);
}
},
};
}
module.exports = {
GLOBAL_RULES: [
/* Some rules are not enabled (potentially non-exhaustive)
*
* - KnownFragmentNamesRule: RelayClassic generates fragments at runtime,
* so RelayCompat queries might reference fragments unknown in build time.
* - NoFragmentCyclesRule: Because of @argumentDefinitions, this validation
* incorrectly flags a subset of fragments using @include/@skip as
* recursive.
* - NoUndefinedVariablesRule: Because of @argumentDefinitions, this
* validation incorrectly marks some fragment variables as undefined.
* - NoUnusedFragmentsRule: Queries generated dynamically with RelayCompat
* might use unused fragments.
* - OverlappingFieldsCanBeMergedRule: RelayClassic auto-resolves
* overlapping fields by generating aliases.
*/
NoUnusedVariablesRule,
UniqueArgumentNamesRule,
UniqueInputFieldNamesRule,
UniqueVariableNamesRule,
],
LOCAL_RULES: [
/*
* GraphQL built-in rules: a subset of these rules are enabled, some of the
* default rules conflict with Relays-specific features:
* - FieldsOnCorrectTypeRule: is not aware of @fixme_fat_interface.
* - KnownDirectivesRule: doesn't pass with @arguments and other Relay
* directives.
* - ScalarLeafsRule: is violated by the @match directive since these rules
* run before any transform steps.
* - VariablesInAllowedPositionRule: violated by the @arguments directive,
* since @arguments is not defined in the schema. relay-compiler does its
* own type-checking for variable/argument usage that is aware of fragment
* variables.
*/
PossibleFragmentSpreadsRule,
VariablesAreInputTypesRule,
// Relay-specific validation
DisallowIdAsAliasValidationRule,
],
validate: (Profiler.instrument(validateOrThrow, 'RelayValidator.validate'): (
schema: Schema,
document: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
) => void),
};
| JavaScript | 0 |
884c167fc7f8d98788652579d8959047544628c8 | Support graphql in resolve-scripts (#171) | packages/resolve-scripts/src/server/express.js | packages/resolve-scripts/src/server/express.js | import bodyParser from 'body-parser';
import express from 'express';
import path from 'path';
import query from 'resolve-query';
import commandHandler from 'resolve-command';
import request from 'request';
import ssr from './render';
import eventStore from './event_store';
import config from '../configs/server.config.js';
const STATIC_PATH = '/static';
const rootDirectory = process.env.ROOT_DIR || '';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const executeQuery = query({
eventStore,
readModels: config.queries
});
const executeCommand = commandHandler({
eventStore,
aggregates: config.aggregates
});
if (config.gateways) {
config.gateways.forEach(gateway => gateway({ executeQuery, executeCommand, eventStore }));
}
app.use((req, res, next) => {
req.resolve = {
executeQuery,
executeCommand,
eventStore
};
next();
});
try {
config.extendExpress(app);
} catch (err) {}
app.get(`${rootDirectory}/api/queries/:queryName`, (req, res) => {
const gqlQuery = req.query && req.query.graphql;
const result = gqlQuery
? executeQuery(req.params.queryName, gqlQuery)
: executeQuery(req.params.queryName);
result.then(state => res.status(200).json(state)).catch((err) => {
res.status(500).end('Query error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
app.post(`${rootDirectory}/api/commands`, (req, res) => {
executeCommand(req.body).then(() => res.status(200).send('ok')).catch((err) => {
res.status(500).end('Command error:' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
const staticMiddleware = process.env.NODE_ENV === 'production'
? express.static(path.join(__dirname, '../../dist/static'))
: (req, res) => {
var newurl = 'http://localhost:3001' + req.path;
request(newurl).pipe(res);
};
app.use(`${rootDirectory}${STATIC_PATH}`, staticMiddleware);
app.get([`${rootDirectory}/*`, `${rootDirectory || '/'}`], async (req, res) => {
try {
const state = await config.initialState(executeQuery, {
cookies: req.cookies,
hostname: req.hostname,
originalUrl: req.originalUrl,
body: req.body
});
ssr(state, { req, res });
} catch (err) {
res.status(500).end('SSR error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
}
});
export default app;
| import bodyParser from 'body-parser';
import express from 'express';
import path from 'path';
import query from 'resolve-query';
import commandHandler from 'resolve-command';
import request from 'request';
import ssr from './render';
import eventStore from './event_store';
import config from '../configs/server.config.js';
const STATIC_PATH = '/static';
const rootDirectory = process.env.ROOT_DIR || '';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const executeQuery = query({
eventStore,
readModels: config.queries
});
const executeCommand = commandHandler({
eventStore,
aggregates: config.aggregates
});
if (config.gateways) {
config.gateways.forEach(gateway => gateway({ executeQuery, executeCommand, eventStore }));
}
app.use((req, res, next) => {
req.resolve = {
executeQuery,
executeCommand,
eventStore
};
next();
});
try {
config.extendExpress(app);
} catch (err) {}
app.get(`${rootDirectory}/api/queries/:queryName`, (req, res) => {
executeQuery(req.params.queryName).then(state => res.status(200).json(state)).catch((err) => {
res.status(500).end('Query error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
app.post(`${rootDirectory}/api/commands`, (req, res) => {
executeCommand(req.body).then(() => res.status(200).send('ok')).catch((err) => {
res.status(500).end('Command error:' + err.message);
// eslint-disable-next-line no-console
console.log(err);
});
});
const staticMiddleware = process.env.NODE_ENV === 'production'
? express.static(path.join(__dirname, '../../dist/static'))
: (req, res) => {
var newurl = 'http://localhost:3001' + req.path;
request(newurl).pipe(res);
};
app.use(`${rootDirectory}${STATIC_PATH}`, staticMiddleware);
app.get([`${rootDirectory}/*`, `${rootDirectory || '/'}`], async (req, res) => {
try {
const state = await config.initialState(executeQuery, {
cookies: req.cookies,
hostname: req.hostname,
originalUrl: req.originalUrl,
body: req.body
});
ssr(state, { req, res });
} catch (err) {
res.status(500).end('SSR error: ' + err.message);
// eslint-disable-next-line no-console
console.log(err);
}
});
export default app;
| JavaScript | 0 |
cee1bc36ab83de27ce8e4809efd2c1f23b93195b | Update browser versions | protractor-remote.conf.js | protractor-remote.conf.js | "use strict";
var request = require("request");
exports.config = {
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
allScriptsTimeout: 11000,
specs: [
"e2e-tests/*.js"
],
multiCapabilities: [
addCommon({browserName: "chrome", version: "latest"}),
addCommon({browserName: "firefox", version: "latest"}),
addCommon({browserName: "internet explorer", version: "latest"}),
addCommon({browserName: "safari", version: "9.0", platform: "OS X 10.11"}),
],
baseUrl: "http://localhost:9090",
onPrepare: function() {
// Disable animations so e2e tests run more quickly
browser.addMockModule("disableNgAnimate", function() {
angular.module("disableNgAnimate", []).run(["$animate", function($animate) {
$animate.enabled(false);
}]);
});
var defer = protractor.promise.defer();
request(browser.baseUrl + "/test_is_integration", function(error, response, body) {
if (!error && response.statusCode === 418 && body === "true") {
defer.fulfill(body);
} else {
defer.reject("Not running against integration!");
}
});
return defer.promise;
},
framework: "jasmine2",
jasmineNodeOpts: {
defaultTimeoutInterval: 60000
}
};
function addCommon(capabilities) {
var buildLabel = "TRAVIS #" + process.env.TRAVIS_BUILD_NUMBER + " (" + process.env.TRAVIS_BUILD_ID + ")";
if (process.env.TRAVIS) {
return {
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER,
"name": "CCJ16 Registration (e2e)",
"build": buildLabel,
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
} else {
return {
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
}
}
| "use strict";
var request = require("request");
exports.config = {
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
allScriptsTimeout: 11000,
specs: [
"e2e-tests/*.js"
],
multiCapabilities: [
addCommon({browserName: "chrome", version: 46}),
addCommon({browserName: "firefox", version: 42}),
addCommon({browserName: "internet explorer", version: 11}),
addCommon({browserName: "safari", version: "9.0", platform: "OS X 10.11"}),
],
baseUrl: "http://localhost:9090",
onPrepare: function() {
// Disable animations so e2e tests run more quickly
browser.addMockModule("disableNgAnimate", function() {
angular.module("disableNgAnimate", []).run(["$animate", function($animate) {
$animate.enabled(false);
}]);
});
var defer = protractor.promise.defer();
request(browser.baseUrl + "/test_is_integration", function(error, response, body) {
if (!error && response.statusCode === 418 && body === "true") {
defer.fulfill(body);
} else {
defer.reject("Not running against integration!");
}
});
return defer.promise;
},
framework: "jasmine2",
jasmineNodeOpts: {
defaultTimeoutInterval: 60000
}
};
function addCommon(capabilities) {
var buildLabel = "TRAVIS #" + process.env.TRAVIS_BUILD_NUMBER + " (" + process.env.TRAVIS_BUILD_ID + ")";
if (process.env.TRAVIS) {
return {
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER,
"name": "CCJ16 Registration (e2e)",
"build": buildLabel,
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
} else {
return {
"browserName": capabilities.browserName,
"platform": capabilities.platform,
"version": capabilities.version,
"device-orientation": capabilities["device-orientation"],
};
}
}
| JavaScript | 0 |
7eb9a1111b42e55044d551cee8502dbff6ae95fa | Remove geolocation caching | geolocate.js | geolocate.js | /* global map */
(function () {
'use strict'
var latitude
var longitude
if (!map) return false
var getCurrentLocation = function (success, error) {
var geolocator = window.navigator.geolocation;
var options = {
enableHighAccuracy: true,
maximumAge: 10000
};
if (geolocator) {
// Fixes an infinite loop bug with Safari
// https://stackoverflow.com/questions/27150465/geolocation-api-in-safari-8-and-7-1-keeps-asking-permission/28436277#28436277
window.setTimeout(function () {
geolocator.getCurrentPosition(success, error, options);
}, 0);
} else {
document.getElementById('geolocator').style.display = 'none';
console.log('Browser does not support geolocation');
}
}
var onGeolocateSuccess = function (position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
/* global map */
map.setView([latitude, longitude], 17);
resetGeolocateButton();
}
var onGeolocateError = function (err) {
console.log(err);
alert('Unable to retrieve current position. Geolocation may be disabled on this browser or unavailable on this system.');
resetGeolocateButton();
}
var resetGeolocateButton = function () {
var button = document.getElementById('geolocator').querySelector('.geolocate-icon');
button.classList.remove('geolocating');
}
document.getElementById('geolocator').querySelector('.geolocate-icon').addEventListener('click', function (e) {
if (e.target.classList.contains('geolocating')) {
return false;
}
e.target.classList.add('geolocating');
getCurrentLocation(onGeolocateSuccess, onGeolocateError);
});
})()
| /* global map */
(function () {
'use strict'
var latitude
var longitude
if (!map) return false
var getCurrentLocation = function (success, error) {
var geolocator = window.navigator.geolocation;
var options = {
enableHighAccuracy: true,
maximumAge: 10000
};
if (geolocator) {
// Fixes an infinite loop bug with Safari
// https://stackoverflow.com/questions/27150465/geolocation-api-in-safari-8-and-7-1-keeps-asking-permission/28436277#28436277
window.setTimeout(function () {
geolocator.getCurrentPosition(success, error, options);
}, 0);
} else {
document.getElementById('geolocator').style.display = 'none';
console.log('Browser does not support geolocation');
}
}
var cacheCurrentLocation = function () {
var onSuccess = function (position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
}
// Do nothing if we are unable to do geolocation
// No error callback
getCurrentLocation(onSuccess)
}
var onGeolocateSuccess = function (position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
/* global map */
map.setView([latitude, longitude], 17);
resetGeolocateButton();
}
var onGeolocateError = function (err) {
console.log(err);
alert('Unable to retrieve current position. Geolocation may be disabled on this browser or unavailable on this system.');
resetGeolocateButton();
}
var resetGeolocateButton = function () {
var button = document.getElementById('geolocator').querySelector('.geolocate-icon');
button.classList.remove('geolocating');
}
document.getElementById('geolocator').querySelector('.geolocate-icon').addEventListener('click', function (e) {
if (e.target.classList.contains('geolocating')) {
return false;
}
e.target.classList.add('geolocating');
getCurrentLocation(onGeolocateSuccess, onGeolocateError);
});
// Requests browser's permission to use
// geolocator upon page load, if necessary
cacheCurrentLocation()
})()
| JavaScript | 0.000001 |
332a3df24e66bc7fee91f5cc0256feff045e431e | Reverting state to 3adfae7e5b3b70310dae64de0ae8a1b8b5471f5f | src/routes/yelpSearch.js | src/routes/yelpSearch.js | var express = require('express'),
yelp = require('yelp-fusion');
var router = express.Router();
var client;
const token = yelp.accessToken(process.env.YELP_KEY, process.env.YELP_SECRET).then(response =>{
client = yelp.client(response.jsonBody.access_token);
}).catch(e => {
console.log(e);
});
function randomGenerator (numBus) {
return Math.floor(Math.random() * numBus);
}
router.post('/yelpSearch', (req, res) => {
let query = req.body.data.query;
let coords = req.body.data.coords.split(',');
// Splits the coordinates into latitude and longitude values
let lat = coords[0], lon = coords[1];
// Radius of search in meters
let rad = 9000;
// If stay, shows radius of 1 mile, otherwise 6 miles
if (req.body.data.stay) {
rad = 1500;
} else {
rad = 9000;
}
// Check to make sure query and coords got passed through
if (query || coords === undefined) {
client.search({
term: query,
latitude: lat ,
longitude: lon ,
radius: rad,
categories: ("coffee"),
limit: 50
}).then(response => {
const resJson = response.jsonBody
// Variable to check when response value found
let resVal;
// Generates a random business number upto 50
let count = resJson.businesses.length;
let randBus = randomGenerator(count);
while (resVal === undefined) {
let randBusiness = resJson.businesses[randBus]
// Only marks cafes with a 4 or higher rating
if (randBusiness.rating >= 4) {
// Returns the selected business name
res.status(200).json(resJson.businesses[randBus]);
resVal = resJson.businesses[randBus].name;
} else {
// Loops with another randomly generated business number
randBus = randomGenerator(count);
}
}
}).catch(e => {
console.log(e);
});
}
})
module.exports = router;
| var express = require('express'),
yelp = require('yelp-fusion');
var router = express.Router();
var client;
const token = yelp.accessToken(process.env.YELP_KEY, process.env.YELP_SECRET).then(response =>{
client = yelp.client(response.jsonBody.access_token);
}).catch(e => {
console.log(e);
});
function randomGenerator (numBus) {
return Math.floor(Math.random() * numBus);
}
function yelpSearch(query, lat, lon, rad) {
}
router.post('/yelpSearch', (req, res) => {
let query = req.body.data.query;
let coords = req.body.data.coords.split(',');
// Splits the coordinates into latitude and longitude values
let lat = coords[0], lon = coords[1];
// Radius of search in meters
let rad = 9000;
// If stay, shows radius of 1 mile, otherwise 6 miles
if (req.body.data.stay) {
rad = 500;
} else {
rad = 9000;
}
console.log("HI");
//TODO: Increase search radius if nothing found
//TODO: Probably put search in own function, put into a while loop
//TODO: Return 404 on errors, alert on page of error
// Check to make sure query and coords got passed through
if (query || coords === undefined) {
client.search({
term: query,
latitude: lat ,
longitude: lon ,
radius: rad,
categories: ("coffee"),
limit: 50
}).then(response => {
const resJson = response.jsonBody
// Variable to check when response value found
let resVal;
// Generates a random business number upto 50
let count = resJson.businesses.length;
let randBus = randomGenerator(count);
while (resVal === undefined) {
let randBusiness = resJson.businesses[randBus]
// Only marks cafes with a 4 or higher rating
if (randBusiness.rating >= 4) {
// Returns the selected business name
return res.status(200).json(resJson.businesses[randBus]);
resVal = resJson.businesses[randBus].name;
} else {
// Loops with another randomly generated business number
randBus = randomGenerator(count);
}
}
}).catch(e => {
return res.status(404).json({data: "Failed to find :("});
console.log(e);
});
}
})
module.exports = router;
| JavaScript | 0.999651 |
235aadbff69e88a730c99c3c10df3737774199e9 | Fix duplicating of alternate label input | htdocs/js/directive/if.js | htdocs/js/directive/if.js | /**
* Directive very highly inspired by core ngIf but evaluate only on events instead of $watch()
*/
angular.module('myApp.directives').directive('gimsIf', function($animate, $rootScope) {
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} nodes array like object
* @returns {jqLite} jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
// collection, otherwise update the original collection.
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes = [node];
do {
node = node.nextSibling;
if (!node) {
break;
}
blockNodes.push(node);
} while (node !== endNode);
return $(blockNodes);
}
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
function evalCondition() {
var value = $scope.$eval($attr.gimsIf);
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end gimsIf: ' + $attr.gimsIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
}
$rootScope.$on('gims-tablefilter-show-labels-toggled', function gimsIfWatchAction() {
evalCondition();
});
evalCondition();
}
};
});
| /**
* Directive very highly inspired by core ngIf but evaluate only on events instead of $watch()
*/
angular.module('myApp.directives').directive('gimsIf', function($animate, $rootScope) {
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} nodes array like object
* @returns {DOMElement} object containing the elements
*/
function getBlockElements(nodes) {
var startNode = nodes[0],
endNode = nodes[nodes.length - 1];
if (startNode === endNode) {
return $(startNode);
}
var element = startNode;
var elements = [element];
do {
element = element.nextSibling;
if (!element) {
break;
}
elements.push(element);
} while (element !== endNode);
return $(elements);
}
function evalCondition(block, childScope, previousElements,$scope, $element, $attr, ctrl, $transclude) {
var value = $scope.$eval($attr.gimsIf);
if (value) {
if (!childScope) {
childScope = $scope.$new();
$transclude(childScope, function(clone) {
clone[clone.length++] = document.createComment(' end gimsIf: ' + $attr.gimsIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when it's template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockElements(block.clone);
$animate.leave(previousElements, function() {
previousElements = null;
});
block = null;
}
}
}
return {
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
$rootScope.$on('gims-tablefilter-show-labels-toggled', function gimsIfWatchAction() {
evalCondition(block, childScope, previousElements,$scope, $element, $attr, ctrl, $transclude);
});
evalCondition(block, childScope, previousElements,$scope, $element, $attr, ctrl, $transclude);
}
};
});
| JavaScript | 0 |
cbc464000d03364d67e5b6c89e0bd22ef7de5f27 | Attach event listeners also to dynamically inserted elements. Fixes #150 | pari/article/static/article/js/media_player.js | pari/article/static/article/js/media_player.js | $(function(){
$("body").on("shown.bs.modal", ".media-popup", function () {
if($(this).data('video')) {
var youtube_url = "http://www.youtube.com/embed/" + $(this).data('video') + "?autoplay=1";
$('.video-container', this).html('<iframe src="' + youtube_url + '" frameborder="0" allowfullscreen></iframe>');
} else {
var soundcloud_url = "https://w.soundcloud.com/player/?url=http://api.soundcloud.com/tracks/" + $(this).data('audio');
$('.audio-container', this).html('<iframe width="100%" height="166" scrolling="no" frameborder="no" src="' + soundcloud_url + '" frameborder="0"></iframe>');
}
});
$("body").on('hidden.bs.modal', ".media-popup", function () {
$('.video-container', this).html('');
$('.audio-container', this).html('');
});
}); | $(function(){
$(".media-popup").on("shown.bs.modal", function () {
if($(this).data('video')) {
var youtube_url = "http://www.youtube.com/embed/" + $(this).data('video') + "?autoplay=1";
$('.video-container', this).html('<iframe src="' + youtube_url + '" frameborder="0" allowfullscreen></iframe>');
} else {
var soundcloud_url = "https://w.soundcloud.com/player/?url=http://api.soundcloud.com/tracks/" + $(this).data('audio');
$('.audio-container', this).html('<iframe width="100%" height="166" scrolling="no" frameborder="no" src="' + soundcloud_url + '" frameborder="0"></iframe>');
}
});
$(".media-popup").on('hidden.bs.modal', function () {
$('.video-container', this).html('');
$('.audio-container', this).html('');
});
}); | JavaScript | 0 |
b8f3f7b57ac0fbde9c1bdd1f3b3ccb931a131c43 | fix localforage error | src/app.js | src/app.js | import feathers from 'feathers/client';
import hooks from 'feathers-hooks';
import rest from 'feathers-rest/client';
import socketio from 'feathers-socketio/client';
import authentication from 'feathers-authentication-client';
import io from 'socket.io-client';
import superagent from 'superagent';
import config from './config';
const storage = __SERVER__ ? require('localstorage-memory') : require('localforage');
const host = clientUrl => (__SERVER__ ? `http://${config.apiHost}:${config.apiPort}` : clientUrl);
const configureApp = transport => feathers()
.configure(transport)
.configure(hooks())
.configure(authentication({ storage }));
export const socket = io('', { path: host('/ws'), autoConnect: false });
const app = configureApp(socketio(socket));
export default app;
export const restApp = configureApp(rest(host('/api')).superagent(superagent));
export function exposeInitialRequest(req) {
restApp.defaultService = null;
restApp.configure(rest(host('/api')).superagent(superagent, {
headers: {
Cookie: req.get('cookie'),
authorization: req.header('authorization')
}
}));
const accessToken = req.header('authorization') || (req.cookies && req.cookies['feathers-jwt']);
restApp.set('accessToken', accessToken);
}
| import feathers from 'feathers/client';
import hooks from 'feathers-hooks';
import rest from 'feathers-rest/client';
import socketio from 'feathers-socketio/client';
import authentication from 'feathers-authentication-client';
import io from 'socket.io-client';
import superagent from 'superagent';
import localForage from 'localforage';
import config from './config';
const storage = __SERVER__ ? require('localstorage-memory') : localForage;
const host = clientUrl => (__SERVER__ ? `http://${config.apiHost}:${config.apiPort}` : clientUrl);
const configureApp = transport => feathers()
.configure(transport)
.configure(hooks())
.configure(authentication({ storage }));
export const socket = io('', { path: host('/ws'), autoConnect: false });
const app = configureApp(socketio(socket));
export default app;
export const restApp = configureApp(rest(host('/api')).superagent(superagent));
export function exposeInitialRequest(req) {
restApp.defaultService = null;
restApp.configure(rest(host('/api')).superagent(superagent, {
headers: {
Cookie: req.get('cookie'),
authorization: req.header('authorization')
}
}));
const accessToken = req.header('authorization') || (req.cookies && req.cookies['feathers-jwt']);
restApp.set('accessToken', accessToken);
}
| JavaScript | 0.000001 |
1f2de197d30e05141d9a6418c2b4a973ecfab6b1 | Fix bugs in AST module | src/AST.js | src/AST.js | /*
NOTE: We forego using classes and class-based inheritance because at this time
super() tends to be slow in transpiled code. Instead, we use regular constructor
functions and give them a common prototype property.
*/
import * as Nodes from './Nodes.js';
export * from './Nodes.js';
function isNode(x) {
return x !== null && typeof x === 'object' && typeof x.type === 'string';
}
class AstNode {
children() {
let keys = Object.keys(this);
let list = [];
for (let i = 0; i < keys.length; ++i) {
if (keys[i] === 'parent')
continue;
let value = this[keys[i]];
if (Array.isArray(value)) {
for (let j = 0; j < value.length; ++j) {
if (isNode(value[j]))
list.push(value[j]);
}
} else if (isNode(value)) {
list.push(value);
}
}
return list;
}
}
Object.keys(Nodes).forEach(k => Nodes[k].prototype = AstNode.prototype);
| /*
NOTE: We forego using classes and class-based inheritance because at this time
super() tends to be slow in transpiled code. Instead, we use regular constructor
functions and give them a common prototype property.
*/
import * as Nodes from './Nodes.js';
export * from './Nodes.js';
function isNode(x) {
return x !== null && typeof x === 'object' && typeof x.type === 'string';
}
class AstNode {
children() {
let keys = Object.keys(this);
let list = [];
for (let i = 0; i < keys.length; ++i) {
if (keys[i] === 'parent')
break;
let value = this[keys[i]];
if (Array.isArray(value)) {
for (var j = 0; j < value.length; ++j) {
if (isNode(value[j]))
list.push(value[j]);
}
} else if (isNode(value)) {
list.push(value);
}
}
return list;
}
}
Object.keys(Nodes).forEach(k => Nodes[k].prototype = AstNode.prototype);
| JavaScript | 0.000001 |
699d473ac92ab61a7abf32002c500150633cfc08 | enable advpng test (#13) | test/advpng.js | test/advpng.js | import test from 'ava'
import { readFile, writeFile, find, rm } from 'fildes-extra'
import { join } from 'path'
import imagemin from 'imagemin'
import imageminAdvpng from 'imagemin-advpng'
const images = join(__dirname, 'images')
const build = join(__dirname, 'build')
test.before(() => {
return find(join(build, '**/advpng.*.png'))
.then(files => files.map(file => rm(file)))
})
const advpng = files => {
return Promise.all(files.map(file => {
return readFile(join(images, file))
.then(buffer => imagemin.buffer(buffer, {
plugins: [imageminAdvpng({
// optimizationLevel: 3
})]
}))
.then(buffer => writeFile(join(build, file, 'advpng.default.png'), buffer))
}))
}
test('advpng', t => {
return find('*.png', { cwd: images })
.then(advpng)
.then(() => find(join(build, '**/advpng.*.png')))
.then(imgs => t.truthy(imgs.length, `found ${imgs.length} advpng's`))
})
| import test from 'ava'
import { readFile, writeFile, find, rm } from 'fildes-extra'
import { join } from 'path'
import imagemin from 'imagemin'
import imageminAdvpng from 'imagemin-advpng'
const images = join(__dirname, 'images')
const build = join(__dirname, 'build')
test.before(() => {
return find(join(build, '**/advpng.*.png'))
.then(files => files.map(file => rm(file)))
})
const advpng = files => {
return Promise.all(files.map(file => {
return readFile(join(images, file))
.then(buffer => imagemin.buffer(buffer, {
plugins: [imageminAdvpng({
// optimizationLevel: 3
})]
}))
.then(buffer => writeFile(join(build, file, 'advpng.default.png'), buffer))
}))
}
// https://github.com/imagemin/imagemin-advpng/issues/3
test.skip('advpng', t => {
return find('*.png', { cwd: images })
.then(advpng)
.then(() => find(join(build, '**/advpng.*.png')))
.then(imgs => t.truthy(imgs.length, `found ${imgs.length} advpng's`))
})
| JavaScript | 0 |
6a0d0d68853cf7757ebcf92cd685f1093dbdfd39 | Fix cookie domain generator | public/javascript/core.js | public/javascript/core.js | //Reusable functions
var Alphagov = {
cookie_domain: function() {
host_parts = document.location.host.split('.').reverse();
return '.' + host_parts.slice(0, 3).reverse().join('.');
},
read_cookie: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
delete_cookie: function(name) {
if (document.cookie && document.cookie != '') {
var date = new Date();
date.setTime(date.getTime()-(24*60*60*1000)); // 1 day ago
document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
},
write_permanent_cookie: function(name, value) {
var date = new Date(2021, 12, 31);
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
}
//General page setup
jQuery(document).ready(function() {
//Setup annotator links
$('a.annotation').each(function(index) {
$(this).linkAnnotator();
});
var has_no_tour_cookie = function() {
return Alphagov.read_cookie('been_on_tour') == null;
}
var write_tour_coookie = function() {
Alphagov.write_permanent_cookie('been_on_tour', 'true');
}
var launch_tour = function() {
$('<div id="splash-back" class="popover-mask"></div>').appendTo($('body'));
$('#splash-back').hide();
$('#splash-back').load('/tour.html #splash', function() {
$(document).trigger('tour-ready');
$('#tour-close').click(close_tour);
$('#splash-back').fadeIn();
});
return false;
}
var close_tour = function() {
$('#splash-back').fadeOut().remove();
return false;
}
//setup tour click event
$('#tour-launcher').click(launch_tour);
//set initial cookie ?
if (has_no_tour_cookie()) {
write_tour_coookie();
launch_tour();
}
});
//Tour setup
$(document).bind('tour-ready', function () {
var $panels = $('#slider .scrollContainer > div');
var $container = $('#slider .scrollContainer');
// if false, we'll float all the panels left and fix the width
// of the container
var horizontal = true;
// collect the scroll object, at the same time apply the hidden overflow
// to remove the default scrollbars that will appear
var $scroll = $('#slider .scroll').css('overflow', 'hidden');
// handle nav selection
function selectNav() {
var nav_li = $(this);
nav_li.parents('ul:first').find('a').removeClass('selected');
nav_li.addClass('selected');
}
$('#slider .navigation').find('a').click(selectNav);
// go find the navigation link that has this target and select the nav
function trigger(data) {
var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
selectNav.call(el);
}
//setup scroll optioons
var scrollOptions = {
target: $scroll, // the element that has the overflow
items: $panels,
navigation: '.navigation a',
axis: 'xy',
onAfter: trigger, // our final callback
offset: 0,
duration: 500,
};
//set first item selected and then setup scroll
$('ul.navigation a:first').click();
$.localScroll(scrollOptions);
}); | //Reusable functions
var Alphagov = {
cookie_domain: function() {
host_parts = document.location.host.split('.');
return '.' + host_parts.slice(-3, 3).join('.');
},
read_cookie: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
delete_cookie: function(name) {
if (document.cookie && document.cookie != '') {
var date = new Date();
date.setTime(date.getTime()-(24*60*60*1000)); // 1 day ago
document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
},
write_permanent_cookie: function(name, value) {
var date = new Date(2021, 12, 31);
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
}
//General page setup
jQuery(document).ready(function() {
//Setup annotator links
$('a.annotation').each(function(index) {
$(this).linkAnnotator();
});
var has_no_tour_cookie = function() {
return Alphagov.read_cookie('been_on_tour') == null;
}
var write_tour_coookie = function() {
Alphagov.write_permanent_cookie('been_on_tour', 'true');
}
var launch_tour = function() {
$('<div id="splash-back" class="popover-mask"></div>').appendTo($('body'));
$('#splash-back').hide();
$('#splash-back').load('/tour.html #splash', function() {
$(document).trigger('tour-ready');
$('#tour-close').click(close_tour);
$('#splash-back').fadeIn();
});
return false;
}
var close_tour = function() {
$('#splash-back').fadeOut().remove();
return false;
}
//setup tour click event
$('#tour-launcher').click(launch_tour);
//set initial cookie ?
if (has_no_tour_cookie()) {
write_tour_coookie();
launch_tour();
}
});
//Tour setup
$(document).bind('tour-ready', function () {
var $panels = $('#slider .scrollContainer > div');
var $container = $('#slider .scrollContainer');
// if false, we'll float all the panels left and fix the width
// of the container
var horizontal = true;
// collect the scroll object, at the same time apply the hidden overflow
// to remove the default scrollbars that will appear
var $scroll = $('#slider .scroll').css('overflow', 'hidden');
// handle nav selection
function selectNav() {
var nav_li = $(this);
nav_li.parents('ul:first').find('a').removeClass('selected');
nav_li.addClass('selected');
}
$('#slider .navigation').find('a').click(selectNav);
// go find the navigation link that has this target and select the nav
function trigger(data) {
var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
selectNav.call(el);
}
//setup scroll optioons
var scrollOptions = {
target: $scroll, // the element that has the overflow
items: $panels,
navigation: '.navigation a',
axis: 'xy',
onAfter: trigger, // our final callback
offset: 0,
duration: 500,
};
//set first item selected and then setup scroll
$('ul.navigation a:first').click();
$.localScroll(scrollOptions);
}); | JavaScript | 0.000003 |
88df841c370dedd466d1c15cb06b8d556771bb14 | fix typo | src/app.js | src/app.js | import express from 'express';
import bodyParser from 'body-parser';
import requireDir from 'require-dir';
const routes = requireDir('./routes');
const connectors = (() => {
const c = requireDir('./connectors');
return Object.keys(c).reduce((m, k) => {
const v = c[k];
console.log(`(${k}) connector: ${v.name}`);
return Object.assign({}, m, {
[v.name]: v.action,
});
}, {});
})();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Object.keys(routes).forEach((k) => {
const v = routes[k];
console.log(`(${k}) path: ${v.path}`);
app.use(v.path, async (req, res, next) => {
try {
const start = new Date();
console.log(`[${start}] starting ${v.path}`);
const data = await v.action(req);
console.log(`[${new Date}] data`, data);
const groups = (data || []).reduce((m, d) => {
const g = m[d.connector] || []
g.push(d);
m[d.connector] = g;
return m;
}, {});
await Promise.all(Object.keys(groups).map(async (k) => {
const c = connectors[k];
if (c) {
await c(groups[k]);
} else {
console.warn(`CONNECTOR NOT FOUND: ${k}`);
}
return true;
}));
res.sendStatus(200);
const end = new Date();
console.log(`[${end}] finished ${v.path} after ${end.getTime() - start.getTime()} ms`);
} catch (e) {
console.error(e);
e.status = 500;
next(e);
}
});
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
console.error(err);
res.sendStatus(err.status || 500);
});
export default app;
| import express from 'express';
import bodyParser from 'body-parser';
import requireDir from 'require-dir';
const routes = requireDir('./routes');
const connectors = (() => {
const c = requireDir('./connectors');
return Object.keys(c).reduce((m, k) => {
const v = c[k];
console.log(`(${k}) connector: ${v.name}`);
return Object.assign({}, m, {
[v.name]: v.action,
});
}, {});
})();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Object.keys(routes).forEach((k) => {
const v = routes[k];
console.log(`(${k}) path: ${v.path}`);
app.use(v.path, async (req, res, next) => {
try {
const start = new Date();
console.log(`[${start}] starting ${v.path}`);
const data = await v.action(req);
console.log(`[${new Date}] data`, data);
const groups = (data || []).reduce((m, d) => {
const g = m[d.conector] || []
g.push(d);
m[d.conector] = g;
return m;
}, {});
await Promise.all(Object.keys(groups).map(async (k) => {
const c = connectors[k];
if (c) {
await c(groups[k]);
} else {
console.warn(`CONNECTOR NOT FOUND: ${k}`);
}
return true;
}));
res.sendStatus(200);
const end = new Date();
console.log(`[${end}] finished ${v.path} after ${end.getTime() - start.getTime()} ms`);
} catch (e) {
console.error(e);
e.status = 500;
next(e);
}
});
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
console.error(err);
res.sendStatus(err.status || 500);
});
export default app;
| JavaScript | 0.000864 |
956b553dac919df4cb90421aeeb094a9a3842eaf | Use filter in page search | src/search/find-pages.js | src/search/find-pages.js | import update from 'lodash/fp/update'
import db from '../pouchdb'
import { keyRangeForPrefix } from '../pouchdb'
import { pageKeyPrefix } from '../activity-logger'
import { searchableTextFields, revisePageFields } from '../page-analysis'
// Post-process result list after any retrieval of pages from the database.
const postprocessPagesResult = update('rows', rows => rows.map(
// Let the page analysis module augment or revise the document attributes.
update('doc', revisePageFields)
))
// Get all pages for a given array of page ids
export function getPages({pageIds}) {
return db.allDocs({
keys: pageIds,
include_docs: true,
}).then(
postprocessPagesResult
)
}
// Search the log for pages matching given query (keyword) string
export function searchPages({
query,
limit,
}) {
return db.search({
query,
filter: doc => (typeof doc._id === 'string'
&& doc._id.startsWith(pageKeyPrefix)),
fields: searchableTextFields,
include_docs: true,
highlighting: true,
limit,
stale: 'update_after',
...keyRangeForPrefix(pageKeyPrefix), // Is this supported yet?
}).then(
postprocessPagesResult
)
}
| import update from 'lodash/fp/update'
import db from '../pouchdb'
import { keyRangeForPrefix } from '../pouchdb'
import { pageKeyPrefix } from '../activity-logger'
import { searchableTextFields, revisePageFields } from '../page-analysis'
// Post-process result list after any retrieval of pages from the database.
const postprocessPagesResult = update('rows', rows => rows.map(
// Let the page analysis module augment or revise the document attributes.
update('doc', revisePageFields)
))
// Get all pages for a given array of page ids
export function getPages({pageIds}) {
return db.allDocs({
keys: pageIds,
include_docs: true,
}).then(
postprocessPagesResult
)
}
// Search the log for pages matching given query (keyword) string
export function searchPages({
query,
limit,
}) {
return db.search({
query,
fields: searchableTextFields,
include_docs: true,
highlighting: true,
limit,
stale: 'update_after',
...keyRangeForPrefix(pageKeyPrefix), // Is this supported yet?
}).then(
postprocessPagesResult
)
}
| JavaScript | 0 |
236f51a9e2689cb9d0d2a71e00046ac4a16ab517 | Update App.js | src/App.js | src/App.js | import React, {Component} from 'react';
import {Main} from './components/Main';
import Warnings from './components/Warnings';
import Top from './components/Top/Top';
import Footer from './components/Footer/Footer';
import {getAddressBalance} from './lib/dAppService';
import 'typeface-roboto';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: '',
balance: '',
source: 'metamask'
};
this.setAccount = this.setAccount.bind(this);
this.setEmptyAccount = this.setEmptyAccount.bind(this);
this.setSource = this.setSource.bind(this);
}
setSource(type) {
this.setState({source: type});
}
setAccount(account) {
const balance = getAddressBalance(account);
this.setState({account, balance});
}
setEmptyAccount() {
this.setState({account: '', balance: ''});
}
render() {
return (
<div className="App">
<Top
{...this.state}
setAccount={this.setAccount}
setEmptyAccount={this.setEmptyAccount}
setSource={this.setSource}
/>
{process.env.REACT_APP_PROVIDER
? <Main/>
: <Warnings/>}
<Footer/>
</div>
);
}
}
export default App;
| import React, {Component} from 'react';
import {Main} from './components/Main';
import Warnings from './components/Warnings';
import Top from './components/Top/Top';
import {StartAuction} from './components/StartAuction/StartAuction';
import Footer from './components/Footer/Footer';
import {getAddressBalance} from './lib/dAppService';
import 'typeface-roboto';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: '',
balance: '',
source: 'metamask'
};
this.setAccount = this.setAccount.bind(this);
this.setEmptyAccount = this.setEmptyAccount.bind(this);
this.setSource = this.setSource.bind(this);
}
setSource(type) {
this.setState({source: type});
}
setAccount(account) {
const balance = getAddressBalance(account);
this.setState({account, balance});
}
setEmptyAccount() {
this.setState({account: '', balance: ''});
}
render() {
return (
<div className="App">
<Top
{...this.state}
setAccount={this.setAccount}
setEmptyAccount={this.setEmptyAccount}
setSource={this.setSource}
/>
{process.env.REACT_APP_PROVIDER
? <Main/>
: <Warnings/>}
<StartAuction/>
<Footer/>
</div>
);
}
}
export default App;
| JavaScript | 0.000001 |
dbf15ea6e4de60662c24ccf49c5640d88c25883d | Fix admin advanced flag | src/server/jwt-helper.js | src/server/jwt-helper.js | import jwt from 'jsonwebtoken'
import config from 'config'
import hashids from 'src/shared/utils/hashids-plus'
import { includes } from 'lodash'
const opts = {}
opts.algorithm = config.jwt.OPTIONS.ALG
opts.expiresIn = config.jwt.OPTIONS.EXP
opts.issuer = config.jwt.OPTIONS.ISS
opts.audience = config.jwt.OPTIONS.AUD
export default function (profile, isAdmin=false) {
const data = {}
data.id = hashids.encode(profile.id)
data.email = profile.email
data.password = profile.password
if (isAdmin) {
data.isAdmin = true
data.advanced = true
}
// Advanced user permission
if (includes(config.jwt.PERMIT.advanced, profile.email)) {
data.advanced = true
}
return jwt.sign(data, config.jwt.SECRET_OR_KEY, opts)
}
export async function verifyJwt (token, checkAdmin=false) {
return new Promise((resolve, reject) => {
jwt.verify(token, config.jwt.SECRET_OR_KEY, opts, function (err, decoded) {
if (!err) {
if (checkAdmin) {
if (decoded.isAdmin) {
resolve(decoded.id)
} else {
throw new Error('Access Denied.')
}
} else {
resolve(decoded.id)
}
} else {
reject(err)
}
})
})
}
| import jwt from 'jsonwebtoken'
import config from 'config'
import hashids from 'src/shared/utils/hashids-plus'
import { includes } from 'lodash'
const opts = {}
opts.algorithm = config.jwt.OPTIONS.ALG
opts.expiresIn = config.jwt.OPTIONS.EXP
opts.issuer = config.jwt.OPTIONS.ISS
opts.audience = config.jwt.OPTIONS.AUD
export default function (profile, isAdmin=false) {
const data = {}
data.id = hashids.encode(profile.id)
data.email = profile.email
data.password = profile.password
if (isAdmin) {
data.isAdmin = true
}
// Advanced user permission
if (includes(config.jwt.PERMIT.advanced, profile.email)) {
data.advanced = true
}
return jwt.sign(data, config.jwt.SECRET_OR_KEY, opts)
}
export async function verifyJwt (token, checkAdmin=false) {
return new Promise((resolve, reject) => {
jwt.verify(token, config.jwt.SECRET_OR_KEY, opts, function (err, decoded) {
if (!err) {
if (checkAdmin) {
if (decoded.isAdmin) {
resolve(decoded.id)
} else {
throw new Error('Access Denied.')
}
} else {
resolve(decoded.id)
}
} else {
reject(err)
}
})
})
}
| JavaScript | 0 |
6260b1fa7145b27a67aeaf1780cd2b1fbde32f0c | fix failed test on windows | test/common.js | test/common.js | var fs = require('fs');
var assert = require('assert');
var csso = require('../lib/index.js');
function normalize(str) {
return str.replace(/\n|\r\n?|\f/g, '\n');
}
describe('csso', function() {
it('justDoIt() should works until removed', function() {
var output = [];
var tmp = console.warn;
try {
console.warn = function() {
output.push(Array.prototype.slice.call(arguments).join(' '));
};
assert.equal(
csso.justDoIt('.foo { color: #ff0000 } .bar { color: rgb(255, 0, 0) }'),
'.bar,.foo{color:red}'
);
} finally {
console.warn = tmp;
}
assert.equal(output.length, 1);
assert(/method is deprecated/.test(String(output[0])), 'should contains `method is deprecated`');
});
it('walk', function() {
function visit(withInfo) {
var visitedTypes = {};
csso.walk(csso.parse('@media (min-width: 200px) { .foo:nth-child(2n) { color: rgb(100%, 10%, 0%); width: calc(3px + 5%) } }', 'stylesheet', withInfo), function(node) {
visitedTypes[node[withInfo ? 1 : 0]] = true;
}, withInfo);
return Object.keys(visitedTypes).sort();
}
var shouldVisitTypes = ['stylesheet', 'atruler', 'atkeyword', 'ident', 'atrulerq', 's', 'braces', 'operator', 'dimension', 'number', 'atrulers', 'ruleset', 'selector', 'simpleselector', 'clazz', 'nthselector', 'nth', 'block', 'declaration', 'property', 'value', 'funktion', 'functionBody', 'percentage', 'decldelim', 'unary'].sort();
assert.deepEqual(visit(), shouldVisitTypes, 'w/o info');
assert.deepEqual(visit(true), shouldVisitTypes, 'with info');
});
it('strigify', function() {
assert.equal(
csso.stringify(csso.parse('.a\n{\rcolor:\r\nred}', 'stylesheet', true)),
normalize(fs.readFileSync(__dirname + '/fixture/stringify.txt', 'utf-8').trim())
);
});
});
| var fs = require('fs');
var assert = require('assert');
var csso = require('../lib/index.js');
describe('csso', function() {
it('justDoIt() should works until removed', function() {
var output = [];
var tmp = console.warn;
try {
console.warn = function() {
output.push(Array.prototype.slice.call(arguments).join(' '));
};
assert.equal(
csso.justDoIt('.foo { color: #ff0000 } .bar { color: rgb(255, 0, 0) }'),
'.bar,.foo{color:red}'
);
} finally {
console.warn = tmp;
}
assert.equal(output.length, 1);
assert(/method is deprecated/.test(String(output[0])), 'should contains `method is deprecated`');
});
it('walk', function() {
function visit(withInfo) {
var visitedTypes = {};
csso.walk(csso.parse('@media (min-width: 200px) { .foo:nth-child(2n) { color: rgb(100%, 10%, 0%); width: calc(3px + 5%) } }', 'stylesheet', withInfo), function(node) {
visitedTypes[node[withInfo ? 1 : 0]] = true;
}, withInfo);
return Object.keys(visitedTypes).sort();
}
var shouldVisitTypes = ['stylesheet', 'atruler', 'atkeyword', 'ident', 'atrulerq', 's', 'braces', 'operator', 'dimension', 'number', 'atrulers', 'ruleset', 'selector', 'simpleselector', 'clazz', 'nthselector', 'nth', 'block', 'declaration', 'property', 'value', 'funktion', 'functionBody', 'percentage', 'decldelim', 'unary'].sort();
assert.deepEqual(visit(), shouldVisitTypes, 'w/o info');
assert.deepEqual(visit(true), shouldVisitTypes, 'with info');
});
it('strigify', function() {
assert.equal(
csso.stringify(csso.parse('.a\n{\rcolor:\r\nred}', 'stylesheet', true)),
fs.readFileSync(__dirname + '/fixture/stringify.txt', 'utf-8').trim()
);
});
});
| JavaScript | 0.000001 |
525318ffb6c5fb21e22d3f1538a0b643c61b025d | fix syntax of example | hello_world_rtm.js | hello_world_rtm.js | var Bot = require('./Slackbot.js');
var bot = Bot();
bot.init();
bot.startRTM({
team: {
token: process.env.token
}
});
bot.hears(['hello'],'direct_message,direct_mention',function(message) {
bot.reply(message,'Hello!');
});
bot.hears(['question','ask'],'direct_message,direct_mention',function(message) {
bot.startConversation(message,function(convo) {
convo.ask('Say YES or NO',[
{
callback: function(response) { convo.say('YES! Good.'); convo.next(); },
pattern: bot.utterances.yes,
},
{
callback: function(response) { convo.say('NO?!?! WTF?'); convo.next(); },
pattern: bot.utterances.no,
},
{
default: true,
callback:function(response) { convo.say('Huh?'); convo.repeat(); convo.next(); }
}
]);
});
});
| var Bot = require('./Slackbot.js');
var bot = Bot();
bot.init();
bot.startRTM({
team: {
token: process.env.token
}
});
bot.hears(['hello'],'direct_message,direct_mention',function(connection,message) {
bot.reply(connection,message,'Hello!');
});
bot.hears(['lunch'],'direct_message,direct_mention',function(connection,message) {
bot.startTask(connection,message,function(task,convo) {
convo.ask('Say YES or NO',{
'yes': {
callback: function(response) { convo.say('YES! Good.'); },
pattern: bot.utterances.yes,
},
'no': {
callback: function(response) { convo.say('NO?!?! WTF?'); },
pattern: bot.utterances.no,
},
'default': function(response) { convo.say('Huh?'); convo.repeat(); }
});
});
});
| JavaScript | 0.000012 |
db71ec4183947c7ab25c8436b7eddc03251d67a8 | Tweak instructions link text, fix href warning | src/App.js | src/App.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './appRedux';
import Cell from './Cell.js';
import Settings from './Settings.js';
import Instructions from './Instructions.js';
import './App.css';
const mapStateToProps = state => ({
settings: state.settings,
cells: state.cells,
win: state.win,
movesMade: state.movesMade,
cheatMode: state.cheatMode,
showInstructions: state.showInstructions
});
class App extends Component {
onPlayCell(cellCoords) {
const { dispatch } = this.props;
dispatch(actionCreators.playCell(cellCoords));
}
onStartGame = settings => {
const { dispatch } = this.props;
dispatch(actionCreators.startGame(settings));
};
onToggleCheatMode = () => {
const { dispatch } = this.props;
dispatch(actionCreators.toggleCheatMode());
};
onShowInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.showInstructions());
};
onCloseInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.closeInstructions());
};
renderCellGrids() {
const { depth } = this.props.settings;
return Array(depth).fill().map((_, z) => {
return (
<div key={['grid', z].join('-')} className="App-cell-grid">
{depth > 1 &&
<h5 className="App-cell-grid-title">
Layer {z + 1}
</h5>}
{this.renderCellGrid(z)}
</div>
);
});
}
renderCellGrid(z) {
const { height } = this.props.settings;
return Array(height).fill().map((_, y) => {
return (
<div key={['row', y, z].join('-')} className="App-cell-row">
{this.renderCellRow(y, z)}
</div>
);
});
}
renderCellRow(y, z) {
const { width } = this.props.settings;
return Array(width).fill().map((_, x) => {
return this.renderCell(x, y, z);
});
}
renderCell(x, y, z) {
const { cells, cheatMode, win } = this.props;
const thisCell = cells[z][y][x];
const cycle = cheatMode && thisCell.cycle;
return (
<Cell
onClickCell={() => {
this.onPlayCell([x, y, z]);
}}
value={thisCell.value}
cycle={cycle}
win={win}
key={[x, y, z].join('-')}
/>
);
}
render() {
const { settings, win, movesMade, showInstructions } = this.props;
return (
<div className="App">
<div className="App-header">
<h2>
{win ? `You Win! (${movesMade} moves)` : 'Chroma Tiles'}
</h2>
</div>
<div className="App-settings">
<Settings
settings={settings}
onUpdateSettings={this.onStartGame}
displayCheatMode={movesMade > 50}
onClickCheatMode={this.onToggleCheatMode}
/>
</div>
<div className="App-container">
{this.renderCellGrids()}
</div>
<div className="App-footer">
<div>
<a href="#instructions" onClick={this.onShowInstructions}>
Show Instructions Again
</a>
</div>
<div>
<a href="https://github.com/alexcavalli/chroma-tiles">
Code on GitHub
</a>
</div>
</div>
{showInstructions &&
<Instructions onCloseInstructions={this.onCloseInstructions} />}
</div>
);
}
}
export default connect(mapStateToProps)(App);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './appRedux';
import Cell from './Cell.js';
import Settings from './Settings.js';
import Instructions from './Instructions.js';
import './App.css';
const mapStateToProps = state => ({
settings: state.settings,
cells: state.cells,
win: state.win,
movesMade: state.movesMade,
cheatMode: state.cheatMode,
showInstructions: state.showInstructions
});
class App extends Component {
onPlayCell(cellCoords) {
const { dispatch } = this.props;
dispatch(actionCreators.playCell(cellCoords));
}
onStartGame = settings => {
const { dispatch } = this.props;
dispatch(actionCreators.startGame(settings));
};
onToggleCheatMode = () => {
const { dispatch } = this.props;
dispatch(actionCreators.toggleCheatMode());
};
onShowInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.showInstructions());
};
onCloseInstructions = () => {
const { dispatch } = this.props;
dispatch(actionCreators.closeInstructions());
};
renderCellGrids() {
const { depth } = this.props.settings;
return Array(depth).fill().map((_, z) => {
return (
<div key={['grid', z].join('-')} className="App-cell-grid">
{depth > 1 &&
<h5 className="App-cell-grid-title">
Layer {z + 1}
</h5>}
{this.renderCellGrid(z)}
</div>
);
});
}
renderCellGrid(z) {
const { height } = this.props.settings;
return Array(height).fill().map((_, y) => {
return (
<div key={['row', y, z].join('-')} className="App-cell-row">
{this.renderCellRow(y, z)}
</div>
);
});
}
renderCellRow(y, z) {
const { width } = this.props.settings;
return Array(width).fill().map((_, x) => {
return this.renderCell(x, y, z);
});
}
renderCell(x, y, z) {
const { cells, cheatMode, win } = this.props;
const thisCell = cells[z][y][x];
const cycle = cheatMode && thisCell.cycle;
return (
<Cell
onClickCell={() => {
this.onPlayCell([x, y, z]);
}}
value={thisCell.value}
cycle={cycle}
win={win}
key={[x, y, z].join('-')}
/>
);
}
render() {
const { settings, win, movesMade, showInstructions } = this.props;
return (
<div className="App">
<div className="App-header">
<h2>
{win ? `You Win! (${movesMade} moves)` : 'Chroma Tiles'}
</h2>
</div>
<div className="App-settings">
<Settings
settings={settings}
onUpdateSettings={this.onStartGame}
displayCheatMode={movesMade > 50}
onClickCheatMode={this.onToggleCheatMode}
/>
</div>
<div className="App-container">
{this.renderCellGrids()}
</div>
<div className="App-footer">
<div>
<a href="#" onClick={this.onShowInstructions}>
Instructions
</a>
</div>
<div>
<a href="https://github.com/alexcavalli/chroma-tiles">
Code on GitHub
</a>
</div>
</div>
{showInstructions &&
<Instructions onCloseInstructions={this.onCloseInstructions} />}
</div>
);
}
}
export default connect(mapStateToProps)(App);
| JavaScript | 0 |
22a0ebd1aed7dd437f672fc5fdc31ec37d72bd26 | Update config.js | test/config.js | test/config.js | module.exports = {
library: "/usr/local/lib/softhsm/libsofthsm2.so",
name: "SoftHSMv2",
slot: 0,
sessionFlags: 4, // SERIAL_SESSION
pin: "12345"
}
| module.exports = {
library: "/usr/lib/libsofthsm.so",
name: "SoftHSM",
slot: 0,
sessionFlags: 4, // SERIAL_SESSION
pin: "6789"
}
| JavaScript | 0.000002 |
2e58c815b8b9b15dd4e4b7e308f3805c08a79ab2 | Move decodeArticleUrl to parent | client/src/components/ArticleShow.js | client/src/components/ArticleShow.js | import React from 'react'
import BackButton from './BackButton'
const ArticleShow = ({channel, articles, match, decodeArticleUrl}) => {
const matchParams = decodeArticleUrl(match.params.article)
const article = articles.find(article => article.title === matchParams)
return (
<div className="article">
<h1>{article.title}</h1>
<BackButton />
<img src={article.urlToImage} className="image-large" alt=""/>
<h3>{article.description}</h3>
<h3><a href={article.url} className="link" target="_blank">Read full article on {channel.name}</a></h3>
</div>
)
}
export default ArticleShow
| import React from 'react'
import BackButton from './BackButton'
function decodeArticleUrl(title) {
const sanitizedTitle = decodeURIComponent(title)
return sanitizedTitle.split("[percent]").join("%")
}
const ArticleShow = ({channel, articles, match}) => {
const matchParams = decodeArticleUrl(match.params.article)
const article = articles.find(article => article.title === matchParams)
return (
<div className="article">
<h1>{article.title}</h1>
<BackButton />
<img src={article.urlToImage} className="image-large" alt=""/>
<h3>{article.description}</h3>
<h3><a href={article.url} className="link" target="_blank">Read full article on {channel.name}</a></h3>
</div>
)
}
export default ArticleShow
| JavaScript | 0.000002 |
ea07381c25811380b99c495f64ac13bcfb085c2f | test of pushing ability | client/src/js/models/SessionModel.js | client/src/js/models/SessionModel.js | /* global gapi */
var _ = require('underscore');
var Backbone = require('backbone');
var UserModel = require('./UserModel.js');
var SessionModel = Backbone.Model.extend({
defaults: {
logged: false,
userId: ''
},
initialize: function() {
this.user = new UserModel({});
},
loginSessionUser: function(googleUser) {
var profile = googleUser.getBasicProfile();
// Get attributes from user's gmail account and assign to
// the current user in this session.
this.updateSessionUser({
id: googleUser.getAuthResponse().id_token,
name: profile.getName(),
email: profile.getEmail(),
image: profile.getImageUrl()
});
// Set the SessionModel's values and show that a user is
// now logged in.
this.set({ userId: this.user.get('id'), logged: true });
},
logoutSessionUser: function() {
// Clear and resets GoogleUser attributes to UserModel
// default values.
this.updateSessionUser(this.user.defaults);
// Reset the SessionModel's values to defaults and show
// that a user is now logged out.
this.set({ userId: this.user.get('id'), logged: false });
},
updateSessionUser: function(userData) {
// A user model is passed into this function.
//
// Select the model's default properties (_.pick its default
// _.keys) and set them using the values passed in from userData.
//
// In this instance, we are picking and updating id, name,
// email, and image.
this.user.set(_.pick(userData, _.keys(this.user.defaults)));
},
checkAuth: function(callback) {
callback = callback || {};
var auth2 = gapi.auth2.getAuthInstance();
var userSignedIn = auth2.isSignedIn.get();
var googleUser = auth2.currentUser.get();
var profile = googleUser.getBasicProfile();
console.log('auth2 is signed in: ', auth2.isSignedIn.get());
// If a User is signed in and their gmail matches a @isl.co gmail,
// log in this user.
if (userSignedIn && profile.getEmail().match(/^.*@isl.co$/g)) {
this.loginSessionUser(googleUser);
if ('success' in callback) {
// If user is successfully signed in, call back the
// auth2SignInChanged()'s success function (in client.js)
callback.success();
}
} else {
this.logoutSessionUser();
if ('error' in callback) {
callback.error();
}
}
console.log('session: ', this.attributes);
console.log('user: ', this.user.attributes);
if ('complete' in callback) {
callback.complete();
}
}
});
module.exports = SessionModel;
| /* global gapi */
var _ = require('underscore');
var Backbone = require('backbone');
var UserModel = require('./UserModel.js');
var SessionModel = Backbone.Model.extend({
defaults: {
logged: false,
userId: ''
},
initialize: function() {
this.user = new UserModel({});
},
loginSessionUser: function(googleUser) {
var profile = googleUser.getBasicProfile();
// Get attributes from user's gmail account and assign to
// the current user in this session.
this.updateSessionUser({
id: googleUser.getAuthResponse().id_token,
name: profile.getName(),
email: profile.getEmail(),
image: profile.getImageUrl()
});
// Set the SessionModel's values and show that a user is
// now logged in.
this.set({ userId: this.user.get('id'), logged: true });
},
logoutSessionUser: function() {
// Clear and resets GoogleUser attributes to UserModel
// default values.
this.updateSessionUser(this.user.defaults);
// Reset the SessionModel's values to defaults and show
// that a user is now logged out.
this.set({ userId: this.user.get('id'), logged: false });
},
updateSessionUser: function(userData) {
// A user model is passed into this function.
//
// Select the model's default properties (_.pick its default
// _.keys) and set them using the values passed in from userData.
//
// In this instance, we are picking and updating id, name,
// email, and image.
this.user.set(_.pick(userData, _.keys(this.user.defaults)));
},
checkAuth: function(callback) {
callback = callback || {};
var auth2 = gapi.auth2.getAuthInstance();
var userSignedIn = auth2.isSignedIn.get();
var googleUser = auth2.currentUser.get();
var profile = googleUser.getBasicProfile();
console.log('auth2 is signed in: ', auth2.isSignedIn.get());
// If a User is signed in and their gmail matches a @isl.co gmail,
// log in this user.
if (userSignedIn && profile.getEmail().match(/^.*@isl.co$/g)) {
this.loginSessionUser(googleUser);
if ('success' in callback) {
// If user is successfully signed in, call back the
// auth2SignInChanged()'s success function (in client.js)
callback.success();
}
} else {
this.logoutSessionUser();
if ('error' in callback) {
callback.error();
}
}
console.log('session: ', this.attributes);
console.log('user: ', this.user.attributes);
if ('complete' in callback) {
callback.complete();
}
}
});
module.exports = SessionModel;
| JavaScript | 0.000001 |
b94493ffe7364f72b6aea3187d816849102b13e2 | align margin (#670) | src/App.js | src/App.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'redux-bundler-react'
import NavBar from './navigation/NavBar'
import navHelper from 'internal-nav-helper'
import IpldExploreForm from './ipld/IpldExploreForm'
import AsyncRequestLoader from './loader/AsyncRequestLoader'
export class App extends Component {
static propTypes = {
doInitIpfs: PropTypes.func.isRequired,
doUpdateUrl: PropTypes.func.isRequired,
route: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element
]).isRequired
}
componentWillMount () {
this.props.doInitIpfs()
}
render () {
const Page = this.props.route
return (
<div className='sans-serif' onClick={navHelper(this.props.doUpdateUrl)}>
<div className='dt dt--fixed' style={{minHeight: '100vh'}}>
<div className='dtc v-top bg-navy' style={{width: 240}}>
<NavBar />
</div>
<div className='dtc v-top'>
<div style={{background: '#F0F6FA'}}>
<IpldExploreForm />
</div>
<main style={{padding: '40px'}}>
<Page />
</main>
</div>
</div>
<div className='absolute top-0 left-0 pa2'>
<AsyncRequestLoader />
</div>
</div>
)
}
}
export default connect('selectRoute', 'doUpdateUrl', 'doInitIpfs', App)
| import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'redux-bundler-react'
import NavBar from './navigation/NavBar'
import navHelper from 'internal-nav-helper'
import IpldExploreForm from './ipld/IpldExploreForm'
import AsyncRequestLoader from './loader/AsyncRequestLoader'
export class App extends Component {
static propTypes = {
doInitIpfs: PropTypes.func.isRequired,
doUpdateUrl: PropTypes.func.isRequired,
route: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element
]).isRequired
}
componentWillMount () {
this.props.doInitIpfs()
}
render () {
const Page = this.props.route
return (
<div className='sans-serif' onClick={navHelper(this.props.doUpdateUrl)}>
<div className='dt dt--fixed' style={{minHeight: '100vh'}}>
<div className='dtc v-top bg-navy' style={{width: 240}}>
<NavBar />
</div>
<div className='dtc v-top'>
<div style={{background: '#F0F6FA'}}>
<IpldExploreForm />
</div>
<main className='pa3'>
<Page />
</main>
</div>
</div>
<div className='absolute top-0 left-0 pa2'>
<AsyncRequestLoader />
</div>
</div>
)
}
}
export default connect('selectRoute', 'doUpdateUrl', 'doInitIpfs', App)
| JavaScript | 0 |
59d991ea7d10961e90b79231f092a5d780300fbe | Clean up sessionsConverter module | src/sessionsConverter.js | src/sessionsConverter.js | 'use strict'
// module pattern
var sessionsConverter = (function(){
// variable to keep track of different labels
var labels = [];
// labels set for checking if label is unique
var labelSet = {};
function init(){
labels = [];
labelSet = {};
}
function getConvertedSessions(sessions){
var convertedSessions = [];
sessions.forEach(function(session){
convertedSessions.push(getConvertedSession(session));
});
return convertedSessions;
}
function getConvertedSession(session){
var now = moment(); // current time
var outcomes = session.outcomes;
// data set item for session
var convertedSession = {};
var momentTimestamp = moment(session.timestamp);
var humanisedTimestamp = moment.duration(momentTimestamp.diff(now)).humanize(true);
convertedSession.label = humanisedTimestamp;
// adding the values map to converted session for developer to view for possible debugging
convertedSession.valuesMap = getValuesMapsFromOutcomes(outcomes);
// extract data and notes arrays
var extractedDataAndNotes = getExtractedDataAndTooltipNotes(convertedSession.valuesMap);
convertedSession.data = extractedDataAndNotes.data;
convertedSession.notes = extractedDataAndNotes.notes;
var color = Chart.helpers.color;
//assign random colour to chart
var colour = randomColor({
format: 'rgba'
});
convertedSession.backgroundColor = color(colour).alpha(0.2).rgbString();
convertedSession.borderColor = colour;
convertedSession.pointBackgroundColor = colour;
return convertedSession;
}
// this creates a mapping of the data value as well as notes for each label
// to be later used to create the ChartJS data array
function getValuesMapsFromOutcomes(outcomes){
var dataMap = {};
var noteMap = {};
// add each outcome to a set
outcomes.forEach(function(outcome){
var lowerCaseLabel = updateLabels(outcome.outcome);
dataMap[lowerCaseLabel] = outcome.value;
noteMap[lowerCaseLabel] = outcome.notes;
});
return {
data : dataMap,
notes: noteMap
}
}
// check if our set has the value or not
function updateLabels(potentialLabel){
var lowerCaseLabel = potentialLabel.toLowerCase();
if(!labelSet.hasOwnProperty(lowerCaseLabel)){
labels.push(potentialLabel);
// now value is in our set
labelSet[lowerCaseLabel] = true;
}
return lowerCaseLabel;
}
// Use values map to create the data and notes arrays confroming to
// ChartJS requirements.
function getExtractedDataAndTooltipNotes(valuesMap){
// go over currently added labels
var data = [];
var notes = [];
labels.forEach(function(label){
data.push(getExtractedDataValue(valuesMap.data[label.toLowerCase()]));
notes.push(getExtractedNoteValue(valuesMap.notes[label.toLowerCase()]))
});
return {
data : data,
notes: notes
}
}
function getExtractedDataValue(dataValue){
return dataValue === undefined ? null : dataValue;
}
function getExtractedNoteValue(noteValue){
return noteValue === undefined ? "none" : noteValue;
}
function getLabels(){
return labels;
}
return {
getChartJSConvertedData: function(sessions){
init();
var chartData = {};
chartData.datasets = getConvertedSessions(sessions);
chartData.labels = getLabels();
return chartData;
}
};
})();
| // module pattern
var sessionsConverter = (function(){
// variable to keep track of different labels
var labels = [];
// labels set for checking if label is unique
var labelSet = {};
function init(){
labels = [];
labelSet = {};
}
function getConvertedSessions(sessions){
var convertedSessions = [];
sessions.forEach(function(session){
convertedSessions.push(getConvertedSession(session));
});
return convertedSessions;
}
function getConvertedSession(session){
var now = moment(); // current time
var outcomes = session.outcomes;
// data set item for session
var convertedSession = {};
var momentTimestamp = moment(session.timestamp);
var humanisedTimestamp = moment.duration(momentTimestamp.diff(now)).humanize(true);
convertedSession.label = humanisedTimestamp;
convertedSession.valuesMap = getValuesMapsFromOutcomes(outcomes);
// extract data and notes arrays
var extractedDataAndNotes = getExtractedDataAndTooltipNotes(convertedSession.valuesMap);
convertedSession.data = extractedDataAndNotes.data;
convertedSession.notes = extractedDataAndNotes.notes;
var color = Chart.helpers.color;
//assign random colour to chart
var colour = randomColor({
format: 'rgba'
});
convertedSession.backgroundColor = color(colour).alpha(0.2).rgbString();
convertedSession.borderColor = colour;
convertedSession.pointBackgroundColor = colour;
return convertedSession;
}
function getValuesMapsFromOutcomes(outcomes){
var dataMap = {};
var noteMap = {};
// add each outcome to a set
outcomes.forEach(function(outcome){
var lowerCaseLabel = outcome.outcome.toLowerCase();
updateLabelSet(outcome.outcome);
dataMap[lowerCaseLabel] = outcome.value;
noteMap[lowerCaseLabel] = outcome.notes;
});
return {
data : dataMap,
notes: noteMap
}
}
// check if our set has the value or not
function updateLabelSet(potentialLabel){
var lowerCaseLabel = potentialLabel.toLowerCase();
if(!labelSet.hasOwnProperty(lowerCaseLabel)){
labels.push(potentialLabel);
// now value is in our set
labelSet[lowerCaseLabel] = true;
}
}
function getExtractedDataAndTooltipNotes(valuesMap){
// go over currently added labels
var data = [];
var notes = [];
labels.forEach(function(label){
data.push(getExtractedDataValue(valuesMap.data[label.toLowerCase()]));
notes.push(getExtractedNoteValue(valuesMap.notes[label.toLowerCase()]))
});
return {
data : data,
notes: notes
}
}
function getExtractedDataValue(dataValue){
return dataValue === undefined ? null : dataValue;
}
function getExtractedNoteValue(noteValue){
return noteValue === undefined ? "none" : noteValue;
}
function getLabels(){
return labels;
}
return {
getChartJSConvertedData: function(sessions){
init();
var chartData = {};
chartData.datasets = getConvertedSessions(sessions);
chartData.labels = getLabels();
return chartData;
}
};
})();
| JavaScript | 0 |
bf5747db8433447954f26aaa9e4fb29fa44b32af | Fix the Windows packaged build, r=vporof (#24) | src/shared/util/spawn.js | src/shared/util/spawn.js | /*
Copyright 2016 Mozilla
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
import cp from 'child_process';
import colors from 'colour';
import { IS_PACKAGED_BUILD } from '../build-info';
export const spawn = (command, main, args, { logger }, options = {}) => new Promise((resolve, reject) => {
logger.log('Spawning',
colors.cyan(command),
colors.blue(main),
colors.yellow(args.join(' ')));
const stdio = process.platform === 'win32' && IS_PACKAGED_BUILD
? 'ignore'
: 'inherit';
const child = cp.spawn(command, [main, ...args], { stdio, ...options });
child.on('error', reject);
child.on('exit', resolve);
return child;
});
| /*
Copyright 2016 Mozilla
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
import cp from 'child_process';
import colors from 'colour';
export const spawn = (command, main, args, { logger }, options = {}) => new Promise((resolve, reject) => {
logger.log('Spawning',
colors.cyan(command),
colors.blue(main),
colors.yellow(args.join(' ')));
const child = cp.spawn(command, [main, ...args], { stdio: 'inherit', ...options });
child.on('error', reject);
child.on('exit', resolve);
return child;
});
| JavaScript | 0 |
66bdbe3a207a81247f1377d3afab5dc7fd7756be | fix arg count check | src/cli.js | src/cli.js | var User = require('./user.js'),
args = process.argv.slice(2);
if (args.length < 2) {
console.log('invalid arg count');
return;
}
switch (args[0]) {
case 'user':
if (args[1] == 'create') {
if (args.length < 4) {
console.log('invalid arg count');
return;
}
return User.create(args[2], args[3]);
}
if (args[1] == 'remove') {
if (args.length < 4) {
console.log('invalid arg count');
return;
}
return User.remove(args[2], args[3]);
}
break;
}
| var User = require('./user.js'),
args = process.argv.slice(2);
if (args.length < 2) {
console.log('invalid arg count');
return;
}
switch (args[0]) {
case 'user':
if (args[1] == 'create') {
if (args.length < 4) {
console.log('invalid arg count');
return;
}
return User.create(args[2], args[3]);
}
if (args[1] == 'remove') {
if (args.length < 3) {
console.log('invalid arg count');
return;
}
return User.remove(args[2], args[3]);
}
break;
}
| JavaScript | 0.000005 |
fbe3162766d590485a8ebbf82a0076012fcfc350 | Test for `set` | test/create.js | test/create.js | 'use strict';
var isArray = Array.isArray;
module.exports = function (t, a) {
var ObservableArray = t(Array)
, arr = new ObservableArray('foo', 'bar', 23)
, evented = 0, x = {};
a(isArray(arr), true, "Is array");
a(arr instanceof ObservableArray, true, "Subclassed");
a.deep(arr, ['foo', 'bar', 23], "Constructor");
arr.on('change', function () { ++evented; });
arr.pop();
a.deep(arr, ['foo', 'bar'], "Pop: value");
a(evented, 1, "Pop: event");
arr.pop();
arr.pop();
a.deep(arr, [], "Pop: clear");
a(evented, 3, "Pop: event");
arr.pop();
a(evented, 3, "Pop: on empty");
arr.shift();
a(evented, 3, "Shift: on empty");
arr.reverse();
a(evented, 3, "Revere: on empty");
arr.push();
a(evented, 3, "Push: empty");
arr.push(x);
a.deep(arr, [x], "Push: value");
a(evented, 4, "Push: event");
arr.reverse();
a(evented, 4, "Reverse: one value");
arr.push(x);
a(evented, 5, "Push: another");
arr.reverse();
a(evented, 5, "Reverse: same layout");
arr.push(34);
a(evented, 6, "Push: another #2");
arr.reverse();
a(evented, 7, "Reverse: diff");
a.deep(arr, [34, x, x], "Reverse: content");
arr.shift();
a.deep(arr, [x, x], "Shift: content");
a(evented, 8, "Shift: event");
arr.sort();
a(evented, 8, "Sort: no change");
arr.pop();
arr.pop();
arr.push('wed');
arr.push('abc');
arr.set(arr.length, 'raz');
a(evented, 13, "Events");
arr.sort();
a.deep(arr, ['abc', 'raz', 'wed'], "Sort: content");
a(evented, 14, "Sort: event");
arr.splice();
a(evented, 14, "Splice: no data");
arr.splice(12);
a(evented, 14, "Splice: too far");
arr.splice(1, 0);
a(evented, 14, "Splice: no delete");
arr.splice(1, 0, 'foo');
a.deep(arr, ['abc', 'foo', 'raz', 'wed'], "Sort: content");
a(evented, 15, "Splice: event");
arr.unshift();
a(evented, 15, "Unshift: no data");
arr.unshift('elo', 'bar');
a.deep(arr, ['elo', 'bar', 'abc', 'foo', 'raz', 'wed'], "Unshift: content");
a(evented, 16, "Unshift: event");
};
| 'use strict';
var isArray = Array.isArray;
module.exports = function (t, a) {
var ObservableArray = t(Array)
, arr = new ObservableArray('foo', 'bar', 23)
, evented = 0, x = {};
a(isArray(arr), true, "Is array");
a(arr instanceof ObservableArray, true, "Subclassed");
a.deep(arr, ['foo', 'bar', 23], "Constructor");
arr.on('change', function () { ++evented; });
arr.pop();
a.deep(arr, ['foo', 'bar'], "Pop: value");
a(evented, 1, "Pop: event");
arr.pop();
arr.pop();
a.deep(arr, [], "Pop: clear");
a(evented, 3, "Pop: event");
arr.pop();
a(evented, 3, "Pop: on empty");
arr.shift();
a(evented, 3, "Shift: on empty");
arr.reverse();
a(evented, 3, "Revere: on empty");
arr.push();
a(evented, 3, "Push: empty");
arr.push(x);
a.deep(arr, [x], "Push: value");
a(evented, 4, "Push: event");
arr.reverse();
a(evented, 4, "Reverse: one value");
arr.push(x);
a(evented, 5, "Push: another");
arr.reverse();
a(evented, 5, "Reverse: same layout");
arr.push(34);
a(evented, 6, "Push: another #2");
arr.reverse();
a(evented, 7, "Reverse: diff");
a.deep(arr, [34, x, x], "Reverse: content");
arr.shift();
a.deep(arr, [x, x], "Shift: content");
a(evented, 8, "Shift: event");
arr.sort();
a(evented, 8, "Sort: no change");
arr.pop();
arr.pop();
arr.push('wed');
arr.push('abc');
arr.push('raz');
a(evented, 13, "Events");
arr.sort();
a.deep(arr, ['abc', 'raz', 'wed'], "Sort: content");
a(evented, 14, "Sort: event");
arr.splice();
a(evented, 14, "Splice: no data");
arr.splice(12);
a(evented, 14, "Splice: too far");
arr.splice(1, 0);
a(evented, 14, "Splice: no delete");
arr.splice(1, 0, 'foo');
a.deep(arr, ['abc', 'foo', 'raz', 'wed'], "Sort: content");
a(evented, 15, "Splice: event");
arr.unshift();
a(evented, 15, "Unshift: no data");
arr.unshift('elo', 'bar');
a.deep(arr, ['elo', 'bar', 'abc', 'foo', 'raz', 'wed'], "Unshift: content");
a(evented, 16, "Unshift: event");
};
| JavaScript | 0.000001 |
17219abf022ff722a98de9575b07aec7057c172b | Fix build sitemap.xml | src/tasks/sitemap-xml.js | src/tasks/sitemap-xml.js | var _ = require('lodash'),
vow = require('vow'),
js2xml = require('js2xmlparser'),
errors = require('../errors').TaskSitemapXML,
logger = require('../logger'),
levelDb = require('../providers/level-db');
module.exports = function (target) {
logger.info('Start to build "sitemap.xml" file', module);
var hosts = target.getOptions().hosts;
// check if any changes were collected during current synchronization
// otherwise we should skip this task
if (!target.getChanges().areModified()) {
logger.warn('No changes were made during this synchronization. This step will be skipped', module);
return vow.resolve(target);
}
// check if any hosts were configured in application configuration file
// otherwise we should skip this task
if (!Object.keys(hosts).length) {
logger.warn('No hosts were configured for creating sitemap.xml file. This step will be skipped', module);
return vow.resolve(target);
}
// get all nodes from db that have inner urls
return levelDb.get().getByCriteria(function (record) {
var key = record.key,
value = record.value;
if (key.indexOf(target.KEY.NODE_PREFIX) < 0) {
return false;
}
return value.hidden && _.isString(value.url) && !/^(https?:)?\/\//.test(value.url);
}, { gte: target.KEY.NODE_PREFIX, lt: target.KEY.PEOPLE_PREFIX, fillCache: true })
.then(function (records) {
// convert data set to sitemap format
// left only data fields that are needed for sitemap.xml file
return records.map(function (record) {
return _.pick(record.value, 'url', 'hidden', 'search');
});
})
.then(function (records) {
return records.reduce(function (prev, item) {
Object.keys(hosts).forEach(function (lang) {
if (!item.hidden[lang]) {
prev.push(_.extend({ loc: hosts[lang] + item.url }, item.search));
}
});
return prev;
}, []);
})
.then(function (records) {
// convert json model to xml format
return levelDb.get().put('sitemapXml', js2xml('urlset', { url: records }));
})
.then(function () {
logger.info('Successfully create sitemap.xml file', module);
return vow.resolve(target);
})
.fail(function (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
return vow.reject(err);
});
};
| var _ = require('lodash'),
vow = require('vow'),
js2xml = require('js2xmlparser'),
errors = require('../errors').TaskSitemapXML,
logger = require('../logger'),
levelDb = require('../providers/level-db');
module.exports = function (target) {
logger.info('Start to build "sitemap.xml" file', module);
var hosts = target.getOptions['hosts'] || {};
// check if any changes were collected during current synchronization
// otherwise we should skip this task
if (!target.getChanges().areModified()) {
logger.warn('No changes were made during this synchronization. This step will be skipped', module);
return vow.resolve(target);
}
// check if any hosts were configured in application configuration file
// otherwise we should skip this task
if (!Object.keys(hosts).length) {
logger.warn('No hosts were configured for creating sitemap.xml file. This step will be skipped', module);
return vow.resolve(target);
}
// get all nodes from db that have inner urls
return levelDb
.getByCriteria(function (record) {
var key = record.key,
value = record.value;
if (key.indexOf(target.KEY.NODE_PREFIX) < 0) {
return false;
}
return value.hidden && _.isString(value.url) && !/^(https?:)?\/\//.test(value.url);
}, { gte: target.KEY.NODE_PREFIX, lt: target.KEY.PEOPLE_PREFIX, fillCache: true })
.then(function (records) {
// convert data set to sitemap format
// left only data fields that are needed for sitemap.xml file
return records.map(function (record) {
return _.pick(record.value, 'url', 'hidden', 'search');
});
})
.then(function (records) {
return records.reduce(function (prev, item) {
Object.keys(hosts).forEach(function (lang) {
if (!item.hidden[lang]) {
prev.push(_.extend({ loc: hosts[lang] + item.url }, item.search));
}
});
return prev;
}, []);
})
.then(function (records) {
// convert json model to xml format
return levelDb.get().put('sitemapXml', js2xml('urlset', { url: records }));
})
.then(function () {
logger.info('Successfully create sitemap.xml file', module);
return vow.resolve(target);
})
.fail(function (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
return vow.reject(err);
});
};
| JavaScript | 0.000007 |