commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
e60e9444fc05f60d1794d51119641315969b7137
|
Fix gh-pages generation
|
package-scripts.js
|
package-scripts.js
|
const pathTo = require('path').join.bind(null, process.cwd());
exports.scripts = {
dev: 'cross-env NODE_ENV=development webpack-dev-server',
ghPages: [
'npm start -- build.ghPages',
`gh-pages --dist ${pathTo('example')}`
].join(' && '),
build: {
default: [
`rimraf ${pathTo('lib')} ${pathTo('example')} ${pathTo('build')}`,
'npm start -- --parallel build.lib,build.ghPages,build.dist,build.min'
].join(' && '),
lib: 'cross-env NODE_ENV=production' +
` babel ${pathTo('src')} --out-dir ${pathTo('lib')}` +
` --source-maps --ignore ${pathTo('src', 'example')}`,
ghPages: 'cross-env NODE_ENV=production BUILD=ghPages webpack',
dist: 'cross-env NODE_ENV=production BUILD=dist webpack',
min: 'cross-env NODE_ENV=production BUILD=min webpack'
},
prepublish: 'npm start -- --parallel build.lib,build.dist,build.min',
test: {
default: `cross-env NODE_ENV=test babel-node ${pathTo('test')}`,
dev: 'npm start -- test | tap-nyan',
cov: 'cross-env NODE_ENV=test' +
' babel-node node_modules/isparta/bin/isparta cover' +
` --report text --report html --report lcov --dir reports/coverage ${pathTo('test')}`,
e2e: 'cross-env NODE_ENV=development nightwatch-autorun'
},
lint: `eslint --cache ${pathTo('.')}`,
precommit: 'npm start -- lint',
prepush: 'npm start -- test',
postversion: 'git push --follow-tags',
ci: {
lint: [
'eslint --debug . --format tap > ${CIRCLE_ARTIFACTS}/lint.log',
'cat ${CIRCLE_ARTIFACTS}/lint.log | tap-xunit > ${CIRCLE_TEST_REPORTS}/lint.xml'
].join(' && '),
test: [
'NODE_ENV=test babel-node test > ${CIRCLE_ARTIFACTS}/test.log',
'cat ${CIRCLE_ARTIFACTS}/test.log | tap-xunit > ${CIRCLE_TEST_REPORTS}/test.xml'
].join(' && '),
cov: 'NODE_ENV=test babel-node node_modules/isparta/bin/isparta cover ' +
' --report text --report lcov --verbose --dir ${CIRCLE_ARTIFACTS}/coverage test/index.js',
e2e: 'REPORT_DIR=${CIRCLE_TEST_REPORTS} LOG_DIR=${CIRCLE_ARTIFACTS}' +
' NODE_ENV=development nightwatch-autorun',
codecov: 'cat ${CIRCLE_ARTIFACTS}/coverage/lcov.info | codecov'
}
};
|
JavaScript
| 0.000072 |
@@ -188,17 +188,17 @@
s',%0A
-%60
+'
gh-pages
@@ -205,34 +205,24 @@
--dist
-$%7BpathTo('
example'
)%7D%60%0A %5D.
@@ -213,19 +213,16 @@
example'
-)%7D%60
%0A %5D.joi
|
a580f49dc84a7dfc7f5776ead1fd9dbf20215f5e
|
Remove babel-node from coverage script
|
package-scripts.js
|
package-scripts.js
|
const pathTo = require('path').join.bind(null, process.cwd());
exports.scripts = {
dev: 'cross-env NODE_ENV=development webpack-dev-server',
ghPages: [
'npm start -- build.ghPages',
'gh-pages --dist example'
].join(' && '),
build: {
default: [
`rimraf ${pathTo('lib')} ${pathTo('example')} ${pathTo('build')}`,
'npm start -- --parallel build.lib,build.ghPages,build.dist,build.min'
].join(' && '),
lib: 'cross-env NODE_ENV=production' +
` babel ${pathTo('src')} --out-dir ${pathTo('lib')}` +
` --source-maps --ignore ${pathTo('src', 'example')}`,
ghPages: 'cross-env NODE_ENV=production BUILD=ghPages webpack',
dist: 'cross-env NODE_ENV=production BUILD=dist webpack',
min: 'cross-env NODE_ENV=production BUILD=min webpack'
},
prepublish: 'npm start -- --parallel build.lib,build.dist,build.min',
test: {
default: `cross-env NODE_ENV=test babel-node ${pathTo('test')}`,
dev: 'npm start -- test | tap-nyan',
cov: 'cross-env NODE_ENV=test' +
' babel-node node_modules/.bin/babel-istanbul cover' +
` --report text --report html --report lcov --dir reports/coverage ${pathTo('test')}`,
e2e: 'cross-env NODE_ENV=development nightwatch-autorun'
},
lint: `eslint --cache ${pathTo('.')}`,
precommit: 'npm start -- lint',
prepush: 'npm start -- test',
postversion: 'git push --follow-tags',
ci: {
lint: [
'eslint --debug . --format tap > ${CIRCLE_ARTIFACTS}/lint.log',
'cat ${CIRCLE_ARTIFACTS}/lint.log | tap-xunit > ${CIRCLE_TEST_REPORTS}/lint.xml'
].join(' && '),
test: [
'NODE_ENV=test babel-node test > ${CIRCLE_ARTIFACTS}/test.log',
'cat ${CIRCLE_ARTIFACTS}/test.log | tap-xunit > ${CIRCLE_TEST_REPORTS}/test.xml'
].join(' && '),
cov: 'NODE_ENV=test babel-node node_modules/.bin/babel-istanbul cover ' +
' --report text --report lcov --verbose --dir ${CIRCLE_ARTIFACTS}/coverage test/index.js',
e2e: 'REPORT_DIR=${CIRCLE_TEST_REPORTS} LOG_DIR=${CIRCLE_ARTIFACTS}' +
' NODE_ENV=development nightwatch-autorun',
codecov: 'cat ${CIRCLE_ARTIFACTS}/coverage/lcov.info | codecov'
}
};
|
JavaScript
| 0 |
@@ -1020,71 +1020,108 @@
test
-' +%0A ' babel-node node_modules/.bin/babel-istanbul cover
+ BABEL_DISABLE_CACHE=1' +%0A ' babel-istanbul cover --no-default-excludes -x **/node_modules/**
' +%0A
@@ -1843,58 +1843,107 @@
est
-babel-node node_modules/.bin/babel-istanbul cover
+BABEL_DISABLE_CACHE=1 babel-istanbul cover' +%0A ' --no-default-excludes -x **/node_modules/**
' +%0A
|
82ed2f43a6394ffb0e7886eefb69a9afc5644cb9
|
Add comments
|
package/helpers.js
|
package/helpers.js
|
NOTSET = {};
Helpers = {};
Helpers.applyMutator = function (mutator, options, keyPath/*, arguments*/) {
options = options || {};
var self = this;
var node = Tracker.nonreactive(function () {
return self.get(keyPath, NOTSET);
});
if (node === NOTSET) node = undefined;
if (options.check && !options.check(node, keyPath)) return;
var result = mutator.apply(node, Array.prototype.slice.call(arguments, 3));
self.forceInvalidate(keyPath, {noChildren: true});
return result;
};
|
JavaScript
| 0 |
@@ -18,24 +18,103 @@
pers = %7B%7D;%0A%0A
+/**%0A * With %60this%60 as a reactiveObj, applys a given mutator on a key path.%0A */%0A
Helpers.appl
|
ada17f3b6e0f1a29f319467d681c1b74a5c55070
|
add unicode test
|
test/spec/binarySpec.js
|
test/spec/binarySpec.js
|
/*global
define, describe, expect, it
*/
/*jslint
browser: true,
white: true
*/
define([
'kb/thrift/transport/echo',
'kb/thrift/protocol/binary'
], function (Thrift) {
'use strict';
function listEquals(l1, l2) {
var i,
len1 = l1.length,
len2 = l2.length;
if (len1 !== len2) {
return false;
}
for (i = 0; i < len1; i += 1) {
if (l1[i] !== l2[i]) {
return false;
}
}
return true;
}
describe('Binary Protocol with XHR Transport', function () {
/* Basic tests */
it('Sets and gets a string', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
arg = 'hello';
protocol.writeString(arg);
var result = protocol.readString();
expect(result.value).toBe(arg);
});
it('Sets and gets a binary (array of bytes)', function () {
var arg = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport);
protocol.writeBinary(arg);
var result = protocol.readBinary();
expect(result.value).toEqual(arg);
});
it('Sets and gets a list of strings', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
listInfo, i, result,
arg = ['peet', 'coco'],
list = [];
protocol.writeListBegin(Thrift.Type.STRING, 2);
arg.forEach(function (pet) {
protocol.writeString(pet);
});
protocol.writeListEnd();
listInfo = protocol.readListBegin();
for (i = 0; i < listInfo.size; i += 1) {
result = protocol.readString();
if (result) {
list.push(result.value);
}
}
protocol.readListEnd();
expect(list).toEqual(arg);
});
it('Sets and gets a map of strings to ints', function() {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
input_i64 = {
peet: 123,
coco: 456
};
protocol.writeMapBegin(Thrift.Type.STRING, Thrift.Type.I64, 2);
Object.keys(input_i64).forEach(function (pet) {
protocol.writeString(pet);
protocol.writeI64(input_i64[pet]);
});
protocol.writeMapEnd();
// Read back the dict
var output_info = protocol.readMapBegin();
for (var i = 0; i < output_info.size; i++) {
var key = protocol.readString();
if (key) {
var value = protocol.readI64();
expect(value.value).toBe(input_i64[key.value]);
}
else {
fail("Could not read key " + i);
}
}
protocol.readMapEnd();
});
// This is another way to test a Thrift map. Create a JS simple object,
// feed it into thrift, read it back and create the equivalent JS
// object, and compare the two.
it('Set and get map of String -> String', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
arg = {
hi: 'there',
greetings: 'earthling'
},
keys = Object.keys(arg);
protocol.writeMapBegin(Thrift.Type.STRING, Thrift.Type.STRING, keys.length);
keys.forEach(function (key) {
protocol.writeString(key);
protocol.writeString(arg[key]);
});
protocol.writeMapEnd();
var mapHeader = protocol.readMapBegin(), result = {};
for (var i = 0; i < mapHeader.size; i += 1) {
var key = protocol.readString().value,
value = protocol.readString().value;
result[key] = value;
}
protocol.readMapEnd();
// todo evaluate header as well.
expect(result).toEqual(arg);
});
it('Sets and gets a Set of strings', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
listInfo, i, result,
arg = ['john', 'frank', 'alice'],
set = [];
protocol.writeSetBegin(Thrift.Type.STRING, arg.length);
arg.forEach(function (name) {
protocol.writeString(name);
});
protocol.writeSetEnd();
listInfo = protocol.readSetBegin();
for (i = 0; i < listInfo.size; i += 1) {
result = protocol.readString();
if (result) {
set.push(result.value);
}
}
protocol.readSetEnd();
expect(set).toEqual(arg);
});
it('Set and get bool', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
arg = true;
protocol.writeBool(arg);
var result = protocol.readBool();
expect(result.value).toBe(arg);
});
it('Set and get I16', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport), arg = 10000;
protocol.writeI16(arg);
var result = protocol.readI16();
expect(result.value).toBe(arg);
});
it('Set and get I32', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
arg = 10000;
protocol.writeI32(arg);
var result = protocol.readI32();
expect(result.value).toBe(arg);
});
it('Set and get I64', function () {
var transport = new Thrift.EchoTransport(),
protocol = new Thrift.TBinaryProtocol(transport),
arg = 10000;
protocol.writeI64(arg);
var result = protocol.readI64();
expect(result.value).toBe(arg);
});
});
});
|
JavaScript
| 0.002639 |
@@ -963,16 +963,377 @@
%7D);%0A%0A
+ it('Sets and gets a very unicode string', function () %7B%0A var transport = new Thrift.EchoTransport(),%0A protocol = new Thrift.TBinaryProtocol(transport),%0A arg = 'hol%C3%A1';%0A protocol.writeString(arg);%0A var result = protocol.readString();%0A expect(result.value).toBe(arg);%0A %7D);%0A%0A%0A
%0A
|
05c46006ce2bb79109ba022d5deb21c63d091e1e
|
Add carousel autoplay
|
site.js
|
site.js
|
$.extend($.easing,
{
def: 'easeOutQuad',
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
}
});
(function( $ ) {
var settings;
var disableScrollFn = false;
var navItems;
var navs = {}, sections = {};
$.fn.navScroller = function(options) {
settings = $.extend({
scrollToOffset: 170,
scrollSpeed: 800,
activateParentNode: true,
}, options );
navItems = this;
//attatch click listeners
navItems.on('click', function(event){
event.preventDefault();
var navID = $(this).attr("href").substring(1);
disableScrollFn = true;
activateNav(navID);
populateDestinations(); //recalculate these!
$('html,body').animate({scrollTop: sections[navID] - settings.scrollToOffset},
settings.scrollSpeed, "easeInOutExpo", function(){
disableScrollFn = false;
}
);
});
//populate lookup of clicable elements and destination sections
populateDestinations(); //should also be run on browser resize, btw
// setup scroll listener
$(document).scroll(function(){
if (disableScrollFn) { return; }
var page_height = $(window).height();
var pos = $(this).scrollTop();
for (i in sections) {
if ((pos + settings.scrollToOffset >= sections[i]) && sections[i] < pos + page_height){
activateNav(i);
}
}
});
};
function populateDestinations() {
navItems.each(function(){
var scrollID = $(this).attr('href').substring(1);
navs[scrollID] = (settings.activateParentNode)? this.parentNode : this;
sections[scrollID] = $(document.getElementById(scrollID)).offset().top;
});
}
function activateNav(navID) {
for (nav in navs) { $(navs[nav]).removeClass('active'); }
$(navs[navID]).addClass('active');
}
})( jQuery );
$(document).ready(function (){
$('nav li a').navScroller();
//section divider icon click gently scrolls to reveal the section
$(".sectiondivider").on('click', function(event) {
$('html,body').animate({scrollTop: $(event.target.parentNode).offset().top - 50}, 400, "linear");
});
//links going to other sections nicely scroll
$(".container a").each(function(){
if ($(this).attr("href").charAt(0) == '#'){
$(this).on('click', function(event) {
event.preventDefault();
var target = $(event.target).closest("a");
var targetHight = $(target.attr("href")).offset().top
$('html,body').animate({scrollTop: targetHight - 170}, 800, "easeInOutExpo");
});
}
});
$(".single-item").slick({
dots: true,
speed: 500
});
});
|
JavaScript
| 0.000011 |
@@ -3071,16 +3071,62 @@
eed: 500
+,%0A%09autoplay: true,%0A autoplaySpeed: 3000
%0A %7D);
|
1c8424b816b8a2417c99a77ab7d17d41690a70b3
|
fix the test case of making the component globally exist
|
test/specs/test.spec.js
|
test/specs/test.spec.js
|
/*
* General specifications GridGallery
* 1- creates a grid using elements that will be in different heights and widths
* 2- will enable gallery view on click to an element of the grid (dialog)
* 3- the dialog will trigger custom events to control data in dialog
* 4- nav of items in grid (disable/enable) depending on initialization
*/
describe('GridGallery', function(){
describe('GridGallery initialization', function(){
it('Global must have the GridGallery as a property', function() {
expect(window.GridGallery).to.equal(true);
});
});
});
|
JavaScript
| 0.000031 |
@@ -535,18 +535,27 @@
.to.
+not.
equal(
-true
+undefined
);%0A
|
342c9a9c24effd48127b50d6598cd3c8c5cdc440
|
change user.username.avatar hash code - updated library
|
test/users.username.avatar.js
|
test/users.username.avatar.js
|
const supertest = require('supertest'),
should = require('should'),
crypto = require('crypto'),
path = require('path');
const app = require(path.resolve('./app')),
dbHandle = require(path.resolve('./test/handleDatabase'));
const agent = supertest.agent(app);
describe('/users/:username/avatar', function () {
let dbData;
function beforeEachPopulate(data) {
// put pre-data into database
beforeEach(async function () {
// create data in database
dbData = await dbHandle.fill(data);
});
afterEach(async function () {
await dbHandle.clear();
});
}
let loggedUser, otherUser;
beforeEachPopulate({
users: 2, // how many users to make
verifiedUsers: [0, 1] // which users to make verified
});
beforeEach(function () {
[loggedUser, otherUser] = dbData.users;
});
describe('GET', function () {
context('logged', function () {
context(':username exists', function () {
it('[nothing uploaded] responds with 200 and a default identicon (identicon.js)', async function () {
const response = await agent
.get(`/users/${otherUser.username}/avatar`)
.set('Content-Type', 'application/vnd.api+json')
.auth(loggedUser.username, loggedUser.password)
.expect(200)
.expect('Content-Type', /^application\/vnd\.api\+json/);
// the request returns a json:
// {
// data: {
// type: 'user-avatars'
// id: username
// attributes: {
// format,
// base64
// }
// }
// }
// check the proper format attribute
should(response).have.propertyByPath('body', 'data', 'type').eql('user-avatars');
should(response).have.propertyByPath('body', 'data', 'id').eql('user1');
should(response).have.propertyByPath('body', 'data', 'attributes', 'format').eql('png');
should(response).have.propertyByPath('body', 'data', 'attributes', 'base64');
// compare hash of the base64 image representation
const data = response.body.data.attributes.base64;
const hash = crypto.createHash('sha256').update(data).digest('hex');
should(hash).equal('e4bc10f78c8e645c9fe170c46534e3593f8230cb295f283c0ad2846b64914f12');
});
it('[png uploaded] responds with 200 and a png image');
it('[jpeg uploaded] responds with 200 and a jpeg image');
});
context(':username doesn\'t exist', function () {
it('responds with 404', async function () {
await agent
.get('/users/nonexistent-user/avatar')
.set('Content-Type', 'application/vnd.api+json')
.auth(loggedUser.username, loggedUser.password)
.expect(404)
.expect('Content-Type', /^application\/vnd\.api\+json/);
});
});
});
context('not logged', function () {
it('responds with 403', async function () {
await agent
.get('/users/nonexistent-user/avatar')
.set('Content-Type', 'application/vnd.api+json')
.expect(403)
.expect('Content-Type', /^application\/vnd\.api\+json/);
});
});
});
describe('PATCH', function () {
context('logged as :username', function () {
context('good data type (png, jpeg)', function () {
it('[png] responds with 200 and saves the image');
it('[jpeg] responds with 200 and saves the image');
it('crops and resizes the image to square 512x512px before saving');
it('gets rid of any previous avatar of the user');
});
context('bad data type', function () {
it('responds with 400 bad data');
});
});
context('not logged as :username', function () {
it('responds with 403');
});
});
describe('DELETE', function () {
context('logged as :username', function () {
it('[data on server] responds with 204 and deletes the avatar from server');
it('[no user image] responds with 204');
});
context('not logged as :username', function () {
it('responds with 403');
});
});
});
|
JavaScript
| 0 |
@@ -2327,72 +2327,72 @@
al('
-e4bc10f78c8e645c9fe170c46534e3593f8230cb295f283c0ad2846b64914f12
+7d76d24aee7faf11a3494ae91b577d94cbb5320cec1b2fd04187fff1197915bb
');%0A
|
422e4e1ddfc18e131f893680bb856d72d4506716
|
Improve handling of presets
|
lib/rules/property-sort-order.js
|
lib/rules/property-sort-order.js
|
'use strict';
var helpers = require('../helpers');
var getOrderFile = function (order) {
var filename = false;
if (typeof order === 'string') {
if (order === 'recess') {
filename = 'recess.yml';
}
else if (order === 'smacss') {
filename = 'smacss.yml';
}
else if (order === 'concentric') {
filename = 'concentric.yml';
}
}
if (filename) {
var orderObj = helpers.loadConfigFile('../data/property-sort-orders', filename);
return orderObj.order;
}
else {
return false;
}
};
var sortProperties = function (obj, order) {
var keys = Object.keys(obj),
unknown = [],
sorted = {},
i;
if (typeof order === 'string') {
if (order === 'alphabetical') {
keys = keys.sort();
}
}
else if (typeof order === 'object') {
var orderedKeys = [];
for (i = 0; i < order.length; i++) {
if (keys.indexOf(order[i]) !== -1) {
orderedKeys.push(order[i]);
}
}
keys = orderedKeys;
}
else {
keys = keys.sort(function (a, b) {
if (order.indexOf(a) === -1) {
if (unknown.indexOf(a) === -1) {
unknown.push(a);
}
}
if (order.indexOf(b) === -1) {
if (unknown.indexOf(b) === -1) {
unknown.push(b);
}
}
if (order.indexOf(a) > order.indexOf(b)) {
return 1;
}
if (order.indexOf(a) < order.indexOf(b)) {
return -1;
}
return 0;
});
}
for (i = 0; i < unknown.length; i++) {
if (keys.indexOf(unknown[i]) !== -1) {
keys.splice(keys.indexOf(unknown[i]), 1);
}
}
keys = keys.concat(unknown.sort());
for (i = 0; i < keys.length; i++) {
sorted[keys[i]] = obj[keys[i]];
}
return sorted;
};
module.exports = {
'name': 'property-sort-order',
'defaults': {
'order': 'alphabetical'
},
'detect': function (ast, parser) {
var result = [],
order = getOrderFile(parser.options.order) || parser.options.order;
ast.traverseByType('block', function (block) {
var properties = {},
sorted,
pKeys,
sKeys;
if (block) {
block.forEach('declaration', function (dec) {
var prop = dec.first('property'),
name = prop.first('ident');
if (name) {
properties[name.content] = prop;
}
});
sorted = sortProperties(properties, order);
pKeys = Object.keys(properties);
sKeys = Object.keys(sorted);
sKeys.every(function (e, i) {
var pKey = pKeys[i],
prop = properties[pKey];
if (e !== pKey) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': prop.start.line,
'column': prop.start.column,
'message': 'Expected `' + e + '`, found `' + pKey + '`',
'severity': parser.severity
});
}
return true;
});
}
});
// console.log(result);
return result;
}
};
|
JavaScript
| 0 |
@@ -46,16 +46,126 @@
ers');%0A%0A
+var orderPresets = %7B%0A 'recess': 'recess.yml',%0A 'smacss': 'smacss.yml',%0A 'concentric': 'concentric.yml'%0A%7D;%0A%0A
var getO
@@ -168,20 +168,22 @@
getOrder
-File
+Config
= funct
@@ -200,33 +200,8 @@
) %7B%0A
- var filename = false;%0A%0A
if
@@ -248,93 +248,37 @@
rder
- === 'recess') %7B%0A filename = 'recess.yml';%0A %7D%0A else if (order === 'smacss'
+Presets.hasOwnProperty(order)
) %7B%0A
@@ -275,32 +275,36 @@
order)) %7B%0A
+var
filename = 'smac
@@ -302,138 +302,38 @@
e =
-'smacss.yml';%0A %7D%0A else if (order === 'concentric') %7B%0A filename = 'concentric.yml';%0A %7D%0A %7D%0A%0A if (filename) %7B%0A var
+orderPresets%5Border%5D,%0A
ord
@@ -406,16 +406,19 @@
ename);%0A
+%0A
retu
@@ -436,31 +436,27 @@
.order;%0A
+
%7D%0A
-else %7B%0A
+%7D%0A%0A
return
@@ -463,20 +463,16 @@
false;%0A
- %7D%0A
%7D;%0A%0Avar
@@ -1869,20 +1869,22 @@
getOrder
-File
+Config
(parser.
|
f0ecd527fb5a4587524c8954f8d1391bf363d4e1
|
Remove social media feed checkbox from SRF
|
src/data/serviceRequestFields.js
|
src/data/serviceRequestFields.js
|
export const singleLineFields = [
{
name: 'Name',
required: true,
type: 'minLength:3',
error: 'Not a valid name'
},
{
name: 'Email',
required: true,
type: 'isEmail',
error: 'Not a valid email'
},
{
name: 'Phone',
required: false,
type: 'minLength:3',
error: 'Not a valid phone number'
},
{
name: 'Department',
required: false,
type: null,
error: 'Text is not valid'
}
]
export const multiLineFields = [
{
name: 'Project Description',
required: true,
type: null,
error: 'Not a valid project description'
},
{
name: 'Project Goal',
required: false,
type: null,
error: 'Not a valid goal'
},
{
name: 'Project Budget',
required: false,
type: null,
error: 'Not a valid number'
},
{
name: 'Key Messages',
required: false,
type: null,
error: 'Not a valid key message'
},
{
name: 'Primary Target Audience',
required: false,
type: null,
error: 'Not a valid target'
},
{
name: 'Secondary Target Audience',
required: false,
type: null,
error: 'Not a valid target'
},
{
name: 'Project Contact (if other than yourself)',
required: false,
type: null,
error: null
},
{
name: 'Comments',
required: false,
type: null,
error: 'Not a valid comment'
}
]
export const leftCheckboxes = [
{ name: 'Citation Writing' },
{ name: 'Direct Mail Piece' },
{ name: 'Editing/Proofreading' },
{ name: 'Email Blast' },
{ name: 'Event Program' },
{ name: 'Invitations' },
{
name: 'Photography',
icon: true,
dialogTitle: 'Photography',
dialogText: `<p>Photography in addition to events listed below is dependent upon student photographer availability.</p><h3>Events covered:</h3>
<ul>
<li>Graduation </li>
<li>Nursing Graduation</li>
<li>Alumni Awards</li>
<li>Faculty Awards</li>
<li>Employee Breakfast</li>
<li>Move-In Day</li>
<li>Poverello Award</li>
<li>Founders Association Awards</li>
<li>March for Life</li>
<li>Rehearsal for Anathan Theatre</li>
<li>Bishop's Requests</li>
<li>Homecoming Events</li>
<li>Festival of Praise (1)</li>
<li>High Profile Talks</li>
<li>Feast of St. Francis Mass</li>
<li>Resurrection Party</li>
<li>Holy Thursday Mass</li>
<li>Baccalaureate Mass</li>
<li>Opening of Orientation</li>
<li>Opening Convocation and Mass</li>
<li>Oath of Fidelity</li>
<li>Vocations Fair</li>
</ul>`,
conditionalFields: [
{
name: 'Photography Event Time',
required: true,
type: null
},
{
name: 'Photography Event Location',
required: true,
type: null
}
]
},
{ name: 'Print Ad' },
{ name: 'Printed Literature (Brochure,Viewbook)' },
{ name: 'Radio Ad' },
{ name: 'Reprint/Update Existing Piece' }
]
export const rightCheckboxes = [
{ name: 'Social Media (New Platform/Feed)' },
{ name: 'Social Media Ad' },
{ name: 'Social Media Post' },
{ name: 'Television Ad' },
{
name: 'Video',
conditionalFields: [
{
name: 'Video Event Time',
required: true,
type: null
},
{
name: 'Video Event Location',
required: true,
type: null
}
]
},
{ name: 'Website (Content Update)' },
{ name: 'Website (Event Posting)' },
{ name: 'Website (New Page/Section)' },
{ name: 'Writing' },
{ name: 'Other' },
{ name: 'Not sure what I need' }
]
|
JavaScript
| 0.000001 |
@@ -3009,56 +3009,8 @@
= %5B%0A
- %7B name: 'Social Media (New Platform/Feed)' %7D,%0A
%7B
|
e5d018a0c6b261fcfeb47e064e10f10f60a9c051
|
add comments
|
easy-challenges/AdditivePersistence.js
|
easy-challenges/AdditivePersistence.js
|
const assert = require('assert');
// Add numbers in num, if more than one number
// return 1 + the additive persistence of new number
// if there's just one number, return 0
const AdditivePersistence = (num) => {
const arr = num.toString().split('');
while (arr.length > 1) {
let added = 0;
for (let i = 0; i < arr.length; i += 1) {
added += parseInt(arr[i], 10);
}
return 1 + AdditivePersistence(added);
}
return 0;
};
// console.log(AdditivePersistence('3891'));
const r1 = 'addPer';
assert(r1);
|
JavaScript
| 0 |
@@ -1,39 +1,278 @@
-const assert = require('assert');%0A%0A
+/* Objective: Continually add up all the numbers in the parameter until%0Ayou reach a single number. When you reach a single number, return how many%0Atimes you had to add to reach it. */%0A%0A// solution:%0Aconst assert = require('assert');%0A%0Aconst AdditivePersistence = (num) =%3E %7B%0A
// A
@@ -314,16 +314,18 @@
number%0A
+
// retur
@@ -369,16 +369,18 @@
number%0A
+
// if th
@@ -414,48 +414,8 @@
rn 0
-%0A%0Aconst AdditivePersistence = (num) =%3E %7B
%0A c
|
d69f20b2060a7e9a512bcf5df0907fd27eb4102e
|
Fix interface reference.
|
lib/endpoints/token.js
|
lib/endpoints/token.js
|
exports = module.exports = function(server) {
return server.token();
};
exports['@require'] = [ 'http://schemas.modulate.io/js/aaa/oauth2/Server' ];
exports['@implements'] = [
'http://i.expressjs.com/endpoint',
'http://schemas.modulate.io/js/aaa/oauth2/endpoint/token'
];
|
JavaScript
| 0 |
@@ -99,33 +99,32 @@
%5B 'http://schema
-s
.modulate.io/js/
@@ -149,132 +149,4 @@
%5D;%0A
-%0Aexports%5B'@implements'%5D = %5B%0A 'http://i.expressjs.com/endpoint',%0A 'http://schemas.modulate.io/js/aaa/oauth2/endpoint/token'%0A%5D;%0A
|
32292585046c6938a90a43b5b0ff48bf6a3b07ec
|
Use ID where it's meant to use an ID
|
lib/pages/merge.js
|
lib/pages/merge.js
|
var React = require("react");
var ActionMixin = require("../logic/actions").ActionMixin([
"pr_info"
]);
module.exports = React.createClass({displayName: 'MergePage',
mixins: [ActionMixin],
componentDidMount: function() {
this.setState({
pr_info: {
pr: this.props.controller.getPullRequest()
}
});
},
squashMergeWithRewrite: function(event) {
var pr = this.state.pr_info.pr;
var commitMessage = pr.getTitle();
if (pr.getBody()) {
commitMessage += "\n\n" + pr.getBody();
}
this.props.controller.squashMergeWithRewrite(pr, commitMessage);
},
squashMergeWithoutRewrite: function(event) {
var pr = this.state.pr_info.pr;
var commitMessage = pr.getTitle();
if (pr.getBody()) {
commitMessage += "\n\n" + pr.getBody();
}
commitMessage += "\n\nSquash-merged from pull request #" + pr.getTitle() +
" from " + pr.getSource().getUser().name + "/" + pr.getSource().getRef();
this.props.controller.squashMergeWithoutRewrite(pr, commitMessage);
},
merge: function(event) {
var pr = this.state.pr_info.pr;
var commitMessage = "Merge pull request #" + pr.getId() + " from " +
pr.getSource().getUser().name + "/" + pr.getSource().getRef();
if (pr.getTitle()) {
commitMessage += "\n\n" + pr.getTitle();
}
this.props.controller.merge(pr, commitMessage);
},
render: function() {
var pr = this.state.pr_info.pr;
if (!pr || Object.keys(pr).length === 0) {
return <div>Loading pull request...</div>;
}
if (pr.getState() === "merged") {
return (
<div>Already merged</div>
);
}
var mergeable = pr.getMergeable();
if (mergeable === null) {
return (
<div>Mergeable state unknown; check again soon</div>
);
}
if (!mergeable) {
return (
<div>PR is not mergeable; try merging {pr.getDest().getRef()} out into {pr.getSource().getRef()}.</div>
);
}
return (
<div>
<a onClick={this.squashMergeWithRewrite}>Squash rewriting history</a><br />
<a onClick={this.squashMergeWithoutRewrite}>Squash leaving PR closed not merged</a><br />
<a onClick={this.merge}>Merge without squashing</a>
</div>
);
}
});
|
JavaScript
| 0.000012 |
@@ -964,21 +964,18 @@
+ pr.get
-Title
+Id
() +%0A
|
5c08a5353f689d70837f01a9c5e6d446d1d38d19
|
Normalize CLI output file path
|
bin/jade.js
|
bin/jade.js
|
#!/usr/bin/env node
/**
* Module dependencies.
*/
var fs = require('fs')
, program = require('commander')
, path = require('path')
, basename = path.basename
, dirname = path.dirname
, resolve = path.resolve
, join = path.join
, mkdirp = require('mkdirp')
, jade = require('../');
// jade options
var options = {};
// options
program
.version(require('../package.json').version)
.usage('[options] [dir|file ...]')
.option('-O, --obj <str>', 'javascript options object')
.option('-o, --out <dir>', 'output the compiled html to <dir>')
.option('-p, --path <path>', 'filename used to resolve includes')
.option('-P, --pretty', 'compile pretty html output')
.option('-c, --client', 'compile function for client-side runtime.js')
.option('-n, --name <str>', 'The name of the compiled template (requires --client)')
.option('-D, --no-debug', 'compile without debugging (smaller functions)')
.option('-w, --watch', 'watch files for changes and automatically re-render')
.option('-E, --extension <extension>', 'specify the output file extension')
.option('--name-after-file', 'Name the template after the last section of the file path (requires --client and overriden by --name)')
.option('--doctype <str>', 'Specify the doctype on the command line (useful if it is not specified by the template)')
program.on('--help', function(){
console.log(' Examples:');
console.log('');
console.log(' # translate jade the templates dir');
console.log(' $ jade templates');
console.log('');
console.log(' # create {foo,bar}.html');
console.log(' $ jade {foo,bar}.jade');
console.log('');
console.log(' # jade over stdio');
console.log(' $ jade < my.jade > my.html');
console.log('');
console.log(' # jade over stdio');
console.log(' $ echo \'h1 Jade!\' | jade');
console.log('');
console.log(' # foo, bar dirs rendering to /tmp');
console.log(' $ jade foo bar --out /tmp ');
console.log('');
});
program.parse(process.argv);
// options given, parse them
if (program.obj) {
if (fs.existsSync(program.obj)) {
options = JSON.parse(fs.readFileSync(program.obj));
} else {
options = eval('(' + program.obj + ')');
}
}
// --filename
if (program.path) options.filename = program.path;
// --no-debug
options.compileDebug = program.debug;
// --client
options.client = program.client;
// --pretty
options.pretty = program.pretty;
// --watch
options.watch = program.watch;
// --name
if (typeof program.name === 'string') {
options.name = program.name;
}
// --doctype
options.doctype = program.doctype;
// left-over args are file paths
var files = program.args;
// compile files
if (files.length) {
console.log();
if (options.watch) {
files.forEach(function(filename) {
try {
renderFile(filename);
} catch (e) {
// keep watching when error occured.
console.error(e.stack || e.message || e);
}
fs.watchFile(filename, {persistent: true, interval: 200},
function (curr, prev) {
if (curr.mtime.getTime() === prev.mtime.getTime()) return;
try {
renderFile(filename);
} catch (e) {
// keep watching when error occured.
console.error(e.stack || e.message || e);
}
});
});
process.on('SIGINT', function() {
process.exit(1);
});
} else {
files.forEach(function (file) {
renderFile(file);
});
}
process.on('exit', function () {
console.log();
});
// stdio
} else {
stdin();
}
/**
* Compile from stdin.
*/
function stdin() {
var buf = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk){ buf += chunk; });
process.stdin.on('end', function(){
var output;
if (options.client) {
output = jade.compileClient(buf, options);
} else {
var fn = jade.compile(buf, options);
var output = fn(options);
}
process.stdout.write(output);
}).resume();
process.on('SIGINT', function() {
process.stdout.write('\n');
process.stdin.emit('end');
process.stdout.write('\n');
process.exit();
})
}
/**
* Process the given path, compiling the jade files found.
* Always walk the subdirectories.
*/
function renderFile(path, rootPath) {
var re = /\.jade$/;
var stat = fs.lstatSync(path);
// Found jade file/\.jade$/
if (stat.isFile() && re.test(path)) {
var str = fs.readFileSync(path, 'utf8');
options.filename = path;
if (program.nameAfterFile) {
options.name = getNameFromFileName(path);
}
var fn = options.client ? jade.compileClient(str, options) : jade.compile(str, options);
// --extension
if (program.extension) var extname = '.' + program.extension;
else if (options.client) var extname = '.js';
else var extname = '.html';
path = path.replace(re, extname);
if (program.out) {
if (typeof rootPath !== 'undefined') {
path = path.replace(rootPath, program.out);
} else {
path = join(program.out, basename(path));
}
}
var dir = resolve(dirname(path));
mkdirp.sync(dir, 0755);
var output = options.client ? fn : fn(options);
fs.writeFileSync(path, output);
console.log(' \033[90mrendered \033[36m%s\033[0m', path);
// Found directory
} else if (stat.isDirectory()) {
var files = fs.readdirSync(path);
files.map(function(filename) {
return path + '/' + filename;
}).forEach(function (file) {
renderFile(file, rootPath || path);
});
}
}
/**
* Get a sensible name for a template function from a file path
*
* @param {String} filename
* @returns {String}
*/
function getNameFromFileName(filename) {
var file = basename(filename, '.jade');
return file.toLowerCase().replace(/[^a-z0-9]+([a-z])/g, function (_, character) {
return character.toUpperCase();
}) + 'Template';
}
|
JavaScript
| 0.000001 |
@@ -4992,32 +4992,50 @@
%7B%0A path =
+ join(program.out,
path.replace(ro
@@ -5042,27 +5042,19 @@
otPath,
-program.out
+'')
);%0A
|
4b799865f6a7379e08070a1f196dde01ec636c70
|
Update to 0.0.2. Fix the @description:en mistake.
|
oneClickRemoveWeiboPost.js
|
oneClickRemoveWeiboPost.js
|
// ==UserScript==
// @name oneClickRemoveWeiboPost
// @name:zh-CN oneClickRemoveWeiboPost 一键删除微博
// @name:zh-HK oneClickRemoveWeiboPost 一键删除微博
// @name:zh-TW oneClickRemoveWeiboPost 一键删除微博
// @name:en oneClickRemoveWeiboPost
// @name:ja oneClickRemoveWeiboPost 一键删除微博
// @namespace https://github.com/catscarlet/oneClickRemoveWeiboPost
// @description 在新浪微博(weibo.com)的个人页面添加一个[删除]按钮,点击直接删除此条微博
// @description:zh-CN 在新浪微博(weibo.com)的个人页面添加一个[删除]按钮,点击直接删除此条微博
// @description:zh-HK 在新浪微博(weibo.com)的個人頁面添加一個[删除]按鈕,點擊直接刪除此條微博
// @description:zh-TW 在新浪微博(weibo.com)的個人頁面添加一個[删除]按鈕,點擊直接刪除此條微博
// @description:en Add a [一键删除] button to the Followers Page on Sina Weibo (weibo.com). Directly delete the annoying fans by one click. No <确认/取消> any more.
// @description:ja 在フォロワーページに[X]ボタンを追加します。 ワンクリックで、迷惑なフォロワーを直接削除します。これ以上の<Y / N>はありません。
// @version 0.0.1
// @author catscarlet
// @match http://weibo.com/*
// @require https://code.jquery.com/jquery-latest.min.js
// @compatible chrome 支持
// @run-at document-end
// @grant none
// ==/UserScript==
(function() {
'use strict';
var $ = $ || window.$;
var postcount = 0;
$(function() {
console.log('oneClickRemoveWeiboPost loaded');
setTimeout(f, 1000);
function f() {
if ($('.WB_feed.WB_feed_v3.WB_feed_v4').attr('module-type') != 'feed') {
//console.log('page not match oneClickRemoveWeiboPost');
setTimeout(f, 2000);
} else {
getPosts();
setTimeout(f, 2000);
};
}
});
function detectPage() {
return 0;
}
function getPosts() {
var post_list = $('.WB_cardwrap.WB_feed_type.S_bg2.WB_feed_like');
postcount = post_list.length;
$('.WB_cardwrap.WB_feed_type.S_bg2.WB_feed_like').attr('oneClickRemoveWeiboPostCount', postcount);
$(post_list).each(function() {
var postdiv = $(this);
if (postdiv.hasClass('WB_cardwrap WB_feed_type S_bg2 WB_feed_like ')) {
var opt_box = postdiv.find('.screen_box');
if (!opt_box.attr('oneClickRemoveWeiboPostBtn')) {
var mid;
mid = $(postdiv).attr('mid');
var str = '<a href="javascript:;" class="W_ficon ficon_arrow_down S_ficon removePostDirectlyBtn" style="background-color: #D0EEFE" action-type="removePostDirectly" mid="' + mid + '">删除</a>';
opt_box.attr('oneClickRemoveWeiboPostBtn', 1);
opt_box.prepend(str);
$('.removePostDirectlyBtn').off('click');
$('.removePostDirectlyBtn').on('click', removePostDirectly);
}
}
});
};
function removePostDirectly() {
var thisBtn = $(this);
thisBtn.off('click');
thisBtn.text('移除');
thisBtn.css('background-color', '#32a2d5');
var mid = $(this).attr('mid');
var data = 'mid=' + mid;
var thisli = $(this).parent().parent().parent().parent();
$.ajax({
type: 'POST',
url: '/aj/mblog/del?ajwvr=6',
data: data,
dataType: 'json',
async: true,
success: function(msg) {
var code = msg.code;
if (code == 100000) {
console.log('移除微博:' + mid + '成功');
console.log(thisli);
thisli.remove();
} else {
thisBtn.css('background-color', '#9e9e9e');
thisBtn.text('失败');
console.log('移除微博:' + mid + '失败,可能是网络错误,或是微博更新了界面。');
console.log(msg);
}
},
error: function(msg) {
thisBtn.css('background-color', '#9e9e9e');
thisBtn.text('失败');
console.log('移除微博:' + mid + '失败,可能是网络错误,或是微博更新了界面。');
console.log(msg);
}
});
}
})();
|
JavaScript
| 0.000015 |
@@ -724,55 +724,9 @@
to
-the Followers Page on Sina Weibo (weibo.com). D
+d
irec
@@ -744,21 +744,12 @@
the
-annoying fans
+post
by
@@ -901,17 +901,17 @@
0.0.
-1
+2
%0A// @aut
@@ -966,16 +966,17 @@
http
+s
://weibo
|
9ba5db8bbd4523407fe64a72b18b16e92c2afda1
|
Add plugin-console-breadcrumbs to main process
|
packages/electron/src/client/main.js
|
packages/electron/src/client/main.js
|
const electron = require('electron')
const Client = require('@bugsnag/core/client')
const Event = require('@bugsnag/core/event')
const Breadcrumb = require('@bugsnag/core/breadcrumb')
const Session = require('@bugsnag/core/session')
const makeDelivery = require('@bugsnag/delivery-electron')
const { FileStore } = require('@bugsnag/electron-filestore')
const { schema } = require('../config/main')
Event.__type = 'electronnodejs'
// noop native client for now
const NativeClient = {
setApp () {},
setDevice () {}
}
module.exports = (opts) => {
const filestore = new FileStore(
opts.apiKey,
electron.app.getPath('userCache'),
electron.app.getPath('crashDumps')
)
const internalPlugins = [
// main internal plugins go here
require('@bugsnag/plugin-electron-state-sync'),
require('@bugsnag/plugin-electron-ipc'),
require('@bugsnag/plugin-node-uncaught-exception'),
require('@bugsnag/plugin-node-unhandled-rejection'),
require('@bugsnag/plugin-electron-app')(NativeClient, process, electron.app, electron.BrowserWindow),
require('@bugsnag/plugin-electron-app-breadcrumbs')(electron.app, electron.BrowserWindow),
require('@bugsnag/plugin-electron-device')(electron.app, electron.screen, process, filestore, NativeClient, electron.powerMonitor),
require('@bugsnag/plugin-electron-session')(electron.app, electron.BrowserWindow)
]
const bugsnag = new Client(opts, schema, internalPlugins, require('../id'))
bugsnag._setDelivery(makeDelivery(filestore, electron.net))
bugsnag._logger.debug('Loaded! In main process.')
return bugsnag
}
module.exports.Client = Client
module.exports.Event = Event
module.exports.Session = Session
module.exports.Breadcrumb = Breadcrumb
|
JavaScript
| 0 |
@@ -1378,16 +1378,68 @@
rWindow)
+,%0A require('@bugsnag/plugin-console-breadcrumbs')
%0A %5D%0A%0A
|
4fc74b8cd21a714b1a385caa4f2b7258e13ccb79
|
Add more tests on makeInitalWorld
|
spec.js
|
spec.js
|
describe('shephy', function () {
var S = shephy;
describe('makeInitalWorld', function () {
it('makes a new world', function () {
var w = S.makeInitalWorld();
[1, 3, 10, 30, 100, 300, 1000].forEach(function (n) {
expect(w.sheepStock[n].length).toEqual(n == 1 ? 6 : 7);
w.sheepStock[n].forEach(function (c) {
expect(c.type).toEqual(S.CARD_TYPE_SHEEP);
expect(c.count).toEqual(n);
});
});
expect(w.field.length).toEqual(1);
expect(w.field[0].type).toEqual(S.CARD_TYPE_SHEEP);
expect(w.field[0].count).toEqual(1);
expect(w.enemySheepCount).toEqual(1);
expect(w.deck.length).toEqual(22);
w.deck.forEach(function (c) {
expect(c.type).toEqual(S.CARD_TYPE_EVENT);
});
expect(w.discardPile.length).toEqual(0);
expect(w.exile.length).toEqual(0);
});
});
});
// vim: expandtab softtabstop=2 shiftwidth=2 foldmethod=marker
// vim: foldmethod=expr
// vim: foldexpr=getline(v\:lnum)=~#'\\v<x?(describe|it|beforeEach|afterEach)>.*<function>\\s*\\([^()]*\\)\\s*\\{'?'a1'\:(getline(v\:lnum)=~#'^\\s*});$'?'s1'\:'=')
|
JavaScript
| 0 |
@@ -875,16 +875,977 @@
%7D);%0A
+ it('returns a world with the same regions except Deck', function () %7B%0A var w0 = S.makeInitalWorld();%0A var wt = S.makeInitalWorld();%0A%0A %5B%0A 'sheepStock',%0A 'field',%0A 'enemySheepCount',%0A 'discardPile',%0A 'exile'%0A %5D.forEach(function (member) %7B%0A expect(wt%5Bmember%5D).toEqual(w0%5Bmember%5D);%0A %7D);%0A%0A var ns0 = w0.deck.map(function (c) %7Breturn c.name;%7D);%0A ns0.sort();%0A var nst = wt.deck.map(function (c) %7Breturn c.name;%7D);%0A nst.sort();%0A expect(ns0).toEqual(nst);%0A %7D);%0A it('returns a shuffled Deck with the same set of cards', function () %7B%0A while (true) %7B%0A var w0 = S.makeInitalWorld();%0A var wt = S.makeInitalWorld();%0A var ns0 = w0.deck.map(function (c) %7Breturn c.name;%7D);%0A var nst = wt.deck.map(function (c) %7Breturn c.name;%7D);%0A if (ns0 == nst)%0A continue;%0A%0A expect(ns0).not.toEqual(nst);%0A break;%0A %7D%0A %7D);%0A
%7D);%0A%7D)
|
8b26e0ab6652394f929a6fed531af6080b1e1bc3
|
Use get_channel_details for download summary
|
contentcuration/contentcuration/frontend/shared/vuex/channel/actions.js
|
contentcuration/contentcuration/frontend/shared/vuex/channel/actions.js
|
import pickBy from 'lodash/pickBy';
import { NOVALUE } from 'shared/constants';
import { Channel, Invitation, User } from 'shared/data/resources';
import client from 'shared/client';
/* CHANNEL LIST ACTIONS */
export function loadChannelList(context, payload = {}) {
if (payload.listType) {
payload[payload.listType] = true;
delete payload.listType;
}
const params = {
// Default to getting not deleted channels
deleted: false,
...payload,
};
return Channel.where(params).then(channels => {
context.commit('ADD_CHANNELS', channels);
return channels;
});
}
export function loadChannel(context, id) {
return Channel.get(id)
.then(channel => {
context.commit('ADD_CHANNEL', channel);
return channel;
})
.catch(() => {
return;
});
}
/* CHANNEL EDITOR ACTIONS */
export function createChannel(context) {
const session = context.rootState.session;
const channelData = {
name: '',
description: '',
language: session.preferences ? session.preferences.language : session.currentLanguage,
content_defaults: session.preferences,
thumbnail_url: '',
bookmark: false,
edit: true,
deleted: false,
editors: [session.currentUser.id],
viewers: [],
};
return Channel.put(channelData).then(id => {
context.commit('ADD_CHANNEL', {
id,
...channelData,
});
return id;
});
}
export function updateChannel(
context,
{
id,
name = NOVALUE,
description = NOVALUE,
thumbnailData = NOVALUE,
language = NOVALUE,
contentDefaults = NOVALUE,
} = {}
) {
if (context.state.channelsMap[id]) {
const channelData = {};
if (!id) {
throw ReferenceError('id must be defined to update a channel');
}
if (name !== NOVALUE) {
channelData.name = name;
}
if (description !== NOVALUE) {
channelData.description = description;
}
if (thumbnailData !== NOVALUE) {
channelData.thumbnail = thumbnailData.thumbnail;
channelData.thumbnail_url = thumbnailData.thumbnail_url;
channelData.thumbnail_encoding = thumbnailData.thumbnail_encoding || {};
}
if (language !== NOVALUE) {
channelData.language = language;
}
if (contentDefaults !== NOVALUE) {
const originalData = context.state.channelsMap[id].content_defaults;
// Pick out only content defaults that have been changed.
contentDefaults = pickBy(contentDefaults, (value, key) => value !== originalData[key]);
if (Object.keys(contentDefaults).length) {
channelData.content_defaults = contentDefaults;
}
}
context.commit('UPDATE_CHANNEL', { id, ...channelData });
return Channel.update(id, channelData);
}
}
export function bookmarkChannel(context, { id, bookmark }) {
return Channel.update(id, { bookmark }).then(() => {
context.commit('SET_BOOKMARK', { id, bookmark });
});
}
export function deleteChannel(context, channelId) {
return Channel.update(channelId, { deleted: true }).then(() => {
context.commit('REMOVE_CHANNEL', { id: channelId });
});
}
export function loadChannelDetails(context, channelId) {
return client.get(window.Urls.get_channel_details(channelId)).then(response => {
return response.data;
});
}
export function getChannelListDetails(context, { excluded = [], ...query }) {
// Make sure we're querying for all channels that match the query
query.public = true;
query.published = true;
query.page_size = Number.MAX_SAFE_INTEGER;
query.page = 1;
return Channel.searchCatalog(query).then(page => {
let results = page.results.filter(channel => !excluded.includes(channel.id));
let promises = results.map(channel =>
client.get(window.Urls.get_node_details(channel.root_id))
);
return Promise.all(promises).then(responses => {
return responses.map((response, index) => {
return {
...results[index],
...response.data,
};
});
});
});
}
/* SHARING ACTIONS */
export function loadChannelUsers(context, channelId) {
return Promise.all([
User.where({ channel: channelId, include_viewonly: true }),
Invitation.where({ channel: channelId }),
]).then(results => {
context.commit('ADD_USERS', results[0]);
context.commit('ADD_INVITATIONS', results[1]);
});
}
export function sendInvitation(context, { channelId, email, shareMode }) {
return client
.post(window.Urls.send_invitation_email(), {
user_email: email,
share_mode: shareMode,
channel_id: channelId,
})
.then(response => {
context.commit('ADD_INVITATION', response.data);
});
}
export function deleteInvitation(context, invitationId) {
// return Invitation.delete(invitationId).then(() => {
// context.commit('DELETE_INVITATION', invitationId);
// });
// Update so that other user's invitations disappear
return Invitation.update(invitationId, { declined: true }).then(() => {
context.commit('DELETE_INVITATION', invitationId);
});
}
export function makeEditor(context, { channelId, userId }) {
let updates = {
editors: context.state.channelsMap[channelId].editors.concat([userId]),
viewers: context.state.channelsMap[channelId].viewers.filter(id => id !== userId),
};
return Channel.update(channelId, updates).then(() => {
context.commit('UPDATE_CHANNEL', { id: channelId, ...updates });
});
}
export function removeViewer(context, { channelId, userId }) {
let viewers = context.state.channelsMap[channelId].viewers.filter(id => id !== userId);
return Channel.update(channelId, { viewers }).then(() => {
context.commit('UPDATE_CHANNEL', { id: channelId, viewers });
});
}
|
JavaScript
| 0 |
@@ -3701,22 +3701,16 @@
annel =%3E
-%0A
client.
@@ -3733,12 +3733,15 @@
get_
-node
+channel
_det
@@ -3757,22 +3757,12 @@
nel.
-root_id))%0A
+id))
);%0A
|
20a5176e75b49fe8e9eea8d18f9fa4146b6e2fb6
|
Fix number rep
|
lib/reps/number.js
|
lib/reps/number.js
|
/* See license.txt for terms of usage */
"use strict";
define(function(require, exports, module) {
// Dependencies
const React = require("react");
const { Reps } = require("reps/reps");
const { ObjectBox } = require("reps/object-box");
/**
* @template TODO docs
*/
const Number = React.createClass({
displayName: "Number",
render: function() {
var value = this.props.object;
if (this.props.mode == "tiny") {
return (
ObjectBox({className: "number"},
value
)
)
}
else {
return (
ObjectBox({className: "number"},
this.stringify(value)
)
)
}
},
stringify: function(object) {
return (Object.is(object, -0) ? "-0" : String(object));
},
});
// Registration
function supportsObject(object, type) {
return type == "boolean" || type == "number";
}
Reps.registerRep({
rep: React.createFactory(Number),
supportsObject: supportsObject
});
exports.Number = React.createFactory(Number);
});
|
JavaScript
| 0.000069 |
@@ -386,47 +386,8 @@
ct;%0A
- if (this.props.mode == %22tiny%22) %7B%0A
@@ -393,34 +393,32 @@
return (%0A
-
-
ObjectBox(%7Bclass
@@ -438,117 +438,8 @@
%22%7D,%0A
- value%0A )%0A )%0A %7D%0A else %7B%0A return (%0A ObjectBox(%7BclassName: %22number%22%7D,%0A
@@ -474,25 +474,15 @@
-
)%0A
- )%0A %7D
+)
%0A %7D
|
c8b80f2c10e94369c6b11f568b8d6903b4b061b9
|
Use hxl.wrap instead of calling constructors directly.
|
test/test-hxlfilters.js
|
test/test-hxlfilters.js
|
////////////////////////////////////////////////////////////////////////
// Test various HXL filters
////////////////////////////////////////////////////////////////////////
//
// hxl.classes.BaseFilter
//
QUnit.module("hxl.classes.BaseFilters", {
setup: function () {
this.test_data = [
['Pointless header'],
['Organisation', 'Sector', 'Province'],
['#org', '#sector+cluster', '#adm1'],
['Org 1', 'WASH', 'Coastal Province'],
['Org 2', 'Health', 'Mountain Province'],
['Org 3', 'Protection', 'Coastal Province']
];
this.dataset = new hxl.classes.Dataset(this.test_data);
}
});
QUnit.test("identity filter", function(assert) {
var filter = new hxl.classes.BaseFilter(this.dataset);
assert.deepEqual(filter.columns, this.dataset.columns);
assert.deepEqual(filter.rows, this.dataset.rows);
});
//
// hxl.classes.RowFilter
//
QUnit.test("row filter value string predicate", function(assert) {
var predicates = [
{ pattern: '#adm1', test: 'Coastal Province'}
];
var filter = new hxl.classes.RowFilter(this.dataset, predicates);
assert.deepEqual(filter.columns, this.dataset.columns);
assert.equal(filter.rows.length, 2);
assert.deepEqual(filter.getValues('#adm1'), ['Coastal Province']);
// test convenience methods
assert.deepEqual(filter.columns, this.dataset.withRows(predicates).columns);
assert.deepEqual(filter.values, this.dataset.withRows(predicates).values);
});
QUnit.test("row filter invert", function(assert) {
var predicates = [
{ pattern: '#adm1', test: 'Coastal Province'}
];
var filter = new hxl.classes.RowFilter(this.dataset, predicates, true);
assert.deepEqual(filter.columns, this.dataset.columns);
assert.equal(filter.rows.length, 1);
assert.deepEqual(filter.getValues('#adm1'), ['Mountain Province']);
// test convenience methods
assert.deepEqual(filter.columns, this.dataset.withoutRows(predicates).columns);
assert.deepEqual(filter.values, this.dataset.withoutRows(predicates).values);
});
QUnit.test("row filter value function predicate", function(assert) {
var predicates = [
{
pattern: '#sector+cluster',
test: function(value) { return value != 'Protection'; }
}
];
var filter = new hxl.classes.RowFilter(this.dataset, predicates);
assert.equal(filter.rows.length, 2);
assert.deepEqual(filter.getValues('#sector'), ['WASH', 'Health']);
// test convenience methods
assert.deepEqual(filter.columns, this.dataset.withRows(predicates).columns);
assert.deepEqual(filter.values, this.dataset.withRows(predicates).values);
});
QUnit.test("row filter row predicate", function(assert) {
var predicates = [
{
test: function(row) { return (row.get('#org') == 'Org 1' && row.get('#adm1') == 'Coastal Province'); }
}
];
var filter = new hxl.classes.RowFilter(this.dataset, predicates);
assert.equal(filter.rows.length, 1);
// test convenience methods
assert.deepEqual(filter.columns, this.dataset.withRows(predicates).columns);
assert.deepEqual(filter.values, this.dataset.withRows(predicates).values);
});
//
// hxl.classes.ColumnFilter
//
QUnit.test("column filter whitelist", function(assert) {
var blacklist = [];
var whitelist = ['#sector'];
var filter = new hxl.classes.ColumnFilter(this.dataset, blacklist, whitelist);
assert.deepEqual(filter.columns.map(function (col) {
return col.displayTag;
}), ['#sector+cluster']);
assert.deepEqual(filter.rows.map(function (row) {
return row.values;
}), this.test_data.slice(3).map(function (data) {
return [data[1]];
}));
// test that the convenience methods work
assert.deepEqual(filter.columns, this.dataset.withColumns(whitelist).columns);
assert.deepEqual(filter.values, this.dataset.withColumns(whitelist).values);
});
QUnit.test("column filter blacklist", function(assert) {
var blacklist = ['#sector'];
var filter = new hxl.classes.ColumnFilter(this.dataset, blacklist);
assert.deepEqual(filter.columns.map(function (col) {
return col.displayTag;
}), ['#org', '#adm1']);
assert.deepEqual(filter.rows.map(function (row) {
return row.values;
}), this.test_data.slice(3).map(function (data) {
return [data[0], data[2]];
}));
// test that the convenience methods work
assert.deepEqual(filter.columns, this.dataset.withoutColumns(blacklist).columns);
assert.deepEqual(filter.values, this.dataset.withoutColumns(blacklist).values);
});
//
// hxl.classes.CountFilter
//
QUnit.test("count filter single column", function(assert) {
var patterns = ['#adm1'];
var filter = new hxl.classes.CountFilter(this.dataset, patterns);
assert.equal(filter.rows.length, 2);
assert.deepEqual(filter.columns.map(
function (col) { return col.displayTag; }
), ['#adm1', '#count_num']);
// test that the convenience methods work
assert.deepEqual(filter.columns, this.dataset.count(patterns).columns);
assert.deepEqual(filter.values, this.dataset.count(patterns).values);
});
QUnit.test("count filter multiple columns", function(assert) {
var patterns = ['#sector', '#adm1'];
var filter = new hxl.classes.CountFilter(this.dataset, patterns);
assert.equal(filter.rows.length, 3);
assert.deepEqual(filter.columns.map(
function (col) { return col.displayTag; }
), ['#sector+cluster', '#adm1', '#count_num']);
// test that the convenience methods work
assert.deepEqual(filter.columns, this.dataset.count(patterns).columns);
assert.deepEqual(filter.values, this.dataset.count(patterns).values);
});
QUnit.test("test numeric aggregation", function(assert) {
var source = new hxl.classes.CountFilter(this.dataset, ['#sector', '#adm1']);
var patterns = ['#adm1'];
var aggregate = '#count_num';
var filter = new hxl.classes.CountFilter(source, patterns, aggregate);
assert.equal(filter.rows.length, 2);
assert.deepEqual(filter.rows.map(function (row) { return row.values; }), [
['Coastal Province', 2, 2, 1, 1, 1],
['Mountain Province', 1, 1, 1, 1, 1]
]);
assert.deepEqual(filter.columns.map(
function (col) { return col.displayTag; }
), ['#adm1', '#count_num', '#count_num+sum', '#count_num+avg', '#count_num+min', '#count_num+max']);
// test that the convenience methods work
assert.deepEqual(filter.columns, source.count(patterns, aggregate).columns);
assert.deepEqual(filter.values, source.count(patterns, aggregate).values);
});
// end
|
JavaScript
| 0 |
@@ -630,31 +630,16 @@
t =
-new hxl.classes.Dataset
+hxl.wrap
(thi
|
0d9cabb1edda88bed2dd5b2d79488044f2ab1e7d
|
update for maxthon
|
test/baidu/browser/maxthon.js
|
test/baidu/browser/maxthon.js
|
module("baidu.browser.maxthon");
test("maxthon", function() {
try{
//遨游三这个地方改掉了……
window.external.max_invoke("GetHotKey");
ok(baidu.browser.maxthon, 'is maxthon');
}catch(ex){
if(baidu.browser.maxthon == 3)
ok(true, '傲游3居然也抛异常……');
equals(baidu.browser.maxthon, undefined, 'not maxthon');
}
});
|
JavaScript
| 0 |
@@ -64,26 +64,20 @@
%7B%0D%0A%09
-
try
+
%7B%0D%0A%09
-
%09//
+
%E9%81%A8%E6%B8%B8%E4%B8%89%E8%BF%99
@@ -87,24 +87,17 @@
%E6%94%B9%E6%8E%89%E4%BA%86%E2%80%A6%E2%80%A6%0D%0A%09
-
+%09
window.e
@@ -131,24 +131,17 @@
ey%22);%0D%0A%09
-
+%09
ok(baidu
@@ -179,33 +179,29 @@
;%0D%0A%09
-
%7D
+
catch
+
(ex)
+
%7B%0D%0A%09
-
%09if
+
(bai
@@ -227,20 +227,16 @@
== 3)%0D%0A%09
-
%09%09ok(tru
@@ -260,16 +260,9 @@
;%0D%0A%09
-
+%09
equa
@@ -320,12 +320,8 @@
;%0D%0A%09
-
%7D%0D%0A%7D
|
96e941b802c43256ed89858d0981d1b66b698873
|
Revert "Workaround to deal with an issue in node-webkit where the validate function fails on object literals"
|
lib/utils/parameter-validator.js
|
lib/utils/parameter-validator.js
|
'use strict';
var _ = require('lodash');
var util = require('util');
var validateDeprecation = function(value, expectation, options) {
if (!options.deprecated) {
return;
}
var valid = (value instanceof options.deprecated || typeof(value) === typeof(options.deprecated.call()));
if (valid) {
var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);
console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
}
return valid;
};
var validate = function(value, expectation, options) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || typeof(value) === typeof(expectation.call())) {
return true;
}
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};
var ParameterValidator = module.exports = {
check: function(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
return true;
}
if (value === undefined) {
throw new Error('No value has been passed.');
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.');
}
return false
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}
};
|
JavaScript
| 0 |
@@ -190,17 +190,16 @@
valid =
-(
value in
@@ -229,64 +229,8 @@
ated
- %7C%7C typeof(value) === typeof(options.deprecated.call()))
;%0A%0A
@@ -518,276 +518,42 @@
) %7B%0A
-%0A // the second part of this check is a workaround to deal with an issue that occurs in node-webkit when%0A // using object literals. https://github.com/sequelize/sequelize/issues/2685%0A if (value instanceof expectation %7C%7C typeof(value) === typeof(expectation.call())
+ if (value instanceof expectation
) %7B%0A
@@ -1284,13 +1284,12 @@
ns);%0A %7D%0A%7D;%0A
-%0A
|
963b993187dfb3886e6f73a76a2aa2a258ea8103
|
Uppercased some constants
|
views/game/list.js
|
views/game/list.js
|
var _ = require('lodash');
var db = require('../../db');
var gamelib = require('../../lib/game');
var user = require('../../lib/user');
module.exports = function(server) {
function matchesAny(list) {
return (function(x) {
return _.contains(list, x);
});
};
const accepted_filters = {
status: {
description: 'Filter by current status of the game',
isRequired: false,
isIn: ['approved', 'pending', 'rejected'],
requiredPermissions: matchesAny(['reviewer', 'admin'])
}
};
const restricted_filters = _.pick(accepted_filters, (function() {
return Object.keys(accepted_filters).filter(function(f) {
return !!accepted_filters[f].requiredPermissions;
});
})());
var DEFAULT_COUNT = 15;
// Sample usage:
// % curl 'http://localhost:5000/game/list'
server.get({
url: '/game/list',
swagger: {
nickname: 'list',
notes: 'List of games matching provided filter',
summary: 'Game List'
},
validation: _.extend({
_user: {
description: 'User (ID or username slug)',
isRequired: false // Only required for restricted filters
},
count: {
description: 'Maximum number of games to return',
isRequired: false,
isInt: true,
min: 1,
max: 100
}
}, accepted_filters)
}, db.redisView(function(client, done, req, res, wrap) {
var GET = req.params;
var filters = _.pick(GET, Object.keys(accepted_filters));
var count = (GET.count && parseInt(GET.count)) || DEFAULT_COUNT;
ensureAuthorized(function() {
// TODO: Filter only 'count' games without having to fetch them all first
// (will be somewhat tricky since we need to ensure order to do pagination
// properly, and we use UUIDs for game keys that have no logical order in the db)
gamelib.getPublicGameObjList(client, null, filters, function(games) {
res.json(_.first(games, count));
done();
});
});
function ensureAuthorized(callback) {
var filtersToAuthorize = _.pick(restricted_filters, Object.keys(filters));
var authKeys = Object.keys(filtersToAuthorize);
if (!authKeys.length) {
return callback();
}
var _user = GET._user;
if (!_user) {
return notAuthorized();
}
var email;
if (!(email = auth.verifySSA(_user))) {
res.json(403, {error: 'bad_user'});
done();
return;
}
user.getUserFromEmail(client, email, function(err, userData) {
if (err) {
res.json(500, {error: err || 'db_error'});
done();
return;
}
var permissions = Object.keys(_.map(userData.permissions, function(hasPerm, p) {
return !!hasPerm;
}));
var hasPermissions = _.every(authKeys, function(key) {
return filtersToAuthorize[key](permissions);
});
if (!hasPermissions) {
notAuthorized();
} else {
callback();
}
});
function notAuthorized() {
res.json(401, {
error: 'not_permitted',
detail: 'provided filters require additional permissions'
});
done();
};
}
}));
};
|
JavaScript
| 0.999054 |
@@ -299,32 +299,32 @@
const
-accepted_filters
+ACCEPTED_FILTERS
= %7B%0A
@@ -587,52 +587,52 @@
nst
-restricted_filters = _.pick(accepted_filters
+RESTRICTED_FILTERS = _.pick(ACCEPTED_FILTERS
, (f
@@ -670,32 +670,32 @@
ct.keys(
-accepted_filters
+ACCEPTED_FILTERS
).filter
@@ -730,32 +730,32 @@
eturn !!
-accepted_filters
+ACCEPTED_FILTERS
%5Bf%5D.requ
@@ -1515,32 +1515,32 @@
%7D,
-accepted_filters
+ACCEPTED_FILTERS
)%0A %7D,
@@ -1674,24 +1674,24 @@
eys(
-accepted_filters
+ACCEPTED_FILTERS
));%0A
@@ -2347,26 +2347,26 @@
ick(
-restricted_filters
+RESTRICTED_FILTERS
, Ob
@@ -3406,21 +3406,24 @@
-if
+return
(
-!
hasPermi
@@ -3432,123 +3432,41 @@
ions
-) %7B%0A notAuthorized();%0A %7D else %7B%0A callback();%0A %7D
+ ? callback() : notAuthorized());
%0A
|
30168260aeca397162548ef6f370a6dbf85a74d7
|
Fix page rendering issue
|
routes/facebook.js
|
routes/facebook.js
|
// --------- Dependencies ---------
var User = require.main.require('./models/user');
var validator = require('validator');
require.main.require('./config/custom-validation.js')(validator);
module.exports = function(app, passport, isLoggedIn) {
app.get('/connect/auth/facebook', isLoggedIn,
passport.authenticate('facebook', {
scope: ['user_managed_groups', 'user_likes']
}));
app.get('/connect/auth/facebook/callback', isLoggedIn,
passport.authenticate('facebook', {
failureRedirect: '/connect',
successRedirect: '/setup/facebook/groups'
}));
app.get('/setup/facebook/groups', isLoggedIn, function(req, res) {
User.setUpFacebookGroups(req.user._id, function(err, allGroups,
existingGroups) {
// An error occurred
if (err) {
req.flash('setupMessage', err.toString());
res.redirect('/setup/facebook/groups');
// Found groups
} else if (Object.keys(allGroups).length > 0) {
// Fill in checkboxes for existing groups
if (existingGroups.length > 0) {
var groupIds = [];
existingGroups.forEach(function(group) {
groupIds.push(group.groupId);
});
for (var key in allGroups) {
if (groupIds.indexOf(allGroups[key].id) > -1) {
allGroups[key].checked = true;
} else {
allGroups[key].checked = false;
}
}
}
res.render('facebook-setup', {
message: req.flash('setupMessage'),
content: allGroups,
contentName: 'groups'
});
// No groups found; proceed to pages
} else {
res.redirect('/setup/facebook/pages');
}
}
);
});
app.post('/setup/facebook/groups', isLoggedIn, function(req, res) {
User.saveFacebookGroups(req.user._id, Object.keys(req.body),
function(err, data) {
// An error occurred
if (err) {
req.flash('setupMessage', err.toString());
res.redirect('/setup/facebook/groups');
// Saved groups
} else {
res.redirect('/setup/facebook/pages');
}
}
);
});
app.get('/setup/facebook/pages', isLoggedIn, function(req, res) {
User.setUpFacebookPages(req.user._id, function(err, allPages,
existingPages) {
// An error occurred
if (err) {
req.flash('setupMessage', err.toString());
res.redirect('/setup/facebook/groups');
// Found pages
} else if (Object.keys(allPages).length > 0) {
// Fill in checkboxes for existing pages
if (existingPages.length > 0) {
var pageIds = [];
existingPages.forEach(function(page) {
pageIds.push(page.pageId);
});
for (var key in allPages) {
if (pageIds.indexOf(allPages[key].id) > -1) {
allPages[key].checked = true;
} else {
allPages[key].checked = false;
}
}
}
// No pages found; proceed to connect page
} else {
res.redirect('/connect');
}
}
);
});
app.post('/setup/facebook/pages', isLoggedIn, function(req, res) {
User.saveFacebookPages(req.user._id, Object.keys(req.body),
function(err, data) {
// An error occurred
if (err) {
req.flash('setupMessage', err.toString());
res.redirect('/setup/facebook/pages');
// Saved pages; return to connect page
} else {
req.flash('connectMessage',
'Your Facebook settings have been updated.');
res.redirect('/connect');
}
}
);
});
app.get('/connect/remove/facebook', isLoggedIn, function(req, res) {
User.removeFacebook(req.user.id, function(err) {
if (err) {
req.flash('connectMessage', err.toString());
} else {
req.flash('connectMessage',
'Your Facebook connection has been removed.');
}
res.redirect('/connect');
});
});
};
|
JavaScript
| 0 |
@@ -2573,32 +2573,241 @@
%7D else %7B%0A
+ if (!req.session.flash.connectMessage) %7B%0A req.flash('connectMessage',%0A 'Your Facebook settings have been updated.');%0A %7D%0A
@@ -2841,32 +2841,32 @@
cebook/pages');%0A
-
@@ -4011,32 +4011,256 @@
%7D
+%0A%0A res.render('facebook-setup', %7B%0A message: req.flash('setupMessage'),%0A content: allPages,%0A contentName: 'pages'%0A %7D);
%0A
@@ -4857,32 +4857,97 @@
%7D else %7B%0A
+ if (!req.session.flash.connectMessage) %7B%0A
@@ -4970,32 +4970,36 @@
onnectMessage',%0A
+
@@ -5044,32 +5044,54 @@
een updated.');%0A
+ %7D%0A
|
467e5c6251d2e84221d2ec0fab9a4ec317ae9a79
|
use stats in tar.js and core.js (#326)
|
lib/plugins/tar.js
|
lib/plugins/tar.js
|
/**
* TAR Format Plugin
*
* @module plugins/tar
* @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}
* @copyright (c) 2012-2014 Chris Talkington, contributors.
*/
var zlib = require('zlib');
var engine = require('tar-stream');
var util = require('archiver-utils');
/**
* @constructor
* @param {TarOptions} options
*/
var Tar = function(options) {
if (!(this instanceof Tar)) {
return new Tar(options);
}
options = this.options = util.defaults(options, {
gzip: false
});
if (typeof options.gzipOptions !== 'object') {
options.gzipOptions = {};
}
this.supports = {
directory: true,
symlink: true
};
this.engine = engine.pack(options);
this.compressor = false;
if (options.gzip) {
this.compressor = zlib.createGzip(options.gzipOptions);
this.compressor.on('error', this._onCompressorError.bind(this));
}
};
/**
* [_onCompressorError description]
*
* @private
* @param {Error} err
* @return void
*/
Tar.prototype._onCompressorError = function(err) {
this.engine.emit('error', err);
};
/**
* [append description]
*
* @param {(Buffer|Stream)} source
* @param {TarEntryData} data
* @param {Function} callback
* @return void
*/
Tar.prototype.append = function(source, data, callback) {
var self = this;
data.mtime = data.date;
function append(err, sourceBuffer) {
if (err) {
callback(err);
return;
}
self.engine.entry(data, sourceBuffer, function(err) {
callback(err, data);
});
}
if (data.sourceType === 'buffer') {
append(null, source);
} else if (data.sourceType === 'stream' && data._stats) {
data.size = data._stats.size;
var entry = self.engine.entry(data, function(err) {
callback(err, data);
});
source.pipe(entry);
} else if (data.sourceType === 'stream') {
util.collectStream(source, append);
}
};
/**
* [finalize description]
*
* @return void
*/
Tar.prototype.finalize = function() {
this.engine.finalize();
};
/**
* [on description]
*
* @return this.engine
*/
Tar.prototype.on = function() {
return this.engine.on.apply(this.engine, arguments);
};
/**
* [pipe description]
*
* @param {String} destination
* @param {Object} options
* @return this.engine
*/
Tar.prototype.pipe = function(destination, options) {
if (this.compressor) {
return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options);
} else {
return this.engine.pipe.apply(this.engine, arguments);
}
};
/**
* [unpipe description]
*
* @return this.engine
*/
Tar.prototype.unpipe = function() {
if (this.compressor) {
return this.compressor.unpipe.apply(this.compressor, arguments);
} else {
return this.engine.unpipe.apply(this.engine, arguments);
}
};
module.exports = Tar;
/**
* @typedef {Object} TarOptions
* @global
* @property {Boolean} [gzip=false] Compress the tar archive using gzip.
* @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options}
* to control compression.
* @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties.
*/
/**
* @typedef {Object} TarEntryData
* @global
* @property {String} name Sets the entry name including internal path.
* @property {(String|Date)} [date=NOW()] Sets the entry date.
* @property {Number} [mode=D:0755/F:0644] Sets the entry permissions.
* @property {String} [prefix] Sets a path prefix for the entry name. Useful
* when working with methods like `directory` or `glob`.
* @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing
* for reduction of fs stat calls when stat data is already known.
*/
/**
* TarStream Module
* @external TarStream
* @see {@link https://github.com/mafintosh/tar-stream}
*/
|
JavaScript
| 0 |
@@ -1646,25 +1646,24 @@
am' && data.
-_
stats) %7B%0A
@@ -1680,17 +1680,16 @@
= data.
-_
stats.si
|
e21417dc8e7335933ab995f8f1224c07baf28985
|
increase font-size
|
lib/views/scripts/bad_browser.js
|
lib/views/scripts/bad_browser.js
|
(function() {
function supportsFixed() {
var container = document.body;
if (document.createElement && container && container.appendChild && container.removeChild) {
var el = document.createElement('div');
if (!el.getBoundingClientRect) return null;
el.innerHTML = 'x';
el.style.cssText = 'position:fixed;top:100px;';
container.appendChild(el);
var originalHeight = container.style.height,
originalScrollTop = container.scrollTop;
container.style.height = '3000px';
container.scrollTop = 500;
var elementTop = el.getBoundingClientRect().top;
container.style.height = originalHeight;
var isSupported = (elementTop === 100);
container.removeChild(el);
container.scrollTop = originalScrollTop;
return isSupported;
}
return null;
}
function getTopMargin(){
if (window.getComputedStyle)
return window.getComputedStyle(document.body).getPropertyValue("margin-top");
var margin = document.body.currentStyle['margin'];
var match = margin.match(/^\d+/)
return (match ? match[0] : 0) + 'px';
}
function convertToPixels(_str, _context) {
if (/px$/.test(_str)) {
return parseFloat(_str);
}
if (!_context) {
context = document.body;
}
var tmp = document.createElement('div');
tmp.style.visbility = 'hidden';
tmp.style.position = 'absolute';
tmp.style.lineHeight = '0';
if (/%$/.test(_str)) {
context = _context.parentNode || _context;
tmp.style.height = _str;
} else {
tmp.style.borderStyle = 'solid';
tmp.style.borderBottomWidth = '0';
tmp.style.borderTopWidth = _str;
}
context.appendChild(tmp);
var px = tmp.offsetHeight;
_context.removeChild(tmp);
return px + 'px';
}
function show_banner() {
var original_top_margin = getTopMargin();
var message = 'You are using an out-of-date version of <%= browser_name %> (<%= version.string %>). It is encouraged that you update your browser. <a href="<%= read_param(:link) || default_info_link %>?for=<%= browser %>&version=<%= version.string %>" style="color:#8B0000">Click here</a> for more details.';
var positioning = supportsFixed() ? 'fixed' : 'absolute';
var alert_box = document.createElement('div');
alert_box.id = 'bad-browser-warning';
alert_box.innerHTML = '<div style="background-color:#f4a83d;border-bottom:1px solid #d6800c;color:#735005;font-family:Verdana,Helvetica,Geneva,Arial,sans-serif;font-size:10px;font-weight:bold;height:25px;left:0;overflow:hidden;padding-top:5px;position:' + positioning + ';text-align:center;top:0;width:100%">'+ message +'<a id="bad-browser-warning-remove" style="position:absolute;right:0;margin-right:10px;border:2px solid #735005;background-color:#FAD163;padding:0 3px;text-decoration:none;color:#735005;height:16px;line-height:14px;cursor:pointer">X</a></div>'
document.body.appendChild(alert_box);
document.body.style.marginTop = (parseFloat(convertToPixels(original_top_margin)) + 25) + 'px';
document.getElementById('bad-browser-warning-remove').onclick = function() {
var alert_box = document.getElementById('bad-browser-warning');
document.body.removeChild(alert_box);
document.body.style.margin = original_top_margin;
}
}
if(window.attachEvent) {
window.attachEvent('onload', show_banner);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
show_banner();
};
window.onload = newonload;
} else {
window.onload = show_banner;
}
}
}());
|
JavaScript
| 0.000039 |
@@ -2402,17 +2402,17 @@
t-size:1
-0
+2
px;font-
|
f34fbb7fe77681c09a36ca5df6095a1845a16a73
|
add weekly route
|
routes/lectures.js
|
routes/lectures.js
|
"use strict";
// old /upcomingLectures is now /lectures/upcoming !!!
// old /lecturesForGroups is now /lectures/groups !!!
// import the express router
var router = require("express").Router();
// create model
var Lecture = require("../models/model_lecture");
// on routes that end in /lectures
router.route("/")
// get all lectures (GET /$apiBaseUrl/lectures)
.get(function(req, res) {
Lecture.find({}).sort({startTime: 1}).exec(function(err, lectures) {
if (err) { res.status(500).send(err); }
res.status(200).json(lectures);
res.end();
});
});
// on routes that end in /lectures/upcoming
router.route("/upcoming")
// get upcoming lectures (GET /$apiBaseUrl/lectures/upcoming)
.get(function(req, res) {
// today at 0:00
var today = new Date();
today.setHours(0,0,0,0);
// show all lectures for current day and later
Lecture.find({"endTime": {"$gte": today}}).sort({startTime: 1}).exec(function(err, lectures) {
if (err) { res.status(500).send(err); }
res.status(200).json(lectures);
res.end();
});
});
// on routes that end in /lectures/groups
router.route("/groups")
// get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
.post(function(req, res) {
// today at 0:00
var today = new Date();
today.setHours(0,0,0,0);
var reqGroups = JSON.parse(req.body.groups || "[]");
var query = { groups: { $in: reqGroups }, "endTime": {"$gte": today}};
// if no reqGroups provided, return all lectures
if (reqGroups.length === 0) {
delete query.groups;
}
// check if we got a proper array
if (reqGroups) {
Lecture.find(query).sort({startTime: 1}).exec(function(err, lectures) {
if (err) { res.status(500).send(err + " - data was: " + reqGroups); }
res.status(200).json(lectures);
res.end();
});
} else {
res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
return;
}
});
// on routes that end in /lectures/:lecture_id
router.route("/:lecture_id")
// get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
.get(function(req, res) {
Lecture.findById(req.params.lecture_id, function(err, lecture) {
if (err) { res.status(500).send(err); }
res.status(200).json(lecture);
res.end();
});
});
module.exports = router;
|
JavaScript
| 0.00002 |
@@ -190,16 +190,49 @@
ter();%0A%0A
+var moment = require(%22moment%22);%0A%0A
// creat
@@ -1765,16 +1765,1207 @@
%7D%0A%0A
+ // check if we got a proper array%0A if (reqGroups) %7B%0A Lecture.find(query).sort(%7BstartTime: 1%7D).exec(function(err, lectures) %7B%0A if (err) %7B res.status(500).send(err + %22 - data was: %22 + reqGroups); %7D%0A res.status(200).json(lectures);%0A res.end();%0A %7D);%0A %7D else %7B%0A res.status(400).json(%7B error: %22ohh that query looks wrong to me: %22 + reqGroups %7D);%0A return;%0A %7D%0A %7D);%0A %0A// on routes that end in /lectures/weekly%0Arouter.route(%22/weekly%22)%0A%0A // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)%0A .post(function(req, res) %7B%0A %0A var mon = moment().day(1);%0A mon.hour(0);%0A mon.minute(0);%0A mon.seconds(0);%0A var sun = moment().day(7);%0A sun.hour(23);%0A sun.minute(59);%0A sun.seconds(59);%0A %0A var reqGroups = JSON.parse(req.body.groups %7C%7C %22%5B%5D%22);%0A var query = %7B groups: %7B $in: reqGroups %7D, %22startTime%22: %7B%22$gte%22: mon%7D, %22endTime%22: %7B%22$lte%22: sun%7D%7D;%0A%0A // if no reqGroups provided, return all lectures%0A if (reqGroups.length === 0) %7B%0A delete query.groups;%0A %7D%0A%0A
|
a9492f594369885a7064d59c92a16f074d5bd252
|
Simplify loop even more
|
test/test.export_csv.js
|
test/test.export_csv.js
|
var assert = require('assert');
var listToCSVString = require('./../responses.js').listToCSVString;
var filterToMostRecent = require('./../responses.js').filterToMostRecent;
var filterAllResults = require('./../responses.js').filterAllResults;
var filterToOneRowPerUse = require('./../responses.js').filterToOneRowPerUse;
suite('In csvExport,', function(){
var row = ['a', 2, '3'];
var headers = ['first', 'second', 'third'];
var headerCount = {
'first': 1,
'second': 1,
'third': 1
};
var complexRow = ['a', [1,2,3], 4];
var complexHeaderCount = {
'first': 1,
'second': 3,
'third': 1
};
var fakeResults = [
// These two have the same parcel ID, but the first is more recent
{
"geo_info": {},
"parcel_id": "1234",
"created":"2011-05-24T23:16:57.266Z",
"responses": {
"use-count":"1",
"use":"restaurant-or-bar",
"restaurant-use":"restaurant"
},
'older': true,
},
{
"geo_info": {},
"parcel_id": "1234",
"created":"2012-05-24T23:16:57.266Z",
"responses": {
"use-count":"1",
"use":"service",
"service-use":"bank+drivethrough"
},
'older': false,
},
// In some cases, this one should be split into two rows because there are multiple uses.
{
"geo_info": {},
"parcel_id": "1235",
"created":"2012-06-24T23:16:57.266Z",
"responses": {
"use-count":"2", // There are 2 uses!
"use":"service",
"service-use":"nail salon",
"use-2":"service",
"service-use-2":"server farm",
"is it vacant?": "yes!"
}
}
];
test('commasep should turn a simple list into a csv string', function(){
var csv = listToCSVString(row, headers, headerCount);
var expected = 'a,2,3';
assert.equal(csv,expected);
});
test('arrays in fields should be serialized with semicolons', function() {
var csv = listToCSVString(complexRow, headers, complexHeaderCount);
var expected = 'a,1;2;3,4';
assert.equal(csv,expected);
});
test('the filterToMostRecent function should only return the most recent of two parcel results', function() {
var filteredResults = filterToMostRecent(fakeResults);
// Check if a parcel ID appears more than once
var parcelIDs = {};
for (var i=0; i < filteredResults.length; i++){
var result = filteredResults[i];
if (parcelIDs.hasOwnProperty(result['parcel_id'])) {
assert(false);
};
parcelIDs[result['parcel_id']] = true;
}
// Make sure it's the newer of the two
if (filteredResults[0]['older']) {
assert(false);
};
});
test('the filterToOneRowPerUse should split results with use_counts > 1 into n rows', function() {
var filteredResults = filterToOneRowPerUse(fakeResults);
// console.log(filteredResults);
if(filteredResults[3] == undefined){
assert(false);
};
});
});
|
JavaScript
| 0 |
@@ -2868,19 +2868,16 @@
ts);%0A
- //
console
|
ec538ac5e63f1a9dfb749e0eff2e33d55a575b31
|
Add a few more beer synonyms
|
lib/rule/bubble.js
|
lib/rule/bubble.js
|
'use strict';
module.exports = defineRules;
var bubbleJobTitles = [
/gurus?/,
/hero(:?es)/,
/ninjas?/,
/rock\s*stars?/,
/super\s*stars?/
];
var temptations = [
/beers?/,
/brewskis?/,
'coffee',
'foosball',
/keg(?:erator)?s?/,
/nerf\s*guns?/,
/ping\s*pong?/,
/pints?/,
/pizzas?/,
/play\s*stations?/,
/pool\s*table|pool/,
/rock\s*walls?/,
'table football',
/table\s*tennis/,
/wiis?/,
/xbox(?:es|s)?/,
/massages?/
];
function defineRules (linter) {
// Job title fails
linter.addRule({
name: 'Job "Titles"',
desc: 'Referring to tech people as Ninjas or similar devalues the work that they do and ' +
'shows a lack of respect and professionalism. It\'s also rather cliched and can be ' +
'an immediate turn-off to many people.',
test: function (spec, result) {
var bubbleJobMentions = spec.containsAnyOf(bubbleJobTitles);
if (bubbleJobMentions.length > 0) {
result.addWarning(
'Tech people are not ninjas, rock stars, gurus or superstars',
bubbleJobMentions
);
result.addCultureFailPoints(bubbleJobMentions.length / 2);
result.addRealismFailPoints(1);
}
}
});
// Temptations
linter.addRule({
name: 'Hollow Benefits',
desc: 'Benefits such as "beer fridge" and "pool table" are not bad in themselves, but ' +
'their appearance in a job spec often disguises the fact that there are few real ' +
'benefits to working for a company. Be wary of these.',
test: function (spec, result) {
var temptationMentions = spec.containsAnyOf(temptations);
if (temptationMentions.length > 0) {
result.addWarning(
'Attempt to attract candidates with hollow benefits: ' +
temptationMentions.join(', '),
temptationMentions
);
result.addCultureFailPoints(1);
result.addRecruiterFailPoints(temptationMentions.length / 2);
}
}
});
}
|
JavaScript
| 0.000001 |
@@ -172,24 +172,37 @@
tations = %5B%0A
+ /ales?/,%0A
/beers?/
@@ -270,24 +270,39 @@
rator)?s?/,%0A
+ /lagers?/,%0A
/nerf%5Cs*
|
23d2f1b2bf3a3fa88a39c3f0fd358976feec9498
|
Implement report feature
|
src/server/models/lophoc-model.js
|
src/server/models/lophoc-model.js
|
import { sequelize, Sequelize } from './index';
import Khoi from './khoi-model';
import NamHoc from './namhoc-model';
const LopHoc = sequelize.define('M_LOP_HOC', {
maLop_pkey: {
type: Sequelize.INTEGER,
primaryKey: true,
notNull: true,
autoIncrement: true,
field: 'MA_LOP_PKEY'
},
maLopHoc: {
type: Sequelize.STRING,
notNull: true,
unique: true,
field: 'MA_LOP_HOC'
},
tenLop: {
type: Sequelize.STRING,
notNull: true,
field: 'TEN_LOP'
},
siSo: {
type: Sequelize.INTEGER,
defaultValue: 0,
field: 'SISO'
},
siSoMax: {
type: Sequelize.INTEGER,
defaultValue: 0,
field: 'SISO_MAX'
},
maKhoi: {
type: Sequelize.INTEGER,
field: 'MA_KHOI'
},
maNamHoc: {
type: Sequelize.INTEGER,
field: 'MA_NAM_HOC'
}
});
Khoi.hasMany(LopHoc, { foreignKey: 'maKhoi', sourceKey: 'maKhoi_pkey' });
LopHoc.belongsTo(Khoi, { foreignKey: 'maKhoi', targetKey: 'maKhoi_pkey' });
NamHoc.hasMany(LopHoc, { foreignKey: 'maNamHoc', sourceKey: 'namHoc_pkey' });
LopHoc.belongsTo(Khoi, { foreignKey: 'maNamHoc', sourceKey: 'namHoc_pkey' });
export default LopHoc;
|
JavaScript
| 0 |
@@ -1164,36 +1164,38 @@
opHoc.belongsTo(
-Khoi
+NamHoc
, %7B foreignKey:
@@ -1198,38 +1198,38 @@
ey: 'maNamHoc',
-source
+target
Key: 'namHoc_pke
|
7695ccfbbabc1c14a6c317106ae19c71c8c8414e
|
disable message posting unless user is logged in
|
routes/messages.js
|
routes/messages.js
|
var express = require('express');
var router = express.Router();
var Message = require('../models/message');
router.get('/', function (req, res, next) { // route '/' is /messages in this context
Message.find()
.exec(function (err, messages) {
if (err) {
return res.status(500).json({ // exit if error
title: 'An error occured',
error: err
});
}
res.status(200).json({ // if no err, return messages
message: 'Success',
obj: messages
});
});
});
router.post('/', function (req, res, next) { // this remains as '/' because we only go here if it begins with /messages
var message = new Message({
content: req.body.content
});
message.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Message saved',
obj: result
})
});
});
router.patch('/:id', function (req, res, next) {
Message.findById(req.params.id, function (err, message) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
if (!message) {
return res.status(500).json({
title: 'Message not found!',
error: {message: 'Message not found!'}
});
}
message.content = req.body.content;
message.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'Message not found!',
error: err
});
}
res.status(200).json({ // if no err, return messages
message: 'Updated message',
obj: result
});
});
});
});
router.delete('/:id', function(req, res, next) {
Message.findById(req.params.id, function (err, message) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
if (!message) {
return res.status(500).json({
title: 'Message not found!',
error: {message: 'Message not found!'}
});
}
message.remove(function (err, result) {
if (err) {
return res.status(500).json({
title: 'Message not found!',
error: err
});
}
res.status(200).json({ // if no err, return messages
message: 'Deleted message',
obj: result
});
});
});
});
module.exports = router;
|
JavaScript
| 0 |
@@ -101,16 +101,51 @@
ssage');
+%0Avar jwt = require('jsonwebtoken');
%0A%0Arouter
@@ -638,32 +638,499 @@
%7D);%0A%7D);%0A%0A
+router.use('/', function (req, res, next) %7B // will be used on every request except .get('/')%0A jwt.verify(req.query.token, 'secret', function(err, decoded)%7B // gives access to all query params, checks for token in params%0A if (err) %7B%0A return res.status(401).json(%7B // not authorized%0A title: 'Authentication failed',%0A error: err%0A %7D);%0A %7D%0A next(); // let request continue if no err%0A %7D);%0A%7D);%0A%0A
router.post('/',
@@ -2564,16 +2564,17 @@
function
+
(req, re
|
c3d551b92c3a286ed0b494643ff67c4e006ff302
|
Remove commented code
|
routes/sendMail.js
|
routes/sendMail.js
|
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
/* GET home page. */
router.post('/', function(req, res, next) {
var data = req.body;
//gather mail options from body
var mailOptions = {
from: data.from, // sender address
to: data.to, // list of receivers
subject: data.subject, // Subject line
/* SCRAP
text: data.text, // plaintext body
html: data.html // html body
*/
template: 'email_body',
context: {
variable1 : 'value1',
variable2: 'value2'
}
};
console.log(mailOptions);
//create transporter object w/ mailgun credentials
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: '[email protected]',
pass: 'makersquare'
}
});
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/email/',
defaultLayout: 'template',
partialsDir: 'views/partials'
},
viewPath: 'views/email/',
extName: '.hbs'
};
transporter.use('compile', hbs(options));
transporter.sendMail(mailOptions, function(error) {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Message sent");
res.send("sent");
}
});
});
module.exports = router;
/*
app.post('/sendMail', function(req, res) {
var data = req.body;
//gather mail options from body
var mailOptions = {
from: data.from, // sender address
to: data.to, // list of receivers
subject: data.subject, // Subject line
// text: data.text, // plaintext body
// html: data.html // html body
template: 'email_body',
context: {
variable1 : 'value1',
variable2: 'value2'
}
};
console.log(mailOptions)
//create transporter object w/ mailgun credentials
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: '[email protected]',
pass: 'makersquare'
}
});
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/email/',
defaultLayout: 'template',
partialsDir: 'views/partials'
},
viewPath: 'views/email/',
extName: '.hbs'
};
transporter.use('compile', hbs(options));
transporter.sendMail(mailOptions, function(error) {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Message sent");
res.send("sent");
}
});
});
*/
|
JavaScript
| 0 |
@@ -1413,1200 +1413,4 @@
er;%0A
-/*%0Aapp.post('/sendMail', function(req, res) %7B%0A var data = req.body;%0A%0A //gather mail options from body%0A var mailOptions = %7B%0A from: data.from, // sender address%0A to: data.to, // list of receivers%0A subject: data.subject, // Subject line%0A // text: data.text, // plaintext body%0A // html: data.html // html body%0A template: 'email_body',%0A context: %7B%0A variable1 : 'value1',%0A variable2: 'value2'%0A %7D%0A %7D;%0A console.log(mailOptions)%0A%0A //create transporter object w/ mailgun credentials%0A var transporter = nodemailer.createTransport(%7B%0A service: 'Mailgun',%0A auth: %7B%0A user: '[email protected]',%0A pass: 'makersquare'%0A %7D%0A %7D);%0A%0A var options = %7B%0A viewEngine: %7B%0A extname: '.hbs',%0A layoutsDir: 'views/email/',%0A defaultLayout: 'template',%0A partialsDir: 'views/partials'%0A %7D,%0A viewPath: 'views/email/',%0A extName: '.hbs'%0A %7D;%0A%0A transporter.use('compile', hbs(options));%0A%0A transporter.sendMail(mailOptions, function(error) %7B%0A if (error) %7B%0A console.log(error);%0A res.send(%22error%22);%0A %7D else %7B%0A console.log(%22Message sent%22);%0A res.send(%22sent%22);%0A %7D%0A %7D);%0A%7D);%0A*/
|
ac723c3dac42b29c69f38a4f9c4d4efb6dbe8762
|
Fix read of .env variables (#2242)
|
packages/react-scripts/config/env.js
|
packages/react-scripts/config/env.js
|
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// @remove-on-eject-end
'use strict';
const fs = require('fs');
const paths = require('./paths');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
`${paths.dotenv}.local`,
paths.dotenv,
];
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv').config({
path: dotenvFile,
});
}
});
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce(
(env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
},
{}
),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
|
JavaScript
| 0.000001 |
@@ -428,16 +428,143 @@
ths');%0A%0A
+// Make sure that including paths.js after env.js will read .env variables.%0Adelete require.cache%5Brequire.resolve('./paths')%5D;%0A%0A
const NO
|
8dccda92338c7877236bdd88a2398b6feba868e5
|
Add hotspot to book cover image
|
packages/test-studio/schemas/book.js
|
packages/test-studio/schemas/book.js
|
import BookIcon from 'react-icons/lib/fa/book'
function formatSubtitle(book) {
return [
'By',
book.authorName || '<unknown>',
book.authorBFF && `[BFF ${book.authorBFF} 🤞]`,
book.publicationYear && `(${book.publicationYear})`
]
.filter(Boolean)
.join(' ')
}
export default {
name: 'book',
type: 'document',
title: 'Book',
description: 'This is just a simple type for generating some test data',
icon: BookIcon,
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
validation: Rule => Rule.min(5).max(100)
},
{
name: 'translations',
title: 'Translations',
type: 'object',
fields: [
{name: 'no', type: 'string', title: 'Norwegian (Bokmål)'},
{name: 'nn', type: 'string', title: 'Norwegian (Nynorsk)'},
{name: 'se', type: 'string', title: 'Swedish'}
]
},
{
name: 'author',
title: 'Author',
type: 'reference',
to: {type: 'author', title: 'Author'}
},
{
name: 'coverImage',
title: 'Cover Image',
type: 'image'
},
{
name: 'publicationYear',
title: 'Year of publication',
type: 'number'
},
{
name: 'isbn',
title: 'ISBN number',
description: 'ISBN-number of the book. Not shown in studio.',
type: 'number',
hidden: true
}
],
orderings: [
{
title: 'Title',
name: 'title',
by: [{field: 'title', direction: 'asc'}, {field: 'publicationYear', direction: 'asc'}]
},
{
title: 'Author name',
name: 'authorName',
by: [{field: 'author.name', direction: 'asc'}]
},
{
title: 'Authors best friend',
name: 'authorBFF',
by: [{field: 'author.bestFriend.name', direction: 'asc'}]
},
{
title: 'Size of coverImage',
name: 'coverImageSize',
by: [{field: 'coverImage.asset.size', direction: 'asc'}]
},
{
title: 'Swedish title',
name: 'swedishTitle',
by: [{field: 'translations.se', direction: 'asc'}, {field: 'title', direction: 'asc'}]
}
],
preview: {
select: {
title: 'title',
translations: 'translations',
createdAt: '_createdAt',
date: '_updatedAt',
authorName: 'author.name',
authorBFF: 'author.bestFriend.name',
publicationYear: 'publicationYear',
media: 'coverImage'
},
prepare(book, options = {}) {
return Object.assign({}, book, {
title:
((options.ordering || {}).name === 'swedishTitle' && (book.translations || {}).se) ||
book.title,
subtitle: formatSubtitle(book)
})
}
}
}
|
JavaScript
| 0 |
@@ -1088,24 +1088,56 @@
ype: 'image'
+,%0A options: %7Bhotspot: true%7D
%0A %7D,%0A
|
bed4c0696c8bd2c3fea271434bf40c572554f250
|
Remove spinner and add some different output
|
packages/provider/index.js
|
packages/provider/index.js
|
const debug = require("debug")("provider");
const Web3 = require("web3");
const { Web3Shim, InterfaceAdapter } = require("@truffle/interface-adapter");
const wrapper = require("./wrapper");
const ora = require("ora");
module.exports = {
wrap: function(provider, options) {
return wrapper.wrap(provider, options);
},
create: function(options) {
const provider = this.getProvider(options);
return this.wrap(provider, options);
},
getProvider: function(options) {
let provider;
if (options.provider && typeof options.provider === "function") {
provider = options.provider();
} else if (options.provider) {
provider = options.provider;
} else if (options.websockets) {
provider = new Web3.providers.WebsocketProvider(
"ws://" + options.host + ":" + options.port
);
} else {
provider = new Web3.providers.HttpProvider(
`http://${options.host}:${options.port}`,
{ keepAlive: false }
);
}
return provider;
},
testConnection: function(options) {
const provider = this.getProvider(options);
const web3 = new Web3Shim({ provider });
return new Promise((resolve, reject) => {
const spinner = ora("Testing the provider.").start();
const noResponseFromNetworkCall = setTimeout(() => {
spinner.fail();
const errorMessage =
"Failed to connect to the network using the " +
"supplied provider.\n Check to see that your provider is valid.";
throw new Error(errorMessage);
}, 20000);
web3.eth
.getBlockNumber()
.then(() => {
spinner.succeed();
// Cancel the setTimeout check above
clearTimeout(noResponseFromNetworkCall);
resolve(true);
})
.catch(error => {
spinner.fail();
// Cancel the setTimeout check above
clearTimeout(noResponseFromNetworkCall);
reject(error);
});
});
}
};
|
JavaScript
| 0.000001 |
@@ -186,36 +186,8 @@
r%22);
-%0Aconst ora = require(%22ora%22);
%0A%0Amo
@@ -1174,23 +1174,15 @@
cons
-t spinner = ora
+ole.log
(%22Te
@@ -1204,17 +1204,57 @@
der.
-%22).start(
+..%22);%0A console.log(%22=======================%22
);%0A
@@ -1315,37 +1315,140 @@
%3E %7B%0A
-spinner.fail(
+console.log(%0A %22%3E There was a timeout while attempting to connect %22 +%0A %22to the network.%22%0A
);%0A c
@@ -1740,24 +1740,48 @@
-spinner.succeed(
+console.log(%22%3E The test was successful!%22
);%0A
@@ -1953,21 +1953,131 @@
-spinner.fail(
+console.log(%0A %22%3E Something went wrong while attempting to connect %22 +%0A %22to the network.%22%0A
);%0A
|
5d61d7c91d90aa4763ce91e85d4d99c4807fe231
|
clean up
|
lib/source-maps.js
|
lib/source-maps.js
|
'use strict';
/**
* Module dependencies.
*/
var SourceMap = require('source-map').SourceMapGenerator;
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var sourceMapResolve = require('source-map-resolve');
var urix = require('urix');
var fs = require('fs');
var path = require('path');
/**
* Expose `mixin()`.
*/
module.exports = mixin;
/**
* Mixin source map support into `renderer`.
*
* @param {Compiler} renderer
* @api public
*/
function mixin(renderer) {
renderer._comment = renderer.comment;
renderer.map = new SourceMap();
renderer.position = { line: 1, column: 1 };
renderer.files = {};
for (var k in exports) renderer[k] = exports[k];
}
/**
* Update position.
*
* @param {String} str
* @api private
*/
exports.updatePosition = function(str) {
var lines = str.match(/\n/g);
if (lines) this.position.line += lines.length;
var i = str.lastIndexOf('\n');
this.position.column = ~i ? str.length - i : this.position.column + str.length;
};
/**
* Emit `str`.
*
* @param {String} str
* @param {Object} [pos]
* @return {String}
* @api private
*/
exports.emit = function(str, pos) {
if (pos) {
var sourceFile = urix(pos.source || 'string');
this.map.addMapping({
source: sourceFile,
generated: {
line: this.position.line,
column: Math.max(this.position.column - 1, 0)
},
original: {
line: pos.start.line,
column: pos.start.column - 1
}
});
this.addFile(sourceFile, pos);
}
this.updatePosition(str);
return str;
};
/**
* Adds a file to the source map output if it has not already been added
* @param {String} file
* @param {Object} pos
*/
exports.addFile = function(file, pos) {
if (typeof pos.content !== 'string') return;
if (Object.prototype.hasOwnProperty.call(this.files, file)) return;
this.files[file] = pos.content;
};
/**
* Applies any original source maps to the output and embeds the source file
* contents in the source map.
*/
exports.applySourceMaps = function() {
Object.keys(this.files).forEach(function(file) {
var content = this.files[file];
this.map.setSourceContent(file, content);
if (this.options.inputSourcemaps !== false) {
var originalMap = sourceMapResolve.resolveSync(content, file, fs.readFileSync);
if (originalMap) {
var map = new SourceMapConsumer(originalMap.map);
var relativeTo = originalMap.sourcesRelativeTo;
this.map.applySourceMap(map, file, urix(path.dirname(relativeTo)));
}
}
}, this);
};
/**
* Process comments, drops sourceMap comments.
* @param {Object} node
*/
exports.comment = function(node) {
if (/^# sourceMappingURL=/.test(node.comment)) {
return this.emit('', node.position);
} else {
return this._comment(node);
}
};
|
JavaScript
| 0.000001 |
@@ -12,40 +12,87 @@
';%0A%0A
-/**%0A * Module dependencies.%0A */%0A
+var fs = require('fs');%0Avar path = require('path');%0Avar urix = require('urix');
%0Avar
@@ -268,88 +268,8 @@
e');
-%0Avar urix = require('urix');%0Avar fs = require('fs');%0Avar path = require('path');
%0A%0A/*
|
c3b85500895191a348909daf575731573e1eed9a
|
correct spacing for issue ticket url
|
lib/tools/Error.js
|
lib/tools/Error.js
|
/**
* Created by apizzimenti on 1/1/17.
*/
var cols = process.stdout.columns,
chalk = require("chalk"),
wrap = require("wordwrap")(4, cols);
function Error (message) {
this.message = message;
}
Error.prototype.throw = function () {
console.log(wrap(chalk.red("Error:\n" + this.message)));
console.log(wrap(chalk.bold("If you feel that this is an error in the application's programming and not with your" +
" internet connection, please submit an error at" +
chalk.bgWhite.black("github.com/apizzimenti/cli-weather/issues"))));
};
Error.prototype.message = function () {
return message;
};
module.exports = {
Error: Error
};
|
JavaScript
| 0.000002 |
@@ -476,16 +476,24 @@
an
-error
+issue ticket
at
+
%22 +%0A
|
0a731075e0072ef9e217a58d8ecd10d5805999fb
|
Add more tests
|
test.js
|
test.js
|
/*global describe, it */
'use strict';
var assert = require('assert');
var extname = require('./');
describe('extname()', function () {
it('should return a files extension and MIME type', function (cb) {
assert.strictEqual(extname('foobar.tar').ext, 'tar');
assert.strictEqual(extname('foobar.tar').mime, 'application/x-tar');
cb();
});
});
|
JavaScript
| 0 |
@@ -338,24 +338,308 @@
on/x-tar');%0A
+ assert.strictEqual(extname('foobar.py').ext, 'py');%0A assert.strictEqual(extname('foobar.py').mime, 'text/x-script.python');%0A assert.strictEqual(extname('foobar.pnm').ext, 'pnm');%0A assert.strictEqual(extname('foobar.pnm').mime, 'image/x-portable-anymap');%0A
cb()
|
00314c6219ec77d8644538d3f81e033f34ff921f
|
Remove invalid test case
|
test.js
|
test.js
|
const DotTag = styled.div`
color: #ebebeb;
font-size: ${props => props.theme.fontSize};
font-family: Helvetica;
${mixin}
`
const StringTagname = styled('div')`
color: #ff0000;
`
const Component = styled(Component)`
color: #ebebeb;
`
const SegmentedComponent = styled(Segmented.Component)`
padding: 3px;
`
const mixin = css`
height: 20px;
padding: 5px;
`
// const comment = css`
// height: 20px;
// padding: 5px;
// `
const arrowFun = (...args) => css`
height: 12px;
`
const test = "broken" /* Highlighting is broken after a styled-component is returned from an arrow function*/
class InsideMethod extends React.Component {
render () {
return styled(Component)`
line-height: 21px;
`
}
}
let variableAssignment
variableAssignment = css`
height: 1px;
`
/* expression */
styled`
height: 12px;
`
(styled.div`
height: 12px;
`)
export default styled(ExportComponent)`
max-width: 100%;
`
function insideFunction() {
return styled.div`
height: 15px;
`
}
const ObjectLiteral = {
styles: styled`
height: 12px;
color: #000000;
font: ${props => 'lol'};
${props => 'padding: 5px'}
${props => 'border'}: 1px solid #000000;
`
}
const rotate360 = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(1turn);
}
`
// .extend
const Comp = styled.div`color: red;`
const NewComp = Comp.extend`
color: green;
`
// .withComponent()
const NewCompWithString = CompWithComponent.withComponent('span')`
color: green;
`
const NewCompWithStringOneLine = CompWithComponent.withComponent('span')`color: green;`
const NewCompWithComponent = CompWithComponent.withComponent(OtherComp)`
color: green;
`
// Typescript
const Root = styled<RootProps>('div')`
height: ${(props) => props.label ? 72 : 48}px;
`
// SC.attrs({})
const Link = styled.a.attrs({
target: '_blank'
})`
color: red;
`
// Functional Media Queries - https://www.styled-components.com/docs/advanced#media-templates
const sizes = {
desktop: 992,
tablet: 768,
phone: 376,
}
const media = Object.keys(sizes).reduce((acc, label) => {
acc[label] = (...args) => css`
@media (max-width: ${sizes[label] / 16}em) {
${css(...args)};
}
`
})
const Input = styled.input.attrs({
// we can define static props
type: 'password',
// or we can define dynamic ones
margin: props => props.size || '1em',
padding: props => props.size || '1em'
})`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed props */
margin: ${props => props.margin};
padding: ${props => props.padding};
`;
const mediaQuery = styled.div`
background: palevioletred;
${media.desktop`
background: red;
`};
${media.breakAt('300px')`
background: palevioletred;
`}
${media.desktop(400)`
background: coral;
`};
`
const Input = styled.input.attrs({
// we can define static props
type: 'password',
// or we can define dynamic ones
margin: props => props.size || '1em',
padding: props => props.size || '1em'
})`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed props */
margin: ${props => props.margin};
padding: ${props => props.padding};
`;
const Input = styled.input.attrs({
// we can define static props
type: 'password',
// or we can define dynamic ones
margin: props => props.size || '1em',
padding: props => props.size || '1em'
})`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
${media.desktop`
background: red;
`};
${media.breakAt('300px')`
background: palevioletred;
`}
${media.desktop(400)`
background: coral;
`};
/* here we use the dynamically computed props */
margin: ${props => props.margin};
padding: ${props => props.padding};
`;
|
JavaScript
| 0.000036 |
@@ -863,37 +863,8 @@
*/%0A
-styled%60%0A height: 12px;%0A%60%0A%0A
(st
|
8a98206fbbe6aff62717dd656b0af37b452fd5d3
|
Add tests to s3 signed url
|
test.js
|
test.js
|
import test from 'ava'
import request from 'supertest'
import { exec } from 'mz/child_process'
import createServer from './dist/server.builded'
test('build application', async (t) => {
t.plan(1)
const build = exec('yarn run prestart')
const b = await build
t.truthy(b.join().indexOf('Done'), 'build was done sucess')
})
// describe('express serving', (t) => {
// it('responds to / with the index.html', (t) => {
// return request(app)
// .get('/')
// .expect('Content-Type', /html/)
// .expect(200)
// .then(res => expect(res.text).to.contain('<div id="root"></div>'))
// })
// it('responds to favicon.icon request', (t) => {
// return request(app)
// .get('/favicon.ico')
// .expect('Content-Type', 'image/x-icon')
// .expect(200)
// })
test('render index.html as static file', async (t) => {
t.plan(2)
const res = await request(createServer({
nodeEnv: test,
port: 6006,
timeout: 28000,
schemaName: 'public',
databaseUrl: '',
sentryDns: '',
}))
.get('/index.html')
t.is(res.status, 200)
t.truthy(res.text.indexOf('<div id="root"></div>'), 'html container with root id was found')
})
// test('responds to any route with the index.html', async (t) => {
// const r = request(app)
// .get('/index.html')
// .expect('Content-Type', /html/)
// .expect(200)
// .then(res => expect(res.text).to.contain('<div id="root"></div>'))
// t.same(await http.get('http://localhost'), {expected: 'output'})
// })
// })
// })
|
JavaScript
| 0 |
@@ -138,16 +138,190 @@
ilded'%0A%0A
+const serverConfig = %7B%0A nodeEnv: test,%0A port: 6006,%0A timeout: 28000,%0A schemaName: 'public',%0A databaseUrl: '',%0A sentryDns: '',%0A s3BucketName: 'vivo-em-nos-staging',%0A%7D%0A%0A
test('bu
@@ -1089,134 +1089,20 @@
ver(
-%7B%0A nodeEnv: test,%0A port: 6006,%0A timeout: 28000,%0A schemaName: 'public',%0A databaseUrl: '',%0A sentryDns: '',%0A %7D
+serverConfig
))%0A
@@ -1248,16 +1248,332 @@
d')%0A%7D)%0A%0A
+test('get s3 signed url', async (t) =%3E %7B%0A t.plan(2)%0A%0A const fileName = 'textura.png'%0A const fileType = 'image/png'%0A%0A const res = await request(createServer(serverConfig))%0A .get(%60/sign-s3?file-name=$%7BfileName%7D&file-type=$%7BfileType%7D%60)%0A%0A t.is(res.status, 200)%0A t.not(JSON.parse(res.text).signedRequest, '')%0A%7D)%0A
// test(
|
754da9d966173389584a978b1fb779d27feeae70
|
switch to underscore.js random function
|
test.js
|
test.js
|
#! /usr/bin/node
var parser = require("./parse.js");
var cexps = require("./cexps.js");
var closures = require("./closure_conversion.js");
var desugar = require("./desugar.js");
var environments = require("./environments.js");
var errors = require("./errors.js");
var tokens = require("./tokenize.js");
var tools = require("./tools.js");
var typecheck = require("./typecheck.js");
var representation = require("./representation.js");
var _ = require("underscore");
var qc = require("quickcheck");
var assert = require("assert");
/* my own generators */
function arbChars(n, max, min) {
return function () {
return _.invoke(_.times(randomInt(1, n),
_.partial(arbChar, max, min)),
"call");
};
}
function arbChar(max, min) {
return function() {
return String.fromCharCode(randomInt(max, min));
};
}
function arbCharRanges(ranges, max) {
return function() {
return _.flatten(
_.map(ranges,
function(bound) {
return arbChars(max, bound[0], bound[1])();
})).join("");
};
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var arbCapital = arbChar(65, 90);
function arbArray(gen) {
return qc.arbArray(gen);
}
function arbStrings() {
return qc.arbArray(qc.arbString);
}
function arbPair(gen) {
return function() {
return [gen(), gen()];
};
}
function arbArrayofPairs() {
return arbArray(function() {
return arbArray(arbPair(qc.arbString));
});
}
function arbPairs() {
return arbArray(arbPair(qc.arbString));
}
/* Tests for misc tools */
function emptyProp(xs) {
return (tools.empty(xs) === tools.empty(xs) &&
((tools.empty(xs) === true) ||
(tools.empty(xs) === false)));
}
function dictProp(pairs) {
var dict = tools.dict(pairs);
var result = _.map(pairs,
function(pair) {
if ((_.size(pair) < 2) ||
(_.size(pair[0]) < 1) ||
(_.size(pair[1]) < 1)) {
return true;
}
return dict[pair[0]] === pair[1];
});
if (_.every(result, _.identity)) {
return true;
}
return false;
}
function opMatchProp(strings) {
var match = tools.opMatch(strings);
var result = _.every(_.map(strings,
function (str) {
if (str.replace(/ /g,'').length < 1) {
return true;
}
var res = match(str);
if (res !== false) {
console.log(str);
return true;
}
return false;
}),
_.identity);
return result;
}
function extendProp(pair) {
if (pair.length < 2) {
// empty lists or lists with one item are undefined
// so just return true because extend can't handle them
return true;
}
var x = _.first(pair);
var y = _.first(_.rest(pair));
var extended = tools.extend(x,y);
return x.length + y.length === extended.length;
}
/* Tokenizer tests */
function toolsTests() {
assert.equal(true, tools.empty([]));
assert.equal(true, qc.forAll(dictProp, arbArrayofPairs));
assert.equal(true, qc.forAll(extendProp, arbPairs));
//assert.equal(true, qc.forAll(opMatchProp, arbStrings));
}
//toolsTests();
|
JavaScript
| 0.000004 |
@@ -636,25 +636,24 @@
_.times(
+_.
random
-Int
(1, n),%0A
@@ -821,25 +821,24 @@
harCode(
+_.
random
-Int
(max, mi
@@ -1069,104 +1069,8 @@
%0A%0A%0A%0A
-function randomInt(min, max) %7B%0A return Math.floor(Math.random() * (max - min + 1)) + min;%0A%7D%0A%0A
var
|
c1e89a21f11616c90beb0c4d79d1d0725a73e548
|
Remove try/catch test, replace with emit check.
|
test.js
|
test.js
|
/* jshint node: true */
/* jshint expr:true */
/* global describe, it, afterEach, beforeEach */
'use strict';
var expect = require('chai').expect,
rimraf = require('rimraf'),
gutil = require('gulp-util'),
symlink = require('./'),
path = require('path'),
fs = require('fs');
symlink._setDebug(true);
/**
* Expect that we created a symlink which contains the desired link text;
* i.e. whether it is relative or absolute
* @param {String} fpath Path to the symlink
* @param {Function} pathMethod A method passed in to compare the cwd to the linked path
* @param {Function} callback Call the callback when we're done
*/
var assertion = function(fpath, pathMethod, callback) {
fs.lstat(fpath, function(err, stats) {
expect(stats.isSymbolicLink()).to.be.true;
fs.readlink(fpath, function(err, link) {
expect(link).to.equal(pathMethod(process.cwd(), link));
callback && callback();
});
});
};
describe('gulp-symlink', function() {
function test(testDir, method, pathMethod) {
var testFile = 'index.js';
var testPath = path.join(testDir, testFile);
beforeEach(function() {
this.gutilFile = new gutil.File({
path: path.join(process.cwd(), testFile)
});
});
it('should throw if no directory was specified', function(cb) {
var stream = method();
try {
stream.write(this.gutilFile);
} catch (e) {
expect(e.toString()).to.contain.string('An output destination is required.');
cb();
}
});
it('should create symlinks', function(cb) {
var stream = method(testDir);
stream.on('data', function() {
assertion(testPath, pathMethod, cb);
});
stream.write(this.gutilFile);
});
it('should create symlinks renamed as a result of a function', function(cb) {
var newName = 'renamed-link.js';
var newTestPath = path.join(testDir, newName);
var stream = method(function() {
return newTestPath;
});
stream.on('data', function() {
assertion(newTestPath, pathMethod, cb);
});
stream.write(this.gutilFile);
});
it('should create renamed symlinks', function(cb) {
var newName2 = 'renamed-link-2.js';
var newTestPath2 = path.join(testDir, newName2);
var stream = method(testDir + path.sep + newName2);
stream.on('data', function() {
assertion(newTestPath2, pathMethod, cb);
});
stream.write(this.gutilFile);
});
it('should create symlinks in nested directories', function(cb) {
var subDir = 'subdir';
var subTestPath = path.join(testDir, subDir, testFile);
var stream = method(path.join(testDir, subDir));
stream.on('data', function() {
assertion(subTestPath, pathMethod, cb);
});
stream.write(this.gutilFile);
});
it('should symlink multiple input files in the same stream', function(cb) {
var stream = method(function(file) {
return path.join(testDir, file.relative);
});
var fileOne = new gutil.File({
path: path.join(process.cwd(), 'test.js')
});
var fileTwo = new gutil.File({
path: path.join(process.cwd(), 'README.md')
});
stream.on('data', function(sym) {
if (sym === fileOne) {
assertion(path.join(testDir, 'test.js'), pathMethod);
} else {
assertion(path.join(testDir, 'README.md'), pathMethod);
}
});
stream.on('end', cb);
stream.write(fileOne);
stream.write(fileTwo);
stream.end();
});
afterEach(function(cb) {
rimraf(testDir, cb);
});
}
describe('using relative paths & relative symlinks', function() {
test('test', symlink.relative, path.relative);
});
describe('using full paths & relative symlinks', function() {
test(__dirname + '/test', symlink.relative, path.relative);
});
describe('using relative paths & absolute symlinks', function() {
test('test', symlink.absolute, path.resolve);
});
describe('using full paths & absolute symlinks', function() {
test(__dirname + '/test', symlink.absolute, path.resolve);
});
});
|
JavaScript
| 0 |
@@ -1355,13 +1355,21 @@
uld
-throw
+emit an error
if
@@ -1398,34 +1398,32 @@
fied', function(
-cb
) %7B%0A
@@ -1441,24 +1441,25 @@
= method();%0A
+%0A
@@ -1462,85 +1462,111 @@
+s
tr
-y %7B%0A stream.write(this.gutilFile);%0A %7D catch (e) %7B
+eam.on('error', function(err) %7B%0A expect(err instanceof gutil.PluginError).to.be.true;
%0A
@@ -1586,16 +1586,18 @@
expect(e
+rr
.toStrin
@@ -1674,18 +1674,13 @@
- cb(
+%7D
);%0A
+%0A
@@ -1679,33 +1679,61 @@
);%0A%0A
-%7D
+stream.write(this.gutilFile);
%0A %7D);%0A
|
25c910da797093e8d7f262eb7d7ab13ac5f39d6b
|
Update environment check
|
test.js
|
test.js
|
import {readFileSync} from 'fs';
import test from 'tape-catch';
import isomorphicEnsure from './module';
if (!require.ensure) require.ensure = isomorphicEnsure({
loaders: {
raw: require('raw-loader'),
json: require('json-loader'),
async: function() { this.async(); },
resolve: function() { this.resolve(); },
cacheable: function() {
this.cacheable();
return '';
},
dependencies: function() {
this.dependencies();
return '';
},
},
dirname: __dirname,
});
test('Doesn’t break the native `require`.', (is) => {
require.ensure([
'./test/fixtures/itWorks',
'./test/fixtures/itReallyWorks.js',
'./test/fixtures/itWorks!Absolutely.js',
'tape-catch',
'tape-catch/index.js',
], (require) => {
is.equal(
require('./test/fixtures/itWorks'),
'It works!',
'for local files without an extension'
);
is.equal(
require('./test/fixtures/itReallyWorks.js'),
'It really works!',
'for local files with an extension'
);
is.equal(
require('./test/fixtures/itWorks!Absolutely.js'),
'It works! Absolutely!',
'for local files with an exclamation mark in the filename'
);
is.equal(
require('tape-catch'),
test,
'for modules'
);
is.equal(
require('tape-catch/index.js'),
test,
'for files in modules'
);
is.end();
});
});
test('Works with raw-loader.', (is) => {
require.ensure([
'raw!./test/fixtures/itWorks.txt',
'raw!babel/README.md',
], (require) => {
require.dirname = __dirname;
is.equal(
require('raw!./test/fixtures/itWorks.txt'),
'It works with raw text files!\n',
'for local files'
);
is.equal(
require('raw!babel/README.md'),
readFileSync('./node_modules/babel/README.md', {encoding: 'utf8'}),
'for module files'
);
is.end();
});
});
test('Works with json-loader.', (is) => {
require.ensure([
'json!./test/fixtures/itWorks.json',
'json!babel/package.json',
], (require) => {
is.deepEqual(
require('json!./test/fixtures/itWorks.json'),
JSON.parse(
readFileSync('./test/fixtures/itWorks.json', {encoding: 'utf8'})
),
'for local files'
);
is.deepEqual(
require('json!babel/package.json'),
JSON.parse(
readFileSync('./node_modules/babel/package.json', {encoding: 'utf8'})
),
'for module files'
);
is.end();
});
});
test('Checks if loaders are compatible.', (is) => {
require.ensure([
'async!./test/fixtures/itWorks.txt',
'resolve!./test/fixtures/itWorks.txt',
'cacheable!./test/fixtures/itWorks.txt',
'dependencies!./test/fixtures/itWorks.txt',
], (require) => {
is.throws(
() => require('async!./test/fixtures/itWorks.txt'),
Error,
'frowns upon async loaders'
);
is.throws(
() => require('resolve!./test/fixtures/itWorks.txt'),
Error,
'frowns upon loaders with `this.resolve`'
);
is.doesNotThrow(
() => require('cacheable!./test/fixtures/itWorks.txt'),
'has nothing against cacheable loaders'
);
is.doesNotThrow(
() => require('dependencies!./test/fixtures/itWorks.txt'),
'has nothing against loaders with dependencies'
);
is.end();
});
});
|
JavaScript
| 0.000001 |
@@ -105,17 +105,23 @@
';%0A%0Aif (
-!
+typeof
require.
@@ -126,16 +126,31 @@
e.ensure
+ !== 'function'
) requir
|
53548d92aebfd61ef4a6d88cb2517780e4a313d6
|
Use `typeof` to check the type.
|
test.js
|
test.js
|
'use strict';
const chai = require('chai');
const mocha = require('mocha');
const describe = mocha.describe;
const beforeEach = mocha.beforeEach;
const it = mocha.it;
const expect = chai.expect;
const circularIterator = require('./');
describe('circular iterator', function() {
let arr;
let iterator;
beforeEach(function() {
arr = ['foo', 'bar', 'buz'];
iterator = circularIterator(arr);
});
describe('public API', function() {
it('should be defined and a function', function() {
expect(circularIterator).to.be.a('function');
});
it('should return the following properties', function() {
const status = circularIterator(arr).next();
expect(status).to.have.property('value');
expect(status).to.have.property('done').that.is.a('boolean');
});
});
describe('usage', function() {
it('should return first item', function() {
expect(circularIterator(arr).next().value).to.equal('foo');
});
it('should return all items in order', function() {
arr.map(function(element) {
expect(iterator.next().value).to.equal(element);
});
});
it('should return first element when the end is reached', function() {
// first call for each element
arr.map(function(element) {
expect(iterator.next().value).to.equal(element);
});
// called again on the same iterator should return the same array elements.
arr.map(function(element) {
expect(iterator.next().value).to.equal(element);
});
});
it('should not return `done` when the end is reached', function() {
arr.map(function() {
iterator.next();
});
expect(iterator.next().done).to.be.false;
});
it('should work with no params', function() {
const voidIterator = circularIterator();
expect(voidIterator.next().value).to.be.undefined;
});
it('should work with non array params', function() {
expect(circularIterator('foo').next().value).to.be.undefined;
expect(circularIterator(true).next().value).to.be.undefined;
expect(circularIterator(false).next().value).to.be.undefined;
expect(circularIterator({foo: 'foo'}).next().value).to.be.undefined;
});
it('should not allow external modifications', function() {
expect(iterator.next().value).to.be.equal('foo');
arr[1] = 'biz';
expect(iterator.next().value).to.be.equal('bar');
});
});
});
|
JavaScript
| 0 |
@@ -506,32 +506,39 @@
%7B%0A expect(
+typeof
circularIterator
@@ -546,12 +546,13 @@
.to.
-be.a
+equal
('fu
|
e7e41c75d3d5f61c9a36f716c6f771ad41467adb
|
change describe
|
test.js
|
test.js
|
'use strict';
const expect = require('chai').expect;
describe('requiring', () => {
it('should not throw an error', () => {
expect(() => require('./lib')).to.not.throw();
});
});
describe('initializing', () => {
let ConfigLive;
beforeEach(() => {
ConfigLive = require('./lib');
});
it('should throw an error when no or invalid host is specified', () => {
expect(() => new ConfigLive()).to.throw(/Invalid host type. Must be a string\./);
expect(() => new ConfigLive(123)).to.throw(/Invalid host type. Must be a string\./);
expect(() => new ConfigLive({})).to.throw(/Invalid host type. Must be a string\./);
});
it('should throw an error when no or invalid port is specified', () => {
expect(() => new ConfigLive('localhost')).to.throw(/Invalid port type. Must be a number\./);
expect(() => new ConfigLive('localhost', '123')).to.throw(/Invalid port type. Must be a number\./);
expect(() => new ConfigLive('localhost', {})).to.throw(/Invalid port type. Must be a number\./);
});
it('should not throw an error when host and port are valid', () => {
expect(() => new ConfigLive('localhost', 6379)).to.not.throw();
});
});
describe('starting', () => {
const host = 'localhost';
const port = 6379;
const ConfigLive = require('./lib');
const cl = new ConfigLive(host, port);
const redis = require('redis');
const redisClient = redis.createClient(port, host);
beforeEach(done => {
redisClient.unref();
redisClient.del('config-live:config', done);
});
it('should emit \'started\' when started', done => {
cl.once('started', config => {
expect(config).to.be.empty;
done();
});
cl.start();
});
it('should emit \'updated\' when a value is set', done => {
cl.once('updated', (config) => {
expect(config).to.eql({ test: 'value1' });
done();
});
cl.set('test', 'value1');
});
it('should emit key update when a value is set', done => {
cl.once('test-updated', (value) => {
expect(value).to.equal('value2');
done();
});
cl.set('test', 'value2');
});
});
|
JavaScript
| 0.000078 |
@@ -1248,16 +1248,14 @@
be('
-starting
+events
', (
|
5bf90cc64c0f1edbbb1b4b79f9ccbb03d65f2f47
|
Add test
|
test.js
|
test.js
|
var assertRejected = require("./");
var test = require("blue-tape");
test("rejected promises should pass", function(t) {
return assertRejected(Promise.reject(new Error("Test")));
});
test("message comparisons are made if specified", function(t) {
return assertRejected(Promise.reject(new Error("Test")), "Test");
});
test("resolved promises fail", function(t) {
return assertRejected(
assertRejected(Promise.resolve("Test"))
);
});
|
JavaScript
| 0.000005 |
@@ -175,24 +175,292 @@
t%22)));%0A%7D);%0A%0A
+test(%22rejected promises should resolve with rejection%22, function(t) %7B%0A%09var error = new Error(%22Test%22);%0A%09return assertRejected(Promise.reject(error)).then(function (x) %7B%0A%09%09if (x !== error) throw new Error(%22Rejected error not sent to .then(). Received: %22 + x);%0A%09%7D);%0A%7D);%0A%0A
test(%22messag
|
931088ed8827ee11eb68905d65af98dfe9f5cadd
|
Refactor test
|
test.js
|
test.js
|
'use strict';
var buzzwords, assert;
buzzwords = require('./');
assert = require('assert');
describe('buzzwords', function () {
it('should be an `Object`', function () {
assert(typeof buzzwords === 'object');
});
});
describe('buzzwords.is(word)', function () {
it('should return true if a word is a buzzword', function () {
assert(buzzwords.is('cloud') === true);
});
it('should return false if a word is not a buzzword', function () {
assert(buzzwords.is('unicorn') === false);
});
});
describe('buzzwords.all()', function () {
var all = buzzwords.all();
it('should return an array', function () {
assert('length' in all);
assert(typeof all === 'object');
});
it('every entry should be lowercase', function () {
var iterator = -1,
length = all.length;
while (++iterator < length) {
assert(all[iterator].toLowerCase() === all[iterator]);
}
});
it('every entry should only occur once', function () {
var iterator = -1,
length = all.length;
while (++iterator < length) {
assert(all.indexOf(all[iterator], iterator + 1) === -1);
}
});
it('should be immutable', function () {
all.push('unicorn');
assert(buzzwords.all().indexOf('unicorn') === -1);
});
});
describe('buzzwords.add(buzzword) and buzzwords.remove(buzzword)',
function () {
it('should add and remove a buzzword', function () {
assert(buzzwords.is('unicorn') === false);
buzzwords.add('unicorn');
assert(buzzwords.is('unicorn') === true);
buzzwords.remove('unicorn');
assert(buzzwords.is('unicorn') === false);
});
it('should add and remove multiple buzzwords', function () {
assert(buzzwords.is('unicorn') === false);
assert(buzzwords.is('rainbow') === false);
buzzwords.add('unicorn', 'rainbow');
assert(buzzwords.is('unicorn') === true);
assert(buzzwords.is('rainbow') === true);
buzzwords.remove('unicorn', 'rainbow');
assert(buzzwords.is('unicorn') === false);
assert(buzzwords.is('rainbow') === false);
});
it('should fail silently when removing a non-existing buzzword',
function () {
assert(buzzwords.is('unicorn') === false);
buzzwords.remove('unicorn');
assert(buzzwords.is('unicorn') === false);
}
);
}
);
|
JavaScript
| 0.000001 |
@@ -8,16 +8,42 @@
rict';%0A%0A
+/**%0A * Dependencies.%0A */%0A%0A
var buzz
@@ -48,16 +48,20 @@
zzwords,
+%0A
assert;
@@ -114,24 +114,43 @@
'assert');%0A%0A
+/**%0A * Tests.%0A */%0A%0A
describe('bu
@@ -634,16 +634,26 @@
var
+all;%0A%0A
all = bu
@@ -748,16 +748,17 @@
n all);%0A
+%0A
@@ -867,95 +867,35 @@
-var iterator = -1,%0A length = all.length;%0A%0A while (++iterator %3C length
+all.forEach(function (value
) %7B%0A
@@ -913,29 +913,21 @@
assert(
+v
al
-l%5Biterator%5D
+ue
.toLower
@@ -937,29 +937,21 @@
e() ===
+v
al
-l%5Biterator%5D
+ue
);%0A
@@ -946,32 +946,34 @@
alue);%0A %7D
+);
%0A %7D);%0A%0A it
@@ -1037,95 +1037,42 @@
-var iterator = -1,%0A length = all.length;%0A%0A while (++iterator %3C length
+all.forEach(function (value, index
) %7B%0A
@@ -1106,31 +1106,20 @@
xOf(
+v
al
-l%5Biterator%5D, iterator
+ue, index
+ 1
@@ -1134,24 +1134,26 @@
);%0A %7D
+);
%0A %7D);%0A%0A
@@ -1528,32 +1528,33 @@
add('unicorn');%0A
+%0A
asse
@@ -1625,32 +1625,33 @@
ove('unicorn');%0A
+%0A
asse
@@ -1923,32 +1923,33 @@
n', 'rainbow');%0A
+%0A
asse
@@ -2089,24 +2089,25 @@
'rainbow');%0A
+%0A
@@ -2367,32 +2367,33 @@
n') === false);%0A
+%0A
@@ -2417,24 +2417,25 @@
'unicorn');%0A
+%0A
|
2384bf0eef8717175dbc3fc7add37ce429af037c
|
support tests with specific plugins
|
test.js
|
test.js
|
var fs = require('fs')
var chalk = require('chalk')
var success = require('success-symbol')
var error = require('error-symbol')
var getSongArtistTitle = require('./')
function stringifyTitle (o) {
return o ? '"' + o[0] + '" - "' + o[1] + '"' : 'nothing'
}
function testFailed (result, expected) {
console.error(chalk.red(' ' + error + ' expected ' + stringifyTitle(expected)))
console.error(chalk.red(' but got ' + stringifyTitle(result)))
}
function testSucceeded (result) {
console.log(chalk.green(' ' + success + ' got ' + stringifyTitle(result)))
}
function runTest (test) {
var expected = test.slice(1)
console.log(' ' + test[0])
var result = getSongArtistTitle(test[0])
if (!result || result[0] !== expected[0] || result[1] !== expected[1]) {
testFailed(result, expected)
return false
}
testSucceeded(result)
return true
}
function runSuite (suite) {
var score = { fail: 0, success: 0 }
suite.map(runTest).forEach(function (success) {
if (success) {
score.success++
} else {
score.fail++
}
})
return score
}
function readTest (test) {
return test.split('\n').filter(function (line) {
return line.substr(0, 2) !== '//'
})
}
function readSuite (pathName) {
return fs.readFileSync(pathName, 'utf8')
.split('\n\n')
.map(readTest)
}
var suites = fs.readdirSync('test')
var total = { fail: 0, success: 0 }
suites.forEach(function (suiteName) {
var suite = readSuite('test/' + suiteName)
var title = suiteName.replace(/\.txt$/, '')
console.log(title)
console.log(title.replace(/./g, '-'))
var result = runSuite(suite)
console.log(
chalk.red(' ' + error + ' ' + result.fail) + ' ' +
chalk.green(' ' + success + ' ' + result.success)
)
total.fail += result.fail
total.success += result.success
})
if (total.fail > 0) {
process.exit(1)
}
|
JavaScript
| 0 |
@@ -581,24 +581,33 @@
on runTest (
+plugins,
test) %7B%0A va
@@ -701,24 +701,33 @@
itle(test%5B0%5D
+, plugins
)%0A if (!res
@@ -964,20 +964,62 @@
ite.
-map(runTest)
+tests%0A .map(runTest.bind(null, suite.plugins))%0A
.for
@@ -1048,16 +1048,18 @@
) %7B%0A
+
+
if (succ
@@ -1061,24 +1061,26 @@
(success) %7B%0A
+
score.
@@ -1093,16 +1093,18 @@
s++%0A
+
%7D else %7B
@@ -1106,24 +1106,26 @@
lse %7B%0A
+
+
score.fail++
@@ -1129,18 +1129,22 @@
l++%0A
-%7D%0A
+ %7D%0A
%7D)%0A r
@@ -1278,24 +1278,57 @@
//'%0A %7D)%0A%7D%0A%0A
+var PLUGINS = /%5Eplugins: (.*?)$/%0A
function rea
@@ -1349,22 +1349,27 @@
me) %7B%0A
-return
+var tests =
fs.read
@@ -1418,26 +1418,272 @@
n')%0A
+%0A
- .map(readTest)
+var plugins = %5B 'base' %5D%0A var pluginsLine = tests%5B0%5D.match(PLUGINS)%0A if (pluginsLine) %7B%0A plugins = pluginsLine%5B1%5D.split(',').map(function (str) %7B return str.trim() %7D)%0A tests.shift()%0A %7D%0A return %7B%0A tests: tests.map(readTest),%0A plugins: plugins%0A %7D
%0A%7D%0A%0A
|
ab1848da8801ab58b55598c7927548166b632795
|
test - updated to use npm
|
test.js
|
test.js
|
var fs = require('fs-extra')
var path = require('path')
var spawn = require('child_process').spawn
var processRoot = process.cwd()
var testFolder = path.join(processRoot, '/test')
function installSample (type) {
return new Promise(function (resolve, reject) {
console.log('installing sample')
var install = spawn('vue-build', ['init', `-s=${type}`], { stdio: 'inherit' })
install.on('close', (code) => {
console.log(`finished installing sample`)
resolve()
})
})
}
function installPackages () {
return new Promise(function (resolve, reject) {
console.log('package installation')
var install = spawn('yarn', ['install'], { stdio: 'inherit' })
install.on('close', (code) => {
if (code !== 0) {
reject(code)
}
console.log(`finished installing packages`)
resolve()
})
})
}
function production () {
return new Promise(function (resolve, reject) {
console.log('building dist')
var prod = spawn('vue-build', ['prod'], { stdio: 'inherit' })
prod.on('close', (code) => {
if (code !== 0) {
reject(code)
}
console.log(`finished building dist`)
resolve()
})
})
}
function test (type) {
return new Promise(function (resolve, reject) {
console.log('testing app')
var prod = spawn('vue-build', [type], { stdio: 'inherit' })
prod.on('close', (code) => {
if (code !== 0) {
reject(code)
}
console.log(`finished testing app`)
resolve()
})
})
}
function simple () {
return new Promise(function (resolve, reject) {
process.chdir(processRoot)
fs.emptyDir(testFolder, function (err) {
if (err) { console.error(err) }
process.chdir(testFolder)
installSample('simple')
.then(installPackages)
.then(production)
.then(resolve)
.catch((err) => { reject(err) })
})
})
}
function full () {
return new Promise(function (resolve, reject) {
process.chdir(processRoot)
fs.emptyDir(testFolder, function (err) {
if (err) { console.error(err) }
process.chdir(testFolder)
installSample('full')
.then(installPackages)
.then(production)
.then(() => test('unit'))
.then(() => test('e2e'))
.then(resolve)
.catch((err) => { reject(err) })
})
})
}
function library () {
return new Promise(function (resolve, reject) {
process.chdir(processRoot)
fs.emptyDir(testFolder, function (err) {
if (err) { console.error(err) }
process.chdir(testFolder)
installSample('library')
.then(installPackages)
.then(production)
.then(() => test('unit'))
.then(resolve)
.catch((err) => { reject(err) })
})
})
}
// Run samples one at a time
simple()
.then(full)
.then(library)
.catch((error) => {
console.log('Tests failed: ', error)
})
|
JavaScript
| 0 |
@@ -641,12 +641,11 @@
wn('
-yarn
+npm
', %5B
@@ -1763,32 +1763,34 @@
'simple')%0A
+
.then(installPac
@@ -1788,32 +1788,34 @@
nstallPackages)%0A
+
.then(prod
@@ -1820,32 +1820,34 @@
oduction)%0A
+
.then(resolve)%0A
@@ -1837,32 +1837,34 @@
.then(resolve)%0A
+
.catch((er
@@ -2144,32 +2144,34 @@
e('full')%0A
+
.then(installPac
@@ -2175,32 +2175,34 @@
Packages)%0A
+
.then(production
@@ -2195,32 +2195,34 @@
hen(production)%0A
+
.then(() =
@@ -2235,32 +2235,34 @@
('unit'))%0A
+
.then(() =%3E test
@@ -2268,32 +2268,34 @@
t('e2e'))%0A
+
.then(resolve)%0A
@@ -2285,32 +2285,34 @@
.then(resolve)%0A
+
.catch((er
@@ -2602,24 +2602,26 @@
ary')%0A
+
.then(instal
@@ -2633,24 +2633,26 @@
ages)%0A
+
.then(produc
@@ -2659,24 +2659,26 @@
tion)%0A
+
+
.then(() =%3E
@@ -2693,24 +2693,26 @@
it'))%0A
+
.then(resolv
@@ -2710,24 +2710,26 @@
en(resolve)%0A
+
.catch
@@ -2808,16 +2808,18 @@
imple()%0A
+
.then(fu
@@ -2822,16 +2822,18 @@
n(full)%0A
+
.then(li
@@ -2839,16 +2839,18 @@
ibrary)%0A
+
.catch((
@@ -2861,16 +2861,18 @@
r) =%3E %7B%0A
+
consol
@@ -2902,11 +2902,13 @@
error)%0A
+
%7D)%0A
|
b87e97ef85dc79a418f350b51ff1b7b0376ebc0a
|
fix issue
|
test.js
|
test.js
|
console.log("test123");
console.log("helloWorld")
|
JavaScript
| 0.000002 |
@@ -44,8 +44,9 @@
oWorld%22)
+;
|
c81e491ee1717337f91db7cc521d2129e40e9ce9
|
improve readability of test
|
test.js
|
test.js
|
var test = require('tape');
var setLocationHash = require('./dist/set-location-hash.js');
var body = document.body;
body.style.height = '9999px';
// create 'div#some' element
var target = document.createElement('div');
target.id = 'some';
target.style.position = 'absolute';
target.style.top = '5000px';
body.appendChild(target);
window.scrollTo(0, 0);
test('if hash changed', function(t) {
'use strict';
setLocationHash('some');
t.plan(1);
t.equal(location.hash, '#some');
});
test('if scroll position unchanged', function(t) {
'use strict';
setLocationHash('some');
t.plan(1);
t.equal(
body.scrollTop || document.documentElement.scrollTop,
0
);
});
test('if returns current URL', function(t) {
'use strict';
var returnVal = setLocationHash('some');
t.plan(1);
t.equal(returnVal, location.href);
});
test('if empty hash available', function(t) {
'use strict';
setLocationHash('');
t.plan(1);
t.equal(location.href.split('#')[1], '');
});
if (typeof history.pushState === 'function' &&
typeof history.replaceState === 'function') {
test('replace option', function(t) {
'use strict';
var currentHistoryLength = history.length;
setLocationHash('baz', {replace: true});
t.plan(1);
t.equal(history.length, currentHistoryLength);
});
test('force option', function(t) {
'use strict';
var currentHistoryLength = history.length;
var currentFrag = location.hash.substring(1);
setLocationHash(currentFrag, {force: true});
t.plan(1);
t.equal(history.length, currentHistoryLength + 1);
});
}
|
JavaScript
| 0.000183 |
@@ -110,16 +110,51 @@
t.body;%0A
+body.style.padding = '0 1px 1px 0';
%0Abody.st
@@ -362,16 +362,150 @@
rget);%0A%0A
+var historyAvailable = typeof history.pushState === 'function' &&%0A typeof history.replaceState === 'function';%0A%0A
window.s
@@ -530,23 +530,25 @@
st('
-if hash changed
+setLocationHash()
', f
@@ -567,32 +567,103 @@
%0A 'use strict';
+%0A if (historyAvailable) %7B%0A t.plan(6);%0A %7D else %7B%0A t.plan(4);%0A %7D
%0A%0A setLocationH
@@ -678,29 +678,16 @@
e');%0A %0A
- t.plan(1);%0A
t.equa
@@ -680,32 +680,37 @@
);%0A %0A t.equal(
+%0A
location.hash, '
@@ -711,16 +711,20 @@
ash,
+%0A
'#some'
);%0A%7D
@@ -723,81 +723,61 @@
ome'
-);%0A%7D);%0A%0Atest('if scroll position unchanged', function(t) %7B%0A 'use strict'
+,%0A 'should change fragment identifier of URL.'%0A )
;%0A%0A
@@ -798,37 +798,26 @@
sh('some');%0A
-%0A
-t.plan(1);
%0A t.equal(%0A
@@ -883,98 +883,71 @@
0
+,
%0A
-);%0A%7D);%0A%0Atest('if returns current URL', function(t) %7B%0A 'use strict';%0A%0A var returnVal =
+ 'should not change scroll position.'%0A );%0A%0A t.equal(%0A
set
@@ -970,126 +970,65 @@
me')
-;%0A%0A t.plan(1);%0A t.equal(returnVal, location.href);%0A%7D);%0A%0Atest('if empty hash available', function(t) %7B%0A 'use strict'
+,%0A location.href,%0A 'should return current URL.'%0A )
;%0A%0A
@@ -1050,29 +1050,16 @@
h('');%0A%0A
- t.plan(1);%0A
t.equa
@@ -1060,16 +1060,21 @@
t.equal(
+%0A
location
@@ -1097,174 +1097,125 @@
%5B1%5D,
- '');%0A%7D);%0A%0Aif (typeof history.pushState === 'function' &&%0A typeof history.replaceState === 'function') %7B%0A%0A test('replace option', function(t) %7B
+%0A '',%0A 'should remove fragment identifier when the argument is empty string.'%0A );
%0A
+%0A
-'use strict';%0A
+if (historyAvailable) %7B
%0A
@@ -1258,17 +1258,16 @@
length;%0A
-%0A
setL
@@ -1299,39 +1299,28 @@
ce: true%7D);%0A
-%0A
-t.plan(1);
%0A t.equal
@@ -1312,32 +1312,39 @@
%0A t.equal(
+%0A
history.length,
@@ -1334,32 +1334,38 @@
history.length,
+%0A
currentHistoryL
@@ -1373,82 +1373,89 @@
ngth
-);%0A %7D);%0A%0A test('for
+,%0A 'should not push new history when %22repla
ce
+%22
option
-', function(t) %7B%0A 'use strict'
+ enabled.'%0A )
;%0A%0A
-var
curr
@@ -1539,17 +1539,16 @@
ing(1);%0A
-%0A
setL
@@ -1592,23 +1592,12 @@
%7D);%0A
-%0A
-t.plan(1);
%0A
@@ -1605,16 +1605,23 @@
t.equal(
+%0A
history.
@@ -1627,16 +1627,22 @@
.length,
+%0A
current
@@ -1662,15 +1662,89 @@
+ 1
+,%0A 'should push new history anyway when %22force%22 option enabled.'%0A
);%0A
+%7D%0A
%7D);%0A
-%7D%0A
|
b35796106b19505e39801e09c00b2487556d5686
|
make basic types tests
|
test.js
|
test.js
|
var QUnit = require("steal-qunit");
var compute = require("can/compute/");
var define = require("can-define");
var stache = require("can/view/stache/");
QUnit.test("basics on a prototype", function(){
var Person = function(first, last){
this.first = first;
this.last = last;
};
define(Person.prototype,{
first: {
type: "string"
},
last: {
type: "string"
},
fullName: {
get: function(){
return this.first+" "+this.last;
}
}
});
var p = new Person("Mohamed", "Cherif");
p.bind("fullName", function(ev, newVal, oldVal){
QUnit.equal(oldVal, "Mohamed Cherif");
QUnit.equal(newVal, "Justin Meyer");
});
p.bind("first", function(el, newVal, oldVal){
QUnit.equal(newVal, "Justin", "first new value");
QUnit.equal(oldVal, "Mohamed", "first old value");
});
can.batch.start();
p.first = "Justin";
p.last = "Meyer";
can.batch.stop();
});
QUnit.test('basics set', function () {
var Defined = function(prop){
this.prop = prop;
};
define(Defined.prototype,{
prop: {
set: function(newVal) {
return "foo" + newVal;
},
configurable: true
}
});
var def = new Defined();
def.prop = "bar";
QUnit.equal(def.prop, "foobar", "setter works");
var DefinedCB = function(prop){
this.prop = prop;
};
define(DefinedCB.prototype, {
prop: {
set: function(newVal,setter) {
setter("foo" + newVal);
}
}
});
var defCallback = new DefinedCB();
defCallback.prop = "bar";
QUnit.equal(defCallback.prop, "foobar", "setter callback works");
});
|
JavaScript
| 0.000014 |
@@ -1549,13 +1549,1186 @@
s%22);%0A%0A%09%7D);%0A%0A
+QUnit.test(%22basic type%22, function () %7B%0A%0A%09%09QUnit.expect(5);%0A%0A%09%09var Typer = function(arrayWithAddedItem,listWithAddedItem)%7B%0A%09%09%09this.arrayWithAddedItem = arrayWithAddedItem;%0A%09%09%09this.listWithAddedItem = listWithAddedItem;%0A%09%09%7D;%0A%0A%09%09define(Typer.prototype,%7B%0A%09%09%09%09arrayWithAddedItem: %7B%0A%09%09%09%09%09type: function (value) %7B%0A%09%09%09%09%09%09if (value && value.push) %7B%0A%09%09%09%09%09%09%09value.push(%22item%22);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09return value;%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D,%0A%09%09%09%09listWithAddedItem: %7B%0A%09%09%09%09%09type: function (value) %7B%0A%09%09%09%09%09%09if (value && value.push) %7B%0A%09%09%09%09%09%09%09value.push(%22item%22);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09return value;%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09Type: can.List%0A%09%09%09%09%7D%0A%09%09%7D); %0A%09%09%09%0A%09%09%09%0A%0A%0A%09%09var t = new Typer();%0A%09%09//deepEqual(t.keys(), %5B%5D, %22no keys%22);%0A%0A%09%09var array = %5B%5D;%0A%09%09t.arrayWithAddedItem = array;%0A%0A%09%09deepEqual(array, %5B%22item%22%5D, %22updated array%22);%0A%09%09QUnit.equal(t.arrayWithAddedItem, array, %22leave value as array%22);%0A%0A%09%09t.listWithAddedItem = %5B%5D;%0A%0A%09%09QUnit.ok(t.listWithAddedItem instanceof can.List, %22convert to can.List%22);%0A%09%09QUnit.equal(t.listWithAddedItem%5B0%5D, %22item%22, %22has item in it%22);%0A%0A%09%09t.bind(%22change%22, function (ev, attr) %7B%0A%09%09%09QUnit.equal(attr, %22listWithAddedItem.1%22, %22got a bubbling event%22);%0A%09%09%7D);%0A%0A%09%09t.listWithAddedItem.push(%22another item%22);%0A%0A%09%7D);%0A%0A
%0A
|
9d2ea5b33922a41a02f388c7702d7edfceff4738
|
fix test
|
test.js
|
test.js
|
'use strict';
var test = require('ava');
var humanNames = require('./');
test(function (t) {
t.assert(humanNames.female.length > 0);
t.assert(humanNames.male.length > 0);
t.assert(humanNames.all.length > 0);
t.assert(humanNames.femaleRandom());
t.assert(humanNames.maleRandom());
t.assert(humanNames.allRandom());
t.assert(humanNames.allRandom() !== humanNames.allRandom());
t.assert(humanNames.all[0] === 'Aaliyah');
t.assert(humanNames.all[1] === 'Aaron');
t.end();
});
|
JavaScript
| 0.000002 |
@@ -242,32 +242,34 @@
mes.femaleRandom
+En
());%0A t.asser
@@ -287,24 +287,26 @@
s.maleRandom
+En
());%0A t.a
@@ -323,32 +323,34 @@
nNames.allRandom
+En
());%0A t.asser
@@ -371,16 +371,18 @@
llRandom
+En
() !== h
@@ -400,16 +400,18 @@
llRandom
+En
());%0A
|
14a59a95f7c86837e17b3b2ba14575dcc8df87c2
|
Tweak test wording
|
test.js
|
test.js
|
import test from 'ava'
import getImgSrc from './'
test('should return img src attributes wtesthin double quotes when they exist', t => {
t.same(getImgSrc('<img class="foo" src="some-image.jpg"></img>'), ['some-image.jpg'])
})
test('should return multiple img src attributes wtesthin single quotes when they exist', t => {
t.same(
getImgSrc('<img class="foo" src=\'some-image.jpg\'></img>' +
'<img class="foo" src="some-other-image.jpg"></img>'),
['some-image.jpg', 'some-other-image.jpg']
)
})
test('should return an empty array when there are no images', t => {
t.same(getImgSrc('<span>HTML wtesthout an image</span> <img class="foo"></img>'), [])
})
|
JavaScript
| 0.000001 |
@@ -50,29 +50,23 @@
%0A%0Atest('
-should
return
+s
img src
@@ -223,29 +223,23 @@
%0A%0Atest('
-should
return
+s
multipl
@@ -516,21 +516,15 @@
st('
-should
return
+s
an
|
c0c7b883e654e7f0ec812baaad6bb626591ba9a3
|
Remove "api" block
|
test.js
|
test.js
|
'use strict';
var fs = require('fs');
var assert = require('assert');
var testit = require('testit');
var isExpression = require('./');
testit('api', function () {
testit('no options', function () {
assert(isExpression('myVar'))
assert(!isExpression('var'))
assert(isExpression('["an", "array", "\'s"].indexOf("index")'))
})
testit('throw === true', function () {
var options = {throw: true}
assert.throws(function () {
isExpression('var', options)
})
})
testit('strict === true', function () {
var options = {strict: true}
assert(isExpression('public'))
assert(!isExpression('public', options))
})
})
function passes (src, options) {
testit(JSON.stringify(src, options), function () {
options = options || {}
assert(isExpression(src, options))
})
}
testit('passes', function () {
passes('myVar')
passes('["an", "array", "\'s"].indexOf("index")')
passes('\npublic')
passes('abc // my comment', {lineComment: true})
passes('() => a', {ecmaVersion: 6})
})
function error (src, line, col, options) {
testit(JSON.stringify(src), function () {
options = options || {}
assert(!isExpression(src, options))
options.throw = true
assert.throws(function () {
isExpression(src, options)
}, function (err) {
assert.equal(err.loc.line, line)
assert.equal(err.loc.column, col)
assert(err.message)
return true
})
})
}
testit('fails', function () {
error('', 1, 0)
error('var', 1, 0)
error('weird error', 1, 6)
error('asdf}', 1, 4)
error('\npublic', 2, 0, {strict: true})
error('abc // my comment', 1, 4)
error('() => a', 1, 1)
})
|
JavaScript
| 0 |
@@ -135,531 +135,8 @@
);%0A%0A
-testit('api', function () %7B%0A testit('no options', function () %7B%0A assert(isExpression('myVar'))%0A assert(!isExpression('var'))%0A assert(isExpression('%5B%22an%22, %22array%22, %22%5C's%22%5D.indexOf(%22index%22)'))%0A %7D)%0A%0A testit('throw === true', function () %7B%0A var options = %7Bthrow: true%7D%0A assert.throws(function () %7B%0A isExpression('var', options)%0A %7D)%0A %7D)%0A%0A testit('strict === true', function () %7B%0A var options = %7Bstrict: true%7D%0A assert(isExpression('public'))%0A assert(!isExpression('public', options))%0A %7D)%0A%7D)%0A%0A
func
|
42ebc0c573fa2d3a100af2534d9eb7df8b1d0c67
|
Fix tests
|
test.js
|
test.js
|
'use strict'
var test = require('tape')
var iso6392 = require('.')
test('iso6392', function(t) {
t.plan(5)
t.ok(Array.isArray(iso6392), 'should be an `array`')
iso6392.forEach(function(language) {
if (language.iso6391 !== 'en') {
return
}
t.equal(language.iso6392B, 'eng', 'bibliographic code')
t.equal(language.iso6392T, null, 'terminologic code')
t.equal(language.iso6391, 'en', '639-1 code')
t.equal(language.name, 'English', 'name')
})
})
|
JavaScript
| 0.000003 |
@@ -352,12 +352,17 @@
2T,
-null
+undefined
, 't
|
9e954f3c40dfdf8c29c9fee7bc0b9edb59f66b33
|
test with commented ASCII PBM
|
test.js
|
test.js
|
var fs = require("fs");
var assert = require("assert");
var mask = require("./mask");
function readToArrayBuffer (path, callback) {
var rs = fs.createReadStream(path);
rs.on("readable", function () {
var buffer = rs.read();
var ab = new ArrayBuffer(buffer.length);
var u8 = new Uint8Array(ab);
for (var i = 0; i < buffer.length; i++) {
u8[i] = buffer[i];
};
return callback(ab);
});
};
function readMask (path, callback) {
return readToArrayBuffer (path, function (ab) {
return mask.fromPBM(ab, callback);
});
};
var pbm = [ "test-data/bullet-ascii.pbm",
"test-data/frame-ascii.pbm",
"test-data/bullet-binary.pbm",
"test-data/frame-binary.pbm",
"test-data/solid-ascii.pbm",
"test-data/solid-binary.pbm" ];
describe("mask", function () {
describe("#fromPBM()", function () {
it("exists.", function () {
assert.notEqual(mask.fromPBM, undefined);
});
function assertReads (path) {
it("reads " + path, function (done) {
readMask(path, function (mask) {
done();
});
});
};
function assertSize (path, width, height) {
it("gets the size of " + path + " right", function (done) {
readMask(path, function (mask) {
assert.equal(mask.size.x, width);
assert.equal(mask.size.y, height);
done();
});
});
};
/* We should be able to read each image and get its size correct. */
pbm.forEach(function (img) {
assertReads(img);
assertSize(img, 10, 10);
});
function assertDataEqual (a, b) {
it("gets the same data for " + a + " and " + b, function (done) {
readMask(a, function (maskA) {
readMask(b, function (maskB) {
assert.equal(maskA.size.x, maskB.size.x);
assert.equal(maskA.size.y, maskB.size.y);
for (var x = 0; x < maskA.size.x; x++) {
for (var y = 0; y < maskA.size.y; y++) {
assert.equal(maskA.data[x][y], maskB.data[x][y]);
};
};
done();
});
});
});
};
/* The binary and ascii variants of things should have equal data. */
assertDataEqual("test-data/bullet-binary.pbm",
"test-data/bullet-ascii.pbm");
assertDataEqual("test-data/frame-binary.pbm",
"test-data/frame-ascii.pbm");
});
describe(".collision()", function () {
function assertCollidesWithSelf (path) {
it ("says " + path + " collides with itself", function (done) {
readMask(path, function (m) {
assert.equal(mask.collision(m, m), true);
done();
});
});
};
function assertDoesNotCollideWithTranslatedSelf (path) {
it("says " + path + "doesn't collide with itself, translated",
function (done) {
readMask(path, function (m) {
var o = m.at(m.size.x, m.size.y);
assert.equal(mask.collision(m, o), false);
done();
});
});
};
function assertCollides(a, b) {
it("says that " + a + " and " + b + " collide", function (done) {
readMask(a, function (maskA) {
readMask(b, function (maskB) {
assert.equal(mask.collision(maskA, maskB), true);
done();
});
});
});
};
function assertDoesNotCollide(a, b) {
it("says that " + a + " and " + b + "do not collide", function (done) {
readMask(a, function (maskA) {
readMask(b, function (maskB) {
assert.equal(mask.collision(maskA, maskB), false);
done();
});
});
});
};
/* Every nonempty image should collide with itself;
every nonempty image should collide with the solid image;
every image should not collide with itself translated by its size. */
pbm.forEach(function (img) {
assertCollidesWithSelf(img);
assertCollides(img, "test-data/solid-binary.pbm");
assertDoesNotCollideWithTranslatedSelf(img);
});
/* The frame image and the bullet image should not collide. */
assertDoesNotCollide("test-data/frame-ascii.pbm",
"test-data/bullet-binary.pbm");
});
describe(".within()", function () {
function assertWithinSelf (path) {
it ("says " + path + " is within itself", function (done) {
readMask(path, function (m) {
assert.equal(mask.within(m, m), true);
done();
});
});
};
function assertWithin(a, b) {
it("says that " + a + " is within " + b, function (done) {
readMask(a, function (maskA) {
readMask(b, function (maskB) {
assert.equal(mask.within(maskA, maskB), true);
done();
});
});
});
};
function assertNotWithin(a, b) {
it("says that " + a + " is not within " + b, function (done) {
readMask(a, function (maskA) {
readMask(b, function (maskB) {
assert.equal(mask.within(maskA, maskB), false);
done();
});
});
});
};
/* Every image should be within itself and within the solid image. */
pbm.forEach(function (img) {
assertWithinSelf(img);
assertWithin(img, "test-data/solid-binary.pbm");
});
/* The frame image should not be within the bullet image. */
assertNotWithin("test-data/frame-ascii.pbm",
"test-data/bullet-binary.pbm");
});
});
|
JavaScript
| 0 |
@@ -2426,32 +2426,330 @@
me-ascii.pbm%22);%0A
+ /* Make sure we read commented ASCII PBM correctly. */%0A it(%22Reads commented ASCII PBM%22, function (done) %7B%0A readMask(%22test-data/commented.pbm%22, function (m) %7B%0A console.log(m);%0A assert.equal(m.size.x, 1);%0A assert.equal(m.size.y, 1);%0A done();%0A %7D);%0A %7D);%0A
%7D);%0A describe
|
7cffdd9ff33370051bcf6416932a7dfbf305e70f
|
check API access before running tests
|
test.js
|
test.js
|
var util = require ('util');
// Setup
// $ env PIWIK_URL= PIWIK_TOKEN= PIWIK_SITEID= npm test
var url = process.env.PIWIK_URL || null;
var token = process.env.PIWIK_TOKEN || null;
var siteId = process.env.PIWIK_SITEID || null;
var piwik = require ('./').setup (url, token);
// handle exits
var errors = 0;
process.on ('exit', function () {
if (errors === 0) {
console.log ('\n\033[1mDONE, no errors.\033[0m\n');
process.exit (0);
} else {
console.log ('\n\033[1mFAIL, '+ errors +' error'+ (errors > 1 ? 's' : '') +' occurred!\033[0m\n');
process.exit (1);
}
});
// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
console.log ();
console.error (err.stack);
console.trace ();
console.log ();
errors++;
});
// Queue to prevent flooding
var queue = [];
var next = 0;
function doNext () {
next++;
if (queue [next]) {
queue [next] ();
}
}
// doTest( passErr, 'methods', [
// ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
if (err instanceof Error) {
console.error (label +': \033[1m\033[31mERROR\033[0m\n');
console.error (util.inspect (err, false, 10, true));
console.log ();
console.error (err.stack);
console.log ();
errors++;
} else {
var testErrors = [];
tests.forEach (function (test) {
if (test [1] !== true) {
testErrors.push (test [0]);
errors++;
}
});
if(testErrors.length === 0) {
console.log (label +': \033[1m\033[32mok\033[0m');
} else {
console.error (label +': \033[1m\033[31mfailed\033[0m ('+ testErrors.join(', ') +')');
}
}
doNext ();
}
// ! Track one
queue.push (function () {
piwik.track (
{
idsite: siteId,
url: 'https://www.npmjs.com/package/piwik',
cvar: {'1': ['node test', process.version]}
},
function (err, data) {
doTest (err, 'track one', [
['data type', typeof data === 'object'],
['data.status', data && data.status === 'success'],
['data.tracked', data && data.tracked === 1]
]);
}
);
});
// ! Track multi
queue.push (function () {
piwik.track (
[
{
idsite: siteId,
url: 'https://www.npmjs.com/package/piwik',
cvar: {'1': ['node test', process.version]}
},
{
idsite: siteId,
url: 'https://github.com/fvdm/nodejs-piwik',
cvar: {'1': ['node test', process.version]}
}
],
function (err, data) {
doTest (err, 'track multi', [
['data type', typeof data === 'object'],
['data.status', data && data.status === 'success'],
['data.tracked', data && data.tracked === 2]
]);
}
);
});
// ! API
queue.push (function () {
piwik.api (
{
method: 'Actions.getPageUrls',
idSite: siteId,
period: 'day',
date: 'today'
},
function (err, data) {
doTest (err, 'api', [
['data type', data instanceof Array],
['data length', data && data.length >= 1],
['item type', data && data[0] instanceof Object],
['item label', data && data[0] && typeof data[0].label === 'string']
]);
}
);
});
// Start the tests
console.log ('Running tests...\n');
queue [0] ();
|
JavaScript
| 0.000001 |
@@ -1671,16 +1671,415 @@
();%0A%7D%0A%0A%0A
+// ! API access%0Aqueue.push (function () %7B%0A piwik.api (%0A %7Bmethod: 'API.getPiwikVersion'%7D,%0A function (err, data) %7B%0A if (err) %7B%0A console.log ('API access: failed ('+ err.message +')');%0A console.log (err.stack);%0A errors++;%0A process.exit (1);%0A %7D else %7B%0A console.log ('API access: %5C033%5B1m%5C033%5B32mok%5C033%5B0m');%0A doNext ();%0A %7D%0A %7D%0A );%0A%7D);%0A%0A%0A
// ! Tra
|
7435975ff48afa36da366bcc9d10c8c767cf7690
|
Update test
|
test.js
|
test.js
|
var assert = require('assert');
var read = require('./lib/de-read.js');
var numberLength = read.util.numberLength;
describe('Number length', function () {
for (var i = 0; i <= 9; i++) {
it('The length of number ' + i + ' is 1', (function (j) {
return function () {
assert.equal(1, numberLength(j));
}
})(i));
}
for (var i = 10; i <= 99; i++) {
it('The length of number ' + i + ' is 2', (function (j) {
return function () {
assert.equal(2, numberLength(j));
}
})(i));
}
for (var i = 100; i <= 999; i++) {
it('The length of number ' + i + ' is 3', (function (j) {
return function () {
assert.equal(3, numberLength(j));
}
})(i));
}
});
describe('Read time', function () {
});
describe('Read year', function () {
});
describe('Read number', function () {
});
|
JavaScript
| 0.000001 |
@@ -145,24 +145,121 @@
nction () %7B%0A
+ it('Not a number', function () %7B%0A assert.equal(-1, numberLength('abc'));%0A %7D);%0A %0A
for (var
|
22224f0f1f3ae9dd39a9929058b8ed0252134d4d
|
Return array rather than array(array)
|
lib/tfl-bus-api.js
|
lib/tfl-bus-api.js
|
var request = require('request')
, Q = require('q')
, _ = require('underscore');
var Bus = function(bus, callback) {
if (!bus) throw new Error('Missing bus number');
var deferred = Q.defer();
this.promise = deferred.promise;
request({
url: 'http://countdown.tfl.gov.uk/search?searchTerm=' + bus
}, function(err, res) {
this.data = JSON.parse(res.body).results.routeResults[0];
if (!callback) {
deferred.resolve(this);
return;
}
callback(this);
}.bind(this));
if (!callback) return this.promise;
else return this;
};
Bus.prototype.start = function() {
return {
lat: this.data.swLatBB,
lng: this.data.swLngBB
};
};
Bus.prototype.end = function() {
return {
lat: this.data.neLatBB,
lng: this.data.neLngBB
};
}
Bus.prototype.findStopBySmsCode = function(smsCode) {
return _.find(this.data.directions[1].segments[0].markers, function(busStop) {
return (busStop.smsCode == smsCode);
});
};
Bus.prototype.findStopByName = function(name) {
return _.find(this.data.directions[1].segments[0].markers, function(busStop) {
return (busStop.name == name);
});
};
Bus.prototype.geometry = function() {
return this.data.directions[0].routeGeometry;
};
module.exports = Bus;
|
JavaScript
| 0.000438 |
@@ -1226,16 +1226,19 @@
Geometry
+%5B0%5D
;%0A%7D;%0A%0Amo
|
ebf2c2b0b5fcc78cf8a811d1ff9b72aad9048361
|
extend processSend data
|
lib/utils/index.js
|
lib/utils/index.js
|
var mkdirp = require('mkdirp');
var async = require('async');
var fs = require('fs');
var hconsole = require('./hconsole');
exports.hconsole = hconsole;
/**
* Ensures a directory exists using mkdir -p.
*
* @param {String} path
* @param {Function} callback
* @api public
*/
exports.ensureDir = function (path, callback) {
mkdirp(path, callback);
};
/**
* Creates a deep-clone of a JSON-serializable object
*
* @param obj - the object to serialize
* @api public
*/
exports.jsonClone = function (obj) {
return JSON.parse(JSON.stringify(obj));
};
/**
* Send a 302 (Found) redirect response for a HTTP Server
* Request object
*/
exports.redirect = function (loc, res) {
res.writeHead(302, {Location: loc});
return res.end(
'<html>' +
'<head>' +
'<title>302 Found</title>' +
'</head>' +
'<body>' +
'<p>' +
'Found: <a href=\'' + loc + '\'>' + loc + '</a>' +
'</p>' +
'</body>' +
'</html>'
);
};
/**
* Makes sure the appropriate app directories exists
*/
exports.ensurePaths = function (config, callback) {
var paths = [config.hoodie.app_path];
async.map(paths, exports.ensureDir, callback);
};
/**
* write app config to stack.json
*/
exports.writeConfig = function (config, callback) {
var stackJSON = config.project_dir + '/data/stack.json';
var stack = {
couch: {
port: Number(config.couch.port),
host: config.host
},
www: {
port: config.www_port,
host: config.host
},
admin: {
port: config.admin_port,
host: config.host
}
};
fs.writeFile(stackJSON, JSON.stringify(stack), function (err) {
if (err) {
return callback(new Error(
'Hoodie could not write stack.json.\n' +
'Please try again.'
));
} else {
return callback();
}
});
};
exports.processSend = function (config, callback) {
if (process.send) {
process.send({
app: {
started: true
}
});
}
return callback();
};
/**
* Attempts to detect a Nodejitsu environment
*/
exports.isNodejitsu = function (env) {
return !!(env.SUBDOMAIN);
};
|
JavaScript
| 0 |
@@ -1980,16 +1980,340 @@
d: true%0A
+ %7D,%0A pid: process.pid,%0A stack: %7B%0A couch: %7B%0A port: Number(config.couch.port),%0A host: config.host%0A %7D,%0A www: %7B%0A port: config.www_port,%0A host: config.host%0A %7D,%0A admin: %7B%0A port: config.admin_port,%0A host: config.host%0A %7D%0A
%7D%0A
|
efdb5d911f7b063ecce65b7a847947ca3fd0e765
|
Update findHomePath for USERPROFILE
|
lib/utils/utils.js
|
lib/utils/utils.js
|
/*
* Copyright 2012 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require('fs'),
path = require('path'),
wrench = require('wrench'),
os = require('os'),
conf = require("./conf"),
childProcess = require('child_process'),
cordovaUtils = require(path.join(conf.NODE_MODULES_DIR,'cordova/src/util')),
CORDOVA_DIR = '.cordova',
_self;
_self = {
findHomePath : function () {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
},
getCordovaDir: function () {
var cordovaPath = path.join(_self.findHomePath(), CORDOVA_DIR);
if (!fs.existsSync(cordovaPath)) {
fs.mkdirSync(cordovaPath);
}
return cordovaPath;
},
quotify : function (property) {
//wrap in quotes if it's not already wrapped
if (property.indexOf("\"") === -1) {
return "\"" + property + "\"";
} else {
return property;
}
},
fetchBlackBerry: function () {
var cli_platforms = require(path.join(conf.NODE_MODULES_DIR, 'cordova/platforms')),
bbVersion = cli_platforms.blackberry10.version,
wwwVersion = cli_platforms.www.version,
cliBBLib = path.join(_self.getCordovaDir(), "lib", "blackberry10", "cordova", bbVersion ),
cliWWWLib = path.join(_self.getCordovaDir(), "lib", "www", "cordova", wwwVersion );
if (!fs.existsSync(cliBBLib)) {
wrench.mkdirSyncRecursive(cliBBLib, 0775);
wrench.copyDirSyncRecursive(conf.CORDOVA_BB_DIR, cliBBLib);
//Re-Adding execution permissions
wrench.chmodSyncRecursive(path.join(cliBBLib, "bin"), 0775);
}
if (!fs.existsSync(cliWWWLib)) {
wrench.mkdirSyncRecursive(cliWWWLib, 0775);
wrench.copyDirSyncRecursive(conf.CORDOVA_HELLO_WORLD_DIR, cliWWWLib);
}
},
isWindows: function () {
return os.type().toLowerCase().indexOf("windows") >= 0;
},
spawn : function (command, args, options, callback) {
//Optional params handling [args, options]
if (typeof args === "Object" && !Array.isArray(args)) {
callback = options;
options = args;
args = [];
} else if (typeof args === "function"){
callback = args;
options = {};
args = [];
} else if (typeof options === "function"){
callback = options;
options = {};
}
var customOptions = options._customOptions || {},
feedback = function (data) { console.log(data.toString());},
proc,
i;
//delete _customOptions from options object before sending to exec
delete options._customOptions;
//Use the process env by default
options.env = options.env || process.env;
proc = childProcess.spawn(command, args, options);
if (!customOptions.silent) {
proc.stdout.on("data", feedback);
proc.stderr.on("data", feedback);
}
proc.on("close", callback);
},
preProcessOptions: function (inputOptions, callback, commandDefaultOptions) {
var projectRoot = cordovaUtils.isCordova(process.cwd()),
options,
platforms,
DEFAULT_OPTIONS = {verbose: false, platforms : [], options: []};
if (!projectRoot) {
err = new Error('Current working directory is not a WebWorks-based project.');
if (callback) {
return callback(err);
} else {
throw err;
}
} else {
platforms = cordovaUtils.listPlatforms(projectRoot);
//We came from the CLI
if (Array.isArray(inputOptions)) {
options = commandDefaultOptions || DEFAULT_OPTIONS;
// Filter all non-platforms into options
inputOptions.forEach(function(option) {
if (platforms.indexOf(option) !== -1) {
options.platforms.push(option);
} else {
if (option === "--verbose" && !options.verbose) {
options.verbose = true;
} else {
options.options.push(option);
}
}
});
} else {
options = inputOptions || commandDefaultOptions || DEFAULT_OPTIONS;
if (inputOptions && commandDefaultOptions) {
options.options = options.options.concat(commandDefaultOptions.options);
}
}
if (!options.platforms || options.platforms.length === 0) {
options.platforms = platforms;
}
if (callback && typeof callback === "function") {
options.callback = callback;
}
return options;
}
}
};
module.exports = _self;
|
JavaScript
| 0 |
@@ -1002,16 +1002,19 @@
env.
-HOMEPATH
+USERPROFILE
%7C%7C
@@ -1025,27 +1025,24 @@
ess.env.
-USERPROFILE
+HOMEPATH
;%0A %7D,
|
bcad7388d8f50373c38e7f67c7fa00d1ba36b3a9
|
Use full path when spawning a watcher
|
lib/watcher-src.js
|
lib/watcher-src.js
|
// @Compiler-Transpile "true"
// @Compiler-Output "./watcher.js"
const JSToolkit = require('js-toolkit')
const FS = JSToolkit.promisifyAll(require('fs'))
const CPPromise = require('childprocess-promise')
const EventEmitter = require('events').EventEmitter
const Chokidar = require('chokidar')
class Watcher extends EventEmitter {
constructor(rootPath) {
super()
this.fswatcher = Chokidar.watch(rootPath, {
ignored: [/[\/\\]\./, /node_modules/, /bower_components/],
followSymlinks: true,
persistent: true
})
this.process = new CPPromise('./watcher-thread')
this.imports = new Map()
this.fswatcher.on('change', path => {
this.compile(path).then(result => {
if (result.options.Output) {
return FS.writeFile(result.options.Output, result.contents).then(() => result)
} else return result
}).then(result => {
this.imports.set(path, result.options.internal.imports)
for (let entry of this.imports) {
if (entry[1].indexOf(path) === -1) continue
this.compile(entry[0])
}
})
})
this.fswatcher.on('addDir', path => this.fswatcher.add(path))
this.fswatcher.on('error', e => this.emit('error', e.stack))
}
scan(dirPath, Ignore) {
Ignore = Ignore || '^\\.|node_modules|bower_components'
return this.process.request('SCAN', {Path: dirPath, Ignore})
}
compile(filePath, options) {
options = options || {}
return this.process.request('COMPILE', {Path: filePath, Options: options}).catch(e => this.emit('error', e.stack))
}
disconnect() {
this.process.disconnect()
}
kill() {
this.process.kill()
}
onError(callback){
this.on('error', callback)
}
}
module.exports = Watcher
|
JavaScript
| 0 |
@@ -570,10 +570,21 @@
ise(
+__dirname +
'
-.
/wat
|
8f6710efd316ecfb78960c720997a2cae7725293
|
refactor carousel component to include remove method
|
res/js/transforms/carousel.js
|
res/js/transforms/carousel.js
|
import { $, $$, getAttr, mapCall, toggleClass } from 'luett'
import delegate from 'delegate'
import { range } from 'lodash'
import stroll from 'stroll.js'
function createScroller (el) {
return stroll.factory(el)
}
function attachNav (el, opts) {
el.insertAdjacentHTML('beforeend', `
<div class="${opts.cssNav}">
<div>
<button type="button" class="${opts.cssNavBtn} ${opts.cssNavBtnPrev}">
<i class="${opts.cssNavBtnIcon}"></i>
</button>
</div>
<div>
<button type="button" class="${opts.cssNavBtn} ${opts.cssNavBtnNext}">
<i class="${opts.cssNavBtnIcon}"></i>
</button>
</div>
</div>
`)
}
function attachIndex (el, opts, numberOfSlides) {
if (numberOfSlides <= 1) {
return
}
el.insertAdjacentHTML('beforeend', `
<ol class="${opts.cssIndex}">
${range(1, Math.min(numberOfSlides + 1, 11)).map(idx => `
<li>
<button type="button" class="${opts.cssIndexBtn}" data-carousel-index="${idx}"></button>
</li>
`).join('\n')}
</ol>
`)
}
function carousel (root, options) {
const conf = Object.assign({}, carousel.DEFAULTS, options.conf)
const iface = Object.create(null)
const crsl = $(`.${conf.cssCarousel}`, root)
// create a default scroller
let scroller = createScroller(crsl)
// configure noop emitter
let emit = () => {}
// set state
let currentSlide = 1
function unsetCurrent () {
$$(`.${conf.cssSlides} > .${conf.cssCurrent}`, root)
.forEach((item) => item.classList.remove(conf.cssCurrent))
}
function setCurrent (el) {
el.classList.add(conf.cssCurrent)
return scroller({ x: el.offsetLeft, y: el.offsetTop })
}
function showSlide (idx) {
const slide = $(`.${conf.cssSlides} > :nth-child(${idx})`, root)
if (!slide) return iface
root.classList.toggle(conf.cssSlidesFirst, idx === 1)
root.classList.toggle(conf.cssSlidesLast, idx === getNumberOfSlides())
mapCall($$(`.${conf.cssIndexBtn}`, root), toggleClass, conf.cssIndexBtnCurrent, false)
mapCall($$(`.${conf.cssIndex} > :nth-child(${idx}) .${conf.cssIndexBtn}`), toggleClass, conf.cssIndexBtnCurrent, true)
const eventData = { index: idx, carousel: crsl, slide }
emit('slide:start', eventData)
unsetCurrent()
setCurrent(slide)
.then(function () {
emit('slide:end', eventData)
})
currentSlide = idx
return iface
}
function getNumberOfSlides () {
return $(`.${conf.cssSlides}`).children.length
}
iface.setEmitter = (emitter) => {
emit = emitter
return iface
}
iface.setScroller = (factory) => {
scroller = factory(crsl)
return iface
}
iface.showSlide = (idx) => {
return showSlide(idx)
}
iface.nextSlide = () => {
return showSlide(currentSlide + 1)
}
iface.prevSlide = () => {
return showSlide(currentSlide - 1)
}
delegate(root, `.${conf.cssNavBtn}`, 'click', function (event) {
event.preventDefault()
if (event.delegateTarget.classList.contains(conf.cssNavBtnPrev)) {
iface.prevSlide()
}
if (event.delegateTarget.classList.contains(conf.cssNavBtnNext)) {
iface.nextSlide()
}
})
delegate(root, `.${conf.cssIndexBtn}`, 'click', function (event) {
event.preventDefault()
const idx = parseInt(getAttr(event.delegateTarget, 'data-carousel-index'), 10)
showSlide(idx)
})
// add nav
attachNav(root, conf)
attachIndex(root, conf, getNumberOfSlides())
// set first slide as current but wait for carousel to return
setTimeout(() => iface.showSlide(currentSlide), 0)
setTimeout(() => root.classList.add(conf.cssReady), 10)
return iface
}
carousel.DEFAULTS = {
cssReady: 'carousel-ready',
cssCurrent: 'carousel-current',
cssSlides: 'carousel-slides',
cssSlidesFirst: 'carousel-first',
cssSlidesLast: 'carousel-last',
cssNav: 'carousel-nav',
cssNavBtn: 'carousel-btn',
cssNavBtnIcon: 'carousel-btn-icon',
cssNavBtnPrev: 'carousel-btn-prev',
cssNavBtnNext: 'carousel-btn-next',
cssCarousel: 'carousel',
cssIndex: 'carousel-index',
cssIndexBtn: 'carousel-btn-index',
cssIndexBtnCurrent: 'carousel-btn-index-current'
}
export default carousel
|
JavaScript
| 0 |
@@ -38,16 +38,24 @@
gleClass
+, remove
%7D from
@@ -769,32 +769,90 @@
%3C/div%3E%0A %60)%0A
+ return %7B remove() %7B remove($(%60.$%7Bopts.cssNav%7D%60), el) %7D%7D%0A
%7D%0A%0Afunction atta
@@ -1280,16 +1280,76 @@
%0A %60)%0A
+ return %7B remove() %7B remove($(%60.$%7Bopts.cssIndex%7D%60), el) %7D%7D%0A
%7D%0A%0Afunct
@@ -1529,18 +1529,16 @@
root)%0A%0A
-
// cre
@@ -1598,18 +1598,16 @@
r(crsl)%0A
-
// con
@@ -1648,19 +1648,16 @@
) =%3E %7B%7D%0A
-%0A
// set
@@ -3194,16 +3194,156 @@
)%0A %7D%0A%0A
+ iface.remove = () =%3E %7B%0A navListener.destroy()%0A nav.remove()%0A indexListener.destroy()%0A index.remove()%0A %7D%0A%0A const navListener =
delegat
@@ -3638,16 +3638,38 @@
%0A %7D)%0A%0A
+ const indexListener =
delegat
@@ -3863,18 +3863,16 @@
)%0A %7D)%0A%0A
-
// add
@@ -3877,16 +3877,28 @@
dd nav%0A
+ const nav =
attachN
@@ -3913,16 +3913,30 @@
conf)%0A
+ const index =
attachI
@@ -3974,18 +3974,16 @@
des())%0A%0A
-
// set
|
ead1c9c8085ec88d5a2db6871d806cf50a41b890
|
add status prop
|
asserts/js/monitoring/node.js
|
asserts/js/monitoring/node.js
|
function NodeModule(options) {
this.id = options._id;
this.name = options.name[lang];
this.description = options.description[lang];
this.metrics = options.metrics;
this.workerId = options.workerId;
this.table = options.table;
this.words = options.words;
this.template = '<div class="card"><div class="card-header">' + this.name + '</div><div class="card-block"></div></div>';
this.$moduleBlock = $(this.template);
this.handleSummary();
}
NodeModule.prototype.fillData = function (metric, data) {
var leftColumn = 'col-xs-4 text-bold margin-bottom-3';
var rightColumn = 'col-xs-8';
if (!data) {
this.$moduleBlock.find('.card-block').append('<span>' + this.words.emptyData + '</span>');
return;
}
this.$moduleBlock.find('.card-block')
.css('font-size', '12px')
.append('<span>' + metric.name[lang] + ':</span>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.os + ':</div><div class="' + rightColumn + '">' + data.os.name + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.version + ':</div><div class="' + rightColumn + '">' + data.os.version + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.platform + ':</div><div class="' + rightColumn + '">' + data.os.type + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.arch + ':</div><div class="' + rightColumn + '">' + data.os.arch + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.kernel + ':</div><div class="' + rightColumn + '">' + data.os.kernel + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.uptime + ':</div><div class="' + rightColumn + '">' +
(new Date((new Date()).getTime() - data.uptime)).toUTCString() + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.inet + ':</div><div class="' + rightColumn + '">' + data.net.name + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.host + ':</div><div class="' + rightColumn + '">' + data.hostname + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.ip + ':</div><div class="' + rightColumn + '">' + data.net.ip.find(function (item) {
return item.family == 'IPv4';
}).address + '</div></div>')
.append('<div class="row"><div class="' + leftColumn + '">' + this.words.mac + ':</div><div class="' + rightColumn + '">' + data.net.ip[0].mac + '</div></div>')
};
NodeModule.prototype.handleSummary = function () {
var self = this;
this.metrics.forEach(function (item) {
$.get('/monitoring/servers/' + self.workerId + '/metrics/' + item._id + '/event', function (result) {
try {
console.log(result);
if (result.ok) {
if (item.sys_name === 'node_details') {
self.fillData(item, result.data);
}
} else {
//TODO Handler ERROR!!!! AAAAAAAAA
}
} catch (e) {
console.error(e);
}
});
});
if (this.metrics.length) {
self.table.appendColumn(6).append(self.$moduleBlock);
}
};
var InitNODE = function(table, workerId, module, words) {
module.table = table;
module.workerId = workerId;
module.words = words;
console.log(module);
new NodeModule(module);
console.log('Node module initialized');
};
|
JavaScript
| 0.000001 |
@@ -775,135 +775,617 @@
-this.$moduleBlock.find('.card-block')%0A .css('font-size', '12px')%0A .append('%3Cspan%3E' + metric.name%5Blang%5D + ':%3C/span
+var status;%0A var statusWord = data.status ? this.words.status.up : this.words.status.down;%0A if (data.status) %7B%0A status = '%3Ci class=%22fa fa-circle%22 style=%22color: green%22%3E%3C/i%3E ' + statusWord;%0A %7D else %7B%0A status = '%3Ci class=%22fa fa-circle%22 style=%22color: red%22%3E%3C/i%3E ' + statusWord;%0A %7D%0A %0A %0A this.$moduleBlock.find('.card-block')%0A .css('font-size', '12px')%0A .append('%3Cspan%3E' + metric.name%5Blang%5D + ':%3C/span%3E')%0A .append('%3Cdiv class=%22row%22%3E%3Cdiv class=%22' + leftColumn + '%22%3E' + this.words.status.title + ':%3C/div%3E%3Cdiv class=%22' + rightColumn + '%22%3E' + status + '%3C/div%3E%3C/div
%3E')%0A
|
87cddaa906ff405459c7950f28317e2850c231ed
|
Add some logs
|
lib/net/rpc-channel.js
|
lib/net/rpc-channel.js
|
// telegram-mt-node
// Copyright 2014 Enrico Stara '[email protected]'
// Released under the MIT License
// https://github.com/enricostara/telegram-mt-node
// RpcChannel class
//
// This class provides a remote procedure call channel to `Telegram` through the given TCP|HTTP connection.
// This channel in not encrypted and therefore use PlainMessage objects to wrap the communication.
// According with the MTProto specification, only few methods can use unencrypted message, see:
// https://core.telegram.org/mtproto/description#unencrypted-messages
// Import dependencies
require('requirish')._(module);
var message = require('lib/message');
var TypeBuilder = require('telegram-tl-node').TypeBuilder;
var logger = require('get-log')('net.RpcChannel');
// The constructor require a [Http|Tcp]Connection, the connection must be already open.
function RpcChannel(connection) {
if (!connection || !connection.isConnected()) {
var msg = 'The connection is mandatory and it must be already open!';
logger.error(msg);
throw new TypeError(msg);
}
this._connection = connection;
this._open = true;
}
// Execute remotely the given method (Type function) using the channel, call back with the response
RpcChannel.prototype.callMethod = function(method, callback) {
if (!this._open) {
callback(new Error('Channel is closed'));
return;
}
var reqMsg = new message.PlainMessage({message: method.serialize()});
this._call(reqMsg, method.typeName, callback);
};
// Execute the call (protected).
RpcChannel.prototype._call = function(reqMsg, context, callback) {
var conn = this._connection;
var start = new Date().getTime();
var self = this;
conn.write(reqMsg.serialize(), function(ex) {
if (ex) {
logger.error('Unable to write: %s ', ex);
if (callback) {
callback(ex);
}
return;
}
conn.read(function(ex2, response) {
if (ex2) {
logger.error('Unable to read: %s ', ex2);
if (callback) {
callback(ex2);
}
return;
}
try {
var resMsg = self._deserializeResponse(response, context);
var Type = TypeBuilder.requireTypeFromBuffer(resMsg);
var resObj = new Type({buffer: resMsg});
resObj.deserialize();
var duration = new Date().getTime() - start;
if (logger.isDebugEnabled()) {
logger.debug('%s executed in %sms', context.methodName, duration);
}
if (callback) {
callback(null, resObj, duration);
}
} catch (ex3) {
logger.error('Unable to deserialize response from %s due to %s ', context.methodName, ex3);
if (callback) {
callback(ex3);
}
}
});
});
};
RpcChannel.prototype._deserializeResponse = function (response) {
return new message.PlainMessage({buffer: response}).deserialize().body;
};
// Check if the channel is open.
RpcChannel.prototype.isOpen = function() {
return this._open;
};
// Close the channel
RpcChannel.prototype.close = function() {
this._open = false;
};
// Export the class
module.exports = exports = RpcChannel;
|
JavaScript
| 0.000002 |
@@ -2225,16 +2225,158 @@
try %7B%0A
+ if (logger.isDebugEnabled()) %7B%0A logger.debug('response: %25s ', response.toString('hex'));%0A %7D%0A
@@ -3013,16 +3013,19 @@
esponse
+%25s
from %25s
@@ -3036,16 +3036,42 @@
to %25s ',
+ response.toString('hex'),
context
|
c8472be787dd991e827ee888bd5d7453698fb663
|
Update authentication endpoint for subdirectory
|
initializers/authentication.js
|
initializers/authentication.js
|
var AuthenticationInitializer = {
name: 'authentication',
before: 'simple-auth',
after: 'registerTrailingLocationHistory',
initialize: function (container) {
window.ENV = window.ENV || {};
window.ENV['simple-auth'] = {
authenticationRoute: 'signin',
routeAfterAuthentication: 'content',
authorizer: 'simple-auth-authorizer:oauth2-bearer'
};
SimpleAuth.Session.reopen({
user: function () {
return container.lookup('store:main').find('user', 'me');
}.property()
});
SimpleAuth.Authenticators.OAuth2.reopen({
serverTokenEndpoint: '/ghost/api/v0.1/authentication/token',
refreshAccessTokens: true,
makeRequest: function (url, data) {
data.client_id = 'ghost-admin';
return this._super(url, data);
}
});
}
};
export default AuthenticationInitializer;
|
JavaScript
| 0 |
@@ -1,8 +1,86 @@
+import ghostPaths from 'ghost/utils/ghost-paths';%0A%0Avar Ghost = ghostPaths();%0A%0A
var Auth
@@ -756,24 +756,25 @@
nt:
-'/g
+G
host
-/api/v0.1
+.apiRoot + '
/aut
|
026d3a611b19140fcc61a8b127ebbc120740c9e1
|
fix double semicolon
|
lib/replace-prelude.js
|
lib/replace-prelude.js
|
'use strict';
var bpack = require('browser-pack');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var preludePath = path.join(__dirname, 'prelude.js');
var prelude = fs.readFileSync(preludePath, 'utf8');
// This plugin replaces the prelude and adds a transform
var plugin = exports.plugin = function (bfy, opts) {
function replacePrelude() {
var packOpts = {
raw : true, // Added in regular Browserifiy as well
preludePath : preludePath,
prelude : prelude
};
// browserify sets "hasExports" directly on bfy._bpack
bfy._bpack = bpack(xtend(bfy._options, packOpts));;
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
}
bfy.transform(require('./transform'));
bfy.on('reset', replacePrelude);
replacePrelude();
};
// Maintain support for the old interface
exports.browserify = function (files) {
console.error('You are setting up proxyquireify via the old API which will be deprecated in future versions.');
console.error('It is recommended to use it as a browserify-plugin instead - see the example in the README.');
return require('browserify')(files).plugin(plugin);
};
|
JavaScript
| 0.00032 |
@@ -644,17 +644,16 @@
kOpts));
-;
%0A //
|
ddff23792d8318024d4fb6ac2981bebc02ee0365
|
use Object.fromEntries and Object.hasOwn instead of reduce
|
lib/rules/no-danger.js
|
lib/rules/no-danger.js
|
/**
* @fileoverview Prevent usage of dangerous JSX props
* @author Scott Andrews
*/
'use strict';
const docsUrl = require('../util/docsUrl');
const jsxUtil = require('../util/jsx');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const DANGEROUS_PROPERTY_NAMES = [
'dangerouslySetInnerHTML'
];
const DANGEROUS_PROPERTIES = DANGEROUS_PROPERTY_NAMES.reduce((props, prop) => {
props[prop] = prop;
return props;
}, Object.create(null));
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Checks if a JSX attribute is dangerous.
* @param {String} name - Name of the attribute to check.
* @returns {boolean} Whether or not the attribute is dnagerous.
*/
function isDangerous(name) {
return name in DANGEROUS_PROPERTIES;
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
dangerousProp: 'Dangerous property \'{{name}}\' found'
};
module.exports = {
meta: {
docs: {
description: 'Prevent usage of dangerous JSX props',
category: 'Best Practices',
recommended: false,
url: docsUrl('no-danger')
},
messages,
schema: []
},
create(context) {
return {
JSXAttribute(node) {
if (jsxUtil.isDOMComponent(node.parent) && isDangerous(node.name.name)) {
report(context, messages.dangerousProp, 'dangerousProp', {
node,
data: {
name: node.name.name
}
});
}
}
};
}
};
|
JavaScript
| 0.000001 |
@@ -96,16 +96,128 @@
rict';%0A%0A
+const has = require('object.hasown/polyfill')();%0Aconst fromEntries = require('object.fromentries/polyfill')();%0A%0A
const do
@@ -248,24 +248,24 @@
/docsUrl');%0A
-
const jsxUti
@@ -609,16 +609,28 @@
RTIES =
+fromEntries(
DANGEROU
@@ -650,93 +650,34 @@
MES.
-reduce((props, prop) =%3E %7B%0A props
+map((prop) =%3E
%5Bprop
-%5D =
+,
prop
-;%0A return props;%0A%7D, Object.create(null
+%5D
));%0A
@@ -1069,16 +1069,12 @@
urn
-name in
+has(
DANG
@@ -1089,16 +1089,23 @@
OPERTIES
+, name)
;%0A%7D%0A%0A//
|
8a71e8abec8b7da38bc0a0594b42bd57370734fa
|
change default tablename
|
lib/stores/SqlStore.js
|
lib/stores/SqlStore.js
|
var _ = require('lodash');
var extend = require('extend');
var uuid = require('node-uuid');
var util = require('util');
var PostgresAdapter = require('./PostgresAdapter');
var SqliteAdapter = require('./SqliteAdapter');
function SqlStore(opts) {
opts = opts || {};
opts.tableName = opts.tableName || 'table_' + uuid.v4().replace(/-/g, '');
extend(this, opts);
var dialect = opts.dialect || 'sqlite';
if (dialect === 'sqlite') this.adapter = new SqliteAdapter(opts);
else if (dialect === 'postgres') this.adapter = new PostgresAdapter(opts);
else throw new Error("Unhandled dialect: " + dialect);
this.dialect = dialect;
}
// http://stackoverflow.com/questions/11532550/atomic-update-select-in-postgres
var takeNextN = function (first) {
return function (n, cb) {
var sql = function (tableName, fields, n) {
return util.format("SELECT %s FROM %s WHERE lock = '' ORDER BY priority DESC, added " + (first ? "ASC" : "DESC") + " LIMIT %s", fields, tableName, n);
};
var lockId = uuid.v4();
this.adapter.run(util.format("UPDATE %s SET lock = '%s' WHERE lock = '' AND id IN (" + sql(this.tableName, 'id', n) + ")", this.tableName, lockId), function (err, result) {
if (err) return cb(err);
if (!this.changes && !_.get(result, 'rowCount')) return cb(null, '');
cb(null, lockId);
});
};
};
SqlStore.prototype.connect = function (cb) {
var self = this;
self.adapter.connect(function (err) {
if (err) return cb(err);
var sql = util.format("CREATE TABLE IF NOT EXISTS %s (id TEXT UNIQUE, lock TEXT, task TEXT, priority NUMERIC", self.tableName);
var dialect = self.dialect;
if (dialect === 'sqlite') {
sql += ", added INTEGER PRIMARY KEY AUTOINCREMENT)";
} else if (dialect === 'postgres') {
sql += ", added SERIAL PRIMARY KEY)";
} else {
throw new Error("Unhandled dialect: " + dialect);
}
self.adapter.run(sql, function (err) {
if (err) return cb(err);
self.adapter.get(util.format("SELECT count(*) as n FROM %s WHERE lock = ''", self.tableName), function (err, row) {
if (err) return cb(err);
cb(null, row ? row.n : 0);
});
});
});
};
SqlStore.prototype.getTask = function (taskId, cb) {
this.adapter.get(util.format("SELECT task FROM %s WHERE id = '%s' AND lock = ''", this.tableName, taskId), function (err, row) {
if (err) return cb(err);
if (!row) return cb(null);
try {
var savedTask = JSON.parse(row.task);
} catch (e) {
return cb('failed_to_deserialize_task');
}
cb(null, savedTask);
});
};
SqlStore.prototype.deleteTask = function (taskId, cb) {
this.adapter.run(util.format("DELETE FROM %s WHERE id = '%s'", this.tableName, taskId || ''), cb);
};
SqlStore.prototype.putTask = function (taskId, task, priority, cb) {
try {
var serializedTask = JSON.stringify(task);
} catch (e) {
return cb('failed_to_serialize_task');
}
this.adapter.upsert({ id: taskId, task: serializedTask, priority: priority || 1, lock: '' }, cb);
};
SqlStore.prototype.takeFirstN = takeNextN(true);
SqlStore.prototype.takeLastN = takeNextN(false);
SqlStore.prototype.getLock = function (lockId, cb) {
this.adapter.all(util.format("SELECT id, task FROM %s WHERE lock = '%s'", this.tableName, lockId || ''), function (err, rows) {
if (err) return cb(err);
var tasks = {};
rows.forEach(function (row) {
tasks[row.id] = JSON.parse(row.task);
})
cb(null, tasks);
});
};
SqlStore.prototype.getRunningTasks = function (cb) {
this.adapter.all("SELECT id, task, lock FROM " + this.tableName, function (err, rows) {
if (err) return cb(err);
var tasks = {};
rows.forEach(function (row) {
tasks[row.lock] = tasks[row.lock] || [];
tasks[row.lock][row.id] = JSON.parse(row.task);
})
cb(null, tasks);
});
};
SqlStore.prototype.releaseLock = function (lockId, cb) {
this.adapter.run(util.format("DELETE FROM %s WHERE lock = '%s'", this.tableName, lockId || ''), cb);
};
SqlStore.prototype.close = function (cb) {
if (this.adapter) return this.adapter.close(cb);
cb();
};
module.exports = SqlStore;
|
JavaScript
| 0.000002 |
@@ -313,19 +313,19 @@
e %7C%7C 'ta
-ble
+sks
_' + uui
|
113aad6db5d2b8d677f638dceb60e8a3f58059f0
|
remove unnecessary variable
|
pkg/interface/config/webpack.prod.js
|
pkg/interface/config/webpack.prod.js
|
const path = require('path');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const webpack = require('webpack');
module.exports = (env) => return {
mode: 'production',
entry: {
app: './src/index.js'
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/typescript', '@babel/preset-react'],
plugins: [
'lodash',
'@babel/transform-runtime',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-class-properties'
]
}
},
exclude: /node_modules/
},
{
test: /\.css$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
},
devtool: 'source-map',
// devServer: {
// contentBase: path.join(__dirname, './'),
// hot: true,
// port: 9000,
// historyApiFallback: true
// },
plugins: [
new MomentLocalesPlugin(),
new CleanWebpackPlugin(),
new webpack.DefinePlugin({
'process.env.LANDSCAPE_STREAM': JSON.stringify(process.env.LANDSCAPE_STREAM),
'process.env.LANDSCAPE_SHORTHASH': JSON.stringify(process.env.LANDSCAPE_SHORTHASH)
})
// new HtmlWebpackPlugin({
// title: 'Hot Module Replacement',
// template: './public/index.html',
// }),
],
output: {
filename: 'index.[contenthash].js',
path: path.resolve(__dirname, '../../arvo/app/landscape/js/bundle'),
publicPath: '/',
},
optimization: {
minimize: true,
usedExports: true
}
};
|
JavaScript
| 0.000006 |
@@ -275,24 +275,8 @@
ts =
- (env) =%3E return
%7B%0A
@@ -1963,17 +1963,16 @@
ath: '/'
-,
%0A %7D,%0A
|
9075a60a4b1f56e0bf21b17cfe3beb9733567ada
|
Fix small typo
|
src/jquery.selector.specifity.js
|
src/jquery.selector.specifity.js
|
(function($) {
$.selector.SimpleSelector.addMethod('specifity', function() {
if (this.spec) return this.spec;
var spec = [
this.id ? 1 : 0,
this.classes.length + this.attrs.length + this.pseudo_classes.length,
((this.tag && this.tag != '*') ? 1 : 0) + this.pseudo_els.length
];
$.each(this.nots, function(i,not){
var ns = not.specifity(); spec[0] += ns[0]; spec[1] += ns[1]; sspec[2] += ns[2];
});
return this.spec = spec;
})
$.selector.Selector.addMethod('specifity', function(){
if (this.spec) return this.spec;
var spec = [0,0,0];
$.each(this.parts, function(i,part){
if (i%2) return;
var ps = part.specifity(); spec[0] += ps[0]; spec[1] += ps[1]; spec[2] += ps[2];
});
return this.spec = spec;
})
$.selector.SelectorsGroup.addMethod('specifity', function(){
if (this.spec) return this.spec;
var spec = [0,0,0];
$.each(this.parts, function(i,part){
var ps = part.specifity(); spec[0] += ps[0]; spec[1] += ps[1]; spec[2] += ps[2];
});
return this.spec = spec;
})
})(jQuery);
|
JavaScript
| 0.00001 |
@@ -395,17 +395,16 @@
ns%5B1%5D;
-s
spec%5B2%5D
|
0af74ceb15874f0aa2eb26ded68b6dfdd5309b31
|
Add loggin when forceJSONContent function is called
|
src/main/web/florence/js/functions/_forceContent.js
|
src/main/web/florence/js/functions/_forceContent.js
|
function forceContent(collectionId) {
// check user is logged in. userType wont be set unless logged in
if (!localStorage.userType) {
return;
}
// open the modal
var modal = templates.forceContentModal;
$('.wrapper').append(modal);
// on save
$('#force-content-json-form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var json = this[0].value;
if (!json) {
sweetAlert("Please insert JSON");
return;
}
// is it possible to parse the JSON to get the uri
if (!tryParseJSON(json)) {
return;
}
var content = JSON.parse(json);
var uri = content.uri;
// if no uri throw an alert
if (!uri) {
sweetAlert("It doesn't look like the JSON input contains a uri. Please check");
return;
}
var safePath = checkPathSlashes(uri);
$.ajax({
url: "/zebedee/content/" + collectionId + "?uri=" + safePath + "/data.json",
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: json,
success: function () {
sweetAlert("Content created", "", "success");
$('.overlay').remove();
viewCollections(collectionId);
console.log('-----------------------------');
console.log('CONTENT CREATED \nuri: ', safePath + '\n', JSON.parse(json));
console.log('-----------------------------');
},
error: function(e) {
sweetAlert(e.responseJSON.message);
}
});
});
// cancel button
$('.btn-modal-cancel').off().click(function () {
$('.overlay').remove();
});
}
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) {
sweetAlert("That doesn't look like valid JSON. Please check");
}
return false;
};
function forceJSONContent(code, collectionId) {
var d = new Date(),
e = new Date();
var minsSinceMidnight = parseInt(((e - d.setHours(0,0,0,0)) / 1000) / 60);
if (!code || !collectionId) {
console.error('Missing arguments! You should pass two arguments - code, collectionID');
return;
}
if (code != minsSinceMidnight) {
console.error('Code error');
return;
}
forceContent(collectionId)
}
|
JavaScript
| 0.000029 |
@@ -256,24 +256,54 @@
nd(modal);%0A%0A
+ logForceContentAction();%0A%0A
// on sa
@@ -2923,8 +2923,417 @@
onId)%0A%7D%0A
+%0Afunction logForceContentAction() %7B%0A%0A var logData = %7B%0A user: this.user = localStorage.getItem('loggedInAs'),%0A trigger: %7B%0A elementClasses: %5B%22Force JSON Content function invoked%22%5D%0A %7D%0A %7D;%0A%0A $.ajax(%7B%0A url: %22/zebedee/clickEventLog%22,%0A type: 'POST',%0A contentType: %22application/json%22,%0A data: JSON.stringify(logData),%0A async: true,%0A %7D);%0A%7D%0A
|
f996375283befd27138c01f3d5ff5fce23344d3f
|
Add some doc comments [ci skip]
|
test/bakery.test.js
|
test/bakery.test.js
|
var test = require('tap').test;
var fs = require('fs');
var streampng = require('streampng');
var pathutil = require('path');
var urlutil = require('url');
var oneshot = require('oneshot');
var bakery = require('../lib/bakery');
var IMG_PATH = pathutil.join(__dirname, 'testimage.png');
var ASSERTION_URL = "http://example.org";
function getImageStream() {
var imgStream = fs.createReadStream(IMG_PATH);
return imgStream;
}
function getImageBuffer() {
var imgBuffer = fs.readFileSync(IMG_PATH);
return imgBuffer;
}
function preheat(callback) {
var imgStream = getImageStream();
var options = {image: imgStream, url: ASSERTION_URL};
bakery.bake(options, callback);
}
function broil(opts, callback) {
oneshot(opts, function (server, urlobj) {
var url = urlutil.format(urlobj);
var bakeOpts = { image: getImageStream(), url: url };
bakery.bake(bakeOpts, function (err, baked) {
if (err) throw err;
callback(baked);
});
});
}
test('bakery.createChunk', function (t) {
var chunk = bakery.createChunk(ASSERTION_URL);
t.same(chunk.keyword, bakery.KEYWORD, 'uses the right keyword');
t.same(chunk.text, ASSERTION_URL, 'assigns the text properly');
t.ok(chunk instanceof streampng.Chunk.tEXt, 'makes a tEXt chunk');
t.end();
});
test('bakery.bake: takes a buffer', function (t) {
var imgBuffer = getImageBuffer();
var options = {
image: imgBuffer,
url: ASSERTION_URL,
};
bakery.bake(options, function (err, baked) {
t.notOk(err, 'should not have an error');
t.ok(baked, 'should get back some data');
bakery.getBakedData(baked, function (err, url) {
t.notOk(err, 'there should be a matching tEXt chunk');
t.same(url, ASSERTION_URL, 'should be able to find the url');
t.end();
});
})
});
test('bakery.bake: takes a stream', function (t) {
var imgStream = getImageStream();
var options = {
image: imgStream,
url: ASSERTION_URL,
};
bakery.bake(options, function (err, baked) {
t.notOk(err, 'should not have an error');
t.ok(baked, 'should get back some data');
bakery.getBakedData(baked, function (err, url) {
t.notOk(err, 'there should be a matching tEXt chunk');
t.same(url, ASSERTION_URL, 'should be able to find the url');
t.end();
});
})
});
test('bakery.bake: do not bake something twice', function (t) {
preheat(function (_, img) {
bakery.bake({image: img, url: 'wut'}, function (err, baked) {
t.ok(err, 'should be an error');
t.notOk(baked, 'should not get an image back');
t.same(err.code, 'IMAGE_ALREADY_BAKED', 'should get correct error code');
t.same(err.contents, ASSERTION_URL, 'should get the contents of the chunk');
t.end();
})
});
});
test('bakery.debake: should work', function (t) {
var expect = {band: 'grapeful dread'};
var opts = {
body: JSON.stringify(expect),
type: 'application/json'
};
broil(opts, function (baked) {
bakery.debake(baked, function (err, contents) {
t.notOk(err, 'should not have an error');
t.same(contents, expect);
t.end();
});
});
});
test('bakery.debake: should get a parse error', function (t) {
var opts = {
body: "{no json here}",
type: 'application/json'
};
broil(opts, function (baked) {
bakery.debake(baked, function (err, contents) {
t.ok(err, 'should have an error');
t.same(err.code, 'JSON_PARSE_ERROR', 'should be a json parse error');
t.end();
});
});
});
test('bakery.debake: 404 should return error', function (t) {
var opts = { body: 'x', statusCode: 404 };
broil(opts, function (baked) {
bakery.debake(baked, function (err, contents) {
t.ok(err, 'should have an error');
t.same(err.code, 'RESOURCE_NOT_FOUND', 'should have a resource not found error');
t.same(err.httpStatusCode, 404, 'should have a 404');
t.end();
});
});
});
test('bakery.debake: 500 should return generic error', function (t) {
var opts = { body: 'x', statusCode: 500 };
broil(opts, function (baked) {
bakery.debake(baked, function (err, contents) {
t.ok(err, 'should have an error');
t.same(err.code, 'RESOURCE_ERROR', 'should have a generic resource error');
t.same(err.httpStatusCode, 500, 'should have a 500');
t.end();
});
});
});
|
JavaScript
| 0 |
@@ -325,16 +325,71 @@
.org%22;%0A%0A
+/**%0A * Get an image stream for the default image.%0A */%0A%0A
function
@@ -476,24 +476,79 @@
gStream;%0A%7D%0A%0A
+/**%0A * Get the image buffer for the default image%0A */%0A%0A
function get
@@ -627,24 +627,80 @@
gBuffer;%0A%7D%0A%0A
+/**%0A * quickly bake an image with the standard url%0A */%0A%0A
function pre
@@ -842,19 +842,98 @@
lback);%0A
-
%7D%0A%0A
+/**%0A * start a server with some options, then bake an image with that url%0A */%0A%0A
function
@@ -4452,24 +4452,16 @@
have a
-generic
resource
|
824199f13557f3c193db2c7d1bb2456db0aaa7da
|
Add relative-time constructor tests.
|
test/constructor.js
|
test/constructor.js
|
module('constructor');
test('create from document.createElement', function() {
var time = document.createElement('time', 'local-time');
equal('TIME', time.nodeName);
equal('local-time', time.getAttribute('is'))
});
test('create from constructor', function() {
var time = new window.LocalTimeElement();
equal('TIME', time.nodeName);
equal('local-time', time.getAttribute('is'));
});
test('ignores elements without a datetime attr', function() {
var time = document.createElement('local-time');
equal(time.textContent, '');
});
test('leaves contents alone if only datetime is set', function() {
var time = document.createElement('local-time');
time.setAttribute('datetime', '1970-01-01T00:00:00.000Z');
equal(time.textContent, '');
});
|
JavaScript
| 0 |
@@ -26,24 +26,35 @@
est('create
+local-time
from documen
@@ -76,32 +76,32 @@
', function() %7B%0A
-
var time = doc
@@ -240,16 +240,27 @@
'create
+local-time
from con
@@ -351,32 +351,32 @@
time.nodeName);%0A
-
equal('local-t
@@ -408,24 +408,437 @@
is'));%0A%7D);%0A%0A
+test('create relative-time from document.createElement', function() %7B%0A var time = document.createElement('time', 'relative-time');%0A equal('TIME', time.nodeName);%0A equal('relative-time', time.getAttribute('is'))%0A%7D);%0A%0Atest('create relative-time from constructor', function() %7B%0A var time = new window.RelativeTimeElement();%0A equal('TIME', time.nodeName);%0A equal('relative-time', time.getAttribute('is'));%0A%7D);%0A%0A
test('ignore
|
928fe8e582ef2c1f73acbaeb3510ab78172ff9c5
|
Update DataChannel
|
test/dataChannel.js
|
test/dataChannel.js
|
var WEBRTC = require('../');
function P2P(alice, bob) {
alice.onicecandidate = function(event) {
var candidate = event.candidate || event;
bob.addIceCandidate(candidate);
};
bob.onicecandidate = function(event) {
var candidate = event.candidate || event;
alice.addIceCandidate(candidate);
};
alice.onnegotiationneeded = function() {
alice.createOffer(function(sdp) {
alice.setLocalDescription(sdp, function() {
bob.setRemoteDescription(sdp, function() {
bob.createAnswer(function(sdp) {
bob.setLocalDescription(sdp, function() {
alice.setRemoteDescription(sdp, function() {
console.log("Alice -> Bob: Connected!");
});
});
});
});
});
});
};
bob.onnegotiationneeded = function() {
bob.createOffer(function(sdp) {
bob.setLocalDescription(sdp, function() {
alice.setRemoteDescription(sdp, function() {
alice.createAnswer(function(sdp) {
alice.setLocalDescription(sdp, function() {
bob.setRemoteDescription(sdp, function() {
console.log("Bob -> Alice: Connected!");
});
});
});
});
});
});
};
alice.onaddstream = function(stream) {
if (stream) {
console.log('Alice got mediaStream');
}
};
bob.onaddstream = function(stream) {
if (stream) {
console.log('Bob got mediaStream');
}
};
alice.ondatachannel = function(event, callback) {
var channel = event ? event.channel || event : null;
if (!channel) {
return false;
}
console.log('Alice: Got DataChannel!');
channel.onopen = function() {
console.log('Alice: DataChannel Open!');
if (callback) {
callback(channel);
}
};
channel.onmessage = function(event) {
var data = event.data;
console.log('Alice:', data);
};
channel.onclose = function() {
console.log('Alice: DataChannel Closed!');
};
};
bob.ondatachannel = function(event, callback) {
var channel = event ? event.channel || event : null;
if (!channel) {
return false;
}
console.log('Bob: Got DataChannel!');
channel.onopen = function() {
console.log('Bob: DataChannel Open!');
if (callback) {
callback(channel);
}
};
channel.onmessage = function(event) {
var data = event.data;
console.log('Bob:', data);
channel.send('Hello Alice!');
};
channel.onclose = function() {
console.log('Bob: DataChannel Closed!');
};
};
}
var config = {
iceServers: [
{
url: 'stun:stun.l.google.com:19302',
},
],
};
function sctpTest() {
console.log('Running SCTP DataChannel Test');
var sctpDataChannelConfig = {
reliable: true,
ordered: true,
};
var sctpDataChannelConstraints = {
audio: false,
video: false,
optional: [
{
RtpDataChannels: false,
DtlsSrtpKeyAgreement: true,
},
],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false,
},
};
var alice = new WEBRTC.RTCPeerConnection(config, sctpDataChannelConstraints);
var bob = new WEBRTC.RTCPeerConnection(config, sctpDataChannelConstraints);
P2P(alice, bob);
alice.ondatachannel(alice.createDataChannel('TestChannel', sctpDataChannelConfig), function(channel) {
channel.send('Hello Bob!');
setTimeout(function () {
channel.close();
}, 1000);
setTimeout(function() {
alice.close();
bob.close();
}, 5000);
});
}
function rtpTest() {
console.log('Running RTP DataChannel Test');
var rtpDataChannelConfig = {
reliable: false,
ordered: false,
};
var rtpDataChannelConstraints = {
audio: false,
video: false,
optional: [
{
RtpDataChannels: true,
DtlsSrtpKeyAgreement: false,
},
],
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false,
},
};
var alice = new WEBRTC.RTCPeerConnection(config, rtpDataChannelConstraints);
var bob = new WEBRTC.RTCPeerConnection(config, rtpDataChannelConstraints);
P2P(alice, bob);
alice.ondatachannel(alice.createDataChannel('TestChannel', rtpDataChannelConfig), function(channel) {
channel.send('Hello Bob!');
setTimeout(function () {
channel.close();
}, 1000);
setTimeout(function() {
alice.close();
bob.close();
setTimeout(function() {
sctpTest();
}, 1000);
}, 5000);
});
}
rtpTest();
|
JavaScript
| 0 |
@@ -1,15 +1,15 @@
var W
-EB
+eb
RTC = re
@@ -23,16 +23,42 @@
../');%0A%0A
+//WebRTC.setDebug(true);%0A%0A
function
@@ -3293,34 +3293,34 @@
ar alice = new W
-EB
+eb
RTC.RTCPeerConne
@@ -3371,34 +3371,34 @@
var bob = new W
-EB
+eb
RTC.RTCPeerConne
@@ -4197,34 +4197,34 @@
ar alice = new W
-EB
+eb
RTC.RTCPeerConne
@@ -4286,10 +4286,10 @@
ew W
-EB
+eb
RTC.
|
adcaf8a1ac12847b3907938f412ad7c71c792721
|
Add tests for splitBasePath
|
test/fileHandler.js
|
test/fileHandler.js
|
var assert = require('assert')
var fileHandler = require('../lib/fileHandler.js')
var fs = require('fs')
describe('fileHandler', function () {
var testFile = './test.txt'
var testString = 'asdf'
describe('read', function () {
var fileStream = fs.openSync(testFile, 'w')
fs.writeSync(fileStream, testString)
fs.closeSync(fileStream)
it('should return the contents of a file as a string', function () {
assert.equal(testString, fileHandler.read(testFile))
})
it('should return false if the file doesn\'t exsist', function () {
assert.equal(false, fileHandler.read('./gabeldigu'))
})
after(function () {
fs.unlink(testFile)
})
})
describe('write', function () {
before(function () {
fileHandler.write(testFile, testString)
})
it('Should create the file if it doesn\'t exsist', function () {
assert.equal(true, fs.existsSync(testFile))
})
it('Should write the first argument to the file', function () {
assert.equal(testString, fs.readFileSync(testFile, {encoding: 'utf8'}))
})
after(function () {
fs.unlink(testFile)
})
})
describe('cssFilePath', function () {
it('should replace the file extesion with css', function () {
assert.equal('someFile.css', fileHandler.cssFilePath('someFile.jcss'))
})
it('should add an extension if there isn\'t one', function () {
assert.equal('asdf/somefile.css', fileHandler.cssFilePath('asdf/somefile'))
})
it('should be able to handle dots in filenames', function () {
assert.equal('foo.bar.css', fileHandler.cssFilePath('foo.bar.jcss'))
})
})
})
|
JavaScript
| 0 |
@@ -1631,20 +1631,640 @@
s'))%0A %7D)%0A
+ %7D),%0A%0A describe('splitBasePath', function () %7B%0A it('should return and array with the start and the last file or directory name in a filepath', function () %7B%0A var testSplit = fileHandler.splitBasePath('/foo/bar/yolo/troll')%0A assert.ok(typeof testSplit == Object)%0A assert.equal('/foo/bar/yolo/', testSplit%5B0%5D)%0A assert.equal('troll', testSplit%5B1%5D)%0A %7D)%0A it('should return an empty string and the passed value if it has no slashes', function () %7B%0A var testSplit = fileHandler.splitBasePath('yolo.42')%0A assert.equal('', testSplit%5B0%5D)%0A assert.equal('yolo.42', testSplit%5B1%5D)%0A %7D)%0A
%7D)%0A%7D)%0A
|
d902d21c62361da38fa05b6f5d3b4ba34cf23ed2
|
add use strict
|
test/future_test.js
|
test/future_test.js
|
var Future = require('../src/future').Future;
var a = require('assert');
describe('futurejs', function () {
describe('then/resolve functions', function () {
it('should call the then callback after resolve was called', function (done) {
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
// verify
f.then(function (v1, v2) {
var err = null;
try {
a.equal(v1, value1);
a.equal(v2, value2);
} catch (e) {
err = e;
} finally {
done(err);
}
});
// execute
setImmediate(function () {
f.resolve(value1, value2);
});
});
it('should call the then callback even if it is defined after resolve was called', function () {
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
// execute
f.resolve(value1, value2);
// verify
f.then(function (v1, v2) {
a.equal(v1, value1);
a.equal(v2, value2);
});
});
it('should throw an Error if resolve gets called twice', function(){
// create object under test
var f = new Future();
// execute
f.resolve();
var fn = function(){
f.resolve();
};
// verify
a.throws(fn);
});
it('should cleanup the resolver callback after resolve was called', function(){
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
f.then(function(){});
// verify
a.notEqual(typeof f.resolver, 'undefined');
// execute
f.resolve(value1, value2);
// verify
a.equal(typeof f.resolver, 'undefined');
});
it('should cleanup the args after the then callback was called', function(){
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
f.resolve(value1, value2);
// verify
a.notEqual(typeof f.args, 'undefined');
// execute
f.then(function(){});
// verify
a.equal(typeof f.args, 'undefined');
});
});
describe('error/reject functions', function () {
it('should call the error callback after reject was called', function (done) {
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
// verify
f.error(function (v1, v2) {
var err = null;
try {
a.equal(v1, value1);
a.equal(v2, value2);
} catch (e) {
err = e;
} finally {
done(err);
}
});
// execute
setImmediate(function () {
f.reject(value1, value2);
});
});
it('should call the error callback even if it is defined after reject was called', function () {
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
// execute
f.reject(value1, value2);
// verify
f.error(function (v1, v2) {
a.equal(v1, value1);
a.equal(v2, value2);
});
});
it('should throw an Error if reject gets called twice', function(){
// create object under test
var f = new Future();
// execute
f.reject();
var fn = function(){
f.reject();
};
// verify
a.throws(fn);
});
it('should cleanup the rejector callback after reject was called', function(){
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
f.error(function(){});
// verify
a.notEqual(typeof f.rejector, 'undefined');
// execute
f.reject(value1, value2);
// verify
a.equal(typeof f.rejector, 'undefined');
});
it('should cleanup the args after the error callback was called', function(){
// prepare env
var value1 = 1;
var value2 = 2;
// create object under test
var f = new Future();
f.reject(value1, value2);
// verify
a.notEqual(typeof f.args, 'undefined');
// execute
f.error(function(){});
// verify
a.equal(typeof f.args, 'undefined');
});
});
describe('reject/resolve', function(){
it('should throw an Error if both reject and resolve get called', function(){
// create object under test
var f1 = new Future();
var f2 = new Future();
// execute
f1.reject();
var fn1 = function(){
f1.resolve();
};
f2.resolve();
var fn2 = function(){
f2.reject();
};
// verify
a.throws(fn1);
a.throws(fn2);
});
});
});
|
JavaScript
| 0.00002 |
@@ -1,12 +1,27 @@
+'use strict';%0A%0A
var Future =
@@ -4372,8 +4372,9 @@
%09%7D);%0A%7D);
+%0A
|
7bf070d225e7523619ffca4322567ec425cb2418
|
test fix
|
test/helper-test.js
|
test/helper-test.js
|
'use strict';
const chai = require('chai');
const expect = chai.expect;
const path = require('path');
const logger = require('hw-logger');
//const log = logger.log;
const helper = require('../lib/helper');
describe('helper', () => {
before(() => {
logger.setLevel('trace');
});
it('should convert to id', () => {
const id = helper.toId('Any title with (special characters) $ * "and accéèentsçàôù" :');
expect(id).to.equal('any-title-with-special-characters-and-acceeentscaou');
});
it('should find repo', () => {
const name = 'repo1';
const repos = [{name, value: 'value1'}, {name: 'repo2', value: 'value2'}];
const repo = helper.findRepo(name, repos);
expect(repo).to.eql(repos[0]);
});
it('should find repo', () => {
const repoName = helper.getRepoName('reponame/subdir/subsubdir/file');
expect(repoName).to.equal('reponame');
});
it('should build breadcrumb', () => {
const repoName = helper.buildBreadcrumb({path: 'reponame/subdir/subsubdir/file'});
expect(repoName).to.eql(['subdir', 'subsubdir', 'file']);
});
it('should execute command', () => {
const text = 'Hello!';
return helper.executeCmd(`echo "${text}"`)
.then(result => {
expect(result).to.have.property('stdout', `${text}\n`);
})
.then(() => helper.executeCmd(`>&2 echo "${text}"`))
.then(result => {
expect(result).to.have.property('stderr', `${text}\n`);
});
});
it('should scan files', () => {
const config = require('../lib/default-config');
const mdExtPattern = config['markdownExt'].join('|');
const include = new RegExp(`\.(${mdExtPattern})$`);
return helper
.scanMdFiles({
baseDir: path.join(__dirname, 'src'),
excludeDir: config['excludeDir'], include
})
.then(result => {
const expectedResult = ['doc1/readme.md',
'markdown-samples/sample-1.md',
'markdown-samples/sample-10.md',
'markdown-samples/sample-11.md',
'markdown-samples/sample-2.md',
'markdown-samples/sample-3.md',
'markdown-samples/sample-4.md',
'markdown-samples/sample-5.md',
'markdown-samples/sample-6.md',
'markdown-samples/sample-7.md',
'markdown-samples/sample-8.md',
'markdown-samples/sample-9.md'
];
expect(result).to.eql(expectedResult);
});
});
});
|
JavaScript
| 0.000001 |
@@ -973,15 +973,8 @@
umb(
-%7Bpath:
'rep
@@ -1001,17 +1001,16 @@
ir/file'
-%7D
);%0A e
@@ -1037,37 +1037,218 @@
ql(%5B
-'subdir', 'subsubdir', 'file'
+%0A %7B%0A title: 'subdir',%0A url: 'subdir'%0A %7D, %7B%0A title: 'subsubdir',%0A url: 'subdir/subsubdir'%0A %7D, %7B%0A title: 'file',%0A url: 'subdir/subsubdir/file'%0A %7D%0A
%5D);%0A
|
fef0a5367c87ec110fca27f5f411df235b824c60
|
Fix export
|
make/configFile.js
|
make/configFile.js
|
"use strict";
/*jshint node: true*/
/*eslint-env node*/
const
fs = require("fs"),
path = require("path"),
defaultContent = {
version: 1,
serve: {
httpPort: 8000
},
host: {
wscript: false,
java: false
},
browsers: {},
metrics: {
coverage: {
statements: 90,
functions: 90,
branches: 90,
lines: 90
},
maintainability: 70
}
},
contentMigrationPath = [
content => {
/*
* from: selenium.browsers: [name]
* to: browsers: { name: { type: "selenium" } }
*/
content.browsers = {};
content.selenium.browsers.forEach(name => {
content.browsers[name] = {
type: "selenium"
};
});
delete content.selenium; // No more needed
}
];
module.export = class ConfigFile {
constructor () {
this.read();
}
getFileName () {
if (!this._fileName) {
this._fileName = path.join(__dirname, "../tmp/config.json");
}
}
read () {
let fileName = this.getFileName();
if (fs.existsSync(fileName)) {
this.content = JSON.parse(fs.readFileSync(fileName).toString());
this.savedJSON = JSON.stringify(this.content); // Ignore formatting
this._checkVersion();
} else {
this.content = defaultContent;
this.savedJSON = "";
}
}
_checkVersion () {
var currentVersion = this.content.version || 0;
if (currentVersion < contentMigrationPath.length) {
contentMigrationPath.slice(currentVersion).forEach(migrate => migrate(this.content));
}
this.content.version = contentMigrationPath.length;
}
isNew () {
return !this.savedJSON;
}
isModified () {
return JSON.stringify(this.content) !== this.savedJSON;
}
save () {
if (this.isModified()) {
let json = JSON.stringify(this.content);
fs.writeFileSync(this.getFileName(), json);
this.savedJSON = json;
}
}
};
|
JavaScript
| 0.000004 |
@@ -1015,16 +1015,17 @@
e.export
+s
= class
|
81092298384de754b51b7a8de1edae3038307dce
|
Fix auth0 x-frame-options
|
src/components/molecules/smart_links/SmartLinks.js
|
src/components/molecules/smart_links/SmartLinks.js
|
'use strict';
import React from 'react';
import Settings from 'components/atoms/settings/Settings';
require('./stylesheets/smart_links.scss');
const CLIENT_ID = require('./API_KEY.js').CLIENT_ID; // File is ignored by git
const CLIENT_DOMAIN = require('./API_KEY.js').CLIENT_DOMAIN; // File is ignored by git
class SmartLinks extends React.Component {
componentWillMount() {
this.lock = new Auth0Lock(CLIENT_ID, CLIENT_DOMAIN);
this.setState({idToken: this.getIdToken()});
}
componentDidMount() {
// In this case, the lock and token are retrieved from the parent component
// If these are available locally, use `this.lock` and `this.idToken`
this.lock.getProfile(this.state.idToken, function(err, profile) {
if (err) {
console.log('Error loading the Profile', err);
return;
}
this.setState({profile: profile});
localStorage.setItem('userProfile', JSON.stringify(profile));
}.bind(this));
}
getIdToken() {
var idToken = localStorage.getItem('userToken');
var authHash = this.lock.parseHash(window.location.hash);
if (!idToken && authHash) {
if (authHash.id_token) {
idToken = authHash.id_token;
localStorage.setItem('userToken', authHash.id_token);
}
if (authHash.error) {
console.log('Error signing in', authHash);
return null;
}
}
return idToken;
}
showLock() {
// We receive lock from the parent component in this case
// If you instantiate it in this component, just do this.lock.show()
this.lock.show();
}
logout() {
localStorage.removeItem('userToken');
this.setState({idToken: null});
}
render() {
if (this.state.idToken) {
return (
<div className='smart-links-component'>
<a href='#'><Settings /></a>
<a href='#'>about</a>
<a href='#'>help</a>
<a href='#' onClick={this.logout.bind(this)}>Logout</a>
</div>
);
} else {
return (
<div className='smart-links-component'>
<a href='#'>about</a>
<a href='#'>help</a>
<a href='#' onClick={this.showLock.bind(this)}>Sign In</a>
</div>
);
}
}
}
SmartLinks.displayName = 'MoleculeSmartLinks';
// Uncomment properties you need
// SmartLinks.propTypes = {};
// SmartLinks.defaultProps = {};
export default SmartLinks;
|
JavaScript
| 0.000131 |
@@ -1569,16 +1569,208 @@
ck.show(
+%7B%7D, function(err, profile) %7B%0A // Popup automatically set to true in this case%0A // auth0 already catch errors%0A localStorage.setItem('userProfile', JSON.stringify(profile));%0A %7D
);%0A %7D%0A
|
77014dc1d8f86df09e940e247ebfe7b9b5ae1d4e
|
fix case
|
playground/home-main.js
|
playground/home-main.js
|
requirejs.config({
// baseUrl: '/',
paths: {
lodash: 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash',
jquery: 'http://code.jquery.com/jquery-1.11.0.min',
firebase: 'https://cdn.firebase.com/js/client/2.0.5/firebase',
react: 'http://fb.me/react-with-addons-0.12.1',
text: 'libs/requirejs-plugins/text',
json: 'libs/requirejs-plugins/json'
//ace: '../ace-builds-1.1.8/src-min/ace',
//'react/addons': 'http://fb.me/react-with-addons-0.12.1'
},
shim: {
lodash: { exports: '_' },
firebase: { exports: 'Firebase' },
//ace: { exports: 'ace' },
jquery: { exports: '$' },
react: { exports: 'React' }
},
map: {
'*': {
'react/addons': 'react'
}
}
});
requirejs(['jquery', 'react', './Examples'], function ($, React, Examples) {
'use strict';
//var Examples = require('./examples.js');
React.render(Examples(), document.getElementById('home-section'));
//window.fiddle = React.render(fiddle(), document.getElementById('container'));
});
|
JavaScript
| 0.000029 |
@@ -841,17 +841,17 @@
ct', './
-E
+e
xamples'
|
58da43393378d0ae3011f4f914e5c2ef548a8485
|
add more globals
|
react-native.js
|
react-native.js
|
module.exports = {
extends: ['./react-base.js'],
plugins: ['react-native'],
globals: {
__DEV__: false,
fetch: false,
navigator: false,
requestAnimationFrame: false,
},
rules: {
'no-console': 0,
// https://github.com/Intellicode/eslint-plugin-react-native
'react-native/no-color-literals': 2,
'react-native/no-inline-styles': 2,
'react-native/no-unused-styles': 2,
'react-native/split-platform-components': 2,
},
};
|
JavaScript
| 0.000001 |
@@ -102,24 +102,88 @@
V__: false,%0A
+ cancelAnimationFrame: false,%0A cancelIdleCallback: false,%0A
fetch: f
@@ -244,16 +244,48 @@
false,%0A
+ requestIdleCallback: false,%0A
%7D,%0A r
|
f9ca6fee6975c0e28ab594cf54e9cbac23543dc2
|
Make CommandLoader#bot private
|
src/lib/command/CommandLoader.js
|
src/lib/command/CommandLoader.js
|
'use babel';
'use strict';
import glob from 'glob';
import path from 'path';
import CommandRegistry from './CommandRegistry';
/**
* Handles loading all commands from the given Bot's commandsDir
* @class CommandLoader
* @param {Bot} bot - Bot instance
*/
export default class CommandLoader
{
constructor(bot)
{
/**
* Bot instance
* @memberof CommandLoader
* @type {Bot}
* @name bot
* @instance
*/
this.bot = bot;
}
/**
* Load or reload all commands from the base commands directory and the
* user-specified {@link Bot#commandsDir} directory and stores them in
* the Bot's {@link CommandRegistry} instance ({@link Bot#commands})
* @memberof CommandLoader
* @instance
*/
loadCommands()
{
if (this.bot.commands.size > 0) this.bot.commands = new CommandRegistry();
let commandFiles = [];
commandFiles.push(...glob.sync(`${path.join(__dirname, './base')}/**/*.js`));
commandFiles.push(...glob.sync(`${this.bot.commandsDir}/**/*.js`));
let loadedCommands = 0;
commandFiles.forEach(fileName =>
{
let commandLocation = fileName.replace('.js', '');
delete require.cache[require.resolve(commandLocation)];
let Command = require(commandLocation).default;
let command = new Command(this.bot);
if (this.bot.disableBase.includes(command.name)) return;
command.classloc = commandLocation;
if (command.overloads)
{
if (!this.bot.commands.has(command.overloads)) // eslint-disable-line curly
throw new Error(`Command "${command.overloads}" does not exist to be overloaded.`);
this.bot.commands.delete(command.overloads);
this.bot.commands.register(command, command.name);
}
else
{
this.bot.commands.register(command, command.name);
}
if (!command.overloads)
{
loadedCommands++;
console.log(`Command '${command.name}' loaded.`); // eslint-disable-line no-console
}
else
{
console.log(`Command '${command.name}' loaded, overloading command '${command.overloads}'.`); // eslint-disable-line no-console
}
});
console.log(`Loaded ${loadedCommands} total commands in ${this.bot.commands.groups.length} groups.`); // eslint-disable-line no-console
}
/**
* Reload the given command in the Bot's {@link CommandRegistry} ({@link Bot#commands})
* @memberof CommandLoader
* @instance
* @param {string} nameOrAlias - {@link Command#name} or {@link Command#aliases} alias
* @returns {boolean}
*/
reloadCommand(nameOrAlias)
{
let name = this.bot.commands.findByNameOrAlias(nameOrAlias).name;
if (!name) return false;
let commandLocation = this.bot.commands.get(name).classloc;
delete require.cache[require.resolve(commandLocation)];
let Command = require(commandLocation).default;
let command = new Command(this.bot);
command.classloc = commandLocation;
this.bot.commands.register(command, command.name, true);
console.log(`Command '${command.name}' reloaded.`); // eslint-disable-line no-console
return true;
}
}
|
JavaScript
| 0 |
@@ -321,105 +321,20 @@
%09/**
-%0A%09%09 * Bot instance%0A%09%09 * @memberof CommandLoader%0A%09%09 * @type %7BBot%7D%0A%09%09 * @name bot%0A%09%09 * @instance%0A%09%09
+ @type %7BBot%7D
*/%0A
@@ -340,16 +340,17 @@
%0A%09%09this.
+_
bot = bo
@@ -649,24 +649,25 @@
%0A%09%09if (this.
+_
bot.commands
@@ -678,24 +678,25 @@
e %3E 0) this.
+_
bot.commands
@@ -863,24 +863,25 @@
ync(%60$%7Bthis.
+_
bot.commands
@@ -1152,32 +1152,33 @@
ew Command(this.
+_
bot);%0A%09%09%09if (thi
@@ -1175,24 +1175,25 @@
%09%09%09if (this.
+_
bot.disableB
@@ -1308,24 +1308,25 @@
%09%09if (!this.
+_
bot.commands
@@ -1469,32 +1469,33 @@
ed.%60);%0A%09%09%09%09this.
+_
bot.commands.del
@@ -1519,32 +1519,33 @@
oads);%0A%09%09%09%09this.
+_
bot.commands.reg
@@ -1597,24 +1597,25 @@
%09%7B%0A%09%09%09%09this.
+_
bot.commands
@@ -2017,24 +2017,25 @@
s in $%7Bthis.
+_
bot.commands
@@ -2392,32 +2392,33 @@
let name = this.
+_
bot.commands.fin
@@ -2503,24 +2503,25 @@
tion = this.
+_
bot.commands
@@ -2682,16 +2682,17 @@
nd(this.
+_
bot);%0A%09%09
@@ -2734,16 +2734,17 @@
%0A%09%09this.
+_
bot.comm
|
3c1d0e61002c5424d2b882a8044b75a11c0dd58c
|
Enable test cases (#2566)
|
tests/jerry/math-pow.js
|
tests/jerry/math-pow.js
|
// Copyright JS Foundation and other contributors, http://js.foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
assert ( isNaN (Math.pow (0.0 /* any number */, NaN)) );
assert ( Math.pow (NaN, 0.0) === 1.0 );
// assert ( Math.pow (NaN, -0.0) === 1.0 );
assert ( isNaN (Math.pow (NaN, 1.0 /* any non-zero number */)) );
assert ( Math.pow (2.0, Infinity) === Infinity );
assert ( Math.pow (2.0, -Infinity) === 0.0 );
assert ( isNaN (Math.pow (1.0, Infinity)) );
assert ( isNaN (Math.pow (1.0, -Infinity)) );
assert ( Math.pow (0.5, Infinity) === 0.0 );
assert ( Math.pow (0.5, -Infinity) === Infinity );
assert ( Math.pow (Infinity, 1.0) === Infinity );
assert ( Math.pow (Infinity, -1.0) === 0 );
assert ( Math.pow (-Infinity, 3.0) === -Infinity );
assert ( Math.pow (-Infinity, 2.0) === Infinity );
assert ( Math.pow (-Infinity, 2.5) === Infinity );
// assert ( Math.pow (-Infinity, -3.0) === -0.0 );
assert ( Math.pow (-Infinity, -2.0) === 0.0 );
assert ( Math.pow (-Infinity, -2.5) === 0.0 );
assert ( Math.pow (0.0, 1.2) === 0.0 );
assert ( Math.pow (0.0, -1.2) === Infinity );
// assert ( Math.pow (-0.0, 3.0) === -0.0 );
// assert ( Math.pow (-0.0, 2.0) === 0.0 );
// assert ( Math.pow (-0.0, 2.5) === 0.0 );
// assert ( Math.pow (-0.0, -3.0) === -Infinity );
// assert ( Math.pow (-0.0, -2.0) === Infinity );
// assert ( Math.pow (-0.0, -2.5) === Infinity );
assert ( isNaN (Math.pow (-3, 2.5)) );
assert(Math.pow (-2, 2) === 4);
assert(Math.pow (2, 2) === 4);
assert(Math.pow (2, 3) === 8);
assert(Math.pow (-2, 3) === -8);
assert(Math.pow (5, 3) === 125);
assert(Math.pow (-5, 3) === -125);
|
JavaScript
| 0 |
@@ -716,27 +716,24 @@
=== 1.0 );%0A
-//
assert ( Mat
@@ -1350,35 +1350,32 @@
=== Infinity );%0A
-//
assert ( Math.po
@@ -1402,24 +1402,24 @@
=== -0.0 );%0A
+
assert ( Mat
@@ -1578,35 +1578,32 @@
=== Infinity );%0A
-//
assert ( Math.po
@@ -1624,27 +1624,24 @@
=== -0.0 );%0A
-//
assert ( Mat
@@ -1661,35 +1661,32 @@
2.0) === 0.0 );%0A
-//
assert ( Math.po
@@ -1706,27 +1706,24 @@
=== 0.0 );%0A
-//
assert ( Mat
@@ -1750,35 +1750,32 @@
== -Infinity );%0A
-//
assert ( Math.po
@@ -1805,19 +1805,16 @@
nity );%0A
-//
assert (
|
e3ddf8220d0759639d4022bf8277ebbb9a7e1f4b
|
Update localStorage.js
|
src/localStorage/localStorage.js
|
src/localStorage/localStorage.js
|
angular.module('ngIdle.localStorage', [])
.service('IdleLocalStorage', ['$window', function($window) {
var storage = $window.localStorage;
return {
set: function(key, value) {
storage.setItem('ngIdle.'+key, angular.toJson(value));
},
get: function(key) {
return angular.fromJson(storage.getItem('ngIdle.'+key));
},
remove: function(key) {
storage.removeItem('ngIdle.'+key);
},
parseJson: function(raw) {
return angular.fromJson(raw);
}
};
}]);
|
JavaScript
| 0 |
@@ -440,88 +440,8 @@
y);%0A
- %7D,%0A parseJson: function(raw) %7B%0A return angular.fromJson(raw);%0A
|
fb26d3982b2811949f0311a73e343d4d3179a50b
|
use pathname not href
|
book/nio.js
|
book/nio.js
|
require(["gitbook"], function(gitbook) {
gitbook.events.bind("page.change", function(event) {
function resetToc() {
$('.js-toolbar-action > .fa').removeClass('fa-chevron-down--rotate180');
$('.book-header').removeClass('toc-open');
};
function setBodyScroll() {
const scrollDistance = 50;
if ($(window).scrollTop() > scrollDistance) {
$('body').addClass('scrolled');
}
else {
$('body').removeClass('scrolled');
}
}
function bindScrollEvent() {
$(window).bind('scroll', setBodyScroll);
}
function bindHashEvent() {
// for any link that includes a '#', but not only a '#'
$('a[href*="#"]').click(function(e) {
// if an internal page link
if (e.currentTarget.href.includes(window.location.href)) {
$('html, body').animate({ scrollTop: $(e.currentTarget.hash).offset().top}, 1000);
// else append hash to page and go to page while keeping the url without the hash out of the history
} else {
window.location.replace(e.currentTarget.href + e.currentTarget.hash);
}
});
}
// scroll to top of header on page change, initialize TOC as closed
$(document).ready(function(){
if (window.location.hash === ""){
$(window).scrollTop(0);
} else {
$('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
};
bindHashEvent();
bindScrollEvent();
resetToc();
$('.accordion').removeClass('accordionClose');
$('table').wrap('<div class="scrolling-wrapper"></div>');
// in mobile, force page change when active chapter is clicked
if ($(window).width() < 600) {
$('.active').click( function(e) {
window.location.href = e.target.href;
});
}
});
// allow dynamic active location in the header
var activeLocation = gitbook.state.config.pluginsConfig['theme-nio']['active-location'];
$(`#nav__list--${activeLocation}`).addClass('active');
// custom search bar placeholder text, add clickable icon, and search on return keypress
$('#book-search-input').append($('<div id="search-icon"></div>'));
$('#book-search-input input').attr('placeholder', 'Search');
$('#book-search-input input').keypress(function (e) {
var key = e.which;
if (key === 13) // the enter key code
{
$('.js-toolbar-action > .fa').click();
}
});
$('#search-icon').click( function() {
$('.js-toolbar-action > .fa').click();
});
// add class to active parent chapter
// remove active chapter globally
$('ul.summary li').removeClass('active--chapter');
// get the level of the selected sub-menu
var level = $('ul.summary li li.active').data('level');
if (level) {
// find the position of the first period after the 2nd index (only works for one or two-digit levels)
var dot = level.indexOf('.', 2);
// the parent is the substring before the second period
var parent = level.substring(0, dot);
$('ul.summary li[data-level="'+parent+'"]').addClass('active--chapter');
}
// this gets the sidebar expand TOC animation working
$('ul.summary > li.active').addClass('animating');
setTimeout(function() {
$('ul.summary > li').removeClass('animating');
}, 50);
$('ul.summary > li.chapter.active').addClass('animating');
setTimeout(function() {
$('ul.summary > li.chapter.active').removeClass('animating');
}, 50);
// replace header hamburger icon with chevron
$('.js-toolbar-action > .fa').removeClass('fa-align-justify');
$('.js-toolbar-action > .fa').addClass('fa-chevron-down');
// remove unwanted page-header elements that are added on each page change
if ($('.js-toolbar-action > .fa').length > 1) {
$('.js-toolbar-action > .fa')[0].remove();
}
if ($('.book-header').length > 1) {
$('.book-header')[1].remove();
}
// rotate chevron on click
$('.js-toolbar-action > .fa').click( function() {
$('.book-header').toggleClass('toc-open');
$('.js-toolbar-action > .fa').toggleClass('fa-chevron-down--rotate180');
});
// add class to blockquote according to key
var blkquotes = $('blockquote');
var classMap = {
'[info]': 'info',
'[warning]': 'warning',
'[danger]': 'danger',
'[success]': 'success'
};
var iconMap = {
'[info]': '<i class="fa fa-info-circle fa-2x blockquote-icon"></i>',
'[warning]': '<i class="fa fa-exclamation-circle fa-2x blockquote-icon"></i>',
'[danger]': '<i class="fa fa-ban fa-2x blockquote-icon"></i>',
'[success]': '<i class="fa fa-check-circle fa-2x blockquote-icon"></i>'
};
blkquotes.each(function() {
for (alertType in classMap) {
htmlStr = $(this).html()
if (htmlStr.indexOf(alertType) > 0) {
// remove alertType from text, replace with icon
htmlStr = htmlStr.replace(alertType, iconMap[alertType]);
$(this).html(htmlStr);
// add class
$(this).addClass(classMap[alertType]);
$(this).addClass('callout');
}
}
})
});
gitbook.events.bind("exercise.submit", function() {
// do something
});
gitbook.events.bind("start", function() {
// do things one time only, on load of book
// repurpose book-header as mobile TOC
// attach book-header to header and add custom content
$('.header').after($('.book-header'));
$('.js-toolbar-action').after( $('.custom-book-header-content'));
});
});
|
JavaScript
| 0.002293 |
@@ -849,20 +849,24 @@
ocation.
-href
+pathname
)) %7B%0A
@@ -1147,31 +1147,8 @@
href
- + e.currentTarget.hash
);%0A
@@ -1486,16 +1486,41 @@
%7D;%0A
+ setBodyScroll();%0A
|
82e66e62f5edbe98d64c84084d32c7f2fffb22ef
|
fix dateinput font on web
|
src/@ui/inputs/DateInput/index.web.js
|
src/@ui/inputs/DateInput/index.web.js
|
import React, { PureComponent } from 'react';
import { createElement } from 'react-native-web';
import { compose, mapProps } from 'recompose';
import PropTypes from 'prop-types';
import moment from 'moment';
import withInputControlStyles from '@ui/inputs/withInputControlStyles';
import { Text as TextInput } from '@ui/inputs';
const displayFormat = 'YYYY-MM-DD';
const NativeMappedDateInput = compose(
mapProps(({
onChangeText,
style,
...otherProps
}) => ({
type: 'date',
onChange: (e) => {
const text = e.target.value;
if (onChangeText) {
onChangeText(text);
}
},
style: [ // this will all get flattened by "withInputControlStyles" below
{
appearance: 'none',
backgroundColor: 'transparent',
borderColor: 'black',
borderRadius: 0,
borderWidth: 0,
boxSizing: 'border-box',
color: 'inherit',
font: 'inherit',
padding: 0,
resize: 'none',
},
style,
],
...otherProps,
})),
withInputControlStyles,
)(props => createElement('input', props));
class DateInput extends PureComponent {
static propTypes = {
value: PropTypes.instanceOf(Date),
onChange: PropTypes.func,
onChangeText: PropTypes.func,
onBlur: PropTypes.bool,
};
state = {
internalDateValue: moment(this.props.value).format(displayFormat),
};
componentWillReceiveProps({ value }) {
if (value !== this.props.value) {
this.setState({
internalDateValue: moment(value).format(displayFormat),
});
}
}
handleBlur = () => {
if (this.props.onBlur) this.props.onBlur();
if (this.props.onChange) this.props.onChange(this.parseValue(this.state.internalDateValue));
if (this.props.onChangeText) this.props.onChangeText(this.state.internalDateValue);
}
handleChange = (text) => {
this.setState({ internalDateValue: text });
}
parseValue = value => moment(value, displayFormat).toDate();
render() {
const {
value, onChange, onChangeText, ...textInputProps
} = this.props;
return (
<TextInput
label="Date"
placeholder={displayFormat}
type="date"
Component={NativeMappedDateInput}
{...textInputProps}
onBlur={this.handleBlur}
value={this.state.internalDateValue}
onChangeText={this.handleChange}
/>
);
}
}
export default DateInput;
|
JavaScript
| 0.000001 |
@@ -912,33 +912,8 @@
t',%0A
- font: 'inherit',%0A
|
a5dfec0ebd09967bc781c304101995585b59b075
|
update forms-material-ui example
|
examples/forms-material-ui/src/components/tweets/CreateCard.template.js
|
examples/forms-material-ui/src/components/tweets/CreateCard.template.js
|
var React = require('react');
var mui = require('material-ui');
var PayloadStates = require('../../constants/PayloadStates');
var _ = require('lodash');
var moment = require('moment');
// Hook Dialogs
var withMuiTheme = require('../../decorators/withMuiTheme').default;
var validators = require('../../utils/validators');
var Template = require('../templates/Template');
var Overlay = require('../common/Overlay');
var tweetConfig = require('../../models/tweet');
module.exports = React.createClass({
displayName: 'CreateCard.template',
getInitialState: function() {
return {
tweet: null,
userId: null,
text: ''
}
},
componentWillReceiveProps: function (nextProps) {
var tweet = this.state.tweet;
if (!tweet) {
return;
}
var nextTweet = lore.store.getState().tweet.byCid[tweet.cid];
if (nextTweet.state === PayloadStates.RESOLVED) {
this.setState({
tweet: null
})
} else {
this.setState({
tweet: nextTweet
})
}
},
onSubmit: function(params) {
var action = lore.actions.tweet.create(_.extend({
createdAt: moment().unix()
}, params));
this.setState({
tweet: action.payload
});
},
getForm: function() {
var data = this.state;
return React.createElement(Template, _.merge({}, tweetConfig.forms, {
fields: {
text: {
data: data.text
},
userId: {
data: data.userId
}
},
onSubmit: this.onSubmit
}));
},
render: function() {
var tweet = this.state.tweet;
return (
<Overlay model={tweet}>
<mui.Card className="form-card">
<mui.CardTitle
title="Template Form"
subtitle="Created by providing a config to the template used by the forms hook" />
{this.getForm()}
</mui.Card>
</Overlay>
);
}
});
|
JavaScript
| 0 |
@@ -1239,32 +1239,45 @@
m: function() %7B%0A
+ debugger%0A
var data = t
@@ -1291,49 +1291,31 @@
te;%0A
-%0A
-return React.createElement(Template,
+var templateProps =
_.m
@@ -1514,16 +1514,74 @@
t%0A %7D)
+;%0A%0A return (%0A %3CTemplate %7B...templateProps%7D /%3E%0A
);%0A %7D,%0A
|
fa02fb7a401846a3cc1a8842bbd6fc2f2380ddb5
|
add extra check to publish.js
|
publish.js
|
publish.js
|
/*
* Copyright (c) 2011-2014 by Animatron.
* All rights are reserved.
*/
/* Variables we get from template:
playerDomain - a URL to player domain host, e.g. player.animatron.com
amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
width — width of the animation
height - height of the animation
playerVersion = player version, default 'latest'
filename = filename of snapshot, used as amazonDomain + filename
autostart = (boolean) autostart of movie on player load
loop = (boolean) loop animation instead of stoping at the end
animation = JSON object of animatron movie (currently not used)
*/
(function(){
var inIFrame = (window.self !== window.top);
var utils = {
isInt: function(n) {
n = Number(n);
return !isNaN(n) && Math.floor(n) === n;
},
serializeToQueryString: function(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
},
parseQueryString: function() {
var queryString = location.search.substring(1);
if (!queryString) {
return {};
}
var queries = queryString.split("&"),
params = {}, temp, i, l;
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
},
getRequiredRect: function () {
if (inIFrame) {
return utils.getIframeSize();
} else {
return {w: width, h: height};
}
},
getIframeSize: function () {
var size = {w:0, h:0};
if (typeof window.innerWidth == 'number') {
size.w = window.innerWidth;
size.h = window.innerHeight;
} else {
size.w = document.documentElement.clientWidth;
size.h = document.documentElement.clientHeight;
}
return size;
},
forcedJS: function (path, then) {
var scriptElm = document.createElement('script');
scriptElm.type = 'text/javascript';
scriptElm.async = 'async';
scriptElm.src = path + '?' + (new Date()).getTime();
scriptElm.onload = scriptElm.onreadystatechange = (function () {
var success = false;
return function () {
if (this.readyState === 'loading') {
return;
}
if (!success && (!this.readyState ||
(this.readyState === 'complete' || this.readyState === 'loaded')
)) {
success = true;
then();
} else if (!success && window.console) {
console.error('Request failed: ' + this.readyState);
}
};
})();
var headElm = document.head || document.getElementsByTagName('head')[0];
headElm.appendChild(scriptElm);
}
};
var TARGET_ID = 'target',
WRAPPER_CLASS = 'anm-wrapper',
PLAYER_VERSION_ID = playerVersion || 'latest';
var params = utils.parseQueryString(),
rect = utils.getRequiredRect(),
targetWidth, targetHeight;
//floating-point w&h parameters mean percentage sizing
if (params.w && !utils.isInt(params.w)) {
targetWidth = params.w = Math.round(params.w * rect.w);
} else {
targetWidth = params.w = params.w || rect.w;
}
if (params.h && !utils.isInt(params.h)) {
targetHeight = params.h = Math.round(params.h * rect.h);
} else {
targetHeight = params.h = params.h || rect.h;
}
if (autostart) {
params.a = 1;
}
if (loop) {
params.r = 1;
}
if (params.v) {
PLAYER_VERSION_ID = params.v;
}
var snapshotUrl = amazonDomain + '/' + filename + '?' +
utils.serializeToQueryString(params);
var start = function () {
try {
if (!inIFrame) {
document.body.className ='no-iframe';
} else {
document.body.style.overflow = 'hidden';
}
var target = document.getElementById(TARGET_ID);
target.style.width = targetWidth + 'px';
target.style.height = targetHeight + 'px';
target.style.marginLeft = -Math.floor(targetWidth / 2) + 'px';
target.style.marginTop = -Math.floor(targetHeight / 2) + 'px';
target.style.position = 'absolute';
target.style.left = '50%';
target.style.top = '50%';
utils.forcedJS('//' + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.min.js',
function () {
var player = anm.Player.forSnapshot(TARGET_ID, snapshotUrl, anm.importers.create('animatron'));
if (anm.interop.playerjs) {
anm.interop.playerjs.setPlayer(player);
}
});
} catch (e) {
if(window.console) console.error(e);
}
};
window.start = start;
})();
|
JavaScript
| 0 |
@@ -5237,32 +5237,47 @@
if (anm.interop
+ && anm.interop
.playerjs) %7B%0A
|
ce1ce46e377415ab5965c01d0c24092b2e706b56
|
fix jest tests
|
agent/__tests__/dehydrate-test.js
|
agent/__tests__/dehydrate-test.js
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
jest.dontMock('../dehydrate');
var dehydrate = require('../dehydrate');
describe('dehydrate', () => {
it('leaves an empty object alone', () => {
var cleaned = [];
var result = dehydrate({}, cleaned);
expect(result).toEqual({});
});
it('preserves a shallowly nested object', () => {
var object = {
a: {b: 1, c: 2, d: 3},
b: ['h', 'i', 'j'],
};
var cleaned = [];
var result = dehydrate(object, cleaned);
expect(cleaned).toEqual([]);
expect(result).toEqual(object);
});
it('cleans a deeply nested object', () => {
var object = {a: {b: {c: {d: 4}}}};
var cleaned = [];
var result = dehydrate(object, cleaned);
expect(cleaned).toEqual([['a', 'b', 'c']]);
expect(result.a.b.c).toEqual({type: 'object', name: '', meta: {}});
});
it('cleans a deeply nested array', () => {
var object = {a: {b: {c: [1, 3]}}};
var cleaned = [];
var result = dehydrate(object, cleaned);
expect(cleaned).toEqual([['a', 'b', 'c']]);
expect(result.a.b.c).toEqual({type: 'array', name: 'Array', meta: {length: 2}});
});
it('cleans multiple things', () => {
var Something = function () {};
var object = {a: {b: {c: [1, 3], d: new Something()}}};
var cleaned = [];
var result = dehydrate(object, cleaned);
expect(cleaned).toEqual([['a', 'b', 'c'], ['a', 'b', 'd']]);
expect(result.a.b.c).toEqual({type: 'array', name: 'Array', meta: {length: 2}});
expect(result.a.b.d).toEqual({type: 'object', name: 'Something', meta: {}});
});
});
|
JavaScript
| 0.000001 |
@@ -1105,34 +1105,36 @@
name: '', meta:
-%7B%7D
+null
%7D);%0A %7D);%0A%0A it(
@@ -1847,18 +1847,20 @@
, meta:
-%7B%7D
+null
%7D);%0A %7D)
|
daa8f93c7ba2517fd18657a66e94d07e80aae95c
|
Version Number
|
bot.user.js
|
bot.user.js
|
// ==UserScript==
// @name Slither.io-bot
// @namespace http://slither.io/
// @version 0.1.3
// @description Slither.io bot
// @author Ermiya Eskandary & Théophile Cailliau
// @match http://slither.io/
// @grant none
// ==/UserScript==
// Functions needed for the bot start here
//UPDATE - removed the onemousemove listener
window.onmousemove = function(e) {
/*if (e = e || window.event) {
if ("undefined" != typeof e.clientX) {
xm = e.clientX - ww / 2;
ym = e.clientY - hh / 2;
}
}*/
};
//Set fake mouse coordinates
window.setMouseCoordinates = function (x, y) {
window.xm = x;
window.ym = y;
};
// return the coordinates relative to the center (snake position).
window.mouseRelativeToCenter = function (x, y) {
mapX = x - getHeight() / 2;
mapY = y - getWidth() / 2;
return [mapX, mapY];
};
// Map to mouse coordinates
window.mapToMouse = function (x, y) {
mouseX = (x - getX())*gsc;
mouseY = (y - getY())*gsc;
return [mouseX, mouseY];
};
// Canvas width
window.getWidth = function () {
return window.ww;
};
// Canvas height
window.getHeight = function () {
return window.hh;
};
// X coordinates on the screen
window.getX = function () {
return window.px;
};
// Y coordinates on the screen
window.getY = function () {
return window.py;
};
// Get scaling ratio
window.getScale = function(){
return window.gsc;
}
window.launchBot = function(d){
return window.botInterval = setInterval(window.loop, d);
}
// Actual bot code starts from here
//sorting function, from property 'distance'.
window.sortFood = function (a, b) {
return a.distance - b.distance;
};
//Given an object (of which properties xx and yy are not null), return the object with an additional property 'distance'.
window.getDistanceFromMe = function (point) {
if (point == null) return null;
point.distance = getDistance(px, py, point.xx, point.yy);
return point;
};
// Get a distance from point (x1; y1) to point (x2; y2).
window.getDistance = function (x1, y1, x2, y2) {
// Calculate the vector coordinates.
var xDistance = (x1 - x2);
var yDistance = (y1 - y2);
// Get the absolute value of each coordinate
xDistance = xDistance < 0 ? xDistance * -1 : xDistance;
yDistance = yDistance < 0 ? yDistance * -1 : yDistance;
//Add the coordinates of the vector to get a distance. Not the real distance, but reliable for distance comparison.
var distance = xDistance + yDistance;
return distance;
};
window.getSortedFood = function () {
return window.foods.filter(function (val) {
return val !== null;
}).map(getDistanceFromMe).sort(sortFood);
};
window.isInFoods = function (foodObject) {
return (foodObject === null) ? false : (window.foods.indexOf(foodObject) >= 0);
};
window.currentFood = null;
window.sortedFood = getSortedFood();
/*window.loop = function () {
if (!isInFoods(currentFood)) {
window.sortedFood = getSortedFood();
window.currentFood = sortedFood[0];
var coordinatesOfClosestFood = window.mapToMouse(window.sortedFood[0].xx, window.sortedFood[0].yy);
window.setMouseCoordinates(coordinatesOfClosestFood[0], coordinatesOfClosestFood[1]);
}
};*/
window.loop = function () {
if (playing) {
var sortedFood = getSortedFood();
var coordinatesOfClosestFood = window.mapToMouse(sortedFood[0].xx, sortedFood[0].yy);
window.setMouseCoordinates(coordinatesOfClosestFood[0], coordinatesOfClosestFood[1]);
}
}
window.launchBot(5);
|
JavaScript
| 0.000017 |
@@ -104,9 +104,9 @@
0.1.
-3
+4
%0A//
|
3770675ac8a27f4dc8b90eb7b478dbe6dcdfbb89
|
test hooks
|
tests/src/util/hooks.js
|
tests/src/util/hooks.js
|
'use strict';
const assert = require('chai').assert;
const validator = require('validator');
const hooks = require('../../../src/util/hooks');
const xssSeed = require('../../../src/seed/xss');
const ip4Seed = require('../../../src/seed/ip4');
const macSeed = require('../../../src/seed/mac');
describe('util/hooks.js', () => {
it(`should be xss`, () => {
const xss = xssSeed();
hooks.set(() => xss);
assert.strictEqual(ip4Seed(), xss);
assert.strictEqual(macSeed(), xss);
hooks.clear();
});
it(`should has argument`, () => {
const xss = xssSeed();
hooks.set((value) => {
assert.strictEqual(value, xss);
});
assert.strictEqual(xssSeed(), undefined);
hooks.clear();
});
it('hook for specific seed', () => {
hooks.set(macSeed, () => {
return 'test-mac-hook';
});
assert.strictEqual(macSeed(), 'test-mac-hook');
assert.isTrue(validator.isIP(ip4Seed(), 4));
hooks.clear();
});
it('specific seed and global override', () => {
hooks.set(() => {
return 'global';
});
hooks.set(macSeed, (value) => {
return 'test-mac-hook-' + value;
});
assert.strictEqual(macSeed(), 'test-mac-hook-global');
assert.strictEqual(ip4Seed(), 'global');
hooks.clear();
});
it(`wrap`, () => {
let sum = hooks.wrap((a, b) => {
return a + b;
});
assert.strictEqual(sum(1, 2), 3);
hooks.set(() => {
return 0;
});
assert.strictEqual(sum(1, 2), 0);
hooks.clear();
});
});
|
JavaScript
| 0.000001 |
@@ -676,32 +676,140 @@
al(value, xss);%0A
+ return 1;%0A %7D);%0A%0A hooks.set((value) =%3E %7B%0A assert.strictEqual(value, 1);%0A
%7D);%0A%0A
|
325a0defd45fb194c44695d5468d03eff3737f89
|
build targets should cover a wider browser range (#346)
|
tests/dummy/config/targets.js
|
tests/dummy/config/targets.js
|
'use strict';
const browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions',
'last 1 edge versions'
];
module.exports = {
browsers
};
|
JavaScript
| 0 |
@@ -35,17 +35,17 @@
'last
-1
+2
Chrome
@@ -63,17 +63,17 @@
'last
-1
+2
Firefox
@@ -84,24 +84,41 @@
sions',%0A
+ 'Firefox ESR',%0A
'last
1 Safari
@@ -109,17 +109,17 @@
'last
-1
+2
Safari
@@ -135,29 +135,251 @@
,%0A
-'last 1 edge versions
+// Last versions of Microsoft Edge are build on top of Chromium. But they are%0A // not shipped yet to a significant number of users. Need to still support%0A // Edge 18 explicitly until chromium-based Edge is shipped to all users.%0A 'Edge %3E= 18
'%0A%5D;
|
a88a9b975441fb8f0f892b8477e97f5fcbf89f32
|
fix edge case if element has default tag, but has sigils
|
builddom.js
|
builddom.js
|
const buildDom = (() =>{
const tagRegex = new RegExp('^([\\w\\-]+)([\\.#].*)?$');
const sigilRegex = new RegExp('^([\\.#])([\\w\\-]+)(.*)$');
const contains = {}.hasOwnProperty;
return function buildDom(obj) {
if (obj instanceof Node) {return obj}
if (Array.isArray(obj)) {return obj.map(buildDom)}
if (typeof obj === 'string' || obj instanceof String) {return document.createTextNode(obj)}
let {
'': selector,
c: children
} = obj;
const match = selector && tagRegex.exec(selector);
let tag = match ? match[1] : 'div';
selector = match ? match[2] : '';
const ids = [], classes = [];
while (selector) {
const match = sigilRegex.exec(selector);
if (!match) {throw "broken selector"}
const [,sigil, string, rest] = match;
if (sigil == '#') {
ids.push(string);
} else {
classes.push(string);
}
selector = rest;
}
const el = document.createElement(tag);
ids.length && (el.id = ids.join(' '));
classes.length && (el.className = classes.join(' '));
for (let attr in obj) {
if (attr && attr !== 'c' && contains.call(obj, attr)) {
el.setAttribute(attr, obj[attr]);
}
}
if (!children) {children = []}
children = buildDom(children);
Array.isArray(children) ? children.forEach(el.appendChild.bind(el)): el.appendChild(children);
return el;
};
})();
// To the extent possible under law, Jona Stubbe has [waived all copyright and related or neighboring rights](http://creativecommons.org/publicdomain/zero/1.0/) to the buildDom JavaScript function. This work is published from: Germany.
|
JavaScript
| 0.000001 |
@@ -568,16 +568,26 @@
ch%5B2%5D :
+selector%7C%7C
'';%0A%09%09co
|
e89f509fc50decc515ccc6862d818119a4329cd6
|
add test modification
|
test/server-test.js
|
test/server-test.js
|
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
require(__dirname + '/../server.js');
var mongoose = require('mongoose');
var User = require(__dirname + '/../models/user');
process.env.MONGOLAB_URI = 'mongodb://localhost/user_test';
describe('the server', function(){
before(function(done){
this.userData = {username: 'test name'};
this.imageData = {imagepath: '/test-path'};
done();
});
after(function(done){
mongoose.connection.db.dropDatabase(function(){
done();
});
});
it('should GET users from the db', function(done){
chai.request('localhost:3000')
.get('/api/users')
.end(function(err, res){
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(Array.isArray(res.body)).to.eql(true);
done();
});
});
it('should GET images from the db', function(done){
chai.request('localhost:3000')
.get('/api/images')
.end(function(err, res){
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(Array.isArray(res.body)).to.eql(true);
done();
});
});
it('should GET a registered end point', function(done){
chai.request('localhost:3000')
.get('/original')
.end(function(err, res){
expect(err).to.eql(null);
expect(res.status).to.eql(200);
done();
});
});
it('should GET a registered end point', function(done){
chai.request('localhost:3000')
.get('/transformed')
.end(function(err, res){
expect(err).to.eql(null);
expect(res.status).to.eql(200);
done();
});
});
it('should send a 404 to an unregistered end point', function(done){
chai.request('localhost:3000')
.get('/5fbhjbu')
.end(function(err, res){
expect(res.status).to.eql(404);
done();
});
});
it('should POST users to the DB', function(done){
chai.request('localhost:3000')
.post('/api/users')
.send(this.userData)
.end(function(err, res){
expect(err).to.eql(null);
expect(res.body.username).to.eql('test name');
expect(res.body).to.have.property('_id');
done();
});
});
it('should POST images to the DB', function(done){
chai.request('localhost:3000')
.post('/api/images')
.send(this.imageData)
.end(function(err, res){
expect(err).to.eql(null);
expect(res.body.imagepath).to.eql('/test-path');
expect(res.body).to.have.property('_id');
done();
});
});
describe(',when you want it to,', function(){
beforeEach(function(done){
(new User({username: 'test guy'})).save(function(err, data){
expect(err).to.eql(null);
this.user = data;
done();
}.bind(this));
});
it('should DELETE users from the DB', function(done){
chai.request('localhost:3000')
.delete('/api/users/' + this.user._id)
.end(function(err, res) {
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(res.body.msg).to.eql('User removed');
done();
});
});
it('should modify users with a PUT request', function(done){
chai.request('localhost:3000')
.put('/api/users/' + this.user._id)
.end(function(err, res){
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(res.body.msg).to.eql('User updated');
done();
});
});
});
});
|
JavaScript
| 0 |
@@ -1398,254 +1398,8 @@
);%0A%0A
- it('should GET a registered end point', function(done)%7B%0A chai.request('localhost:3000')%0A .get('/transformed')%0A .end(function(err, res)%7B%0A expect(err).to.eql(null);%0A expect(res.status).to.eql(200);%0A done();%0A %7D);%0A %7D);%0A%0A
it
|
580fa8a9f6105376a28c09a732a0e6263133c5ff
|
add routes for non-retina assets
|
tests/mapbox-server/create.js
|
tests/mapbox-server/create.js
|
/* global FakeXMLHttpRequest */
import Pretender from 'pretender';
import Sprites from './data/sprites';
import SpritesPng from './data/sprites-png';
import Style from './data/style';
import Terrain from './data/terrain';
// have to monkeypatch until https://github.com/pretenderjs/FakeXMLHttpRequest/issues/31 is fixed :-(
FakeXMLHttpRequest.prototype._setResponseBody = function _setResponseBody(body) {
var chunkSize = this.chunkSize || 10;
var index = 0;
this.responseText = "";
do {
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.LOADING);
}
this.responseText += body.substring(index, index + chunkSize);
index += chunkSize;
} while (index < body.length);
this.response = this.responseText
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.DONE);
} else {
this.readyState = FakeXMLHttpRequest.DONE;
}
};
export default function create() {
return new Pretender(function() {
this.get('https://api.mapbox.com/styles/v1/mapbox/streets-v9', function() {
return [ 200, { 'content-type': 'application/json' }, Style ];
});
this.get('https://api.mapbox.com/v4/mapbox.mapbox-terrain-v2,mapbox.mapbox-streets-v7.json', function() {
return [ 200, { 'content-type': 'application/json' }, Terrain ];
});
this.get('https://api.mapbox.com/styles/v1/mapbox/streets-v9/[email protected]', function() {
return [ 200, { 'content-type': 'application/json' }, Sprites ];
});
this.get('https://api.mapbox.com/styles/v1/mapbox/streets-v9/[email protected]', function() {
return [ 200, {}, SpritesPng ];
});
});
}
|
JavaScript
| 0 |
@@ -1371,19 +1371,16 @@
9/sprite
-@2x
.json',
@@ -1459,16 +1459,329 @@
Sprites
+ %5D;%0A %7D);%0A%0A this.get('https://api.mapbox.com/styles/v1/mapbox/streets-v9/[email protected]', function() %7B%0A return %5B 200, %7B 'content-type': 'application/json' %7D, Sprites %5D;%0A %7D);%0A%0A this.get('https://api.mapbox.com/styles/v1/mapbox/streets-v9/sprite.png', function() %7B%0A return %5B 200, %7B%7D, SpritesPng
%5D;%0A
|
55b50de408063178d1084551c4dcb94cb6cc991b
|
Fix digest algorithm for signer in test
|
test/signed_data.js
|
test/signed_data.js
|
"use strict";
var assert = require("assert");
var fs = require("fs");
var trusted = require("../index.js");
var DEFAULT_RESOURCES_PATH = "test/resources";
var DEFAULT_OUT_PATH = "test/out";
describe("SignedData", function() {
var cert, key;
before(function() {
try {
fs.statSync(DEFAULT_OUT_PATH).isDirectory();
} catch (err) {
fs.mkdirSync(DEFAULT_OUT_PATH);
}
cert = trusted.pki.Certificate.load(DEFAULT_RESOURCES_PATH + "/cert1.crt", trusted.DataFormat.PEM);
key = trusted.pki.Key.readPrivateKey(DEFAULT_RESOURCES_PATH + "/cert1.key", trusted.DataFormat.PEM, "");
});
it("Sign new data", function() {
var sd;
var signer;
var policies;
sd = new trusted.cms.SignedData();
assert.equal(sd.content, null, "Init: content != null");
assert.equal(sd.signers().length, 0, "Init: signers != 0");
assert.equal(sd.certificates().length, 0, "Init: certificates != 0");
sd.policies = ["noAttributes", "noSignerCertificateVerify", "wrongPolicy"];
signer = sd.createSigner(cert, key);
assert.equal(signer.digestAlgorithm.name, "sha1");
assert.equal(sd.signers().length, 1);
sd.content = {
type: trusted.cms.SignedDataContentType.buffer,
data: "Hello world"
};
policies = sd.policies;
assert.equal(policies.indexOf("noAttributes") !== -1, true);
assert.equal(policies.indexOf("wrongPolicy") === -1, true);
sd.sign();
sd.save(DEFAULT_OUT_PATH + "/testsig.sig", trusted.DataFormat.PEM);
assert.equal(sd.export() !== null, true, "sd.export()");
assert.equal(sd.verify() !== false, true, "Verify signature");
});
it("load", function() {
var cms;
var signers;
var signer;
cms = new trusted.cms.SignedData();
cms.load(DEFAULT_OUT_PATH + "/testsig.sig", trusted.DataFormat.PEM);
assert.equal(cms.signers().length, 1, "Wrong signers length");
assert.equal(cms.certificates().length, 1, "Wrong certificates length");
assert.equal(cms.isDetached(), false, "Detached");
signers = cms.signers();
for (var i = 0; i < signers.length; i++) {
signer = cms.signers(i);
assert.equal(signer.digestAlgorithm.name, "sha1", "Wrong digest algorithm");
}
});
});
|
JavaScript
| 0.00001 |
@@ -1181,17 +1181,19 @@
me, %22sha
-1
+256
%22);%0A
@@ -2375,17 +2375,19 @@
me, %22sha
-1
+256
%22, %22Wron
|
603e259f36a2fbaf65da6e7425b4a7e799919724
|
Test page with controls
|
test/test-player.js
|
test/test-player.js
|
var jumping = false;
setTimeout(function() {
jumping = true;
}, 1000);
setTimeout(function() {
jumping = false;
}, 2000);
var testPlayer = {
positionX: 193,
positionY: 175,
width: 35,
height: 70,
update: function(game) {
game.offsetX += 2;
if(jumping) game.offsetY += 1;
},
draw: function(d) {
d.fillStyle("#000000").fillRect(0, 0, 35, 70);
}
}
|
JavaScript
| 0 |
@@ -1,36 +1,98 @@
var
-jumping = false;%0AsetTimeout(
+right = false, left = false, up = false, down = false;%0Awindow.addEventListener(%22keydown%22,
func
@@ -100,50 +100,221 @@
ion(
+e
) %7B%0A%09
-jumping = true;%0A%7D, 1000);%0AsetTimeout(
+switch(e.keyCode) %7B%0A%09%09case 40:%0A%09%09%09down = true;%0A%09%09%09break;%0A%09%09case 39:%0A%09%09%09right = true;%0A%09%09%09break;%0A%09%09case 38:%0A%09%09%09up = true;%0A%09%09%09break;%0A%09%09case 37:%0A%09%09%09left = true;%0A%09%09%09break;%0A%09%7D%0A%7D);%0Awindow.addEventListener(%22keyup%22,
func
@@ -322,39 +322,191 @@
ion(
+e
) %7B%0A%09
-jumping = false;%0A%7D, 2000);
+switch(e.keyCode) %7B%0A%09%09case 40:%0A%09%09%09down = false;%0A%09%09%09break;%0A%09%09case 39:%0A%09%09%09right = false;%0A%09%09%09break;%0A%09%09case 38:%0A%09%09%09up = false;%0A%09%09%09break;%0A%09%09case 37:%0A%09%09%09left = false;%0A%09%09%09break;%0A%09%7D%0A%7D)%0A
%0A%0A%0Av
@@ -608,16 +608,31 @@
game) %7B%0A
+%09%09if(right) %7B%0A%09
%09%09game.o
@@ -650,20 +650,102 @@
;%0A%09%09
-if(jumping)
+%7D%0A%09%09if(left) %7B%0A%09%09%09game.offsetX -= 2;%0A%09%09%7D%0A%09%09if(up) %7B%0A%09%09%09game.offsetY += 1;%0A%09%09%7D%0A%09%09if(down) %7B%0A%09%09%09
game
@@ -753,22 +753,26 @@
offsetY
-+
+-
= 1;%0A
+%09%09%7D%0A
%09%7D,%0A%09dra
|
1c6139aeafbb336baf11dcb2271956a091dd6267
|
update "browser" test
|
test/testBrowser.js
|
test/testBrowser.js
|
function runBrowserTests() {
// Mock objects
const div = document.createElement("div");
// asyncTest("Test navigation option", function () {
//
// const options = {
// genome: "hg19",
// showNavigation: false
// };
//
// igv.createBrowser(div, options)
// .then(function (browser) {
// ok(browser);
// start();
// })
//
// .catch(function (error) {
// ok(false);
// console.log(error);
// start();
// })
// });
asyncTest("Test ruler option", function () {
const options = {
genome: "hg19",
showRuler: false
};
igv.createBrowser(div, options)
.then(function (browser) {
ok(browser);
start();
})
.catch(function (error) {
ok(false);
console.log(error);
start();
})
})
}
|
JavaScript
| 0.000003 |
@@ -95,19 +95,16 @@
%22);%0A%0A
- //
asyncTe
@@ -146,29 +146,20 @@
on () %7B%0A
- //
%0A
- //
con
@@ -172,27 +172,24 @@
ions = %7B%0A
- //
gen
@@ -205,26 +205,24 @@
9%22,%0A
-//
showNav
@@ -209,25 +209,24 @@
-
showNavigati
@@ -242,19 +242,16 @@
%0A
- //
%7D;%0A
@@ -246,29 +246,20 @@
%7D;%0A
- //
%0A
- //
igv
@@ -286,27 +286,24 @@
options)%0A
- //
.th
@@ -321,35 +321,32 @@
(browser) %7B%0A
- //
ok(
@@ -351,34 +351,32 @@
k(browser);%0A
-//
sta
@@ -363,33 +363,32 @@
-
start();%0A //
@@ -375,35 +375,32 @@
start();%0A
- //
%7D)%0A
@@ -399,29 +399,21 @@
%7D)%0A
- //
%0A
-//
.ca
@@ -400,33 +400,32 @@
%7D)%0A%0A
-
.catch(function
@@ -433,27 +433,24 @@
error) %7B%0A
- //
@@ -460,27 +460,24 @@
(false);%0A
- //
@@ -496,27 +496,24 @@
(error);%0A
- //
@@ -525,19 +525,16 @@
t();%0A
- //
@@ -540,19 +540,16 @@
%7D)%0A
- //
%7D);%0A%0A
|
2364fe4e890fcd8295a37d6da9047444fe0b6e0e
|
fix test
|
test/test_server.js
|
test/test_server.js
|
var assert = require('assert');
var should = require('should');
var request = require('request');
var supertest = require('supertest');
var api = require('../src/main').api();
describe('jenkins test project', function() {
it('should got hello jenkins', function() {
request.get('http://localhost:8090', function(e, r, body) {
body.should.be.equal('Hello Jenkins')
})
})
})
describe('jenkins test with supertest', function() {
it('should locally get hello jenkins', function() {
supertest(api).get('/').expect(200).end(function(e, r) {
r.body.should.be.equal('Hello Jenkins');
})
})
it('should locally get welcome home', function() {
supertest(api).get('/home').expect(200).end(function(e, r) {
r.body.should.be.equal('Welcome Home');
})
})
})
|
JavaScript
| 0.000002 |
@@ -257,32 +257,34 @@
', function() %7B%0A
+//
request.
@@ -331,24 +331,26 @@
r, body) %7B%0A
+//
@@ -387,16 +387,18 @@
nkins')%0A
+//
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.