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
|
---|---|---|---|---|---|---|---|
e7b61708bcfd9665ec20492fc272c87773627acb | Remove trailing whitespace | js/reddit.js | js/reddit.js | var Reddit = {
downloadPost: function(name, callback) {
// post factory, download from reddit
console.log('Loading post ' + name);
$.get('post.php', {
name: name
}, function(postList) {
var post = postList.data.children[0].data;
callback(new Reddit.Post(post));
}, 'json');
},
Post: function(data) {
this.name = data.name;
this.title = data.title;
this.url = data.url;
this.permalink = data.permalink;
},
Channel: function(subreddits) {
if (typeof subreddits == 'string') {
subreddits = [subreddits];
}
this.subreddits = subreddits;
this.items = [];
this.currentID = 0;
this.limit = 25;
this.onnewitemavailable = function() {};
this.onerror = function() {};
},
};
Reddit.Channel.prototype = {
constructor: Reddit.Channel,
getCurrent: function(callback) {
var self = this;
if (this.items.length > this.currentID) {
// current item is already downloaded, return immediately
return callback(this.items[this.currentID]);
}
// we don't yet have the current item; download it
this.downloadNextPage(function() {
callback(self.items[self.currentID]);
}, this.onerror);
},
downloadNextPage: function(ondone, onerror) {
var after;
var self = this;
if (this.items.length == 0) {
after = '';
}
else {
after = this.items[this.items.length - 1].name;
}
$.get('feed.php', {
r: this.subreddits.join('+'),
after: after,
limit: this.limit
}, function(feed) {
var prevlength = self.items.length;
// TODO: Optimize O(n^2) algorithm
if (feed == null) {
Render.invalid();
return;
}
feed.data.children = feed.data.children.map(function(item) {
return new Reddit.Post(item.data);
}).filter(function(item) {
/*
console.log('Filter: ');
console.log(item);
*/
return true;
// Go through all items that have already been displayed
// and make sure we only inject new content
// This is important, as pages in reddit may have changed
// during ranking.
for (var i = 0; i < self.items.length; ++i) {
var loadedItem = self.items[i];
if (item.name === loadedItem.name) {
console.log('Skipping already loaded item', item.name);
return false;
}
}
return true;
});
self.items.push.apply(self.items, feed.data.children);
var newlength = self.items.length;
for (var i = 0; i < feed.data.children.length; ++i) {
self.onnewitemavailable(feed.data.children[i]);
}
if (prevlength == newlength) {
// we ran out of pages
console.log('End of subreddit.');
self.onerror();
}
else {
ondone();
}
}, 'json');
},
goNext: function(onerror) {
if (typeof onerror == 'function') {
this.onerror = onerror;
}
++this.currentID;
},
goPrevious: function(onerror) {
if (this.currentID - 1 < 0) {
if (typeof onerror == 'function') {
return onerror();
}
return;
}
--this.currentID;
}
};
| var Reddit = {
downloadPost: function(name, callback) {
// post factory, download from reddit
console.log('Loading post ' + name);
$.get('post.php', {
name: name
}, function(postList) {
var post = postList.data.children[0].data;
callback(new Reddit.Post(post));
}, 'json');
},
Post: function(data) {
this.name = data.name;
this.title = data.title;
this.url = data.url;
this.permalink = data.permalink;
},
Channel: function(subreddits) {
if (typeof subreddits == 'string') {
subreddits = [subreddits];
}
this.subreddits = subreddits;
this.items = [];
this.currentID = 0;
this.limit = 25;
this.onnewitemavailable = function() {};
this.onerror = function() {};
},
};
Reddit.Channel.prototype = {
constructor: Reddit.Channel,
getCurrent: function(callback) {
var self = this;
if (this.items.length > this.currentID) {
// current item is already downloaded, return immediately
return callback(this.items[this.currentID]);
}
// we don't yet have the current item; download it
this.downloadNextPage(function() {
callback(self.items[self.currentID]);
}, this.onerror);
},
downloadNextPage: function(ondone, onerror) {
var after;
var self = this;
if (this.items.length == 0) {
after = '';
}
else {
after = this.items[this.items.length - 1].name;
}
$.get('feed.php', {
r: this.subreddits.join('+'),
after: after,
limit: this.limit
}, function(feed) {
var prevlength = self.items.length;
// TODO: Optimize O(n^2) algorithm
if (feed == null) {
Render.invalid();
return;
}
feed.data.children = feed.data.children.map(function(item) {
return new Reddit.Post(item.data);
}).filter(function(item) {
/*
console.log('Filter: ');
console.log(item);
*/
return true;
// Go through all items that have already been displayed
// and make sure we only inject new content
// This is important, as pages in reddit may have changed
// during ranking.
for (var i = 0; i < self.items.length; ++i) {
var loadedItem = self.items[i];
if (item.name === loadedItem.name) {
console.log('Skipping already loaded item', item.name);
return false;
}
}
return true;
});
self.items.push.apply(self.items, feed.data.children);
var newlength = self.items.length;
for (var i = 0; i < feed.data.children.length; ++i) {
self.onnewitemavailable(feed.data.children[i]);
}
if (prevlength == newlength) {
// we ran out of pages
console.log('End of subreddit.');
self.onerror();
}
else {
ondone();
}
}, 'json');
},
goNext: function(onerror) {
if (typeof onerror == 'function') {
this.onerror = onerror;
}
++this.currentID;
},
goPrevious: function(onerror) {
if (this.currentID - 1 < 0) {
if (typeof onerror == 'function') {
return onerror();
}
return;
}
--this.currentID;
}
};
| JavaScript | 0.999999 |
94d0e3f5e07877cae2ac2e28b031890ba863c7d5 | Fix incorrect executive rights on `test.js` | test.js | test.js | 'use strict';
/**
* Dependencies.
*/
var emoji,
gemoji,
assert;
emoji = require('./data/emoji.json');
gemoji = require('./');
assert = require('assert');
/**
* Tests for basic structure.
*/
describe('gemoji', function () {
it('should have a `name` property', function () {
assert(
Object.prototype.toString.call(gemoji.name) === '[object Object]'
);
});
it('should have an `unicode` property', function () {
assert(
Object.prototype.toString.call(gemoji.unicode) ===
'[object Object]'
);
});
});
/**
* Validate if a crawled gemoji is indeed (correctly)
* present in this module.
*
* @param {Object} gemojiObject
* @param {string} gemojiObject.emoji - Unicode
* representation.
* @param {string} gemojiObject.description - Human
* description of the picture.
* @param {Array.<string>} gemojiObject.aliases - List
* of names used by GitHub.
* @param {Array.<string>} gemojiObject.tags - List
* of tags.
*/
function describeGemojiObject(gemojiObject) {
var unicode,
information,
description,
aliases,
tags,
name;
unicode = gemojiObject.emoji;
/**
* Some gemoji, such as `octocat`, do not have a
* unicode representation. Those are not present in
* `gemoji`. Exit.
*/
if (!unicode) {
return;
}
description = gemojiObject.description;
aliases = gemojiObject.aliases;
tags = gemojiObject.tags;
name = aliases[0];
information = gemoji.unicode[unicode];
describe(unicode + ' ' + description, function () {
aliases.forEach(function (alias) {
it('should be accessible by name (' + alias + ' > object)',
function () {
assert(gemoji.name[alias].emoji === unicode);
}
);
});
it('should be accessible by emoji (' + unicode + ' > object)',
function () {
assert(gemoji.unicode[unicode].name === name);
}
);
describe('Information', function () {
it('should have a `name` field', function () {
assert(typeof information.name === 'string');
assert(information.name === name);
});
it('should have an `emoji` field', function () {
assert(typeof information.emoji === 'string');
assert(information.emoji === unicode);
});
it('should have a `description` field', function () {
assert(typeof information.description === 'string');
assert(information.description === description);
});
it('should have a `names` list', function () {
assert(Array.isArray(information.names) === true);
assert(information.names.length >= 1);
information.names.forEach(function (name) {
assert(typeof name === 'string');
assert(aliases.indexOf(name) !== -1);
});
aliases.forEach(function (name) {
assert(information.names.indexOf(name) !== -1);
});
});
it('should have a `tags` list', function () {
assert(Array.isArray(information.tags) === true);
information.tags.forEach(function (tag) {
assert(typeof tag === 'string');
assert(tags.indexOf(tag) !== -1);
});
tags.forEach(function (tag) {
assert(information.tags.indexOf(tag) !== -1);
});
});
});
});
}
/**
* Validate all crawled gemoji-objects.
*/
emoji.forEach(describeGemojiObject);
| 'use strict';
/**
* Dependencies.
*/
var emoji,
gemoji,
assert;
emoji = require('./data/emoji.json');
gemoji = require('./');
assert = require('assert');
/**
* Tests for basic structure.
*/
describe('gemoji', function () {
it('should have a `name` property', function () {
assert(
Object.prototype.toString.call(gemoji.name) === '[object Object]'
);
});
it('should have an `unicode` property', function () {
assert(
Object.prototype.toString.call(gemoji.unicode) ===
'[object Object]'
);
});
});
/**
* Validate if a crawled gemoji is indeed (correctly)
* present in this module.
*
* @param {Object} gemojiObject
* @param {string} gemojiObject.emoji - Unicode
* representation.
* @param {string} gemojiObject.description - Human
* description of the picture.
* @param {Array.<string>} gemojiObject.aliases - List
* of names used by GitHub.
* @param {Array.<string>} gemojiObject.tags - List
* of tags.
*/
function describeGemojiObject(gemojiObject) {
var unicode,
information,
description,
aliases,
tags,
name;
unicode = gemojiObject.emoji;
/**
* Some gemoji, such as `octocat`, do not have a
* unicode representation. Those are not present in
* `gemoji`. Exit.
*/
if (!unicode) {
return;
}
description = gemojiObject.description;
aliases = gemojiObject.aliases;
tags = gemojiObject.tags;
name = aliases[0];
information = gemoji.unicode[unicode];
describe(unicode + ' ' + description, function () {
aliases.forEach(function (alias) {
it('should be accessible by name (' + alias + ' > object)',
function () {
assert(gemoji.name[alias].emoji === unicode);
}
);
});
it('should be accessible by emoji (' + unicode + ' > object)',
function () {
assert(gemoji.unicode[unicode].name === name);
}
);
describe('Information', function () {
it('should have a `name` field', function () {
assert(typeof information.name === 'string');
assert(information.name === name);
});
it('should have an `emoji` field', function () {
assert(typeof information.emoji === 'string');
assert(information.emoji === unicode);
});
it('should have a `description` field', function () {
assert(typeof information.description === 'string');
assert(information.description === description);
});
it('should have a `names` list', function () {
assert(Array.isArray(information.names) === true);
assert(information.names.length >= 1);
information.names.forEach(function (name) {
assert(typeof name === 'string');
assert(aliases.indexOf(name) !== -1);
});
aliases.forEach(function (name) {
assert(information.names.indexOf(name) !== -1);
});
});
it('should have a `tags` list', function () {
assert(Array.isArray(information.tags) === true);
information.tags.forEach(function (tag) {
assert(typeof tag === 'string');
assert(tags.indexOf(tag) !== -1);
});
tags.forEach(function (tag) {
assert(information.tags.indexOf(tag) !== -1);
});
});
});
});
}
/**
* Validate all crawled gemoji-objects.
*/
emoji.forEach(describeGemojiObject);
| JavaScript | 0.001299 |
60267a2d2a01b39410f20c8953f6b71430d4d6ed | fix example not using mocks (#445) | packages/data-point/examples/reducer-entity-instance.js | packages/data-point/examples/reducer-entity-instance.js | const assert = require("assert");
const DataPoint = require("../");
const { Model, Request } = DataPoint;
const mocks = require("./async-example.mocks");
// mock request calls
mocks();
const PersonRequest = Request("PersonRequest", {
url: "https://swapi.co/api/people/{value}/"
});
const PersonModel = Model("PersonModel", {
value: {
name: "$name",
birthYear: "$birth_year"
}
});
const dataPoint = DataPoint.create();
dataPoint.resolve([PersonRequest, PersonModel], 1).then(output => {
assert.deepStrictEqual(output, {
name: "Luke Skywalker",
birthYear: "19BBY"
});
});
| const assert = require("assert");
const DataPoint = require("../");
const { Model, Request } = DataPoint;
const PersonRequest = Request("PersonRequest", {
url: "https://swapi.co/api/people/{value}"
});
const PersonModel = Model("PersonModel", {
value: {
name: "$name",
birthYear: "$birth_year"
}
});
const dataPoint = DataPoint.create();
dataPoint.resolve([PersonRequest, PersonModel], 1).then(output => {
assert.deepStrictEqual(output, {
name: "Luke Skywalker",
birthYear: "19BBY"
});
});
| JavaScript | 0 |
6ddb22900275b3c8d3adf9840dad0be002a99d27 | fix init method | src/core/plugin.js | src/core/plugin.js | 'use strict';
const EventEmittable = require('./eventemittable');
const Unique = require('./unique');
const Promise = require('bluebird');
const ParamValidator = require('./param-validator');
const errorist = require('errorist');
const validator = ParamValidator.validator;
const {DepGraph} = require('dependency-graph');
const each = require('lodash/collection/each');
const customError = require('../util/custom-error');
const PluginError = customError('PluginError');
const Plugin = ParamValidator
.stampName('Plugin')
.compose(Unique)
.static({
PluginError
})
.validate({
init() {
const originalFunc = this.func;
this.func = Promise.method(this.func);
const depGraph = this.depGraph = this.depGraph || new DepGraph();
const name = this.name;
depGraph.addNode(name);
each([].concat(this.dependencies || []), dep => {
try {
depGraph.addDependency(name, dep);
} catch (ignored) {
throw PluginError(`Cannot find dependency "${dep}" needed by ` +
`plugin "${name}"`);
}
});
Object.defineProperty(this, 'originalFunc', {
value: originalFunc,
writable: false,
configurable: true
});
}
}, {
init: [
validator.object({
instance: validator.object({
name: validator.string()
.required()
.label('name')
.description('Plugin name'),
func: validator.func()
.required()
.label('func')
.description('Plugin function'),
dependencies: validator.array()
.items(validator.string())
.single(true)
.label('dependencies')
.description('Plugin dependencies'),
api: validator.object()
.required()
.label('api')
.description('API object which each plugin will have access to')
})
.label('instance')
.unknown(true)
.description('Stampit instance')
})
.unknown(true)
]
})
.methods({
load() {
return this.func(this.api)
.catch(err => {
throw errorist(err);
})
.tap(() => this.emit('loaded', {
name: this.name
}));
}
})
.compose(EventEmittable, Unique);
module.exports = Plugin;
| 'use strict';
const EventEmittable = require('./eventemittable');
const Unique = require('./unique');
const Promise = require('bluebird');
const ParamValidator = require('./param-validator');
const errorist = require('errorist');
const validator = ParamValidator.validator;
const {DepGraph} = require('dependency-graph');
const each = require('lodash/collection/each');
const customError = require('../util/custom-error');
const PluginError = customError('PluginError');
const Plugin = ParamValidator
.stampName('Plugin')
.compose(Unique)
.static({
PluginError
})
.validate({
init() {
const originalFunc = this.func;
this.func = Promise.method(this.func);
const depGraph = this.depGraph = this.depGraph || new DepGraph();
const name = this.name;
depGraph.addNode(name);
each([].concat(this.dependencies || []), dep => {
try {
depGraph.addDependency(name, dep);
} catch (ignored) {
throw PluginError(`Cannot find dependency "${dep}" needed by ` +
`plugin "${name}"`);
}
});
Object.defineProperty(this, 'originalFunc', {
value: originalFunc,
writable: false,
configurable: true
});
}
}, {
init: [
validator.object({
instance: validator.object({
name: validator.string()
.required()
.label('name')
.description('Plugin name'),
func: validator.func()
.required()
.label('func')
.description('Plugin function'),
dependencies: validator.array()
.items(validator.string())
.single(true)
.label('dependencies')
.description('Plugin dependencies'),
api: validator.object()
.required()
.label('api')
.description('API object which each plugin will have access to')
})
.unknown(true)
.label('context')
.description('Stampit init context')
})
]
})
.methods({
load() {
return this.func(this.api)
.catch(err => {
throw errorist(err);
})
.tap(() => this.emit('loaded', {
name: this.name
}));
}
})
.compose(EventEmittable, Unique);
module.exports = Plugin;
| JavaScript | 0.000096 |
2601c94c7a30f2f127daf3d09d876524605a2992 | update script | js/script.js | js/script.js | jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();jQuery('.article-body iframe').remove();jQuery('.article-body .adsbygoogle').remove();jQuery('#main').css('overflow', 'hidden'); | jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();jQuery('.article-body iframe').remove();jQuery('.article-body script').remove();jQuery('#main').css('overflow', 'hidden'); | JavaScript | 0.000001 |
c07af02a3c872b2ce90da9700754ffd7e2d2c058 | add stop timer logic | js/script.js | js/script.js | // Declare global variables
var mainTimer = document.getElementById("startTimer");
var timerState = document.getElementById("displayTimer");
var breakState = document.getElementById("displayBreak");
var count = parseInt(document.getElementById("displayTimer").innerHTML);
var breakCount = parseInt(document.getElementById("displayBreak").innerHTML);
var alertSound = document.getElementById("alertsound");
var timerAdd = document.getElementById("timerAdd");
var timerSubtract = document.getElementById("timerSubtract");
var breakAdd = document.getElementById("breakAdd");
var breakSubtract = document.getElementById("breakSubtract");
var clickCount = 0;
// Event handler for user clicks on main timer
mainTimer.addEventListener("click", activateTimer);
// Start timer and decrement down
function activateTimer(event) {
if (timerState.style.zIndex == "-1") {
timerState.style.zIndex = "1";
breakState.style.zIndex = "1";
clickCount++;
var counter = setInterval(timer, 1000);
if (clickCount <= 1) {
count *= 60;
}
// Format timer to minutes and seconds
function timer() {
if (timerState.style.zIndex == "1") {
count -= 1;
if (count === 0) {
alertSound.play();
clearInterval(counter);
var breakCounter = setInterval(breakTimer);
}
timerState.innerHTML = count;
if (Math.floor(count / 60) > 10) {
if (count % 60 >= 10) {
timerState.innerHTML = Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
Math.floor(count / 60) + ":" + "0" + count % 60;
}
} else {
if (count % 60 >= 10) {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + "0" + count % 60;
}
}
// Format break timer to minutes and seconds
function breakTimer() {}
} else {
clearInterval(counter);
timerState.style.zIndex = "-1";
breakState.style.zIndex = "-1";
}
}
}
event.preventDefault();
}
// Event handlers for incrementing idle timer
timerAdd.addEventListener("click", function(event) {
count += 1;
if (count < 10) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
event.preventDefault();
});
// Event handlers for decrementing idle timer
timerSubtract.addEventListener("click", function(event) {
if (count > 1) {
count -= 1;
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
if (count < 10 && count > 0) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
event.preventDefault();
});
// Event handler for incrementing idle break timer
breakAdd.addEventListener("click", function(event) {
breakCount += 1;
breakState.innerHTML = breakCount;
event.preventDefault();
});
// Event handler for decrementing idle break timer
breakSubtract.addEventListener("click", function(event) {
if (breakCount > 0) {
breakCount -= 1;
breakState.innerHTML = breakCount;
}
event.preventDefault();
});
| // Declare global variables
var mainTimer = document.getElementById("startTimer");
var timerState = document.getElementById("displayTimer");
var breakState = document.getElementById("displayBreak");
var count = parseInt(document.getElementById("displayTimer").innerHTML);
var breakCount = parseInt(document.getElementById("displayBreak").innerHTML);
var alertSound = document.getElementById("alertsound");
var timerAdd = document.getElementById("timerAdd");
var timerSubtract = document.getElementById("timerSubtract");
var breakAdd = document.getElementById("breakAdd");
var breakSubtract = document.getElementById("breakSubtract");
var clickCount = 0;
// Event handler for user clicks on main timer
mainTimer.addEventListener("click", activateTimer);
// Start timer and decrement down
function activateTimer(event) {
if (timerState.style.zIndex == "-1") {
timerState.style.zIndex = "1";
breakState.style.zIndex = "1";
clickCount++;
var counter = setInterval(timer, 1000);
if (clickCount <= 1) {
count *= 60;
}
// Format timer to minutes and seconds
function timer() {
count -= 1;
if (count === 0) {
alertSound.play();
clearInterval(counter);
var breakCounter = setInterval(breakTimer);
}
timerState.innerHTML = count;
if (Math.floor(count / 60) > 10) {
if (count % 60 >= 10) {
timerState.innerHTML = Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + "0" + count % 60;
}
} else {
if (count % 60 >= 10) {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + "0" + count % 60;
}
}
// Format break timer to minutes and seconds
function breakTimer() {}
}
} else {
timerState.style.zIndex = "-1";
breakState.style.zIndex = "-1";
}
event.preventDefault();
}
// Event handlers for incrementing idle timer
timerAdd.addEventListener("click", function(event) {
count += 1;
if (count < 10) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
event.preventDefault();
});
// Event handlers for decrementing idle timer
timerSubtract.addEventListener("click", function(event) {
if (count > 1) {
count -= 1;
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
if (count < 10 && count > 0) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
event.preventDefault();
});
// Event handler for incrementing idle break timer
breakAdd.addEventListener("click", function(event) {
breakCount += 1;
breakState.innerHTML = breakCount;
event.preventDefault();
});
// Event handler for decrementing idle break timer
breakSubtract.addEventListener("click", function(event) {
if (breakCount > 0) {
breakCount -= 1;
breakState.innerHTML = breakCount;
}
event.preventDefault();
});
| JavaScript | 0.000001 |
d4c2050662bcaf878d4e12bda96beb2eb3584125 | Update componentsDirective | angular/directives/componentsDirective.js | angular/directives/componentsDirective.js | (function() {
'use strict';
/**
* @ngdoc directive
* @name app
*
* @description
* _Update the description and restriction._
*
* @restrict A
* */
angular.module('components.directives').directive('componentsDirective', [function() {
return {
restrict: 'A',
link : function(scope, elem, attr) {
}
};
}]);
})(); | (function() {
'use strict';
/**
* @ngdoc directive
* @name app
*
* @description
* _Please update the description and restriction._
*
* @restrict A
* */
angular.module('components.directives').directive('componentsDirective', function() {
return {
restrict: 'A',
link : function(scope, elem, attr) {
}
};
});
})(); | JavaScript | 0 |
1b42aa05260069c1965f016dc94840cc8c3226e7 | fix whoami | scripts/eastereggs.js | scripts/eastereggs.js | module.exports = function(robot){
var thankYouResponses = [
"You're welcome!",
"No problem."
];
robot.hear(/(thanks|thank you) bocbot/i, function(res){
var index = Math.floor(Math.random() * thankYouResponses.length);
res.reply(thankYouResponses[index]);
});
robot.hear(/I like pie/i, function(res){
robot.send('I like pie too');
});
robot.respond(/open (.*) door/i, function(res){
var doorType = res.match[1];
if (doorType == 'pod bay')
res.reply("I'm afraid I can't let you do that.");
else
res.reply('Opening ' + doorType + ' doors.');
});
robot.respond(/(you are|you're)(.*) slow/i, function(res){
setTimeout(function(){
res.reply('Who you callin\' slow?');
}, 1000 * 15);
});
robot.respond(/(have|drink|consume)(.*) beer/i, function(res){
var beersHad = robot.brain.get('totalBeersHad') || 0;
if (beersHad > 4){
var lastBeerFrom = robot.brain.get('lastBeerFrom');
res.reply("I think I've had too many. " + lastBeerFrom + " got me too drunk. I need to sleep it off first.");
}
else{
res.reply("Sure thing! _chugs beer_");
robot.brain.set('totalBeersHad', beersHad + 1);
robot.brain.set('lastBeerFrom', res.message.user.name);
}
});
robot.respond(/sleep it off/i, function(res){
robot.brain.set('totalBeersHad', 0);
res.reply('zzzzz');
});
robot.respond(/who am i/, function(res){
if (robot.auth.isAdmin(res.message.user))
res.respond(res.message.user.name);
});
} | module.exports = function(robot){
var thankYouResponses = [
"You're welcome!",
"No problem."
];
robot.hear(/(thanks|thank you) bocbot/i, function(res){
var index = Math.floor(Math.random() * thankYouResponses.length);
res.reply(thankYouResponses[index]);
});
robot.hear(/I like pie/i, function(res){
robot.send('I like pie too');
});
robot.respond(/open (.*) door/i, function(res){
var doorType = res.match[1];
if (doorType == 'pod bay')
res.reply("I'm afraid I can't let you do that.");
else
res.reply('Opening ' + doorType + ' doors.');
});
robot.respond(/(you are|you're)(.*) slow/i, function(res){
setTimeout(function(){
res.reply('Who you callin\' slow?');
}, 1000 * 15);
});
robot.respond(/(have|drink|consume)(.*) beer/i, function(res){
var beersHad = robot.brain.get('totalBeersHad') || 0;
if (beersHad > 4){
var lastBeerFrom = robot.brain.get('lastBeerFrom');
res.reply("I think I've had too many. " + lastBeerFrom + " got me too drunk. I need to sleep it off first.");
}
else{
res.reply("Sure thing! _chugs beer_");
robot.brain.set('totalBeersHad', beersHad + 1);
robot.brain.set('lastBeerFrom', res.message.user.name);
}
});
robot.respond(/sleep it off/i, function(res){
robot.brain.set('totalBeersHad', 0);
res.reply('zzzzz');
});
robot.respond(/who am i/, function(res){
res.sendPrivate(res.message.user.name);
});
} | JavaScript | 0.000015 |
166e2e7881707c45f5ea7022ea1dd61665093848 | Update script.js | js/script.js | js/script.js | (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var width = 512;
var height = 288;
var blockSize = 16;
document.getElementById("startbtn").onclick = paintscreen;
//paint a block
function paintblock(x, y) {
for(var i = 0; i < blockSize; i++) {
for(var j = 0; j< blockSize; j++) {
if(i == 0 || i == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(x+i, y+j, 1, 1);
}
if(j == 0 || j == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(x+i, y+j, 1, 1);
}
}
}
}
//paint the screen
function paintscreen() {
for(var i = 0; i< 32; i++) {
for(var j = 0; j < 18; j++) {
paintblock(i*blockSize, j*blockSize);
}
}
}
}
})(window, document, undefined);
| (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var width = 512;
var height = 288;
var blockSize = 16;
document.getElementById("startbtn").onclick = paintscreen;
//paint a block
function paintblock(x, y) {
for(var i = 0; i < blockSize; i++) {
for(var j = 0; j< blockSize; j++) {
if(i == 0 || i == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(i*x, j*y, 1, 1);
}
if(j == 0 || j == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(i*x, j*y, 1, 1);
}
}
}
}
//paint the screen
function paintscreen() {
for(var i = 0; i< 32; i++) {
for(var j = 0; j < 18; j++) {
paintblock(i*blockSize, j*blockSize);
}
}
}
}
})(window, document, undefined);
| JavaScript | 0.000002 |
9222123ab11b5b92f8b10ac74a7149b659b2f8cc | Update app/assets/javascripts/ckeditor/config.js | app/assets/javascripts/ckeditor/config.js | app/assets/javascripts/ckeditor/config.js | /*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
/* Filebrowser routes */
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
// Rails CSRF token
config.filebrowserParams = function(){
var csrf_token, csrf_param, meta,
metas = document.getElementsByTagName('meta'),
params = new Object();
for ( var i = 0 ; i < metas.length ; i++ ){
meta = metas[i];
switch(meta.name) {
case "csrf-token":
csrf_token = meta.content;
break;
case "csrf-param":
csrf_param = meta.content;
break;
default:
continue;
}
}
if (csrf_param !== undefined && csrf_token !== undefined) {
params[csrf_param] = csrf_token;
}
return params;
};
config.addQueryString = function( url, params ){
var queryString = [];
if ( !params ) {
return url;
} else {
for ( var i in params )
queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
}
return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
};
// Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
CKEDITOR.on( 'dialogDefinition', function( ev ){
// Take the dialog name and its definition from the event data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var content, upload;
if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
upload = (content == null ? null : content.get('upload'));
if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
upload.filebrowser['params'] = config.filebrowserParams();
upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
}
}
});
};
| /*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
/* Filebrowser routes */
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
// Rails CSRF token
config.filebrowserParams = function(){
var csrf_token, csrf_param, meta,
metas = document.getElementsByTagName('meta'),
params = new Object();
for ( var i = 0 ; i < metas.length ; i++ ){
meta = metas[i];
switch(meta.name) {
case "csrf-token":
csrf_token = meta.content;
break;
case "csrf-param":
csrf_param = meta.content;
break;
default:
continue;
}
}
if (csrf_param !== undefined && csrf_token !== undefined) {
params[csrf_param] = csrf_token;
}
return params;
};
config.addQueryString = function( url, params ){
var queryString = [];
if ( !params ) {
return url;
} else {
for ( var i in params )
queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
}
return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
};
// Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
CKEDITOR.on( 'dialogDefinition', function( ev ){
// Take the dialog name and its definition from the event data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var content, upload;
if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
upload = (content == null ? null : content.get('upload'));
if (upload && upload.filebrowser['params'] == null) {
upload.filebrowser['params'] = config.filebrowserParams();
upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
}
}
});
};
| JavaScript | 0.000106 |
6b8befeff80e1ea8ae3cd7401b40a6e1a8703bb1 | Update script.js | js/script.js | js/script.js | var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
(function(window, document, undefined) {
window.onload = init;
function init() {
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var myTimer;
// set the dynamic outside the loop
var dynamic = 10;
//loop function
function loop() {
// change dynamic
//dynamic = dynamic * 1.1;
x = dynamic;
y = dynamic;
//if we've reached the end, change direction
if(x
// stop the the animation if it runs out-of-canvas
if (x > canvas.width || y > canvas.height) {
//c.clearRect(0, 0, canvas.width, canvas.height);
clearInterval(myTimer);
}
// clear the canvas for this loop's animation
//c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.arc(x, y, 10, 0, Math.PI * 2, false);
c.fill();
}
$("#startbtn").click(function(){ dynamic=10; myTimer=setInterval(loop,20); });
}
})(window, document, undefined);
| var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
(function(window, document, undefined) {
window.onload = init;
function init() {
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var myTimer;
// set the dynamic outside the loop
var dynamic = 10;
//loop function
function loop() {
// change dynamic
dynamic = dynamic * 1.1;
x = dynamic;
y = dynamic * 1.2;
// stop the the animation if it runs out-of-canvas
if (x > canvas.width || y > canvas.height) {
//c.clearRect(0, 0, canvas.width, canvas.height);
clearInterval(myTimer);
}
// clear the canvas for this loop's animation
//c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.arc(x, y, 10, 0, Math.PI * 2, false);
c.fill();
}
$("#startbtn").click(function(){ dynamic=10; myTimer=setInterval(loop,20); });
}
})(window, document, undefined);
| JavaScript | 0.000002 |
614dc5f34e7dde8034e0882f63939c0d49fc13a2 | Update script.js | js/script.js | js/script.js | (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var cwidth = 960;
var cheight = 540;
document.getElementById("paintbtn").onclick = paint;
function reset(){
c.clearRect ( 0 , 0 , canvas.width, canvas.height );
c.beginPath();
}
function createRoom(x, y, pw, ph){
var randw = Math.floor((Math.random() * ((pw/2) - 2 + 1) + 2) );
var randh = Math.floor((Math.random() * ((ph/2) - 2 + 1) + 2) );
//alert(randw + ", " + randh);
return [randw, randh];
}
function paint(){
reset();
var widthSelect = document.getElementById("width");
var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;
var heightSelect = document.getElementById("height");
var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
//alert(pathWidth + ", " + pathHeight);
for(var i = 0; i< pathWidth; i++){
for(var j = 0; j< pathHeight; j++){
c.beginPath();
c.lineWidth = 1;
c.rect(i*30+0.5, j*30+0.5, 30, 30);
c.stroke();
}
}
for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
var randRoom = Math.floor((Math.random() * 9));
if(randRoom < 1){
roomDim = createRoom(i,j,pathWidth,pathHeight);
c.beginPath();
c.lineWidth = 3;
c.rect(i*30 + 0.5, j*30+ 0.5, roomDim[0]*30, roomDim[1]*30);
c.stroke();
}
}
}
}
}
})(window, document, undefined);
| (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var cwidth = 960;
var cheight = 540;
document.getElementById("paintbtn").onclick = paint;
function reset(){
c.clearRect ( 0 , 0 , canvas.width, canvas.height );
c.beginPath();
}
function createRoom(x, y, pw, ph){
var randw = Math.floor((Math.random() * ((pw/2) - 2 + 1) + 2) );
var randh = Math.floor((Math.random() * ((ph/2) - 2 + 1) + 2) );
//alert(randw + ", " + randh);
return [randw, randh];
}
function paint(){
reset();
var widthSelect = document.getElementById("width");
var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;
var heightSelect = document.getElementById("height");
var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
//alert(pathWidth + ", " + pathHeight);
for(var i = 0; i< pathWidth; i++){
for(var j = 0; j< pathHeight; j++){
c.beginPath();
c.lineWidth = 1;
c.rect(i*30+0.5, j*30+0.5, 30, 30);
c.stroke();
}
}
for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
var randRoom = Math.floor((Math.random() * 19));
if(randRoom < 1){
roomDim = createRoom(i,j,pathWidth,pathHeight);
c.beginPath();
c.lineWidth = 3;
c.rect(i*30 + 0.5, j*30+ 0.5, roomDim[0]*30, roomDim[1]*30);
c.stroke();
}
}
}
}
}
})(window, document, undefined);
| JavaScript | 0.000002 |
ee8efc2d327da8d4b10e94ab274273225bda038a | Support browsers without `console.log` | js/search.js | js/search.js | function Search (url) {
this.reset();
this.url = url;
this.MAXIMUM_ACTIVE_CONNECTIONS = 10;
this.QUEUE_DELAY = 100;
}
Search.prototype.reset = function () {
this.discovered = [];
this.activeConnections = 0;
this.searchQueue = [];
this.nextSearchQueue = [];
this.chains = [];
}
Search.prototype.checkUser = function (user) {
return $.ajax({
url: this.url + user + ".json",
contentType: "application/json",
type: "GET"
});
}
Search.prototype.add = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
// Push the user into the queue so the followers can be found for it
this.searchQueue.push([user, chain]);
}
Search.prototype.addNext = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
this.nextSearchQueue.push([user, chain]);
}
Search.prototype.register = function (user, chain) {
// Check if the user has already been searched
if (this.hasSearched(user)) {
return;
}
chain.push(user);
// Add the new chain into the existing list of chains
this.chains.push(chain);
this.discovered.push(user);
}
Search.prototype.hasSearched = function (user) {
return (this.discovered.indexOf(user) >= 0);
}
Search.prototype.queueFinished = function () {
// Placeholder method that should be overriden by subclasses
}
/*
Move all users who are in the next search queue to the current search queue
and reset the next search queue.
*/
Search.prototype.shiftQueue = function () {
this.searchQueue = this.nextSearchQueue;
this.nextSearchQueue = [];
}
Search.prototype.processQueue = function () {
// Hold a reference to `this` so we can hold the reference in the timeout
var self = this;
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// If all of the connections are in use, wait a bit until trying to
// process the queue again
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
return;
}
// Fire the finished signal only when there is nothing left in the queue and
// all connections have finished
if (self.searchQueue.length == 0 && self.activeConnections == 0) {
self.queueFinished();
return;
}
// Process the queue until it is empty
while (self.searchQueue.length > 0) {
// Keep pushing to the console to make sure it didn't stall
if (console != null && console.log != null) {
console.log("Processing queue...");
}
// Check to see if all of the connections are in use
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// Stop trying to process the queue
break;
}
// Pull the first item off the queue
var queueItem = self.searchQueue.splice(0, 1);
// If there is nothing left on the queue, just continue
if (queueItem.length == 0) {
continue;
}
// Process the item from the queue
self.processQueueItem(queueItem[0]);
}
// Once the queue empties, fire it once more to call `queueFinished`
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
};
Search.prototype.processQueueItem = function (queueItem) {
var self = this;
var user = queueItem[0];
var chain = queueItem[1];
self.activeConnections += 1;
var $request = this.checkUser(user);
$request.then(function (user) {
var users = self.getNextUsers(user);
users.forEach(function (u) {
self.addNext(u, chain);
});
self.activeConnections -= 1;
});
$request.fail(function () {
self.activeConnections -= 1;
});
}
| function Search (url) {
this.reset();
this.url = url;
this.MAXIMUM_ACTIVE_CONNECTIONS = 10;
this.QUEUE_DELAY = 100;
}
Search.prototype.reset = function () {
this.discovered = [];
this.activeConnections = 0;
this.searchQueue = [];
this.nextSearchQueue = [];
this.chains = [];
}
Search.prototype.checkUser = function (user) {
return $.ajax({
url: this.url + user + ".json",
contentType: "application/json",
type: "GET"
});
}
Search.prototype.add = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
// Push the user into the queue so the followers can be found for it
this.searchQueue.push([user, chain]);
}
Search.prototype.addNext = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
this.nextSearchQueue.push([user, chain]);
}
Search.prototype.register = function (user, chain) {
// Check if the user has already been searched
if (this.hasSearched(user)) {
return;
}
chain.push(user);
// Add the new chain into the existing list of chains
this.chains.push(chain);
this.discovered.push(user);
}
Search.prototype.hasSearched = function (user) {
return (this.discovered.indexOf(user) >= 0);
}
Search.prototype.queueFinished = function () {
// Placeholder method that should be overriden by subclasses
}
/*
Move all users who are in the next search queue to the current search queue
and reset the next search queue.
*/
Search.prototype.shiftQueue = function () {
this.searchQueue = this.nextSearchQueue;
this.nextSearchQueue = [];
}
Search.prototype.processQueue = function () {
// Hold a reference to `this` so we can hold the reference in the timeout
var self = this;
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// If all of the connections are in use, wait a bit until trying to
// process the queue again
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
return;
}
// Fire the finished signal only when there is nothing left in the queue and
// all connections have finished
if (self.searchQueue.length == 0 && self.activeConnections == 0) {
self.queueFinished();
return;
}
// Process the queue until it is empty
while (self.searchQueue.length > 0) {
console.log("Processing queue...");
// Check to see if all of the connections are in use
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// Stop trying to process the queue
break;
}
// Pull the first item off the queue
var queueItem = self.searchQueue.splice(0, 1);
// If there is nothing left on the queue, just continue
if (queueItem.length == 0) {
continue;
}
// Process the item from the queue
self.processQueueItem(queueItem[0]);
}
// Once the queue empties, fire it once more to call `queueFinished`
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
};
Search.prototype.processQueueItem = function (queueItem) {
var self = this;
var user = queueItem[0];
var chain = queueItem[1];
self.activeConnections += 1;
var $request = this.checkUser(user);
$request.then(function (user) {
var users = self.getNextUsers(user);
users.forEach(function (u) {
self.addNext(u, chain);
});
self.activeConnections -= 1;
});
$request.fail(function () {
self.activeConnections -= 1;
});
}
| JavaScript | 0 |
dca094b389a6ae0c3a2d1074ddd4e91349facc23 | create the DummySerial | js/serial.js | js/serial.js | var GameboyJS;
(function (GameboyJS) {
"use strict";
// Handlers for the Serial port of the Gameboy
// The ConsoleSerial is an output-only serial port
// designed for debug purposes as some test roms output data on the serial port
//
// Will regularly output the received byte (converted to string) in the console logs
// This handler always push the value 0xFF as an input
var ConsoleSerial = {
current: '',
timeout: null,
out: function(data) {
ConsoleSerial.current += String.fromCharCode(data);
if (data == 10) {
ConsoleSerial.print();
} else {
clearTimeout(ConsoleSerial.timeout);
ConsoleSerial.timeout = setTimeout(ConsoleSerial.print, 500);
}
},
in: function() {
return 0xFF;
},
print: function() {
clearTimeout(ConsoleSerial.timeout);
console.log('serial: '+ConsoleSerial.current);
ConsoleSerial.current = '';
}
};
GameboyJS.ConsoleSerial = ConsoleSerial;
// A DummySerial outputs nothing and always inputs 0xFF
var DummySerial = {
out: function() {},
in: function() {
return 0xFF;
}
};
GameboyJS.DummySerial = DummySerial;
}(GameboyJS || (GameboyJS = {})));
| var GameboyJS;
(function (GameboyJS) {
"use strict";
// Handler for the Serial port of the Gameboy
//
// It is designed for debug purposes as some tests output data on the serial port
//
// Will regularly output the received byte (converted to string) in the console logs
// This handler always push the value 0xFF as an input
var ConsoleSerial = {
current: '',
timeout: null,
out: function(data) {
ConsoleSerial.current += String.fromCharCode(data);
if (data == 10) {
ConsoleSerial.print();
} else {
clearTimeout(ConsoleSerial.timeout);
ConsoleSerial.timeout = setTimeout(ConsoleSerial.print, 500);
}
},
in: function(){
return 0xFF;
},
print: function() {
clearTimeout(ConsoleSerial.timeout);
console.log('serial: '+ConsoleSerial.current);
ConsoleSerial.current = '';
}
};
GameboyJS.ConsoleSerial = ConsoleSerial;
}(GameboyJS || (GameboyJS = {})));
| JavaScript | 0.000496 |
9495a3b19811899337da8f1ceabea434c3685c8f | Update social.js | js/social.js | js/social.js | var social = {
facebook: {
share: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
},
count: function(url) {
var result;
var s = $.get("https://graph.facebook.com/",{id: url},function(data, status){
result = data.share;
});
return result;
}
}
}
| var social = {
facebook: {
share: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
},
count: function(url) {
var result;
$.get("https://graph.facebook.com/",{id: url},function(data, status){
result = data.share;
});
return result;
}
}
}
| JavaScript | 0.000001 |
1ed5717d54476c8f599ffea682c2e53ce6f93102 | Update social.js | js/social.js | js/social.js | var social = {
linkedin: {
process: function(url, callback) {
$.get("https://graph.facebook.com/",{id: url},function(data, status){
callback(data.count);
});
}
},
facebook: {
process: function(url, callback) {
$.get("https://graph.facebook.com/",{format: "json", url: url},function(data, status){
callback(data.share);
});
}
},
reddit: {
process: function(domain, callback) {
$.get("https://api.reddit.com/domain/" + domain,function(data, status){
var results = data.data.children;
var array = new Array();
for(var i = 0; i < results.length; i++) {
var url = results[i].data.url;
var score = results[i].data.score;
var old = array.find(function(v){return v.url === url});
if(typeof old === "undefined") {
var value = {
url: url,
score: score,
count: 1
};
array.push(value);
} else {
old.score = old.score + score;
old.count = old.count + 1;
}
}
callback({
items: array,
count: array.reduce(function(total,current){return total + current.count;},0),
score: array.reduce(function(total,current){return total + current.score;},0),
find: function(url) {
return this.items.find(function(item){return item.url === url})
}
});
});
}
}
}
function intToString(integer) {
if(isNaN(integer) || integer <= 0) {
return "";
} else if(integer < 1000) {
return integer;
} else if(integer < 1000000) {
return Math.round(integer / 1000) + "k";
} else {
return Math.round(integer / 1000000) + "m";
}
}
| var social = {
facebook: {
share: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
},
count: function(url, callback) {
$.get("https://graph.facebook.com/",{id: url},function(data, status){
callback(data.share);
});
}
},
reddit: {
process: function(domain, callback) {
$.get("https://api.reddit.com/domain/" + domain,function(data, status){
var results = data.data.children;
var array = new Array();
for(var i = 0; i < results.length; i++) {
var url = results[i].data.url;
var score = results[i].data.score;
var old = array.find(function(v){return v.url === url});
if(typeof old === "undefined") {
var value = {
url: url,
score: score,
count: 1
};
array.push(value);
} else {
old.score = old.score + score;
old.count = old.count + 1;
}
}
callback({
items: array,
count: array.reduce(function(total,current){return total + current.count;},0),
score: array.reduce(function(total,current){return total + current.score;},0),
find: function(url) {
return this.items.find(function(item){return item.url === url})
}
});
});
}
}
}
function intToString(integer) {
if(isNaN(integer) || integer <= 0) {
return "";
} else if(integer < 1000) {
return integer;
} else if(integer < 1000000) {
return Math.round(integer / 1000) + "k";
} else {
return Math.round(integer / 1000000) + "m";
}
}
| JavaScript | 0.000001 |
856780f40f382efb558d161d2e1fc45934689146 | fix object parsing | game/world.js | game/world.js | var Player = require('./player');
var World = module.exports = function World(level, players) {
//Mixin level definitions
for (var key in level) {
this[key] = level[key];
}
this.init();
this.width = this.map_definition.width;
this.height = this.map_definition.height;
this.map = new Array(this.height);
this.tileset = {};
this.players = new Array(this.player_definition.length);
for (var i = 0, imax = this.player_definition.length; i < imax; i += 1) {
this.players[i] = new Player(this.player_definition[i]);
}
for (var i = 0, imax = this.map_definition.height; i < imax; i += 1) {
this.map[i] = new Array(this.map_definition.width);
for (var j = 0, jmax = this.map_definition.width; j < jmax; j += 1) {
this.map[i][j] = new this.map_definition.tileDefinition[i][j]();
this.tileset[this.map[i][j].type] = {
traversable: this.map_definition.tileDefinition[i][j].prototype.traversable
};
}
}
for (var i = 0, imax = this.map_definition.objectDefinition.length; i < imax; i += 1) {
var object_definition = this.map_definition.objectDefinition[i];
this.map[object_definition.x][object_definition.y].object = new object_definition.object();
}
}
| var Player = require('./player');
var World = module.exports = function World(level, players) {
//Mixin level definitions
for (var key in level) {
this[key] = level[key];
}
this.init();
this.width = this.map_definition.width;
this.height = this.map_definition.height;
this.map = new Array(this.height);
this.tileset = {};
this.players = new Array(this.player_definition.length);
for (var i = 0, imax = this.player_definition.length; i < imax; i += 1) {
this.players[i] = new Player(this.player_definition[i]);
}
for (var i = 0, imax = this.map_definition.height; i < imax; i += 1) {
this.map[i] = new Array(this.map_definition.width);
for (var j = 0, jmax = this.map_definition.width; j < jmax; j += 1) {
this.map[i][j] = new this.map_definition.tileDefinition[i][j]();
this.tileset[this.map[i][j].type] = {
traversable: this.map_definition.tileDefinition[i][j].prototype.traversable
};
}
}
for (var i = 0, imax = this.map_definition.objectDefinition.length; i < imax; i += 1) {
var object_definition = this.map_definition.objectDefinition[i];
this.map[object.x][object.y].object = new object_definition();
}
}
| JavaScript | 0.000067 |
255dadb1c03ea3076ba45e6198dac4dfe2839755 | Fix anvil jss suite. | tests/anvil/configSet/Resources/suites/jss.js | tests/anvil/configSet/Resources/suites/jss.js | /*
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
module.exports = new function() {
var finish;
var valueOf;
this.init = function(testUtils) {
finish = testUtils.finish;
valueOf = testUtils.valueOf;
}
this.name = "jss";
this.tests = [
{name: "platform_jss_dirs"}
]
this.platform_jss_dirs = function(testRun) {
var test = Ti.UI.createView({
id: "test",
backgroundColor: "blue"
});
valueOf(testRun, test).shouldNotBeNull();
if (Ti.Platform.name == "android") {
valueOf(testRun, test.backgroundColor).shouldBe("red");
} else {
valueOf(testRun, test.backgroundColor).shouldBe("blue");
}
finish(testRun);
}
}
| /*
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
module.exports = new function() {
var finish;
var valueOf;
this.init = function(testUtils) {
finish = testUtils.finish;
valueOf = testUtils.valueOf;
}
this.name = "jss";
this.tests = [
{name: "platform_jss_dirs"}
]
this.platform_jss_dirs = function(testRun) {
var test = Ti.UI.createView({ id: "test" });
valueOf(testRun, test).shouldNotBeNull();
if (Ti.Platform.name == "android") {
valueOf(testRun, test.backgroundColor).shouldBe("red");
} else {
valueOf(testRun, test.backgroundColor).shouldBe("blue");
}
finish(testRun);
}
}
| JavaScript | 0 |
386b47b0b505ca9445a5d4597110aa8f226e5a77 | Remove CM_FormField_Integer.getValue in favor of correct value sync. | library/CM/FormField/Integer.js | library/CM/FormField/Integer.js | /**
* @class CM_FormField_Integer
* @extends CM_FormField_Abstract
*/
var CM_FormField_Integer = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Integer',
_$noUiHandle: null,
ready: function() {
var field = this;
var $input = this.$('input');
var $slider = this.$('.noUiSlider');
var $sliderValue = this.$('.noUiSlider-value');
$slider.noUiSlider({
range: {min: field.getOption('min'), max: field.getOption('max')},
start: $input.val(),
step: field.getOption('step'),
handles: 1,
behaviour: 'tap'
});
$slider.on('slide set', function(e, val) {
val = parseInt(val);
$input.val(val);
$sliderValue.html(val);
field._onChange();
});
this._$noUiHandle = $slider.find('.noUi-handle');
this._$noUiHandle.attr('tabindex', '0');
$input.watch('disabled', function(propName, oldVal, newVal) {
if (false === newVal) {
$slider.removeAttr('disabled');
field._$noUiHandle.attr('tabindex', '0');
} else {
$slider.attr('disabled', 'disabled');
field._$noUiHandle.attr('tabindex', '-1');
}
});
this.bindJquery($(window), 'keydown', this._onKeyDown);
this.on('destruct', function() {
$input.unwatch('disabled');
});
},
/**
* @param {Number} value
*/
setValue: function(value) {
this.$('.noUiSlider').val(value);
this._onChange();
},
_onChange: function() {
this.trigger('change');
},
_onKeyDown: function(event) {
if (this._$noUiHandle.is(':focus')) {
if (event.which === cm.keyCode.LEFT || event.which === cm.keyCode.DOWN) {
this.setValue(this.getValue() - this.getOption('step'));
event.preventDefault();
}
if (event.which === cm.keyCode.RIGHT || event.which === cm.keyCode.UP) {
this.setValue(this.getValue() + this.getOption('step'));
event.preventDefault();
}
}
}
});
| /**
* @class CM_FormField_Integer
* @extends CM_FormField_Abstract
*/
var CM_FormField_Integer = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Integer',
_$noUiHandle: null,
ready: function() {
var field = this;
var $input = this.$('input');
var $slider = this.$('.noUiSlider');
var $sliderValue = this.$('.noUiSlider-value');
$slider.noUiSlider({
range: {min: field.getOption('min'), max: field.getOption('max')},
start: $input.val(),
step: field.getOption('step'),
handles: 1,
behaviour: 'tap'
});
$slider.on('slide set', function(e, val) {
val = parseInt(val);
$input.val(val);
$sliderValue.html(val);
field._onChange();
});
this._$noUiHandle = $slider.find('.noUi-handle');
this._$noUiHandle.attr('tabindex', '0');
$input.watch('disabled', function(propName, oldVal, newVal) {
if (false === newVal) {
$slider.removeAttr('disabled');
field._$noUiHandle.attr('tabindex', '0');
} else {
$slider.attr('disabled', 'disabled');
field._$noUiHandle.attr('tabindex', '-1');
}
});
this.bindJquery($(window), 'keydown', this._onKeyDown);
this.on('destruct', function() {
$input.unwatch('disabled');
});
},
/**
* @param {Number} value
*/
setValue: function(value) {
this.$('.noUiSlider').val(value);
this._onChange();
},
/**
* @returns {Number}
*/
getValue: function() {
return parseInt(this.$('.noUiSlider').val());
},
_onChange: function() {
this.trigger('change');
},
_onKeyDown: function(event) {
if (this._$noUiHandle.is(':focus')) {
if (event.which === cm.keyCode.LEFT || event.which === cm.keyCode.DOWN) {
this.setValue(this.getValue() - this.getOption('step'));
event.preventDefault();
}
if (event.which === cm.keyCode.RIGHT || event.which === cm.keyCode.UP) {
this.setValue(this.getValue() + this.getOption('step'));
event.preventDefault();
}
}
}
});
| JavaScript | 0 |
dd0ef7f927a5183b450b4f6e6b4b38a5339b886a | complete has user media method | scripts/src/UserMedia.js | scripts/src/UserMedia.js | window.define(['src/NavigatorWrapper'], function(NavigatorWrapper) {
"use strict";
var UserMedia = function(navigator) {
if(typeof navigator === "undefined") {
this.navigator = new NavigatorWrapper();
}
else {
this.navigator = navigator;
}
};
UserMedia.prototype.hasGetUserMedia = function() {
try {
this.navigator.getUserMedia();
return true;
}
catch(e) {
return false;
}
};
UserMedia.prototype.startCamera = function() {
// Not showing vendor prefixes.
navigator.webkitGetUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
console.log('Ready to go. Do some stuff. ', e);
};
}, function(e) {
console.log('Reeeejected!', e);
});
};
return UserMedia;
});
| window.define(['src/NavigatorWrapper'], function(NavigatorWrapper) {
"use strict";
var UserMedia = function(navigator) {
if(typeof navigator === "undefined") {
this.navigator = new NavigatorWrapper();
}
else {
this.navigator = navigator;
}
};
UserMedia.prototype.hasGetUserMedia = function() {
// Note: Opera is un prefixed.
return
};
UserMedia.prototype.startCamera = function() {
// Not showing vendor prefixes.
navigator.webkitGetUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
console.log('Ready to go. Do some stuff. ', e);
};
}, function(e) {
console.log('Reeeejected!', e);
});
};
return UserMedia;
});
| JavaScript | 0.000398 |
780473fccf5293da6dec4707707f4c472aba3243 | allow GH deps | tests/unit/package/dependency-version-test.js | tests/unit/package/dependency-version-test.js | 'use strict';
var assert = require('../../helpers/assert');
var semver = require('semver');
function assertVersionLock(_deps) {
var deps = _deps || {};
Object.keys(deps).forEach(function(name) {
if (name !== 'ember-cli' &&
semver.valid(deps[name]) &&
semver.gtr('1.0.0', deps[name])) {
// only valid if the version is fixed
assert(semver.valid(deps[name]), '"' + name + '" has a valid version');
}
});
}
describe('dependencies', function() {
var pkg;
describe('in package.json', function() {
before(function() {
pkg = require('../../../package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
describe('in blueprints/app/files/package.json', function() {
before(function() {
pkg = require('../../../blueprints/app/files/package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
});
| 'use strict';
var assert = require('../../helpers/assert');
var semver = require('semver');
function assertVersionLock(deps) {
deps = deps || {};
Object.keys(deps).forEach(function(name) {
if (name !== 'ember-cli' && semver.gtr('1.0.0', deps[name])) {
// only valid if the version is fixed
assert(semver.valid(deps[name]), '"' + name + '" has a valid version');
}
});
}
describe('dependencies', function() {
var pkg;
describe('in package.json', function() {
before(function() {
pkg = require('../../../package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
describe('in blueprints/app/files/package.json', function() {
before(function() {
pkg = require('../../../blueprints/app/files/package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
});
| JavaScript | 0.000001 |
420ca6d21c2072a0f10e05a1cf5d2fc8e961e4c6 | Create login functionality in Ally framework | plugins/gui-core/gui-resources/scripts/js/views/auth.js | plugins/gui-core/gui-resources/scripts/js/views/auth.js | define
([
'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
var AuthLogin = function(username, password, logintoken){
=======
var AuthDetails = function(username){
var authDetails = new $.rest('Superdesk/User');
authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
var user = users.UserList[0];
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.Name);
localStorage.setItem('superdesk.login.email', user.EMail);
});
return $(authDetails);
},
AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
authLogin = new $.rest('Authentication');
authLogin.resetData().insert({
UserName: username,
LoginToken: logintoken,
HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
}).done(function(user){
localStorage.setItem('superdesk.login.session', user.Session);
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
});
return $(authLogin);
},
AuthToken = function(username, password) {
var authToken = new $.rest('Authentication');
authToken.resetData().select({ userName: username }).done(
function(data){
authLogin = AuthLogin(username, password, data.Token);
authLogin.on('failed', function(){
$(authToken).trigger('failed', 'authToken');
}).on('success', function(){
$(authToken).trigger('success');
});
}
);
return $(authToken);
},
AuthApp =
{
success: $.noop,
require: function()
{
if(this.showed) return;
var self = this; // rest
self.showed = true;
$.tmpl('auth', null, function(e, o)
{
var dialog = $(o).eq(0).dialog
({
draggable: false,
resizable: false,
modal: true,
width: "40.1709%",
buttons:
[
{ text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
{ text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
]
}),
form = dialog.find('form');
form.off('submit.superdesk')//
.on('submit.superdesk', function(event)
{
var username = $(this).find('#username'), password=$(this).find('#password');
AuthToken(username.val(), password.val()).on('failed',function(evt, type){
username.val('');
password.val('')
}).on('success', function(){
AuthApp.success && AuthApp.success.apply();
$(dialog).dialog('close');
self.showed = false;
});
event.preventDefault();
});
});
}
};
return AuthApp;
}); | define
([
'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
var AuthLogin = function(username, password, logintoken){
=======
var AuthDetails = function(username){
var authDetails = new $.rest('Superdesk/User');
authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
var user = users.UserList[0];
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.Name);
localStorage.setItem('superdesk.login.email', user.EMail);
});
return $(authDetails);
},
AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
authLogin = new $.rest('Authentication');
authLogin.resetData().insert({
UserName: username,
LoginToken: logintoken,
HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
}).done(function(user){
localStorage.setItem('superdesk.login.session', user.Session);
<<<<<<< HEAD
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
=======
//localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
/* authDetails = AuthDetails(username);
$(authDetails).on('failed', function(){
$(authLogin).trigger('failed', 'authDetails');
});
*/
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
});
return $(authLogin);
},
AuthToken = function(username, password) {
var authToken = new $.rest('Authentication');
authToken.resetData().select({ userName: username }).done(
function(data){
authLogin = AuthLogin(username, password, data.Token);
authLogin.on('failed', function(){
$(authToken).trigger('failed', 'authToken');
}).on('success', function(){
$(authToken).trigger('success');
});
}
);
return $(authToken);
},
AuthApp =
{
success: $.noop,
require: function()
{
if(this.showed) return;
var self = this; // rest
self.showed = true;
$.tmpl('auth', null, function(e, o)
{
var dialog = $(o).eq(0).dialog
({
draggable: false,
resizable: false,
modal: true,
width: "40.1709%",
buttons:
[
{ text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
{ text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
]
}),
form = dialog.find('form');
form.off('submit.superdesk')//
.on('submit.superdesk', function(event)
{
var username = $(this).find('#username'), password=$(this).find('#password');
AuthToken(username.val(), password.val()).on('failed',function(evt, type){
username.val('');
password.val('')
}).on('success', function(){
AuthApp.success && AuthApp.success.apply();
$(dialog).dialog('close');
self.showed = false;
});
event.preventDefault();
});
});
}
};
return AuthApp;
}); | JavaScript | 0 |
b8f3d96e5a9eff76834b4cb95238218eb42c6a4c | use explicit cookie name for cookieconsent | sirepo/package_data/static/js/sirepo-common.js | sirepo/package_data/static/js/sirepo-common.js | 'use strict';
// Common code shared between the landing page app and the various sirepo apps
window.cookieconsent.initialise({
//TODO(pjm): set cookie domain?
content: {
//TODO(pjm): update with links to terms of service when available
message: 'This site uses cookies to deliver our services. By using our site, you acknowledge that you accept our use of cookies.',
dismiss: 'I accept',
link: null,
},
cookie: {
name: 'sr_cookieconsent',
},
palette: {
popup: {
background: "#000",
},
button: {
background: "#286090",
},
},
});
| 'use strict';
// Common code shared between the landing page app and the various sirepo apps
window.cookieconsent.initialise({
//TODO(pjm): set cookie domain?
content: {
//TODO(pjm): update with links to terms of service when available
message: 'This site uses cookies to deliver our services. By using our site, you acknowledge that you accept our use of cookies.',
dismiss: 'I accept',
link: null,
},
palette: {
popup: {
background: "#000",
},
button: {
background: "#286090",
},
},
});
| JavaScript | 0.000001 |
c9340fce163c1d4c07dd5ce9d066818768bb76f3 | Fix style violation. | frontend/js/components/atoms/Card.js | frontend/js/components/atoms/Card.js | import React, { PropTypes, Component } from 'react';
import Icon from './../atoms/Icon';
class Card extends Component {
constructor(props) {
super(props);
}
render() {
return (
<section
className={`${this.props.className} card`}
onClick={this.props.onClick}>
{
(!!this.props.title || !!this.props.onClose) &&
<div className="card-title">
<h2>{this.props.title}</h2>
{this.props.onClose &&
<Icon onClick={this.props.onClose}>close</Icon>
}
</div>
}
<div className="card-body">
{ this.props.children }
</div>
<div className="card-actions">
{this.props.actions}
</div>
</section>
);
}
}
Card.propTypes = {
style: PropTypes.object,
children: PropTypes.any,
className: PropTypes.string,
onClick: PropTypes.func,
title: PropTypes.string,
actions: PropTypes.any,
onClose: PropTypes.func
};
export default Card;
| import React, { PropTypes, Component } from 'react';
class Card extends Component {
constructor(props) {
super(props);
}
render() {
return (
<section
className={`${this.props.className} card`}
onClick={this.props.onClick}>
{
(!!this.props.title || !!this.props.onClose) &&
<div className="card-title">
<h2>{this.props.title}</h2>
{this.props.onClose &&
<Icon onClick={this.props.onClose}>close</Icon>
}
</div>
}
<div className="card-body">
{ this.props.children }
</div>
<div className="card-actions">
{this.props.actions}
</div>
</section>
);
}
}
Card.propTypes = {
style: PropTypes.object,
children: PropTypes.any,
className: PropTypes.string,
onClick: PropTypes.func,
title: PropTypes.string,
onClose: PropTypes.func
};
export default Card;
| JavaScript | 0 |
07b88fb9792c25d4c70651488c14f5a6249e1331 | Remove unnecessary Em.run wrapping | test/app/app_test.js | test/app/app_test.js | module("Application", {
setup: function () {
MY_APP.reset();
}
});
test("Parameters", function () {
ok(MY_APP.rootElement === "#MY_APP", "rootElement");
ok(Ember.$.support.cors, "Cross-origin resource sharing support");
});
| module("Application", {
setup: function () {
Ember.run(function () {MY_APP.reset();});
}
});
test("Parameters", function () {
ok(MY_APP.rootElement === "#MY_APP", "rootElement");
ok(Ember.$.support.cors, "Cross-origin resource sharing support");
});
| JavaScript | 0.000008 |
01ae2f9b8f48b29b8478138d2af15acc2d0cfa9e | Update Cell.js | src/entity/Cell.js | src/entity/Cell.js | function Cell(gameServer, owner, position, size) {
this.gameServer = gameServer;
this.owner = owner; // playerTracker that owns this cell
this.tickOfBirth = 0;
this.color = { r: 0, g: 0, b: 0 };
this.position = { x: 0, y: 0 };
this._sizeSquared = 0;
this._size = 0;
this._mass = 0;
this.cellType = -1; // 0 = Player Cell, 1 = Food, 2 = Virus, 3 = Ejected Mass
this.isSpiked = false; // If true, then this cell has spikes around it
this.isAgitated = false;// If true, then this cell has waves on it's outline
this.killedBy = null; // Cell that ate this cell
this.isMoving = false; // Indicate that cell is in boosted mode
this.boostDistance = 0;
this.boostDirection = { x: 1, y: 0, angle: Math.PI / 2 };
if (this.gameServer) {
this.tickOfBirth = this.gameServer.tickCounter;
this.nodeId = this.gameServer.lastNodeId++ >> 0;
if (size) this.setSize(size);
if (position) this.position = position;
}
}
module.exports = Cell;
// Fields not defined by the constructor are considered private and need a getter/setter to access from a different class
Cell.prototype.setColor = function (color) {
this.color.r = color.r;
this.color.g = color.g;
this.color.b = color.b;
};
Cell.prototype.setSize = function (size) {
this._size = size;
this._sizeSquared = size * size;
this._mass = this._sizeSquared / 100;
if (this.owner)
this.owner.isMassChanged = true;
};
// by default cell cannot eat anyone
Cell.prototype.canEat = function (cell) {
return false;
};
// Returns cell age in ticks for specified game tick
Cell.prototype.getAge = function () {
if (this.tickOfBirth == null) return 0; // age cant be less than 0
return Math.max(0, this.gameServer.tickCounter - this.tickOfBirth);
};
// Called to eat prey cell
Cell.prototype.onEat = function (prey) {
if (!this.gameServer.config.playerBotGrow) {
if (this._mass >= 625 && prey._mass <= 17 && prey.cellType == 0)
prey._sizeSquared = 0; // Can't grow from players under 17 mass
}
this.setSize(Math.sqrt(this._sizeSquared + prey._sizeSquared));
};
Cell.prototype.setBoost = function (distance, angle) {
this.boostDistance = distance;
this.boostDirection = {
x: Math.sin(angle),
y: Math.cos(angle),
angle: angle
};
this.isMoving = true;
if (!this.owner) {
var index = this.gameServer.movingNodes.indexOf(this);
if (index < 0)
this.gameServer.movingNodes.push(this);
}
};
Cell.prototype.checkBorder = function (border) {
this.position.x = Math.max(this.position.x, border.minx + this._size / 2);
this.position.y = Math.max(this.position.y, border.miny + this._size / 2);
this.position.x = Math.min(this.position.x, border.maxx - this._size / 2);
this.position.y = Math.min(this.position.y, border.maxy - this._size / 2);
};
Cell.prototype.onEaten = function (hunter) { };
Cell.prototype.onAdd = function (gameServer) { };
Cell.prototype.onRemove = function (gameServer) { };
| function Cell(gameServer, owner, position, size) {
this.gameServer = gameServer;
this.owner = owner; // playerTracker that owns this cell
this.tickOfBirth = 0;
this.color = { r: 0, g: 0, b: 0 };
this.position = { x: 0, y: 0 };
this._sizeSquared = 0;
this._size = 0;
this._mass = 0;
this.cellType = -1; // 0 = Player Cell, 1 = Food, 2 = Virus, 3 = Ejected Mass
this.isSpiked = false; // If true, then this cell has spikes around it
this.isAgitated = false;// If true, then this cell has waves on it's outline
this.killedBy = null; // Cell that ate this cell
this.isMoving = false; // Indicate that cell is in boosted mode
this.boostDistance = 0;
this.boostDirection = { x: 1, y: 0, angle: Math.PI / 2 };
if (this.gameServer) {
this.tickOfBirth = this.gameServer.tickCounter;
this.nodeId = this.getNextNodeId();
if (size) this.setSize(size);
if (position) this.position = position;
}
}
module.exports = Cell;
// Fields not defined by the constructor are considered private and need a getter/setter to access from a different class
Cell.prototype.getNextNodeId = function () {
if (this.gameServer.lastNodeId > 2147483647) {
this.gameServer.lastNodeId = 1;
}
return this.gameServer.lastNodeId++ >> 0;
};
Cell.prototype.setColor = function (color) {
this.color.r = color.r;
this.color.g = color.g;
this.color.b = color.b;
};
Cell.prototype.setSize = function (size) {
this._size = size;
this._sizeSquared = size * size;
this._mass = this._sizeSquared / 100;
if (this.owner)
this.owner.isMassChanged = true;
};
// by default cell cannot eat anyone
Cell.prototype.canEat = function (cell) {
return false;
};
// Returns cell age in ticks for specified game tick
Cell.prototype.getAge = function () {
if (this.tickOfBirth == null) return 0; // age cant be less than 0
return Math.max(0, this.gameServer.tickCounter - this.tickOfBirth);
};
// Called to eat prey cell
Cell.prototype.onEat = function (prey) {
if (!this.gameServer.config.playerBotGrow) {
if (this._mass >= 625 && prey._mass <= 17 && prey.cellType != 3)
prey._sizeSquared = 0; // Can't grow from cells under 17 mass
}
this.setSize(Math.sqrt(this._sizeSquared + prey._sizeSquared));
};
Cell.prototype.setBoost = function (distance, angle) {
this.boostDistance = distance;
this.boostDirection = {
x: Math.sin(angle),
y: Math.cos(angle),
angle: angle
};
this.isMoving = true;
if (!this.owner) {
var index = this.gameServer.movingNodes.indexOf(this);
if (index < 0)
this.gameServer.movingNodes.push(this);
}
};
Cell.prototype.checkBorder = function (border) {
this.position.x = Math.max(this.position.x, border.minx + this._size / 2);
this.position.y = Math.max(this.position.y, border.miny + this._size / 2);
this.position.x = Math.min(this.position.x, border.maxx - this._size / 2);
this.position.y = Math.min(this.position.y, border.maxy - this._size / 2);
};
Cell.prototype.onEaten = function (hunter) { };
Cell.prototype.onAdd = function (gameServer) { };
Cell.prototype.onRemove = function (gameServer) { };
| JavaScript | 0 |
9211bb282e64d552267a601f29d1d1447a5fd7e2 | delete toBeFalsy, add toBeNull and toBeCloseTo methods | src/expectation.js | src/expectation.js | define(['is-equal', 'get-type', 'condition'],
function (isEqual, getType, condition) {
"use strict";
function Expectation (context, thing, opts) {
opts = opts || {};
var not = opts.not || false,
passed = null,
message = function () {
var n,
text = [passed ? "PASSED: " : "FAILED: ",
"expected ", getType(thing), ' ', condition(thing).text, ' '];
for (n = 0; n < arguments.length; n++) {
text.push(arguments[n]);
}
return context.out(text.join(''), {
"color": "#000",
"background": passed ? 'rgba(44, 226, 44, 0.4)' : 'rgba(226, 44, 44, 0.4)',
"test": true
});
};
this.toEqual = function (otherThing) {
var result = isEqual(thing, otherThing);
passed = not ? !result : result;
message(not ? 'not ' : '', 'to equal ', getType(otherThing), ' ', condition(otherThing).text);
if (getType(thing) === getType(otherThing)
&& typeof thing === "object"
&& !passed) {
context.diff(thing, otherThing);
}
};
this.toBeCloseTo = function (num, margin) {
passed = thing < num + margin || thing > num - margin;
passed = not ? !passed : passed;
message(not ? 'not ' : '', 'to be close to ', num, ' by a margin of ', margin);
};
this.toBeTruthy = function () {
passed = not ? !thing : !!thing;
message(not ? 'not ' : '', 'to be truthy');
};
this.toBeDefined = function () {
passed = not ? thing === void 0 : thing !== void 0;
message(not ? 'not ' : '', 'to be defined');
};
this.toBeNull = function () {
passed = not ? thing !== null : thing === null;
message(not ? 'not ' : '', 'to be null');
};
return this;
}
return Expectation;
});
| define(['is-equal', 'get-type', 'condition'],
function (isEqual, getType, condition) {
"use strict";
function Expectation (context, thing, opts) {
opts = opts || {};
var not = opts.not || false,
passed = null,
message = function () {
var n,
text = [passed ? "PASSED: " : "FAILED: ",
"expected ", getType(thing), ' ', condition(thing).text, ' '];
for (n = 0; n < arguments.length; n++) {
text.push(arguments[n]);
}
return context.out(text.join(''), {
"color": "#000",
"background": passed ? 'rgba(44, 226, 44, 0.4)' : 'rgba(226, 44, 44, 0.4)',
"test": true
});
};
this.toEqual = function (otherThing) {
var result = isEqual(thing, otherThing);
passed = not ? !result : result;
message(not ? "not " : "", 'to equal ', getType(otherThing), ' ', condition(otherThing).text);
if (getType(thing) === getType(otherThing)
&& typeof thing === "object"
&& !passed) {
context.diff(thing, otherThing);
}
};
this.toBeTruthy = function () {
passed = not ? !thing : !!thing;
message(not ? "not " : "", 'to be truthy');
};
this.toBeFalsy = function () {
passed = not ? !!thing : !thing;
message(not ? "not " : "", 'to be falsy');
};
this.toBeDefined = function () {
passed = not ? thing === void 0 : thing !== void 0;
message(not ? "not " : "", 'to be defined');
};
return this;
}
return Expectation;
});
| JavaScript | 0 |
18a2b4ee7bc9398c9208470c33406c4f584e1e76 | Add small delay on experiment return log | src/experiments.js | src/experiments.js | /* @flow */
import { info, track, immediateFlush } from 'beaver-logger/client';
import { FPTI } from './config';
import { getReturnToken, getSessionState, getDomainSetting, eventEmitter } from './lib';
export let onAuthorizeListener = eventEmitter();
function log(experiment : string, treatment : string, token : ?string, state : string) {
getSessionState(session => {
let event = `experiment_group_${ experiment }_${ treatment }_${ state }`;
let loggedEvents = session.loggedExperimentEvents = session.loggedExperimentEvents || [];
let duplicate = loggedEvents.indexOf(event) !== -1;
if (duplicate) {
info(`duplicate_${ event }`);
} else {
info(event);
loggedEvents.push(event);
track({
[ FPTI.KEY.STATE ]: FPTI.STATE.CHECKOUT,
[ FPTI.KEY.TRANSITION ]: state,
[ FPTI.KEY.EXPERIMENT_NAME ]: experiment,
[ FPTI.KEY.TREATMENT_NAME ]: treatment,
[ FPTI.KEY.TOKEN ]: token,
[ FPTI.KEY.CONTEXT_ID ]: token,
[ FPTI.KEY.CONTEXT_TYPE ]: token ? FPTI.CONTEXT_TYPE.EC_TOKEN : FPTI.CONTEXT_TYPE.UID
});
immediateFlush();
}
});
}
export function logExperimentTreatment(experiment : string, treatment : string, token : ?string) {
let exp;
let state;
if (experiment === 'walmart_paypal_incontext' || experiment === 'walmart_paypal_incontext_redirect') {
exp = 'walmart_paypal_incontext';
state = 'redirect';
} else if (experiment === 'walmart_paypal_incontext_click') {
exp = 'walmart_paypal_incontext';
state = 'click';
} else {
exp = experiment;
state = 'start';
}
getSessionState(session => {
session.externalExperiment = exp;
session.externalExperimentTreatment = treatment;
if (token) {
session.externalExperimentToken = token;
}
});
log(exp, treatment, token, state);
}
function logReturn(token : string) {
let {
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
} = getSessionState(session => session);
if (externalExperiment && externalExperimentTreatment && externalExperimentToken === token) {
log(externalExperiment, externalExperimentTreatment, token, `complete`);
} else {
info(`experiment_mismatch`, {
token,
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
});
}
}
if (getDomainSetting('log_authorize')) {
onAuthorizeListener.once(({ paymentToken }) => {
setTimeout(() => {
logReturn(paymentToken);
}, 1);
});
let returnToken = getReturnToken();
if (returnToken) {
setTimeout(() => {
if (returnToken) {
logReturn(returnToken);
}
}, 1);
}
}
| /* @flow */
import { info, track, immediateFlush } from 'beaver-logger/client';
import { FPTI } from './config';
import { getReturnToken, getSessionState, getDomainSetting, eventEmitter } from './lib';
export let onAuthorizeListener = eventEmitter();
function log(experiment : string, treatment : string, token : ?string, state : string) {
getSessionState(session => {
let event = `experiment_group_${ experiment }_${ treatment }_${ state }`;
let loggedEvents = session.loggedExperimentEvents = session.loggedExperimentEvents || [];
let duplicate = loggedEvents.indexOf(event) !== -1;
if (duplicate) {
info(`duplicate_${ event }`);
} else {
info(event);
loggedEvents.push(event);
track({
[ FPTI.KEY.STATE ]: FPTI.STATE.CHECKOUT,
[ FPTI.KEY.TRANSITION ]: state,
[ FPTI.KEY.EXPERIMENT_NAME ]: experiment,
[ FPTI.KEY.TREATMENT_NAME ]: treatment,
[ FPTI.KEY.TOKEN ]: token,
[ FPTI.KEY.CONTEXT_ID ]: token,
[ FPTI.KEY.CONTEXT_TYPE ]: token ? FPTI.CONTEXT_TYPE.EC_TOKEN : FPTI.CONTEXT_TYPE.UID
});
immediateFlush();
}
});
}
export function logExperimentTreatment(experiment : string, treatment : string, token : ?string) {
let exp;
let state;
if (experiment === 'walmart_paypal_incontext' || experiment === 'walmart_paypal_incontext_redirect') {
exp = 'walmart_paypal_incontext';
state = 'redirect';
} else if (experiment === 'walmart_paypal_incontext_click') {
exp = 'walmart_paypal_incontext';
state = 'click';
} else {
exp = experiment;
state = 'start';
}
getSessionState(session => {
session.externalExperiment = exp;
session.externalExperimentTreatment = treatment;
if (token) {
session.externalExperimentToken = token;
}
});
log(exp, treatment, token, state);
}
function logReturn(token : string) {
let {
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
} = getSessionState(session => session);
if (externalExperiment && externalExperimentTreatment && externalExperimentToken === token) {
log(externalExperiment, externalExperimentTreatment, token, `complete`);
} else {
info(`experiment_mismatch`, {
token,
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
});
}
}
if (getDomainSetting('log_authorize')) {
onAuthorizeListener.once(({ paymentToken }) => {
logReturn(paymentToken);
});
let returnToken = getReturnToken();
if (returnToken) {
logReturn(returnToken);
}
}
| JavaScript | 0.000001 |
fcab90f27c6588b3c3d6c6b1eb4fa1589e499974 | test cases for vanilla usage of stringify; #1 | test/comment-json.js | test/comment-json.js | 'use strict';
var expect = require('chai').expect;
var json = require('../');
describe("vanilla usage of `json.stringify()`", function(){
var subjects = [
'abc',
1,
true,
false,
null,
undefined,
[],
{},
['abc', 1, {a: 1, b: undefined}],
[undefined, 1, 'abc'],
{
a: undefined,
b: false,
c: [1, '1']
}
];
var replacers = [
null,
function (key, value) {
if (typeof value === 'string') {
return undefined;
}
return value;
}
];
var spaces = [
1,
2,
' ',
'1'
];
subjects.forEach(function (subject) {
replacers.forEach(function (replacer) {
spaces.forEach(function (space) {
var desc = [subject, replacer, space].map(function (s) {
return JSON.stringify(s);
}).join(', ');
it(desc, function(){
expect(json.stringify(subject, replacer, space)).to.equal(JSON.stringify(subject, replacer, space));
});
});
});
});
}); | 'use strict';
var expect = require('chai').expect;
var comment_json = require('../'); | JavaScript | 0.000015 |
22ca2419a125125101b1966b6c9c6d96fbec760f | Update ArmQuadrapus.js | game/js/gameentities/ArmQuadrapus.js | game/js/gameentities/ArmQuadrapus.js | "use strict";
var QuadrapusArm = function(world, Bullet, options, audio) {
this.world = world;
this.color = options.color || "#800080";
this.Bullet = Bullet;
this.audio = audio;
this.spriteName = options.spriteName || null;
this.type = "boss";
this.active = true;
this.width = options.width;
this.height = 13;
this.x = options.x;
this.y = options.y;
this.side = options.side;
this.section = options.section;
this.lives = 7;
this.hitboxMetrics = {
x: 0,
y: 0,
width: 90,
height: 13
};
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.update = function() {
this.updateHitbox();
};
QuadrapusArm.prototype.shotArc = function(start, end, step) {
if (start < end) {
for (var i = start; i < end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 2,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
} else {
for (var i = start; i > end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 2,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
}
};
QuadrapusArm.prototype.draw = function() {
if (this.spriteName === null) {
this.world.drawRectangle(this.color, this.x, this.y, this.width, this.height);
} else {
this.world.drawSprite(this.spriteName, this.x, this.y, this.width, this.height);
}
};
QuadrapusArm.prototype.updateHitbox = function() {
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.explode = function(source) {
if (source === "bullet") {
this.lives--;
}
if (this.lives < 1) {
this.active = false;
}
};
| "use strict";
var QuadrapusArm = function(world, Bullet, options, audio) {
this.world = world;
this.color = options.color || "#800080";
this.Bullet = Bullet;
this.audio = audio;
this.spriteName = options.spriteName || null;
this.type = "boss";
this.active = true;
this.width = options.width;
this.height = 13;
this.x = options.x;
this.y = options.y;
this.side = options.side;
this.section = options.section;
this.lives = 7;
this.hitboxMetrics = {
x: 0,
y: 0,
width: 90,
height: 13
};
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.update = function() {
this.updateHitbox();
};
QuadrapusArm.prototype.shotArc = function(start, end, step) {
if (start < end) {
for (var i = start; i < end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 5,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
} else {
for (var i = start; i > end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 5,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
}
};
QuadrapusArm.prototype.draw = function() {
if (this.spriteName === null) {
this.world.drawRectangle(this.color, this.x, this.y, this.width, this.height);
} else {
this.world.drawSprite(this.spriteName, this.x, this.y, this.width, this.height);
}
};
QuadrapusArm.prototype.updateHitbox = function() {
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.explode = function(source) {
if (source === "bullet") {
this.lives--;
}
if (this.lives < 1) {
this.active = false;
}
};
| JavaScript | 0 |
378a32f905aa64f9ecf2d588c2aabd078f25cbd4 | Fix charts not showing in printed compendium | src/main/web/js/app/print-compendium.js | src/main/web/js/app/print-compendium.js | $(function () {
if ($('body').hasClass('compendium_landing_page')) {
$('.js-print-chapters').click(function (e) {
e.preventDefault();
addLoadingOverlay();
var $chapters = $('.chapter'),
chapterLength = $chapters.length;
$chapters.each(function (index) {
// Synchronously adds div with id to get around Ajax working asynchronously
$('main').append("<div id='compendium-print" + index + "'></div>");
var url = $(this).attr('href');
// Set what content from each page we want to retrieve for printing
var childIntro = ('.page-intro');
var childContent = ('.page-content');
// Get chapter content
$.get(url, function (response) {
// Remove noscript tags around images, they break the charts when requested
var html = response.replace(/<\/noscript>/g, '').replace(/<noscript>/g, '');
// Add in print page breaks before each chapter and add to compendium landing page
var $response = $(html);
$response.find(childIntro).addClass('print--break-before').appendTo('#compendium-print' + index);
$response.find(childContent).appendTo('#compendium-print' + index).imagesLoaded().then(function() {
chaptersComplete(index);
});
});
});
// Tally number of chapters complete and print window when done
function chaptersComplete(index) {
if (index+1 == chapterLength) {
window.print();
location.reload();
}
}
});
// Function to wait until all images are loaded in the DOM - stackoverflow.com/questions/4774746/jquery-ajax-wait-until-all-images-are-loaded
$.fn.imagesLoaded = function () {
// get all the images (excluding those with no src attribute)
var $imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred().resolve().promise();}
// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.onerror = function(){dfd.resolve();}
img.src = this.src;
});
// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($,dfds);
};
}
}); | $(function() {
if ($('body').hasClass('compendium_landing_page')) {
$('.js-print-chapters').click(function (e) {
addLoadingOverlay();
$('.chapter').each(function (index) {
// Synchronously adds div with id to get around Ajax working asynchronously
$('main').append("<div id='compendium-print" + index + "'></div>");
var url = $(this).attr('href');
// Set what content from each page we want to retrieve for printing
var childIntro = ('.page-intro');
var childContent = ('.page-content');
$.get(url, function (data) {
$(data).find(childIntro).addClass('print--break-before').appendTo('#compendium-print' + index);
$(data).find(childContent).appendTo('#compendium-print' + index);
});
e.preventDefault();
});
$(document).ajaxStop(function () {
window.print();
location.reload();
});
});
}
});
| JavaScript | 0 |
30984b994111903bb7f41557e9a2eeed58ccd0d2 | remove some useless code. | src/client/containers/notes/list.js | src/client/containers/notes/list.js | import R from 'ramda'
import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import {visibleNotesSelector} from '../../selectors/notes';
import {notesActions} from '../../actions/notes';
import {personsActions} from '../../actions/persons';
import {companiesActions} from '../../actions/companies';
import {missionsActions} from '../../actions/missions';
import {Content} from '../../components/layout';
import {AvatarView, Sort, FilterPreferred, Filter, Refresh, NewLabel, UpdatedLabel} from '../../components/widgets';
import {Header, HeaderLeft, HeaderRight, Title, TitleIcon} from '../../components/widgets';
import {AddButton} from '../../components/notes/widgets';
import {ItemNote} from '../notes';
import routes from '../../routes';
import Masonry from 'react-masonry-component';
const sortMenu = [
{key: 'createdAt', label: 'Sort by creation date'},
{key: 'updatedAt', label: 'Sort by updated date'},
];
class NotesList extends Component {
state = {}
componentWillMount = () => {
this.props.dispatch(notesActions.load())
this.props.dispatch(personsActions.load())
this.props.dispatch(companiesActions.load())
this.props.dispatch(missionsActions.load())
}
handleSort = (mode) => {
this.props.dispatch(notesActions.sort(mode))
}
handleRefresh = () => {
this.props.dispatch(notesActions.load({forceReload: true}))
}
handleSearchFilter = (filter) => {
this.props.dispatch(notesActions.filter(filter))
}
handleResetFilter = () => this.handleSearchFilter('')
render() {
const {notes, persons, companies, missions, filter, sortCond} = this.props
if (!notes || !persons || !companies || !missions) return <div />
const listNotes = (notes, persons, companies, missions) => {
return (
notes.map((note) => {
return <ItemNote
key={note.get('_id')}
note={note}
persons={persons}
companies={companies}
missions={missions} />
}).toSetSeq()
)
}
const options = {
transitionDuration: 0,
gutter: 10,
}
return (
<Content>
<Header>
<HeaderLeft>
<TitleIcon icon={routes.notes.list.iconName} />
<Title title='Notes' />
</HeaderLeft>
<HeaderRight>
<Filter filter={filter} onReset={this.handleResetFilter} onChange={this.handleSearchFilter}/>
<Sort sortMenu={sortMenu} sortCond={sortCond} onClick={this.handleSort}/>
<Refresh onClick={this.handleRefresh} />
</HeaderRight>
</Header>
<Masonry options={options}>
{listNotes(notes, persons, companies, missions)}
</Masonry>
<AddButton title="Add a note" />
</Content>
)
}
}
export default connect(visibleNotesSelector)(NotesList)
| import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import {visibleNotesSelector} from '../../selectors/notes';
import {notesActions} from '../../actions/notes';
import {personsActions} from '../../actions/persons';
import {companiesActions} from '../../actions/companies';
import {missionsActions} from '../../actions/missions';
import {Content} from '../../components/layout';
import {AvatarView, Sort, FilterPreferred, Filter, Refresh, NewLabel, UpdatedLabel} from '../../components/widgets';
import {Header, HeaderLeft, HeaderRight, Title, TitleIcon} from '../../components/widgets';
import {AddButton} from '../../components/notes/widgets';
import {ItemNote} from '../notes';
import routes from '../../routes';
import Masonry from 'react-masonry-component';
const sortMenu = [
{key: 'createdAt', label: 'Sort by creation date'},
{key: 'updatedAt', label: 'Sort by updated date'},
];
class NotesList extends Component {
state = {}
componentWillMount = () => {
this.props.dispatch(notesActions.load())
this.props.dispatch(personsActions.load())
this.props.dispatch(companiesActions.load())
this.props.dispatch(missionsActions.load())
}
handleSort = (mode) => {
this.props.dispatch(notesActions.sort(mode))
}
handleResetFilter = () => {
this.props.dispatch(notesActions.filter(''))
}
handleRefresh = () => {
this.props.dispatch(notesActions.load({forceReload: true}))
}
handleSearchFilter = (filter) => {
this.props.dispatch(notesActions.filter(filter))
// Masonry hack for reloading layout on search
this.masonry.layout()
}
render() {
const {notes, persons, companies, missions, filter, sortCond} = this.props
if (!notes || !persons || !companies || !missions) return <div />
const listNotes = (notes, persons, companies, missions) => {
return (
notes.map((note) => {
return <ItemNote
key={note.get('_id')}
note={note}
persons={persons}
companies={companies}
missions={missions} />
}).toSetSeq()
)
}
const options = {
transitionDuration: 0,
gutter: 10,
}
return (
<Content>
<Header>
<HeaderLeft>
<TitleIcon icon={routes.notes.list.iconName} />
<Title title='Notes' />
</HeaderLeft>
<HeaderRight>
<Filter filter={filter} onReset={this.handleResetFilter} onChange={this.handleSearchFilter}/>
<Sort sortMenu={sortMenu} sortCond={sortCond} onClick={this.handleSort}/>
<Refresh onClick={this.handleRefresh} />
</HeaderRight>
</Header>
<Masonry
ref={function(c) {if (c != null) this.masonry = c.masonry;}.bind(this)}
options={options}>
{listNotes(notes, persons, companies, missions)}
</Masonry>
<AddButton title="Add a note" />
</Content>
)
}
}
export default connect(visibleNotesSelector)(NotesList)
| JavaScript | 0.000011 |
c52eafcd58cc7d5126ead2dddb835964aa505c8d | add live reloading to customers | src/components/HomePage/HomePage.js | src/components/HomePage/HomePage.js | import React, { PropTypes, Component } from 'react';
import styles from './HomePage.scss';
import withStyles from '../../decorators/withStyles';
import IdleScreen from '../IdleScreen';
import Passenger from '../Passenger';
import Firebase from 'firebase';
import $ from 'jquery';
@withStyles(styles)
class HomePage extends Component {
static propTypes = {
};
constructor(props){
super(props);
var self = this;
self.state = {
customers: {},
passenger: null
}
var newItems = false;
self.firebaseCustomerRef = new Firebase('https://jagertrain.firebaseio.com/customers');
self.firebaseCustomerRef.once("value", (dataSnapshot)=> {
var customers = dataSnapshot.val();
dataSnapshot.forEach(function(childSnapshot) {
var passenger = childSnapshot.val();
var img = new Image();
img.src = '/passengers/' + passenger.forename.toLowerCase() + '_' + passenger.surname.toLowerCase() + '.png';
});
self.setState({
customers: customers
});
});
self.firebaseCustomerRef.on("child_added", (customer)=> {
if (self.state.customers[customer.key()]) return null;
let customerVal = customer.val();
customerVal.key = customer.key;
self.state.customers[customerVal.key] = customerVal;
self.setState({
customers: self.state.customers
});
});
self.firebaseCustomerRef.on("child_changed", (customer)=> {
if (!self.state.customers[customer.key()]) return null;
let customerVal = customer.val();
customerVal.key = customer.key;
self.state.customers[customerVal.key] = customerVal;
self.setState({
customers: self.state.customers
});
});
self.firebaseTransactionsRef = new Firebase('https://jagertrain.firebaseio.com/transactions');
self.firebaseTransactionsRef.on("child_added", (transaction)=> {
if (!newItems) return;
var passenger = this.state.customers[transaction.val().customer];
if (typeof passenger === "undefined") {
console.log('id not recognised');
return;
}
let audio = new Audio(`/sounds/clip_${Math.floor((Math.random() * 7) + 1)}.ogg`);
audio.play();
var $IdleScreem = $('.IdleScreen').addClass("spin-out");
passenger.imageUrl = '/passengers/' + passenger.forename.toLowerCase() + '-' + passenger.surname.toLowerCase() + '.png';
setTimeout(function(){
self.setState({
passenger: passenger
});
setTimeout(function(){
var $Passenger = $('.Passenger');
$Passenger.fadeOut(1000, function() {
self.setState({
passenger: null
});
});
}, 5000);
}, 2000);
});
this.firebaseTransactionsRef.once('value', (dataSnapshot) => {
newItems = true;
});
self.firebaseSoundPlaysRef = new Firebase('https://jagertrain.firebaseio.com/soundplays');
self.firebaseSoundPlaysRef.on('child_changed', (soundPlay) => {
var id = soundPlay.val();
let audio = new Audio(`/sounds/clip_${id}.ogg`);
audio.play();
});
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
render() {
const title = 'Riskdisk Jagertrain 2015';
this.context.onSetTitle(title);
if (this.state.passenger) {
return (
<div className="HomePage">
<div className="HomePage-container">
<Passenger passenger={this.state.passenger} />
</div>
</div>
);
}
else {
return (
<div className="IdleScreen-wrapper">
<IdleScreen />
<h2>All Aboard!!! #RDJT</h2>
</div>
)
}
}
}
export default HomePage;
| import React, { PropTypes, Component } from 'react';
import styles from './HomePage.scss';
import withStyles from '../../decorators/withStyles';
import IdleScreen from '../IdleScreen';
import Passenger from '../Passenger';
import Firebase from 'firebase';
import $ from 'jquery';
@withStyles(styles)
class HomePage extends Component {
static propTypes = {
};
constructor(props){
super(props);
var self = this;
self.state = {
customers: {},
passenger: null
}
var newItems = false;
self.firebaseCustomerRef = new Firebase('https://jagertrain.firebaseio.com/customers');
self.firebaseCustomerRef.once("value", (dataSnapshot)=> {
var customers = dataSnapshot.val();
dataSnapshot.forEach(function(childSnapshot) {
var passenger = childSnapshot.val();
var img = new Image();
img.src = '/passengers/' + passenger.forename.toLowerCase() + '_' + passenger.surname.toLowerCase() + '.png';
});
self.setState({
customers: customers
});
});
self.firebaseTransactionsRef = new Firebase('https://jagertrain.firebaseio.com/transactions');
self.firebaseTransactionsRef.on("child_added", (transaction)=> {
if (!newItems) return;
var passenger = this.state.customers[transaction.val().customer];
if (typeof passenger === "undefined") {
console.log('id not recognised');
return;
}
let audio = new Audio(`/sounds/clip_${Math.floor((Math.random() * 7) + 1)}.ogg`);
audio.play();
var $IdleScreem = $('.IdleScreen').addClass("spin-out");
passenger.imageUrl = '/passengers/' + passenger.forename.toLowerCase() + '-' + passenger.surname.toLowerCase() + '.png';
setTimeout(function(){
self.setState({
passenger: passenger
});
setTimeout(function(){
var $Passenger = $('.Passenger');
$Passenger.fadeOut(1000, function() {
self.setState({
passenger: null
});
});
}, 5000);
}, 2000);
});
this.firebaseTransactionsRef.once('value', (dataSnapshot) => {
newItems = true;
});
self.firebaseSoundPlaysRef = new Firebase('https://jagertrain.firebaseio.com/soundplays');
self.firebaseSoundPlaysRef.on('child_changed', (soundPlay) => {
var id = soundPlay.val();
let audio = new Audio(`/sounds/clip_${id}.ogg`);
audio.play();
});
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
render() {
const title = 'Riskdisk Jagertrain 2015';
this.context.onSetTitle(title);
if (this.state.passenger) {
return (
<div className="HomePage">
<div className="HomePage-container">
<Passenger passenger={this.state.passenger} />
</div>
</div>
);
}
else {
return (
<div className="IdleScreen-wrapper">
<IdleScreen />
<h2>All Aboard!!! #RDJT</h2>
</div>
)
}
}
}
export default HomePage;
| JavaScript | 0 |
4f17de7379a358ecaaca5108e0174d1035680bbd | fix test | test/fixtures/tag.js | test/fixtures/tag.js | module.exports = `
acyort.template.register(['archives', 'archives'])
acyort.template.extension = 'swig'
`
| module.exports = `
acyort.builder.register(['archives', 'archives'])
acyort.builder.extension = 'swig'
`
| JavaScript | 0.000002 |
906cfa81f2509da651e3f40c4a2580be3535b733 | comment cleanup | src/components/NumericInput.spec.js | src/components/NumericInput.spec.js | // the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow } from 'enzyme';
import chai from 'chai';
import NumericInput from './NumericInput';
const expect = chai.expect;
/* *****************************************************************************
in terms of basic markup, the NumericInput component
should be a div.form-group
should include an input[type="text"]
should include an input.form-control
should include a label with the appropriate text if a label is specified
should include a placeholder if a placeholder is specified
should include a label with the the required flag if a label is specified & required is set
should not include a label with the the required flag if a label is specified & required is not set
should not include a label with the the required flag if a label is not specified & required is set
*/
describe('in terms of basic markup, the NumericInput component', () => {
it('should be a div.form-group', () => {
const component = shallow(<NumericInput />);
expect(component.is('div.form-group')).to.equal(true);
});
it('should include an input[type="text"]', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input[type="text"]').length).to.equal(1);
});
it('should include an input.form-control', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input.form-control').length).to.equal(1);
});
it('should include a label with the appropriate text if a label is specified', () => {
const label = 'some label';
const component = shallow(<NumericInput label={label} />);
expect(component.find('Label').length).to.equal(1);
expect(component.find('Label').props().label).to.equal(label);
});
it('should include a placeholder if a placeholder is specified', () => {
const placeholder = 'a number goes here';
const component = shallow(<NumericInput placeholder={placeholder} />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input').props().placeholder).to.equal(placeholder);
});
});
| // the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow } from 'enzyme';
import chai from 'chai';
import NumericInput from './NumericInput';
const expect = chai.expect;
/* *****************************************************************************
in terms of basic markup, the NumericInput component
should be a div.form-group
should include an input[type="text"]
should include an input.form-control
should include a label with the appropriate text if a label is specified
should include a placeholder if a placeholder is specified
*/
describe('in terms of basic markup, the NumericInput component', () => {
it('should be a div.form-group', () => {
const component = shallow(<NumericInput />);
expect(component.is('div.form-group')).to.equal(true);
});
it('should include an input[type="text"]', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input[type="text"]').length).to.equal(1);
});
it('should include an input.form-control', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input.form-control').length).to.equal(1);
});
it('should include a label with the appropriate text if a label is specified', () => {
const label = 'some label';
const component = shallow(<NumericInput label={label} />);
expect(component.find('Label').length).to.equal(1);
expect(component.find('Label').props().label).to.equal(label);
});
it('should include a placeholder if a placeholder is specified', () => {
const placeholder = 'a number goes here';
const component = shallow(<NumericInput placeholder={placeholder} />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input').props().placeholder).to.equal(placeholder);
});
});
| JavaScript | 0 |
edbf526aeca5f2f38dbe1c042bb1d1cabe72db24 | Remove indirect Symbol polyfill requirement | src/components/ObserverContainer.js | src/components/ObserverContainer.js | // based on @researchgate/react-intersection-observer
import { parseRootMargin, shallowCompareOptions } from '../lib/utils'
export function getPooled(options = {}) {
const root = options.root || null
const rootMargin = parseRootMargin(options.rootMargin)
const threshold = Array.isArray(options.threshold)
? options.threshold
: [options.threshold != null ? options.threshold : 0]
const observers = storage.keys()
for (let observer = observers.next(); !observer.done; observer = observers.next()) {
const unmatched =
shallowCompareOptions(root, observer.value.root) ||
shallowCompareOptions(rootMargin, observer.value.rootMargin) ||
shallowCompareOptions(threshold, observer.value.threshold)
if (!unmatched) {
return observer.value
}
}
return null
}
export const storage = new Map()
export default class ObserverContainer {
static create(callback, options) {
return getPooled(options) || new IntersectionObserver(callback, options)
}
static findElement(entry, observer) {
const observerElements = storage.get(observer)
if (observerElements) {
const elements = observerElements.values()
for (let element = elements.next(); !element.done; element = elements.next()) {
if (element.value.target === entry.target) {
return element.value
}
}
}
return null
}
static observe(element) {
let targets
if (storage.has(element.observer)) {
targets = storage.get(element.observer)
} else {
targets = new Set()
storage.set(element.observer, targets)
}
targets.add(element)
element.observer.observe(element.target)
}
static unobserve(element) {
if (storage.has(element.observer)) {
const targets = storage.get(element.observer)
if (targets.delete(element)) {
if (targets.size > 0) {
element.observer.unobserve(element.target)
} else {
element.observer.disconnect()
storage.delete(element.observer)
}
}
}
}
static clear() {
storage.clear()
}
static count() {
return storage.size
}
}
| // based on @researchgate/react-intersection-observer
import { parseRootMargin, shallowCompareOptions } from '../lib/utils'
export function getPooled(options = {}) {
const root = options.root || null
const rootMargin = parseRootMargin(options.rootMargin)
const threshold = Array.isArray(options.threshold)
? options.threshold
: [options.threshold != null ? options.threshold : 0]
for (const observer of storage.keys()) {
const unmatched = [
[root, observer.root],
[rootMargin, observer.rootMargin],
[threshold, observer.thresholds],
].some(option => shallowCompareOptions(...option))
if (!unmatched) {
return observer
}
}
return null
}
export const storage = new Map()
export default class ObserverContainer {
static create(callback, options) {
return getPooled(options) || new IntersectionObserver(callback, options)
}
static findElement(entry, observer) {
const elements = storage.get(observer)
if (elements) {
for (const element of elements.values()) {
if (element.target === entry.target) {
return element
}
}
}
return null
}
static observe(element) {
let targets
if (storage.has(element.observer)) {
targets = storage.get(element.observer)
} else {
targets = new Set()
storage.set(element.observer, targets)
}
targets.add(element)
element.observer.observe(element.target)
}
static unobserve(element) {
if (storage.has(element.observer)) {
const targets = storage.get(element.observer)
if (targets.delete(element)) {
if (targets.size > 0) {
element.observer.unobserve(element.target)
} else {
element.observer.disconnect()
storage.delete(element.observer)
}
}
}
}
static clear() {
storage.clear()
}
static count() {
return storage.size
}
}
| JavaScript | 0 |
b1befcf2041910f2651e3f0e435d7c172457ccb9 | Fix string concatenation for showProgress | src/components/Tooltip/Container.js | src/components/Tooltip/Container.js | import React from 'react';
import PropTypes from 'prop-types';
import CloseBtn from './CloseBtn';
const JoyrideTooltipContainer = ({
continuous,
backProps,
closeProps,
primaryProps,
skipProps,
index,
isLastStep,
setTooltipRef,
size,
step,
}) => {
const { content, hideBackButton, locale, showProgress, showSkipButton, title, styles } = step;
const { back, close, last, next, skip } = locale;
const output = {
primary: close,
};
if (continuous) {
output.primary = isLastStep ? last : next;
if (showProgress) {
output.primary = <span>{output.primary} ({index + 1}/{size})</span>;
}
}
if (showSkipButton && !isLastStep) {
output.skip = (
<button
style={styles.buttonSkip}
type="button"
{...skipProps}
>
{skip}
</button>
);
}
if (!hideBackButton && index > 0) {
output.back = (
<button
style={styles.buttonBack}
type="button"
{...backProps}
>
{back}
</button>
);
}
output.close = (<CloseBtn {...closeProps} styles={styles.buttonClose} />);
return (
<div
key="JoyrideTooltip"
ref={setTooltipRef}
style={styles.tooltip}
>
<div style={styles.tooltipContainer}>
{output.close}
{title && (<h4 style={styles.tooltipTitle}>{title}</h4>)}
{!!content && (
<div style={styles.tooltipContent}>
{content}
</div>
)}
</div>
<div style={styles.tooltipFooter}>
{output.skip}
{output.back}
<button
style={styles.buttonNext}
type="button"
{...primaryProps}
>
{output.primary}
</button>
</div>
</div>
);
};
JoyrideTooltipContainer.propTypes = {
backProps: PropTypes.object.isRequired,
closeProps: PropTypes.object.isRequired,
continuous: PropTypes.bool.isRequired,
index: PropTypes.number.isRequired,
isLastStep: PropTypes.bool.isRequired,
primaryProps: PropTypes.object.isRequired,
setTooltipRef: PropTypes.func.isRequired,
size: PropTypes.number.isRequired,
skipProps: PropTypes.object.isRequired,
step: PropTypes.object.isRequired,
};
export default JoyrideTooltipContainer;
| import React from 'react';
import PropTypes from 'prop-types';
import CloseBtn from './CloseBtn';
const JoyrideTooltipContainer = ({
continuous,
backProps,
closeProps,
primaryProps,
skipProps,
index,
isLastStep,
setTooltipRef,
size,
step,
}) => {
const { content, hideBackButton, locale, showProgress, showSkipButton, title, styles } = step;
const { back, close, last, next, skip } = locale;
const output = {
primary: close,
};
if (continuous) {
if (isLastStep) {
output.primary = last;
}
else {
output.primary = next;
}
if (showProgress) {
output.primary += ` (${index + 1}/${size})`;
}
}
if (showSkipButton && !isLastStep) {
output.skip = (
<button
style={styles.buttonSkip}
type="button"
{...skipProps}
>
{skip}
</button>
);
}
if (!hideBackButton && index > 0) {
output.back = (
<button
style={styles.buttonBack}
type="button"
{...backProps}
>
{back}
</button>
);
}
output.close = (<CloseBtn {...closeProps} styles={styles.buttonClose} />);
return (
<div
key="JoyrideTooltip"
ref={setTooltipRef}
style={styles.tooltip}
>
<div style={styles.tooltipContainer}>
{output.close}
{title && (<h4 style={styles.tooltipTitle}>{title}</h4>)}
{!!content && (
<div style={styles.tooltipContent}>
{content}
</div>
)}
</div>
<div style={styles.tooltipFooter}>
{output.skip}
{output.back}
<button
style={styles.buttonNext}
type="button"
{...primaryProps}
>
{output.primary}
</button>
</div>
</div>
);
};
JoyrideTooltipContainer.propTypes = {
backProps: PropTypes.object.isRequired,
closeProps: PropTypes.object.isRequired,
continuous: PropTypes.bool.isRequired,
index: PropTypes.number.isRequired,
isLastStep: PropTypes.bool.isRequired,
primaryProps: PropTypes.object.isRequired,
setTooltipRef: PropTypes.func.isRequired,
size: PropTypes.number.isRequired,
skipProps: PropTypes.object.isRequired,
step: PropTypes.object.isRequired,
};
export default JoyrideTooltipContainer;
| JavaScript | 0.000875 |
5ba27204d584301e716122c84bfe55f18fb45f19 | clean some commented code | src/components/Utils/FirebaseApi.js | src/components/Utils/FirebaseApi.js | import storage from 'key-storage';
import INITIAL_STATE from '../../INITIAL_STATE';
import fbConfig from '../../fbConfig';
import firebase from 'firebase';
firebase.initializeApp(fbConfig);
var DB = firebase.database();
class FirebaseApi {
getTodos(status_filter = [], priorities_filter = []) {
return DB.ref('todos').once('value').then((snapshot) => {
return snapshot.val();
});
}
getTodo(id) {
return DB.ref(`todos/${id}/`).once('value').then((snapshot) => {
return snapshot.val();
});
}
createTodo(todo) {
let newTodo = DB.ref('todos').push();
let newId = newTodo.getKey();
todo.id = newId;
newTodo.set(todo);
return newId;
}
deleteTodo(id) {
return DB.ref(`todos/${id}`).remove();
}
updateTodo(id, todo) {
return DB.ref(`todos/${id}`).update(todo);
}
getKey(key) {
return storage.gey(key);
}
setKey(key, val) {
storage.set(key, val);
return;
}
deleteKey(key) {
storage.remove(key);
return;
}
}
export default new FirebaseApi();
| import storage from 'key-storage';
import INITIAL_STATE from '../../INITIAL_STATE';
import fbConfig from '../../fbConfig';
import firebase from 'firebase';
firebase.initializeApp(fbConfig);
var DB = firebase.database();
class FirebaseApi {
constructor() {
}
getTodos(status_filter = [], priorities_filter = []) {
return DB.ref('todos').once('value').then((snapshot) => {
return snapshot.val();
});
}
useFilters(todos, status_filter = [], priorities_filter = []) {
/*todos = todos.filter((obj, i) => {
return status_filter.indexOf(parseInt(obj.status)) != -1 || priorities_filter.indexOf(parseInt(obj.priority)) != -1;
});*/
return todos;
}
getTodo(id) {
return DB.ref(`todos/${id}/`).once('value').then((snapshot) => {
return snapshot.val();
});
}
createTodo(todo) {
let newTodo = DB.ref('todos').push();
let newId = newTodo.getKey();
todo.id = newId;
newTodo.set(todo);
return newId;
}
deleteTodo(id) {
return DB.ref(`todos/${id}`).remove();
}
updateTodo(id, todo) {
return DB.ref(`todos/${id}`).update(todo);
}
getKey(key) {
return storage.gey(key);
}
setKey(key, val) {
storage.set(key, val);
return;
}
deleteKey(key) {
storage.remove(key);
return;
}
}
export default new FirebaseApi();
| JavaScript | 0.000001 |
a8537e6386e0906db044d1f00a2b82ec59c13570 | use fixed position for global backdrops. | src/components/backdrop/backdrop.js | src/components/backdrop/backdrop.js | /*
* @ngdoc module
* @name material.components.backdrop
* @description Backdrop
*/
/**
* @ngdoc directive
* @name mdBackdrop
* @module material.components.backdrop
*
* @restrict E
*
* @description
* `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet.
* Apply class `opaque` to make the backdrop use the theme backdrop color.
*
*/
angular
.module('material.components.backdrop', ['material.core'])
.directive('mdBackdrop', function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) {
var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";
return {
restrict: 'E',
link: postLink
};
function postLink(scope, element, attrs) {
// If body scrolling has been disabled using mdUtil.disableBodyScroll(),
// adjust the 'backdrop' height to account for the fixed 'body' top offset
var body = $window.getComputedStyle($document[0].body);
if (body.position == 'fixed') {
var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10));
element.css({
height: hViewport + 'px'
});
}
// backdrop may be outside the $rootElement, tell ngAnimate to animate regardless
if ($animate.pin) $animate.pin(element, $rootElement);
$$rAF(function () {
// Often $animate.enter() is used to append the backDrop element
// so let's wait until $animate is done...
var parent = element.parent()[0];
if (parent) {
if ( parent.nodeName == 'BODY' ) {
element.css({position : 'fixed'});
}
var styles = $window.getComputedStyle(parent);
if (styles.position == 'static') {
// backdrop uses position:absolute and will not work properly with parent position:static (default)
$log.warn(ERROR_CSS_POSITION);
}
}
$mdTheming.inherit(element, element.parent());
});
}
});
| /*
* @ngdoc module
* @name material.components.backdrop
* @description Backdrop
*/
/**
* @ngdoc directive
* @name mdBackdrop
* @module material.components.backdrop
*
* @restrict E
*
* @description
* `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet.
* Apply class `opaque` to make the backdrop use the theme backdrop color.
*
*/
angular
.module('material.components.backdrop', ['material.core'])
.directive('mdBackdrop', function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) {
var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";
return {
restrict: 'E',
link: postLink
};
function postLink(scope, element, attrs) {
// If body scrolling has been disabled using mdUtil.disableBodyScroll(),
// adjust the 'backdrop' height to account for the fixed 'body' top offset
var body = $window.getComputedStyle($document[0].body);
if (body.position == 'fixed') {
var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10));
element.css({
height: hViewport + 'px'
});
}
// backdrop may be outside the $rootElement, tell ngAnimate to animate regardless
if ($animate.pin) $animate.pin(element, $rootElement);
$$rAF(function () {
// Often $animate.enter() is used to append the backDrop element
// so let's wait until $animate is done...
var parent = element.parent()[0];
if (parent) {
var styles = $window.getComputedStyle(parent);
if (styles.position == 'static') {
// backdrop uses position:absolute and will not work properly with parent position:static (default)
$log.warn(ERROR_CSS_POSITION);
}
}
$mdTheming.inherit(element, element.parent());
});
}
});
| JavaScript | 0 |
5cc7e868dfb3ad719b0113e0eae5d1b5b6a07200 | Update HomePage.js | src/modules/core/components/HomePage.js | src/modules/core/components/HomePage.js | import React from "react";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import injectSheet from "react-jss";
import { Grid, Row, Col } from "react-bootstrap/lib";
import {
FeaturedArticle,
RecommendedArticles,
LatestArticlesRibbon,
LeftColumn,
RightColumn,
} from "../../articles/components/summaries";
import { SectionFeature, SectionColumn } from "../../sections/components";
const HomePageQuery = gql`
query HomePageQuery {
featuredArticle {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
title
media_type
attachment_url
medium_attachment_url
thumb_attachment_url
}
section {
name
permalink
}
}
columnArticles {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
attachment_url
}
section {
name
permalink
}
}
}
`;
const styles = {
HomePage: {
margin: "23px 0px 13px",
},
recommendedArticles: {
padding: 0,
},
primaryComponents: {
borderRight: "solid 1px #ddd",
marginBottom: "19px",
paddingRight: "14px",
},
"@media (max-width: 991px)": {
primaryComponents: {
borderRight: "none",
paddingRight: 0,
},
},
"@media (max-width: 767px)": {
skinnyCol: {
padding: "0 !important",
},
},
adbanner: {
fontFamily: "Circular Std",
marginTop: "0%",
margin: "auto",
},
"@media screen and (min-width: 769px)": {
adbanner: {
display: "none",
},
},
};
const HomePage = ({ classes, data }) => {
if (data.loading) {
return null;
}
const { featuredArticle, columnArticles } = data;
const firstColumnSectionSlugs = ["opinions", "features", "humor"];
const secondColumnSectionSlugs = [
"staff-editorials",
"ae",
"sports-at-stuyvesant",
];
return (
<div>
<Grid fluid>
<Row>
<center>
<div className={classes.adbanner}>
<h1 className="col-md-12 container-fluid">
Check out the promotions on the bottom of the page!
</h1>
</div>
</center>
<Col
xs={12}
sm={12}
md={9}
lg={9}
className={classes.primaryComponents}
>
<FeaturedArticle article={featuredArticle} />
<SectionFeature slug={"news"} />
</Col>
<Col
xsHidden
smHidden
md={3}
lg={3}
className={classes.recommendedArticles}
>
<RecommendedArticles />
</Col>
</Row>
<Row>
<Col xsHidden sm={12} md={12} lg={12}>
<LatestArticlesRibbon className={classes.latestArticlesRibbon} />
</Col>
</Row>
<Row>
<LeftColumn articles={columnArticles.slice(0, 3)} />
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={firstColumnSectionSlugs} />
</Col>
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={secondColumnSectionSlugs} />
</Col>
<RightColumn articles={columnArticles.slice(3)} />
</Row>
</Grid>
</div>
);
};
export default graphql(HomePageQuery)(injectSheet(styles)(HomePage));
| import React from "react";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import injectSheet from "react-jss";
import { Grid, Row, Col } from "react-bootstrap/lib";
import {
FeaturedArticle,
RecommendedArticles,
LatestArticlesRibbon,
LeftColumn,
RightColumn,
} from "../../articles/components/summaries";
import { SectionFeature, SectionColumn } from "../../sections/components";
const HomePageQuery = gql`
query HomePageQuery {
featuredArticle {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
title
media_type
attachment_url
medium_attachment_url
thumb_attachment_url
}
section {
name
permalink
}
}
columnArticles {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
attachment_url
}
section {
name
permalink
}
}
}
`;
const styles = {
HomePage: {
margin: "23px 0px 13px",
},
recommendedArticles: {
padding: 0,
},
primaryComponents: {
borderRight: "solid 1px #ddd",
marginBottom: "19px",
paddingRight: "14px",
},
"@media (max-width: 991px)": {
primaryComponents: {
borderRight: "none",
paddingRight: 0,
},
},
"@media (max-width: 767px)": {
skinnyCol: {
padding: "0 !important",
},
},
adbanner: {
fontFamily: "Circular Std",
marginTop: "0%",
margin: "auto",
},
"@media screen and (min-width: 769px)": {
adbanner: {
display: "none",
},
},
};
const HomePage = ({ classes, data }) => {
if (data.loading) {
return null;
}
const { featuredArticle, columnArticles } = data;
const firstColumnSectionSlugs = ["opinions", "features", "humor"];
const secondColumnSectionSlugs = [
"staff-editorials",
"ae",
"sports-at-stuyvesant",
];
return (
<div>
<Grid fluid>
<Row>
<center>
<div className={classes.adbanner}>
<h1 className="col-md-12 container-fluid">
Check out the promotions on the bottom of the page!
</h1>
</div>
</center>
<Col
xs={12}
sm={12}
md={9}
lg={9}
className={classes.primaryComponents}
>
<FeaturedArticle article={featuredArticle} />
<SectionFeature slug={"sing!"} />
</Col>
<Col
xsHidden
smHidden
md={3}
lg={3}
className={classes.recommendedArticles}
>
<RecommendedArticles />
</Col>
</Row>
<Row>
<Col xsHidden sm={12} md={12} lg={12}>
<LatestArticlesRibbon className={classes.latestArticlesRibbon} />
</Col>
</Row>
<Row>
<LeftColumn articles={columnArticles.slice(0, 3)} />
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={firstColumnSectionSlugs} />
</Col>
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={secondColumnSectionSlugs} />
</Col>
<RightColumn articles={columnArticles.slice(3)} />
</Row>
</Grid>
</div>
);
};
export default graphql(HomePageQuery)(injectSheet(styles)(HomePage));
| JavaScript | 0 |
18d70ee9f03026a0435d85dbd299f3d9e7cae3fd | test exit code of info command | test/info-command.js | test/info-command.js | const assert = require('assert')
const path = require('path')
const z1 = require('..')
const { works } = require('./lib/command')
const {
TIMEOUT,
KILL_TIMEOUT
} = require('./lib/config')
describe('info command', function () {
this.timeout(TIMEOUT)
before(async function () {
await z1.start('test-app/basic', [], {
workers: 1
})
})
after(async function () {
await z1.stop('basic', {
timeout: KILL_TIMEOUT
})
})
it('should not exit with an exit code', async function () {
await works('z1 info basic')
})
describe('option', function () {
/**
* Test if the given option outputs the expected result
* @param {string} optionName
* @param {string} expectedResult
*/
function checkOption(optionName, expectedResult) {
describe(optionName, function () {
it(`should output the ${optionName} of the app`, async function () {
const result = await works(`z1 info basic --${optionName}`)
assert.strictEqual(result.out, expectedResult + '\n')
})
})
}
checkOption('available', '1')
checkOption('dir', path.resolve('test-app/basic'))
checkOption('killed', '0')
checkOption('name', 'basic')
checkOption('pending', '0')
checkOption('ports', '8080')
checkOption('revive-count', '0')
})
})
| const assert = require('assert')
const path = require('path')
const z1 = require('..')
const { works } = require('./lib/command')
const {
TIMEOUT,
KILL_TIMEOUT
} = require('./lib/config')
describe('info command', function () {
this.timeout(TIMEOUT)
describe('option', function () {
before(async function () {
await z1.start('test-app/basic', [], {
workers: 1
})
})
after(async function () {
await z1.stop('basic', {
timeout: KILL_TIMEOUT
})
})
/**
* Test if the given option outputs the expected result
* @param {string} optionName
* @param {string} expectedResult
*/
function checkOption(optionName, expectedResult) {
describe(optionName, function () {
it('should output the directory of the app', async function () {
const result = await works('z1 info basic ' + optionName)
assert.strictEqual(result.out, expectedResult + '\n')
})
})
}
checkOption('--available', '1')
checkOption('--dir', path.resolve('test-app/basic'))
checkOption('--killed', '0')
checkOption('--name', 'basic')
checkOption('--pending', '0')
checkOption('--ports', '8080')
checkOption('--revive-count', '0')
})
})
| JavaScript | 0.000001 |
dec236142e9a5d25ee10f1dcc26bf126a9af26bc | Fix test regression | test/linters/less.js | test/linters/less.js | var expect = require('unexpected'),
Path = require('path'),
fs = require('fs'),
less = require('../../lib/linters/less');
/*global describe, it*/
function loadTestCase(lessFileName, cb) {
var lessPath = Path.resolve(__dirname, 'less', lessFileName);
fs.readFile(lessPath, 'utf-8', function (err, lessStr) {
if (err) {
return cb(err);
}
less(lessPath, lessStr, {}, cb);
});
}
describe('less', function () {
it('should produce an error when a missing file is referenced in an @import', function (done) {
loadTestCase('importedFileNotFound.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', '\'notFound.less\' wasn\'t found.');
done(err);
});
});
it('should produce an error when a file has a syntax error', function (done) {
loadTestCase('syntaxError.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an imported file has a syntax error', function (done) {
loadTestCase('syntaxErrorInImportedFile.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an undefined variable is referenced', function (done) {
loadTestCase('undefinedVariableReferenced.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'variable @foo is undefined.');
done(err);
});
});
});
| var expect = require('unexpected'),
Path = require('path'),
fs = require('fs'),
less = require('../../lib/linters/less');
/*global describe, it*/
function loadTestCase(lessFileName, cb) {
var lessPath = Path.resolve(__dirname, 'less', lessFileName);
fs.readFile(lessPath, 'utf-8', function (err, lessStr) {
if (err) {
return cb(err);
}
less(lessPath, lessStr, {}, cb);
});
}
describe('less', function () {
it('should produce an error when a missing file is referenced in an @import', function (done) {
loadTestCase('importedFileNotFound.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', '"notFound.less" wasn\'t found.');
done(err);
});
});
it('should produce an error when a file has a syntax error', function (done) {
loadTestCase('syntaxError.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an imported file has a syntax error', function (done) {
loadTestCase('syntaxErrorInImportedFile.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an undefined variable is referenced', function (done) {
loadTestCase('undefinedVariableReferenced.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'variable @foo is undefined.');
done(err);
});
});
});
| JavaScript | 0.000018 |
112e38a232389471c602bc6499605cda1472b6ff | Add a test case | test/mongodb.test.js | test/mongodb.test.js | // This test written in mocha+should.js
var should = require('./init.js');
var User, Post, Post1, db;
describe('mongodb', function(){
before(function() {
db = getDataSource();
User = db.define('User', {
name: { type: String, index: true },
email: { type: String, index: true },
age: Number,
});
Post = db.define('Post', {
title: { type: String, length: 255, index: true },
content: { type: String }
});
Post1 = db.define('Post1', {
id: {type: String, id: true},
title: { type: String, length: 255, index: true },
content: { type: String }
});
User.hasMany(Post);
Post.belongsTo(User);
});
beforeEach(function(done) {
User.destroyAll(function() {
Post.destroyAll(function() {
done();
});
});
});
it('hasMany should support additional conditions', function (done) {
User.create(function (e, u) {
u.posts.create({}, function (e, p) {
u.posts({where: {_id: p.id}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
done();
});
});
});
});
it('should allow to find by id string', function (done) {
Post.create(function (err, post) {
Post.find(post.id.toString(), function (err, post) {
should.not.exist(err);
should.exist(post);
done();
});
});
});
it('find should return an object with an id, which is instanceof ObjectId', function (done) {
Post.create(function (err, post) {
Post.findById(post.id, function (err, post) {
should.not.exist(err);
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return object with an id, which is instanceof ObjectID', function (done) {
var post = new Post({title: 'a', content: 'AAA'})
post.save(function (err, post) {
Post.all({where: {title: 'a'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'a');
post.should.have.property('content', 'AAA');
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return honor filter.fields', function (done) {
var post = new Post({title: 'b', content: 'BBB'})
post.save(function (err, post) {
Post.all({fields: ['title'], where: {title: 'b'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'b');
post.should.not.have.property('content');
done();
});
});
});
it('create should convert id from string to ObjectID if format matches',
function(done) {
var oid = new db.ObjectID().toString();
Post1.create({id: oid, title: 'c', content: 'CCC'}, function (err, post) {
Post1.findById(oid, function (err, post) {
should.not.exist(err);
post.id.should.be.equal(oid);
done();
});
});
});
after(function(done){
User.destroyAll(function(){
Post.destroyAll(done);
});
});
});
| // This test written in mocha+should.js
var should = require('./init.js');
var User, Post, db;
describe('mongodb', function(){
before(function() {
db = getDataSource();
User = db.define('User', {
name: { type: String, index: true },
email: { type: String, index: true },
age: Number,
});
Post = db.define('Post', {
title: { type: String, length: 255, index: true },
content: { type: String }
});
User.hasMany(Post);
Post.belongsTo(User);
});
beforeEach(function(done) {
User.destroyAll(function() {
Post.destroyAll(function() {
done();
});
});
});
it('hasMany should support additional conditions', function (done) {
User.create(function (e, u) {
u.posts.create({}, function (e, p) {
u.posts({where: {_id: p.id}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
done();
});
});
});
});
it('should allow to find by id string', function (done) {
Post.create(function (err, post) {
Post.find(post.id.toString(), function (err, post) {
should.not.exist(err);
should.exist(post);
done();
});
});
});
it('find should return an object with an id, which is instanceof ObjectId', function (done) {
Post.create(function (err, post) {
Post.findById(post.id, function (err, post) {
should.not.exist(err);
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return object with an id, which is instanceof ObjectID', function (done) {
var post = new Post({title: 'a', content: 'AAA'})
post.save(function (err, post) {
Post.all({where: {title: 'a'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'a');
post.should.have.property('content', 'AAA');
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return honor filter.fields', function (done) {
var post = new Post({title: 'b', content: 'BBB'})
post.save(function (err, post) {
Post.all({fields: ['title'], where: {title: 'b'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'b');
post.should.not.have.property('content');
done();
});
});
});
after(function(done){
User.destroyAll(function(){
Post.destroyAll(done);
});
});
});
| JavaScript | 0.99959 |
d2a2e43c5e5561ab1601e64fcfbfe8be864eda5e | Remove erroneous semicolon in security test script | test/security/pwn.js | test/security/pwn.js | (function(){
var message = 'Ya been pwned by an XSS from an unsanitized script tag injection.';
if(alertify){
alertify.error(message);
} else {
document.body.innerHTML = '<h1>' + message + '</h1>';
}
})();
| (function(){
var message = 'Ya been pwned by an XSS from an unsanitized script tag injection.';
if(alertify){
alertify.error(message);
} else {
document.body.innerHTML = '<h1>' + message + '</h1>';
};
})();
| JavaScript | 0.99886 |
00c68399e37c09d6d718cb8e184232b9e3c3ec80 | Update EU_cookies_law.min.js | EU_cookies_law.min.js | EU_cookies_law.min.js | /*! Simple EU Cookies Law Compliance without dependencies by cara-tm.com, 2017. MIT license */
var EU_cookies_law=function(r){"use strict";var msg="You refuse external third-party cookies: none, at the initiative of this site, is present on your device.",
future='1 Month',
minutes=1;
var domain=window.location.hostname,lang=(navigator.language||navigator.browserLanguage),countries=['AT','BE','BG','HR','CZ','CY','DK','EE','FI','FR','DE','EL','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','SK','SI','ES','SE','GB','UK'],affected!==1,seconds=60,mins=minutes,accept_cookies=document.getElementById('ok-cookies'),refuse_cookies=document.getElementById('no-cookies');if(0!==navigator.cookieEnabled){for(var i=0;i<countries.length;i++){if(countries[i]===lang.substring(0,2).toUpperCase()){affected!==0;break}}
if(affected!==1){sanitize_msg('');jsloader(r);}else check_cookies();
accept_cookies.onclick=function(evt){launch(evt);evt.preventDefault();};function launch(){future=Number(future.replace(/\D+$/,''));var expires=new Date(new Date().setMonth(new Date().getMonth()+future));cookie_creation('Ok',expires);jsloader(r);sanitize_msg('');}refuse_cookies.onclick=function(evt){var tomorrow=new Date(new Date().setDate(new Date().getDate()+1));cookie_creation('No',tomorrow);sanitize_msg(msg);window.location='';evt.preventDefault();};function getCookie(sName){var oRegex=new RegExp('(?:; )?'+sName+'=([^;]*);?');if(oRegex.test(document.cookie))
return decodeURIComponent(RegExp.$1);else return null;}
function check_cookies(){tick();if(getCookie(domain)==='Ok'+domain){sanitize_msg('');jsloader(r);}else if(getCookie(domain)==='No'+domain){sanitize_msg(msg);}}
function cookie_creation(c,e){return document.cookie=domain+'='+encodeURIComponent(c+domain)+';expires='+e.toGMTString();}
function jsloader(el){var s=[];var a=document.getElementsByTagName("script")[0];if(!window.scriptHasRun){window.scriptHasRun=true;for(var i=0;i<el.length;i++){if(el[i]!=0||!window.scriptHasRun){window.scriptHasRun=true;s[i]=document.createElement('script');s[i].src=el[i];document.getElementsByTagName('head')[0].appendChild(s[i])||a.parentNode.insertBefore(s[i],a);}}}}
function sanitize_msg(m){document.getElementById("cookies-delay").innerHTML='';return document.getElementById('cookie-choices').innerHTML=m;}
function tick(){if(minutes!=0&&null!==document.getElementById('counter')){var counter=document.getElementById('counter'),current_minutes=mins-1;seconds--;if(typeof counter.innerHTML!==null)counter.innerHTML=current_minutes.toString()+':'+(seconds<10?'0':'')+String(seconds);if(seconds>0){setTimeout(tick,1000);}else{if(mins>1){countdown(mins-1);}}if(seconds==0){launch();sanitize_msg('');}}else document.getElementById('cookies-delay').innerHTML='';}}else{sanitize_msg("Veuillez activer les Cookies sur votre navigateur.");}};
// Array of third part JS files to load (with external cookies) if only the 'Cookies Choice' button is accepted by visitors or after a delay if the counter feature is enabled:
EU_cookies_law(["js/google-analytics.js", " "]);
| /*! Simple EU Cookies Law Compliance without dependencies by cara-tm.com, 2017. MIT license */
var EU_cookies_law=function(r){"use strict";var msg="You refuse external third-party cookies: none, at the initiative of this site, is present on your device.",
future='1 Month',
minutes=1;
var domain=window.location.hostname,lang=(navigator.language||navigator.browserLanguage),countries=['AT','BE','BG','HR','CZ','CY','DK','EE','FI','FR','DE','EL','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','SK','SI','ES','SE','GB','UK'],affected!==1,seconds=60,mins=minutes,accept_cookies=document.getElementById('ok-cookies'),refuse_cookies=document.getElementById('no-cookies');if(0!==navigator.cookieEnabled){for(var i=0;i<countries.length;i++){if(countries[i]===lang.substring(0,2).toUpperCase()){affected!==0;break}}
if(affected!==1){sanitize_msg('');jsloader(r);}else check_cookies();
accept_cookies.onclick=function(evt){launch(evt);evt.preventDefault();};function launch(){future=Number(future.replace(/\D+$/,''));var expires=new Date(new Date().setMonth(new Date().getMonth()+future));cookie_creation('Ok',expires);jsloader(r);sanitize_msg('');}refuse_cookies.onclick=function(evt){var tomorrow=new Date(new Date().setDate(new Date().getDate()+1));cookie_creation('No',tomorrow);sanitize_msg(msg);window.location='';evt.preventDefault();};function getCookie(sName){var oRegex=new RegExp('(?:; )?'+sName+'=([^;]*);?');if(oRegex.test(document.cookie))
return decodeURIComponent(RegExp.$1);else return null}
function check_cookies(){tick();if(getCookie(domain)==='Ok'+domain){sanitize_msg('');jsloader(r)}else if(getCookie(domain)==='No'+domain){sanitize_msg(msg)}}
function cookie_creation(c,e){return document.cookie=domain+'='+encodeURIComponent(c+domain)+';expires='+e.toGMTString()}
function jsloader(el){var s=[];var a=document.getElementsByTagName("script")[0];if(!window.scriptHasRun){window.scriptHasRun=true;for(var i=0;i<el.length;i++){if(el[i]!=0||!window.scriptHasRun){window.scriptHasRun=true;s[i]=document.createElement('script');s[i].src=el[i];document.getElementsByTagName('head')[0].appendChild(s[i])||a.parentNode.insertBefore(s[i],a)}}}}
function sanitize_msg(m){document.getElementById("cookies-delay").innerHTML='';return document.getElementById('cookie-choices').innerHTML=m};
function tick(){if(minutes!=0&&null!==document.getElementById('counter')){var counter=document.getElementById('counter'),current_minutes=mins-1;seconds--;if(typeof counter.innerHTML!==null)counter.innerHTML=current_minutes.toString()+':'+(seconds<10?'0':'')+String(seconds);if(seconds>0){setTimeout(tick,1000);}else{if(mins>1){countdown(mins-1);}}if(seconds==0){launch();sanitize_msg('');}}else document.getElementById('cookies-delay').innerHTML='';}}else{sanitize_msg("Veuillez activer les Cookies sur votre navigateur.");}};
// Array of third part JS files to load (with external cookies) if only the 'Cookies Choice' button is accepted by visitors or after a delay if the counter feature is enabled:
EU_cookies_law(["js/google-analytics.js", " "]);
| JavaScript | 0 |
2559bbadf7de3f94e2028bd503e903a60ba159a4 | Remove the upload button in folder views (#950) | source/features/remove-upload-files-button.js | source/features/remove-upload-files-button.js | import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
const repoUrl = pageDetect.getRepoURL();
export default () => {
if (pageDetect.isRepoRoot() || pageDetect.isRepoTree()) {
const uploadFilesButton = select(`.file-navigation a[href^="/${repoUrl}/upload"]`);
if (uploadFilesButton) {
uploadFilesButton.remove();
}
}
};
| import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
const repoUrl = pageDetect.getRepoURL();
export default () => {
if (pageDetect.isRepoRoot()) {
const uploadFilesButton = select(`.file-navigation a[href^="/${repoUrl}/upload"]`);
if (uploadFilesButton) {
uploadFilesButton.remove();
}
}
};
| JavaScript | 0 |
2770897c6b795898e9e6404d61026fd292192e7c | Fix weird floating green bug thingy | src/main/js/components/Workspace.js | src/main/js/components/Workspace.js | var React = require('react');
var Interact = require('interact.js');
var _ = require('lodash');
var PersonContainer = require('containers/PersonContainer.js');
var Space = require('components/Space.js');
var Workspace = React.createClass({
componentDidMount: function() {
var self = this;
Interact('.draggable')
.draggable({
inertia:true,
restrict: {
restriction: ".workspace"
},
autoScroll: true,
onmove: dragMoveListener
});
function dragMoveListener (event) {
// Keep the dragged position in the data-x/data-y attributes
var target = event.target;
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// Translate the element on the screen
target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
// Update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
var fromSpaceIndex, toSpaceIndex;
Interact('.dropzone')
.dropzone({
// Only accept elements matching this CSS selector
accept: '.draggable.drag-drop',
// Require a 75% element overlap for a drop to be possible
overlap: 0.50,
// target -> dropzoneElement, relatedTarget -> draggableElement
ondropactivate: function (event) {
event.target.classList.add('drop-active');
},
ondropdeactivate: function (event) {
event.target.classList.remove('drop-active');
},
ondragenter: function (event) {
event.target.classList.add('drop-target');
event.relatedTarget.classList.add('can-drop');
toSpaceIndex = getIndexFromId(event.target.id);
},
ondragleave: function (event) {
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
if(fromSpaceIndex === undefined) {
fromSpaceIndex = getIndexFromId(event.target.id);
}
},
ondrop: function (event) {
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
var personIndex = getIndexFromId(event.relatedTarget.id);
if(fromSpaceIndex === undefined) {
fromSpaceIndex = toSpaceIndex;
}
self.props.movePerson(fromSpaceIndex, toSpaceIndex, personIndex);
if (fromSpaceIndex === toSpaceIndex) {
event.relatedTarget.removeAttribute('style');
event.relatedTarget.removeAttribute('data-x');
event.relatedTarget.removeAttribute('data-y');
}
fromSpaceIndex = undefined;
toSpaceIndex = undefined;
}
});
function getIndexFromId(idString) {
var segments = _.split(idString, '_');
return parseInt(segments[segments.length-1]);
}
},
render: function() {
return <div id="space_-1" className="container-fluid workspace dropzone">
<div className="floatingSpace">
<h2>Floating</h2>
{this.props.people.map(function (person, idx) {
return <PersonContainer key={person.name} name={person.name} index={idx} spaceIndex={-1}/>
})}
</div>
{this.props.spaces.map(function (space, idx) {
return <Space key={idx} name={space.name} people={space.people} index={idx}/>;
})}
</div>
}
});
module.exports = Workspace;
| var React = require('react');
var Interact = require('interact.js');
var _ = require('lodash');
var PersonContainer = require('containers/PersonContainer.js');
var Space = require('components/Space.js');
var Workspace = React.createClass({
componentDidMount: function() {
var self = this;
Interact('.draggable')
.draggable({
inertia:true,
restrict: {
restriction: ".workspace"
},
autoScroll: true,
onmove: dragMoveListener
});
function dragMoveListener (event) {
// Keep the dragged position in the data-x/data-y attributes
var target = event.target;
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// Translate the element on the screen
target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
// Update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
var fromSpaceIndex, toSpaceIndex;
Interact('.dropzone')
.dropzone({
// Only accept elements matching this CSS selector
accept: '.draggable.drag-drop',
// Require a 75% element overlap for a drop to be possible
overlap: 0.50,
// target -> dropzoneElement, relatedTarget -> draggableElement
ondropactivate: function (event) {
event.target.classList.add('drop-active');
},
ondropdeactivate: function (event) {
event.target.classList.remove('drop-active');
},
ondragenter: function (event) {
event.target.classList.add('drop-target');
event.relatedTarget.classList.add('can-drop');
toSpaceIndex = getIndexFromId(event.target.id);
},
ondragleave: function (event) {
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
if(fromSpaceIndex === undefined) {
fromSpaceIndex = getIndexFromId(event.target.id);
}
},
ondrop: function (event) {
event.target.classList.remove('drop-target');
var personIndex = getIndexFromId(event.relatedTarget.id);
if(fromSpaceIndex === undefined) {
fromSpaceIndex = toSpaceIndex;
}
self.props.movePerson(fromSpaceIndex, toSpaceIndex, personIndex);
fromSpaceIndex = undefined;
toSpaceIndex = undefined;
}
});
function getIndexFromId(idString) {
var segments = _.split(idString, '_');
return parseInt(segments[segments.length-1]);
}
},
render: function() {
return <div id="space_-1" className="container-fluid workspace dropzone">
<div className="floatingSpace">
<h2>Floating</h2>
{this.props.people.map(function (person, idx) {
return <PersonContainer key={person.name} name={person.name} index={idx} spaceIndex={-1}/>
})}
</div>
{this.props.spaces.map(function (space, idx) {
return <Space key={idx} name={space.name} people={space.people} index={idx}/>;
})}
</div>
}
});
module.exports = Workspace;
| JavaScript | 0 |
50b105a0da0695ba25e67b03a6df354e712e0c6c | correct test | test/subscription.js | test/subscription.js | const hub = require('../')
const test = require('tape')
// test('subscription - val + fields', t => {
// const server = hub({
// _uid_: 'server',
// port: 6060,
// a: {
// val: 'a',
// b: { c: 'c!' }
// }
// })
// server.set({ nostamp: 'nostamp!' }, false)
// const client = hub({
// _uid_: 'client',
// url: 'ws://localhost:6060'
// })
// Promise.all([
// client.get([ 'a', 'b', 'c' ], {}).once('c!'),
// client.get([ 'a' ], {}).once('a')
// ]).then(() => {
// client.subscribe({ nostamp: true })
// return client.get('nostamp', {}).once('nostamp!')
// }).then(() => {
// t.pass('received correct payload')
// client.set(null)
// server.set(null)
// t.end()
// })
// client.subscribe({ a: true })
// })
test('subscription - reuse', t => {
const server = hub({
_uid_: 'server',
port: 6060,
a: 'hello'
})
server.set({ nostamp: 'nostamp!' }, false)
const client = hub({
_uid_: 'client',
url: 'ws://localhost:6060'
})
const client2 = hub({
_uid_: 'client2',
url: 'ws://localhost:6060'
})
client.subscribe({ a: true })
client2.subscribe({ a: true })
Promise.all([
client.get('a', {}).once(true),
client2.get('a', {}).once(true)
]).then(() => {
t.pass('received correct payload (reuse)')
client.set(null)
client2.set(null)
server.set(null)
t.end()
})
})
| const hub = require('../')
const test = require('tape')
// test('subscription - val + fields', t => {
// const server = hub({
// _uid_: 'server',
// port: 6060,
// a: {
// val: 'a',
// b: { c: 'c!' }
// }
// })
// server.set({ nostamp: 'nostamp!' }, false)
// const client = hub({
// _uid_: 'client',
// url: 'ws://localhost:6060'
// })
// Promise.all([
// client.get([ 'a', 'b', 'c' ], {}).once('c!'),
// client.get([ 'a' ], {}).once('a')
// ]).then(() => {
// client.subscribe({ nostamp: true })
// return client.get('nostamp', {}).once('nostamp!')
// }).then(() => {
// t.pass('received correct payload')
// client.set(null)
// server.set(null)
// t.end()
// })
// client.subscribe({ a: true })
// })
test('subscription - reuse', t => {
const server = hub({
_uid_: 'server',
port: 6060,
a: 'hello'
})
server.set({ nostamp: 'nostamp!' }, false)
const client = hub({
_uid_: 'client',
url: 'ws://localhost:6060'
})
const client2 = hub({
_uid_: 'client2',
url: 'ws://localhost:6060'
})
client.subscribe({ a: true })
client2.subscribe({ a: true })
Promise.all([
client.get('a', {}).once(true),
client2.get('a', {}).once(true)
]).then(() => {
t.pass('received correct payload (reuse)')
client.set(null)
client2.set(null)
server.set(null)
t.end()
})
})
| JavaScript | 0.000717 |
8b096564b08a788d8d10f04c541e885ac49c2867 | Add correct column widths | src/pages/dataTableUtilities/columns.js | src/pages/dataTableUtilities/columns.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import { tableStrings } from '../../localization';
const PAGE_COLUMN_WIDTHS = {
customerInvoice: [2, 4, 2, 2, 1],
supplierInvoice: [2, 4, 2, 2, 1],
};
const PAGE_COLUMNS = {
customerInvoice: ['itemCode', 'itemName', 'availableQuantity', 'totalQuantity', 'remove'],
supplierInvoice: ['itemCode', 'itemName', 'totalQuantity', 'editableExpiryDate', 'remove'],
};
const COLUMNS = () => ({
itemCode: {
key: 'itemCode',
title: tableStrings.item_code,
sortable: true,
},
itemName: {
key: 'itemName',
title: tableStrings.item_name,
sortable: true,
},
availableQuantity: {
key: 'availableQuantity',
title: tableStrings.available_stock,
sortable: true,
alignText: 'right',
},
totalQuantity: {
key: 'totalQuantity',
type: 'editable',
title: tableStrings.quantity,
sortable: true,
alignText: 'right',
},
remove: {
key: 'remove',
type: 'checkable',
title: tableStrings.remove,
alignText: 'center',
},
editableExpiryDate: {
key: 'editableExpiryDate',
type: 'date',
title: tableStrings.batch_expiry,
alignText: 'center',
},
});
const getColumns = page => {
const columnKeys = PAGE_COLUMNS[page];
const widths = PAGE_COLUMN_WIDTHS[page];
if (!columnKeys) return [];
if (!(columnKeys.length === widths.length)) return [];
const columns = COLUMNS();
return columnKeys.map((columnKey, i) => ({ ...columns[columnKey], width: widths[i] }));
};
export default getColumns;
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import { tableStrings } from '../../localization';
const PAGE_COLUMN_WIDTHS = {
customerInvoice: [2, 4, 2, 2, 1],
supplierInvoice: [1, 3, 1, 1, 1],
};
const PAGE_COLUMNS = {
customerInvoice: ['itemCode', 'itemName', 'availableQuantity', 'totalQuantity', 'remove'],
supplierInvoice: ['itemCode', 'itemName', 'totalQuantity', 'editableExpiryDate', 'remove'],
};
const COLUMNS = () => ({
itemCode: {
key: 'itemCode',
title: tableStrings.item_code,
sortable: true,
},
itemName: {
key: 'itemName',
title: tableStrings.item_name,
sortable: true,
},
availableQuantity: {
key: 'availableQuantity',
title: tableStrings.available_stock,
sortable: true,
alignText: 'right',
},
totalQuantity: {
key: 'totalQuantity',
type: 'editable',
title: tableStrings.quantity,
sortable: true,
alignText: 'right',
},
remove: {
key: 'remove',
type: 'checkable',
title: tableStrings.remove,
alignText: 'center',
},
editableExpiryDate: {
key: 'editableExpiryDate',
type: 'date',
title: tableStrings.batch_expiry,
alignText: 'center',
},
});
const getColumns = page => {
const columnKeys = PAGE_COLUMNS[page];
const widths = PAGE_COLUMN_WIDTHS[page];
if (!columnKeys) return [];
if (!(columnKeys.length === widths.length)) return [];
const columns = COLUMNS();
return columnKeys.map((columnKey, i) => ({ ...columns[columnKey], width: widths[i] }));
};
export default getColumns;
| JavaScript | 0.001313 |
38908396f516ce76132bab0a2c288835668c00c9 | Fix stream view spec to look for different things on FF and on webkit. Sigh. | spec/javascripts/app/views/stream_view_spec.js | spec/javascripts/app/views/stream_view_spec.js | describe("app.views.Stream", function(){
beforeEach(function(){
loginAs({name: "alice", avatar : {small : "http://avatar.com/photo.jpg"}});
this.posts = $.parseJSON(spec.readFixture("multi_stream_json"))["posts"];
this.stream = new app.models.Stream();
this.stream.add(this.posts);
this.view = new app.views.Stream({model : this.stream});
app.stream.bind("fetched", this.collectionFetched, this); //untested
// do this manually because we've moved loadMore into render??
this.view.render();
_.each(this.view.collection.models, function(post){ this.view.addPost(post); }, this);
});
describe("initialize", function(){
it("binds an infinite scroll listener", function(){
spyOn($.fn, "scroll");
new app.views.Stream({model : this.stream});
expect($.fn.scroll).toHaveBeenCalled();
});
});
describe("#render", function(){
beforeEach(function(){
this.statusMessage = this.stream.posts.models[0];
this.reshare = this.stream.posts.models[1];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
this.reshareElement = $(this.view.$("#" + this.reshare.get("guid")));
});
context("when rendering a status message", function(){
it("shows the message in the content area", function(){
expect(this.statusElement.find(".post-content p").text()).toContain("LONG POST"); //markdown'ed
});
});
});
describe('clicking read more', function() {
var readMoreLink;
beforeEach(function() {
this.statusMessage = this.stream.posts.models[0];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
readMoreLink = this.statusElement.find('.read-more a');
readMoreLink.text("read more");
});
it('expands the post', function() {
expect(this.statusElement.find('.collapsible .details').attr('style')).toContain('display: none;');
readMoreLink.click();
expect(this.statusElement.find('.collapsible .details').attr('style')).not.toContain('display: none;');
});
it('removes the read-more div', function() {
expect(this.statusElement.find('.read-more').length).toEqual(1);
readMoreLink.click();
expect(this.statusElement.find('.read-more').length).toEqual(0);
});
it('collapses the p elements on webkit', function() {
// The expander plugin has different behavior on firefox and webkit >.<
expect(this.statusElement.find('.collapsible p').length).toEqual(2);
readMoreLink.click();
if(this.statusElement.find('.collapsible .summary').length > 0) {
// Firefox
expect(this.statusElement.find('.collapsible p').length).toEqual(2);
} else {
// Chrome
expect(this.statusElement.find('.collapsible p').length).toEqual(1);
}
});
});
describe("infScroll", function(){
// NOTE: inf scroll happens at 500px
it("calls render when the user is at the bottom of the page", function(){
spyOn($.fn, "height").andReturn(0);
spyOn($.fn, "scrollTop").andReturn(100);
spyOn(this.view, "render");
this.view.infScroll();
expect(this.view.render).toHaveBeenCalled();
});
});
describe("removeLoader", function() {
it("emptys the pagination div when the stream is fetched", function(){
$("#jasmine_content").append($('<div id="paginate">OMG</div>'));
expect($("#paginate").text()).toBe("OMG");
this.view.stream.trigger("fetched");
expect($("#paginate")).toBeEmpty();
});
});
describe("unbindInfScroll", function(){
it("unbinds scroll", function() {
spyOn($.fn, "unbind");
this.view.unbindInfScroll();
expect($.fn.unbind).toHaveBeenCalledWith("scroll");
});
});
});
| describe("app.views.Stream", function(){
beforeEach(function(){
loginAs({name: "alice", avatar : {small : "http://avatar.com/photo.jpg"}});
this.posts = $.parseJSON(spec.readFixture("multi_stream_json"))["posts"];
this.stream = new app.models.Stream();
this.stream.add(this.posts);
this.view = new app.views.Stream({model : this.stream});
app.stream.bind("fetched", this.collectionFetched, this); //untested
// do this manually because we've moved loadMore into render??
this.view.render();
_.each(this.view.collection.models, function(post){ this.view.addPost(post); }, this);
});
describe("initialize", function(){
it("binds an infinite scroll listener", function(){
spyOn($.fn, "scroll");
new app.views.Stream({model : this.stream});
expect($.fn.scroll).toHaveBeenCalled();
});
});
describe("#render", function(){
beforeEach(function(){
this.statusMessage = this.stream.posts.models[0];
this.reshare = this.stream.posts.models[1];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
this.reshareElement = $(this.view.$("#" + this.reshare.get("guid")));
});
context("when rendering a status message", function(){
it("shows the message in the content area", function(){
expect(this.statusElement.find(".post-content p").text()).toContain("LONG POST"); //markdown'ed
});
});
});
describe('clicking read more', function() {
var readMoreLink;
beforeEach(function() {
this.statusMessage = this.stream.posts.models[0];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
readMoreLink = this.statusElement.find('.read-more a');
readMoreLink.text("read more");
});
it('expands the post', function() {
expect(this.statusElement.find('.collapsible .details').attr('style')).toContain('display: none;');
readMoreLink.click();
expect(this.statusElement.find('.collapsible .details').attr('style')).not.toContain('display: none;');
});
it('removes the read-more div', function() {
expect(this.statusElement.find('.read-more').length).toEqual(1);
readMoreLink.click();
expect(this.statusElement.find('.read-more').length).toEqual(0);
});
xit('collapses the p elements', function() {
// This does not work on firefox. Seems to be different behavior of the expander plugin. Needs more work.
expect(this.statusElement.find('.collapsible p').length).toEqual(2);
readMoreLink.click();
expect(this.statusElement.find('.collapsible p').length).toEqual(1);
});
});
describe("infScroll", function(){
// NOTE: inf scroll happens at 500px
it("calls render when the user is at the bottom of the page", function(){
spyOn($.fn, "height").andReturn(0);
spyOn($.fn, "scrollTop").andReturn(100);
spyOn(this.view, "render");
this.view.infScroll();
expect(this.view.render).toHaveBeenCalled();
});
});
describe("removeLoader", function() {
it("emptys the pagination div when the stream is fetched", function(){
$("#jasmine_content").append($('<div id="paginate">OMG</div>'));
expect($("#paginate").text()).toBe("OMG");
this.view.stream.trigger("fetched");
expect($("#paginate")).toBeEmpty();
});
});
describe("unbindInfScroll", function(){
it("unbinds scroll", function() {
spyOn($.fn, "unbind");
this.view.unbindInfScroll();
expect($.fn.unbind).toHaveBeenCalledWith("scroll");
});
});
});
| JavaScript | 0 |
5a5d8f8086c70f4cd328ea806e01e0e523fbcaa9 | Fix test | test/test.winston.js | test/test.winston.js | var expect = require('chai').expect;
var winstonSupport = require('../lib/winston');
var winston = require('winston');
var runServer = require('../lib/testHelper').runServer;
describe("winston", function(){
describe('name', function(){
it('should be "fluent"', function(done){
expect((new (winstonSupport.Transport)()).name).to.be.equal('fluent');
done();
});
});
describe('transport', function(){
it('should send log records', function(done){
runServer(function(server, finish){
var logger = new (winston.Logger)({
transports: [
new (winstonSupport.Transport)('debug', {port: server.port})
]
});
logger.info('foo %s', 'bar', {x: 1});
setTimeout(function(){
finish(function(data){
expect(data[0].tag).to.be.equal('debug');
expect(data[0].data).exist;
expect(data[0].time).exist;
expect(data[0].data.message).to.be.equal('foo bar');
expect(data[0].data.level).to.be.equal('info');
expect(data[0].data.meta.x).to.be.equal(1);
done();
});
}, 1000);
});
});
});
});
| var expect = require('chai').expect;
var winstonSupport = require('../lib/winston');
var winston = require('winston');
var runServer = require('../lib/testHelper').runServer;
describe("winston", function(){
describe('name', function(){
it('should be "fluent"', function(done){
expect(winstonSupport.name).to.be.equal('fluent');
done();
});
});
describe('transport', function(){
it('should send log records', function(done){
runServer(function(server, finish){
var logger = new (winston.Logger)({
transports: [
new (winstonSupport.Transport)('debug', {port: server.port})
]
});
logger.info('foo %s', 'bar', {x: 1});
setTimeout(function(){
finish(function(data){
expect(data[0].tag).to.be.equal('debug');
expect(data[0].data).exist;
expect(data[0].time).exist;
expect(data[0].data.message).to.be.equal('foo bar');
expect(data[0].data.level).to.be.equal('info');
expect(data[0].data.meta.x).to.be.equal(1);
done();
});
}, 1000);
});
});
});
});
| JavaScript | 0.000004 |
4d633f24b26d224580c3fef255fa352623fd982a | Use velocity to animate thread scroll for better performance | src/modules/Thread/events/scroll.js | src/modules/Thread/events/scroll.js | const {
headerHeight,
threadpostScrollDuration,
threadpostScrollHighlightDuration
} = window.appSettings;
export default function createPostScroller( $context ) {
return function (href) {
const $item = $context.find(href);
// $context.animate({
// scrollTop: offset - headerHeight
// }, threadpostScrollDuration);
$item.velocity('scroll', {
container: $context,
duration: threadpostScrollDuration,
offset: -headerHeight
});
$item.addClass('highlight');
setTimeout(() => $item.removeClass('highlight'),
threadpostScrollHighlightDuration
);
}
}
| const {
headerHeight,
threadpostScrollDuration,
threadpostScrollHighlightDuration
} = window.appSettings;
export default function createPostScroller( $context ) {
return function (href) {
const $item = $context.find(href);
const offset = $item[0].offsetTop;
console.log(`Post scrolled to has offset: "${offset}px"`);
$context.animate({
scrollTop: offset - headerHeight
}, threadpostScrollDuration);
$item.addClass('highlight');
setTimeout(() => $item.removeClass('highlight'),
threadpostScrollHighlightDuration
);
}
}
| JavaScript | 0.000004 |
fac54d5ba2296bd891dc60da065f7503af984f4e | Revert "We need an entity name" | blueprints/ember-cli-latex-maths/index.js | blueprints/ember-cli-latex-maths/index.js | module.exports = {
//description: '',
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
// afterInstall: function(options) {
// // Perform extra work here.
// }
afterInstall: function() {
return this.addBowerPackageToProject('katex'); // is a promise
}
};
| module.exports = {
//description: '',
normalizeEntityName: function() {}, // no-op since we're just adding dependencies
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
// afterInstall: function(options) {
// // Perform extra work here.
// }
afterInstall: function() {
return this.addBowerPackageToProject('katex'); // is a promise
}
};
| JavaScript | 0.000009 |
6c3f7569aa4e41f34d9447f1095b886e94e7c801 | Remove Error type as it is a javascript file | templates/expo-template-tabs/App.js | templates/expo-template-tabs/App.js | import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import AppNavigator from './navigation/AppNavigator';
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
async function loadResourcesAsync() {
await Promise.all([
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free to
// remove this if you are not using it in your app
'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
}),
]);
}
function handleLoadingError(error) {
// In this case, you might want to report the error to your error reporting
// service, for example Sentry
console.warn(error);
}
function handleFinishLoading(setLoadingComplete) {
setLoadingComplete(true);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
| import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import AppNavigator from './navigation/AppNavigator';
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
async function loadResourcesAsync() {
await Promise.all([
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free to
// remove this if you are not using it in your app
'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
}),
]);
}
function handleLoadingError(error: Error) {
// In this case, you might want to report the error to your error reporting
// service, for example Sentry
console.warn(error);
}
function handleFinishLoading(setLoadingComplete) {
setLoadingComplete(true);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
| JavaScript | 0.000001 |
a1f070f309dba348b5c537ae9efdc34cf622fa0b | handle condition where expected value is an empty string | test/acceptance/acceptance_tests.js | test/acceptance/acceptance_tests.js | const fs = require('fs');
const _ = require('lodash');
const tape = require('tape');
const filename = process.argv[2];
if (!filename) {
console.error('no source supplied');
process.exit(1);
}
if (!fs.existsSync(filename)) {
console.error(`file ${filename} not found`);
process.exit(1);
}
// this function matches the behavior of row_fxn_regexp in the machine, with the
// addition of trimming return values to match behavior later in the machine
function getActualValue(matcher, replace) {
// if a replace was specified, replace the matched groups
// eg - if matched groups are ["abc", "a", "c"] and replace is "$1:$2"
// then the output is "a:c"
if (matcher) {
if (replace) {
return matcher.reduce((acc, curr, idx) => {
// ignore the first matched group since it's the entire string
return idx === 0 ? acc : acc.replace(`$${idx}`, curr);
}, replace);
}
// otherwise, return the trimmed concatenation of all the matched groups
return matcher.slice(1).join('').trim();
}
return '';
}
function shouldRunAcceptanceTests(source) {
return source.test && // return false if there's no 'test' blob
_.get(source.test, 'enabled', true) && // default 'enabled' to true
_.get(source.test, 'acceptance-tests', []).length > 0;
}
fs.readFile(filename, (err, data) => {
const source = JSON.parse(data);
if (!shouldRunAcceptanceTests(source)) {
return;
}
// find all the conform fields that utilize the regexp function and compile
// them for later. The output of this is an object keyed on the regexp fields.
const fields_with_regexp = Object.keys(source.conform).reduce((acc, curr) => {
if (_.isObject(source.conform[curr]) && source.conform[curr]['function'] === 'regexp') {
acc[curr] = {
// which field to use from the test inputs blob
input_field: source.conform[curr].field,
regexp: new RegExp(source.conform[curr].pattern),
replace: source.conform[curr].replace
};
}
return acc;
}, {});
// iterate the tests, validating each
source.test['acceptance-tests'].forEach((acceptanceTest) => {
tape.test(`testing '${acceptanceTest.description}'`, (t) => {
// iterate the conform fields that use the regexp function
Object.keys(fields_with_regexp).forEach((field) => {
// figure out which input value to use from the inputs blob
const input_value = acceptanceTest.inputs[fields_with_regexp[field].input_field];
const expected_value = acceptanceTest.expected[field];
// run test only if test has input and expected value for this field
if (input_value && expected_value !== undefined) {
// the compiled regexp to match with
const regexp = fields_with_regexp[field].regexp;
// the specific match group(s) to use, if any
const replace = fields_with_regexp[field].replace;
// run the regex against the input value
const actual_value = getActualValue(input_value.match(regexp), replace);
t.equals(actual_value, expected_value,
`${field} field: expected '${expected_value}' from input '${input_value}'`);
}
});
t.end();
});
});
});
| const fs = require('fs');
const _ = require('lodash');
const tape = require('tape');
const filename = process.argv[2];
if (!filename) {
console.error('no source supplied');
process.exit(1);
}
if (!fs.existsSync(filename)) {
console.error(`file ${filename} not found`);
process.exit(1);
}
// this function matches the behavior of row_fxn_regexp in the machine, with the
// addition of trimming return values to match behavior later in the machine
function getActualValue(matcher, replace) {
// if a replace was specified, replace the matched groups
// eg - if matched groups are ["abc", "a", "c"] and replace is "$1:$2"
// then the output is "a:c"
if (matcher) {
if (replace) {
return matcher.reduce((acc, curr, idx) => {
// ignore the first matched group since it's the entire string
return idx === 0 ? acc : acc.replace(`$${idx}`, curr);
}, replace);
}
// otherwise, return the trimmed concatenation of all the matched groups
return matcher.slice(1).join('').trim();
}
}
function shouldRunAcceptanceTests(source) {
return source.test && // return false if there's no 'test' blob
_.get(source.test, 'enabled', true) && // default 'enabled' to true
_.get(source.test, 'acceptance-tests', []).length > 0;
}
fs.readFile(filename, (err, data) => {
const source = JSON.parse(data);
if (!shouldRunAcceptanceTests(source)) {
return;
}
// find all the conform fields that utilize the regexp function and compile
// them for later. The output of this is an object keyed on the regexp fields.
const fields_with_regexp = Object.keys(source.conform).reduce((acc, curr) => {
if (_.isObject(source.conform[curr]) && source.conform[curr]['function'] === 'regexp') {
acc[curr] = {
// which field to use from the test inputs blob
input_field: source.conform[curr].field,
regexp: new RegExp(source.conform[curr].pattern),
replace: source.conform[curr].replace
};
}
return acc;
}, {});
// iterate the tests, validating each
source.test['acceptance-tests'].forEach((acceptanceTest) => {
tape.test(`testing '${acceptanceTest.description}'`, (t) => {
// iterate the conform fields that use the regexp function
Object.keys(fields_with_regexp).forEach((field) => {
// figure out which input value to use from the inputs blob
const input_value = acceptanceTest.inputs[fields_with_regexp[field].input_field];
const expected_value = acceptanceTest.expected[field];
// run test only if test has input and expected value for this field
if (input_value && expected_value) {
// the compiled regexp to match with
const regexp = fields_with_regexp[field].regexp;
// the specific match group(s) to use, if any
const replace = fields_with_regexp[field].replace;
// run the regex against the input value
const actual_value = getActualValue(input_value.match(regexp), replace);
t.equals(actual_value, expected_value,
`${field} field: expected '${expected_value}' from input '${input_value}'`);
}
});
t.end();
});
});
});
| JavaScript | 0.00003 |
43ce6e09f4fbe8f3fc5fe09d5b5986d4ee57ea55 | fix auth.account data util | test/data/auth/account-data-util.js | test/data/auth/account-data-util.js | "use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
var Role = require("./role-data-util");
class AccountDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/auth/account-manager");
return _getSert(input, ManagerType, (data) => {
return {
username: data.username
};
});
}
getNewData() {
return Role.getTestData()
.then((role) => {
var Model = require("spot-models").auth.Account;
var data = new Model();
var code = generateCode();
data.username = `${code}@unit.test`;
data.password = "Standar123";
data.email = `${code}@unit.test`;
data.isLocked = false;
data.profile = {
firstname: "John",
lastname: code,
gender: "M",
dob: new Date(),
email: `${code}@unit.test`
};
data.roles = [role];
data.facebook = {};
return Promise.resolve(data);
});
}
getTestData() {
return this.getNewData()
.then((data) => {
data.username = "dev";
data.email = "dev@unit.test";
data.profile.firstname = "Test";
data.profile.lastname = "Unit";
data.profile.email = "dev@unit.test";
data.profile.gender = "M";
data.profile.dob = new Date();
return this.getSert(data);
});
}
}
module.exports = new AccountDataUtil();
| "use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
var Role = require("./role-data-util");
class AccountDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/auth/account-manager");
return _getSert(input, ManagerType, (data) => {
return {
username: data.username
};
});
}
getNewData() {
return Role.getTestData()
.then((role) => {
var Model = require("spot-models").auth.Account;
var data = new Model();
var code = generateCode();
data.username = `${code}@unit.test`;
data.password = "Standar123";
data.email = `${code}@unit.test`;
data.isLocked = false;
data.profile = {
firstname: "John",
lastname: code,
gender: "M",
dob: new Date(),
email: `${code}@unit.test`
};
data.roles = [role];
data.facebook = {};
return Promise.resolve(data);
});
}
getTestData() {
return this.getNewData()
.then((data) => {
data.username = "dev";
data.email = "dev@unit.test";
data.profile.firstname = "Test";
data.profile.lastname = "Unit";
return this.getSert(data);
});
}
}
module.exports = new AccountDataUtil();
| JavaScript | 0.000028 |
a978d3d342c20c4071005397ef316ee0bb216fbe | Increase wait-time for glob return | test/new-server/cli-get-fileSpec.js | test/new-server/cli-get-fileSpec.js | 'use strict';
var module = require('../../lib/index');
var setup = module.setup;
var file1 = "test/fixtures/index.html";
var file2 = "test/fixtures/forms.html";
var file3 = "test/fixtures/scrolling.html";
var css = "test/fixtures/assets/style.css";
var scss = "test/fixtures/scss/main.scss";
describe("Style Injector: transform the files option into useable watchers", function () {
it("can load", function () {
expect(setup).toBeDefined();
});
describe("When getting single files with a string", function () {
var files;
var cb;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return an array of files even if only 1 file", function () {
files = setup.getFiles(file1, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1]);
});
});
it("should return an array of files if an array given", function () {
files = setup.getFiles([file1, file2], cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("when getting multiple files given as strings", function () {
describe("When the files DO exist", function () {
var files = [file1, file2];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("When the files DO NOT exist", function () {
//
var files = ["test/fixtures/index.html", "test/fixtures/kittie.html"];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith(["test/fixtures/index.html"]);
});
});
});
});
describe("Getting files from a glob", function () {
var cb;
var files;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return files from a single glob string", function () {
files = setup.getFiles("test/fixtures/*.html", cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3]);
});
});
it("should return files from an array of globs", function () {
files = setup.getFiles([
"test/fixtures/*.html",
"test/fixtures/assets/*.css",
"test/fixtures/scss/*.scss"], cb);
waits(300);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3, css, scss]);
});
});
});
}); | 'use strict';
var module = require('../../lib/index');
var setup = module.setup;
var file1 = "test/fixtures/index.html";
var file2 = "test/fixtures/forms.html";
var file3 = "test/fixtures/scrolling.html";
var css = "test/fixtures/assets/style.css";
var scss = "test/fixtures/scss/main.scss";
describe("Style Injector: transform the files option into useable watchers", function () {
it("can load", function () {
expect(setup).toBeDefined();
});
describe("When getting single files with a string", function () {
var files;
var cb;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return an array of files even if only 1 file", function () {
files = setup.getFiles(file1, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1]);
});
});
it("should return an array of files if an array given", function () {
files = setup.getFiles([file1, file2], cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("when getting multiple files given as strings", function () {
describe("When the files DO exist", function () {
var files = [file1, file2];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("When the files DO NOT exist", function () {
//
var files = ["test/fixtures/index.html", "test/fixtures/kittie.html"];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith(["test/fixtures/index.html"]);
});
});
});
});
describe("Getting files from a glob", function () {
var cb;
var files;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return files from a single glob string", function () {
files = setup.getFiles("test/fixtures/*.html", cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3]);
});
});
it("should return files from an array of globs", function () {
files = setup.getFiles([
"test/fixtures/*.html",
"test/fixtures/assets/*.css",
"test/fixtures/scss/*.scss"], cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3, css, scss]);
});
});
});
}); | JavaScript | 0.000001 |
785151564291dcc0d1482758b3a723976f4878d7 | fix in content visibility | src/javascript/static/pages/home.js | src/javascript/static/pages/home.js | const Login = require('../../_common/base/login');
const localize = require('../../_common/localize').localize;
const State = require('../../_common/storage').State;
const TabSelector = require('../../_common/tab_selector');
const urlFor = require('../../_common/url').urlFor;
const BinaryPjax = require('../../app/base/binary_pjax');
const BinarySocket = require('../../app/base/socket');
const isEuCountry = require('../../app/common/country_base').isEuCountry;
const FormManager = require('../../app/common/form_manager');
const isBinaryApp = require('../../config').isBinaryApp;
const Home = (() => {
let clients_country;
const onLoad = () => {
TabSelector.onLoad();
BinarySocket.wait('website_status', 'authorize', 'landing_company').then(() => {
clients_country = State.getResponse('website_status.clients_country');
// we need to initiate selector after it becoming visible
TabSelector.repositionSelector();
const form_id = '#frm_verify_email';
FormManager.init(form_id, [
{ selector: '#email', validations: ['req', 'email'], request_field: 'verify_email' },
{ request_field: 'type', value: 'account_opening' },
]);
FormManager.handleSubmit({
form_selector : form_id,
fnc_response_handler: handler,
fnc_additional_check: checkCountry,
});
socialLogin();
if (isEuCountry()) {
$('.mfsa_message').slideDown(300);
}
});
};
const socialLogin = () => {
$('#google-signup').off('click').on('click', (e) => {
e.preventDefault();
window.location.href = Login.socialLoginUrl('google');
});
};
const checkCountry = (req) => {
if ((clients_country !== 'my') || /@binary\.com$/.test(req.verify_email)) {
return true;
}
$('#frm_verify_email').find('div')
.html($('<p/>', { class: 'notice-msg center-text', html: localize('Sorry, account signup is not available in your country.') }));
return false;
};
const handler = (response) => {
const error = response.error;
if (error) {
$('#signup_error').setVisibility(1).text(error.message);
} else if (isBinaryApp()) {
BinaryPjax.load(urlFor('new_account/virtualws'));
} else {
$('.signup-box div').replaceWith($('<p/>', { text: localize('Thank you for signing up! Please check your email to complete the registration process.'), class: 'gr-10 gr-centered center-text' }));
$('#social-signup').setVisibility(0);
}
};
const onUnload = () => {
TabSelector.onUnload();
};
return {
onLoad,
onUnload,
};
})();
module.exports = Home;
| const Login = require('../../_common/base/login');
const localize = require('../../_common/localize').localize;
const State = require('../../_common/storage').State;
const TabSelector = require('../../_common/tab_selector');
const urlFor = require('../../_common/url').urlFor;
const BinaryPjax = require('../../app/base/binary_pjax');
const BinarySocket = require('../../app/base/socket');
const isEuCountry = require('../../app/common/country_base').isEuCountry;
const FormManager = require('../../app/common/form_manager');
const isBinaryApp = require('../../config').isBinaryApp;
const Home = (() => {
let clients_country;
const onLoad = () => {
TabSelector.onLoad();
BinarySocket.wait('website_status', 'authorize', 'landing_company').then(() => {
clients_country = State.getResponse('website_status.clients_country');
// we need to initiate selector after it becoming visible
TabSelector.repositionSelector();
const form_id = '#frm_verify_email';
FormManager.init(form_id, [
{ selector: '#email', validations: ['req', 'email'], request_field: 'verify_email' },
{ request_field: 'type', value: 'account_opening' },
]);
FormManager.handleSubmit({
form_selector : form_id,
fnc_response_handler: handler,
fnc_additional_check: checkCountry,
});
socialLogin();
if (isEuCountry()) {
$('.mfsa_message').slideDown(300);
$('.eu-hide').setVisibility(0);
}
});
};
const socialLogin = () => {
$('#google-signup').off('click').on('click', (e) => {
e.preventDefault();
window.location.href = Login.socialLoginUrl('google');
});
};
const checkCountry = (req) => {
if ((clients_country !== 'my') || /@binary\.com$/.test(req.verify_email)) {
return true;
}
$('#frm_verify_email').find('div')
.html($('<p/>', { class: 'notice-msg center-text', html: localize('Sorry, account signup is not available in your country.') }));
return false;
};
const handler = (response) => {
const error = response.error;
if (error) {
$('#signup_error').setVisibility(1).text(error.message);
} else if (isBinaryApp()) {
BinaryPjax.load(urlFor('new_account/virtualws'));
} else {
$('.signup-box div').replaceWith($('<p/>', { text: localize('Thank you for signing up! Please check your email to complete the registration process.'), class: 'gr-10 gr-centered center-text' }));
$('#social-signup').setVisibility(0);
}
};
const onUnload = () => {
TabSelector.onUnload();
};
return {
onLoad,
onUnload,
};
})();
module.exports = Home;
| JavaScript | 0.000003 |
643c4f809de50861fcc63df149d56a8034340ad3 | Add differencesById function to get the differences between to arrays of objects that contain an 'id' field. | website/app/index/util.js | website/app/index/util.js | function isImage(mime) {
switch (mime) {
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
case "image/x-ms-bmp":
case "image/bmp":
return true;
default:
return false;
}
}
function numberWithCommas(n) {
n = n.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(n)) {
n = n.replace(pattern, "$1,$2");
}
return n;
}
function bytesToSizeStr(bytes) {
if(bytes === 0) return '0 Byte';
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function _add_json_callback(url) {
return url + "&callback=JSON_CALLBACK";
}
function _add_json_callback2(url) {
var qIndex = url.indexOf("?");
var argSeparator = "&";
if (qIndex == -1) {
argSeparator = "?";
}
return url + argSeparator + "callback=JSON_CALLBACK";
}
function differenceById(from, others) {
var idsFrom = from.map(function(entry) {
return entry.id;
});
var idsOthers = others.map(function(entry) {
return entry.id;
});
var diff = _.difference(idsFrom, idsOthers);
return from.filter(function(entry) {
return _.indexOf(diff, function(e) {
return e == entry.id;
}) !== -1;
})
}
String.prototype.capitalize = function () {
return this.replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
};
// save a reference to the core implementation
var indexOfValue = _.indexOf;
// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({
// return the index of the first array element passing a test
indexOf: function (array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}
});
| function isImage(mime) {
switch (mime) {
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
case "image/x-ms-bmp":
case "image/bmp":
return true;
default:
return false;
}
}
function numberWithCommas(n) {
n = n.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(n)) {
n = n.replace(pattern, "$1,$2");
}
return n;
}
function bytesToSizeStr(bytes) {
if(bytes === 0) return '0 Byte';
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function _add_json_callback(url) {
return url + "&callback=JSON_CALLBACK";
}
function _add_json_callback2(url) {
var qIndex = url.indexOf("?");
var argSeparator = "&";
if (qIndex == -1) {
argSeparator = "?";
}
return url + argSeparator + "callback=JSON_CALLBACK";
}
String.prototype.capitalize = function () {
return this.replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
};
// save a reference to the core implementation
var indexOfValue = _.indexOf;
// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({
// return the index of the first array element passing a test
indexOf: function (array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}
});
| JavaScript | 0 |
3a4825862bae25157bbfefe51eb0d9a9f70b1d8e | Add test on robot to check instanciation with serialPort | tests/server/robot_test.js | tests/server/robot_test.js | var chai = require('chai');
var expect = chai.expect;
var Robot = require('../../src/Robot');
var sinon = require('sinon');
describe('Robot', function() {
describe('#contructor', function() {
it('should be instanciate', function() {
var robot = new Robot
expect(robot).to.be.instanceof(Robot);
});
it('should be instanciate with an adapater', function() {
var fakeAdapter = {};
var robot = new Robot(fakeAdapter);
expect(robot.serialPort).to.deep.equal({});
});
});
describe('#setSpeed', function() {
it('should set speed with an amplitude and alpha', function() {
var robot = new Robot();
robot.setSpeed(2, 100);
expect(robot.x).to.be.equal(-42);
expect(robot.y).to.be.equal(-91);
});
});
describe('#move', function() {
var sandbox;
var fakeSerialPort;
var robot;
beforeEach(function() {
sandbox = sinon.sandbox.create();
fakeSerialPort = {
write: sinon.spy()
};
robot = new Robot(fakeSerialPort);
robot.x = 41;
robot.y = 90;
});
it('should write x,y on serial port', function(done) {
robot.move();
sinon.assert.calledWithExactly(fakeSerialPort.write, sinon.match(function(value) {
return JSON.stringify(value.toJSON())=== JSON.stringify([robot.x, robot.y]);
}));
done();
});
afterEach(function(done) {
sandbox.restore();
done();
});
});
});
| var chai = require('chai');
var expect = chai.expect;
var Robot = require('../../src/Robot');
var sinon = require('sinon');
describe('Robot', function() {
describe('#contructor', function() {
it('should be instanciate', function() {
var robot = new Robot
expect(robot).to.be.instanceof(Robot);
});
it('should be instanciate with an adapater', function() {
var robot = new Robot();
});
});
describe('#setSpeed', function() {
it('should set speed with an amplitude and alpha', function() {
var robot = new Robot();
robot.setSpeed(2, 100);
expect(robot.x).to.be.equal(-42);
expect(robot.y).to.be.equal(-91);
});
});
describe('#move', function() {
var sandbox;
var fakeSerialPort;
var robot;
beforeEach(function() {
sandbox = sinon.sandbox.create();
fakeSerialPort = {
write: sinon.spy()
};
robot = new Robot(fakeSerialPort);
robot.x = 41;
robot.y = 90;
});
it('should write x,y on serial port', function(done) {
robot.move();
sinon.assert.calledWithExactly(fakeSerialPort.write, sinon.match(function(value) {
return JSON.stringify(value.toJSON())=== JSON.stringify([robot.x, robot.y]);
}));
done();
});
afterEach(function(done) {
sandbox.restore();
done();
});
});
});
| JavaScript | 0 |
52f786328eba779610777cf14b7943e7d8cab282 | Disable import/export linting rule since it will fail when only one action is defined, but pass on mutliple actions | generators/root/templates/action/const.js | generators/root/templates/action/const.js | /* eslint-disable import/prefer-default-export */
/* Populated by react-webpack-redux:action */
| /* Populated by react-webpack-redux:action */
| JavaScript | 0 |
077407297bc919cf829aaf60b4236a326c49d436 | improve build config | scripts/rollup.config.js | scripts/rollup.config.js | import commonjs from 'rollup-plugin-commonjs'
import nodeResolve from 'rollup-plugin-node-resolve'
import json from 'rollup-plugin-json'
import babel from 'rollup-plugin-babel'
import buble from 'rollup-plugin-buble'
import { terser } from 'rollup-plugin-terser'
import defaultsDeep from 'lodash/defaultsDeep'
const pkg = require('../package.json')
const banner = `/**
* vue-meta v${pkg.version}
* (c) ${new Date().getFullYear()} Declan de Wet & Sébastien Chopin (@Atinux)
* @license MIT
*/
`.replace(/ {4}/gm, '').trim()
function rollupConfig({
plugins = [],
...config
}) {
return defaultsDeep({}, config, {
input: 'src/browser.js',
output: {
name: 'VueMeta',
format: 'umd',
sourcemap: false,
banner
},
plugins: [
json(),
nodeResolve()
].concat(plugins),
})
}
const babelConfig = {
runtimeHelpers: true,
exclude : 'node_modules/**',
presets: [['@nuxt/babel-preset-app', {
// useBuiltIns: 'usage',
// target: { ie: 9 }
}]]
}
export default [
rollupConfig({
output: {
file: pkg.web,
},
plugins: [
babel(babelConfig),
commonjs()
]
}),
rollupConfig({
output: {
file: pkg.web.replace('.js', '.min.js'),
},
plugins: [
babel(babelConfig),
commonjs(),
terser()
]
}),
rollupConfig({
input: 'src/index.js',
output: {
file: pkg.main,
format: 'cjs'
},
plugins: [
commonjs()
],
external: Object.keys(pkg.dependencies)
})
]
| import commonjs from 'rollup-plugin-commonjs'
import nodeResolve from 'rollup-plugin-node-resolve'
import json from 'rollup-plugin-json'
import babel from 'rollup-plugin-babel'
import buble from 'rollup-plugin-buble'
import { terser } from 'rollup-plugin-terser'
const pkg = require('../package.json')
const banner = `/**
* vue-meta v${pkg.version}
* (c) ${new Date().getFullYear()} Declan de Wet & Sébastien Chopin (@Atinux)
* @license MIT
*/
`.replace(/ {4}/gm, '').trim()
const baseConfig = {
input: 'src/browser.js',
output: {
file: pkg.web,
format: 'umd',
name: 'VueMeta',
sourcemap: false,
banner
},
plugins: [
json(),
nodeResolve(),
commonjs(),
/*buble({
objectAssign: 'Object.assign'
}),*/
]
}
export default [{
...baseConfig,
}, {
...baseConfig,
output: {
...baseConfig.output,
file: pkg.web.replace('.js', '.min.js'),
},
plugins: [
...baseConfig.plugins,
babel({
runtimeHelpers: true,
presets: ['@nuxt/babel-preset-app']
}),
terser()
]
}, {
...baseConfig,
input: 'src/index.js',
output: {
...baseConfig.output,
file: pkg.main,
format: 'cjs'
},
external: Object.keys(pkg.dependencies)
}]
| JavaScript | 0.000022 |
7777b2f6b31d3ea8366af600811a8ac13871d302 | Update EnvironmentPlugin TODO comment | lib/EnvironmentPlugin.js | lib/EnvironmentPlugin.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./WebpackError");
/** @typedef {import("./Compiler")} Compiler */
const needsEnvVarFix =
["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
process.platform === "win32";
class EnvironmentPlugin {
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues = keys[0];
} else {
this.keys = keys;
this.defaultValues = {};
}
}
/**
* @param {Compiler} compiler webpack compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.keys.reduce((defs, key) => {
// NOTE remove once the required node version is >=8.10.0.
// Work around https://github.com/nodejs/node/pull/18463,
// affecting Node 8 & 9 by performing an OS-level
// operation that always succeeds before reading
// environment variables:
if (needsEnvVarFix) require("os").cpus();
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
if (value === undefined) {
compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
const error = new WebpackError(
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.warnings.push(error);
});
}
defs[`process.env.${key}`] =
value === undefined ? "undefined" : JSON.stringify(value);
return defs;
}, {});
new DefinePlugin(definitions).apply(compiler);
}
}
module.exports = EnvironmentPlugin;
| /*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./WebpackError");
/** @typedef {import("./Compiler")} Compiler */
const needsEnvVarFix =
["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
process.platform === "win32";
class EnvironmentPlugin {
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues = keys[0];
} else {
this.keys = keys;
this.defaultValues = {};
}
}
/**
* @param {Compiler} compiler webpack compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.keys.reduce((defs, key) => {
// TODO remove once the fix has made its way into Node 8.
// Work around https://github.com/nodejs/node/pull/18463,
// affecting Node 8 & 9 by performing an OS-level
// operation that always succeeds before reading
// environment variables:
if (needsEnvVarFix) require("os").cpus();
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
if (value === undefined) {
compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
const error = new WebpackError(
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.warnings.push(error);
});
}
defs[`process.env.${key}`] =
value === undefined ? "undefined" : JSON.stringify(value);
return defs;
}, {});
new DefinePlugin(definitions).apply(compiler);
}
}
module.exports = EnvironmentPlugin;
| JavaScript | 0 |
cea687e75c54459b2d04ee3d65bbb994cfccb66e | Update locales verify script to count special chars | scripts/locales/verify.js | scripts/locales/verify.js | const fs = require('fs')
const path = require('path')
const defaultLocale = require('../../src/config.js').bot.locale
const COLORS = {
BRIGHT: '\x1b[1m',
RESET: '\x1b[0m',
RED: '\x1b[31m',
GREEN: '\x1b[32m',
CYAN: '\x1b[36m'
}
const CONSTANT_CHARACTERS = ['"', '\n', '`']
const referenceLocaleData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', `${defaultLocale}.json`)))
const fileNames = fs.readdirSync(path.join(__dirname, '..', '..', 'src', 'locales'))
const errorStringsByLocale = {}
function traverse (object, reference, location, locale) {
for (const key in reference) {
if (typeof reference[key] !== typeof object[key]) {
errorStringsByLocale[locale].push(`${COLORS.CYAN}${location}[${key}]${COLORS.RESET} expected ${COLORS.GREEN}${typeof reference[key]}${COLORS.RESET} but found ${COLORS.RED}${typeof object[key]}${COLORS.RESET}`)
} else if (typeof reference[key] === 'object') {
traverse(object[key], reference[key], location + `[${key}]`, locale)
} else if (typeof reference[key] === 'string' && object[key].length > 0) {
for (const character of CONSTANT_CHARACTERS) {
const referenceCharCount = (reference[key].match(new RegExp(character, 'g')) || []).length
const charCount = (object[key].match(new RegExp(character, 'g')) || []).length
if (referenceCharCount !== charCount) {
const printCharacter = character === '\n' ? '\\n' : character
errorStringsByLocale[locale].push(`${COLORS.CYAN}${location}[${key}]${COLORS.RESET} expected ${COLORS.GREEN}${referenceCharCount} ${COLORS.BRIGHT}${printCharacter}${COLORS.RESET} character(s)${COLORS.RESET} but found ${COLORS.RED}${charCount} ${COLORS.BRIGHT}${printCharacter}${COLORS.RESET} character(s)`)
}
}
}
}
}
for (const fileName of fileNames) {
if (fileName === 'en-US.json') {
continue
}
const localeData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', fileName)))
const locale = fileName.replace('.json', '')
errorStringsByLocale[locale] = []
traverse(localeData, referenceLocaleData, locale, locale)
}
const okStrings = []
const errorStrings = []
for (const locale in errorStringsByLocale) {
const strings = errorStringsByLocale[locale]
if (strings.length === 0) {
okStrings.push(`${COLORS.GREEN}√${COLORS.RESET} ${locale} ${locale === 'en-US' ? '(Reference)' : ''}`)
continue
}
// Prettify the logs
let longestLocation = 0
for (const line of strings) {
const parts = line.split('expected')
const location = parts[0]
if (location.length > longestLocation) {
longestLocation = location.length
}
}
for (let i = 0; i < strings.length; ++i) {
const parts = strings[i].split('expected')
let location = parts[0]
while (location.length < longestLocation) {
location += ' '
}
parts[0] = location
strings[i] = parts.join('expected')
}
errorStrings.push(`${COLORS.RED}X${COLORS.RESET} ${locale}\n${strings.join('\n')}`)
}
console.log(okStrings.join('\n'))
console.log(errorStrings.join('\n'))
console.log(`\nNote that for untranslated strings, their values must be "" (an empty string). They cannot be undefined.\nEmpty string translations will fall back to using the default en-US strings.`) | const fs = require('fs')
const path = require('path')
const defaultLocale = require('../../src/config.js').bot.locale
const COLORS = {
RESET: '\x1b[0m',
RED: '\x1b[31m',
GREEN: '\x1b[32m',
CYAN: '\x1b[36m'
}
const referenceLocaleData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', `${defaultLocale}.json`)))
const fileNames = fs.readdirSync(path.join(__dirname, '..', '..', 'src', 'locales'))
const errorStringsByLocale = {}
function traverse (object, reference, location, locale) {
for (const key in reference) {
if (typeof reference[key] !== typeof object[key]) {
errorStringsByLocale[locale].push(`${COLORS.CYAN}${location}[${key}]${COLORS.RESET} expected ${COLORS.GREEN}${typeof reference[key]}${COLORS.RESET} but found ${COLORS.RED}${typeof object[key]}${COLORS.RESET}`)
} else if (typeof reference[key] === 'object' && typeof object[key] === 'object') {
traverse(object[key], reference[key], location + `[${key}]`, locale)
}
}
}
for (const fileName of fileNames) {
const localeData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', fileName)))
const locale = fileName.replace('.json', '')
errorStringsByLocale[locale] = []
traverse(localeData, referenceLocaleData, locale, locale)
}
const okStrings = []
const errorStrings = []
for (const locale in errorStringsByLocale) {
const strings = errorStringsByLocale[locale]
if (strings.length === 0) {
okStrings.push(`${COLORS.GREEN}√${COLORS.RESET} ${locale} ${locale === 'en-US' ? '(Reference)' : ''}`)
continue
}
// Prettify the logs
let longestLocation = 0
for (const line of strings) {
const parts = line.split('expected')
const location = parts[0]
if (location.length > longestLocation) {
longestLocation = location.length
}
}
for (let i = 0; i < strings.length; ++i) {
const parts = strings[i].split('expected')
let location = parts[0]
while (location.length < longestLocation) {
location += ' '
}
parts[0] = location
strings[i] = parts.join('expected')
}
errorStrings.push(`${COLORS.RED}X${COLORS.RESET} ${locale}\n${strings.join('\n')}`)
}
console.log(okStrings.join('\n'))
console.log(errorStrings.join('\n'))
console.log(`\nNote that for untranslated strings, their values must be "" (an empty string). They cannot be undefined.\nEmpty string translations will fall back to using the default en-US strings.`) | JavaScript | 0 |
bd697ab9f5db3f6e9377f93c5b946795b59eab28 | update vendor bundle to include new packages | webpack.config.vendor.js | webpack.config.vendor.js | const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
var AssetsPlugin = require('assets-webpack-plugin');
var assetsPluginInstance = new AssetsPlugin({ filename: 'vendor-assets.json' });
const BUILD_DIR = path.resolve(__dirname, 'public');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: ['.js'] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
entry: {
vendor: [
'bootstrap',
'babel-polyfill',
'event-source-polyfill',
'react',
'react-async-script',
'react-bootstrap-slider',
'react-bootstrap-typeahead',
'react-google-recaptcha',
'react-dom',
'react-redux',
'react-redux-toastr',
'redux',
'redux-thunk',
'jquery',
'jquery-migrate',
'jquery-nearest',
'jquery-validation',
'jquery-validation-unobtrusive',
'moment',
'prop-types',
'socket.io-client',
'underscore',
'query-string',
'path-to-regexp'
]
},
devtool: isDevBuild ? 'inline-source-map' : 'source-map',
output: {
publicPath: '/',
filename: '[name]-[hash].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new webpack.NormalModuleReplacementPlugin(/\/iconv-loader$/, require.resolve('node-noop')), // Workaround for https://github.com/andris9/encoding/issues/16
assetsPluginInstance
]
};
const clientBundleConfig = merge(sharedConfig, {
output: { path: BUILD_DIR },
module: {
rules: [
]
},
plugins: [
new webpack.DllPlugin({
path: path.join(BUILD_DIR, '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return clientBundleConfig;
};
| const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
var AssetsPlugin = require('assets-webpack-plugin');
var assetsPluginInstance = new AssetsPlugin({ filename: 'vendor-assets.json' });
const BUILD_DIR = path.resolve(__dirname, 'public');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: ['.js'] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
entry: {
vendor: [
'bootstrap',
'babel-polyfill',
'event-source-polyfill',
'react',
'react-async-script',
'react-bootstrap-slider',
'react-bootstrap-typeahead',
'react-google-recaptcha',
'react-dom',
'react-redux',
'react-redux-toastr',
'redux',
'redux-thunk',
'jquery',
'jquery-migrate',
'jquery-nearest',
'jquery-validation',
'jquery-validation-unobtrusive',
'moment',
'prop-types',
'socket.io-client',
'underscore'
]
},
devtool: isDevBuild ? 'inline-source-map' : 'source-map',
output: {
publicPath: '/',
filename: '[name]-[hash].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new webpack.NormalModuleReplacementPlugin(/\/iconv-loader$/, require.resolve('node-noop')), // Workaround for https://github.com/andris9/encoding/issues/16
assetsPluginInstance
]
};
const clientBundleConfig = merge(sharedConfig, {
output: { path: BUILD_DIR },
module: {
rules: [
]
},
plugins: [
new webpack.DllPlugin({
path: path.join(BUILD_DIR, '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return clientBundleConfig;
};
| JavaScript | 0 |
7fe248ce228359a0e5e00fc229df2d032614a9d5 | Allow more powerful overrides in lazylinkfield | src/resources/elements/lazylinkfield.js | src/resources/elements/lazylinkfield.js | import {containerless} from 'aurelia-framework';
import {Field} from './abstract/field';
/**
* LazyLinkfield is a field that lazily proxies the a whole field (value & UI)
* to another place.
*/
@containerless
export class LazyLinkfield extends Field {
target = '#';
overrides = {};
_child = undefined;
/** @inheritdoc */
init(id = '', args = {}) {
this.target = args.target || '#';
this.overrides = args.overrides || {};
return super.init(id, args);
}
createChild() {
this._child = this.resolveRef(this.target).clone();
this._child.parent = this;
for (const [field, value] of Object.entries(this.overrides)) {
let target;
let fieldPath;
if (field.includes(';')) {
[elementPath, fieldPath] = field.split(';');
fieldPath = fieldPath.split('/');
target = this._child.resolveRef(elementPath);
} else {
fieldPath = field.split('/');
target = this._child;
}
const lastFieldPathEntry = fieldPath.splice(-1)[0];
target = this.resolveRawPath(target, fieldPath);
if (value === null) {
delete target[lastFieldPathEntry];
} else {
target[lastFieldPathEntry] = value;
}
}
}
resolveRawPath(object, path) {
if (path.length === 0) {
return object;
} else if (path[0] === '#') {
return this.resolveRawPath(object, path.splice(1));
}
return this.resolveRawPath(object[path[0]], path.splice(1));
}
deleteChild() {
this._child = undefined;
}
shouldDisplay() {
const display = super.shouldDisplay();
if (display) {
if (this._child === undefined) {
this.createChild();
}
} else if (this._child !== undefined) {
this.deleteChild();
}
return display;
}
get child() {
return this.display ? this._child : undefined;
}
/**
* Set the value of the target field.
*
* @override
* @param {Object} value The new value to set to the target field.
*/
setValue(value) {
if (!this._child) {
return;
}
this._child.setValue(value);
}
/**
* Get the value of the target field.
*
* @override
* @return {Object} The value of the target field, or undefined if
* {@link #resolveTarget} returns {@linkplain undefined}.
*/
getValue() {
return this._child ? this._child.getValue() : undefined;
}
}
| import {containerless} from 'aurelia-framework';
import {Field} from './abstract/field';
/**
* LazyLinkfield is a field that lazily proxies the a whole field (value & UI)
* to another place.
*/
@containerless
export class LazyLinkfield extends Field {
target = '#';
overrides = {};
_child = undefined;
/** @inheritdoc */
init(id = '', args = {}) {
this.target = args.target || '#';
this.overrides = args.overrides || {};
return super.init(id, args);
}
createChild() {
this._child = this.resolveRef(this.target).clone();
this._child.parent = this;
for (const [field, value] of Object.entries(this.overrides)) {
const lastSlash = field.lastIndexOf('/');
const path = field.substr(0, lastSlash);
const fieldName = field.substr(lastSlash + 1, field.length);
this._child.resolveRef(path)[fieldName] = value;
}
}
deleteChild() {
this._child = undefined;
}
shouldDisplay() {
const display = super.shouldDisplay();
if (display) {
if (this._child === undefined) {
this.createChild();
}
} else if (this._child !== undefined) {
this.deleteChild();
}
return display;
}
get child() {
return this.display ? this._child : undefined;
}
/**
* Set the value of the target field.
*
* @override
* @param {Object} value The new value to set to the target field.
*/
setValue(value) {
if (!this._child) {
return;
}
this._child.setValue(value);
}
/**
* Get the value of the target field.
*
* @override
* @return {Object} The value of the target field, or undefined if
* {@link #resolveTarget} returns {@linkplain undefined}.
*/
getValue() {
return this._child ? this._child.getValue() : undefined;
}
}
| JavaScript | 0 |
f24b7ba1d4c03810d84f35c0e75919d216817851 | Add missing js | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Index.js | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Index.js | import {Ajax} from './Framework/Ajax'
import {Form} from './Framework/Form'
import {Link} from './Framework/Link'
import {LoadingBar} from './Framework/LoadingBar'
import {Navbar} from './Framework/Navbar'
import {Popover} from './Framework/Popover'
import {Scrolling} from './Framework/Scrolling'
import {SetHeight} from './Framework/SetHeight'
import {Searchbar} from './Framework/Searchbar'
import {Select} from './Framework/Select'
import {Slider} from './Framework/Slider'
import {Sortable} from './Framework/Sortable'
import {Table} from './Framework/Table'
import {Tabs} from './Framework/Tabs'
import {Tooltip} from './Framework/Tooltip'
export class Index {
constructor () {
this.ajax = new Ajax()
this.form = new Form()
this.link = new Link()
this.loadingBar = new LoadingBar()
this.navbar = new Navbar()
this.scrolling = new Scrolling()
this.setHeight = new SetHeight()
this.searchBar = new Searchbar()
this.table = new Table()
this.tabs = new Tabs()
this.initializeSliders()
this.initializeSortables()
this.initializePopovers()
this.initializeTooltips()
this.initializeSelects()
this.initializeOtherChoiceTypes()
}
initializeSliders () {
$('.slider').each((index, element) => {
element.slider = new Slider($(element))
})
}
initializeSortables () {
$('.sortable').each((index, element) => {
element.sortable = new Sortable($(element))
})
}
initializePopovers () {
$('[data-toggle="popover"]').each((index, element) => {
element.popover = new Popover($(element))
})
}
initializeTooltips () {
$('[data-toggle="tooltip"]').each((index, element) => {
element.tooltip = new Tooltip($(element))
})
}
initializeSelects () {
$('.select2').each((index, element) => {
element.select2 = new Select($(element))
})
}
initializeOtherChoiceTypes () {
$(function() {
$('[data-role=other-choice-list]').on('change', function() {
let $select = $(this)
let $textField = $select.closest('[data-role=other-choice-wrapper]').find('[data-role=other-choice-text-input]')
if ($select.val() === 'other') {
$textField.show().focus()
$select.hide()
return
}
$textField.hide()
$select.show()
}).trigger('change')
})
}
}
window.index = new Index()
| import {Ajax} from './Framework/Ajax'
import {Form} from './Framework/Form'
import {Link} from './Framework/Link'
import {LoadingBar} from './Framework/LoadingBar'
import {Navbar} from './Framework/Navbar'
import {Popover} from './Framework/Popover'
import {Scrolling} from './Framework/Scrolling'
import {SetHeight} from './Framework/SetHeight'
import {Searchbar} from './Framework/Searchbar'
import {Select} from './Framework/Select'
import {Slider} from './Framework/Slider'
import {Sortable} from './Framework/Sortable'
import {Table} from './Framework/Table'
import {Tabs} from './Framework/Tabs'
import {Tooltip} from './Framework/Tooltip'
export class Index {
constructor () {
this.ajax = new Ajax()
this.form = new Form()
this.link = new Link()
this.loadingBar = new LoadingBar()
this.navbar = new Navbar()
this.scrolling = new Scrolling()
this.setHeight = new SetHeight()
this.searchBar = new Searchbar()
this.table = new Table()
this.tabs = new Tabs()
this.initializeSliders()
this.initializeSortables()
this.initializePopovers()
this.initializeTooltips()
this.initializeSelects()
}
initializeSliders () {
$('.slider').each((index, element) => {
element.slider = new Slider($(element))
})
}
initializeSortables () {
$('.sortable').each((index, element) => {
element.sortable = new Sortable($(element))
})
}
initializePopovers () {
$('[data-toggle="popover"]').each((index, element) => {
element.popover = new Popover($(element))
})
}
initializeTooltips () {
$('[data-toggle="tooltip"]').each((index, element) => {
element.tooltip = new Tooltip($(element))
})
}
initializeSelects () {
$('.select2').each((index, element) => {
element.select2 = new Select($(element))
})
}
}
window.index = new Index()
| JavaScript | 0.999043 |
0943dd66807181b67745c7ab9a312a8f048ee4c0 | add mainFields | webpack_config/common.js | webpack_config/common.js | /*eslint-env node*/
const path = require('path');
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
entry: './src/entry.js',
},
output: {
path: path.resolve('./dist'),
publicPath: '/dist/',
filename: '[name].js',
jsonpFunction: 'entryJsonp',
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
mainFields: ['jsnext:main', 'main', 'module', 'browser'],
},
node: {
fs: 'empty',
},
module: {
rules: [
{
test: /\.worker\.ts$/,
use: {
loader: 'worker-loader',
options: {
inline: true,
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'webpack-strip-block',
options: {
start: 'IGNORE_WEBPACK:START',
end: 'IGNORE_WEBPACK:END',
},
},
{
loader: 'babel-loader',
},
],
},
{
// eslint-disable-next-line max-len
test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|cur)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
name: '[hash].[ext]',
limit: 10000,
},
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: { transpileOnly: true },
},
{
test: /\.(css|less)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publ icPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../',
},
},
{
loader: 'css-loader',
options: {
url: false,
sourceMap: false,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('cssnano')({ preset: 'default' }),
autoprefixer({
overrideBrowserslist: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
remove: false,
}),
],
},
},
{
loader: 'less-loader',
options: {
sourceMap: false,
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
'@entrylabs/tool': 'EntryTool',
'entry-paint': 'EntryPaint',
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: path.join(__dirname, '..'),
}),
new ManifestPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
| /*eslint-env node*/
const path = require('path');
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
entry: './src/entry.js',
},
output: {
path: path.resolve('./dist'),
publicPath: '/dist/',
filename: '[name].js',
jsonpFunction: 'entryJsonp',
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
node: {
fs: 'empty',
},
module: {
rules: [
{
test: /\.worker\.ts$/,
use: {
loader: 'worker-loader',
options: {
inline: true,
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'webpack-strip-block',
options: {
start: 'IGNORE_WEBPACK:START',
end: 'IGNORE_WEBPACK:END',
},
},
{
loader: 'babel-loader',
},
],
},
{
// eslint-disable-next-line max-len
test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|cur)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
name: '[hash].[ext]',
limit: 10000,
},
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: { transpileOnly: true },
},
{
test: /\.(css|less)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publ icPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../',
},
},
{
loader: 'css-loader',
options: {
url: false,
sourceMap: false,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('cssnano')({ preset: 'default' }),
autoprefixer({
overrideBrowserslist: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
remove: false,
}),
],
},
},
{
loader: 'less-loader',
options: {
sourceMap: false,
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
'@entrylabs/tool': 'EntryTool',
'entry-paint': 'EntryPaint',
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: path.join(__dirname, '..'),
}),
new ManifestPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
| JavaScript | 0.000001 |
2c3d10a4c63354899c1e077a6f1a2dc890eed2b7 | Test corrected. | tests/test-apache-crypt.js | tests/test-apache-crypt.js | // Apache crypt.
var crypt = require('../lib/apache-crypt');
module.exports = {
// Test for valid password.
testValidPassword: function(test) {
var crypted = crypt("validPass", "B5xBYM2HbnPqI");
test.equal(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
},
// Test for invalid password.
testInValidPassword: function(test) {
var crypted = crypt("invalidPass", "B5xBYM2HbnPqI");
test.notEqual(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
}
}; | // Apache crypt.
var crypt = require('../lib/apache-crypt');
module.exports = {
// Test for valid password.
testValidPassword: function(test) {
var crypted = crypt("validPass", "B5xBYM2HbnPqI");
test.ok(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
},
// Test for invalid password.
testInValidPassword: function(test) {
var crypted = crypt("invalidPass", "B5xBYM2HbnPqI");
test.notEqual(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
}
}; | JavaScript | 0 |
297a9ea827655e5fb406a86907bb0d89b01deae8 | fix typo | tests/test-localAddress.js | tests/test-localAddress.js | var request = require('../index')
, assert = require('assert')
;
request.get({
uri: 'http://www.google.com', localAddress: '1.2.3.4' // some invalid address
}, function(err, res) {
assert(!res) // asserting that no response received
})
request.get({
uri: 'http://www.google.com', localAddress: '127.0.0.1'
}, function(err, res) {
assert(!res) // asserting that no response received
})
| var request = request = require('../index')
, assert = require('assert')
;
request.get({
uri: 'http://www.google.com', localAddress: '1.2.3.4' // some invalid address
}, function(err, res) {
assert(!res) // asserting that no response received
})
request.get({
uri: 'http://www.google.com', localAddress: '127.0.0.1'
}, function(err, res) {
assert(!res) // asserting that no response received
})
| JavaScript | 0.999991 |
9b0bb45721a2dc5b32823b33a7f4576e1a311b9a | 更新 gulpfile | Gulpfile.js | Gulpfile.js | /**
* jshint strict:true
*/
//npm install gulp gulp-minify-css gulp-uglify gulp-clean gulp-cleanhtml gulp-jshint gulp-strip-debug gulp-zip --save-dev
var gulp = require('gulp');
var watch = require('gulp-watch');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var coffee = require('gulp-coffee');
var sass = require('gulp-sass');
var cleanhtml = require('gulp-cleanhtml');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var browserify = require('gulp-browserify');
var paths = require('./paths');
gulp.task('clean', function(cb) {
return gulp.src('build/*', { read: false })
.pipe(clean({ force: true }))
.on('end', cb);
});
gulp.task('copy', function() {
return gulp.src(paths.staticFiles, { base: 'src' })
.pipe(gulp.dest('build/'));
});
gulp.task('jshint', function() {
return gulp.src(['Gulpfile.js', 'src/js/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('scripts', function() {
var ignore = ['underscore', 'jquery', 'angular', 'angular-elastic'];
gulp.src('src/js/lib/{lib-all,angular-all}.js')
.pipe(browserify())
.pipe(gulp.dest('./build/js/'));
return gulp.src('src/js/*.js')
.pipe(browserify({ignore: ignore}))
.pipe(gulp.dest('build/js/'));
});
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(sass())
.pipe(gulp.dest('build/css/'));
});
gulp.task('build', ['scripts', 'styles', 'copy']);
gulp.task('watch', ['build'], function() {
function errorHanlder(error) {
console.log(error);
}
gulp.watch(paths.staticFiles, ['copy'])
.on('error', errorHandler);
gulp.watch('src/js/**/*', ['scripts'])
.on('error', errorHandler);
gulp.watch('src/css/**/*', ['styles'])
.on('error', errorHandler);
});
gulp.task('zip', ['build'], function() {
var manifest = require('./src/manifest');
var filename = manifest.name + ' v' + manifest.version + '.zip';
return gulp.src('build/**/*')
.pipe(zip(filename))
.pipe(gulp.dest('dist'));
});
//run all tasks after build directory has been cleaned
gulp.task('default', ['clean', 'build']); | /**
* jshint strict:true
*/
//npm install gulp gulp-minify-css gulp-uglify gulp-clean gulp-cleanhtml gulp-jshint gulp-strip-debug gulp-zip --save-dev
var gulp = require('gulp');
var watch = require('gulp-watch');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var coffee = require('gulp-coffee');
var sass = require('gulp-sass');
var cleanhtml = require('gulp-cleanhtml');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var browserify = require('gulp-browserify');
var paths = require('./paths');
gulp.task('clean', function() {
return gulp.src('build/*', { read: false })
.pipe(clean({ force: true }));
});
gulp.task('copy', function() {
return gulp.src(paths.staticFiles, { base: 'src' })
.pipe(gulp.dest('build'));
});
gulp.task('jshint', function() {
return gulp.src(['Gulpfile.js', 'src/js/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('scripts', function() {
var ignore = ['underscore', 'jquery', 'angular', 'angular-elastic'];
gulp.src('src/js/lib/{lib-all,angular-all}.js')
.pipe(browserify())
.pipe(gulp.dest('./build/js/'));
return gulp.src('src/js/*.js')
.pipe(browserify({ignore: ignore}))
.pipe(gulp.dest('./build/js/'));
});
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(sass())
.pipe(gulp.dest('build/css'));
});
gulp.task('build', ['scripts', 'styles', 'copy']);
gulp.task('watch', ['build'], function() {
gulp.watch(paths.static, ['copy']);
gulp.watch(paths['js:app'], ['scripts']);
gulp.watch(paths['js:page'], ['scripts']);
gulp.watch(paths['js:trans'], ['scripts']);
gulp.watch(paths['js:static'], ['scripts']);
gulp.watch(paths.coffee, ['scripts']);
gulp.watch(paths.styles, ['styles']);
});
gulp.task('zip', ['build'], function() {
var manifest = require('./src/manifest');
var filename = manifest.name + ' v' + manifest.version + '.zip';
return gulp.src('build/**/*')
.pipe(zip(filename))
.pipe(gulp.dest('dist'));
});
//run all tasks after build directory has been cleaned
gulp.task('default', ['clean', 'build']); | JavaScript | 0 |
0c0c53589a54fb7f91f8100c5a3d4929bd00f1ff | Update gulpfile to watch contrib styles and not just core project files | Gulpfile.js | Gulpfile.js | var autoprefix = require("gulp-autoprefixer"),
connect = require("gulp-connect"),
gulp = require("gulp"),
sass = require("gulp-sass");
var paths = {
scss: [
"./core/**/*.scss",
"./contrib/**/*.scss"]
};
gulp.task("sass", function () {
return gulp.src(paths.scss)
.pipe(sass({
sourcemaps: true
}))
.pipe(autoprefix("last 2 versions"))
.pipe(gulp.dest("./contrib"))
.pipe(connect.reload());
});
gulp.task("connect", function() {
connect.server({
root: "contrib",
port: 8000,
livereload: true
});
});
gulp.task("default", ["sass", "connect"], function() {
gulp.watch(paths.scss, ["sass"]);
});
| var autoprefix = require("gulp-autoprefixer"),
connect = require("gulp-connect"),
gulp = require("gulp"),
sass = require("gulp-sass");
var paths = {
scss: [
"./core/**/*.scss",
"./contrib/styles.scss"]
};
gulp.task("sass", function () {
return gulp.src(paths.scss)
.pipe(sass({
sourcemaps: true
}))
.pipe(autoprefix("last 2 versions"))
.pipe(gulp.dest("./contrib"))
.pipe(connect.reload());
});
gulp.task("connect", function() {
connect.server({
root: "contrib",
port: 8000,
livereload: true
});
});
gulp.task("default", ["sass", "connect"], function() {
gulp.watch(paths.scss, ["sass"]);
});
| JavaScript | 0 |
81ab1414e614937b4ec0c841cf1dfd83a496193a | Fix use of wrong length value | src/PiecemealDownloadManager.js | src/PiecemealDownloadManager.js | define(['Promise', './PiecemealDownload'], function(Promise, PiecemealDownload) {
'use script';
function PiecemealDownloadManager(url) {
this.url = url;
}
PiecemealDownloadManager.prototype = {
getBytes: function(offset, length) {
offset = +(offset || 0);
if (isNaN(offset) || !isFinite(offset) || offset < 0) {
throw new TypeError('offset must be a finite number >= 0');
}
if (isNaN(length)) length = Infinity;
if (length < 0) {
throw new TypeError('length must be a number >= 0');
}
if (length === 0) {
return Promise.resolve(new Uint8Array(0));
}
var self = this;
return new Promise(function(resolve, reject) {
var dl = new PiecemealDownload(self.url, [{offset:offset, length:length}]);
var buf = new Uint8Array(length);
var count = 0;
dl.onPiece = function(pieceOffset, pieceBytes) {
if (pieceOffset >= (offset + length)) return;
if ((pieceOffset + pieceBytes.length) <= offset) return;
var diff = pieceOffset - offset;
pieceBytes = pieceBytes.subarray(diff, Math.min(pieceBytes.length, diff + length));
buf.set(pieceBytes, pieceOffset - offset);
count += pieceBytes.length;
if (count === length) {
resolve(buf);
}
};
dl.startDownload();
});
},
};
return PiecemealDownloadManager;
});
| define(['Promise', './PiecemealDownload'], function(Promise, PiecemealDownload) {
'use script';
function PiecemealDownloadManager(url) {
this.url = url;
}
PiecemealDownloadManager.prototype = {
getBytes: function(offset, length) {
offset = +(offset || 0);
if (isNaN(offset) || !isFinite(offset) || offset < 0) {
throw new TypeError('offset must be a finite number >= 0');
}
if (isNaN(length)) length = Infinity;
if (length < 0) {
throw new TypeError('length must be a number >= 0');
}
if (length === 0) {
return Promise.resolve(new Uint8Array(0));
}
var self = this;
return new Promise(function(resolve, reject) {
var dl = new PiecemealDownload(self.url, [{offset:offset, length:length}]);
var buf = new Uint8Array(length);
var count = 0;
dl.onPiece = function(pieceOffset, pieceBytes) {
if (pieceOffset >= (offset + length)) return;
if ((pieceOffset + pieceBytes.length) <= offset) return;
var diff = pieceOffset - offset;
pieceBytes = pieceBytes.subarray(diff, Math.min(pieceBytes.length, diff + pieceBytes.length));
buf.set(pieceBytes, pieceOffset - offset);
count += pieceBytes.length;
if (count === length) {
resolve(buf);
}
};
dl.startDownload();
});
},
};
return PiecemealDownloadManager;
});
| JavaScript | 0.023183 |
adda1e261b87633559d9165e13dcafbd6f709ac7 | correct error with submission hooks. | src/services/submissions/hooks/index.js | src/services/submissions/hooks/index.js | 'use strict';
const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication').hooks;
exports.before = {
all: [
auth.verifyToken(),
auth.populateUser(),
auth.restrictToAuthenticated()
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
exports.after = {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
| 'use strict';
const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication').hooks;
exports.before = {
all: [
// auth.verifyToken(),
// auth.populateUser(),
// auth.restrictToAuthenticated()
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
exports.after = {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
};
| JavaScript | 0 |
fe899e38f4f19ba914f568af0232d52fbfda3003 | add S3 copy object example | javascriptv3/example_code/s3/src/s3_copyobject.js | javascriptv3/example_code/s3/src/s3_copyobject.js | /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html.
Purpose:
s3_copyobject.js demonstrates how to copy an object from one Amazon Simple Storage Solution (Amazon S3) bucket to another.
Inputs (replace in code):
- DESTINATION_BUCKET_NAME
- SOURCE_BUCKET_NAME
- OBJECT_NAME
Running the code:
node s3_copyobject.js
*/
// snippet-start:[s3.JavaScript.buckets.copyObjectV3]
// Get service clients module and commands using ES6 syntax.
import { CopyObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js";
// Set the bucket parameters.
export const params = {
Bucket: "DESTINATION_BUCKET_NAME",
CopySource: "/SOURCE_BUCKET_NAME/OBJECT_NAME",
Key: "OBJECT_NAME"
};
// Create the Amazon S3 bucket.
export const run = async () => {
try {
const data = await s3Client.send(new CopyObjectCommand(params));
console.log("Success", data);
return data; // For unit tests.
} catch (err) {
console.log("Error", err);
}
};
run();
// snippet-end:[s3.JavaScript.buckets.copyObjectV3]
// For unit tests only.
// module.exports ={run, bucketParams};
| /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html.
Purpose:
s3_copyobject.js demonstrates how to copy an object from one Amazon Simple Storage Solution (Amazon S3) bucket to another.
Inputs (replace in code):
- BUCKET_NAME
Running the code:
node s3_copyobject.js
*/
// snippet-start:[s3.JavaScript.buckets.copyObjectV3]
// Get service clients module and commands using ES6 syntax.
import { CopyObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js";
// Set the bucket parameters.
export const params = {
Bucket: "brmurbucket",
CopySource: "/apigatewaystack-mybucket160f8132-1dysc21xykp8d/index.js",
Key: "index.js"
};
// Create the Amazon S3 bucket.
export const run = async () => {
try {
const data = await s3Client.send(new CopyObjectCommand(params));
console.log("Success", data);
return data; // For unit tests.
} catch (err) {
console.log("Error", err);
}
};
run();
// snippet-end:[s3.JavaScript.buckets.copyObjectV3]
// For unit tests only.
// module.exports ={run, bucketParams};
| JavaScript | 0 |
9daee0f6354a660f6ec6e33aeb9669a11b8a7c89 | add ts and tsx to extension config | .storybook/main.js | .storybook/main.js | const path = require("path");
const glob = require("glob");
const projectRoot = path.resolve(__dirname, "../");
const ignoreTests = process.env.IGNORE_TESTS === "true";
const isChromatic = !ignoreTests;
const getStories = () =>
glob.sync(`${projectRoot}/src/**/*.stories.@(js|mdx)`, {
...(ignoreTests && {
ignore: `${projectRoot}/src/**/*-test.stories.@(js|mdx)`,
}),
});
module.exports = {
stories: (list) => [
...list,
"./welcome-page/welcome.stories.js",
"../docs/*.stories.mdx",
...getStories(),
],
addons: [
"@storybook/addon-actions",
"@storybook/addon-docs",
"@storybook/addon-controls",
"@storybook/addon-viewport",
"@storybook/addon-a11y",
"@storybook/addon-google-analytics",
"@storybook/addon-links",
"@storybook/addon-toolbars",
"./theme-selector/register",
],
webpackFinal: async (config, { configType }) => {
config.resolve = {
alias: {
helpers: path.resolve(__dirname, "__helpers__/"),
},
extensions: [".js", ".tsx", ".ts"],
};
// Workaround to stop hashes being added to font filenames, so we can pre-load them
config.module.rules.find((rule) =>
rule.test.toString().includes("woff2")
).options.name = "static/media/[name].[ext]";
return config;
},
...(isChromatic && {
previewHead: (head) => `
${head}
<meta name="robots" content="noindex">
`,
managerHead: (head) => `
${head}
<meta name="robots" content="noindex">
`,
}),
};
| const path = require("path");
const glob = require("glob");
const projectRoot = path.resolve(__dirname, "../");
const ignoreTests = process.env.IGNORE_TESTS === "true";
const isChromatic = !ignoreTests;
const getStories = () =>
glob.sync(`${projectRoot}/src/**/*.stories.@(js|mdx)`, {
...(ignoreTests && {
ignore: `${projectRoot}/src/**/*-test.stories.@(js|mdx)`,
}),
});
module.exports = {
stories: (list) => [
...list,
"./welcome-page/welcome.stories.js",
"../docs/*.stories.mdx",
...getStories(),
],
addons: [
"@storybook/addon-actions",
"@storybook/addon-docs",
"@storybook/addon-controls",
"@storybook/addon-viewport",
"@storybook/addon-a11y",
"@storybook/addon-google-analytics",
"@storybook/addon-links",
"@storybook/addon-toolbars",
"./theme-selector/register",
],
webpackFinal: async (config, { configType }) => {
config.resolve = {
alias: {
helpers: path.resolve(__dirname, "__helpers__/"),
},
extensions: [".js"],
};
// Workaround to stop hashes being added to font filenames, so we can pre-load them
config.module.rules.find((rule) =>
rule.test.toString().includes("woff2")
).options.name = "static/media/[name].[ext]";
return config;
},
...(isChromatic && {
previewHead: (head) => `
${head}
<meta name="robots" content="noindex">
`,
managerHead: (head) => `
${head}
<meta name="robots" content="noindex">
`,
}),
};
| JavaScript | 0 |
678c011c7125fb12e22d86678cc0d05794db8135 | Add default response to search | controllers/people/index.js | controllers/people/index.js | 'use strict';
var _ = require('underscore'),
ccb = require('../../lib/ccb'),
peopleModel = require('../../models/people'),
Promise = require('bluebird');
module.exports = function (router) {
router.get('/', function (req, res) {
if(process.env.NODE_ENV === 'production' && req.query.token !== process.env.slack_token) { //make this an express middleware
res.send('An Error Occurred: invalid token');
}
if(!req.query.text) {
res.send('An Error Occurred: invalid input');
}
var obj = {},
names = decodeURI(req.query.text).split(' '),
individuals = [];
obj.first_name = names[0];
obj.last_name = names[1];
peopleModel.search({
first_name: names[0],
last_name: names[1]
}).then(function(first) {
individuals = individuals.concat(ccb.parseIndividuals(first));
if (individuals.length === 0) {
return peopleModel.search({
last_name: names[0] //if no first names found, search the name as a last name
});
} else {
return Promise.resolve(null);
}
}).then(function(last) {
individuals = individuals.concat(ccb.parseIndividuals(last));
var output = _.map(individuals, function(individual) {
return ccb.individualToString(individual);
}).join(', ');
res.send(output || "Couldn't find anyone by that name");
})
});
};
| 'use strict';
var _ = require('underscore'),
ccb = require('../../lib/ccb'),
peopleModel = require('../../models/people'),
Promise = require('bluebird');
module.exports = function (router) {
router.get('/', function (req, res) {
if(process.env.NODE_ENV === 'production' && req.query.token !== process.env.slack_token) { //make this an express middleware
res.send('An Error Occurred: invalid token');
}
if(!req.query.text) {
res.send('An Error Occurred: invalid input');
}
var obj = {},
names = decodeURI(req.query.text).split(' '),
individuals = [];
obj.first_name = names[0];
obj.last_name = names[1];
peopleModel.search({
first_name: names[0],
last_name: names[1]
}).then(function(first) {
individuals = individuals.concat(ccb.parseIndividuals(first));
if (individuals.length === 0) {
return peopleModel.search({
last_name: names[0] //if no first names found, search the name as a last name
});
} else {
return Promise.resolve(null);
}
}).then(function(last) {
individuals = individuals.concat(ccb.parseIndividuals(last));
console.log(ccb.parseIndividuals(last));
var output = _.map(individuals, function(individual) {
return ccb.individualToString(individual);
}).join(', ');
res.send(output);
})
});
};
| JavaScript | 0.000001 |
dbdad7ffd14a30ccfe0553721ca7d46a9d257a6d | remove full browser width from web components wrapper | src/BookReaderComponent/BookReaderComponent.js | src/BookReaderComponent/BookReaderComponent.js | /**
* BookReaderTemplate to load BookNavigator components
*/
import { LitElement, html, css } from 'lit-element';
import '../ItemNavigator/ItemNavigator.js'
import '../BookNavigator/BookNavigator.js'
export class BookReader extends LitElement {
static get properties() {
return {
base64Json: { type: String },
baseHost: { type: String },
};
}
constructor() {
super();
this.base64Json = '';
this.baseHost = 'https://archive.org';
}
firstUpdated() {
this.fetchData();
}
/**
* Fetch metadata response from public metadata API
* convert response to base64 data
* set base64 data to props
*/
async fetchData() {
const ocaid = new URLSearchParams(location.search).get('ocaid');
const response = await fetch(`${this.baseHost}/metadata/${ocaid}`);
const bookMetadata = await response.json();
const jsonBtoa = btoa(JSON.stringify(bookMetadata));
this.setBaseJSON(jsonBtoa);
}
/**
* Set base64 data to prop
* @param {string} value - base64 string format
*/
setBaseJSON(value) {
this.base64Json = value;
}
render() {
return html`
<div class="ia-bookreader">
<item-navigator
itemType="bookreader"
basehost=${this.baseHost}
item=${this.base64Json}>
<div slot="bookreader">
<slot name="bookreader"></slot>
</div>
</item-navigator>
</div>
`;
}
static get styles() {
return css`
:host {
display: block;
--primaryBGColor: var(--black, #000);
--secondaryBGColor: #222;
--tertiaryBGColor: #333;
--primaryTextColor: var(--white, #fff);
--primaryCTAFill: #194880;
--primaryCTABorder: #c5d1df;
--secondaryCTAFill: #333;
--secondaryCTABorder: #999;
--primaryErrorCTAFill: #e51c26;
--primaryErrorCTABorder: #f8c6c8;
}
.ia-bookreader {
background-color: var(--primaryBGColor);
position: relative;
height: auto;
}
item-navigator {
display: block;
width: 100%;
color: var(--primaryTextColor);
--menuButtonLabelDisplay: block;
--menuWidth: 320px;
--menuSliderBg: var(--secondaryBGColor);
--activeButtonBg: var(--tertiaryBGColor);
--animationTiming: 100ms;
--iconFillColor: var(--primaryTextColor);
--iconStrokeColor: var(--primaryTextColor);
--menuSliderHeaderIconHeight: 2rem;
--menuSliderHeaderIconWidth: 2rem;
--iconWidth: 2.4rem;
--iconHeight: 2.4rem;
--shareLinkColor: var(--primaryTextColor);
--shareIconBorder: var(--primaryTextColor);
--shareIconBg: var(--secondaryBGColor);
--activityIndicatorLoadingDotColor: var(--primaryTextColor);
--activityIndicatorLoadingRingColor: var(--primaryTextColor);
}
`;
}
}
window.customElements.define("ia-bookreader", BookReader);
| /**
* BookReaderTemplate to load BookNavigator components
*/
import { LitElement, html, css } from 'lit-element';
import '../ItemNavigator/ItemNavigator.js'
import '../BookNavigator/BookNavigator.js'
export class BookReader extends LitElement {
static get properties() {
return {
base64Json: { type: String },
baseHost: { type: String },
};
}
constructor() {
super();
this.base64Json = '';
this.baseHost = 'https://archive.org';
}
firstUpdated() {
this.fetchData();
}
/**
* Fetch metadata response from public metadata API
* convert response to base64 data
* set base64 data to props
*/
async fetchData() {
const ocaid = new URLSearchParams(location.search).get('ocaid');
const response = await fetch(`${this.baseHost}/metadata/${ocaid}`);
const bookMetadata = await response.json();
const jsonBtoa = btoa(JSON.stringify(bookMetadata));
this.setBaseJSON(jsonBtoa);
}
/**
* Set base64 data to prop
* @param {string} value - base64 string format
*/
setBaseJSON(value) {
this.base64Json = value;
}
render() {
return html`
<div class="ia-bookreader">
<item-navigator
itemType="bookreader"
basehost=${this.baseHost}
item=${this.base64Json}>
<div slot="bookreader">
<slot name="bookreader"></slot>
</div>
</item-navigator>
</div>
`;
}
static get styles() {
return css`
:host {
display: block;
--primaryBGColor: var(--black, #000);
--secondaryBGColor: #222;
--tertiaryBGColor: #333;
--primaryTextColor: var(--white, #fff);
--primaryCTAFill: #194880;
--primaryCTABorder: #c5d1df;
--secondaryCTAFill: #333;
--secondaryCTABorder: #999;
--primaryErrorCTAFill: #e51c26;
--primaryErrorCTABorder: #f8c6c8;
}
.ia-bookreader {
background-color: var(--primaryBGColor);
position: relative;
width: 100vw;
height: auto;
}
item-navigator {
display: block;
width: 100%;
color: var(--primaryTextColor);
--menuButtonLabelDisplay: block;
--menuWidth: 320px;
--menuSliderBg: var(--secondaryBGColor);
--activeButtonBg: var(--tertiaryBGColor);
--animationTiming: 100ms;
--iconFillColor: var(--primaryTextColor);
--iconStrokeColor: var(--primaryTextColor);
--menuSliderHeaderIconHeight: 2rem;
--menuSliderHeaderIconWidth: 2rem;
--iconWidth: 2.4rem;
--iconHeight: 2.4rem;
--shareLinkColor: var(--primaryTextColor);
--shareIconBorder: var(--primaryTextColor);
--shareIconBg: var(--secondaryBGColor);
--activityIndicatorLoadingDotColor: var(--primaryTextColor);
--activityIndicatorLoadingRingColor: var(--primaryTextColor);
}
`;
}
}
window.customElements.define("ia-bookreader", BookReader);
| JavaScript | 0 |
0814008f10a5317bc7d60044d2e449134c19c740 | use yarn publish | scripts/publish-to-npm.js | scripts/publish-to-npm.js | 'use strict';
const yargs = require('yargs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));
const fs = require('fs-extra');
const path = require('path');
const rootDir = process.cwd();
let argv = yargs
.usage(
'$0 [-t|--tag]'
)
.command({
command: '*',
builder: yargs => {
return yargs
.option('t', {
alias: 'tag',
describe: 'the npm dist-tag',
default: 'latest',
type: 'string',
});
},
handler: async argv => {
const packageJsonData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.json'))
);
const packageDirs = (
await Promise.all(packageJsonData.workspaces.map((item) => glob(item)))
).flat();
await Promise.all(packageDirs.map((item) => {
const publishCmd = `yarn publish --tag ${argv.tag}`;
return execa(publishCmd, { stdio: 'inherit', cwd: path.join(rootDir, item) });
}))
},
})
.help().argv;
| 'use strict';
const yargs = require('yargs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));
const fs = require('fs-extra');
const path = require('path');
const rootDir = process.cwd();
let argv = yargs
.usage(
'$0 [-t|--tag]'
)
.command({
command: '*',
builder: yargs => {
return yargs
.option('t', {
alias: 'tag',
describe: 'the npm dist-tag',
default: 'latest',
type: 'string',
});
},
handler: async argv => {
const packageJsonData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.json'))
);
const packageDirs = (
await Promise.all(packageJsonData.workspaces.map((item) => glob(item)))
).flat();
await Promise.all(packageDirs.map((item) => {
const publishCmd = `npm publish --tag ${argv.tag}`;
return execa(publishCmd, { stdio: 'inherit', cwd: path.join(rootDir, item) });
}))
},
})
.help().argv;
| JavaScript | 0 |
709f9ae84a27cca1e4b4c540237a7c75cddd5383 | fix line endings and update build 2 | Jakefile.js | Jakefile.js | var build = require('./build/build.js'),
lint = require('./build/hint.js');
var COPYRIGHT = "/*\r\n Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin\r\n" +
" Leaflet is a modern open-source JavaScript library for interactive maps.\n" +
" http://leaflet.cloudmade.com\r\n*/\r\n";
desc('Check Leaflet source for errors with JSHint');
task('lint', function () {
var files = build.getFiles();
console.log('Checking for JS errors...');
var errorsFound = lint.jshint(files);
if (errorsFound > 0) {
console.log(errorsFound + ' error(s) found.\n');
fail();
} else {
console.log('\tCheck passed');
}
});
desc('Combine and compress Leaflet source files');
task('build', ['lint'], function (compsBase32, buildName) {
var name = buildName || 'custom',
path = 'dist/leaflet' + (compsBase32 ? '-' + name : '');
var files = build.getFiles(compsBase32);
console.log('Concatenating ' + files.length + ' files...');
var content = build.combineFiles(files);
console.log('\tUncompressed size: ' + content.length);
build.save(path + '-src.js', COPYRIGHT + content);
console.log('\tSaved to ' + path);
console.log('Compressing...');
var compressed = COPYRIGHT + build.uglify(content);
console.log('\tCompressed size: ' + compressed.length);
build.save(path + '.js', compressed);
console.log('\tSaved to ' + path);
});
task('default', ['build']); | var build = require('./build/build.js'),
lint = require('./build/hint.js');
var COPYRIGHT = "/*\r\n Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin\n" +
" Leaflet is a modern open-source JavaScript library for interactive maps.\n" +
" http://leaflet.cloudmade.com\r\n*/\r\n";
desc('Check Leaflet source for errors with JSHint');
task('lint', function () {
var files = build.getFiles();
console.log('Checking for JS errors...');
var errorsFound = lint.jshint(files);
if (errorsFound > 0) {
console.log(errorsFound + ' error(s) found.\n');
fail();
} else {
console.log('\tCheck passed');
}
});
desc('Combine and compress Leaflet source files');
task('build', ['lint'], function (compsBase32, buildName) {
var name = buildName || 'custom',
path = 'dist/leaflet' + (compsBase32 ? '-' + name : '');
var files = build.getFiles(compsBase32);
console.log('Concatenating ' + files.length + ' files...');
var content = build.combineFiles(files);
console.log('\tUncompressed size: ' + content.length);
build.save(path + '-src.js', COPYRIGHT + content);
console.log('\tSaved to ' + path);
console.log('Compressing...');
var compressed = COPYRIGHT + build.uglify(content);
console.log('\tCompressed size: ' + compressed.length);
build.save(path + '.js', compressed);
console.log('\tSaved to ' + path);
});
task('default', ['build']); | JavaScript | 0 |
1c4a59f86ac4e1e062ad061b5850f0175184958e | Make sure we're only adding labels to lis on the top level | github.com.js | github.com.js | var dotjs_github = {};
dotjs_github.init = function() {
dotjs_github.$issues = $('.issues');
var style = '<style>' +
'.filter-exclude { margin-top: 10px; }' +
'.filter-exclude input {' +
' box-sizing: border-box;' +
' padding: 3px 4px;' +
' width: 100%;' +
'}' +
'.filter-exclude .minibutton {' +
' display: block;' +
' text-align: center;' +
'}' +
'.filter-list li {' +
' position: relative;' +
'}' +
'.filter-list .hide-it {' +
' font-size: 20px;' +
' line-height: 20px;' +
' left: -45px;' +
' position: absolute;' +
' top: 0px;' +
'}' +
'.filter-list .hide-it.clicked {' +
' color: #ccc;' +
'}' +
'.filter-list .custom-hidden a:nth-child(2) {' +
' text-decoration: line-through;' +
' opacity: 0.3;' +
'}' +
'.filter-list .hide-it:hover {' +
' text-decoration: none;' +
'}' +
'.issues .item.hidden {' +
' display: none;' +
'}' +
'</style>';
$('body').append( style );
$('.sidebar .filter-item').live('click.dotjs_github', function( e ) {
e.preventDefault();
setTimeout( function() {
dotjs_github.$issues = $('.issues');
dotjs_github.add_hide_links();
}, 500 );
});
dotjs_github.add_hide_links();
};
dotjs_github.add_hide_links = function() {
var $labels = $('.js-color-label-list');
$labels.children('li').prepend('<a href="#" class="hide-it minibutton">☠</a>');
$labels.find('.hide-it').bind('click', function( e ) {
e.preventDefault();
e.stopPropagation();
var $el = $(this);
var val = $el.next().data('label');
var $issues = dotjs_github.$issues.find('.list-browser-item .label[data-name="' + $.trim( val ) + '"]').closest('tr');
if ( ! $el.hasClass('clicked') ) {
$el.addClass('clicked').closest('li').addClass('custom-hidden');
$issues.addClass('hidden');
} else {
$el.removeClass('clicked').closest('li').removeClass('custom-hidden');
$issues.removeClass('hidden');
}//end else
var count = $('.issues-list').find('.list-browser-item:not(.hidden)').length;
var $selected = $('.list-browser-filter-tabs .selected');
$selected.html( parseInt( count, 10 ) + ' ' + $selected.data('filter') + ' issues' );
});
};
dotjs_github.init();
| var dotjs_github = {};
dotjs_github.init = function() {
dotjs_github.$issues = $('.issues');
var style = '<style>' +
'.filter-exclude { margin-top: 10px; }' +
'.filter-exclude input {' +
' box-sizing: border-box;' +
' padding: 3px 4px;' +
' width: 100%;' +
'}' +
'.filter-exclude .minibutton {' +
' display: block;' +
' text-align: center;' +
'}' +
'.filter-list li {' +
' position: relative;' +
'}' +
'.filter-list .hide-it {' +
' font-size: 20px;' +
' line-height: 20px;' +
' left: -45px;' +
' position: absolute;' +
' top: 0px;' +
'}' +
'.filter-list .hide-it.clicked {' +
' color: #ccc;' +
'}' +
'.filter-list .custom-hidden a:nth-child(2) {' +
' text-decoration: line-through;' +
' opacity: 0.3;' +
'}' +
'.filter-list .hide-it:hover {' +
' text-decoration: none;' +
'}' +
'.issues .item.hidden {' +
' display: none;' +
'}' +
'</style>';
$('body').append( style );
$('.sidebar .filter-item').live('click.dotjs_github', function( e ) {
e.preventDefault();
setTimeout( function() {
dotjs_github.$issues = $('.issues');
dotjs_github.add_hide_links();
}, 500 );
});
dotjs_github.add_hide_links();
};
dotjs_github.add_hide_links = function() {
var $labels = $('.js-color-label-list');
$labels.find('li').prepend('<a href="#" class="hide-it minibutton">☠</a>');
$labels.find('.hide-it').bind('click', function( e ) {
e.preventDefault();
e.stopPropagation();
var $el = $(this);
var val = $el.next().data('label');
var $issues = dotjs_github.$issues.find('.list-browser-item .label[data-name="' + $.trim( val ) + '"]').closest('tr');
if ( ! $el.hasClass('clicked') ) {
$el.addClass('clicked').closest('li').addClass('custom-hidden');
$issues.addClass('hidden');
} else {
$el.removeClass('clicked').closest('li').removeClass('custom-hidden');
$issues.removeClass('hidden');
}//end else
var count = $('.issues-list').find('.list-browser-item:not(.hidden)').length;
var $selected = $('.list-browser-filter-tabs .selected');
$selected.html( parseInt( count, 10 ) + ' ' + $selected.data('filter') + ' issues' );
});
};
dotjs_github.init();
| JavaScript | 0 |
5f9703e389ba0ab7471ef4d3f41b9f07b9198f71 | Update throbber test time to avoid test inaccuracies | test/__playground/throbber.formatted.js | test/__playground/throbber.formatted.js | #!/usr/bin/env node
'use strict';
var throbber = require('../../lib/throbber')
, interval = require('clock/lib/interval')
, format = require('../../lib/index').red;
var i = interval(100, true);
throbber(i, format);
process.stdout.write('START');
setTimeout(i.stop.bind(i), 550);
| #!/usr/bin/env node
'use strict';
var throbber = require('../../lib/throbber')
, interval = require('clock/lib/interval')
, format = require('../../lib/index').red;
var i = interval(100, true);
throbber(i, format);
process.stdout.write('START');
setTimeout(i.stop.bind(i), 500);
| JavaScript | 0 |
17b95e4b726a9c59096fe56c20cda3b05bb3acd3 | add new test spec for models | server/spec/modelSpec.js | server/spec/modelSpec.js | import jasmine from 'jasmine';
import Sequelize from 'sequelize';
import expect from 'expect';
import Users from '../models/users';
import Group from '../models/group';
// import GroupMembers from '../models/groupMembers';
// import Messages from '../models/messages';
import db from '../config/db_url.json';
describe('Model test suite', () => {
beforeEach((done) => {
const sequelize = new Sequelize(db.url);
sequelize.authenticate().then(() => { console.log('Connection established'); })
.catch((err) => { console.log('Error occured', err); });
done();
}, 10000);
it('I should be able to create a new user with this model', (done) => {
Users.sync({ force: true }).then(() => {
Users.create({ name: 'Peter', username: 'Ike', email: 'alobam@gmail.com', password: 'show' })
.then((user) => {
if (user) {
expect('Ike').toBe(user.dataValues.username);
}
done();
}).catch((err) => { console.log('Failed', err); done(); });
});
}, 10000);
it('I should be able to create a new group with this model', (done) => {
Group.sync({ force: true }).then(() => {
Group.create({ groupName: 'Zikites', groupCategory: 'Class of 2014', userId: 1 })
.then((group) => {
if (group) {
expect('Zikites').toNotBe('Zike');
expect('Class of 2014').toBe(group.dataValues.groupCategory);
}
done();
});
}).catch((err) => { console.log('Failed', err); });
}, 10000);
/* it('I should be able to add users to group I created', (done) => {
GroupMembers.sync({ force: true }).then(() => {
GroupMembers.create({ userId: 1, admin: 1, groupId: 1 })
.then((members) => {
if (members) {
expect(1).toBe(members.dataValues.userId);
}
done();
});
}).catch((err) => {
console.log('Failed', err);
});
}, 10000);*/
});
| import jasmine from 'jasmine';
import Sequelize from 'sequelize';
import expect from 'expect';
import Users from '../models/users';
import Group from '../models/group';
// import GroupMembers from '../models/groupMembers';
// import Messages from '../models/messages';
import db from '../config/db_url.json';
describe('Model test suite', () => {
beforeEach((done) => {
const sequelize = new Sequelize(db.url);
sequelize.authenticate().then(() => { console.log('Connection established'); })
.catch((err) => { console.log('Error occured', err); });
done();
}, 10000);
it('I should be able to create a new user with this model', (done) => {
Users.sync({ force: true }).then(() => {
Users.create({ name: 'Peter', username: 'Ike', email: 'alobam@gmail.com', password: 'show' })
.then((user) => {
if (user) {
expect('Ike').toBe(user.dataValues.username);
}
done();
}).catch((err) => { console.log('Failed', err); done(); });
});
}, 10000);
it('I should be able to create a new group with this model', (done) => {
Group.sync({ force: true }).then(() => {
Group.create({ groupName: 'Zikites', groupCategory: 'Class of 2014', userId: 1 })
.then((group) => {
if (group) {
expect('Zikites').toNotBe('Zike');
expect('Class of 2014').toBe(group.dataValues.groupCategory);
}
done();
});
}).catch((err) => { console.log('Failed', err); });
}, 10000);
/* it('I should be able to add users to group I created', (done) => {
GroupMembers.sync({ force: true }).then(() => {
GroupMembers.create({ userId: 1, admin: 1, groupId: 1 })
.then((members) => {
if (members) {
expect(1).toBe(members.dataValues.userId);
}
done();
});
}).catch((err) => {
console.log('Failed', err);
});
}, 10000);*/
});
/* describe('Models test suite', () => {
describe('Establish connection to the database', () => {
beforeAll((done) => {
const sequelize = new Sequelize(db.url);
sequelize.authenticate().then(() => {
console.log('Connected');
// 'Connected';
}).catch((err) => {
if (err) {
return 'Unable to connect';
}
});
done();
});
});
describe('Users model', () => {
beforeEach((done) => {
const User = Users.sync({ force: true }).then(() => {
Users.create({ name: 'Ebuka', username: 'Bonachristi', email:
'bona@gmail.com', password: 'samodu' })
.then((result) => {
if (result) {
return 'Registered';
}
}).catch((err) => {
if (err) {
return 'Failed';
}
});
});
it('should be able to create a new account', () => {
expect(User).to.be.a('Registered');
done();
});
});
});
describe('Create a new group', () => {
beforeEach((done) => {
const CreateGroup = Group.sync({ force: true }).then(() => {
Group.create({}).then((group) => {
if (group) {
return 'Group Created';
}
}).catch((err) => {
if (err) {
return 'Error occured, group not created';
}
});
});
it('Registered users should be able to create a group', () => {
expect(CreateGroup).to.be.a('Group Created');
done();
});
});
});
describe('Add registered users to group', () => {
beforeEach((done) => {
const AddMembers = GroupMembers.sync({ force: true }).then(() => {
GroupMembers.create({}).then((users) => {
if (users) {
return 'Added';
}
}).catch((err) => {
if (err) {
return 'Failed';
}
});
});
it('Users should be added by groups by registered user', () => {
expect(AddMembers).to.be.a('Added');
done();
});
});
});
describe('A user should be able to post messages to groups he created', () => {
beforeEach((done) => {
const post = Messages.sync({ force: true }).then(() => {
Messages.create({}).then((message) => {
if (message) {
return 'Posted';
}
}).catch((err) => {
if (err) {
return 'Failed';
}
});
});
it('Should be able to post message to group', () => {
expect(post).to.be.a('Posted');
done();
});
});
});
});*/
| JavaScript | 0 |
aa10cda61021ef3d32c301755e594faecbf24f2e | Add tests to <Text> | src/Text/__tests__/Text.test.js | src/Text/__tests__/Text.test.js | import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import StatusIcon from 'src/StatusIcon';
import Text from '../Text';
import BasicRow from '../BasicRow';
it('renders without crashing', () => {
const div = document.createElement('div');
const element = (
<Text
align="right"
basic="Basic text"
aside="Aside text"
tag="Tag" />
);
ReactDOM.render(element, div);
});
it('renders using <BasicRow> with BEM className', () => {
const wrapper = shallow(<Text basic="text" />);
const rowWrapper = wrapper.find(BasicRow);
expect(wrapper.children()).toHaveLength(1);
expect(rowWrapper.exists()).toBeTruthy();
expect(rowWrapper.hasClass('ic-text__row')).toBeTruthy();
expect(rowWrapper.hasClass('ic-text__basic')).toBeTruthy();
});
it('passing "basic", "tag" and "stateIcon" to <BasicRow>', () => {
const icon = <StatusIcon status="loading" />;
const wrapper = shallow(
<Text
basic="Basic text"
tag="Tag"
stateIcon={icon} />
);
const rowWrapper = wrapper.find(BasicRow);
expect(rowWrapper.prop('basic')).toBe('Basic text');
expect(rowWrapper.prop('tag')).toBe('Tag');
expect(rowWrapper.prop('stateIcon')).toEqual(icon);
});
it('takes custom <BasicRow> and passes the same props to it', () => {
const FooRow = () => <div />;
const customRow = <FooRow />;
const icon = <StatusIcon status="loading" />;
const wrapper = shallow(
<Text
basic="Basic text"
tag="Tag"
stateIcon={icon}
basicRow={customRow} />
);
const rowWrapper = wrapper.find(FooRow);
expect(rowWrapper.prop('basic')).toBe('Basic text');
expect(rowWrapper.prop('tag')).toBe('Tag');
expect(rowWrapper.prop('stateIcon')).toEqual(icon);
});
it('renders aside text', () => {
const wrapper = shallow(<Text basic="Basic" aside="Aside" />);
expect(wrapper.children()).toHaveLength(2);
expect(wrapper.childAt(1).hasClass('ic-text__aside')).toBeTruthy();
expect(wrapper.childAt(1).text()).toBe('Aside');
});
| import React from 'react';
import ReactDOM from 'react-dom';
import Text from '../Text';
it('renders without crashing', () => {
const div = document.createElement('div');
const element = (
<Text
align="right"
basic="Basic text"
aside="Aside text"
tag="Tag" />
);
ReactDOM.render(element, div);
});
| JavaScript | 0 |
63c03ef48a1fc0dbeec02943909bc9bc26ad7a2c | Mark TODO | lib/api/register_user.js | lib/api/register_user.js | var data = require(__dirname+'/../data/');
var sql = require(__dirname +'/../data/sequelize.js');
var config = require(__dirname+'/../../config/environment.js');
var validator = require(__dirname+'/../validator.js');
var RippleRestClient = require('ripple-rest-client');
var uuid = require('node-uuid');
/**
* Register a User
* - creates external account named "default"
* - creates ripple address as provided
* @require data, sql, config
* @param {string} name
* @param {string} rippleAddress
* @param {string} password
* @returns {User}, {ExternalAccount}, {RippleAddress}
*/
function registerUser(opts, fn) {
var userOpts = {
name: opts.name,
password: opts.password,
address: opts.ripple_address,
secret: opts.secret,
currency: opts.currency,
amount: opts.amount
};
if (!validator.isRippleAddress(opts.ripple_address)) {
fn({ ripple_address: 'invalid ripple address' });
return;
}
sql.transaction(function(sqlTransaction){
data.users.create(userOpts, function(err, user) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
var addressOpts = {
user_id: user.id,
address: opts.ripple_address,
managed: false,
type: 'independent'
};
data.rippleAddresses.create(addressOpts, function(err, ripple_address) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
data.externalAccounts.create({ name: 'default', user_id: user.id, address:addressOpts.address, type:addressOpts.type }, function(err, account){
if (err) { fn(err, null); return; }
var addressOpts = {
user_id: user.id,
address: config.get('COLD_WALLET'),
managed: true,
type: 'hosted',
tag: account.id
};
// We might be missing the cold wallet
if (addressOpts.address) {
// CS Fund user account with XRP
var rippleRootRestClient = new RippleRestClient({
api: config.get('RIPPLE_REST_API'),
account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'
});
var options = {
secret: 'masterpassphrase',
client_resource_id: uuid.v4(),
payment: {
destination_account: userOpts.address,
source_account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
destination_amount: {
value: '60',
currency: 'XRP',
issuer: ''
}
}
};
rippleRootRestClient.sendAndConfirmPayment(options, function(error, response){
if (error || (response.success != true)) {
logger.error('rippleRestClient.sendAndConfirmPayment', error);
return fn(error, null);
}
// CS Set trust line from user account to cold wallet. We should let users to this manually.
var coldWallet = config.get('COLD_WALLET');
var rippleRestClient = new RippleRestClient({
api: config.get('RIPPLE_REST_API'),
account:userOpts.address
});
rippleRestClient.setTrustLines({
account: userOpts.address,
secret: userOpts.secret,
limit: userOpts.amount,
currency: userOpts.currency,
counterparty: coldWallet,
account_allows_rippling: true
}, fn);
});
// CS Create in DB
// TODO the server.js process is restarted here - why?
data.rippleAddresses.create(addressOpts, function(err, hosted_address) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
var response = user.toJSON();
response.ripple_address = ripple_address;
response.external_account = account;
response.hosted_address = hosted_address;
sqlTransaction.commit();
fn(err, response);
});
}
});
});
});
});
}
module.exports = registerUser;
| var data = require(__dirname+'/../data/');
var sql = require(__dirname +'/../data/sequelize.js');
var config = require(__dirname+'/../../config/environment.js');
var validator = require(__dirname+'/../validator.js');
var RippleRestClient = require('ripple-rest-client');
var uuid = require('node-uuid');
/**
* Register a User
* - creates external account named "default"
* - creates ripple address as provided
* @require data, sql, config
* @param {string} name
* @param {string} rippleAddress
* @param {string} password
* @returns {User}, {ExternalAccount}, {RippleAddress}
*/
function registerUser(opts, fn) {
var userOpts = {
name: opts.name,
password: opts.password,
address: opts.ripple_address,
secret: opts.secret,
currency: opts.currency,
amount: opts.amount
};
if (!validator.isRippleAddress(opts.ripple_address)) {
fn({ ripple_address: 'invalid ripple address' });
return;
}
sql.transaction(function(sqlTransaction){
data.users.create(userOpts, function(err, user) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
var addressOpts = {
user_id: user.id,
address: opts.ripple_address,
managed: false,
type: 'independent'
};
data.rippleAddresses.create(addressOpts, function(err, ripple_address) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
data.externalAccounts.create({ name: 'default', user_id: user.id, address:addressOpts.address, type:addressOpts.type }, function(err, account){
if (err) { fn(err, null); return; }
var addressOpts = {
user_id: user.id,
address: config.get('COLD_WALLET'),
managed: true,
type: 'hosted',
tag: account.id
};
// We might be missing the cold wallet
if (addressOpts.address) {
// CS Fund user account with XRP
var rippleRootRestClient = new RippleRestClient({
api: config.get('RIPPLE_REST_API'),
account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'
});
var options = {
secret: 'masterpassphrase',
client_resource_id: uuid.v4(),
payment: {
destination_account: userOpts.address,
source_account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
destination_amount: {
value: '60',
currency: 'XRP',
issuer: ''
}
}
};
rippleRootRestClient.sendAndConfirmPayment(options, function(error, response){
if (error || (response.success != true)) {
logger.error('rippleRestClient.sendAndConfirmPayment', error);
return fn(error, null);
}
// CS Set trust line from user account to cold wallet. We should let users to this manually.
var coldWallet = config.get('COLD_WALLET');
var rippleRestClient = new RippleRestClient({
api: config.get('RIPPLE_REST_API'),
account:userOpts.address
});
rippleRestClient.setTrustLines({
account: userOpts.address,
secret: userOpts.secret,
limit: userOpts.amount,
currency: userOpts.currency,
counterparty: coldWallet,
account_allows_rippling: true
}, fn);
});
// CS Create in DB
data.rippleAddresses.create(addressOpts, function(err, hosted_address) {
if (err) { sqlTransaction.rollback(); fn(err, null); return; }
var response = user.toJSON();
response.ripple_address = ripple_address;
response.external_account = account;
response.hosted_address = hosted_address;
sqlTransaction.commit();
fn(err, response);
});
}
});
});
});
});
}
module.exports = registerUser;
| JavaScript | 0.000004 |
847544231b0819913f22e2fe437f5cf475542962 | fix code identity | server/streak/service.js | server/streak/service.js | const rp = require('request-promise');
const cheerio = require('cheerio');
const getStreakBody = (userName) => {
var options = {
uri: `https://github.com/users/${userName}/contributions`,
transform: function (body) {
return cheerio.load(body);
}
};
return rp(options)
.then(function ($) {
const currentDateStreak = [];
let currentStreak = [];
$('.day').filter(function (i, el) {
return $(this).prop('data-count') !== '0';
}).each(function (index) {
const date = new Date($(this).prop('data-date'));
date.setHours(0, 0, 0, 0);
if (currentDateStreak[index - 1]) {
const tempDate = currentDateStreak[index - 1].date;
tempDate.setDate(tempDate.getDate() + 1);
tempDate.setHours(0, 0, 0, 0);
if (date.getTime() === tempDate.getTime()) {
currentStreak.push({
date: date,
commit: $(this).prop('data-count')
});
} else {
currentStreak = [];
}
}
currentDateStreak.push({
date: date
});
});
return currentStreak;
})
.catch((err) => {
console.log('error', err);
});
};
module.exports = {
getStreakBody
}; | const rp = require('request-promise');
const cheerio = require('cheerio');
const getStreakBody = (userName) => {
var options = {
uri: `https://github.com/users/${userName}/contributions`,
transform: function (body) {
return cheerio.load(body);
}
};
return rp(options)
.then(function ($) {
const currentDateStreak = [];
let currentStreak = [];
$('.day').filter(function (i, el) {
return $(this).prop('data-count') !== '0';
}).each(function (index) {
const date = new Date($(this).prop('data-date'));
date.setHours(0, 0, 0, 0);
if (currentDateStreak[index - 1]) {
const tempDate = currentDateStreak[index - 1].date;
tempDate.setDate(tempDate.getDate() + 1);
tempDate.setHours(0, 0, 0, 0);
if (date.getTime() === tempDate.getTime()) {
if ($(this).prop('fill') != '#ebedf0') {
currentStreak.push({
date: date,
commit: $(this).prop('data-count')
});
}
} else {
currentStreak = [];
}
}
currentDateStreak.push({
date: date
});
});
return currentStreak;
})
.catch( (err) => {
console.log('errror', err);
});
};
module.exports = {
getStreakBody
}; | JavaScript | 0.000717 |
5418e50f4d56f3f700c9ecc745c3d1d3e25bbfc9 | Add extra named-chunks test cases for variations with require.ensure error callback present. | test/cases/chunks/named-chunks/index.js | test/cases/chunks/named-chunks/index.js | it("should handle named chunks", function(done) {
var sync = false;
require.ensure([], function(require) {
require("./empty?a");
require("./empty?b");
testLoad();
sync = true;
process.nextTick(function() {
sync = false;
});
}, "named-chunk");
function testLoad() {
require.ensure([], function(require) {
require("./empty?c");
require("./empty?d");
sync.should.be.ok();
done();
}, "named-chunk");
}
});
it("should handle empty named chunks", function(done) {
var sync = false;
require.ensure([], function(require) {
sync.should.be.ok();
}, "empty-named-chunk");
require.ensure([], function(require) {
sync.should.be.ok();
done();
}, "empty-named-chunk");
sync = true;
setImmediate(function() {
sync = false;
});
});
it("should handle named chunks when there is an error callback", function(done) {
var sync = false;
require.ensure([], function(require) {
require("./empty?a");
require("./empty?b");
testLoad();
sync = true;
process.nextTick(function() {
sync = false;
});
}, function(error) {}, "named-chunk");
function testLoad() {
require.ensure([], function(require) {
require("./empty?c");
require("./empty?d");
sync.should.be.ok();
done();
}, function(error) {}, "named-chunk");
}
});
it("should handle empty named chunks when there is an error callback", function(done) {
var sync = false;
require.ensure([], function(require) {
sync.should.be.ok();
}, function(error) {}, "empty-named-chunk");
require.ensure([], function(require) {
sync.should.be.ok();
done();
}, function(error) {}, "empty-named-chunk");
sync = true;
setImmediate(function() {
sync = false;
});
});
| it("should handle named chunks", function(done) {
var sync = false;
require.ensure([], function(require) {
require("./empty?a");
require("./empty?b");
testLoad();
sync = true;
process.nextTick(function() {
sync = false;
});
}, "named-chunk");
function testLoad() {
require.ensure([], function(require) {
require("./empty?c");
require("./empty?d");
sync.should.be.ok();
done();
}, "named-chunk");
}
});
it("should handle empty named chunks", function(done) {
var sync = false;
require.ensure([], function(require) {
sync.should.be.ok();
}, "empty-named-chunk");
require.ensure([], function(require) {
sync.should.be.ok();
done();
}, "empty-named-chunk");
sync = true;
setImmediate(function() {
sync = false;
});
});
| JavaScript | 0 |
ce9b5866133de731e00202a8faa19f7de1ecbd38 | Fix in category filter popup | cityproblems/site/static/site/js/index.js | cityproblems/site/static/site/js/index.js | var mainPageViewCtrl = function ($scope, $http, $route)
{
"use strict";
$scope.showMenu = false;
$scope.alerts=[];
$scope.$on('$routeChangeSuccess', function(next, current)
{
if((current.params.reportBy != $scope.reportBy || current.params.category != $scope.category) && (typeof current.params.reportBy != "undefined" && typeof current.params.category != "undefined"))
{
$scope.reportBy = current.params.reportBy;
$scope.category = current.params.category;
loadMarkers();
$('#popup-filter-category').trigger('close');
}
});
$scope.init=function(categories)
{
$scope.categories = angular.fromJson(categories);
$scope.tmpCategory = "all";
}
$scope.$watch("category", function(category, oldValue)
{
if(category != oldValue)
for(var i=0;i<$scope.categories.length;++i)
if($scope.categories[i]["url_name"] == category)
{
$scope.categoryTitle = $scope.categories[i].title;
break;
}
}
)
function clearMap()
{
if(!$scope.markers)
{
$scope.markers=[];
return;
}
for(var i=0;i<$scope.markers.length;++i)
$scope.markers[i].setMap(null);
$scope.markers=[];
}
$scope.map_init=function()
{
var zoom = parseInt($scope.zoom);
if(zoom!=zoom)
$scope.zoom=11;
var latitude = parseFloat($scope.latitude.replace(",", "."));
var longitude = parseFloat($scope.longitude.replace(",", "."));
if(latitude!=latitude || longitude!=longitude)
{
alert("Wrong map config. Please fix it in site parameters");
return;
}
var latLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadMarkers()
{
$http.post($scope.loadDataURL, {reportBy: $scope.reportBy, category: $scope.category})
.success(function(data)
{
if ("error" in data)
$scope.alerts.push({type: 'danger', msg: data["error"]});
else
{
clearMap();
var objList = data["problems"];
var infowindow = new google.maps.InfoWindow();
$scope.infowindow=infowindow;
for(var i=0;i<objList.length;++i)
{
var myLatlng = new google.maps.LatLng(parseFloat(objList[i].latitude), parseFloat(objList[i].longitude));
var marker = new google.maps.Marker({
position: myLatlng,
map: $scope.map,
html: '<a href="'+$scope.problemViewURL+objList[i].id+'/" target="_blank">'+objList[i].title+'</a>'
});
google.maps.event.addListener(marker, 'click', function ()
{
infowindow.setContent(this.html);
infowindow.open($scope.map, this);
});
$scope.markers.push(marker);
}
}
})
.error(function(data)
{
//document.write(data);
$scope.alerts.push({type: 'danger', msg: "Error while load data"});
});
}
$scope.closeAlert = function(index)
{
$scope.alerts.splice(index, 1);
};
};
mainPageViewCtrl.$inject = ["$scope", "$http", "$route"];
| var mainPageViewCtrl = function ($scope, $http, $route)
{
"use strict";
$scope.showMenu = false;
$scope.alerts=[];
$scope.$on('$routeChangeSuccess', function(next, current)
{
if((current.params.reportBy != $scope.reportBy || current.params.category != $scope.category) && (typeof current.params.reportBy != "undefined" && typeof current.params.category != "undefined"))
{
$scope.reportBy = current.params.reportBy;
$scope.category = current.params.category;
loadMarkers();
}
});
$scope.init=function(categories)
{
$scope.categories = angular.fromJson(categories);
$scope.tmpCategory = "all";
}
$scope.$watch("category", function(category, oldValue)
{
if(category != oldValue)
for(var i=0;i<$scope.categories.length;++i)
if($scope.categories[i]["url_name"] == category)
{
$scope.categoryTitle = $scope.categories[i].title;
break;
}
}
)
function clearMap()
{
if(!$scope.markers)
{
$scope.markers=[];
return;
}
for(var i=0;i<$scope.markers.length;++i)
$scope.markers[i].setMap(null);
$scope.markers=[];
}
$scope.map_init=function()
{
var zoom = parseInt($scope.zoom);
if(zoom!=zoom)
$scope.zoom=11;
var latitude = parseFloat($scope.latitude.replace(",", "."));
var longitude = parseFloat($scope.longitude.replace(",", "."));
if(latitude!=latitude || longitude!=longitude)
{
alert("Wrong map config. Please fix it in site parameters");
return;
}
var latLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
$scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadMarkers()
{
$http.post($scope.loadDataURL, {reportBy: $scope.reportBy, category: $scope.category})
.success(function(data)
{
if ("error" in data)
$scope.alerts.push({type: 'danger', msg: data["error"]});
else
{
clearMap();
var objList = data["problems"];
var infowindow = new google.maps.InfoWindow();
$scope.infowindow=infowindow;
for(var i=0;i<objList.length;++i)
{
var myLatlng = new google.maps.LatLng(parseFloat(objList[i].latitude), parseFloat(objList[i].longitude));
var marker = new google.maps.Marker({
position: myLatlng,
map: $scope.map,
html: '<a href="'+$scope.problemViewURL+objList[i].id+'/" target="_blank">'+objList[i].title+'</a>'
});
google.maps.event.addListener(marker, 'click', function ()
{
infowindow.setContent(this.html);
infowindow.open($scope.map, this);
});
$scope.markers.push(marker);
}
}
})
.error(function(data)
{
//document.write(data);
$scope.alerts.push({type: 'danger', msg: "Error while load data"});
});
}
$scope.closeAlert = function(index)
{
$scope.alerts.splice(index, 1);
};
};
mainPageViewCtrl.$inject = ["$scope", "$http", "$route"];
| JavaScript | 0.000001 |
0e8964f2cca4493045814fb74fb4ea7de53d9242 | Fix paths on Windows | lib/asset_types/html5.js | lib/asset_types/html5.js | var loader = require("@loader");
var nodeRequire = loader._nodeRequire;
var path = nodeRequire("path");
// Register the html5-upgrade asset type
module.exports = function(register){
var shivPath = path.join(__dirname, "/../../scripts/html5shiv.min.js");
var loaderBasePath = loader.baseURL.replace("file:", "");
var shivUrl = path.relative(loaderBasePath, shivPath).replace(/\\/g, "/");
register("html5shiv", function(){
var elements = Object.keys(loader.global.can.view.callbacks._tags)
.filter(function(tagName) {
return tagName.indexOf("-") > 0;
});
var comment = document.createComment(
"[if lt IE 9]>\n" +
"\t<script src=\""+ shivUrl + "\"></script>" +
"\t<script>\n\t\thtml5.elements = \"" + elements.join(" ") +
"\";\nhtml5.shivDocument();\n\t</script>" +
"<![endif]"
);
return comment;
});
};
| var loader = require("@loader");
var nodeRequire = loader._nodeRequire;
var path = nodeRequire("path");
// Register the html5-upgrade asset type
module.exports = function(register){
var shivPath = path.join(__dirname, "/../../scripts/html5shiv.min.js");
var loaderBasePath = loader.baseURL.replace("file:", "");
var shivUrl = path.relative(loaderBasePath, shivPath);
register("html5shiv", function(){
var elements = Object.keys(loader.global.can.view.callbacks._tags)
.filter(function(tagName) {
return tagName.indexOf("-") > 0;
});
var comment = document.createComment(
"[if lt IE 9]>\n" +
"\t<script src=\""+ shivUrl + "\"></script>" +
"\t<script>\n\t\thtml5.elements = \"" + elements.join(" ") +
"\";\nhtml5.shivDocument();\n\t</script>" +
"<![endif]"
);
return comment;
});
};
| JavaScript | 0 |
0f6506374ddfed2969454b081e5494f0cda811de | Update cred.js | server/routes/cred.js | server/routes/cred.js | var User = require('../models/users.js');
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var wellknown = require('nodemailer-wellknown');
module.exports = router;
router.post('/sendEmail', function(req,res){
var email = req.body.email;
console.log('email in send', email)
User.getByEmail(email)
.then(user => {
console.log('user in sendEmail:', user);
if(user[0]){
var config = wellknown('GandiMail');
config.auth = {
user: 'info@fairshare.cloud',
pass: 'AeK6yxhT'
};
var transporter = nodemailer.createTransport(config);
var mailOptions = {
from: '"Info" <info@fairshare.cloud>',
to: '<'+ email +'>',
subject: "Click the following link to reset your Fairshare password",
html: '<a href=' + 'https://www.fairshare.cloud/resetPassword>Reset Password</a>'
};
transporter.sendMail(mailOptions, function(err, info){
if(err){
return console.log(err);
}else{
res.status(200).send(info);
}
});
}else{
res.status(401).send('Email is not registered')
}
})
.catch(err => console.warn(err))
})
| var User = require('../models/users.js');
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var wellknown = require('nodemailer-wellknown');
module.exports = router;
router.post('/sendEmail', function(req,res){
var email = req.body.email;
console.log('email in send', email)
User.getByEmail(email)
.then(user => {
console.log('user in sendEmail:', user);
if(user[0]){
var config = wellknown('GandiMail');
config.auth = {
user: 'info@fairshare.cloud',
pass: 'AeK6yxhT'
};
var transporter = nodemailer.createTransport(config);
var mailOptions = {
from: '"Info" <info@fairshare.cloud>',
to: '<'+ email +'>',
subject: "Click the following link to reset your Fairshare password",
html: '<a href=' + 'http://localhost:3000/resetPassword>Reset Password</a>'
};
transporter.sendMail(mailOptions, function(err, info){
if(err){
return console.log(err);
}else{
res.status(200).send(info);
}
});
}else{
res.status(401).send('Email is not registered')
}
})
.catch(err => console.warn(err))
}) | JavaScript | 0.000001 |
b03df04b45b069a4bea75bed5a8428eb7b1275c2 | reformulate as recursion | WordSmushing/smushing.js | WordSmushing/smushing.js | "use strict";
var assert = require('assert');
var smush = function(w1,w2) {
if (w1 === '') return w2;
return w1[0] + smush(w1.substr(1), w2);
};
describe('word smushing', function() {
it.only('should join words with no overlap', function() {
assert.equal('thecat', smush('the', 'cat'));
});
it('should do single character overlaps', function() {
assert.equal('henot', smush('hen', 'not'));
});
});
| "use strict";
var assert = require('assert');
var smush = function(w1,w2) {
return w1 + w2;
};
describe('word smushing', function() {
it('should join words with no overlap', function() {
assert.equal('thecat', smush('the', 'cat'));
});
it('should do single character overlaps', function() {
assert.equal('henot', smush('hen', 'not'));
});
});
| JavaScript | 0.999976 |
c4b6024abd81b33562c78c343ecb99e0210ecfb5 | Add test that child nodes are rendered. | src/components/with-drag-and-drop/draggable-context/__spec__.js | src/components/with-drag-and-drop/draggable-context/__spec__.js | import React from 'react';
import { DragDropContext } from 'react-dnd';
import DraggableContext from './draggable-context';
import { mount } from 'enzyme';
describe('DraggableContext', () => {
it('is wrapped in a DragDropContextContainer', () => {
expect(DraggableContext.name).toBe('DragDropContextContainer');
});
it('has a DecoratedComponent pointing to the original component', () => {
expect(DraggableContext.DecoratedComponent.name).toBe('DraggableContext');
});
describe('render', () => {
it('renders this.props.children', () => {
let wrapper = mount(
<DraggableContext>
<div>
<p>One</p>
<p>Two</p>
</div>
</DraggableContext>
);
expect(wrapper.find('div').length).toEqual(1);
expect(wrapper.find('p').length).toEqual(2);
});
});
});
| import React from 'react';
import { DragDropContext } from 'react-dnd';
import DraggableContext from './draggable-context';
fdescribe('DraggableContext', () => {
it('is wrapped in a DragDropContextContainer', () => {
expect(DraggableContext.name).toBe('DragDropContextContainer');
});
it('has a DecoratedComponent pointing to the original component', () => {
expect(DraggableContext.DecoratedComponent.name).toBe('DraggableContext');
});
});
| JavaScript | 0 |
eafcb68040b44a73e6c2d3605e75f75847d2dfef | update TableHeader | src/_TableHeader/TableHeader.js | src/_TableHeader/TableHeader.js | /**
* @file TableHeader component
* @author liangxiaojun(liangxiaojun@derbysoft.com)
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TableHeaderSortIcon from '../_TableHeaderSortIcon';
class TableHeader extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
}
headerRenderer = () => {
const {header, colIndex} = this.props;
switch (typeof header) {
case 'function':
return header(colIndex);
default:
return header;
}
};
clickHandler = () => {
const {sortable, onSort} = this.props;
sortable && onSort && onSort();
};
render() {
const {
className, style, header, hidden,
sortable, sortProp, sort, sortAscIconCls, sortDescIconCls
} = this.props,
finalHeader = this.headerRenderer(),
tableHeaderClassName = classNames('table-header', {
sortable: sortable,
hidden: hidden,
[className]: className
});
return (
<th className={tableHeaderClassName}
style={style}
title={typeof header === 'string' ? header : null}
onClick={this.clickHandler}>
<div className="table-header-inner">
{finalHeader}
{
sortable ?
<TableHeaderSortIcon sort={sort}
sortProp={sortProp}
sortAscIconCls={sortAscIconCls}
sortDescIconCls={sortDescIconCls}/>
:
null
}
</div>
</th>
);
}
}
TableHeader.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
colIndex: PropTypes.number,
sortable: PropTypes.bool,
sortProp: PropTypes.string,
sort: PropTypes.object,
sortAscIconCls: PropTypes.string,
sortDescIconCls: PropTypes.string,
hidden: PropTypes.bool,
onSort: PropTypes.func
};
TableHeader.defaultProps = {
colIndex: 0,
sortable: false,
hidden: false
};
export default TableHeader; | /**
* @file TableHeader component
* @author liangxiaojun(liangxiaojun@derbysoft.com)
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TableHeaderSortIcon from '../_TableHeaderSortIcon';
class TableHeader extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
}
headerRenderer = () => {
const {header, colIndex} = this.props;
switch (typeof header) {
case 'function':
return header(colIndex);
default:
return header;
}
};
clickHandler = e => {
e.preventDefault();
const {sortable, onSort} = this.props;
sortable && onSort && onSort();
};
render() {
const {
className, style, header, hidden,
sortable, sortProp, sort, sortAscIconCls, sortDescIconCls
} = this.props,
finalHeader = this.headerRenderer(),
tableHeaderClassName = classNames('table-header', {
sortable: sortable,
hidden: hidden,
[className]: className
});
return (
<th className={tableHeaderClassName}
style={style}
title={typeof header === 'string' ? header : null}
onClick={this.clickHandler}>
<div className="table-header-inner">
{finalHeader}
{
sortable ?
<TableHeaderSortIcon sort={sort}
sortProp={sortProp}
sortAscIconCls={sortAscIconCls}
sortDescIconCls={sortDescIconCls}/>
:
null
}
</div>
</th>
);
}
}
TableHeader.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
colIndex: PropTypes.number,
sortable: PropTypes.bool,
sortProp: PropTypes.string,
sort: PropTypes.object,
sortAscIconCls: PropTypes.string,
sortDescIconCls: PropTypes.string,
hidden: PropTypes.bool,
onSort: PropTypes.func
};
TableHeader.defaultProps = {
colIndex: 0,
sortable: false,
hidden: false
};
export default TableHeader; | JavaScript | 0 |
b97fac279648ce2216a4f01cf6f1ec44e244ef08 | Refresh the whole scrollbar when adapting to size | Source/Widget/Scrollbar.js | Source/Widget/Scrollbar.js | /*
---
script: Scrollbar.js
description: Scrollbars for everything
license: MIT-style license.
authors: Yaroslaff Fedin
requires:
- ART.Widget.Paint
- ART.Widget.Section
- ART.Widget.Button
- Base/Widget.Trait.Slider
provides: [ART.Widget.Scrollbar]
...
*/
ART.Widget.Scrollbar = new Class({
Includes: [
ART.Widget.Paint,
Widget.Trait.Slider
],
name: 'scrollbar',
position: 'absolute',
layout: {
'scrollbar-track#track': {
'scrollbar-thumb#thumb': {},
},
'scrollbar-button#decrement': {},
'scrollbar-button#increment': {}
},
layered: {
stroke: ['stroke'],
background: ['fill', ['backgroundColor']],
reflection: ['fill', ['reflectionColor']]
},
options: {
slider: {
wheel: true
}
},
initialize: function() {
this.parent.apply(this, arguments);
this.setState(this.options.mode);
},
adaptSize: function(size, old){
if (!size || $chk(size.height)) size = this.parentNode.size;
var isVertical = (this.options.mode == 'vertical');
var other = isVertical ? 'horizontal' : 'vertical';
var prop = isVertical ? 'height' : 'width';
var Prop = prop.capitalize();
var setter = 'set' + Prop;
var getter = 'getClient' + Prop;
var value = size[prop];
if (isNaN(value) || !value) return;
var invert = this.parentNode[other];
var scrolled = this.getScrolled();
$(scrolled).setStyle(prop, size[prop])
var ratio = size[prop] / $(scrolled)['scroll' + Prop]
var delta = (!invert || invert.hidden ? 0 : invert.getStyle(prop));
this[setter](size[prop] - delta);
var offset = 0;
if (isVertical) {
offset += this.track.offset.padding.top + this.track.offset.padding.bottom
} else {
offset += this.track.offset.padding.left + this.track.offset.padding.right
}
var track = size[prop] - this.increment[getter]() - this.decrement[getter]() - delta - ((this.style.current.strokeWidth || 0) * 2) - offset * 2
this.track[setter](track);
this.track.thumb[setter](Math.ceil(track * ratio))
this.refresh(true);
this.parent.apply(this, arguments);
},
inject: Macro.onion(function(widget) {
this.adaptToSize(widget.size);
}),
onSet: function(value) {
var prop = (this.options.mode == 'vertical') ? 'height' : 'width';
var direction = (this.options.mode == 'vertical') ? 'top' : 'left';
var result = (value / 100) * this.parentNode.element['scroll' + prop.capitalize()];
$(this.getScrolled())['scroll' + direction.capitalize()] = result;
},
getScrolled: function() {
if (!this.scrolled) {
var parent = this;
while ((parent = parent.parentNode) && !parent.getScrolled);
this.scrolled = parent.getScrolled ? parent.getScrolled() : this.parentNode.element;
}
return this.scrolled;
},
getTrack: function() {
return $(this.track)
},
getTrackThumb: function() {
return $(this.track.thumb);
},
hide: Macro.onion(function() {
this.element.setStyle('display', 'none');
}),
show: Macro.onion(function() {
this.element.setStyle('display', 'block');
})
})
ART.Widget.Scrollbar.Track = new Class({
Extends: ART.Widget.Section,
layered: {
innerShadow: ['inner-shadow']
},
name: 'track',
position: 'absolute'
});
ART.Widget.Scrollbar.Thumb = new Class({
Extends: ART.Widget.Button,
name: 'thumb'
});
ART.Widget.Scrollbar.Button = new Class({
Extends: ART.Widget.Button,
position: 'absolute'
}); | /*
---
script: Scrollbar.js
description: Scrollbars for everything
license: MIT-style license.
authors: Yaroslaff Fedin
requires:
- ART.Widget.Paint
- ART.Widget.Section
- ART.Widget.Button
- Base/Widget.Trait.Slider
provides: [ART.Widget.Scrollbar]
...
*/
ART.Widget.Scrollbar = new Class({
Includes: [
ART.Widget.Paint,
Widget.Trait.Slider
],
name: 'scrollbar',
position: 'absolute',
layout: {
'scrollbar-track#track': {
'scrollbar-thumb#thumb': {},
},
'scrollbar-button#decrement': {},
'scrollbar-button#increment': {}
},
layered: {
stroke: ['stroke'],
background: ['fill', ['backgroundColor']],
reflection: ['fill', ['reflectionColor']]
},
options: {
slider: {
wheel: true
}
},
initialize: function() {
this.parent.apply(this, arguments);
this.setState(this.options.mode);
},
adaptSize: function(size, old){
if (!size || $chk(size.height)) size = this.parentNode.size;
var isVertical = (this.options.mode == 'vertical');
var other = isVertical ? 'horizontal' : 'vertical';
var prop = isVertical ? 'height' : 'width';
var Prop = prop.capitalize();
var setter = 'set' + Prop;
var getter = 'getClient' + Prop;
var value = size[prop];
if (isNaN(value) || !value) return;
var invert = this.parentNode[other];
var scrolled = this.getScrolled();
$(scrolled).setStyle(prop, size[prop])
var ratio = size[prop] / $(scrolled)['scroll' + Prop]
var delta = (!invert || invert.hidden ? 0 : invert.getStyle(prop));
this[setter](size[prop] - delta);
var offset = 0;
if (isVertical) {
offset += this.track.offset.padding.top + this.track.offset.padding.bottom
} else {
offset += this.track.offset.padding.left + this.track.offset.padding.right
}
var track = size[prop] - this.increment[getter]() - this.decrement[getter]() - delta - ((this.style.current.strokeWidth || 0) * 2) - offset * 2
this.track[setter](track);
this.track.thumb[setter](Math.ceil(track * ratio))
this.refresh();
this.parent.apply(this, arguments);
},
inject: Macro.onion(function(widget) {
this.adaptToSize(widget.size);
}),
onSet: function(value) {
var prop = (this.options.mode == 'vertical') ? 'height' : 'width';
var direction = (this.options.mode == 'vertical') ? 'top' : 'left';
var result = (value / 100) * this.parentNode.element['scroll' + prop.capitalize()];
$(this.getScrolled())['scroll' + direction.capitalize()] = result;
},
getScrolled: function() {
if (!this.scrolled) {
var parent = this;
while ((parent = parent.parentNode) && !parent.getScrolled);
this.scrolled = parent.getScrolled ? parent.getScrolled() : this.parentNode.element;
}
return this.scrolled;
},
getTrack: function() {
return $(this.track)
},
getTrackThumb: function() {
return $(this.track.thumb);
},
hide: Macro.onion(function() {
this.element.setStyle('display', 'none');
}),
show: Macro.onion(function() {
this.element.setStyle('display', 'block');
})
})
ART.Widget.Scrollbar.Track = new Class({
Extends: ART.Widget.Section,
layered: {
innerShadow: ['inner-shadow']
},
name: 'track',
position: 'absolute'
});
ART.Widget.Scrollbar.Thumb = new Class({
Extends: ART.Widget.Button,
name: 'thumb'
});
ART.Widget.Scrollbar.Button = new Class({
Extends: ART.Widget.Button,
position: 'absolute'
}); | JavaScript | 0 |
def49f76b0b9a0259aa3cb3e8bca5242f50d65be | Update LoadCSSJS.min.js | LoadCSSJS.min.js | LoadCSSJS.min.js | /*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT Licence */
function LoadCSSJS(e,t,r){"use strict";var a="";-1==a.indexOf("["+e+"]")?(Loader(e,t,r),a+="["+e+"]"):alert("File "+e+" already added!")}function Loader(e,t,r){if("css"==t){var s=document.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute("href",e),r?"":r="all",s.setAttribute("media",r),s.setAttribute("type","text/css")}else if("js"==t){var s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e)}if("undefined"!=typeof s){var a=document.getElementsByTagName("head");a=a[a.length-1],a.appendChild(s)}}
| /*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT Licence */
function LoadCSSJS(e,t,r){"use strict";var els="";-1==els.indexOf("["+e+"]")?(Loader(e,t,r),els+="["+e+"]"):alert("File "+e+" already added!")}function Loader(e,t,r){if("css"==t){var s=document.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute("href",e),r?"":r="all",s.setAttribute("media",r),s.setAttribute("type","text/css")}else if("js"==t){var s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e)}if("undefined"!=typeof s){var a=document.getElementsByTagName("head");a=a[a.length-1],a.appendChild(s)}}
| JavaScript | 0 |
7ef05101fafd008f7886571b2595bc810025f4aa | Fix floatbar behaviour on "More threads/posts" clicks. | client/common/system/floatbar/floatbar.js | client/common/system/floatbar/floatbar.js | 'use strict';
var _ = require('lodash');
N.wire.on('navigate.done', function () {
var $window = $(window)
, $floatbar = $('#floatbar')
, isFixed = false
, navTop;
if (0 === $floatbar.length) {
// Do nothing if there's no floatbar.
return;
}
navTop = $floatbar.offset().top;
isFixed = false;
function updateFloatbarState() {
var scrollTop = $window.scrollTop();
if (scrollTop >= navTop && !isFixed) {
isFixed = true;
$floatbar.addClass('floatbar-fixed');
} else if (scrollTop <= navTop && isFixed) {
isFixed = false;
$floatbar.removeClass('floatbar-fixed');
}
}
updateFloatbarState();
$window.on('scroll.floatbar', _.throttle(updateFloatbarState, 100));
});
N.wire.on('navigate.exit', function () {
// Remove floatbar event handler.
$(window).off('scroll.floatbar');
// Get floatbar back to the initial position to ensure next `navigate.done`
// handler will obtain correct floatbar offset on next call.
$('#floatbar').removeClass('floatbar-fixed');
});
| 'use strict';
var _ = require('lodash');
N.wire.on('navigate.done', function () {
var $window = $(window)
, $floatbar = $('#floatbar')
, isFixed = false
, navTop;
// Remove previous floatbar handlers if any.
$window.off('scroll.floatbar');
if (0 === $floatbar.length) {
// Do nothing if there's no floatbar.
return;
}
navTop = $floatbar.offset().top;
isFixed = false;
function updateFloatbarState() {
var scrollTop = $window.scrollTop();
if (scrollTop >= navTop && !isFixed) {
isFixed = true;
$floatbar.addClass('floatbar-fixed');
} else if (scrollTop <= navTop && isFixed) {
isFixed = false;
$floatbar.removeClass('floatbar-fixed');
}
}
updateFloatbarState();
$window.on('scroll.floatbar', _.throttle(updateFloatbarState, 100));
});
| JavaScript | 0 |
b9dcce9939f2bcaeec8d4dbc4d8607e3b6ba856a | remove console statement | client/components/projects/ProjectItem.js | client/components/projects/ProjectItem.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { formatTime } from '../../helpers';
class ProjectItem extends React.Component {
constructor(props) {
super(props);
this.state = {
showInput: false,
newName: '',
};
this.handleNewName = this.handleNewName.bind(this);
this.handleRenaming = this.handleRenaming.bind(this);
this.handleShowInput = this.handleShowInput.bind(this);
this.handleEnterButton = this.handleEnterButton.bind(this);
}
handleNewName(e) {
this.setState({ newName: e.target.value });
}
handleShowInput(name) {
this.setState({
showInput: !this.state.showInput,
newName: name,
});
}
handleRenaming(id, name) {
this.props.renameMe(id, name);
this.setState({
showInput: false,
});
}
handleEnterButton(event) {
if (event.charCode === 13) {
this.renameLink.click();
}
}
render() {
const { project, onDelete } = this.props;
const { newName, showInput } = this.state;
const hideTaskName = this.state.showInput ? 'none' : '';
return (
<li
style={{ paddingLeft: `${this.props.padding}px` }}
className="projects__item"
>
<Link
className="projects__item-title"
style={{ display: `${hideTaskName}` }}
to={`/projects/${project._id}`}
>
<span>{project.name}</span>
<span className="pretty-time">{formatTime(project.timeSpent)}</span>
</Link>
{showInput ? (
<input
type="text"
value={newName}
className="name-input"
onKeyPress={this.handleEnterButton}
onChange={this.handleNewName}
/>
) : null}
<div className="buttons-group">
{showInput ? (
<button
onClick={() =>
this.handleRenaming(project._id, this.state.newName)
}
ref={link => {
this.renameLink = link;
}}
className="button--info"
>
Ok
</button>
) : null}
<button
onClick={() => this.handleShowInput(project.name)}
className="button--info"
>
Edit
</button>
<button
onClick={() => onDelete(project._id)}
className="button--info button--danger"
>
Delete
</button>
</div>
</li>
);
}
}
ProjectItem.propTypes = {
project: PropTypes.object.isRequired,
onDelete: PropTypes.func.isRequired,
renameMe: PropTypes.func.isRequired,
padding: PropTypes.number.isRequired,
};
export default ProjectItem;
| import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { formatTime } from '../../helpers';
class ProjectItem extends React.Component {
constructor(props) {
super(props);
this.state = {
showInput: false,
newName: '',
};
this.handleNewName = this.handleNewName.bind(this);
this.handleRenaming = this.handleRenaming.bind(this);
this.handleShowInput = this.handleShowInput.bind(this);
this.handleEnterButton = this.handleEnterButton.bind(this);
}
handleNewName(e) {
this.setState({ newName: e.target.value });
}
handleShowInput(name) {
this.setState({
showInput: !this.state.showInput,
newName: name,
});
}
handleRenaming(id, name) {
this.props.renameMe(id, name);
this.setState({
showInput: false,
});
}
handleEnterButton(event) {
if (event.charCode === 13) {
this.renameLink.click();
}
}
render() {
const { project, onDelete } = this.props;
const { newName, showInput } = this.state;
const hideTaskName = this.state.showInput ? 'none' : '';
console.log(project);
return (
<li
style={{ paddingLeft: `${this.props.padding}px` }}
className="projects__item"
>
<Link
className="projects__item-title"
style={{ display: `${hideTaskName}` }}
to={`/projects/${project._id}`}
>
<span>{project.name}</span>
<span className="pretty-time">{formatTime(project.timeSpent)}</span>
</Link>
{showInput ? (
<input
type="text"
value={newName}
className="name-input"
onKeyPress={this.handleEnterButton}
onChange={this.handleNewName}
/>
) : null}
<div className="buttons-group">
{showInput ? (
<button
onClick={() =>
this.handleRenaming(project._id, this.state.newName)
}
ref={link => {
this.renameLink = link;
}}
className="button--info"
>
Ok
</button>
) : null}
<button
onClick={() => this.handleShowInput(project.name)}
className="button--info"
>
Edit
</button>
<button
onClick={() => onDelete(project._id)}
className="button--info button--danger"
>
Delete
</button>
</div>
</li>
);
}
}
ProjectItem.propTypes = {
project: PropTypes.object.isRequired,
onDelete: PropTypes.func.isRequired,
renameMe: PropTypes.func.isRequired,
padding: PropTypes.number.isRequired,
};
export default ProjectItem;
| JavaScript | 0.000032 |
bd57d8643a445faf8777c4d2961821cfa8e56288 | connect relevancy feature flag to experiment | share/spice/news/news.js | share/spice/news/news.js | (function (env) {
"use strict";
env.ddg_spice_news = function (api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('news');
}
var useRelevancy = DDG.opensearch.installed.experiment === "organic_ux" && DDG.opensearch.installed.variant === 'b',
entityWords = [],
goodStories = [],
searchTerm = DDG.get_query().replace(/(?: news|news ?)/i, '').trim(),
// Some sources need to be set by us.
setSourceOnStory = function(story) {
switch(story.syndicate) {
case "Topsy":
story.source = story.author || "Topsy";
break;
case "NewsCred":
if(story.source) {
if(story.author) {
story.source = story.source + " by " + story.author;
}
} else {
story.source = "NewsCred";
}
break;
}
};
if (useRelevancy) {
// Words that we have to skip in DDG.isRelevant.
var skip = [
"news",
"headline",
"headlines",
"latest",
"breaking",
"update",
"s:d",
"sort:date"
];
if (Spice.news && Spice.news.entities && Spice.news.entities.length) {
for (var j = 0, entity; entity = Spice.news.entities[j]; j++) {
var tmpEntityWords = entity.split(" ");
for (var k = 0, entityWord; entityWord = tmpEntityWords[k]; k++) {
if (entityWord.length > 3) {
entityWords.push(entityWord);
}
}
}
}
}
// Check if the title is relevant to the query.
for(var i = 0, story; story = api_result.results[i]; i++) {
if (!useRelevancy || DDG.isRelevant(story.title, skip)) {
setSourceOnStory(story);
story.sortableDate = parseInt(story.date || 0);
goodStories.push(story);
// additional news relevancy for entities. story need only
// contain one word from one entity to be good. strict indexof
// check though.
} else if (entityWords.length > 0) {
var storyOk = 0;
var tmpStoryTitle = story.title.toLowerCase();
for (var k = 0, entityWord; entityWord = entityWords[k]; k++) {
if (tmpStoryTitle.indexOf(entityWord) !== -1) {
storyOk = 1;
break;
}
}
if (storyOk) {
setSourceOnStory(story);
goodStories.push(story);
}
}
}
if (useRelevancy && goodStories < 3) {
return Spice.failed('news');
}
Spice.add({
id: 'news',
name: 'News',
data: goodStories,
ads: api_result.ads,
meta: {
idField: 'url',
count: goodStories.length,
searchTerm: searchTerm,
itemType: 'Recent News',
rerender: [
'image'
]
},
templates: {
item: 'news_item'
},
onItemShown: function(item) {
if (!item.fetch_image || item.image || item.fetched_image) { return; }
// set flag so we don't try to fetch more than once:
item.fetched_image = 1;
// try to fetch the image and set it on the model
// which will trigger the tile to re-render with the image:
$.getJSON('/f.js?o=json&i=1&u=' + item.url, function(meta) {
if (meta && meta.image) {
item.set('image', meta.image);
}
});
},
sort_fields: {
date: function(a, b) {
return b.sortableDate - a.sortableDate;
}
},
sort_default: 'date'
});
}
}(this));
| (function (env) {
"use strict";
env.ddg_spice_news = function (api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('news');
}
var useRelevancy = false,
entityWords = [],
goodStories = [],
searchTerm = DDG.get_query().replace(/(?: news|news ?)/i, '').trim(),
// Some sources need to be set by us.
setSourceOnStory = function(story) {
switch(story.syndicate) {
case "Topsy":
story.source = story.author || "Topsy";
break;
case "NewsCred":
if(story.source) {
if(story.author) {
story.source = story.source + " by " + story.author;
}
} else {
story.source = "NewsCred";
}
break;
}
};
if (useRelevancy) {
// Words that we have to skip in DDG.isRelevant.
var skip = [
"news",
"headline",
"headlines",
"latest",
"breaking",
"update",
"s:d",
"sort:date"
];
if (Spice.news && Spice.news.entities && Spice.news.entities.length) {
for (var j = 0, entity; entity = Spice.news.entities[j]; j++) {
var tmpEntityWords = entity.split(" ");
for (var k = 0, entityWord; entityWord = tmpEntityWords[k]; k++) {
if (entityWord.length > 3) {
entityWords.push(entityWord);
}
}
}
}
}
// Check if the title is relevant to the query.
for(var i = 0, story; story = api_result.results[i]; i++) {
if (!useRelevancy || DDG.isRelevant(story.title, skip)) {
setSourceOnStory(story);
story.sortableDate = parseInt(story.date || 0);
goodStories.push(story);
// additional news relevancy for entities. story need only
// contain one word from one entity to be good. strict indexof
// check though.
} else if (entityWords.length > 0) {
var storyOk = 0;
var tmpStoryTitle = story.title.toLowerCase();
for (var k = 0, entityWord; entityWord = entityWords[k]; k++) {
if (tmpStoryTitle.indexOf(entityWord) !== -1) {
storyOk = 1;
break;
}
}
if (storyOk) {
setSourceOnStory(story);
goodStories.push(story);
}
}
}
if (useRelevancy && goodStories < 3) {
return Spice.failed('news');
}
Spice.add({
id: 'news',
name: 'News',
data: goodStories,
ads: api_result.ads,
meta: {
idField: 'url',
count: goodStories.length,
searchTerm: searchTerm,
itemType: 'Recent News',
rerender: [
'image'
]
},
templates: {
item: 'news_item'
},
onItemShown: function(item) {
if (!item.fetch_image || item.image || item.fetched_image) { return; }
// set flag so we don't try to fetch more than once:
item.fetched_image = 1;
// try to fetch the image and set it on the model
// which will trigger the tile to re-render with the image:
$.getJSON('/f.js?o=json&i=1&u=' + item.url, function(meta) {
if (meta && meta.image) {
item.set('image', meta.image);
}
});
},
sort_fields: {
date: function(a, b) {
return b.sortableDate - a.sortableDate;
}
},
sort_default: 'date'
});
}
}(this));
| JavaScript | 0 |
75aa9ab5476e62adbb5abbbaaf8cbfbf5933ea94 | stop serving bower_components separately. bower_components are now inside the app directory (ionic/www) and hence get served along with the app directory. | server/boot/dev-assets.js | server/boot/dev-assets.js | var path = require('path');
module.exports = function(app) {
if (!app.get('isDevEnv')) return;
var serveDir = app.loopback.static;
app.use(serveDir(projectPath('.tmp')));
// app.use('/bower_components', serveDir(projectPath('client/bower_components')));
// app.use('/bower_components', serveDir(projectPath('bower_components')));
app.use('/lbclient', serveDir(projectPath('client/lbclient')));
};
function projectPath(relative) {
return path.resolve(__dirname, '../..', relative);
}
| var path = require('path');
module.exports = function(app) {
if (!app.get('isDevEnv')) return;
var serveDir = app.loopback.static;
app.use(serveDir(projectPath('.tmp')));
app.use('/bower_components', serveDir(projectPath('client/bower_components')));
// app.use('/bower_components', serveDir(projectPath('bower_components')));
app.use('/lbclient', serveDir(projectPath('client/lbclient')));
};
function projectPath(relative) {
return path.resolve(__dirname, '../..', relative);
}
| JavaScript | 0 |
ba0731679463757c03975f43fdbe63ed22675aff | Improve copy Grunt task structure | grunt/copy.js | grunt/copy.js | 'use strict';
module.exports = {
fonts: {
files: [
{
expand: true,
cwd: '<%= paths.src %>/fonts/',
src: ['**/*'],
dest: '<%= paths.dist %>/fonts/',
},
{
expand: true,
cwd: '<%= paths.bower %>/bootstrap/fonts/',
src: ['**/*'],
dest: '<%= paths.dist %>/fonts/',
},
],
vendor: [
{
expand: true,
cwd: '<%= paths.bower %>/',
src: ['ckeditor/**/*'],
dest: '<%= paths.dist %>/vendor/',
},
],
},
};
| 'use strict';
module.exports = {
fonts: {
files: [
{
expand: true,
cwd: '<%= paths.src %>/fonts/',
src: ['**/*'],
dest: '<%= paths.dist %>/fonts/',
},
{
expand: true,
cwd: '<%= paths.bower %>/bootstrap/fonts/',
src: ['**/*'],
dest: '<%= paths.dist %>/fonts/',
},
{
expand: true,
cwd: '<%= paths.bower %>/',
src: ['ckeditor/**/*'],
dest: '<%= paths.dist %>/vendor/',
},
],
},
};
| JavaScript | 0.000033 |