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
|
---|---|---|---|---|---|---|---|
698f35d4196afb6838eb892d79e491f180fe4d8e | format code | messages/handleCourseMessage.js | messages/handleCourseMessage.js | 'use strict'
const {type} = require('message-type')
const canvasApi = require('../canvasApi')
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const ugParser = require('./ugParser')
const calcSisForOmregistrerade = require('./calcSisForOmregistrerade')
const createCsvFile = require('./createCsvFile')
const csvVol = config.full.azure.csvBlobName
const csvDir = config.full.localFile.csvDir
function parseKey ({ug1Name, _desc}) {
const {userType} = _desc
if (userType === type.students) {
return ugParser.parseKeyStudent(ug1Name)
}
if (userType === type.teachers || userType === type.assistants || userType === type.courseresponsibles) {
return ugParser.parseKeyTeacher(ug1Name)
}
log.error('Course code not parsable from Key. type, ', userType + ' ug1Name, ' + ug1Name)
throw new Error('Key parse error, type, ' + userType + ' ug1Name, ' + ug1Name)
}
function handleCourseMessage (msg) {
let sisCourseCodeFunction
if (msg._desc.userType === type.omregistrerade) {
log.info('using calcSisForOmregistrerade')
sisCourseCodeFunction = calcSisForOmregistrerade
} else {
log.info('using parseKey')
sisCourseCodeFunction = parseKey
}
return Promise.resolve()
.then(() => sisCourseCodeFunction(msg))
.then(sisCourseCode => createCsvFile(msg, sisCourseCode, csvDir, csvVol))
.then(({name}) => canvasApi.sendCsvFile(name, true))
.then(canvasReturnValue => {
return {msg, resp: canvasReturnValue}
})
}
module.exports = {handleCourseMessage, parseKey}
| JavaScript | 0.000061 | @@ -478,16 +478,17 @@
esc%7D) %7B%0A
+
const %7B
@@ -506,16 +506,17 @@
_desc%0A%0A
+
if (use
@@ -538,24 +538,25 @@
students) %7B%0A
+
return ug
@@ -587,20 +587,22 @@
g1Name)%0A
+
%7D%0A%0A
+
if (use
@@ -703,16 +703,17 @@
s) %7B%0A
+
return u
@@ -745,20 +745,22 @@
g1Name)%0A
+
%7D%0A%0A
+
log.err
@@ -842,16 +842,17 @@
g1Name)%0A
+
throw n
@@ -963,16 +963,17 @@
(msg) %7B%0A
+
let sis
@@ -991,16 +991,17 @@
unction%0A
+
if (msg
@@ -1043,16 +1043,17 @@
rade) %7B%0A
+
log.i
@@ -1089,24 +1089,25 @@
rerade')%0A
+
sisCourseCod
@@ -1143,16 +1143,17 @@
trerade%0A
+
%7D else
@@ -1157,16 +1157,17 @@
se %7B%0A
+
log.info
@@ -1185,16 +1185,17 @@
seKey')%0A
+
sisCo
@@ -1222,20 +1222,22 @@
arseKey%0A
+
%7D%0A%0A
+
return
|
5fc2d1337e5a3e90c1a884949c4af49afc7ef7fa | use .txt() for the "date" value | lib/build.js | lib/build.js |
/**
* Module dependencies.
*/
var xmlbuilder = require('xmlbuilder');
/**
* Module exports.
*/
exports.build = build;
function ISODateString(d){
function pad(n){
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z';
}
// instanceof is horribly unreliable so we use these hackish but safer checks
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
function isBoolean(obj) {
return (obj === true || obj === false || toString.call(obj) == '[object Boolean]');
}
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
/**
* generate an XML plist string from the input object
*
* @param {Object} obj - the object to convert
* @returns {String} converted plist
* @api public
*/
function build (obj) {
var XMLHDR = { 'version': '1.0','encoding': 'UTF-8' }
, XMLDTD = { 'ext': 'PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"' }
, doc = xmlbuilder.create()
, child = doc.begin('plist', XMLHDR, XMLDTD).att('version', '1.0');
walk_obj(obj, child);
return child.end({
pretty: true
});
}
/**
* depth first, recursive traversal of a javascript object. when complete,
* next_child contains a reference to the build XML object.
*
* @api private
*/
function walk_obj(next, next_child) {
var tag_type, i, prop;
if (isArray(next)) {
next_child = next_child.ele('array');
for(i=0 ;i < next.length;i++) {
walk_obj(next[i], next_child);
}
} else if (isObject(next)) {
if (Buffer.isBuffer(next)) {
next_child.ele('data').raw(next.toString('base64'));
} else {
next_child = next_child.ele('dict');
for(prop in next) {
if (next.hasOwnProperty(prop)) {
next_child.ele('key').txt(prop);
walk_obj(next[prop], next_child);
}
}
}
} else if (isNumber(next)) {
// detect if this is an integer or real
tag_type =(next % 1 === 0) ? 'integer' : 'real';
next_child.ele(tag_type).txt(next.toString());
} else if (isDate(next)) {
next_child.ele('date').raw(ISODateString(new Date(next)));
} else if (isBoolean(next)) {
val = next ? 'true' : 'false';
next_child.ele(val);
} else if (isString(next)) {
next_child.ele('string').text(next);
}
}
| JavaScript | 0 | @@ -2670,19 +2670,19 @@
'date').
-raw
+txt
(ISODate
@@ -2859,17 +2859,16 @@
ring').t
-e
xt(next)
|
a365069f4c00d47a849348146298a9b0e449628b | Remove version warning message in functions emulator (#504) | lib/functionsEmulator.js | lib/functionsEmulator.js | 'use strict';
var _ = require('lodash');
var chalk = require('chalk');
var path = require('path');
var RSVP = require('rsvp');
var getProjectId = require('./getProjectId');
var utils = require('./utils');
var parseTriggers = require('./parseTriggers');
var functionsConfig = require('./functionsConfig');
var ensureDefaultCredentials = require('./ensureDefaultCredentials');
var track = require('./track');
var EmulatorController;
var FunctionsEmulator = function(options) {
this.controller = null;
this.emulatedFunctions = [];
this.options = options;
this.config = {};
this.triggers = [];
this.urls = {};
};
var _pollOperation = function(op, controller) {
return new RSVP.Promise(function(resolve, reject) {
var poll = function() {
controller.client.getOperation(op[0].name)
.then(function(results) {
var operation = results[0];
if (operation.done) {
if (operation.response) {
resolve(operation.response.value);
} else {
reject(operation.error || new Error('Deployment failed'));
}
} else {
setTimeout(poll, 500);
}
})
.catch(reject);
};
poll();
});
};
var _getProviderString = function(eventType) {
var provider = _.last(eventType.split('/')[1].split('.'));
return _.capitalize(provider);
};
FunctionsEmulator.prototype.stop = function() {
delete process.env.FIREBASE_PROJECT;
delete process.env.GCLOUD_PROJECT;
var controller = this.controller;
return new RSVP.Promise(function(resolve) {
if (controller) {
controller.stop().then(resolve);
// Force-kill controller after 0.5 s
setInterval(function() {
controller.kill().then(resolve);
}, 500);
} else {
resolve();
}
});
};
FunctionsEmulator.prototype._getPorts = function() {
var portsConfig = {
supervisorPort: this.options.port,
restPort: this.options.port + 1,
grpcPort: this.options.port + 2
};
if (_.includes(this.options.targets, 'hosting')) {
return _.mapValues(portsConfig, function(port) {
return port + 1; // bump up port numbers by 1 so hosting can be served on first port
});
}
return portsConfig;
};
FunctionsEmulator.prototype.start = function(shellMode) {
shellMode = shellMode || false;
var options = this.options;
var projectId = getProjectId(options);
var emulatedFunctions = this.emulatedFunctions;
var instance = this;
var functionsDir = path.join(options.config.projectDir, options.config.get('functions.source'));
var ports = this._getPorts();
var controllerConfig = _.merge({tail: true, service: 'rest'}, ports);
var firebaseConfig;
var emulatedProviders = {};
try {
// Require must be inside try/catch, since it's an optional dependency. As well, require may fail if node version incompatible.
var emulatorConfig = require('@google-cloud/functions-emulator/src/config');
// Must set projectId here instead of later when initializing the controller,
// otherwise emulator may crash since it is looking for a config file in /src/options.js
emulatorConfig.set('projectId', projectId); // creates config file in a directory known to the emulator
EmulatorController = require('@google-cloud/functions-emulator/src/cli/controller');
} catch (err) {
var msg = err;
if (process.version !== 'v6.9.1') {
msg = 'Please use Node version v6.9.1, you have ' + process.version + '\n';
}
utils.logWarning(chalk.yellow('functions:') + ' Cannot start emulator. ' + msg);
return RSVP.reject();
}
this.controller = new EmulatorController(controllerConfig);
var controller = this.controller;
utils.logBullet(chalk.cyan.bold('functions:') + ' Preparing to emulate functions.');
ensureDefaultCredentials();
return functionsConfig.getFirebaseConfig(projectId, options.instance)
.then(function(result) {
firebaseConfig = JSON.stringify(result);
process.env.FIREBASE_PROJECT = firebaseConfig;
process.env.GCLOUD_PROJECT = projectId;
return controller.start();
}).then(function() {
return parseTriggers(projectId, functionsDir, firebaseConfig);
}).catch(function(e) {
utils.logWarning(chalk.yellow('functions:') + ' Failed to load functions source code. ' +
'Ensure that you have the latest SDK by running ' + chalk.bold('npm i --save firebase-functions') +
' inside the functions directory.');
return RSVP.reject(e);
}).then(function(triggers) {
instance.triggers = triggers;
var promises = _.map(triggers, function(trigger) {
if (trigger.httpsTrigger) {
return controller.deploy(trigger.name, {
localPath: functionsDir,
triggerHttp: true
}).catch(function() {
return RSVP.reject({name: trigger.name});
});
}
if (!shellMode) {
return RSVP.resolve(); // Don't emulate non-HTTPS functions if shell not running
}
var parts = trigger.eventTrigger.eventType.split('/');
var triggerProvider = parts[1];
var triggerEvent = parts[3];
return controller.deploy(trigger.name, {
localPath: functionsDir,
triggerProvider: triggerProvider,
triggerEvent: triggerEvent,
triggerResource: trigger.eventTrigger.resource
});
});
return RSVP.allSettled(promises);
}).then(function(operations) {
return RSVP.all(_.map(operations, function(operation) {
if (operation.state === 'rejected') {
utils.logWarning(chalk.yellow('functions:') + ' Failed to emulate ' + operation.reason.name);
return RSVP.resolve();
}
if (!operation.value) {
return RSVP.resolve(); // Emulation was not attempted
}
return _pollOperation(operation.value, controller).then(function(res) {
var funcName = _.chain(res).get('name').split('/').last().value();
emulatedFunctions.push(funcName);
if (res.httpsTrigger) {
emulatedProviders.HTTPS = true;
var message = chalk.green.bold('functions: ') + funcName;
instance.urls[funcName] = res.httpsTrigger.url;
if (!shellMode) {
message += ': ' + chalk.bold(res.httpsTrigger.url);
}
utils.logSuccess(message);
} else {
var provider = _getProviderString(res.eventTrigger.eventType);
emulatedProviders[provider] = true;
utils.logSuccess(chalk.green.bold('functions: ') + funcName);
}
});
}));
}).then(function() {
var providerList = _.keys(emulatedProviders).sort().join(',');
if (emulatedFunctions.length > 0) {
track('Functions Emulation', providerList, emulatedFunctions.length);
} else {
return instance.stop();
}
}).catch(function(e) {
if (e) {
utils.logWarning(chalk.yellow('functions:') + ' Error from emulator. ' + e);
}
return instance.stop();
});
};
module.exports = FunctionsEmulator;
| JavaScript | 0 | @@ -3367,136 +3367,8 @@
rr;%0A
- if (process.version !== 'v6.9.1') %7B%0A msg = 'Please use Node version v6.9.1, you have ' + process.version + '%5Cn';%0A %7D%0A
|
29f263950a3ea5dc70a5aec6066fe2c7391c2887 | Fix a bug in cache callback. | lib/cache.js | lib/cache.js | var http = require("http"),
url = require("url"),
util = require("util");
var map = {},
head = null,
tail = null,
size = 512,
n = 0;
var headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.36 (KHTML, like Gecko) Chrome/13.0.767.1 Safari/534.36"
};
module.exports = function(key, callback) {
var value = map[key];
// If this value is in the cache…
if (value) {
// Move it to the front of the least-recently used list.
if (value.previous) {
value.previous.next = value.next;
if (value.next) value.next.previous = value.previous;
else tail = value.previous;
value.previous = null;
value.next = head;
head.previous = value;
head = value;
}
// If the value is loaded, callback.
// Otherwise, add the callback to the list.
return value.callbacks
? value.callbacks.push(callback)
: callback(value.value);
}
// Otherwise, add the value to the cache.
value = map[key] = {
key: key,
next: head,
previous: null,
callbacks: [callback]
};
// Add the value to the front of the least-recently used list.
if (head) head.previous = value;
else tail = value;
head = value;
n++;
util.log(key);
// Load the requested resource!
var u = url.parse(key);
http.get({
host: u.host,
port: u.port,
path: u.pathname + (u.search ? "?" + u.search : ""),
headers: headers
}, function(response) {
var body = new Buffer(+response.headers['content-length'] || 2048), // TODO realloc
offset = 0;
response
.on("data", function(chunk) {
offset += chunk.copy(body, offset);
})
.on("end", function() {
value.value = body.slice(0, offset);
value.callbacks.forEach(function(callback) { callback(value.value); });
delete value.callbacks;
});
}).on("error", function(error) {
callback(null);
});
flush();
};
// Flush any extra values.
function flush() {
for (var value = tail; n > size && value; value = value.previous) {
n--;
delete map[value.key];
if (value.next) value.next.previous = value.previous;
else if (tail = value.previous) tail.next = null;
if (value.previous) value.previous.next = value.next;
else if (head = value.next) head.previous = null;
}
}
| JavaScript | 0 | @@ -1723,24 +1723,137 @@
unction() %7B%0A
+ var callbacks = value.callbacks;%0A delete value.callbacks; // must be deleted before callback!%0A
va
@@ -1897,22 +1897,16 @@
-value.
callback
@@ -1967,42 +1967,8 @@
%7D);%0A
- delete value.callbacks;%0A
|
3a58de3460047f8151e31ed8b506abe0f8a29bf9 | Update cache.js | lib/cache.js | lib/cache.js | var catchallDir = '/usr/local/etc/catchall',
cacheDir = catchallDir + "/cache";
var cfg = require('yaconfig').file(catchallDir + "/cached.json"),
fs = require('fs'),
crypto = require('crypto'),
path = require('path');
//yaconfig makes our directories - this is fine.
try {
fs.mkdirSync(cacheDir, 0777);
} catch(e) {
}
function _cacheKey(source) {
return crypto.createHash('md5').update(source).digest("hex");
}
function _cachePath(key) {
return cacheDir + "/" + key + ".cache";
}
function exists(path) {
try {
fs.lstatSync(path);
return true;
} catch(e) {
return false;
}
}
exports.get = function(source, lastModified, callback) {
var key = _cacheKey(source);
//no cache?
if(!cfg.get(key)) return callback(true);
//old cache?
if(cfg.get(key) < lastModified.getTime()) return callback(true);
var cachePath = _cachePath(key);
//exists? necessary to beat race condition with http requests
if(!exists(cachePath)) return callback(true);
callback(null, cachePath);
}
exports.set = function(source, lastModified, content, callback) {
var key = _cacheKey(source);
cfg.set(key, lastModified.getTime());
fs.writeFile(_cachePath(key), content);
} | JavaScript | 0.00036 | @@ -16,23 +16,9 @@
= '
-/usr/local/etc/
+.
catc
@@ -1217,12 +1217,13 @@
content);%0A%0A%7D
+%0A
|
788bbb94da9be5d8f0a8b0b5b173d1a6e463a50e | use native isArray method | lib/check.js | lib/check.js |
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path');
/**
* Initialize a `check` instance with the given filename.
*
* @param {String} filename
* @api public
*/
module.exports = function(filename) {
return new check(filename);
};
/**
* Initialize a new `check` with the given filename.
*
* @param {String} filename
* @api private
*/
function check(filename) {
this.filename = filename || '';
this.types = [];
this.valid = null;
};
/**
* Set valid file types.
*
* @param {Array|String} types
* @api public
*/
check.prototype.accept = function(types) {
this.types = types;
return this;
};
/**
* Catch if the filename has passed the validation.
*
* @param {Function} fn
* @api public
*/
check.prototype.pass = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result && fn(filename, type);
});
return this;
};
/**
* Catch if the filename failed to validate.
*
* @param {Function} fn
* @api public
*/
check.prototype.fail = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result || fn(filename, type);
});
return this;
};
/**
* Check if a file exists and matches the specified file types.
*
* @param {Function} fn
* @api private
*/
check.prototype._validate = function(fn) {
var type = path.extname(this.filename).substr(1)
, hasType = !!this.types.length
, isTypeAccepted = isArray(this.types)
? (!!~this.types.indexOf(type))
: (this.types === type);
if (this.valid !== null) {
fn(this.valid, type);
} else {
fs.stat(this.filename, function(err, stats) {
var result
= this.valid
= hasType
? (stats && stats.isFile() && isTypeAccepted && true || false)
: (stats && stats.isFile() && true || false);
fn(result, type);
});
}
return this;
};
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
| JavaScript | 0.00007 | @@ -1505,16 +1505,22 @@
epted =
+Array.
isArray(
@@ -1972,99 +1972,4 @@
;%0A %0A
-%0Afunction isArray(obj) %7B%0A return Object.prototype.toString.call(obj) === '%5Bobject Array%5D';%0A%7D;%0A
|
816203edee083d829f93072da5bcf320e7305e08 | fix pypo | lib/handlers/hydrater.js | lib/handlers/hydrater.js | 'use strict';
/**
* @file Define the hydrater endpoint
*
* Will queue requests onto the system file
*
*/
var restify = require('restify');
/**
* This handler receives a document on a POST request and process the document.
*
* @param {Object} req Request object from the client
* @param {Object} res Response we want to return
* @param {Object} server Current server. See implementation in index.js
* @param {Function} next Callback to call once res has been populated.
*/
module.exports = function(req, res, server, logger, next) {
if(!req.params.file_path) {
return next(new restify.BadMethodError('No file to process'));
} else if(!req.params.callback && !req.params.long_poll) {
return next(new restify.BadMethodError('No specified callback'));
}
// Push the new task to the queue
var task = {};
task.file_path = req.params.file_path;
task.callback = req.params.callback;
if(req.params.long_poll) {
task.res = res;
task.next = next;
delete req.params.long_poll;
}
else {
res.send(202);
next();
}
task.document = req.params.document;
task.document.metadatas = task.document.metadatas || {};
task.document.datas = task.document.datas || {};
// Add this new task to queue
server.queue.push(task);
logger("Queuing: " + task.file_path);
};
| JavaScript | 0.000003 | @@ -773,16 +773,18 @@
));%0A %7D%0A
+%0A%0A
// Pus
@@ -908,16 +908,17 @@
llback;%0A
+%0A
if(req
@@ -1061,16 +1061,17 @@
();%0A %7D%0A
+%0A
task.d
@@ -1244,16 +1244,16 @@
o queue%0A
-
server
@@ -1271,16 +1271,17 @@
(task);%0A
+%0A
logger
|
ab2e7b39c16d371cb4127313e827476ee703bd86 | clean up | lib/import-cable-type.js | lib/import-cable-type.js | /**
* @fileOverview read a csv file with cable type details and insert the cable types in mongo.
* @author Dong Liu
*/
var csv = require('csv'),
fs = require('fs'),
path = require('path'),
mongoose = require('mongoose'),
CableType = require('../model/meta.js').CableType;
var inputPath, realPath, db, line = 0,
types = [],
parser, processed = 0,
success = 0;
if (process.argv.length === 3) {
inputPath = process.argv[2];
} else {
console.warn('needs exact one argument for the input csv file path');
process.exit(1);
}
realPath = path.resolve(process.cwd(), inputPath);
if (!fs.existsSync(realPath)) {
console.warn(realPath + ' does not exist.');
console.warn('Please input a valid csv file path.');
process.exit(1);
}
mongoose.connect('mongodb://localhost/cable_frib');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('db connected');
});
// stream = fs.createReadStream(__dirname + '/' + fileName);
function createType(types, i) {
CableType.create({
name: types[i][4] + 'C_' + types[i][5] + '_' + types[i][6] + '_' + types[i][1],
service: types[i][3],
conductorNumber: types[i][4],
conductorSize: types[i][5],
fribType: types[i][6],
typeNumber: types[i][1],
pairing: types[i][7],
shielding: types[i][8],
outerDiameter: types[i][9],
voltageRating: types[i][10],
raceway: types[i][11],
tunnelHotcell: (types[i][12] === 'yes'),
otherRequirements: types[i][13],
createdBy: 'system',
createdOn: Date.now()
}, function (err, doc) {
processed += 1;
if (err) {
console.log(err);
} else {
success += 1;
console.log('New type created with id: ' + doc.id);
}
if (processed === types.length) {
console.log(processed + 'types were processed, and ' + success + ' types were inserted. Bye.');
mongoose.connection.close();
process.exit();
}
});
}
parser = csv.parse();
parser.on('readable', function () {
var record;
do {
record = parser.read();
if (!!record) {
line += 1;
console.log('read ' + line + ' lines ...');
if (record.length > 2 && record[1].length === 3) {
types.push(record);
}
}
} while (!!record);
});
parser.on('error', function (err) {
console.log(err.message);
});
parser.on('finish', function () {
var i;
for (i = 0; i < types.length; i += 1) {
createType(types, i);
}
});
fs.createReadStream(realPath).pipe(parser);
| JavaScript | 0.000001 | @@ -964,70 +964,8 @@
);%0A%0A
-// stream = fs.createReadStream(__dirname + '/' + fileName);%0A%0A
func
|
a931624215682a5608bd496ad5145d1dbc5875d3 | Move init to #run | lib/impulse-bin/index.js | lib/impulse-bin/index.js | /**
* Modules for commander.js and others
*
* Licensed under MIT.
* Copyright (c) 2013 David Smith <https://github.com/codeactual/>
*/
/*jshint node:true*/
'use strict';
module.exports = {
ImpulseBin: ImpulseBin,
create: function() { return new ImpulseBin(); },
extend: function(ext) { extend(ImpulseBin.prototype, ext); }
};
var util = require('util');
var sprintf = util.format;
var requireComponent = require('../component/require');
var configurable = requireComponent('configurable.js');
var extend = requireComponent('extend');
function ImpulseBin() {
this.settings = {
adapter: 'commander',
quietOption: 'quiet',
requiredOptionTmpl: '--%s is required',
verboseOption: 'verbose',
verboseLogName: '[verbose]',
stdoutLogName: '[stdout]',
stderrLogName: '[stderr]'
};
// Assigned in run():
this.adapter = null; // Ex. require('./lib/adapter/commander.js')
this.options = {}; // Ex, commander options object from adapter
this.provider = null; // Ex. commander module after parse()
this.console = require('long-con').create();
this.verbose = this.createVerbose();
}
configurable(ImpulseBin.prototype);
/**
* Wrap adapter require() for stubbing.
*
* @param {string} name Ex. 'commander'
*/
ImpulseBin.prototype.loadAdapter = function(name) {
return require('../adapter/' + this.get('adapter'));
};
/**
* Run the module (function) with a prepared context.
*
* @param {object} provider Ex. commander.js parse() output
* @param {function} handler Handles CLI options/args from provider
*/
ImpulseBin.prototype.run = function(provider, handler) {
var self = this;
var bind = requireComponent('bind');
var each = requireComponent('each');
var extend = requireComponent('extend');
this.adapter = this.loadAdapter();
this.options = this.adapter.options(provider);
this.provider = provider;
this.stderr = this.console.create(this.get('stderrLogName'), console.error, 'red');
this.stdout = this.console.create(this.get('stdoutLogName'), console.log);
this.console.set('quiet', this.options[this.get('quietOption')]);
var context = {
args: this.adapter.args(provider),
child_process: require('child_process'),
clc: this.clc,
fs: require('fs'),
options: this.options,
provider: provider,
shelljs: require('outer-shelljs').create(),
util: util
};
handler.call(extend(context, this));
};
ImpulseBin.prototype.createVerbose = function(name) {
if (!this.options[this.get('verboseOption')]) { return impulseBinNoOp; }
return this.console.create(this.get('verboseLogName'), console.log);
};
ImpulseBin.prototype.exit = function(msg, code) {
this.stderr(msg);
process.exit(typeof code === 'undefined' ? 1 : code);
};
/**
* Exit if the given CLI options are undefined.
*
* @param {string|array} key
* @param {number} exitCode
*/
ImpulseBin.prototype.exitOnMissingOption = function(key, exitCode) {
var self = this;
[].concat(key).forEach(function(key) {
if (typeof self.options[key] === 'undefined') {
self.exit(sprintf(self.get('requiredOptionTmpl'), key), exitCode);
}
});
};
ImpulseBin.prototype.exitOnShelljsErr = function(res) {
if (res.code !== 0) { this.exit(res.output, res.code); }
};
function defClrFn(str) { return str; }
function impulseBinNoOp() {}
| JavaScript | 0.00001 | @@ -1085,47 +1085,8 @@
();%0A
- this.verbose = this.createVerbose();%0A
%7D%0A%0Ac
@@ -1990,16 +1990,55 @@
le.log);
+%0A this.verbose = this.createVerbose();
%0A%0A this
|
d8625ff5fc7609b2be1f3238a0f7d0db2b639d50 | update mbtiles log message | lib/interfaces/charts.js | lib/interfaces/charts.js | /*
* Copyright 2017 Teppo Kurki <teppo.kurki@iki.fi>
*
* 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.
*/
const debug = require('debug')('signalk-server:interfaces:charts')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
const _ = require('lodash')
const pathPrefix = '/signalk'
const versionPrefix = '/v1'
const apiPathPrefix = pathPrefix + versionPrefix + '/api/'
const parseStringAsync = Promise.promisify(require('xml2js').parseString)
const path = require('path')
const express = require('express')
const chartProviders = {}
module.exports = function (app) {
let chartBaseDir
const api = {}
api.start = function () {
debug('Starting charts interface')
chartBaseDir = path.join(app.config.configPath, 'public', 'mapcache')
if (app.config.configPath != app.config.appPath) {
debug('using mapcache from config dir')
app.use('/mapcache', express.static(chartBaseDir))
}
app.get(apiPathPrefix + 'resources/charts/*', (req, res, next) => {
loadCharts(chartBaseDir, app, req).then(charts => {
var parts = req.path.split('/')
var chart_parts = parts.slice(6)
if (typeof charts[chart_parts[0]] !== 'undefined') {
res.json(charts[chart_parts[0]])
} else {
res.status(404).send('Not found')
}
})
})
app.get(apiPathPrefix + 'resources/charts', (req, res, next) => {
loadCharts(chartBaseDir, app, req)
.then(charts => {
res.json(charts)
})
.catch(err => {
console.error(err.message)
res.json({})
})
})
app.get('/charts/:map/:z/:x/:y', (req, res) => {
const { map, z, x, y } = req.params
const provider = chartProviders[map]
if (!provider) {
res.sendStatus(404)
return
}
provider.getTile(z, x, y, (err, tile, headers) => {
if (err && err.message && err.message === 'Tile does not exist') {
res.sendStatus(404)
} else if (err) {
console.error(`Error fetching tile ${map}/${z}/${x}/${y}:`, err)
res.sendStatus(500)
} else {
headers['Cache-Control'] = 'public, max-age=7776000' // 90 days
res.writeHead(200, headers)
res.end(tile)
}
})
})
}
api.stop = function () {}
return api
}
function loadCharts (chartBaseDir, app, req) {
return fs
.readdirAsync(chartBaseDir)
.then(files => {
return Promise.props(
files
.map(filename => ({
filename,
fullFilename: path.join(chartBaseDir, filename)
}))
.reduce((acc, { filename, fullFilename }) => {
acc[filename] = fs
.statAsync(fullFilename)
.then(stat => {
if (stat.isDirectory()) {
return directoryToMapInfo(fullFilename, filename)
} else {
return fileToMapInfo(fullFilename, filename)
}
})
.catch(err => {
console.error(err + ' ' + filename)
if (
err.toString() ===
"Error: Cannot find module '@mapbox/mbtiles'"
) {
console.error(
'For mbtiles support please run npm install @mapbox/mbtiles'
)
}
return undefined
})
return acc
}, {})
)
})
.catch(err => {
console.error(err.message)
return {}
})
}
function directoryToMapInfo (fullDirname, dirname) {
const resourceFile = path.join(fullDirname, 'tilemapresource.xml')
return fs
.readFileAsync(resourceFile)
.then(resXml => {
return parseStringAsync(resXml)
})
.then(parsed => {
const result = parsed.TileMap
var scale = '250000'
if (typeof result.Metadata !== 'undefined') {
var metaScale = result.Metadata[0]['$'].scale
if (typeof metaScale !== 'undefined') scale = metaScale
}
return {
identifier: dirname,
name: result.Title[0],
description: result.Title[0],
tilemapUrl: '/mapcache/' + dirname,
scale: parseInt(scale)
}
})
.catch(err => {
console.error('Error reading ' + resourceFile + ' ' + err.message)
return undefined
})
}
function fileToMapInfo (fullFilename, filename) {
debug(fullFilename)
return new Promise((resolve, reject) => {
const MBTiles = require('@mapbox/mbtiles')
new MBTiles(fullFilename, (err, mbtiles) => {
if (err) {
reject(err)
return
}
mbtiles.getInfo((err, mbtilesData) => {
if (err) {
reject(err)
return
}
if (_.isUndefined(mbtilesData) || _.isUndefined(mbtilesData.bounds)) {
resolve(undefined)
return
}
chartProviders[filename] = mbtiles
resolve({
identifier: filename,
name: mbtilesData.name || mbtilesData.id,
description: mbtilesData.description,
bounds: mbtilesData.bounds,
minzoom: mbtilesData.minzoom,
maxzoom: mbtilesData.maxzoom,
format: mbtilesData.format,
tilemapUrl: '/charts/' + filename + '/{z}/{x}/{y}',
type: 'tilelayer',
scale: '250000'
})
})
})
})
}
| JavaScript | 0 | @@ -3795,72 +3795,271 @@
ror(
-%0A 'For mbtiles support please run npm install
+'Please install mbtiles support with ')%0A console.error('npm install @mapbox/mbtiles')%0A console.error('or if you installed from npm with -g ')%0A console.error(%0A 'sudo npm install -g --unsafe-perm
@ma
|
30b8c22189d25378d3db1e986b30d6766776da34 | fix js message when no collection | Resources/public/arkounay_image_bundle.js | Resources/public/arkounay_image_bundle.js | // Refresh thumbnails :
function readURL(input, $img) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img.show();
$img.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function refreshThumbnail(){
$(".form-with-image .form-image input[type=file]").change(function(){
readURL(this, $(this).closest('.row').find('.js-img'));
});
}
refreshThumbnail();
$(function(){
function updateImageFromPath($pacImage) {
var val = $pacImage.find('.arkounay-image-path').val();
if (val !== '') {
$pacImage.find('img').attr('src', val);
}
}
function submitFile(file, $image) {
var formData = new FormData();
formData.append('file', file);
var $progress = $image.find('progress');
$.ajax({
url: url,
type: 'POST',
xhr: function () {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$progress.show();
$progress.attr({value: e.loaded, max: e.total});
} else {
$progress.hide();
}
}, false);
}
return xhr;
},
success: function (res) {
if (res[0] !== false) {
$image.find('.arkounay-image-path').val(res[0]);
updateImageFromPath($image);
} else {
alert("Le fichier spécifié (" + file.name + ") n'a pas pu être envoyé sur le serveur.\n\nSeules les images sont autorisés.");
}
$progress.hide();
},
error: function() {
alert("Une erreur est survenue lors de l'envoi du fichier " + file.name + ".");
$progress.hide();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
var arkounayImageSel = '.arkounay-image';
$(document).on('click', '.arkounay-image-button-upload', function (e) {
e.preventDefault();
e.stopPropagation();
$(this).parent().find('.arkounay-image-file-input').click();
});
$(document).on('change', '.arkounay-image-file-input', function () {
var file = this.files[0];
submitFile(file, $(this).closest('.arkounay-image'));
});
$(document).on('drag dragstart dragend dragover dragenter dragleave drop', arkounayImageSel, function(e) {
e.preventDefault();
e.stopPropagation();
})
.on('dragover dragenter', arkounayImageSel, function() {
$(this).addClass('is-dragover');
})
.on('dragleave dragend drop', arkounayImageSel, function() {
$(this).removeClass('is-dragover');
})
.on('drop', arkounayImageSel, function(e) {
submitFile(e.originalEvent.dataTransfer.files[0], $(this))
});
$(document).on('change', '.arkounay-image-path', function () {
updateImageFromPath($(this).closest('.arkounay-image'));
});
$.each($(arkounayImageSel), function(i, el) {
updateImageFromPath($(el));
});
$('.arkounay-image-collection').collection({
up: '<a href="#">▲</a>',
down: '<a href="#">▼</a>',
add: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> ' + addStr + '</a>',
remove: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-trash"></span> Supprimer</a>',
duplicate: '<a href="#">[ # ]</a>',
add_at_the_end: true
});
}); | JavaScript | 0.000001 | @@ -3469,16 +3469,30 @@
%7D);%0A%0A
+ $collection =
$('.ark
@@ -3515,16 +3515,67 @@
ection')
+;%0A if ($collection.length) %7B%0A $collection
.collect
@@ -3580,16 +3580,20 @@
ction(%7B%0A
+
@@ -3632,16 +3632,20 @@
+
down: '%3C
@@ -3678,16 +3678,20 @@
+
+
add: '%3Ca
@@ -3788,24 +3788,28 @@
r + '%3C/a%3E',%0A
+
remo
@@ -3921,16 +3921,20 @@
+
duplicat
@@ -3969,16 +3969,20 @@
+
+
add_at_t
@@ -3998,16 +3998,26 @@
rue%0A
-%7D);
+ %7D);%0A %7D
%0A%0A%7D);
|
a805017c4690ef9ccaf512269d1c250dcc8b52ff | Add support for --log-file. | lib/entry.js | lib/entry.js | var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var optimist = require('optimist');
var app = require('./web/app');
var settings = require('./settings');
var crawler = require('./crawler/app');
var utils = require('./utils');
var _ = require('underscore');
exports.run = function() {
var argv;
var child_args;
optimist = optimist.usage('Usage: $0 [-l 0.0.0.0] -p [port] -d [devops.json] [-D] [-c] [-h]');
optimist = optimist['default']('l', '0.0.0.0');
optimist = optimist.describe('l', 'Listening address');
optimist = optimist['default']('p', 3000);
optimist = optimist['default']('d', settings.saved_crawls_path);
optimist = optimist['default']('c', false);
optimist = optimist['default']('h', false);
optimist = optimist['default']('D', false);
optimist = optimist.alias('c', 'crawler');
optimist = optimist.describe('c', 'Run the crawler to update devops.json');
optimist = optimist.describe('D', 'Detach and run as a service');
optimist = optimist.alias('h', 'help');
optimist = optimist.describe('h', 'Print usage help');
argv = optimist.argv;
if (argv.h) {
optimist.showHelp(console.log);
} else if (argv.c) {
crawler.run(argv);
} else if (argv.D) {
child_args = process.argv.slice(2);
child_args = child_args.filter(function (element) {
return (element != '-D');
});
child_process.fork('./lib/entry.js', child_args);
process.exit();
} else {
app.run(argv);
console.log("Gutsy now listening on", argv.l + ":" + argv.p);
}
};
exports.run();
| JavaScript | 0 | @@ -358,16 +358,32 @@
ld_args;
+%0A var log_file;
%0A%0A opti
@@ -1018,24 +1018,93 @@
service');%0A
+ optimist = optimist.describe('log-file', 'File to log output to');%0A
optimist =
@@ -1265,30 +1265,48 @@
ole.log);%0A
-%7D else
+ process.exit();%0A %7D%0A%0A
if (argv.c)
@@ -1333,22 +1333,360 @@
rgv);%0A
-%7D else
+ process.exit();%0A %7D%0A%0A if (argv%5B'log-file'%5D) %7B%0A log_file = fs.createWriteStream(argv%5B'log-file'%5D, %7B flags: 'a' %7D);%0A // process.stderr.pipe(log_file) doesn't work in node 0.6 and later%0A process.__defineGetter__('stdout', function() %7B return log_file; %7D);%0A process.__defineGetter__('stderr', function() %7B return log_file; %7D);%0A %7D%0A%0A
if (arg
@@ -1910,18 +1910,10 @@
%0A %7D
- else %7B%0A
+%0A%0A
ap
@@ -1925,18 +1925,16 @@
(argv);%0A
-
consol
@@ -1989,20 +1989,16 @@
rgv.p);%0A
- %7D%0A
%7D;%0A%0Aexpo
|
539b3dd598b6e97ca80e7dd342e3d4713eba973b | Update copied and pasted test description | components/norg-app/test/norg-app.test.js | components/norg-app/test/norg-app.test.js | import { html, fixture, expect } from '@open-wc/testing';
import '../norg-app.js';
describe('NorgApp', () => {
it('renders the nodes table', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el.shadowRoot.querySelector('main')).lightDom.to.contain(
'norg-nodes-table');
});
it('changes the page if a menu link gets clicked', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
const drawer = el.shadowRoot.querySelector('mwc-drawer');
const button = drawer.querySelector('mwc-icon-button');
expect(drawer.open).to.be.false;
button.click();
expect(drawer.open).to.be.true;
});
it('matches the snapshot', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el).shadowDom.to.equalSnapshot();
});
it('passes the a11y audit', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
await expect(el).shadowDom.to.be.accessible({ignoredRules: ['aria-allowed-role']});
});
});
| JavaScript | 0 | @@ -344,51 +344,31 @@
t('c
-hanges the page if a menu link gets clicked
+ontrols the drawer menu
', a
|
b73a2af61ea5655fdbf3b53ff42a2a20f9817b92 | change resolving of cascades files | lib/faced.js | lib/faced.js | /*jslint node: true, nomen:true*/
"use strict";
var _ = require("underscore");
var OpenCV = require("opencv");
var Detector = require("./detector");
var cascades = {
"face": "../node_modules/opencv/data/haarcascade_frontalface_alt2.xml",
"mouth": "../node_modules/opencv/data/haarcascade_mcs_mouth.xml",
"nose": "../node_modules/opencv/data/haarcascade_mcs_nose.xml",
"eyeLeft": "../node_modules/opencv/data/haarcascade_mcs_lefteye.xml",
"eyeRight": "../node_modules/opencv/data/haarcascade_mcs_righteye.xml"
};
var Faced = function () {
var element;
this.cascades = {};
_.each(cascades, function (path, element) {
this.cascades[element] = new OpenCV.CascadeClassifier(__dirname + "/" + path);
}, this);
};
Faced.prototype.detect = function (path, fn, context) {
if (!this.cascades) {
throw new Error("Faced has been destroyed");
}
OpenCV.readImage(path, _.bind(function (err, img) {
var detector, size;
if (err || typeof img !== "object") {
return fn.call(context, undefined, undefined, path);
}
size = img.size();
if (size[0] === 0 || size[1] === 0) {
return fn.call(context, undefined, undefined, path);
}
detector = new Detector(this.cascades);
detector.run(img, function (faces) {
fn.call(context, faces, img, path);
});
}, this));
};
Faced.prototype.destroy = function () {
delete this.cascades;
}
module.exports = Faced; | JavaScript | 0 | @@ -143,16 +143,125 @@
ctor%22);%0A
+var path = require('path');%0A%0Avar hc_path = path.join( path.dirname(require.resolve(%22opencv%22)), '..', 'data');
%0Avar cas
@@ -286,37 +286,28 @@
e%22:
-%22../node_modules/opencv/data/
+path.join(hc_path, %22
haar
@@ -331,24 +331,26 @@
ce_alt2.xml%22
+)
,%0A %22mouth
@@ -356,37 +356,28 @@
h%22:
-%22../node_modules/opencv/data/
+path.join(hc_path, %22
haar
@@ -394,24 +394,26 @@
s_mouth.xml%22
+)
,%0A %22nose%22
@@ -418,37 +418,28 @@
e%22:
-%22../node_modules/opencv/data/
+path.join(hc_path, %22
haar
@@ -455,24 +455,26 @@
cs_nose.xml%22
+)
,%0A %22eyeLe
@@ -482,37 +482,28 @@
t%22:
-%22../node_modules/opencv/data/
+path.join(hc_path, %22
haar
@@ -526,16 +526,18 @@
eye.xml%22
+)
,%0A %22e
@@ -550,37 +550,28 @@
t%22:
-%22../node_modules/opencv/data/
+path.join(hc_path, %22
haar
@@ -595,16 +595,17 @@
eye.xml%22
+)
%0A%7D;%0A%0Avar
@@ -784,26 +784,8 @@
ier(
-__dirname + %22/%22 +
path
|
21e0366b6e16160d38cc14eec7d8fc0e0803350c | Fix lint | src/overridable.js | src/overridable.js | import React, {PureComponent} from 'react'
import {withPropsFromContext} from 'react-context-props'
export default (styles = {}, designName) => Target => {
class OverridableComponent extends PureComponent {
constructor(props) {
super(props)
this.designName = designName || Target.displayName || Target.name
this.Component = Target
}
getOverride() {
if (!this.props.design.getOverrideFor) {
return {...styles, ...this.props.styles}
}
const override = this.props.design.getOverrideFor(
Object.assign(Target, {designName: this.designName})
)
this.Component = override.Component
return {...styles, ...this.props.styles, ...override.css}
}
render() {
const {design, ...otherProps} = this.props // eslint-disable-line
const props = {...otherProps, styles: this.getOverride()}
return <this.Component {...props} />
}
}
OverridableComponent.displayName = Target.displayName || Target.name
OverridableComponent.defaultProps = {
design: {},
styles: {},
}
return withPropsFromContext(['design'])(OverridableComponent)
}
| JavaScript | 0.000032 | @@ -8,16 +8,17 @@
React, %7B
+
PureComp
@@ -22,16 +22,17 @@
omponent
+
%7D from '
@@ -46,16 +46,17 @@
import %7B
+
withProp
@@ -67,16 +67,17 @@
mContext
+
%7D from '
@@ -436,32 +436,33 @@
return %7B
+
...styles, ...th
@@ -476,16 +476,17 @@
s.styles
+
%7D%0A
@@ -575,16 +575,17 @@
arget, %7B
+
designNa
@@ -603,16 +603,17 @@
signName
+
%7D)%0A
@@ -671,16 +671,17 @@
return %7B
+
...style
@@ -720,16 +720,17 @@
ride.css
+
%7D%0A %7D%0A
@@ -758,16 +758,17 @@
const %7B
+
design,
@@ -780,16 +780,17 @@
herProps
+
%7D = this
@@ -840,16 +840,17 @@
rops = %7B
+
...other
@@ -882,16 +882,17 @@
erride()
+
%7D%0A
|
f1d2871905f49a3c2597d124e3edfe1bbd67518d | _parent._parent in event | lib/event/index.js | lib/event/index.js | 'use strict'
const delegateEvent = require('./delegate')
const addListener = require('./listener')
exports.properties = {
hasEvents: true
}
exports.on = {
Child: {
define: {
eventCache: {
value: {}
},
key: {
set (val) {
this.parent.parent.setKey('hasEvents', true, false)
const cache = this.eventCache
if (!cache[val]) {
cache[val] = true
addListener(val, (e) => delegateEvent(val, e))
}
this._key = val
},
get (val) {
return this._key
}
}
}
}
}
| JavaScript | 1 | @@ -249,32 +249,68 @@
set (val) %7B%0A
+ // dangerous for context!%0A
this.p
@@ -308,23 +308,25 @@
this.
+_
parent.
+_
parent.s
|
9feff4f992b27bf75eeca193d1b48d3d5909949e | Fix jshint error. | src/pat/depends.js | src/pat/depends.js | /**
* Patterns depends - show/hide/disable content based on form status
*
* Copyright 2012-2013 Florian Friesdorf
* Copyright 2012-2013 Simplon B.V. - Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"../registry",
"../core/logger",
"../lib/dependshandler",
"../core/parser"
], function($, patterns, logging, DependsHandler, Parser) {
var log = logging.getLogger("depends"),
parser = new Parser("depends");
parser.add_argument("condition");
parser.add_argument("action", "show", ["show", "enable"]);
parser.add_argument("transition", "none", ["none", "css", "fade", "slide"]);
parser.add_argument("effect-duration", "fast");
parser.add_argument("effect-easing", "swing");
var depends = {
name: "depends",
trigger: ".pat-depends",
jquery_plugin: true,
transitions: {
none: {hide: "hide", show: "show"},
fade: {hide: "fadeOut", show: "fadeIn"},
slide: {hide: "slideUp", show: "slideDown"}
},
init: function($el, opts) {
return $el.each(function() {
var slave = this,
$slave = $(this),
options = parser.parse($slave, opts),
handler, state;
try {
handler=new DependsHandler($slave, options.condition);
} catch (e) {
log.error("Invalid condition: " + e.message);
return;
}
state=handler.evaluate();
switch (options.action) {
case "show":
if (state)
$slave.show();
else
$slave.hide();
break;
case "enable":
if (state)
depends._enable($slave);
else
depends._disable($slave);
break;
}
var data = {handler: handler,
options: options,
slave: slave};
handler.getAllInputs().each(function() {
if (this.form) {
var $form = $(this.form),
slaves = $form.data("patDepends.slaves");
if (!slaves) {
slaves=[data];
$form.on("reset.pat-depends", depends.onReset);
} else if (slaves.indexOf(data)===-1)
slaves.push(data);
$form.data("patDepends.slaves", slaves);
}
$(this).on("change.pat-depends", null, data, depends.onChange);
});
});
},
onReset: function(event) {
var slaves = $(this).data("patDepends.slaves"),
i;
setTimeout(function() {
for (i=0; i<slaves.length; i++) {
event.data=slaves[i];
depends.onChange(event);
}
}, 50);
},
_enable: function($slave) {
if ($slave.is(":input"))
$slave[0].disabled=null;
else if ($slave.is("a"))
$slave.off("click.patternDepends");
$slave.removeClass("disabled");
},
_disable: function($slave) {
if ($slave.is(":input"))
$slave[0].disabled="disabled";
else if ($slave.is("a"))
$slave.on("click.patternDepends", depends.blockDefault);
$slave.addClass("disabled");
},
_hide_or_show: function($slave, new_state, options) {
var duration = (options.transition==="css" || options.transition==="none") ? null : options.effect.duration;
$slave.removeClass("visible hidden in-progress");
var onComplete = function() {
$slave
.removeClass("in-progress")
.addClass(new_state ? "visible" : "hidden");
};
if (!duration) {
if (options.transition!=="css")
$slave[new_state ? "show" : "hide"]();
onComplete();
} else {
var t = depends.transitions[options.transition];
$slave.addClass("in-progress");
$slave[new_state ? t.show : t.hide]({
duration: duration,
easing: options.effect.easing,
complete: onComplete
});
}
},
onChange: function(event) {
var handler = event.data.handler,
options = event.data.options,
slave = event.data.slave,
$slave = $(slave),
state = handler.evaluate(),
duration = (options.transition==="css" || options.transition==="none") ? null : options.effect.duration;
switch (options.action) {
case "show":
depends._hide_or_show($slave, state, options);
break;
case "enable":
if (state)
depends._enable($slave);
else
depends._disable($slave);
break;
}
},
blockDefault: function(event) {
event.preventDefault();
}
};
patterns.register(depends);
return depends; // XXX for tests only
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -5006,129 +5006,8 @@
te()
-,%0A duration = (options.transition===%22css%22 %7C%7C options.transition===%22none%22) ? null : options.effect.duration
;%0A%0A
|
ef3c9923f653fbec4e4164b252efb06605c385ee | Fix linting errors | src/pat/masonry.js | src/pat/masonry.js | /**
* Patternslib pattern for Masonry
* Copyright 2015 Syslab.com GmBH
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([
"pat-registry",
"pat-parser",
"masonry",
"imagesloaded"
], function() {
return factory.apply(this, arguments);
});
} else {
factory(root.patterns, root.patterns.Parser, root.Masonry, root.imagesLoaded);
}
}(this, function(registry, Parser, Masonry, imagesLoaded) {
"use strict";
var parser = new Parser("masonry");
parser.add_argument("column-width");
parser.add_argument("container-style", "{ position: 'relative' }");
parser.add_argument("gutter");
parser.add_argument("hidden-style", "{ opacity: 0, transform: 'scale(0.001)' }");
parser.add_argument("is-fit-width", false);
parser.add_argument("is-origin-left", true);
parser.add_argument("is-origin-top", true);
parser.add_argument("item-selector", ".item");
parser.add_argument("stamp", "");
parser.add_argument("transition-duration", "0.4s");
parser.add_argument("visible-style", "{ opacity: 1, transform: 'scale(1)' }");
var masonry = {
name: "masonry",
trigger: ".pat-masonry",
init: function mypattern_init($el, opts) {
var options = parser.parse($el, opts);
imagesLoaded(this, $.proxy(function() {
new Masonry($el[0], {
columnWidth: this.getTypeCastedValue(options.columnWidth),
containerStyle: options.containerStyle,
gutter: this.getTypeCastedValue(options.gutter),
hiddenStyle: options.hiddenStyle,
isFitWidth: options.is['fit-width'],
isOriginTOp: options.is['origin-top'],
isOriginLeft: options.is['origin-left'],
itemSelector: options.itemSelector,
stamp: options.stamp,
transitionDuration: options.transitionDuration,
visibleStyle: options.visibleStyle,
});
}, this));
},
getTypeCastedValue: function (original) {
var val = Number(original);
if (isNaN(val)) {
val = original || 0;
}
return val;
}
};
registry.register(masonry);
}));
| JavaScript | 0.000075 | @@ -31,17 +31,16 @@
Masonry
-
%0A * Copy
@@ -129,17 +129,17 @@
===
-'
+%22
function
' &&
@@ -134,17 +134,17 @@
function
-'
+%22
&& defi
@@ -170,16 +170,38 @@
efine(%5B%0A
+ %22jquery%22,%0A
@@ -420,16 +420,24 @@
factory(
+root.$,
root.pat
@@ -522,16 +522,19 @@
unction(
+$,
registry
@@ -1867,17 +1867,17 @@
ions.is%5B
-'
+%22
fit-widt
@@ -1877,17 +1877,17 @@
it-width
-'
+%22
%5D,%0A
@@ -1932,25 +1932,25 @@
options.is%5B
-'
+%22
origin-top'%5D
@@ -1947,17 +1947,17 @@
igin-top
-'
+%22
%5D,%0A
@@ -2006,17 +2006,17 @@
ions.is%5B
-'
+%22
origin-l
@@ -2018,17 +2018,17 @@
gin-left
-'
+%22
%5D,%0A
@@ -2279,25 +2279,24 @@
visibleStyle
-,
%0A
|
9c48a19e7db09ae624a5249a17fa7cc50c3f062f | create require name for custom modules | lib/flow.client.js | lib/flow.client.js | var Flow = require('flow');
var server = require('./socket');
// init flow with core module
var CoreInst = Flow({
// load module bundles and return the entry-point exports
module: function (name, callback) {
// crate script dom element
var node = document.createElement('script');
node.onload = function () {
node.remove();
callback(null, require(name));
};
// set url and append dom script elm to the document head
node.src = name[0] === '/' ? '/app_module' : '/module/';
node.src += name + '/bundle.js';
document.head.appendChild(node);
},
// load composition
composition: function (name, callback) {
this.flow('C/' + name, {
net: '/',
to: '@'
}, function (err, composition) {
composition = JSON.parse(composition);
composition._roles = {'*': true};
callback(err, composition);
});
},
request: server.request,
// Load html snippets.
markup: function (urls, callback) {
var self = this;
var count = 0;
var snippets = {};
var errorHappend;
var next = function (url, index) {
self.flow(url, {net: '/'}, function (err, snippet) {
if (errorHappend) {
return;
}
if (err) {
errorHappend = true;
return callback(err);
}
snippets[url] = snippet;
if (++count === urls.length) {
callback(null, snippets, true);
}
});
};
urls.forEach(next);
},
// Load css files.
styles: function (urls) {
urls.forEach(function (url) {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', url);
global.document.head.appendChild(link);
});
},
reset: function () {
// reset module instances
CoreInst.reset();
// reset DOM body
document.body.innerHTML = '';
// remove styles
var styles = document.head.querySelectorAll('link[rel=stylesheet]');
if (styles) {
styles.forEach(function (stylesheet) {
stylesheet.remove();
});
}
// reset server
server.reset();
// load entrypoint
CoreInst.load('*');
}
});
CoreInst.load('*');
| JavaScript | 0 | @@ -357,32 +357,97 @@
node.remove();%0A
+ name = name%5B0%5D === '/' ? name + '/bundle.js' : name;%0A
call
|
8c649e6f89d391e7075315cab6ef9144b3554bd4 | Fix "Source Maps are off" | lib/global-eval.js | lib/global-eval.js | // we define a __exec for globally-scoped execution
// used by module format implementations
var __exec;
(function() {
var hasBtoa = typeof btoa != 'undefined';
function getSource(load) {
var lastLineIndex = load.source.lastIndexOf('\n');
// wrap ES formats with a System closure for System global encapsulation
var wrap = load.metadata.format != 'global';
var sourceMap = load.metadata.sourceMap;
if (sourceMap) {
if (typeof sourceMap != 'object')
throw new TypeError('load.metadata.sourceMap must be set to an object.');
if (sourceMap.mappings)
sourceMap.mappings = ';' + sourceMap.mappings;
sourceMap = JSON.stringify(sourceMap);
}
return (wrap ? '(function(System, SystemJS, require) {' : '') + load.source + (wrap ? '\n})(System, System);' : '')
// adds the sourceURL comment if not already present
+ (load.source.substr(lastLineIndex, 15) != '\n//# sourceURL='
? '\n//# sourceURL=' + load.address + (sourceMap ? '!transpiled' : '') : '')
// add sourceMappingURL if load.metadata.sourceMap is set
+ (sourceMap && hasBtoa && '\n//# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(sourceMap))) || '');
}
var curLoad;
// System.register, System.registerDynamic, AMD define pipeline
// if currently evalling code here, immediately reduce the registered entry against the load record
hook('pushRegister_', function() {
return function(register) {
if (!curLoad)
return false;
this.reduceRegister_(curLoad, register);
return true;
};
});
// System clobbering protection (mostly for Traceur)
var curSystem;
var callCounter = 0;
function preExec(loader, load) {
curLoad = load;
if (callCounter++ == 0)
curSystem = __global.System;
__global.System = __global.SystemJS = loader;
}
function postExec() {
if (--callCounter == 0)
__global.System = __global.SystemJS = curSystem;
curLoad = undefined;
}
__exec = function(load) {
if ((load.metadata.integrity || load.metadata.nonce) && supportsScriptExec)
return scriptExec.call(this, load);
try {
preExec(this, load);
curLoad = load;
(0, eval)(getSource(load));
postExec();
}
catch(e) {
postExec();
throw addToError(e, 'Evaluating ' + load.address);
}
};
var supportsScriptExec = false;
if (isBrowser && typeof document != 'undefined' && document.getElementsByTagName) {
var scripts = document.getElementsByTagName('script');
$__curScript = scripts[scripts.length - 1];
if (!(window.chrome && window.chrome.extension || navigator.userAgent.match(/^Node\.js/)))
supportsScriptExec = true;
}
// script execution via injecting a script tag into the page
// this allows CSP integrity and nonce to be set for CSP environments
var head;
function scriptExec(load) {
if (!head)
head = document.head || document.body || document.documentElement;
var script = document.createElement('script');
script.text = getSource(load, false);
var onerror = window.onerror;
var e;
window.onerror = function(_e) {
e = addToError(_e, 'Evaluating ' + load.address);
}
preExec(this, load);
if (load.metadata.integrity)
script.setAttribute('integrity', load.metadata.integrity);
if (load.metadata.nonce)
script.setAttribute('nonce', load.metadata.nonce);
head.appendChild(script);
head.removeChild(script);
postExec();
window.onerror = onerror;
if (e)
throw e;
}
})(); | JavaScript | 0 | @@ -564,94 +564,8 @@
);%0A%0A
- if (sourceMap.mappings)%0A sourceMap.mappings = ';' + sourceMap.mappings;%0A%0A
@@ -3536,8 +3536,9 @@
%7D%0A%0A%7D)();
+%0A
|
739dac61b706563a04eee791635094e1182ae4ea | remove commented out imports | troposphere/static/js/components/common/InstanceDetail.react.js | troposphere/static/js/components/common/InstanceDetail.react.js | import React from 'react';
import Router from 'react-router';
import Backbone from 'backbone';
import stores from 'stores';
import InstanceDetailsSection from 'components/projects/resources/instance/details/sections/InstanceDetailsSection.react';
import PastInstanceDetailsSection from 'components/projects/resources/instance/details/sections/PastInstanceDetailsSection.react';
import InstanceActionsAndLinks from 'components/projects/resources/instance/details/actions/InstanceActionsAndLinks.react';
import InstanceMetricsSection from 'components/projects/resources/instance/details/sections/InstanceMetricsSection.react';
import Instance from 'models/Instance';
import InstanceState from 'models/InstanceState';
import InstanceInfoSection from 'components/projects/resources/instance/details/sections/InstanceInfoSection.react';
// var React = require('react/addons'),
// Router = require('react-router'),
// Backbone = require('backbone'),
// BreadcrumbBar = require('components/projects/common/BreadcrumbBar.react'),
//
// InstanceDetailsSection = require('components/projects/resources/instance/details/sections/InstanceDetailsSection.react'),
//
//
// stores = require('stores'),
// Time = require('components/common/Time.react'),
// ResourceTags = require('components/projects/resources/instance/details/sections/ResourceTags.react'),
// actions = require('actions'),
// moment = require('moment'),
// CryptoJS = require('crypto-js'),
// Gravatar = require('components/common/Gravatar.react');
var InstanceDetail = React.createClass({
displayName: "InstanceDetail",
mixins: [Router.State],
getInitialState: function(){
return{
instance: stores.InstanceStore.get(this.getParams().id),
instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})
}
},
onNewData: function(){
this.setState({instance: stores.InstanceStore.get(this.getParams().id), instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})});
},
componentDidMount: function(){
stores.InstanceStore.addChangeListener(this.onNewData);
stores.InstanceHistoryStore.addChangeListener(this.onNewData);
stores.ProviderStore.addChangeListener(this.onNewData);
},
renderInactiveInstance: function(){
var instanceObj = new Instance(this.state.instanceHistory.models[0].get('instance')),
instanceStateObj = new InstanceState({"status_raw": "deleted"}),
image = this.state.instanceHistory.models[0].get('image'),
size = this.state.instanceHistory.models[0].get('size');
instanceObj.set('image', image);
instanceObj.set('size', size);
instanceObj.set('state', instanceStateObj);
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-6">
<InstanceInfoSection instance={instanceObj}/>
</div>
<div className="col-md-6">
<PastInstanceDetailsSection instance={instanceObj} />
</div>
</div>
<hr/>
</div>
);
},
renderActiveInstance: function(){
var instance = this.state.instance;
var metrics = typeof show_instance_metrics != "undefined" ? <InstanceMetricsSection instance={instance}/> : "";
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-9">
<InstanceInfoSection instance={instance}/>
<hr/>
<InstanceDetailsSection instance={instance} />
<hr/>
{metrics}
</div>
<div className="col-md-3">
<InstanceActionsAndLinks
project={null}
instance={instance}
/>
</div>
</div>
</div>
);
},
render: function(){
if(!this.state.instanceHistory){
return <div className="loading" />
}
return this.state.instance ? this.renderActiveInstance() : this.renderInactiveInstance();
},
});
export default InstanceDetail;
| JavaScript | 0 | @@ -830,731 +830,8 @@
';%0A%0A
- // var React = require('react/addons'),%0A // Router = require('react-router'),%0A // Backbone = require('backbone'),%0A // BreadcrumbBar = require('components/projects/common/BreadcrumbBar.react'),%0A //%0A // InstanceDetailsSection = require('components/projects/resources/instance/details/sections/InstanceDetailsSection.react'),%0A //%0A //%0A // stores = require('stores'),%0A // Time = require('components/common/Time.react'),%0A // ResourceTags = require('components/projects/resources/instance/details/sections/ResourceTags.react'),%0A // actions = require('actions'),%0A // moment = require('moment'),%0A // CryptoJS = require('crypto-js'),%0A // Gravatar = require('components/common/Gravatar.react');%0A%0A
var
|
d96c20cd158d9dc46e7138fffc42d724fe09d3df | make output resizable only when plugin present | present/js/play.js | present/js/play.js | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
function initPlayground(transport) {
"use strict";
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var output = document.createElement('div');
var outpre = document.createElement('pre');
var running;
// TODO(adg): check that jquery etc is loaded.
$(output).resizable({
handles: "n,w,nw",
minHeight: 27,
minWidth: 135,
maxHeight: 608,
maxWidth: 990
});
function onKill() {
if (running) running.Kill();
}
function onRun(e) {
onKill();
output.style.display = "block";
outpre.innerHTML = "";
run1.style.display = "none";
var options = {Race: e.shiftKey};
running = transport.Run(text(code), PlaygroundOutput(outpre), options);
}
function onClose() {
onKill();
output.style.display = "none";
run1.style.display = "inline-block";
}
var run1 = document.createElement('button');
run1.innerHTML = 'Run';
run1.className = 'run';
run1.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run1);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);
buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
}
| JavaScript | 0.00001 | @@ -764,55 +764,41 @@
%0A%0A%09%09
-// TODO(adg): check that jquery etc is loaded.%0A
+if ($ && $(output).resizable) %7B%0A%09
%09%09$(
@@ -820,16 +820,17 @@
le(%7B%0A%09%09%09
+%09
handles:
@@ -840,16 +840,17 @@
,w,nw%22,%0A
+%09
%09%09%09minHe
@@ -862,16 +862,17 @@
%0927,%0A%09%09%09
+%09
minWidth
@@ -878,16 +878,17 @@
h:%09135,%0A
+%09
%09%09%09maxHe
@@ -901,16 +901,17 @@
608,%0A%09%09%09
+%09
maxWidth
@@ -920,13 +920,18 @@
990%0A
+%09
%09%09%7D);
+%0A%09%09%7D
%0A%0A%09%09
|
828103f6d3ffc139dce1badf6d420cc990b0d77b | Use 'protocol' and 'host' from config.server | src/modules/socket/socket-client.js | src/modules/socket/socket-client.js | /* @flow */
import eio from 'engine.io-client/engine.io';
import { bus, config } from '../../core-client.js';
import * as models from '../../models/models.js';
import stringpack from 'stringpack';
const protocol = config.server.protocol, host = config.server.apiHost;
let backOff = 1, client;
const packer = stringpack(Object.keys(models).sort().map(key => models[key]));
function disconnected() {
/* eslint-disable no-use-before-define */
if (backOff < 256) {
backOff *= 2;
} else {
backOff = 256;
}
bus.emit('change', {
state: { connectionStatus: 'offline', backOff }
});
setTimeout(connect, backOff * 1000);
}
function onMessage(message) {
const changes = packer.decode(message);
changes.source = 'server';
bus.emit('change', changes);
}
function connect() {
client = new eio.Socket((protocol === 'https:' ? 'wss:' : 'ws:') + '//' + host, {
jsonp: 'document' in window && 'createElement' in window.document // Disable JSONP in non-web environments, e.g.- react-native
});
client.on('close', disconnected);
client.on('open', () => {
backOff = 1;
bus.emit('change', {
state: { connectionStatus: 'online', backOff }
});
});
client.on('message', onMessage);
}
bus.on('change', (changes) => {
if (changes.source === 'server') return;
const { state, ...filtered } = changes;
if (Object.keys(filtered).length) {
client.send(packer.encode(filtered));
}
}, 1);
connect();
| JavaScript | 0.000072 | @@ -202,33 +202,11 @@
nst
-protocol = config.server.
+%7B%0A%09
prot
@@ -210,21 +210,25 @@
rotocol,
-
+%0A%09
host
+,%0A%7D
= confi
@@ -239,17 +239,10 @@
rver
-.apiHost
;
+%0A
%0Alet
|
574c1c9dc1311238d216418855fa3b90dd219f72 | Add lib code | lib/index.js | lib/index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mockRes = exports.mockReq = undefined;
var _sinon = require('sinon');
var _sinon2 = _interopRequireDefault(_sinon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Returns a new mock request for use in testing.
var mockReq = exports.mockReq = function mockReq() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ret = {};
return Object.assign(ret, {
accepts: _sinon2.default.stub().returns(ret),
acceptsCharsets: _sinon2.default.stub().returns(ret),
acceptsEncodings: _sinon2.default.stub().returns(ret),
acceptsLanguages: _sinon2.default.stub().returns(ret),
body: {},
flash: _sinon2.default.stub().returns(ret),
get: _sinon2.default.stub().returns(ret),
is: _sinon2.default.stub().returns(ret),
params: {},
query: {},
session: {}
}, options);
};
// Returns a new mock response for use in testing.
var mockRes = exports.mockRes = function mockRes() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ret = {};
return Object.assign(ret, {
append: _sinon2.default.stub().returns(ret),
attachement: _sinon2.default.stub().returns(ret),
clearCookie: _sinon2.default.stub().returns(ret),
cookie: _sinon2.default.stub().returns(ret),
download: _sinon2.default.stub().returns(ret),
end: _sinon2.default.stub().returns(ret),
format: {},
get: _sinon2.default.stub().returns(ret),
headersSent: _sinon2.default.stub().returns(ret),
json: _sinon2.default.stub().returns(ret),
jsonp: _sinon2.default.stub().returns(ret),
links: _sinon2.default.stub().returns(ret),
locals: {},
location: _sinon2.default.stub().returns(ret),
redirect: _sinon2.default.stub().returns(ret),
render: _sinon2.default.stub().returns(ret),
send: _sinon2.default.stub().returns(ret),
sendFile: _sinon2.default.stub().returns(ret),
sendStatus: _sinon2.default.stub().returns(ret),
set: _sinon2.default.stub().returns(ret),
status: _sinon2.default.stub().returns(ret),
type: _sinon2.default.stub().returns(ret),
vary: _sinon2.default.stub().returns(ret)
}, options);
}; | JavaScript | 0.000007 | @@ -425,39 +425,38 @@
rguments.length
-%3C= 0 %7C%7C
+%3E 0 &&
arguments%5B0%5D ==
@@ -445,35 +445,35 @@
&& arguments%5B0%5D
+!
==
-=
undefined ? %7B%7D
@@ -460,37 +460,32 @@
!== undefined ?
- %7B%7D :
arguments%5B0%5D;%0A%0A
@@ -473,32 +473,37 @@
d ? arguments%5B0%5D
+ : %7B%7D
;%0A%0A var ret = %7B
@@ -1121,15 +1121,14 @@
gth
-%3C= 0 %7C%7C
+%3E 0 &&
arg
@@ -1141,11 +1141,11 @@
%5B0%5D
+!
==
-=
und
@@ -1156,13 +1156,8 @@
ed ?
- %7B%7D :
arg
@@ -1165,16 +1165,21 @@
ments%5B0%5D
+ : %7B%7D
;%0A%0A var
|
fed83241144ccd26079890088371170793d4796d | Add the translate module to the main index | lib/index.js | lib/index.js | this.interaction_machine = require("./interaction_machine");
this.InteractionMachine = this.interaction_machine.InteractionMachine;
this.app = require("./app");
this.App = this.app.App;
this.dummy = require("./dummy");
this.DummyApi = this.dummy.DummyApi;
this.tester = require("./tester");
this.AppTester = this.tester.AppTester;
this.config = require("./config");
this.user = require("./user");
this.promise = require("./promise");
this.states = require("./states/index");
this.metrics = require("./metrics");
this.http = require("./http");
this.utils = require("./utils");
this.test_utils = require("./test_utils");
this.fixtures = require("./fixtures");
| JavaScript | 0.000001 | @@ -569,24 +569,65 @@
%22./utils%22);%0A
+this.translate = require(%22./translate%22);%0A
this.test_ut
|
058514cacfa222b39c02d26df1648e47d86a7e93 | Remove unnecessary content from index.js | lib/index.js | lib/index.js | /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2016 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
/**
@class biojsiobiom
*/
/**
* Private Methods
*/
/*
* Public Methods
*/
/**
* Method responsible to say Hello
*
* @example
*
* biojsiobiom.hello('biojs');
*
* @method hello
* @param {String} name Name of a person
* @return {String} Returns hello name
*/
module.exports.hello = function (name) {
return 'hello ' + name;
};
//module.exports.Biom = require("./biojs-io-biom");
| JavaScript | 0.000006 | @@ -145,383 +145,22 @@
*/%0A%0A
-/**%0A@class biojsiobiom%0A */%0A%0A%0A%0A/**%0A * Private Methods%0A */%0A%0A/*%0A * Public Methods%0A */%0A%0A/**%0A * Method responsible to say Hello%0A *%0A * @example%0A *%0A * biojsiobiom.hello('biojs');%0A *%0A * @method hello%0A * @param %7BString%7D name Name of a person%0A * @return %7BString%7D Returns hello name%0A */%0A%0A%0Amodule.exports.hello = function (name) %7B%0A%0A return 'hello ' + name;%0A%7D;%0A%0A//module.exports.Biom
+module.exports
= r
|
e7b9ebc894ef7d58fd7405ff2c2c82dfcd4bace2 | Resolve lint issues in lib/index | lib/index.js | lib/index.js | /**
* An app that makes apps.
*
* @package appmaker
* @author Andrew Sliwinski <a@mozillafoundation.org>
*/
var Vue = require('vue');
var model = require('./model');
var router = require('./router');
// Restore user state
model.restore(function (err) {
if (err) throw new Error('Could not restore user state.');
// Register views
Vue.component('templates', require('../views/templates'));
Vue.component('apps', require('../views/apps'));
Vue.component('profile', require('../views/profile'));
Vue.component('detail', require('../views/detail'));
// Vue.component('play', require('../views/play'));
// Vue.component('edit', require('../views/edit'));
// Vue.component('block', require('../views/brick'));
// Create "app"
var app = new Vue({
el: '#app',
data: {
currentView: 'templates',
title: 'Templates'
}
});
// Route
router(app);
}); | JavaScript | 0 | @@ -744,20 +744,16 @@
ick'));%0A
-
%0A //
@@ -946,8 +946,9 @@
pp);%0A%7D);
+%0A
|
40701a683eb8a49625124fcc0c7aa80dc3f3104c | Group the differences | lib/index.js | lib/index.js | // Dependencies
var LevDist = require("levdist");
//function Change(removed, added, notModified,) {
// this._ = [removed, added];
// this.
//}
function Diff(oldLines, newLines, sensitivity) {
var self = this;
self.old_lines = oldLines;
self.new_lines = newLines;
self.sensitivity = sensitivity || 0;
self.changes = [];
// Convert to array
oldLines = typeof oldLines === "string" ? oldLines.split("\n") : oldLines;
newLines = typeof newLines === "string" ? newLines.split("\n") : newLines;
// Iterate the new lines
var cOldLine = null
, oldLineI = 0
;
debugger
newLines.forEach(function (cNewLine, i) {
cOldLine = oldLines[oldLineI];
if (cOldLine) {
++oldLineI;
}
self.changes.push({
_: [cOldLine, cNewLine]
, changes: LevDist(cOldLine, cNewLine)
});
});
}
Diff.prototype.toString = function () {
var self = this
, str = ""
, cDiff = { added: "", removed: "" }
;
self.changes.forEach(function (cChange) {
if (cChange.changes <= self.sensitivity) {
str += cDiff.removed;
str += cDiff.added;
str += " " + cChange._[1] + "\n"
} else {
cDiff.removed += " - " + cChange._[0] + "\n"
if (cChange._[1]) {
cDiff.added += " + " + cChange._[1] + "\n"
}
}
});
return str;
};
function LineDiff (oldLines, newLines, sensitivity) {
return new Diff(oldLines, newLines, sensitivity);
}
module.exports = LineDiff;
| JavaScript | 0.999991 | @@ -44,18 +44,16 @@
ist%22);%0A%0A
-//
function
@@ -80,26 +80,23 @@
ed,
-notModified,
+sensitivity
) %7B%0A
-//
@@ -126,22 +126,100 @@
d%5D;%0A
-// this.%0A//
+ this.changes = LevDist(removed, added);%0A this.modified = this.changes %3E sensitivity;%0A
%7D%0A%0Af
@@ -653,53 +653,9 @@
null
-%0A , oldLineI = 0%0A ;%0A%0A debugger
+;
%0A
@@ -729,201 +729,92 @@
nes%5B
-oldLineI%5D;%0A%0A if (cOldLine) %7B%0A ++oldLineI;%0A %7D%0A%0A self.changes.push(%7B%0A _: %5BcOldLine, cNewLine%5D%0A , changes: LevDist(cOldLine, cNewLine)%0A %7D
+i%5D %7C%7C %22%22;%0A self.changes.push(new Change(cOldLine, cNewLine, self.sensitivity)
);%0A
@@ -1012,24 +1012,25 @@
if (
+!
cChange.
changes
@@ -1025,35 +1025,16 @@
nge.
-changes %3C= self.sensitivity
+modified
) %7B%0A
@@ -1099,16 +1099,77 @@
.added;%0A
+ cDiff.removed = %22%22;%0A cDiff.added = %22%22;
%0A
@@ -1406,16 +1406,67 @@
%7D);%0A%0A
+ str += cDiff.removed;%0A str += cDiff.added;%0A%0A
retu
|
939d6089384c817429b719e7a6925b48e48ee65c | Call prototype.initialize to prevent overwriting other plugins | lib/index.js | lib/index.js | var extend = require('xtend')
var Joi = require('joi')
var difference = require('lodash.difference')
module.exports = function modelBase (bookshelf, params) {
if (!bookshelf) {
throw new Error('Must pass an initialized bookshelf instance')
}
var model = bookshelf.Model.extend({
initialize: function (attrs, options) {
if (this.validate) {
var baseValidation = {
// id might be number or string, for optimization
id: Joi.any().optional(),
created_at: Joi.date().optional(),
updated_at: Joi.date().optional()
}
this.validate = this.validate.isJoi ?
this.validate.keys(baseValidation) :
Joi.object(this.validate).keys(baseValidation)
} else {
this.validate = Joi.any()
}
this.on('saving', this.validateSave)
},
hasTimestamps: ['created_at', 'updated_at'],
validateSave: function (model, attrs, options) {
var validation
// model is not new or update method explicitly set
if ((model && !model.isNew()) || (options && options.method === 'update')) {
var schemaKeys = this.validate._inner.children.map(function (child) {
return child.key
})
var presentKeys = Object.keys(attrs)
var optionalKeys = difference(schemaKeys, presentKeys)
// only validate the keys that are being updated
validation = Joi.validate(attrs, this.validate.optionalKeys(optionalKeys))
} else {
validation = Joi.validate(this.attributes, this.validate)
}
if (validation.error) {
throw new Error(validation.error)
} else {
return validation.value
}
}
}, {
/* Model CRUD */
/**
* Naive findAll - fetches all data for `this`
* @param {Object} filter (optional)
* @param {Object} options (optional)
* @return {Promise(bookshelf.Collection)} Bookshelf Collection of Models
*/
findAll: function (filter, options) {
filter = extend({}, filter)
return this.forge().query({ where: filter }).fetchAll(options)
},
/**
* Naive findOne - fetch data for `this` matching data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
findOne: function (data, options) {
options = extend({ require: true }, options)
return this.forge(data).fetch(options)
},
/**
* Naive add - create and save a model based on data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
create: function (data, options) {
return this.forge(data)
.save(null, options)
},
/**
* Naive update - update a model based on data
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} edited Model
*/
update: function (data, options) {
options = extend({ patch: true, require: true }, options)
return this.forge({ id: options.id }).fetch(options)
.then(function (model) {
return model ? model.save(data, options) : undefined
})
},
/**
* Naive destroy
* @param {Object} options
* @return {Promise(bookshelf.Model)} empty Model
*/
destroy: function (options) {
options = extend({ require: true }, options)
return this.forge({ id: options.id })
.destroy(options)
},
/**
* Find or create - try and find the model, create one if not found
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} single Model
*/
findOrCreate: function (data, options) {
options = extend({ require: false }, options)
return this.findOne(data, options)
.bind(this)
.then(function (model) {
return model ? model : this.create(data, options)
})
}
})
return model
}
| JavaScript | 0 | @@ -324,24 +324,79 @@
options) %7B%0A
+ bookshelf.Model.prototype.initialize.call(this)%0A%0A
if (th
|
799eea05c603047500b201dbd974c65f5b7020fa | Support non-space whitespace in key mappings. This closes #141. | commands.js | commands.js | var availableCommands = {};
var keyToCommandRegistry = {};
function addCommand(command, description, isBackgroundCommand) {
if (availableCommands[command])
{
console.log(command, "is already defined! Check commands.js for duplicates.");
return;
}
availableCommands[command] = { description: description, isBackgroundCommand: isBackgroundCommand };
}
function mapKeyToCommand(key, command) {
if (!availableCommands[command])
{
console.log(command, "doesn't exist!");
return;
}
keyToCommandRegistry[key] = { command: command, isBackgroundCommand: availableCommands[command].isBackgroundCommand };
}
function unmapKey(key) { delete keyToCommandRegistry[key]; }
function parseCustomKeyMappings(customKeyMappings) {
lines = customKeyMappings.split("\n");
for (var i = 0; i < lines.length; i++) {
if (lines[i][0] == "\"" || lines[i][0] == "#") { continue }
split_line = lines[i].split(" "); // TODO(ilya): Support all whitespace.
var lineCommand = split_line[0];
if (lineCommand == "map") {
if (split_line.length != 3) { continue; }
var key = split_line[1];
var vimiumCommand = split_line[2];
if (!availableCommands[vimiumCommand]) { continue }
console.log("Mapping", key, "to", vimiumCommand);
mapKeyToCommand(key, vimiumCommand);
}
else if (lineCommand == "unmap") {
if (split_line.length != 2) { continue; }
var key = split_line[1];
console.log("Unmapping", key);
unmapKey(key);
}
else if (lineCommand == "unmapAll") {
keyToCommandRegistry = {};
}
}
}
function clearKeyMappingsAndSetDefaults() {
keyToCommandRegistry = {};
mapKeyToCommand('?', 'showHelp');
mapKeyToCommand('j', 'scrollDown');
mapKeyToCommand('k', 'scrollUp');
mapKeyToCommand('h', 'scrollLeft');
mapKeyToCommand('l', 'scrollRight');
mapKeyToCommand('gg', 'scrollToTop');
mapKeyToCommand('G', 'scrollToBottom');
mapKeyToCommand('<c-e>', 'scrollDown');
mapKeyToCommand('<c-y>', 'scrollUp');
mapKeyToCommand('<c-d>', 'scrollPageDown');
mapKeyToCommand('<c-u>', 'scrollPageUp');
mapKeyToCommand('<c-f>', 'scrollFullPageDown');
mapKeyToCommand('<c-b>', 'scrollFullPageUp');
mapKeyToCommand('r', 'reload');
mapKeyToCommand('gf', 'toggleViewSource');
mapKeyToCommand('i', 'enterInsertMode');
mapKeyToCommand('H', 'goBack');
mapKeyToCommand('L', 'goForward');
mapKeyToCommand('zi', 'zoomIn');
mapKeyToCommand('zo', 'zoomOut');
mapKeyToCommand('f', 'activateLinkHintsMode');
mapKeyToCommand('F', 'activateLinkHintsModeToOpenInNewTab');
mapKeyToCommand('/', 'enterFindMode');
mapKeyToCommand('n', 'performFind');
mapKeyToCommand('N', 'performBackwardsFind');
mapKeyToCommand('yy', 'copyCurrentUrl');
mapKeyToCommand('K', 'nextTab');
mapKeyToCommand('J', 'previousTab');
mapKeyToCommand('gt', 'nextTab');
mapKeyToCommand('gT', 'previousTab');
mapKeyToCommand('t', 'createTab');
mapKeyToCommand('d', 'removeTab');
mapKeyToCommand('u', 'restoreTab');
}
// Navigating the current page:
addCommand('showHelp', 'Show help', true);
addCommand('scrollDown', 'Scroll down');
addCommand('scrollUp', 'Scroll up');
addCommand('scrollLeft', 'Scroll left');
addCommand('scrollRight', 'Scroll right');
addCommand('scrollToTop', 'Scroll to the top of the page');
addCommand('scrollToBottom', 'Scroll to the bottom of the page');
addCommand('scrollPageDown', 'Scroll a page down');
addCommand('scrollPageUp', 'Scroll a page up');
addCommand('scrollFullPageDown', 'Scroll a full page down');
addCommand('scrollFullPageUp', 'Scroll a full page up');
addCommand('reload', 'Reload the page');
addCommand('toggleViewSource', 'View page source');
addCommand('zoomIn', 'Zoom in');
addCommand('zoomOut', 'Zoom out');
addCommand('copyCurrentUrl', 'Copy the current URL to the clipboard');
addCommand('enterInsertMode', 'Enter insert mode');
addCommand('activateLinkHintsMode', 'Enter link hints mode to open links in current tab');
addCommand('activateLinkHintsModeToOpenInNewTab', 'Enter link hints mode to open links in new tab');
addCommand('enterFindMode', 'Enter find mode');
addCommand('performFind', 'Cycle forward to the next find match');
addCommand('performBackwardsFind', 'Cycle backward to the previous find match');
// Navigating your history:
addCommand('goBack', 'Go back in history');
addCommand('goForward', 'Go forward in history');
// Manipulating tabs:
addCommand('nextTab', 'Go one tab right', true);
addCommand('previousTab', 'Go one tab left', true);
addCommand('createTab', 'Create new tab', true);
addCommand('removeTab', 'Close current tab', true);
addCommand('restoreTab', "Restore closed tab", true);
// An ordered listing of all available commands, grouped by type. This is the order they will
// be shown in the help page.
var commandGroups = {
pageNavigation:
["scrollDown", "scrollUp", "scrollLeft", "scrollRight",
"scrollToTop", "scrollToBottom", "scrollPageDown", "scrollPageUp", "scrollFullPageDown",
"reload", "toggleViewSource", "zoomIn", "zoomOut", "copyCurrentUrl",
"enterInsertMode", "activateLinkHintsMode", "activateLinkHintsModeToOpenInNewTab",
"enterFindMode", "performFind", "performBackwardsFind"],
historyNavigation:
["goBack", "goForward"],
tabManipulation:
["nextTab", "previousTab", "createTab", "removeTab", "restoreTab"],
misc:
["showHelp"]
};
| JavaScript | 0 | @@ -930,52 +930,15 @@
lit(
-%22 %22); // TODO(ilya): Support all whitespace.
+/%5Cs+/);
%0A%0A
|
a033143013e39c560ed2262d38ec308c3eccd869 | Add Dapper+Twinky to exclusion list for transfemme | lib/index.js | lib/index.js | import _ from 'lodash';
const code = /`.+?`/g;
export function removeCode(text) {
return text.replace(code, '');
}
const BASE = {
core: true,
slots: [
['Non-binary', 'Trans', 'Cis', 'Questioning', 'Genderfluid', 'Bigender', 'Agender', 'Genderqueer'],
['Flexible', 'Nonconforming', 'Femmetype', 'Sophisticate', 'Twinky', 'Dapper', 'Queerdo', 'Soft', 'Leather', 'Androgynous'],
['Queen', 'Dandy', 'Butch', 'Dude', 'Bro', 'Shortcake', 'Otter', 'Dragon', 'Beefcake', 'Bear', 'Princen', 'Gentleperson']
],
trigger: ['gender roll']
};
// Modifiers consist of adding and removing
const GQ = {
core: true,
parent: BASE,
mods: [
[[], ['Cis']],
[[], []],
[[], []]
],
trigger: ['genderqueer roll', 'gender queer roll']
};
const TF = {
core: true,
parent: GQ,
mods: [
[['Self-Rescuing'], []],
[[], []],
[[], ['Bear', 'Beefcake', 'Dude', 'Bro']]
],
trigger: ['transfemme roll', 'transfeminine roll']
};
const TM = {
core: true,
parent: GQ,
mods: [
[[], []],
[[], ['Femmetype']],
[[], ['Princen', 'Queen']]
],
trigger: ['transmasc roll', 'transmasculine roll']
};
const NO_CAKE = {
mods: [
[[], []],
[[], []],
[[], ['Beefcake', 'Shortcake']]
],
trigger: ['-cake', '--no-gluten']
};
const YES_ROBOTS = {
mods: [
[[], []],
[[], []],
[['Droid', 'Robot'], []]
],
trigger: ['+robots', '+robot']
};
const YES_ROBOTS_TF = {
requires: TF,
mods: [
[[], []],
[[], []],
[['Gynoid'], []]
],
trigger: ['+robots', '+robot']
};
const NO_LEATHER = {
mods: [
[[], []],
[[], ['Leather']],
[[], []]
],
trigger: ['-leather']
};
const NO_ANIMALS = {
mods: [
[[], []],
[[], []],
[[], ['Otter', 'Bear', 'Dragon']]
],
trigger: ['-animal', '-animals']
};
// This should be an object, for lookups
export const ALL_ROLLS = {BASE, GQ, TF, TM, NO_CAKE, YES_ROBOTS, YES_ROBOTS_TF, NO_LEATHER, NO_ANIMALS};
// This should be a list, in case ordering is ever relevant.
export const ENABLED_ROLLS = [BASE, GQ, TF, TM, NO_CAKE, YES_ROBOTS, YES_ROBOTS_TF, NO_LEATHER, NO_ANIMALS];
export function determineRolls(text) {
text = text.toLowerCase();
const chosen = ENABLED_ROLLS.filter(x => _.some(x.trigger, t => text.includes(t)));
let core = chosen.filter(x => _.has(x, 'parent') || _.has(x, 'slots'));
if (core.length !== 1) {
// nothing we can do here!
return null;
}
const mods = _.without(chosen, core[0]);
// expand core
while (!_.has(core[0], 'slots')) {
core.unshift(core[0].parent);
}
_.remove(mods, m => (_.has(m, 'requires') && !_.includes(core, m.requires)));
return [core, mods];
}
// first roll in rolls must be a core one with 'slots'
export function applyModifiers(rolls) {
const slots = _.cloneDeep(rolls.shift().slots);
rolls.forEach(function (roll) {
roll = roll.mods;
[0, 1, 2].forEach(function (n) {
const [add, remove] = roll[n];
slots[n].push(...add);
_.pullAll(slots[n], remove);
});
});
[0, 1, 2].forEach(function (n) {
slots[n] = _.uniq(slots[n]);
});
return slots;
}
export function genderRoll(text, pickerFunc = _.sample) {
text = removeCode(text); // this way we can demonstrate sample rolls in code blocks
const rolls = determineRolls(text);
if (rolls === null) {
return null;
}
const slots = applyModifiers(_.flatten(rolls));
const selections = slots.map(pickerFunc);
return selections.join(' ');
}
| JavaScript | 0.000001 | @@ -832,32 +832,50 @@
%5B%5D%5D,%0A %5B%5B%5D, %5B
+'Dapper', 'Twinky'
%5D%5D,%0A %5B%5B%5D, %5B'B
|
176f9e1c9a9661790cedfcde6120078a5eb82a03 | Allow passing in a default set of exchanges. | lib/index.js | lib/index.js | var uri = require('url')
, dns = require('dns')
, NoDataError = require('./errors/nodataerror');
var DEFAULT_PROVIDERS = [ 'google' ];
exports = module.exports = function() {
var map = {};
DEFAULT_PROVIDERS.forEach(function(provider) {
var conf = require('./providers/' + provider);
var i, len;
for (i = 0, len = conf.exchanges.length; i < len; ++i) {
map[conf.exchanges[i].toLowerCase()] = conf.services;
}
});
var plugin = {};
plugin.resolveServices = function(identifier, type, cb) {
if (typeof type == 'function') {
cb = type;
type = undefined;
}
var url = uri.parse(identifier);
if (url.protocol != 'acct:') {
// This plugin only supports resolving of `acct:`-type identifiers. If
// the identifier is unsupported, return without an error and without
// resolving services. The expectation is that other discovery mechanisms
// are registered with `fingro` that will be used as alternatives.
return cb(null);
}
dns.resolve(url.hostname, 'MX', function (err, records) {
if (err) { return cb(err); }
records.sort(function(lhs, rhs) { return rhs.priority < lhs.priority; });
var result = {}
, record
, services
, i, len;
for (i = 0, len = records.length; i < len; ++i) {
record = records[i];
services = map[record.exchange.toLowerCase()]
if (services) {
Object.keys(services).forEach(function(type) {
var val = services[type];
if (typeof val == 'string') {
result[type] = { location: val };
} else {
result[type] = val;
}
});
if (type) {
result = result[type];
if (!result) { return cb(new NoDataError('Service not found: ' + type)); }
return cb(null, result);
}
return cb(null, result);
}
}
// Unable to find a service mapping from the configured set of mail
// exchanges. Return without an error and without resolving services.
// The expectation is that other discovery mechanisms are registered
// with `fingro` that will be used as alternatives.
return cb(null);
});
}
return plugin;
}
| JavaScript | 0 | @@ -175,24 +175,54 @@
ion(
-) %7B%0A %0A var map
+exchanges) %7B%0A if (!exchanges) %7B%0A exchanges
= %7B
@@ -226,17 +226,21 @@
= %7B%7D;%0A
-%0A
+ %0A
DEFAUL
@@ -280,24 +280,26 @@
ider) %7B%0A
+
var conf = r
@@ -333,24 +333,26 @@
vider);%0A
+
var i, len;%0A
@@ -351,24 +351,26 @@
i, len;%0A
+
+
for (i = 0,
@@ -420,19 +420,27 @@
%7B%0A
-map
+ exchanges
%5Bconf.ex
@@ -490,16 +490,24 @@
-%7D%0A
+ %7D%0A
%7D);%0A
+ %7D%0A
%0A
@@ -1469,19 +1469,25 @@
vices =
-map
+exchanges
%5Brecord.
|
e01d0dc03228801f895584be587dcf7afc801ace | Correct output debug statement | lib/index.js | lib/index.js | var p2list = require('properties-parser');
var p2tree = require('java.properties.js').default;
var path = require('path');
var createProperties2JsonPreprocessor = function(file, config) {
config = typeof config === 'object' ? config : {};
var distPath = config.dist || 'spec/javascripts/fixtures/json/';
var fileName = path.basename(file.path).replace(/\.[^/.]+$/, '');
console.log('Move output: ', distPath + '/' + fileName + '.json');
file.rename(path.normalize(distPath + '/' + fileName + '.json'));
var content = config.tree ? p2tree(file.content) : p2list.parse(file.content);
return JSON.stringify(content);
};
module.exports = {
transform: createProperties2JsonPreprocessor
};
| JavaScript | 0.001266 | @@ -391,12 +391,15 @@
og('
-Move
+Writing
out
@@ -406,16 +406,31 @@
put: ',
+path.normalize(
distPath
@@ -457,16 +457,17 @@
'.json')
+)
;%0A file
|
906ef441890ad31529db727b06d133318e0c4dec | Switch to keyup to repaint any time the block is changed. | wagtailcodeblock/static/wagtailcodeblock/js/wagtailcodeblock.js | wagtailcodeblock/static/wagtailcodeblock/js/wagtailcodeblock.js | function CodeBlockDefinition() {
window.wagtailStreamField.blocks.StructBlockDefinition.apply(this, arguments);
}
CodeBlockDefinition.prototype.render = function(placeholder, prefix, initialState, initialError) {
var block = window.wagtailStreamField.blocks.StructBlockDefinition.prototype.render.apply(
this, arguments
);
var languageField = $(document).find('#' + prefix + '-language');
var codeField = $(document).find('#' + prefix + '-code');
var targetField = $(document).find('#' + prefix + '-target');
function updateLanguage() {
var languageCode = languageField.val();
targetField.removeClass().addClass('language-' + languageCode);
prismRepaint();
}
function prismRepaint() {
Prism.highlightElement(targetField[0]);
}
function populateTargetCode() {
var codeText = codeField.val();
targetField.text(codeText);
prismRepaint(targetField);
}
updateLanguage();
populateTargetCode();
languageField.on('change', updateLanguage);
codeField.on('change', populateTargetCode);
codeField.keypress(function() {
prismRepaint();
});
return block;
}
window.telepath.register('wagtailcodeblock.blocks.CodeBlock', CodeBlockDefinition);
| JavaScript | 0 | @@ -1105,22 +1105,21 @@
eld.on('
-change
+keyup
', popul
@@ -1138,79 +1138,8 @@
e);%0D
-%0A codeField.keypress(function() %7B%0D%0A prismRepaint();%0D%0A %7D);%0D
%0A%0D%0A
|
708118c6822c56b650de66d390376da58a1e35ed | clear interval | lib/index.js | lib/index.js | 'use strict';
const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
var NUM_LEDS = parseInt(process.argv[2], 10) || 10;
var pixelData = new Uint32Array(NUM_LEDS);
var itv;
ws281x.init(NUM_LEDS);
function init () {
var server = restify.createServer();
server.get('/rainbow', (req, res, next) => {
res.send('rainbow');
// ---- animation-loop
clearInterval(itv);
var offset = 0;
itv = setInterval(function () {
for (var i = 0; i < NUM_LEDS; i++) {
pixelData[i] = colorwheel((offset + i) % 256);
}
offset = (offset + 1) % 256;
ws281x.render(pixelData);
}, 1000 / 30);
});
server.get('/stop', (req, res, next) => {
res.send('stop');
clearInterval(itv);
ws281x.reset();
});
server.listen(8080);
}
// rainbow-colors, taken from http://goo.gl/Cs3H0v
function colorwheel(pos) {
pos = 255 - pos;
if (pos < 85) { return rgb2Int(255 - pos * 3, 0, pos * 3); }
else if (pos < 170) { pos -= 85; return rgb2Int(0, pos * 3, 255 - pos * 3); }
else { pos -= 170; return rgb2Int(pos * 3, 255 - pos * 3, 0); }
}
function rgb2Int(r, g, b) {
return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}
module.exports = {
init: init
};
| JavaScript | 0.000003 | @@ -199,30 +199,8 @@
tv;%0A
-ws281x.init(NUM_LEDS);
%0A%0Afu
@@ -376,24 +376,71 @@
erval(itv);%0A
+ ws281x.reset();%0A ws281x.init(NUM_LEDS);%0A
var offs
|
bd01810ba846c1dfe7a438f3cb97fd6f147f3735 | remove express powered by header. added uncaught error handler | lib/index.js | lib/index.js | var express = require('express');
var bodyParser = require('body-parser');
var buildLog = require('./log.js');
var buildConfig = require('./config.js');
var buildRedis = require('./redis.js');
var buildCache = require('./cache.js');
var buildCron = require('./cron.js');
var buildRouter = require('./router.js');
module.exports = function (config, options) {
var conf = buildConfig(config);
var log = (options && options.log) ? options.log(conf) : buildLog(conf);
log.info('server: building redis connection');
var redis = buildRedis(conf, log);
log.info('server: building cache');
var cache = buildCache(conf, log, redis);
log.info('server: building cron');
var cron = buildCron(conf, log, redis, cache);
return {
config : conf,
log : log,
redis : redis,
cache : cache,
cron : cron,
start : function () {
cron.startCron();
cron.listenForMessages();
if (!config.port) {
throw new Error('missing "port" key in config');
}
var router = buildRouter(conf, log, cache, cron);
var app = express();
app.use(accessLogger);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
function accessLogger(req, res, next) {
log.debug('access: ' + req.method + ' ' + req.url);
next();
}
app.listen(config.port);
log.info('server: running on port ' + config.port);
}
};
}; | JavaScript | 0.000005 | @@ -1065,16 +1065,48 @@
ress();%0A
+%09%09%09app.disable('x-powered-by');%0A
%09%09%09app.u
@@ -1228,16 +1228,191 @@
router);
+%0A%09%09%09app.use(function (e, req, res, next) %7B%0A%09%09%09%09var status = e.status %7C%7C 500;%0A%09%09%09%09res.send(status);%0A%09%09%09%09log.error('uncaught error: ' + (e.message %7C%7C '?'), %7B error: e %7D);%0A%09%09%09%7D);
%0A%0A%09%09%09fun
|
92d72d89b9bfe74dfe181e64a8ba979ab8d6fb80 | raise error if protocol isn't valid | lib/index.js | lib/index.js | 'use strict';
const os = require('os');
const net = require('net');
const secNet = require('tls');
const http = require('http');
const https = require('https');
const util = require('util');
const winston = require('winston');
/**
* parse winston level as a string and return its equivalent numeric value
* @return {int} level
*/
function levelToInt(level) {
if (level === 'error') return 0;
else if (level === 'warn') return 1;
else if (level === 'info') return 2;
else if (level === 'verbose') return 3;
else if (level === 'debug') return 4;
else if (level === 'silly') return 5;
return 0;
}
/**
* open a TCP socket and send logs to Gelf server
* @param {string} msg – JSON stringified GELF msg
*/
const sendTCPGelf = function (host, port, tls) {
const options = {
host,
port,
rejectUnauthorized: false
};
// whether or not tls is required
let clientType;
if (tls) clientType = secNet;
else clientType = net;
const client = clientType.connect(options, () => {
// console.log('Connected to Graylog server');
});
client.on('end', () => {
console.log('Disconnected from Graylog server');
});
client.on('error', (err) => {
console.error('Error connecting to Graylog:', err.message);
});
return {
send(msg) {
client.write(`${msg}\0`);
},
end() {
client.end();
}
};
};
/**
* send logs to Gelf server via HTTP(S)
* @param {string} msg – JSON stringified GELF msg
*/
const sendHTTPGelf = function (host, port, tls) {
const options = {
port,
hostname: host,
path: '/gelf',
method: 'POST',
rejectUnauthorized: false
};
let clientType;
if (tls) clientType = https;
else clientType = http;
return (msg) => {
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(msg)
};
const req = clientType.request(options, (res) => {
// usefull for debug
// console.log('statusCode: ', res.statusCode);
});
req.on('error', (e) => {
console.error('Error connecting to Graylog:', e.message);
});
req.write(msg);
req.end();
};
};
const Log2gelf = winston.transports.Log2gelf = function (options) {
this.name = options.name || 'log2gelf';
this.hostname = options.hostname || os.hostname();
this.host = options.host || '127.0.0.1';
this.port = options.port || 12201;
this.protocol = options.protocol || 'tcp';
this.service = options.service || 'nodejs';
this.level = options.level || 'info';
this.silent = options.silent || false;
this.handleExceptions = options.handleExceptions || false;
this.environment = options.environment || 'development';
this.release = options.release;
this.customPayload = {};
Object.keys(options).forEach((key) => {
if (key[0] === '_') this.customPayload[key] = options[key];
});
// set protocol to use
if (this.protocol === 'tcp') {
const tcpGelf = sendTCPGelf(this.host, this.port, false);
this.send = tcpGelf.send;
this.end = tcpGelf.end;
}
else if (this.protocol === 'tls') {
const tcpGelf = sendTCPGelf(this.host, this.port, true);
this.send = tcpGelf.send;
this.end = tcpGelf.end;
}
else if (this.protocol === 'http') this.send = sendHTTPGelf(this.host, this.port, false);
else if (this.protocol === 'https') this.send = sendHTTPGelf(this.host, this.port, true);
};
// Inherit from `winston.Transport` so you can take advantage
// of the base functionality and `.handleExceptions()`.
util.inherits(Log2gelf, winston.Transport);
Log2gelf.prototype.log = function (level, msg, meta, callback) {
const timestamp = Math.floor(Date.now() / 1000);
const intLevel = levelToInt(level);
const payload = {
timestamp,
level: intLevel,
host: this.hostname,
short_message: msg,
full_message: meta ? JSON.stringify(meta) : undefined,
_service: this.service,
_environment: this.environment,
_release: this.release
};
const gelfMsg = Object.assign({}, payload, this.customPayload);
this.send(JSON.stringify(gelfMsg));
callback(null, true);
};
module.exports = Log2gelf;
| JavaScript | 0.000017 | @@ -3662,24 +3662,121 @@
ort, true);%0A
+ else throw new TypeError('protocol shoud be one of the following: tcp, tls, http or https');%0A
%7D;%0A%0A// Inher
|
3803a80298692ca5a7b38ccf635a79accee26fb5 | Copy user_access | lib/index.js | lib/index.js | 'use strict';
var fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Encoder = require('node-html-encoder').Encoder;
var AnyfetchClient = require('cluestr');
var async = require('async');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} document to hydrate
* @param {function} cb Callback, first parameter, is the error if any, then the processed data
*/
var reg = new RegExp("(<([^>]+)>)", "g");
function exists(item){
return item ? item : '';
}
module.exports = function(path, document, cb) {
if(!document.metadatas) {
document.metadatas = {};
}
if(!document.datas) {
document.datas = {};
}
var anyfetchClient = new AnyfetchClient();
anyfetchClient.setAccessToken(document.access_token);
var mailparser = new MailParser();
var encoder = new Encoder('entity');
mailparser.on("end", function(mail_object){
document.document_type = "email";
document.metadatas.to = [];
(mail_object.to || []).forEach(function(item){
document.metadatas.to.push(item);
});
document.metadatas.cc = [];
(mail_object.cc || []).forEach(function(item){
document.metadatas.cc.push(item);
});
document.metadatas.bcc = [];
(mail_object.bcc || []).forEach(function(item){
document.metadatas.bcc.push(item);
});
document.metadatas.from = exists(mail_object.from);
document.metadatas.subject = exists(mail_object.subject);
if (mail_object.html) {
document.datas.html = encoder.htmlDecode(mail_object.html).trim();
}
if (mail_object.headers && mail_object.headers.date) {
document.creation_date = new Date(mail_object.headers.date);
}
if (mail_object.text) {
document.metadatas.text = mail_object.text;
}
else if (document.datas.html) {
document.metadatas.text = document.datas.html.replace(reg, " ");
document.metadatas.text = document.metadatas.text.replace(" ", " ");
}
document.metadatas.text = document.metadatas.text.trim();
async.each((mail_object.attachments || []), function(attachment, cb){
var docAttachment = {};
docAttachment.identifier = document.identifier + "/" + attachment.fileName;
docAttachment.document_type = "file";
docAttachment.metadatas = {};
docAttachment.metadatas.path = "/" + attachment.fileName;
// File to send
var fileConfigAttachment = function(){
return {
file: attachment.content,
filename: attachment.fileName,
knownLength: attachment.length
};
};
anyfetchClient.sendDocumentAndFile(docAttachment, fileConfigAttachment, function(err) {
cb(err);
});
}, function(err){
cb(err, document);
});
});
fs.createReadStream(path).pipe(mailparser);
}; | JavaScript | 0.000001 | @@ -2366,24 +2366,80 @@
t.fileName;%0A
+ docAttachment.user_access = document.user_access;%0A
// Fil
@@ -2880,8 +2880,9 @@
ser);%0A%7D;
+%0A
|
c9a2f9b16a40449f060a50c92654fc21eb043587 | Update index.js | lib/index.js | lib/index.js | var tokenize = require('./tokenize');
var languageProcessor = require('./language-processor');
/**
* Constructor
* @param {Object} options - Instance options
*/
var Sentiment = function (options) {
this.options = options;
};
/**
* Registers the specified language
*
* @param {String} languageCode
* - Two-digit code for the language to register
* @param {Object} language
* - The language module to register
*/
Sentiment.prototype.registerLanguage = function (languageCode, language) {
languageProcessor.addLanguage(languageCode, language);
};
/**
* Performs sentiment analysis on the provided input 'phrase'.
*
* @param {String} phrase
* - Input phrase
* @param {Object} opts
* - Options
* @param {Object} opts.language
* - Input language code (2 digit code), defaults to 'en'
* @param {Object} opts.extras
* - Optional sentiment additions to AFINN (hash k/v pairs)
* @param {function} callback
* - Optional callback
* @return {Object}
*/
Sentiment.prototype.analyze = function (phrase, opts, callback) {
// Parse arguments
if (typeof phrase === 'undefined') phrase = '';
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var languageCode = opts.language || 'en';
var labels = languageProcessor.getLabels(languageCode);
// Merge extra labels
if (typeof opts.extras === 'object') {
labels = Object.assign(labels, opts.extras);
}
// Storage objects
var tokens = tokenize(phrase),
score = 0,
words = [],
positive = [],
negative = [],
calculation = [];
// Iterate over tokens
var i = tokens.length;
while (i--) {
var obj = tokens[i];
if (!labels.hasOwnProperty(obj)) continue;
words.push(obj);
// Apply scoring strategy
var tokenScore = labels[obj];
// eslint-disable-next-line max-len
tokenScore = languageProcessor.applyScoringStrategy(languageCode, tokens, i, tokenScore);
if (tokenScore > 0) positive.push(obj);
if (tokenScore < 0) negative.push(obj);
score += tokenScore;
var zipObj = {};
// Calculations breakdown
zipObj[obj] = tokenScore;
calculation.push(zipObj);
}
var result = {
score: score,
calculation: calculation,
comparative: tokens.length > 0 ? score / tokens.length : 0,
tokens: tokens,
words: words,
positive: positive,
negative: negative
};
// Handle optional async interface
if (typeof callback === 'function') {
process.nextTick(function () {
callback(null, result);
});
} else {
return result;
}
};
module.exports = Sentiment;
| JavaScript | 0.000002 | @@ -2393,45 +2393,8 @@
re,%0A
- calculation: calculation,%0A
@@ -2456,24 +2456,61 @@
length : 0,%0A
+ calculation: calculation,%0A
toke
|
c867172e874a73de564c6900c8fbf04b25970f26 | Allow the init function to be async | packages/express/index.js | packages/express/index.js | const express = require('express');
module.exports = init => {
const app = express();
app.disable('x-powered-by');
init(app, express);
const port = process.env.PORT;
if (!port) {
throw new Error('missing port');
}
app.listen(port, () => {
console.log(`app listen on port ${port}`);
});
};
| JavaScript | 0.000142 | @@ -46,16 +46,22 @@
xports =
+ async
init =%3E
@@ -122,16 +122,22 @@
y');%0A%0A
+await
init(app
|
315b7c3c60261f0dd4d3a6aed06871473f3340d9 | returning the data | lib/index.js | lib/index.js | /**
* Fixture loader
*/
'use strict';
/**
* Module dependencies.
*/
var path = require('path');
var fs = require('fs');
/**
* Types.
*/
/**
* Load fixtures.
*/
function load(basePath, data, opts) {
fs.readdirSync(basePath).forEach(function(fileName) {
var filePath = path.join(basePath, fileName);
var ext = path.extname(fileName);
var name = path.basename(fileName, ext);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
data[name] = {};
return load(filePath, data[name], opts);
}
if (!stat.isFile()) return;
if (data.hasOwnProperty(name)) {
throw new Error('conflict: ' + filePath);
}
var fileData = fs.readFileSync(filePath);
var fixture = function(type) {
switch (type || ext.slice(1)) {
case 'buffer':
return fileData.slice();
case 'json':
return JSON.parse(fileData.toString());
default:
return opts.trim ? fileData.toString().trim() : fileData.toString();
}
};
if (opts.type === 'function') {
data[name] = fixture;
return;
}
Object.defineProperty(data, name, {
configurable: true,
enumerable: true,
get: fixture,
});
});
}
/**
* Reload fixtures.
*/
exports.reload = function(opts) {
opts = opts || {};
if (!opts.path) {
opts.path = path.join(process.cwd(), 'test', 'fixtures');
}
if (!opts.scope) {
Object.keys(exports).forEach(function(key) {
if (key === 'reload') return;
delete exports[key];
});
opts.scope = exports;
}
if (!opts.hasOwnProperty('trim')) {
opts.trim = true;
}
if (!fs.existsSync(opts.path)) return;
var stat = fs.statSync(opts.path);
if (!stat.isDirectory()) return;
load(opts.path, opts.scope, opts);
};
/**
* Initial load.
*/
exports.reload();
| JavaScript | 0.999951 | @@ -1800,16 +1800,38 @@
, opts);
+%0A%0A return opts.scope;
%0A%7D;%0A%0A/**
|
26a4afaaf97c094d4d44149578ccf4bb803ce45c | Remove style attribute from mainNav after slide up, fixes #99 | site/javascript/garden.js | site/javascript/garden.js | // A thingy to handle the sections ----------------------------------------------
// ------------------------------------------------------------------------------
function Sections(page) {
this.page = page;
this.init();
}
Sections.prototype = {
init: function(attribute) {
this.heights = this.page.nav.find('ul').map(function(idx, ele) {
return $(this).outerHeight();
}).get();
this.links = {
next: $('#nav_next_section'),
prev: $('#nav_prev_section')
};
},
map: function() {
this.names = $('section>[id]').map(function(idx, ele) {
return {
id: this.id.replace('.intro', ''),
offset: $(this).offset().top - 100,
title: $(this).find(':header:first').html()
};
}).get();
},
highlight: function() {
var scroll = this.page.window.scrollTop(),
articleID = this.names[this.names.length - 1].id;
for(var i = 0, l = this.names.length; i < l; i++) {
if (scroll >= 0 && this.names[i].offset > scroll) {
articleID = this.names[i - 1].id;
break;
}
}
var sectionID = articleID.split('.')[0],
page = this.page,
nav = page.nav;
if (sectionID !== page.section) {
nav.filter('.nav_' + page.section).removeClass('active');
nav.filter('.nav_' + sectionID).addClass('active');
this.expand(sectionID);
page.section = sectionID;
}
if (articleID !== page.article) {
nav.find('a[href="#' + page.article + '"]').removeClass('active');
nav.find('a[href="#' + articleID + '"]').addClass('active');
page.article = articleID;
this.mobile(articleID);
}
},
expand: function (sectionName) {
var nav = this.page.nav,
index = nav.find('a[href=#' + sectionName + ']')
.closest('nav > ul > li').index();
var height = this.page.window.height()
- $('nav > div').height()
- (33 * this.heights.length),
sections = [],
currentHeight = 0,
distance = 0;
while ((currentHeight + this.heights[index]) < height) {
sections.push(index);
currentHeight += this.heights[index];
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
if (index < 0 || index >= this.heights.length) {
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
}
}
for(var i = 0, len = nav.length; i < len; i++) {
if ($.inArray(i, sections) === -1) {
nav.eq(i).find('ul').slideUp();
} else {
nav.eq(i).find('ul').slideDown();
}
}
},
mobile: function(index){
for(var i = 0; i < this.names.length; i++) {
if (this.names[i].id === index) {
this.updateLinks(i);
break;
}
}
},
updateLinks: function(index) {
if (index !== this.names.length - 1) {
this.setLink(this.links.next, this.names[index + 1]);
} else {
this.links.next.slideUp(100);
}
if (index !== 0) {
this.setLink(this.links.prev, this.names[index - 1]);
} else {
this.links.prev.slideUp(100);
}
},
setLink: function(ele, data) {
ele.slideDown(100).attr('href', '#' + data.id)
.find('.nav_section_name').html(data.title);
}
};
// This more or less controls the page ------------------------------------------
// ------------------------------------------------------------------------------
function Page() {
$.extend(true, this, {
window: $(window),
nav: $('nav > ul > li'),
section: null,
articule: null
});
this.sections = new Sections(this);
this.init();
}
Page.prototype = {
init: function() {
var that = this,
mainNav = $('#nav_main');
$.extend(this, {
scrollLast: 0,
resizeTimeout: null
});
this.window.scroll(function() {
that.onScroll();
});
this.window.resize(function() {
that.onResize();
});
that.sections.map();
setTimeout(function() {
that.sections.highlight();
}, 10);
// Mobile, for position: fixed
if ($.mobile) {
var navs = $('#nav_mobile, #nav_main');
navs.css('position', 'absolute');
this.window.scroll(function(){
navs.offset({
top: that.window.scrollTop()
});
});
}
// Show menu for tablets
$('#show_menu').click(function (){
var scrollTop = $.mobile ? that.window.scrollTop() : 0;
mainNav.slideDown(300).css('top', scrollTop);
return false;
});
$('#nav_main').click(function(){
if(that.window.width() < 1000)
mainNav.slideUp(300);
});
},
onScroll: function() {
if ((+new Date()) - this.scrollLast > 50) {
this.scrollLast = +new Date();
this.sections.highlight();
}
},
onResize: function() {
clearTimeout(this.resizeTimeout);
var that = this;
this.resizeTimeout = setTimeout(function() {
that.sections.map();
that.sections.expand(that.section);
}, 100);
}
};
var Garden = new Page();
prettyPrint();
// GA tracking code
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-20768522-1'], ['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
| JavaScript | 0 | @@ -5379,16 +5379,56 @@
deUp(300
+, function() %7Bthis.removeAttr('style');%7D
);%0A
|
4b45eb37d1b8537979930a964892be6c267e019d | Fix reducer function name | site/reducers/playback.js | site/reducers/playback.js | import {
START_PLAYBACK,
PAUSE_PLAYBACK,
} from '../constants/ActionTypes'
const initialState = {
startTime: null,
pauseTime: null,
}
export default function song(state = initialState, action) {
switch (action.type) {
case START_PLAYBACK:
return Object.assign({}, state, {
startTime: performance.now(),
})
case PAUSE_PLAYBACK:
return Object.assign({}, state, {
pauseTime: performance.now(),
})
default:
return state
}
}
| JavaScript | 0.999551 | @@ -165,12 +165,16 @@
ion
-song
+playback
(sta
|
afcb5b74c511a2c1ee0abbb521c7b2c477c2e5b6 | Remove unused vars. Fixes build | lib/index.js | lib/index.js | 'use strict';
const _handlers = Symbol('handlers');
const _queue = Symbol('queue');
const _state = Symbol('state');
const _value = Symbol('value');
class Handlers {
constructor () {
this.fulfill = null;
this.reject = null;
}
}
/**
* @class promise
*/
class FidelityPromise {
constructor (state = PENDING, value) {
this.state = state;
this.value = value;
this[_queue] = [];
this[_handlers] = new Handlers();
}
/**
* Follows the [Promises/A+](https://promisesaplus.com/) spec
* for a `then` function.
* @returns a promise
*/
then (onFulfilled, onRejected) {
const next = new FidelityPromise();
if (typeof onFulfilled === 'function') {
next[_handlers].fulfill = onFulfilled;
}
if (typeof onRejected === 'function') {
next[_handlers].reject = onRejected;
}
this[_queue].push(next);
process(this);
return next;
}
catch (onRejected) {
return this.then(null, onRejected);
}
}
const PENDING = 0;
const FULFILLED = 1;
const REJECTED = 2;
const TRUE = new FidelityPromise(FULFILLED, true);
const FALSE = new FidelityPromise(FULFILLED, false);
const NULL = new FidelityPromise(FULFILLED, null);
const UNDEFINED = new FidelityPromise(undefined);
const ZERO = new FidelityPromise(FULFILLED, 0);
const EMPTYSTRING = new FidelityPromise(FULFILLED, '');
/**
* @module fidelity
*/
module.exports = {
promise: promise,
deferred: deferred,
resolve: resolve,
PENDING: PENDING,
FULFILLED: FULFILLED,
REJECTED: REJECTED
};
/**
* Creates a promise that will be resolved or rejected at some time
* in the future.
* @param {function} fn The function that will do the work of this promise.
* The function is passed two function arguments, `resolve()` and `reject()`.
* Call one of these when the work has completed (or failed).
* @returns {object} A promise object
* @instance
*/
function promise (fn) {
const p = new FidelityPromise(PENDING, null);
if (typeof fn === 'function') {
try {
fn((v) => resolvePromise(p, v), (r) => transition(p, REJECTED, r));
} catch (e) {
transition(p, REJECTED, e);
}
}
return p;
}
/**
* Returns a promise that is resolved with `value`.
* @param {any} value The value to resolve the returned promise with
* @returns {object} A promise resolved with `value`
* @method resolve
* @instance resolve
*/
function resolve (value) {
if (value && value.then) return value;
switch (value) {
case null:
return NULL;
case undefined:
return UNDEFINED;
case true:
return TRUE;
case false:
return FALSE;
case 0:
return ZERO;
case '':
return EMPTYSTRING;
}
return new FidelityPromise(FULFILLED, value);
}
/**
* Creates a `deferred` object, containing a promise which may
* be resolved or rejected at some point in the future.
* @returns {object} deferred The deferred object
* @returns {function} deferred.resolve(value) The resolve function
* @returns {function} deferred.reject(cause) The reject function
* @returns {object} deferred.promise The inner promise object
* @instance
*/
function deferred () {
var resolver;
var rejecter;
var p = promise((resolve, reject) => {
resolver = resolve;
rejecter = reject;
});
function resolve (value) {
resolver(value);
}
function reject (cause) {
rejecter(cause);
}
return {
promise: p,
resolve: resolve,
reject: reject
};
}
function resolvePromise (p, x) {
if (x === p) {
transition(p, REJECTED, new TypeError('The promise and its value are the same.'));
return;
}
if (x && ((typeof x === 'function') || (typeof x === 'object'))) {
let called = false;
let thenFunction;
try {
thenFunction = x.then;
if (thenFunction && (typeof thenFunction === 'function')) {
thenFunction.call(x, (y) => {
if (!called) {
resolvePromise(p, y);
called = true;
}
}, (r) => {
if (!called) {
transition(p, REJECTED, r);
called = true;
}
});
} else {
transition(p, FULFILLED, x);
called = true;
}
} catch (e) {
if (!called) {
transition(p, REJECTED, e);
called = true;
}
}
} else {
transition(p, FULFILLED, x);
}
}
function process (p) {
if (p.state === PENDING) return;
global.process.nextTick(() => {
let qp, handler, value;
while (p[_queue].length) {
qp = p[_queue].shift();
if (p.state === FULFILLED) {
handler = qp[_handlers].fulfill || ((v) => v);
} else if (p.state === REJECTED) {
handler = qp[_handlers].reject || ((r) => {
throw r;
});
}
try {
value = handler(p.value);
} catch (e) {
transition(qp, REJECTED, e);
continue;
}
resolvePromise(qp, value);
}
});
return p;
}
function transition (p, state, value) {
if (p.state === state ||
p.state !== PENDING ||
arguments.length !== 3) return;
p.state = state;
p.value = value;
return process(p);
}
| JavaScript | 0 | @@ -81,72 +81,8 @@
e');
-%0Aconst _state = Symbol('state');%0Aconst _value = Symbol('value');
%0A%0Acl
|
215d8166bbf11aec7b9cc56c18364f092b88d849 | Remove underscore.js dependency. | formErrors.js | formErrors.js | angular.module('FormErrors', [])
// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
return {
// only works if embedded in a form or an ngForm (that's in a form).
// It does use its closest parent that is a form OR ngForm
require: '^form',
template:
'<div class="form-errors" ng-transclude>' +
'<div class="form-error" ng-repeat="error in errors">' +
'{{error}}' +
'</div>' +
'</div>',
replace: true,
transclude: true,
restrict: 'AE',
scope: { isValid: '=' },
link: function postLink(scope, elem, attrs, ctrl) {
// list of some default error reasons
var defaultErrorReasons = {
required: 'is required.',
minlength: 'is too short.',
maxlength: 'is too long.',
email: 'is not a valid email address.',
pattern: 'does not expect the matched pattern.',
fallback: 'is invalid.'
},
// uppercase words helper
ucwords = function(text) {
return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
},
// breakup camelCase
breakup = function(text, separator) {
return text.replace(/[A-Z]/g, function (match) {
return separator + match;
});
},
// humanize words
humanize = function (value) {
return ucwords(breakup(value, ' ').replace(/[-_+]/g, ' '));
},
// this is where we form our message
formMessage = function formMessage(elem, error, props) {
// get the nice name if used the niceName directive
// or humanize the elem name and call it good
var niceName = props.$niceName || humanize(elem);
// get a reason from our default set
var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;
// if they used the errorMessages directive, grab that message
if(typeof props.$errorMessages === 'object')
reason = props.$errorMessages[error];
else if(typeof props.$errorMessages === 'string')
reason = props.$errorMessages;
// return our nicely formatted message
return niceName + ' ' + reason;
};
// only update the list of errors if there was actually a change
scope.$watch(function() { return ctrl.$error; }, function() {
// we can pass in a variable to keep track of form validity in page's ctrl
scope.isValid = ctrl.$valid;
scope.errors = [];
_.each(ctrl, function(props, elem) {
// elem has some internal properties we don't want to iterate over
if(elem[0] === '$') return;
_.each(props.$error, function(isInvalid, error) {
// don't need to even try and get a a message unless it's invalid
if(isInvalid) {
scope.errors.push(formMessage(elem, error, props));
}
});
});
}, true);
}
};
}])
// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$niceName = attrs.niceName;
}
};
}])
// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
// attrs.errorMessages can be:
// 1) "must be filled out."
// 2) "'must be filled out.'"
// 3) "{ required: 'must be filled out.' }"
try {
ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
} catch(e) {
ctrl.$errorMessages = attrs.errorMessages;
}
}
};
}]); | JavaScript | 0 | @@ -3135,27 +3135,36 @@
-_.e
+angular.forE
ach(ctrl, fu
@@ -3344,11 +3344,20 @@
-_.e
+angular.forE
ach(
|
2c5b10044921635da6e3f7b9cfa33180b7f55138 | rewrite for sensors | lib/index.js | lib/index.js | /**
* Imports
*/
var fs = require('fs')
/**
* Vars
*/
var motorPath = '/sys/class/tacho-motor/'
var paths = fs.readdirSync(motorPath).reduce(function (obj, file) {
var portName = fs.readFileSync(motorPath + file + '/port_name', 'utf-8').trim()
obj[portName] = file.trim()
return obj
}, {})
/**
* Expose devices
*/
module.exports = devices
/**
* Get a device
* @param {String} port
* @return {String} path
*/
function devices (port) {
const portName = 'out' + port.toUpperCase()
return portToPath(portName)
}
/**
* Convert port to path
* @return {Object}
*/
function portToPath (port) {
return motorPath + paths[port]
}
| JavaScript | 0.000311 | @@ -67,14 +67,20 @@
otor
-Path =
+ = %7B%0A path:
'/s
@@ -105,208 +105,195 @@
or/'
-%0Avar paths = fs.readdirSync(motorPath).reduce(function (obj, file) %7B%0A var portName = fs.readFileSync(motorPath + file + '/port_name', 'utf-8').trim()%0A obj%5BportName%5D = file.trim()%0A return obj%0A%7D, %7B%7D)
+,%0A available: getPaths('/sys/class/tacho-motor/'),%0A prefix: 'out'%0A%7D%0A%0Avar sensor = %7B%0A path: '/sys/class/lego-sensor/',%0A available: getPaths('/sys/class/lego-sensor/'),%0A prefix: 'in'%0A%7D
%0A%0A/*
@@ -450,32 +450,86 @@
%7B%0A
-const portName = 'out' +
+var device = isNaN(port) ? motor : sensor%0A if (device === motor) %7B%0A port =
por
@@ -544,16 +544,20 @@
rCase()%0A
+ %7D%0A
return
@@ -561,145 +561,284 @@
urn
-portToPath(portName)%0A%7D%0A%0A/**%0A * Convert port to path%0A * @return %7BObject%7D%0A */%0A%0Afunction portToPath (port) %7B%0A return motorPath + paths%5Bport%5D
+device.path + device.available%5Bdevice.prefix + port%5D%0A%7D%0A%0Afunction getPaths (path) %7B%0A return fs.readdirSync(path).reduce(function (obj, file) %7B%0A var portName = fs.readFileSync(path + file + '/port_name', 'utf-8').trim()%0A obj%5BportName%5D = file.trim()%0A return obj%0A %7D, %7B%7D)
%0A%7D%0A
|
42b44fabcb141b429cb024bd173a385666d60595 | fix validate import (commonJS / ES6 compatibility issue) | lib/index.js | lib/index.js | const modDelim = '_';
const elemDelim = '__';
export function buildClassName(bemjson) {
if (!bemjson) {
return '';
}
// validation
// istanbul ignore next
if (process.env.NODE_ENV !== 'production') {
require('./validate.js')(bemjson);
}
let out = '';
// block
if (typeof bemjson.block !== 'undefined') {
out += (out ? ' ' : '') + bemjson.block;
// elem
if (typeof bemjson.elem !== 'undefined') {
out += elemDelim + bemjson.elem;
}
const entity = out;
if (typeof bemjson.mods !== 'undefined') {
Object.keys(bemjson.mods).forEach(modName => {
const modValue = bemjson.mods[modName];
let modValueString = '';
if (modValue !== false) {
// 'short' boolean mods
if (modValue !== true) {
modValueString += modDelim + modValue;
}
out += ' ' + entity + modDelim + modName + modValueString;
}
});
}
}
if (typeof bemjson.mix !== 'undefined') {
// convert object or array into array
const mixes = [].concat(bemjson.mix);
mixes
// filter holes in array
.filter(mix => mix)
.forEach(mix => {
out += (out ? ' ' : '') + buildClassName(mix);
});
}
if (typeof bemjson.className !== 'undefined') {
out += (out ? ' ' : '') + bemjson.className;
}
return out;
}
| JavaScript | 0 | @@ -255,16 +255,24 @@
ate.js')
+.default
(bemjson
|
49e4ea4ea04539ce473da175b48d95277700e33b | Add missing use strict statement to lib/index.js | lib/index.js | lib/index.js | var Client = require('./client'),
Sandbox = require('./sandbox'),
accounts = require('./accounts'),
calendars = require('./calendars'),
contacts = require('./contacts'),
model = require('./model'),
request = require('./request'),
transport = require('./transport');
/**
* model
*/
for (var key in model) {
exports[key] = model[key];
}
/**
* accounts
*/
exports.createAccount = accounts.create;
/**
* calendars
*/
exports.createCalendarObject = calendars.createCalendarObject;
exports.updateCalendarObject = calendars.updateCalendarObject;
exports.deleteCalendarObject = calendars.deleteCalendarObject;
exports.syncCalendar = calendars.sync;
/**
* contacts
*/
exports.createCard = contacts.createCard;
exports.updateCard = contacts.updateCard;
exports.deleteCard = contacts.deleteCard;
exports.syncAddressBook = contacts.sync;
/**
* client
*/
exports.Client = Client;
/**
* request
*/
exports.request = request;
exports.Request = request.Request;
/**
* sandbox
*/
exports.createSandbox = function() {
return new Sandbox();
};
exports.Sandbox = Sandbox;
/**
* transport
*/
exports.transport = transport;
exports.Transport = transport.Transport;
| JavaScript | 0.000003 | @@ -1,12 +1,27 @@
+'use strict';%0A%0A
var Client =
|
ab77a4b0726e7e6ee7ee9c0ee8093a314b773175 | refactor add commands from array | lib/index.js | lib/index.js | const api = require('../api')
const getLastMessage = require('./modules/getlastmessage')
class Botact {
constructor(options) {
if (!options.confirmation || !options.token) {
throw 'Bot\'s options isn\'t full.'
}
this.msg = []
this.action = {}
this.settings = options
this.messages = { commands: [], hears: [] }
}
confirm(req, res) {
if (req.body.type === 'confirmation') {
this.settings.group_id = req.body.group_id
return res.end(this.settings.confirmation)
}
return false
}
execute() {
setInterval(() => {
const method = this.msg.map(obj => `API.messages.send(${JSON.stringify(obj)})`)
this.msg = []
if (method.length) {
api('execute', {
code: `return [ ${method.join(',')} ];`,
access_token: this.settings.token
}).then(console.log).catch(console.log)
}
}, 350)
}
command(command, callback) {
if (typeof command === 'object') {
return command.some(cmd => this.messages.commands[cmd.toLowerCase()] = callback)
}
this.messages.commands[command.toLowerCase()] = callback
}
hears(command, callback) {
if (typeof command === 'object') {
return command.some(cmd => this.messages.hears[cmd.toLowerCase()] = callback)
}
this.messages.hears[command.toLowerCase()] = callback
}
on(callback) {
this.messages.on = callback
}
reply(user_id, message, attachments) {
this.msg.push({
user_id: user_id,
message: message,
attachment: attachments
})
}
event(event, callback) {
this.action[event] = callback
}
listen(req, res) {
res.end('ok')
const data = req.body.object
data.body = getLastMessage(data).body
if (req.body.type === 'message_new') {
let methods = {}
Object.keys(this.messages.hears).map(method => methods[method] = this.messages.hears[method])
if (this.messages.commands[data.body.toLowerCase()]) {
this.messages.commands[data.body.toLowerCase()](data)
} else {
if (!Object.keys(methods).length) {
if (typeof this.messages.on === 'function') {
return this.messages.on(data)
}
return console.log('Bot can\'t found reserved reply.')
}
Object.keys(methods).some((key, i) => {
if (new RegExp(key, 'i').test(data.body.toLowerCase())) {
return methods[key](data) || true
}
if (i === --Object.keys(methods).length) {
return this.messages.on(data)
}
})
}
}
if (typeof this.action[req.body.type] === 'function') {
this.action[req.body.type](data)
}
}
}
module.exports = Botact
| JavaScript | 0.000052 | @@ -974,39 +974,32 @@
t') %7B%0A
-return
command.
some(cmd =%3E
@@ -978,36 +978,39 @@
%7B%0A command.
-some
+forEach
(cmd =%3E this.mes
@@ -1052,34 +1052,42 @@
callback)%0A %7D
-%0A%0A
+ else %7B%0A
this.message
@@ -1127,24 +1127,30 @@
= callback%0A
+ %7D%0A
%7D%0A%0A hears
@@ -1220,23 +1220,16 @@
-return
command.
some
@@ -1224,20 +1224,23 @@
command.
-some
+forEach
(cmd =%3E
@@ -1291,26 +1291,34 @@
lback)%0A %7D
-%0A%0A
+ else %7B%0A
this.mes
@@ -1359,24 +1359,30 @@
= callback%0A
+ %7D%0A
%7D%0A%0A on(ca
|
f49f0c7bb89f086cf0050ef3baf02ec84237c156 | Remove eventual onEmpty DOM | lib/html5/_list.js | lib/html5/_list.js | 'use strict';
var isFunction = require('es5-ext/lib/Function/is-function')
, d = require('es5-ext/lib/Object/descriptor')
, isList = require('es5-ext/lib/Object/is-list')
, isPlainObject = require('es5-ext/lib/Object/is-plain-object')
, makeElement = require('dom-ext/lib/Document/prototype/make-element')
, castAttributes = require('dom-ext/lib/Element/prototype/cast-attributes')
, elExtend = require('dom-ext/lib/Element/prototype/extend')
, replaceContent = require('dom-ext/lib/Element/prototype/replace-content')
, isNode = require('dom-ext/lib/Node/is-node')
, isText = require('dom-ext/lib/Text/is-text')
, memoize = require('memoizee/lib/regular')
, map = Array.prototype.map;
module.exports = function (name, childName, isChildNode) {
require('../base/element').extProperties[name] = {
_construct: d(function (list/*, renderItem, thisArg*/) {
var attrs, renderItem, render, thisArg, cb, onEmpty;
if (isPlainObject(list) && !isFunction(arguments[1])) {
attrs = list;
list = arguments[1];
renderItem = arguments[2];
thisArg = arguments[3];
} else {
renderItem = arguments[1];
thisArg = arguments[2];
}
if (isNode(list) || !isList(list) || !isFunction(renderItem)) {
return elExtend.apply(this, arguments);
}
if (attrs) {
if (attrs.onEmpty) {
onEmpty = attrs.onEmpty;
delete attrs.onEmpty;
}
castAttributes.call(this, attrs);
}
cb = function (item, index, list) {
var result;
result = this.safeCollect(renderItem.bind(thisArg, item, index, list));
if (result == null) return null;
if (isText(result) && !result.data && result._isDomExtLocation_) {
return result;
}
if (!isChildNode(result)) {
result = makeElement.call(this.document, childName, result);
}
return result;
};
render = function () {
var content = map.call(list, cb, this._domjs);
if (!content.length && onEmpty) content = onEmpty;
replaceContent.call(this, content);
}.bind(this);
if (typeof list.on === 'function') {
cb = memoize(cb, { length: 1 });
list.on('change', render);
}
render();
return this;
})
};
};
| JavaScript | 0.000005 | @@ -484,16 +484,85 @@
xtend')%0A
+ , remove = require('dom-ext/lib/Element/prototype/remove')%0A
, repl
@@ -1504,24 +1504,72 @@
rs.onEmpty;%0A
+%09%09%09%09%09if (isNode(onEmpty)) remove.call(onEmpty);%0A
%09%09%09%09%7D%0A%09%09%09%09ca
|
e7ad1992ab12a19774c4be3c30724f5677314f45 | Fix a typo | lib/index.js | lib/index.js | 'use babel'
import {Motion} from './main'
import {ensureUninstalled} from './helpers'
module.exports = {
config: {
liveReload: {
description: 'Automatically reload motion page in editor',
type: 'boolean',
default: true
},
lintingDelay: {
description: 'Delay for updating lint messages in editor in ms',
type: 'integer',
minimum: 0,
default: 300
}
},
activate() {
require('atom-package-deps').install().then(function() {
atom.config.set('color-picker.automaticReplace', true)
atom.config.set('autocomplete-plus.enableBuiltinProvider', false)
atom.packages.disablePackage('autocomplete-snippets')
})
this.motion = new Motion()
this.motion.activate()
ensureUninstalled('steel-motion')
ensureUninstalled('intelli-colorpicker')
ensureUninstalled('number-range')
ensureUninstalled('flint')
ensureUninstalled('language-flint')
},
consumeLinter(indieRegistry) {
const linter = indieRegistry.register({name: 'Motion'})
this.motion.consumeLinter(linter)
},
consumeStatusbar(statusBar) {
this.motion.consumeStatusbar(statusBar)
},
provideAutocomplete() {
return this.motion.provideAutocomplete()
},
provideDeclarations() {
return this.flint.provideDeclarations()
},
dispose() {
this.motion.dispose()
}
}
| JavaScript | 0.003765 | @@ -1273,21 +1273,22 @@
rn this.
-flint
+motion
.provide
|
62ca306b5e396e826f5da94bbd7f3b60f3f3d15e | Add more tests | web/src/js/components/Search/__tests__/SearchTextResult.test.js | web/src/js/components/Search/__tests__/SearchTextResult.test.js | /* eslint-env jest */
import React from 'react'
import {
shallow
} from 'enzyme'
const getMockProps = () => ({
result: {
title: 'Some search result',
linkURL: 'http://www.example.com',
snippet: 'This is the search result description.'
}
})
afterEach(() => {
jest.clearAllMocks()
})
describe('SearchTextResult page component', () => {
it('renders without error', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
shallow(
<SearchTextResult {...mockProps} />
)
})
})
| JavaScript | 0 | @@ -577,12 +577,1357 @@
)%0A %7D)
+%0A%0A it('displays the title as a clickable link', () =%3E %7B%0A const SearchTextResult = require('js/components/Search/SearchTextResult').default%0A const mockProps = getMockProps()%0A mockProps.result.title = 'Hey, click to our site!'%0A const wrapper = shallow(%0A %3CSearchTextResult %7B...mockProps%7D /%3E%0A )%0A const anchor = wrapper.find(%60a%5Bhref=%22$%7BmockProps.result.linkURL%7D%22%5D%60).first()%0A expect(anchor.find('h3').first().text()).toEqual('Hey, click to our site!')%0A %7D)%0A%0A it('displays the link URL', () =%3E %7B%0A const SearchTextResult = require('js/components/Search/SearchTextResult').default%0A const mockProps = getMockProps()%0A mockProps.result.linkURL = 'https://example.io'%0A const wrapper = shallow(%0A %3CSearchTextResult %7B...mockProps%7D /%3E%0A )%0A const linkURL = wrapper%0A .find('div')%0A .filterWhere(n =%3E n.text() === 'https://example.io')%0A expect(linkURL.length).toBe(1)%0A %7D)%0A%0A it('displays the snippet text', () =%3E %7B%0A const SearchTextResult = require('js/components/Search/SearchTextResult').default%0A const mockProps = getMockProps()%0A mockProps.result.snippet = 'Hi there!'%0A const wrapper = shallow(%0A %3CSearchTextResult %7B...mockProps%7D /%3E%0A )%0A const snippetElem = wrapper%0A .find('div')%0A .filterWhere(n =%3E n.text() === 'Hi there!')%0A expect(snippetElem.length).toBe(1)%0A %7D)
%0A%7D)%0A
|
41a709f414e27e6d9060f3074e1f78d7a6f63e84 | Add response declaration | lib/index.js | lib/index.js | 'use strict'
// Load modules
const Wreck = require('wreck')
const Boom = require('boom')
const Hoek = require('hoek')
// Declare internals
const internals = {}
exports.register = (server, options, next) => {
server.register({
register: require('bucker'),
options: options.logger || {}
}, (err) => {
next()
})
server.decorate('reply', 'message', function (message, botToken) {
let response
let defaults = {
proxy: 'https://graph.facebook.com/v2.6/me/messages',
access_token: ''
}
switch (options.provider) {
case 'facebook-messenger': {
server.log('debug', 'Using facebook-messenger provider')
const data = this.request.payload
if (data && data.object === 'page') {
data.entry.forEach((entry) => {
entry.messaging.forEach((event) => {
if (event.sender && event.sender.id) {
let payload = {}
payload.recipient = { id: event.sender.id }
payload.message = message
const config = Hoek.applyToDefaults(defaults, options)
const url = config.proxy
const tokenParam = botToken ? `?access_token=${botToken}` : config.access_token ? `?access_token=${config.access_token}` : ''
Wreck.post(url + tokenParam, { payload: payload }, (err, res, payload) => {
server.log('debug', 'FACEBOOK MESSENGER RESPONSE ->')
server.log('debug', payload.toString())
})
} else {
const msg = 'Invalid message format, no sender id provided'
server.log('error', msg)
response = Boom.badRequest(msg)
}
})
})
} else {
const msg = 'Invalid message format'
server.log('error', msg)
response = Boom.badRequest(msg)
}
break
}
default: {
const msg = 'Invalid provider'
server.log('error', msg)
response = Boom.badRequest(msg)
}
}
return this.response(response)
})
server.decorate('reply', 'validateWebhook', function () {
switch (options.provider) {
case 'facebook-messenger': {
response = this.request.query['hub.challenge']
}
default: {
const msg = 'Invalid provider'
server.log('error', msg)
response = Boom.badRequest(msg)
}
}
return this.response(response)
})
server.decorate('reply', 'notify', function (message, botToken, userId) {
let response
let defaults = {
proxy: 'https://graph.facebook.com/v2.6/me/messages',
access_token: ''
}
switch (options.provider) {
case 'facebook-messenger': {
server.log('debug', 'Using facebook-messenger provider')
if (userId) {
let payload = {}
payload.recipient = { id: userId }
payload.message = message
const config = Hoek.applyToDefaults(defaults, options)
const url = config.proxy
const tokenParam = botToken ? `?access_token=${botToken}` : config.access_token ? `?access_token=${config.access_token}` : ''
Wreck.post(url + tokenParam, { payload: payload }, (err, res, payload) => {
server.log('debug', 'FACEBOOK MESSENGER RESPONSE ->')
server.log('debug', payload.toString())
})
} else {
const msg = 'Invalid message format, no sender id provided'
server.log('error', msg)
response = Boom.badRequest(msg)
}
break
}
default: {
const msg = 'Invalid provider'
server.log('error', msg)
response = Boom.badRequest(msg)
}
}
return this.response(response)
})
server.ext('onPreHandler', (request, reply) => {
let response
switch (options.provider) {
case 'facebook-messenger': {
const data = request.payload
if (data && data.object === 'page') {
data.entry.forEach((entry) => {
entry.messaging.forEach((event) => {
request.server.log('debug', 'FACEBOOK MESSENGER REQUEST:')
request.server.log('debug', event)
response = event
if (event.postback && event.postback.referral) {
request.refParams = internals.strParamToParamList(event.postback.referral.ref)
} else if (event.referral) {
request.refParams = internals.strParamToParamList(event.referral.ref)
}
})
})
}
break
}
default: {
response = { status: 'success' }
}
}
request.event = response
return reply.continue()
})
next()
}
internals.strParamToParamList = (strParam) => {
let strParamsList = strParam.split(',')
const params = {}
for (var i = 0; i < strParamsList.length; i++) {
params[strParamsList[i].split(':')[0]] = strParamsList[i].split(':')[1]
}
return params
}
exports.register.attributes = {
pkg: require('../package.json'),
once: true
}
| JavaScript | 0 | @@ -2172,24 +2172,41 @@
nction () %7B%0A
+ let response%0A
switch (
|
70fe2dab0f4105f88105a3583348c16db5ac9763 | add lowr function | lib/index.js | lib/index.js | var async = require('async')
, etcd = new (require('node-etcd'))();
// Accepts an array of strings as configuration keys.
// Each {key1} corresponds to /config/{key1} entry in etcd.
// Returns an object with properties corresponding to input keys.
// Each property is an EventEmitter. It emits the `modified` event
// when the value of the configuration key. In addition, each EventEmitter
// has a `current` property which returns the current string value stored in etcd.
exports.etcd_config = function (keys, callback) {
var config = {};
async.each(
keys,
function (key, callback) {
etcd.get('/config/' + key, function (error, result) {
if (error)
return callback(error);
var watch = etcd.watcher('/config/' + key, result.node.modifiedIndex + 1);
watch.current = result.node.value;
watch.on('change', function (result) {
if (watch.current !== result.node.value)
this.emit('modified', result.node.value);
watch.current = result.node.value;
});
watch.on('error', function (error) {
throw error; // TODO (tjanczuk): consider surfacing etcd errors differently?
});
config[key] = watch;
callback();
});
},
function (error) {
callback && (error ? callback(error) : callback(null, config));
}
);
return config; // for convenience of REPL
};
// Converts response from etcd into a JS object representing only
// the data and its hierarchy. Etcd directories are represented as JS objects.
function etcd2js(node) {
if (node.value !== undefined)
return node.value;
var result = {};
if (Array.isArray(node.nodes)) {
node.nodes.forEach(function (child) {
result[child.key.substring(node.key.length === 1 ? 1 : node.key.length + 1)]
= etcd2js(child);
});
}
return result;
}
exports.etcd2js = etcd2js;
// Gets the key from etcd (recursively) and returns a JS representation of
// the hierarchy.
exports.etcd_get = function (key, callback) {
etcd.get(key, { recursive: true }, function (error, result) {
error ? callback(error): callback(null, etcd2js(result.node));
});
};
| JavaScript | 0.001708 | @@ -2393,12 +2393,2348 @@
%0A %7D);%0A%7D;%0A
+%0A// The .lowr async function completes in either of two situations:%0A//%0A// 1. If the sync_root is not locked, it obtains an exclusive, distributed lock of the sync_root %0A// via etcd and returns a function that can be used to release the lock as a callback parameter. %0A//%0A// 2. If the sync_root is locked, it waits for that lock to be released, and returns without any results.%0A//%0A// This logic allows several homogenic, distributed processes to ensure that a certain workload is%0A// completed by only one of them. %0A//%0A// The lock TTL in etcd is configured with the %60/config/lock.ttl%60 confguration entry. %0A// While the lock is held, it is reset to that TTL every %60/config/lock.renew%60 period. %0Avar lock_id = process.pid + '.' + Date.now();%0Aexports.lowr = function (sync_root, etcdconfig, callback) %7B%0A // Attempt to take the lock%0A etcd.set(%0A '/lock/' + sync_root, %0A lock_id, %0A %7B prevExist: false, ttl: +etcdconfig.lock_ttl.current %7D,%0A function (error, result) %7B%0A if (error) %7B%0A if (error.errorCode === 105) %7B%0A // Lock is currently held, wait for its release%0A var watch = etcd.watcher('/lock/' + sync_root, error.error.index + 1);%0A watch.on('change', function (result) %7B%0A if (result.node.value === undefined)%0A done();%0A %7D);%0A watch.on('error', done);%0A%0A function done(error, result) %7B%0A watch.stop();%0A callback(error, result);%0A %7D%0A%0A return;%0A %7D%0A%0A return callback(error);%0A %7D%0A%0A // Lock was taken, renew it periodically until released%0A%0A var renew = setInterval(function () %7B%0A etcd.set('/lock/' + sync_root, lock_id, %7B ttl: +etcdconfig.lock_ttl.current %7D);%0A %7D, +etcdconfig.lock_renew.current * 1000);%0A%0A // Return a function that must be used to release the lock%0A%0A callback(null, function (callback) %7B%0A clearInterval(renew);%0A etcd.compareAndDelete('/lock/' + sync_root, lock_id, function (error) %7B%0A return callback && callback(error);%0A %7D);%0A %7D);%0A %7D);%0A%7D;%0A
|
6f5f47c0149938ed92d7e64c3e2d4200d0e6625a | Fix for returning only single device | src/plugins/ble.js | src/plugins/ble.js | // install : cordova plugin add https://github.com/don/cordova-plugin-ble-central#:/plugin
// link : https://github.com/don/cordova-plugin-ble-central
angular.module('ngCordova.plugins.ble', [])
.factory('$cordovaBLE', ['$q', function ($q) {
return {
scan: function (services, seconds) {
var q = $q.defer();
ble.scan(services, seconds, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
connect: function (deviceID) {
var q = $q.defer();
ble.connect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
disconnect: function (deviceID) {
var q = $q.defer();
ble.disconnect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
read: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.read(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
write: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.write(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
writeCommand: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.writeCommand(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
notify: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.notify(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
indicate: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.indicate(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isConnected: function (deviceID) {
var q = $q.defer();
ble.isConnected(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isEnabled: function () {
var q = $q.defer();
ble.isEnabled(function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
}
};
}]);
| JavaScript | 0 | @@ -235,16 +235,28 @@
, %5B'$q',
+ '$timeout',
functio
@@ -260,16 +260,26 @@
tion ($q
+, $timeout
) %7B%0A%0A
@@ -351,32 +351,58 @@
q = $q.defer();%0A
+ var devices = %5B%5D;%0A
ble.scan
@@ -447,33 +447,36 @@
%7B%0A
-q.resolve
+devices.push
(result);%0A
@@ -522,32 +522,32 @@
.reject(error);%0A
-
%7D);%0A
@@ -534,32 +534,115 @@
r);%0A %7D);%0A
+ $timeout(function() %7B%0A %09q.resolve(devices);%0A %09%09 %7D, seconds*1000);%0A
return q
|
462fa68d7ea0c6eb1bf5e4230c519a1e0be3cf95 | Add a function to ease page creation. | page/index.js | page/index.js | module.exports = {
detail: require('./detail'),
search: require('./search')
};
| JavaScript | 0 | @@ -1,83 +1,620 @@
-module.exports = %7B%0A detail: require('./detail'),%0A search: require('./search')
+//Dependency%0Avar React = require('react');%0Avar detailMixin = require('./detail').mixin;%0A%0A//Function to help page creation.%0Amodule.exports = %7B%0A detail: detailMixin,%0A search: require('./search'),%0A /**%0A * Helper to creates a detail page.%0A * @param %7Bobject%7D config - The page configtration.%0A * @returns %7Bobject%7D - The react component associated to the page.%0A */%0A createDetail: function createDetail(config)%7B%0A config = config %7C%7C %7B%7D;%0A if(config.mixins !== undefined)%7B%0A config.mixins.push(detailMixin);%0A %7D else %7B%0A config.mixins = %5BdetailMixin%5D;%0A %7D%0A return React.createClass(config);%0A %7D
%0A%7D;%0A
|
ef9ccdded16892d965871416a615c1c2506cae2b | Set the public directory. | lib/index.js | lib/index.js | "use strict";
const BloggifyCore = require("bloggify-core")
, ul = require("ul")
, defaults = require("./defaults")
, Lien = require("lien")
;
/**
* bloggifyServer
* The Bloggify server.
*
* @name bloggifyServer
* @function
* @param {Number} a Param descrpition.
* @param {Number} b Param descrpition.
* @return {Number} Return description.
*/
module.exports = class BloggifyServer extends BloggifyCore {
constructor (options) {
if (typeof options === "string") {
options = { root: options };
}
options = ul.deepMerge(options, defaults);
super(options.root, options);
this.server = new Lien(options.server);
this._serverLoaded = false;
this._serverPort = options.server.port;
this.server.on("load", (err, data) => {
this._serverLoaded = [err, data];
});
if (options.loadPlugins !== false) {
this.loadPlugins();
}
let firstRequests = this._firstRequests = [];
this.on("plugins-loaded", () => {
firstRequests._called = true;
firstRequests.forEach(c => c[2]());
});
this.server.router.use(function (req, res, next) {
if (firstRequests._called) {
return next();
}
firstRequests.push([req, res, next]);
});
}
onLoad (cb) {
if (this._serverLoaded) {
return cb(this._serverLoaded[0], this._serverLoaded[1]);
}
this.server.on("load", cb);
}
};
| JavaScript | 0 | @@ -539,32 +539,33 @@
ns %7D;%0A %7D%0A
+%0A
options
@@ -633,24 +633,105 @@
, options);%0A
+%0A options.server.public = %60$%7Bthis.paths.root%7D/$%7Boptions.server.public%7D%60;%0A%0A
this
|
18f39e6beb8a5461c1689d23bb649e6afee49acc | increase nodejs memory limits | lib/index.js | lib/index.js | #!/bin/sh
':' // ; export MAX_MEM="--max-old-space-size=60"; exec "$(command -v node || command -v nodejs)" "${NODE_OPTIONS:-$MAX_MEM}" "$0" "$@"
/*
* @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
*
* @licence SPM Agent for MongoDB is free-to-use, proprietary software.
* THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
* This source code may not be copied, reverse engineered, or altered for any purpose.
* This source code is to be used exclusively by users and customers of Sematext.
* Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
*/
var SpmAgent = require('spm-agent')
var osAgent = require('spm-agent-os')
var mongoDbAgent = require('./mongodb-agent')
// this requires are here to compile with enclose.js
// var packageJson = require('../package.json')
// var packageJson2 = require('spm-agent/package.json')
var url = require('url')
function MongoDbMonitor () {
var mongoDbUrl = [{url: 'mongodb://localhost:27017/admin'}]
if (SpmAgent.Config.mongodb && SpmAgent.Config.mongodb.url) {
mongoDbUrl = SpmAgent.Config.mongodb.url
} else if (process.env.SPM_MONGODB_URL) {
mongoDbUrl = [{url: process.env.SPM_MONGODB_URL}]
}
if (process.argv.length > 3) {
var parsedUrl = url.parse(process.argv[3])
if (/mongodb/.test(parsedUrl.protocol) && parsedUrl.port !== null) {
mongoDbUrl = [{url: process.argv[3]}]
} else {
console.error('Invalid MongoDB-URL: ' + process.argv[3] + ' using ' + mongoDbUrl)
}
}
var njsAgent = new SpmAgent()
var agentsToLoad = [
mongoDbAgent,
osAgent
]
agentsToLoad.forEach(function (a) {
try {
var Monitor = a
if (a === mongoDbAgent) {
mongoDbUrl.forEach(function (connection) {
var secureUrl = null
if (connection) {
secureUrl = connection.url.replace(/:.*@/i, ' ')
}
SpmAgent.Logger.info('Start Monitor for: ' + secureUrl)
njsAgent.createAgent(new Monitor(connection))
})
} else {
njsAgent.createAgent(new Monitor())
}
} catch (err) {
console.log(err)
SpmAgent.Logger.error('Error loading agent ' + a + ' ' + err)
}
})
return njsAgent
}
var tokens = 0
console.log('SPM Token: ' + SpmAgent.Config.get('tokens.spm'))
if (SpmAgent.Config.get('tokens.spm') || process.env.SPM_TOKEN || process.argv[2] && process.argv[2].length > 30) {
if (process.argv[2] && process.argv[2].length > 30) {
process.env.SPM_TOKEN = process.argv[2]
}
tokens++
MongoDbMonitor()
} else {
console.log('Missing SPM_TOKEN')
}
if (tokens === 0) {
console.log('Please specify the required environment variables: SPM_TOKEN or edit /etc/spmagent/config file')
process.exit(-1)
}
process.on('uncaughtException', function (err) {
console.error((new Date()).toUTCString() + ' uncaughtException:', err.message)
console.error(err.stack)
process.exit(1)
})
| JavaScript | 0.000001 | @@ -53,9 +53,10 @@
ize=
-6
+12
0%22;
|
d3c5aa99800a362f0af86e709913beb7015112bd | customize enhancements #2 | module/Customize/public/scripts/zork/customize.js | module/Customize/public/scripts/zork/customize.js | /**
* User interface functionalities
* @package zork
* @subpackage user
* @author David Pozsar <david.pozsar@megaweb.hu>
*/
( function ( global, $, js )
{
"use strict";
if ( typeof js.customize !== "undefined" )
{
return;
}
var customCssSelector = "head link.customize-stylesheet[data-customize]";
/**
* @class Customize module
* @constructor
* @memberOf Zork
*/
global.Zork.Customize = function ()
{
this.version = "1.0";
this.modulePrefix = [ "zork", "customize" ];
};
global.Zork.prototype.customize = new global.Zork.Customize();
global.Zork.Customize.prototype.reload = function ()
{
$( customCssSelector ).each( function () {
var css = $( this ),
id = css.data( "customize" ),
href = js.core.uploadsUrl
+ "/customize/custom." + id + "."
+ Number( new Date() ).toString(36)
+ ".css",
link = $( "<link />" )
.one( "ready load", function () {
css.remove();
} )
.attr( {
"href" : href,
"type" : "text/css",
"rel" : "stylesheet"
} );
css.removeClass( "customize-stylesheet" );
$( "head" ).append( link );
} );
};
global.Zork.Customize.prototype.properties = function ( element )
{
js.require( "js.ui.dialog" );
element = $( element );
var addButton = $( "<button type='button' />" ).text(
element.data( "jsPropertiesAddLabel" ) ||
js.core.translate( "customize.form.addProperty" )
);
addButton.click( function () {
js.ui.dialog.prompt( {
"message": js.core.translate( "customize.form.addMessage" ),
"input": function ( prop ) {
if ( prop && ( prop = String( prop ).replace( /[^a-zA-Z0-9\-]/, "" ) ) ) {
element
.prepend(
$( "<dd />" )
.append(
$( "<input type='text'>" )
.attr( {
"name": "properties[" + prop + "][value]"
} )
)
.append(
$( "<label />" )
.append(
$( "<input type='checkbox' value='important'>" )
.attr( {
"name": "properties[" + prop + "][priority]"
} )
)
.append( js.core.translate( "customize.form.important" ) )
)
)
.prepend(
$( "<dt />" )
.append(
$( "<label />" )
.attr( "for", "properties[" + prop + "][value]" )
.text( prop )
)
);
}
}
} );
} );
element.before( addButton );
};
global.Zork.Customize.prototype.properties.isElementConstructor = true;
} ( window, jQuery, zork ) );
| JavaScript | 0 | @@ -1277,16 +1277,28 @@
%22href%22
+
: href
@@ -1337,16 +1337,28 @@
%22type%22
+
: %22tex
@@ -1402,16 +1402,28 @@
%22rel%22
+
: %22st
@@ -1435,38 +1435,227 @@
eet%22
-%0A %7D
+,%0A %22class%22 : %22customize-stylesheet%22,%0A %22data-customize%22 : id%0A %7D )%0A .data( %22customize%22, id
);%0A
|
2c3a6ea785caa13aafdf30dcaff8468d54c4b612 | Fix change event on preferences’ redirect list | pages/list.js | pages/list.js | import binarySearch from './binary-search.js';
import compareSequences from './compare-sequences.js';
// Sort siblings next to each other, but don’t separate a (TODO: effective) TLD from the component before.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1315558
const getDomainSort = domain => {
const components = domain.split('.');
const suffixCount =
components.length === 1 ? 0 :
1;
for (let i = 0; i < suffixCount; i++) {
const tail = components.pop();
components[components.length - 1] += '.' + tail;
}
return components.reverse();
};
const associateSelectionActions = (list, buttons) => {
const updateDisabled = () => {
const disabled = list.selectedOptions.length === 0;
buttons.forEach(button => {
button.disabled = disabled;
});
};
list.addEventListener('change', updateDisabled);
updateDisabled();
};
const allowList = document.getElementById('allow');
const allowRemove = document.getElementById('allow-remove');
const allowMove = document.getElementById('allow-move');
const redirectList = document.getElementById('redirect');
const redirectRemove = document.getElementById('redirect-remove');
const redirectMove = document.getElementById('redirect-move');
associateSelectionActions(allowList, [allowRemove, allowMove]);
associateSelectionActions(redirectList, [redirectRemove, redirectMove]);
allowRemove.addEventListener('click', () => {
port.postMessage({
type: 'block',
hostnames: Array.from(allowList.selectedOptions, option => option.text),
});
});
allowMove.addEventListener('click', () => {
port.postMessage({
type: 'redirect',
hostnames: Array.from(allowList.selectedOptions, option => option.text),
});
});
redirectRemove.addEventListener('click', () => {
port.postMessage({
type: 'block',
hostnames: Array.from(redirectList.selectedOptions, option => option.text),
});
});
redirectMove.addEventListener('click', () => {
port.postMessage({
type: 'allow',
hostnames: Array.from(redirectList.selectedOptions, option => option.text),
});
});
const optionSorts = new WeakMap();
const domainOptions = new Map();
const createDomainOption = domain => {
const option = document.createElement('option');
option.text = domain;
optionSorts.set(option, getDomainSort(domain));
domainOptions.set(domain, option);
return option;
};
const compareOptions = (a, b) =>
compareSequences(optionSorts.get(a), optionSorts.get(b));
const removeIfExists = hostname => {
const option = domainOptions.get(hostname);
if (option === undefined) {
return null;
}
const parent = option.parentNode;
option.remove();
domainOptions.delete(hostname);
return parent;
};
const port = browser.runtime.connect({
name: 'state',
});
port.onMessage.addListener(message => {
switch (message.type) {
case 'state': {
const { redirect, allow } = message;
allow.map(createDomainOption)
.sort(compareOptions)
.forEach(allowList.appendChild, allowList);
redirect.map(createDomainOption)
.sort(compareOptions)
.forEach(redirectList.appendChild, redirectList);
break;
}
case 'allow':
case 'redirect':
case 'block': {
const { hostnames } = message;
let allowChanged = false;
let redirectChanged = false;
for (const hostname of hostnames) {
switch (removeIfExists(hostname)) {
case allowList:
allowChanged = true;
break;
case redirectList:
redirectChanged = true;
break;
}
}
const targetList =
message.type === 'allow' ? (allowChanged = true, allowList) :
message.type === 'redirect' ? (redirectChanged = true, redirectList) :
null;
if (targetList !== null) {
for (const hostname of hostnames) {
const option = createDomainOption(hostname);
const insertIndex = binarySearch(targetList.options, reference => compareOptions(option, reference));
if (insertIndex === targetList.options.length) {
targetList.appendChild(option);
} else {
targetList.options[insertIndex].before(option);
}
}
}
if (allowChanged) {
allowList.dispatchEvent(new Event('change'));
}
if (redirectChanged) {
allowList.dispatchEvent(new Event('change'));
}
break;
}
default:
throw new Error(`Unexpected message type ${message.type}`);
}
});
port.postMessage({
type: 'state',
});
| JavaScript | 0 | @@ -4061,37 +4061,40 @@
ctChanged) %7B%0A%09%09%09
-allow
+redirect
List.dispatchEve
|
54c16c82884055987ca52a50fcc50f5583ff0766 | Support resetting a build for requiring | lib/index.js | lib/index.js | /*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/
var log = require('./log'),
fs = require('fs'),
path = require('path'),
pack = require('./pack'),
args = require('./args'),
find = require('./util').find,
CWD = process.cwd(),
queue = [],
buildRunning = false,
exists = fs.exists || path.exists;
exports.cwd = function() {
return CWD;
};
var runQueue = function() {
if (!buildRunning) {
var item = queue.pop();
if (item) {
buildRunning = true;
exports.init(item.opts, function() {
buildRunning = false;
item.callback();
runQueue();
});
}
}
};
exports.add = function(opts, callback) {
queue.push({
opts: opts,
callback: callback
});
runQueue();
};
exports.init = function (opts, initCallback) {
var options = opts || args.parse(),
watch,
buildFile = options.config,
buildFileName;
if (options.cwd) {
CWD = options.cwd;
}
if (!buildFile) {
buildFile = path.join(CWD, 'build.json');
}
buildRunning = true;
buildFileName = path.basename(buildFile);
options.buildFile = buildFile;
options.buildFileName = buildFileName;
if (options.version || options.help) {
require('./help');
return;
}
if (options['global-config']) {
log.info('racing to find the closest .shifter.json file');
find(CWD, '.shifter.json', function(err, file) {
if (file) {
log.info('woohoo, found a config here: ' + file);
var json = JSON.parse(fs.readFileSync(file, 'utf8'));
Object.keys(json).forEach(function(key) {
if (!args.has(key)) {
log.info('override config found for ' + key);
options[key] = json[key];
}
});
}
});
}
if (options.watch) {
watch = require('./watch');
watch.start(options);
return;
}
if (options.quiet) {
log.quiet();
}
log.info('revving up');
if (!options.walk) {
log.info('looking for ' + buildFileName + ' file');
}
exists(buildFile, function (yes) {
var json, walk, ant;
if (yes) {
if (options.ant) {
log.error('already has a ' + buildFileName + ' file, hitting the brakes');
}
log.info('found ' + buildFileName + ' file, shifting');
try {
json = require(buildFile);
} catch (e) {
console.log(e.stack);
log.error('hitting the brakes! failed to parse ' + buildFileName + ', syntax error?');
}
if (pack.valid(json)) {
log.info('putting the hammer down, let\'s build this thing!');
pack.munge(json, options, function (json, options) {
var mods, builder;
if (options.list) {
mods = Object.keys(json.builds).sort();
log.info('This module includes these builds:');
console.log(mods.join(', '));
if (json.rollups) {
log.info('and these rollups');
console.log(Object.keys(json.rollups).join(', '));
}
} else {
builder = require('./builder');
builder.start(json, options, function() {
buildRunning = false;
if (initCallback) {
initCallback();
}
});
}
});
} else {
log.error('hitting the brakes, your ' + buildFileName + ' file is invalid, please fix it!');
}
} else {
if (options.walk) {
walk = require('./walk');
walk.run(options);
} else {
log.warn('no ' + buildFileName + ' file, downshifting to convert ant files');
ant = require('./ant');
ant.process(options, function () {
if (!options.ant) {
exports.init(options, initCallback);
}
});
}
}
});
};
| JavaScript | 0 | @@ -959,41 +959,57 @@
-var options = opts %7C%7C args.parse(
+log.reset();%0A var options = args.defaults(opts
),%0A
@@ -2245,24 +2245,79 @@
t();%0A %7D%0A%0A
+ if (options.silent) %7B%0A log.silent();%0A %7D%0A%0A
log.info
@@ -3699,24 +3699,65 @@
/builder');%0A
+ builder.reset();%0A
|
d7a5954bc099f702c419d90e940bafbab77c7106 | change conditiona in setDestination to !nearestHuman from NH == null or undefined | public/js/board.js | public/js/board.js | var Board = function( attributes ){
this.humanoid;
this.humanoids = attributes.humanoids || [];
this.width = attributes.width || '600px';
this.height = attributes.height || '400px';
}
Board.prototype = {
isPositionEqual: function( position1, position2 ){
return position1.x === position2.x && position1.y === position2.y
},
isValidDestination: function( target_position ){
var result = true
for(var i= 0; i < this.humanoids.length; i++ ){
if( this.isPositionEqual( this.humanoids[i].position , target_position ) ){
result = false
}
}
return result
},
nearestHumanoid: function( humanoidType ){
var similarHumanoids = this.findSimilarHumanoids( humanoidType )
var closestPos = this.findClosestPos( similarHumanoids )
var closestHumanoid = this.findClosestHumanoid( closestPos, similarHumanoids )
return closestHumanoid
},
isAnyHumanRemaining: function(){
var result = false
for( var i=0; i < this.humanoids.length; i++ ){
if(this.humanoids[i].humanType == "human") { result = true; break };
}
return result
},
nextTurn: function(){
for( var i=0; i< this.humanoids.length; i++ ){
this.humanoid = this.humanoids[i]
if( this.humanoid.humanType == "infectedHuman" ){
this.humanoid.incrementTimeSinceInfection()
continue
}
var nearestZombie = this.nearestHumanoid( "zombie" )
var nearestHuman = this.nearestHumanoid( "human" )
var destination = this.setDestination( nearestHuman, nearestZombie )
destination.x = ( (destination.x + this.width) % this.width )
destination.y = ( (destination.y + this.height) % this.height )
if ( this.humanoid.isAbleToBite( nearestHuman ) ){
this.humanoid.bite( nearestHuman )
}
if( this.isValidDestination( destination ) ){
this.humanoid.position = destination
}
};
},
setDestination: function( nearestHuman, nearestZombie ){
if( nearestHuman === null || nearestHuman === undefined ) { return this.humanoid.moveNearest( nearestZombie )}
else if( this.humanoid.humanType == "zombie" ){ return this.setZombieDestination( nearestHuman, nearestZombie ) }
else if( this.humanoid.humanType == "human" ){ return this.setHumanDestination( nearestHuman, nearestZombie ) }
else { return this.humanoid.position }
},
setZombieDestination: function( nearestHuman, nearestZombie ){
if ( Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) < Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) * gameSettings.zombieSpread){
return this.humanoid.moveNearest( nearestHuman )
}
else {
return this.humanoid.moveNearest( nearestZombie )
}
},
setHumanDestination: function( nearestHuman, nearestZombie ){
if ( Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) < gameSettings.humanFearRange ){
return this.humanoid.moveNearest( nearestZombie )
}
else {
return this.humanoid.moveNearest( nearestHuman )
}
},
deleteSelfHumanoid: function(){
var otherHumanoids = []
for( var i=0; i < this.humanoids.length; i++){otherHumanoids.push(this.humanoids[i])}
for( var i=0; i < this.humanoids.length; i++ ){
if( this.isPositionEqual( this.humanoids[i].position , this.humanoid.position ) ){
otherHumanoids.splice( i, 1 )
break
}
}
return otherHumanoids
},
findSimilarHumanoids: function( humanoidType ){
var otherHumanoids = this.deleteSelfHumanoid()
var similar = [];
for( var i=0; i< otherHumanoids.length; i++ ){
if( otherHumanoids[i].humanType === humanoidType ){ similar.push(otherHumanoids[i])}
}
return similar
},
findClosestPos: function( otherHumanoids ){
var closestPos = []
for( var i=0; i< otherHumanoids.length; i++ ){
var dist = Pathfinder.distanceTo( otherHumanoids[i].position, this.humanoid.position )
closestPos.push( dist );
}
return closestPos
},
findClosestHumanoid: function( closestPos, otherHumanoids ){
var closestHumanoidValue = Math.min.apply( null, closestPos )
for( var i=0; i < closestPos.length; i++ ){
if( closestPos[i] == closestHumanoidValue ){ var closestHumanoid = otherHumanoids[i]}
}
return closestHumanoid
}
} | JavaScript | 0.000002 | @@ -1990,16 +1990,17 @@
if(
+!
nearestH
@@ -2008,48 +2008,8 @@
man
-=== null %7C%7C nearestHuman === undefined
) %7B
|
809ddd475e59b6bc08dc60342d482e8a78b86290 | Add comment | lib/index.js | lib/index.js | 'use strict';
var transform = require('babel-core').transform;
var MagicString = require('magic-string');
var traverse = require('babel-traverse')['default'];
var PersistentFilter = require('broccoli-persistent-filter');
function LazyCode(node, options) {
PersistentFilter.call(this, node, options);
}
LazyCode.prototype = Object.create(PersistentFilter.prototype);
LazyCode.prototype.constructor = LazyCode;
LazyCode.prototype.extensions = ['js'];
LazyCode.prototype.targetExtension = 'js';
LazyCode.prototype.processString = function (content) {
var ast = transform(content).ast;
var positions = [];
var s = new MagicString(content);
traverse(ast, {
enter: function(path) {
if (path.node.type === 'CallExpression') {
if (path.node.callee.name === 'define') {
var start = path.node.arguments[2].body.body[0].start;
var end = path.node.arguments[2].body.body[path.node.arguments[2].body.body.length - 1].end;
if (path.node.arguments[0].value === 'dummy/config/environment') {
positions.push([start, end, true]);
} else {
positions.push([start, end]);
}
}
}
}
});
positions.forEach(function(cords) {
var content = s.snip(cords[0], cords[1]).toString();
content = content.split('\n').map(function(piece) {
return piece.trim();
}).join('').replace(/"/g, '\\"');
s.overwrite(cords[0], cords[1], content);
if (cords.length > 2) {
s.insert(cords[0], 'eval("(function() {');
s.insert(cords[0], '})()");');
} else {
s.insert(cords[0], 'eval("');
s.insert(cords[1], '");');
}
});
return s.toString();
};
module.exports = LazyCode;
| JavaScript | 0 | @@ -956,16 +956,232 @@
1%5D.end;%0A
+ // TODO make this generic%0A // Ember CLI is making assumptions on evaluation being in the%0A // module body. The environment has a try/catch return which%0A // requires an outer scope%0A
@@ -1245,24 +1245,24 @@
ronment') %7B%0A
-
@@ -1370,18 +1370,16 @@
%7D%0A
-%0A%0A
@@ -1380,17 +1380,16 @@
%7D%0A
-%0A
%7D%0A
|
aed045646fa7f33f4ac1e657c2e0b04326b11b3f | Fix non camelCase identifiers | lib/node/column-namer.js | lib/node/column-namer.js | 'use strict';
function strip_table_name(name) {
return name.split('.').pop();
}
// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
constructor (columns) {
this.columns = columns.map(name => strip_table_name(name));
}
uniqueName(baseName) {
var name = baseName;
var ok = this.isUnique(name);
if (!ok) {
// try adding a numeric suffix
var count = 1;
while (!ok) {
name = baseName + '_' + (++count);
ok = this.isUnique(name);
}
}
this.columns.push(name); // ?
return name;
}
isUnique(name) {
// TODO: should this be case-insensitive?
return !this.columns.includes(name);
}
};
| JavaScript | 0.999999 | @@ -18,32 +18,31 @@
nction strip
-_
+T
table
-_n
+N
ame(name) %7B%0A
@@ -266,16 +266,15 @@
trip
-_
+T
table
-_n
+N
ame(
|
5fe32b5cb0ff7d66db112171af86583a4f6cd7aa | Replace double backslash in file paths on Windows with single forward slash, fixes #5 | lib/index.js | lib/index.js | var through = require("through");
var path = require("path");
console.warn("Injecting Rewireify into modules");
module.exports = function rewireify(file, options) {
options = {
ignore: options.ignore || ""
};
var ignore = ["__get__", "__set__", "rewire"].concat(options.ignore.split(","));
if (/\.json$/.test(file) || ignore.indexOf(path.basename(file, ".js")) > -1) {
return through();
}
var data = "";
var post = "";
function write(buffer) {
data += buffer;
}
function end() {
post += "/* This code was injected by Rewireify */\n";
post += "var __getter = require(\"" + path.join(__dirname, "__get__") + "\").toString();\n";
post += "var __setter = require(\"" + path.join(__dirname, "__set__") + "\").toString();\n";
post += "\n";
post += "eval(__getter);\n"
post += "eval(__setter);\n"
post += "module.exports.__get__ = __get__;\n";
post += "module.exports.__set__ = __set__;\n";
this.queue(data);
this.queue(post);
this.queue(null);
}
return through(write, end);
};
| JavaScript | 0 | @@ -492,16 +492,194 @@
r;%0A %7D%0A%0A
+ function pathTo(file) %7B%0A var relpath = __dirname;%0A%0A if (path.sep == %22%5C%5C%22) %7B%0A relpath = relpath.replace(/%5C%5C/g, %22/%22);%0A %7D%0A%0A return path.join(relpath, file);%0A %7D%0A%0A
functi
@@ -689,17 +689,16 @@
end() %7B%0A
-%0A
post
@@ -794,33 +794,19 @@
%22 + path
-.join(__dirname,
+To(
%22__get__
@@ -881,25 +881,11 @@
path
-.join(__dirname,
+To(
%22__s
|
482904105748551fa859fcda702baae33d33fe80 | Fix typo | lib/passport-yj/index.js | lib/passport-yj/index.js | /*
* Module dependencies
*/
var Strategy = require('./strategy');
/*
* Framework version
*/
require('pgkinfo')(module, 'version');
/*
* Expose constructors
*/
exports.YJStrategy = Strategy;
| JavaScript | 0.999999 | @@ -107,10 +107,10 @@
e('p
-g
k
+g
info
|
6daf0ffe40d554926808657c747a0cfd8092bd0f | Fix bug with IdP Discovery script | modules/discojuice/www/discojuice/idpdiscovery.js | modules/discojuice/www/discojuice/idpdiscovery.js | /*
* IdP Discovery Service
*
* An implementation of the IdP Discovery Protocol in Javascript
*
* Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
* Licence: LGPLv2
*/
var IdPDiscovery = function() {
var acl = true;
var returnURLs = [];
var serviceNames = {
'http://dev.andreas.feide.no/simplesaml/module.php/saml/sp/metadata.php/default-sp': 'Andreas Developer SP',
'https://beta.foodl.org/simplesaml/module.php/saml/sp/metadata.php/saml': 'Foodle Beta',
'https://foodl.org/simplesaml/module.php/saml/sp/metadata.php/saml': 'Foodle',
'https://ow.feide.no/simplesaml/module.php/saml/sp/metadata.php/default-sp': 'Feide OpenWiki',
'https://openwiki.feide.no/simplesaml/module.php/saml/sp/metadata.php/default-sp': 'Feide OpenWiki Administration',
'https://rnd.feide.no/simplesaml/module.php/saml/sp/metadata.php/saml': 'Feide Rnd',
'http://ulx.foodl.org/simplesaml/module.php/saml/sp/metadata.php/saml': 'Foodle ULX Demo'
};
var query = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
query[d(e[1])] = d(e[2]);
})();
return {
"nameOf": function(entityid) {
if (serviceNames[entityid]) return serviceNames[entityid];
return entityid;
},
"getSP": function() {
return (query.entityID || null);
},
"getName": function() {
return this.nameOf(this.getSP());
},
// This function takes an url as input and returns the hostname.
"getHostname" : function(str) {
var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
return str.match(re)[1].toString();
},
"returnTo": function(e) {
var returnTo = query['return'] || null;
var returnIDParam = query.returnIDParam || 'entityID';
if(!returnTo) {
DiscoJuice.Utils.log('Missing required parameter [return]');
return;
}
if (acl) {
var allowed = false;
var returnToHost = this.getHostname(returnTo);
for (var i = 0; i < returnURLs.length; i++) {
if (returnURLs[i] == returnToHost) allowed = true;
}
if (!allowed) {
DiscoJuice.Utils.log('Access denied for return parameter [' + returnToHost + ']');
return;
}
}
if (e && e.auth) {
returnTo += '&auth=' + e.auth;
}
if (!e.entityid) {
window.location = returnTo;
} else {
window.location = returnTo + '&' + returnIDParam + '=' + escape(e.entityid);
}
},
"receive": function() {
var entityID = this.getSP();
if(!entityID) {
DiscoJuice.Utils.log('Missing required parameter [entityID]');
return;
}
var preferredIdP = DiscoJuice.Utils.readCookie() || null;
if (query.IdPentityID) {
DiscoJuice.Utils.createCookie(query.IdPentityID);
preferredIdP = query.IdPentityID;
}
var isPassive = query.isPassive || 'false';
if (isPassive === 'true') {
this.returnTo(preferredIdP);
}
},
"setup": function(options, rurls) {
var that = this;
this.returnURLs = rurls;
$(document).ready(function() {
var overthere = that;
var name = overthere.getName();
if (!name) name = 'unknown service';
options.callback = function(e) {
overthere.returnTo(e);
};
$("a.signin").DiscoJuice(options);
$("div.noscript").hide();
});
}
};
}();
| JavaScript | 0.000001 | @@ -1790,24 +1790,95 @@
on(e) %7B%0A%09%09%09%0A
+// %09%09%09console.log('ReturnTo');%0A// %09%09%09console.log(e);%0A// %09%09%09return;%0A%09%09%09%0A
%09%09%09var retur
@@ -2191,16 +2191,21 @@
0; i %3C
+this.
returnUR
@@ -2231,16 +2231,21 @@
%09%09%09%09if (
+this.
returnUR
@@ -2283,16 +2283,17 @@
= true;%0A
+%0A
%09%09%09%09%7D%0A%09%09
@@ -2399,24 +2399,112 @@
ost + '%5D');%0A
+%09%09%09%09%09DiscoJuice.Utils.log('Allowed hosts');%0A%09%09%09%09%09DiscoJuice.Utils.log(this.returnURLs);%0A
%09%09%09%09%09return;
@@ -2597,26 +2597,26 @@
f (!e.entity
-id
+ID
) %7B%0A%09%09%09%09wind
@@ -2727,18 +2727,18 @@
e.entity
-id
+ID
);%0A%09%09%09%7D%0A
|
7e7261f0ef2e1044775eec2824a863b3b77966c2 | change public api | lib/index.js | lib/index.js | var esprima = require('esprima');
var fs = require('fs');
var skip = /^\s+\*/gm;
var mapName = function(elm){
return elm.name;
};
var findReturns = function(expr){
var returns = []
expr.body.forEach(function(expr){
if(expr.type === 'ReturnStatement'){
if(expr.argument.type === 'Literal'){
returns.push(expr.argument.value);
} else if(expr.argument.type === 'ObjectExpression'){
returns.push('Object');
} else if(expr.argument.type === 'ArrayExpression'){
returns.push('Array');
} else if(expr.argument.type === 'FunctionExpression'){
returns.push('Function');
}
}
});
return returns;
};
var findRaises = function(expr){
var raises = []
expr.body.forEach(function(expr){
if(expr.type === 'ThrowStatement'){
if(expr.argument.type === 'NewExpression'){
raises.push(expr.argument.callee.name);
}
}
});
return raises;
};
var parseExpressions = function(expr){
var expressions = {};
var _parse = function(expr){
if(!expr){
return;
} else if(expr.length && typeof expr.forEach === 'function'){
return expr.forEach(_parse);
}
if(expr.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'FunctionDeclaration'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'AssignmentExpression' && expr.right.type === 'FunctionExpression'){
var data = {};
if(expr.left.type === 'MemberExpression'){
data.name = expr.left.property.name;
if(expr.left.object.type === 'MemberExpression'){
if(expr.left.object.property.name === 'prototype'){
data.class = expr.left.object.object.name;
}
}
}
if(expr.right.type === 'FunctionExpression'){
data.params = expr.right.params.map(mapName);
data.returns = findReturns(expr.right.body);
data.raises = findRaises(expr.right.body);
}
expressions[expr.loc.start.line] = data;
} else if(expr.type === 'VariableDeclarator' && expr.init.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.init.params.map(mapName),
returns: findReturns(expr.init.body),
raises: findRaises(expr.init.body),
};
} else {
_parse(expr.expression || expr.callee || expr.body || expr.declarations);
}
};
_parse(expr);
return expressions;
};
module.exports.parseDataFile = function(filename, options){
return module.exports.parseData(fs.readFileSync(filename, 'utf-8'), options);
};
module.exports.parseData = function(contents, options){
options = options || {};
var tolerant = (options.tolerant === undefined)? true: options.tolerant;
var parsed = esprima.parse(contents, {comment: true, loc: true, tolerant: tolerant});
var expressions = parseExpressions(parsed);
var results = [];
parsed.comments.forEach(function(comment){
if(comment.type === 'Block'){
var body = comment.value;
body = body.replace(skip, '');
results.push({
doc: body,
data: expressions[comment.loc.end.line + 1],
});
}
});
return results;
};
| JavaScript | 0 | @@ -3308,20 +3308,16 @@
ts.parse
-Data
File = f
@@ -3375,20 +3375,24 @@
ts.parse
-Data
+Contents
(fs.read
@@ -3458,12 +3458,16 @@
arse
-Data
+Contents
= f
@@ -4096,12 +4096,62 @@
results;%0A%7D;%0A
+%0Amodule.exports.parse = module.exports.parseFile;%0A
|
b593b0434d39420196ab742beb7137eb336ccced | Fix casing | source/static/scripts.js | source/static/scripts.js | // Piwik/Matomo
var _paq = _paq || [];
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.openfisca.org"]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.data.gouv.fr/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '4']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
function getPathName() {
if (location.pathname.startsWith('/doc/')) { // Very ugly. Triggered when the doc is hosted under the /doc/ subdomain. A proper configuration system would be preferable.
return '/doc';
}
return '';
}
$(document).ready(function() {
$('a[href^="https://"], a[href^="http://"]').attr("target", "_blank"); // Make all external links open in a new Window
// Activate action button tooltip
$('.actionbutton').tooltip()
});
| JavaScript | 0.000002 | @@ -931,17 +931,17 @@
n a new
-W
+w
indow%0A%0A
|
ae8b3a33c1cb288ba476c1155f94184c9f108f23 | Add suit selection | public/js/index.js | public/js/index.js | $('#simulate').click(function () {
boardData = {
table: { flop: ['ah', 'td', 'jh'] },
hands: [['ac', 'jd'], ['90%']]
};
submitData(boardData, function(data){
$('#output').append($('<pre>').text(JSON.stringify(data, null, ' ')));
});
});
$('#cardPicker').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var playerId = button.attr('data-playerId');
var numCards = button.attr('data-numCards');
console.log(playerId);
console.log(numCards);
var $modal = $(this);
$('#selection-title #currCard', this).text(numCards);
$('#selection-title #numCards', this).text(numCards);
$modal.data("playerId",playerId);
<!-- TODO: implement num cards functionality -->
});
$("#saveCards").click(function() {
console.log("Saving changes for player id: " + $("#cardPicker").data("playerId"));
});
$(window).load(function() {
$('#liteAccordion').liteAccordion({
containerWidth: 700,
containerHeight: 500
});
});
| JavaScript | 0 | @@ -1,12 +1,68 @@
+var suits = %5B'clubs', 'spades', 'diamonds', 'hearts'%5D;%0A%0A
$('#simulate
@@ -1125,16 +1125,631 @@
500%0A %7D);%0A%7D);%0A
+%0A/*%0A * Modal suit pickers:%0A */%0A%0A/*%0A * When you click on a suit image, it will display the cards associated with the suit and hide the old display.%0A */%0A(function () %7B%0A var suitDisplayed = suits%5B0%5D; // init%0A%0A function getCardDisplay(suit) %7B%0A return $('#card-selection-' + suit.toLowerCase());%0A %7D%0A%0A suits.forEach(function (suit) %7B%0A $('.suit-select #suit-' + suit).click(function () %7B%0A getCardDisplay(suitDisplayed).hide();%0A%0A getCardDisplay(suit).show();%0A suitDisplayed = suit;%0A %7D);%0A %7D);%0A%0A $('.suit-select #suit-' + suitDisplayed).click();%0A%7D)();%0A%0A
|
55fc827b45bcee19b29bd1f732d6978632f43030 | Add alert command | lib/index.js | lib/index.js | define(['require', 'exports', './terminal', './env', './fs/index'], function(require, exports, terminal, env, fs) {
var Terminal = exports.Terminal = terminal.Terminal;
var Environment = exports.Environment = env.Environment;
var Filesystem = exports.Filesystem = fs.Filesystem;
exports.Machine = (function() {
function Machine(name) {
this.name = name;
var fsData;
// try {
// fsData = JSON.parse(localStorage.machines)[name];
// } catch(e) {
fsData = {
root: {
files: {
bin: {
files: {
echo: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(args.join(' '));
context.data.write(args.join(' '));
}
}
},
pwd: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(context.fs.pathTo(context.currentDir));
context.data.write(context.fs.pathTo(context.currentDir));
}
}
},
ls: {
executable: true,
command: {
exec: function(args, context) {
var files = context.fs.listFiles(context.fs.getFile(args[0], context.currentDir));
files.forEach(function(file) {
context.view.stream.write(file.name);
});
}
}
},
cd: {
executable: true,
command: {
exec: function(args, context) {
context.currentDir = context.fs.getFile(args[0], context.currentDir) || context.currentDir;
}
}
},
test: {
executable: true,
command: {
exec: function(args, context) {
console.log(arguments);
context.data.on('data', function(d) {
alert('someone sent me: ' + d);
});
}
}
}
}
}
}
}
};
// }
this.fs = new Filesystem(fsData);
this.env = new Environment({
vars: {
PATH: "/bin"
}
}, this.fs);
/*try {
var machines = JSON.parse(localStorage.machines);
} catch(e) {
var machines = {};
}
machines[this.name] = this.fs.data;
localStorage.machines = JSON.stringify(machines);*/
}
Machine.prototype.createTerminal = function createTerminal(view) {
return new Terminal(this, view);
};
return Machine;
})();
});
| JavaScript | 0.000026 | @@ -1685,32 +1685,334 @@
%09%09%7D%0A%09%09%09%09%09%09%09%09%09%7D,%0A
+%09%09%09%09%09%09%09%09%09alert: %7B%0A%09%09%09%09%09%09%09%09%09%09executable: true,%0A%09%09%09%09%09%09%09%09%09%09command: %7B%0A%09%09%09%09%09%09%09%09%09%09%09exec: function(args, context) %7B%0A%09%09%09%09%09%09%09%09%09%09%09%09if(args.length %3E 0 && args%5B0%5D) alert(args.join(' '));%0A%09%09%09%09%09%09%09%09%09%09%09%09context.data.on('data', function(d) %7B%0A%09%09%09%09%09%09%09%09%09%09%09%09%09alert(d);%0A%09%09%09%09%09%09%09%09%09%09%09%09%7D);%0A%09%09%09%09%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%09%09%09%7D,%0A
%09%09%09%09%09%09%09%09%09test: %7B
|
d81ddccf6f38c9e8e7545d8fd892faa37bc6eeb5 | Update Invitation Service's updateInvitation method to return the result | lib/invitations.js | lib/invitations.js | var async = require('async'),
crypto = require('crypto'),
pg = require('pg'),
config = require('../config'),
INVITATIONS = 'SELECT * FROM invitations ORDER BY id',
INVITATION_BY_ID = 'SELECT * FROM invitations WHERE id=$1 LIMIT 1',
INVITATION_GUESTS = 'SELECT * FROM guests WHERE invitation_id=$1',
UPDATE_INVITATION = 'UPDATE invitations SET rsvp=true WHERE id=$1';
exports.encipherId = function (id) {
var cipher = crypto.createCipher('bf', config.secrets.invitation);
cipher.update(String(id), 'utf8', 'hex');
return cipher.final('hex');
};
exports.decipherId = function (encipheredId) {
var decipher = crypto.createDecipher('bf', config.secrets.invitation);
decipher.update(encipheredId, 'hex', 'utf8');
return decipher.final('utf8');
};
exports.loadInvitation = function (id, callback) {
function processResults(results, callback) {
var invitation = results.invitation.rows[0];
if (invitation) {
invitation.guests = results.guests.rows;
}
callback(null, invitation);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
async.parallel.bind(null, {
invitation: db.query.bind(db, INVITATION_BY_ID, [id]),
guests : db.query.bind(db, INVITATION_GUESTS, [id])
}),
processResults
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.loadInvitations = function (callback) {
function processInvitation(db, invitation, callback) {
db.query(INVITATION_GUESTS, [invitation.id], function (err, results) {
if (err) { return callback(err); }
invitation.guests = results.rows;
callback(null, invitation);
});
}
function processInvitations(db, results, callback) {
async.map(results.rows, processInvitation.bind(null, db), callback);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
db.query.bind(db, INVITATIONS),
processInvitations.bind(null, db)
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.updateInvitation = function (id, changes, callback) {
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
db.query(UPDATE_INVITATION, [id], function () {
done();
callback.apply(null, arguments);
});
});
};
| JavaScript | 0 | @@ -2582,32 +2582,44 @@
%5Bid%5D, function (
+err, results
) %7B%0A
@@ -2646,38 +2646,48 @@
callback
-.apply(null, arguments
+(err, results && results.rows%5B0%5D
);%0A
|
2a16ebd43ac451e4dff7a4f9cedfddfa2ef971e2 | remove test code | lib/jobs/create.js | lib/jobs/create.js | 'use strict';
var method = require('./../method');
var assign = require('lodash.assign');
var path = require('path');
var os = require('os');
var fs = require('fs');
var AdmZip = require('adm-zip');
/**
* @memberof jobs
* @method create
* @description Create a new Paperspace job.
* @param {object} params - Job creation parameters
* @param {string} params.name - A memorable name for this job
* @param {string} params.machineType - Job type: either 'GPU+', 'P4000', 'P5000', 'P6000', 'V100', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', or 'C10'<p>
* @param {string} params.container - A required reference to a container name or container link to be used for the job.
* @param {string} [params.project] - The name of the project for this job. If not provided, this is taken from the .ps_project/config.json file, or the current directory name.
* @param {string} [params.command] - An optional command to run within the workspace or container.
* @param {string} [params.workspace] - An optional path to a workspace to merge with the container. If a zip file is provided that is used instead. If no workspace is provieded the current directory is zipped up and transferred. If the workspace is 'none', no workspace is merged and the container is run as-is.
* @param {string} [params.dataset] - An optional reference to a dataset to be merged with the container.
* @param {function} cb - Node-style error-first callback function
* @returns {object} job - The created job JSON object
* @example
* paperspace.jobs.create({
* name: 'My Job 1',
* machineType: 'P6000',
* container: 'http://dockerhub.com/mycontainer',
* project: 'My Project' // Optional; if not specified the project name is taken from the current directory or the .ps_project/config.json file.
* }, function(err, resp) {
* // handle error or http response
* });
* @example
* $ paperspace jobs create \
* --name "My Job 1" \
* --machineType "P6000" \
* --container "http://dockerhub.com/mycontainer" \
* --project "My Project"
* @example
* # HTTP request:
* https://api.paperspace.io
* POST /jobs/createJob { "name": "My Job 1", "machineType": "P6000", "container": "http://dockerhub.com/mycontainer", "project": "My Project"}
* x-api-key: 1ba4f98e7c0...
* # Returns 201 on success
* @example
* // Example return value:
* {
* "id": "j123abc",
* "name": "My Job 1",
* "machineType": "P6000",
* "project": "My Project",
* "state": "Pending",
* }
*/
function create(params, cb) {
var cwd = process.cwd();
// XXX TODO test code DO NOT CHECK IN:
cwd = '/home/sanfilip/sdk/streamtest';
if (!params.project && !params.projectId) {
// default to name of project in .ps_project/config or name of current directory
params.project = path.basename(cwd);
if (params.project == '/') {
var err = { error: 'Error: cannot create project from root dir. Please create a project dir and run from there.' };
console.log(err.error);
return err;
}
}
if (params.workspace) {
if (params.workspace != 'none') {
if (!fs.existsSync(params.workspace)) {
var err = { error: 'Error: cannot find workspace file.' };
console.log(err.error);
return err;
}
// TODO check that workspace file is a zip file
// save workspace file name as a extra parameter since we are not using multer to parse the files on the server
params.workspaceFileName = path.basename(workspace);
}
}
if (!params.workspace) {
// no workspace provided; zip the current directory
// don't allow zipping of the root directory
if (cwd == '/') {
var err = { error: 'Error: cannot zip workspace from root dir.' };
console.log(err.error);
return err;
}
// construct zip file name in tmpdir
var zip_file = path.resolve(os.tmpdir(), path.basename(cwd) + '.zip');
// delete prior zip file if it exists
if (fs.existsSync(zip_file)) {
fs.unlinkSync(zip_file);
}
// zip up current working directory
var zip = new AdmZip();
zip.addLocalFolder(cwd);
zip.writeZip(zip_file);
//check it does not exceed the current limit for upload using loopback storage component with s3
if (getFilesizeInBytes(zip_file) > 10485760) {
var err = { error: 'Error: zipped workspace ' + zip_file + ' cannot exceed 10485760 bytes.' };
console.log(err.error);
return err;
}
// save name of the workspace file for superagent to attach it
params.workspace = zip_file;
// save workspace file name as a extra parameter since we are not using multer to parse the files on the server
params.workspaceFileName = path.basename(zip_file);
} else {
// no workspace desired
if (params.workspace == 'none') delete params.workspace;
}
return method(create, params, cb);
}
function getFilesizeInBytes(filename) {
var stats = fs.statSync(filename)
var fileSizeInBytes = stats["size"]
return fileSizeInBytes
}
assign(create, {
auth: true,
group: 'jobs',
name: 'create',
method: 'post',
route: '/jobs/createJob',
requires: {
name: 'string',
machineType: 'string',
container: 'string',
},
file: 'workspace',
returns: {},
});
module.exports = create;
| JavaScript | 0.000873 | @@ -2596,16 +2596,19 @@
CK IN:%0A%09
+//
cwd = '/
|
914fd59719b4480d2b3b46b2c3f52c098667f0c5 | Fix null value | lib/protocol/endpoint.js | lib/protocol/endpoint.js | "use strict";
const EventEmitter = require("events");
const noop = () => {};
const noopLogger = {
fatal: noop,
error: noop,
warn : noop,
info : noop,
debug: noop,
trace: noop,
child: function() { return this; }
};
const CLIENT_PRELUDE = Buffer.from("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
module.exports = function(dependencies) {
const tls = dependencies.tls;
const protocol = dependencies.protocol;
function Endpoint(options) {
EventEmitter.call(this);
this.options = options;
options.host = options.host || options.address;
options.servername = options.address;
this._acquiredStreamSlots = 0;
this._maximumStreamSlots = 0;
this._lastSuccessPingedTime = null;
this._PingedThreshold = (this.options.heartBeat || 30000) * 2;
this._heartBeatInterval = (this.options.heartBeat || 30000);
options.ALPNProtocols = ["h2"];
this._connect();
this._setupHTTP2Pipeline();
this._heartBeatIntervalCheck = this._setupHTTP2HealthCheck();
}
Endpoint.prototype = Object.create(EventEmitter.prototype, {
availableStreamSlots: {
get: function() {
return this._maximumStreamSlots - this._acquiredStreamSlots;
}
}
});
Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
const serializer = new protocol.Serializer(noopLogger.child("serializer"));
const compressor = new protocol.Compressor(noopLogger.child("compressor"), "REQUEST");
const deserializer = new protocol.Deserializer(noopLogger.child("deserializer"));
const decompressor = new protocol.Decompressor(noopLogger.child("decompressor"), "RESPONSE");
this._connection.pipe(compressor);
compressor.pipe(serializer);
serializer.pipe(this._socket);
this._socket.pipe(deserializer);
deserializer.pipe(decompressor);
decompressor.pipe(this._connection);
this._connection.on("RECEIVING_SETTINGS_HEADER_TABLE_SIZE", compressor.setTableSizeLimit.bind(compressor));
this._connection.on("ACKNOWLEDGED_SETTINGS_HEADER_TABLE_SIZE", decompressor.setTableSizeLimit.bind(decompressor));
this._connection.on("RECEIVING_SETTINGS_MAX_CONCURRENT_STREAMS", maxStreams => {
this._maximumStreamSlots = maxStreams;
this.emit("wakeup");
});
serializer.on("error", this._protocolError.bind(this, "serializer"));
compressor.on("error", this._protocolError.bind(this, "compressor"));
deserializer.on("error", this._protocolError.bind(this, "deserializer"));
decompressor.on("error", this._protocolError.bind(this, "decompressor"));
};
Endpoint.prototype._connect = function connect() {
this._socket = tls.connect(this.options);
this._socket.on("secureConnect", this._connected.bind(this));
this._socket.on("error", this._error.bind(this));
this._socket.on("close", this._close.bind(this));
this._socket.on("end", this.emit.bind(this, "end"));
this._socket.write(CLIENT_PRELUDE);
this._connection = new protocol.Connection(noopLogger, 1);
this._connection.on("error", this._protocolError.bind(this, "connection"));
this._connection.on("GOAWAY", this._goaway.bind(this));
};
Endpoint.prototype._connected = function connected() {
this.emit("connect");
};
Endpoint.prototype._setupHTTP2HealthCheck = function healthcheck() {
return setInterval(() => {
if ((Date.now() - this._lastSuccessPingedTime) > _PingedThreshold) {
_error("Not receiving Ping response after " + this._PingedThreshold + " ms");
}
else {
this._connection.ping(()=> { this._lastSuccessPingedTime = Date.now() });
}
}, this._heartBeatInterval);
};
Endpoint.prototype._protocolError = function protocolError(component, errCode) {
this._error(component + " error: " + errCode);
};
Endpoint.prototype._error = function error(err) {
this.lastError = err;
this.emit("error", err);
};
Endpoint.prototype._goaway = function goaway(frame) {
// When we receive a goaway we must be prepared to
// signal streams which have not been processed by the
// server enabling them to be re-enqueued. We hold
// onto the last stream ID to process it in `close`
this.lastStream = frame.last_stream;
if (frame.error === "NO_ERROR") {
return;
}
let message = "GOAWAY: " + frame.error;
if(frame.debug_data) {
message += " " + frame.debug_data.toString();
}
this._error(message);
}
Endpoint.prototype._close = function close() {
// After the endpoint closes we loop through all
// dangling streams to handle their state.
this._connection._streamIds.forEach( (stream, id) => {
// Ignore stream 0 (connection stream)
if (id === 0) {
return;
}
// let stream = this._connection._streamIds[id];
// Is stream unprocessed? (last_stream < id)
if (this.lastStream < id) {
stream.emit("unprocessed");
} else if (this.lastError) {
// If it *has* been at least partially processed
// and an error has occurred
stream.emit("error", this.lastError);
}
});
}
Endpoint.prototype.createStream = function createStream() {
let stream = this._connection.createStream();
this._connection._allocateId(stream);
this._acquiredStreamSlots += 1;
stream.on("end", () => {
stream = null;
this._acquiredStreamSlots -= 1;
this.emit("wakeup");
if (this._closePending) {
this.close();
}
});
return stream;
};
Endpoint.prototype.close = function close() {
if (this._acquiredStreamSlots === 0) {
this._connection.close();
}
this._closePending = true;
};
Endpoint.prototype.destroy = function destroy() {
clearInterval(this._heartBeatIntervalCheck);
this._socket.destroy();
};
return Endpoint;
};
| JavaScript | 0.000176 | @@ -3352,16 +3352,55 @@
if (
+this._lastSuccessPingedTime != null &&
(Date.no
@@ -3436,16 +3436,21 @@
Time) %3E
+this.
_PingedT
@@ -3645,16 +3645,17 @@
te.now()
+;
%7D);%0A
|
d808a3f88a6eb69719351cab2f5d47456b321df9 | update default colors | public/js/likes.js | public/js/likes.js | /* globals define, app, ajaxify, bootbox, socket, templates, utils */
$(document).ready(function () {
'use strict';
require([
'translator'
], function (translator) {
var events = {
'event:voted' : likesDidUpdate,
'posts.upvote': likeDidChange,
'posts.unvote': likeDidChange
}, components = {
TOGGLE_BUTTON: 'ns/likes/toggle',
COUNT_BUTTON : 'ns/likes/count',
USER_LIST : 'ns/likes/users'
}, previewLimit = 3, Color = net.brehaut.Color,
initColor = Color('#9e9e9e'), targetColor = Color('#ff0000'), totalToColor = 8;
$(window).on('action:ajaxify.start', function (ev, data) {
if (ajaxify.currentPage !== data.url) {
setSubscription(false);
}
});
$(window).on('action:topic.loading', function (e) {
//To be sure, that we subscribed only once
setSubscription(false);
setSubscription(true);
addListeners(
$(getComponentSelector(components.TOGGLE_BUTTON)),
$(getComponentSelector(components.COUNT_BUTTON))
);
});
$(window).on('action:posts.loaded', function (e, data) {
data.posts.forEach(function (post, index) {
addListeners(
getComponentByPostId(post.pid, components.TOGGLE_BUTTON),
getComponentByPostId(post.pid, components.COUNT_BUTTON)
);
});
});
function addListeners($toggleButtons, $countButtons) {
$toggleButtons.on('click', function (e) {
var $el = $(this);
toggleLike(getPostId($el), $el.hasClass('liked'));
});
$countButtons.on('click', function (e) {
showVotersFor(getPostId($(this)));
});
$countButtons.each(function (index, el) {
var $el = $(el);
evaluateVotesNumber($el, parseInt($el.text()));
});
}
function evaluateVotesNumber($button, votes) {
$button.css(
'color',
initColor.blend(targetColor, votes / totalToColor).toCSS());
}
function getComponentByPostId(pid, componentType) {
return $('[data-pid="' + pid + '"]').find(getComponentSelector(componentType));
}
function getComponentSelector(componentType) {
return '[component="' + componentType + '"]';
}
function getPostId($child) {
return $child.parents('[data-pid]').attr('data-pid');
}
/**
* Triggered on like/unliked
* @param data {object} Fields: {downvote:false,post:{pid:"14",uid: 4,votes:2},upvote:true,user:{reputation:3}}
*/
function likeDidChange(data) {
var label = data.upvote ? ' Unlike' : ' Like';
getComponentByPostId(data.post.pid, components.TOGGLE_BUTTON).toggleClass('liked', data.upvote).text(label);
}
/**
* Triggered on Like entity update
* @param data {object} Same signature as for like/unliked handler
*/
function likesDidUpdate(data) {
var votes = data.post.votes;
var button = getComponentByPostId(data.post.pid, components.COUNT_BUTTON);
button.data('likes', votes).text(votes);
evaluateVotesNumber(button, votes);
//TODO Re-render list only if user is interested in it
//showVotersFor(data.post.pid);
}
function renderVoters($el, votersData) {
var usernames = votersData.usernames, len = usernames.length, previewUsernames, renderNames, count = votersData.otherCount;
if (len + count > previewLimit) {
previewUsernames = usernames.slice(0, previewLimit);
count = count + len - previewLimit;
//Commas are not allowed from translation
renderNames = previewUsernames.join(', ').replace(/,/g, '|');
translator.translate('[[topic:users_and_others, ' + renderNames + ', ' + count + ']]', function (translated) {
translated = translated.replace(/\|/g, ',');
$el.text(translated);
});
} else {
$el.text(usernames.join(', '));
}
$el
.css('opacity', 0)
.animate({'opacity': 1}, 200);
}
function showVotersFor(pid) {
socket.emit('posts.getUpvoters', [pid], function (error, data) {
if (!error && data.length) {
renderVoters(getComponentByPostId(pid, components.USER_LIST), data[0]);
}
});
}
function setSubscription(state) {
var method = state ? 'on' : 'removeListener';
for (var socketEvent in events) {
socket[method](socketEvent, events[socketEvent]);
}
}
function toggleLike(pid, liked) {
socket.emit(liked ? 'posts.unvote' : 'posts.upvote', {
pid : pid,
room_id: app.currentRoom
}, function (error) {
if (error) {
app.alertError(error.message);
}
});
}
});
}); | JavaScript | 0.000001 | @@ -635,13 +635,13 @@
('#9
-e9e9e
+E9E9E
'),
@@ -666,13 +666,13 @@
r('#
-ff000
+4CAF5
0'),
@@ -5493,8 +5493,9 @@
%7D);%0A%7D);
+%0A
|
2e075f5cc86f883f179003d543a321787f1c9971 | Update prefs.js | public/js/prefs.js | public/js/prefs.js | window.prefs = {};
$(document).ready(function() {
window.api.get("prefs/get/name-subj", function(data) {
var btnTrue = data.val;
if(btnTrue == "1") {
$("prefs-hwView-swap").prop("checked", true);
}
$("#prefs-hwView-swap").change(function() {
if(btnTrue == "1") {
btnTrue = "0";
} else {
btnTrue = "1";
};
window.api.post("prefs/set", { name: "name-subj", value: btnTrue}, function() {});
});
});
});
| JavaScript | 0.000001 | @@ -456,16 +456,241 @@
%7D);%0A
+ alert(%22buttonstuff!%22);%0A %7D);%0A $(%22#usr-btn%22).click(function() %7B%0A var usrname = $(%22#usr-name%22).val();%0A window.api.post(%22prefs/setName%22, %7B name: %22#%7Busrname%7D%22 %7D, function() %7B%0A alert(%22maybe this worked!%22);%0A %7D);%0A
%7D);%0A%7D)
|
71f24279ef1a2f852735cbc9522cdfcce17eb725 | remove duplicate | lib/index.js | lib/index.js | 'use strict';
var _ = require('lodash');
// Tasks
//
// require('./tasks/docs/browserSync.js');
// require('./tasks/docs/clean.js');
// require('./tasks/docs/copy.js');
// require('./tasks/docs/deploy.js');
// require('./tasks/docs/ngdocs.js');
// require('./tasks/docs/readme.js');
// require('./tasks/docs/resolveDocsDependencies.js');
// require('./tasks/docs/scripts.js');
// require('./tasks/docs/styles.js');
// require('./tasks/docs/views.js');
// require('./tasks/src/bump.js');
// require('./tasks/src/changelog.js');
// require('./tasks/src/clean.js');
// require('./tasks/src/deploy.js');
// require('./tasks/src/jshint.js');
// require('./tasks/src/scripts.js');
// require('./tasks/src/styles.js');
// require('./tasks/src/templates.js');
// require('./tasks/src/karma.js');
// require('./tasks/test/jshint.js');
require('./debug');
module.exports = function(gulp, options) {
if(!options.type) throw new Error('Required option: \'type\'');
if(!options.pkg) throw new Error('Required option: \'pkg\'');
var config = require('./config')(options);
config.channels = require('gulp-channels')(gulp, config);
require('./tasks/src/bump.js')(gulp, config);
require('./tasks/src/changelog.js')(gulp, config);
require('./tasks/src/clean.js')(gulp, config);
require('./tasks/src/copy.js')(gulp, config);
require('./tasks/src/deploy.js')(gulp, config);
require('./tasks/src/views.js')(gulp, config);
require('./tasks/src/serve.js')(gulp, config);
require('./tasks/src/watch.js')(gulp, config);
require('./tasks/src/jshint.js')(gulp, config);
require('./tasks/src/scripts.js')(gulp, config);
require('./tasks/src/styles.js')(gulp, config);
require('./tasks/src/templates.js')(gulp, config);
require('./tasks/test/clean.js')(gulp, config);
require('./tasks/test/jshint.js')(gulp, config);
require('./tasks/test/karma.js')(gulp, config);
require('./tasks/docs/clean.js')(gulp, config);
require('./tasks/docs/browserSync.js')(gulp, config);
require('./tasks/docs/clean.js')(gulp, config);
require('./tasks/docs/copy.js')(gulp, config);
require('./tasks/docs/deploy.js')(gulp, config);
require('./tasks/docs/ngdocs.js')(gulp, config);
require('./tasks/docs/readme.js')(gulp, config);
require('./tasks/docs/resolveDocsDependencies.js')(gulp, config);
require('./tasks/docs/scripts.js')(gulp, config);
require('./tasks/docs/styles.js')(gulp, config);
require('./tasks/docs/views.js')(gulp, config);
};
module.exports.component = function(gulp, options) {
options.type = 'component';
module.exports(gulp, options);
};
module.exports.application = function(gulp, options) {
options.type = 'application';
module.exports(gulp, options);
};
| JavaScript | 0.004769 | @@ -1883,59 +1883,8 @@
);%0A%0A
- require('./tasks/docs/clean.js')(gulp, config);%0A%0A
re
|
7f61b5dca20864208fbcaad669423446a6164137 | Add year-parser test case | db/test/unit/tdsystem/year-parser.spec.js | db/test/unit/tdsystem/year-parser.spec.js | 'use strict';
var client = require('cheerio-httpcli');
var parser = require('../../../js/tdsystem/year-parser');
var util = require('../../../js/swimtrack-util');
var testUrl = 'http://www.tdsystem.co.jp/i2015.htm';
describe('Test 2015 top page', function() {
it('should find a right meet and venue from a given meet name', function(done) {
client.fetch(testUrl, 'Shift_JIS', function(err, $, res) {
let parseResult = parser.parsePage(2015, $);
let meets = parseResult.meets;
let meetFound = false;
for (let i = 0; i < meets.length; i++) {
let meet = meets[i];
if (meet.name === '中部学生選手権水泳競技大会') {
meetFound = true;
expect(meet.days).toContain('2015-07-04');
expect(meet.days).toContain('2015-07-05');
expect(meet.venue.city).toEqual('愛知');
expect(meet.venue.name).toEqual('日本ガイシアリーナ');
expect(meet.venue.course).toEqual('長水路');
break;
}
}
expect(meetFound).toEqual(true);
done();
});
});
});
| JavaScript | 0.000041 | @@ -365,21 +365,8 @@
Url,
- 'Shift_JIS',
fun
@@ -474,16 +474,58 @@
.meets;%0A
+ expect(meets.length).toEqual(198);%0A%0A
le
|
dde71cf4893ce6503370a8e018697c4b3d010261 | Use local version of async-each | lib/index.js | lib/index.js |
/**
* Module dependencies
*/
var LZString = require('./vendor/lz-string');
var Promise = require('promise');
var map = require('map');
var each = require('each');
var type = require('type');
// bug, see: https://github.com/paulmillr/async-each/issues/2
require('async-each');
var asyncEach = window.asyncEach;
/**
* Expose `storage`
*/
module.exports = exports = {};
/**
* Constants
*/
var LIMIT = 1024*20; // 20kb
var PREFIX = '.b'; // default prefix for every block
var KEYS = '.storage-keys'; // namespace for storing keys
var SEPARATOR = '~'; // keys separator
/**
* Put `val` with `key` to the storage.
* Put means add or replace.
*/
exports.put = Promise.denodeify(function(key, val, cb) {
key = prepareKey(key);
getBlock(key, function(err, res) {
put(res, key, val);
saveBlock(res, cb);
});
});
/**
* Get value from the storage by `key`.
*/
exports.get = Promise.denodeify(function(key, cb) {
key = prepareKey(key);
getBlock(key, function(err, res) {
cb(null, res.values[key]);
});
});
/**
* Delete value by `key`
*/
exports.del = Promise.denodeify(function(key, cb) {
key = prepareKey(key);
getBlock(key, function(err, res) {
if (err) return cb(err);
del(res, key);
saveBlock(res, cb);
});
});
/**
* Batch operations in one transaction
* `ops` has levelup semantic
* https://github.com/rvagg/node-levelup#batch
*/
exports.batch = Promise.denodeify(function(ops, cb) {
if (type(ops) !== 'array') return cb(new Error('`operations` must be array'));
var keys = map(ops, 'key');
var blocks = [];
var keysMap = {};
var blocksMap = {};
// get block's names for change
each(keys, function(key) {
key = prepareKey(key);
var name = getBlockName(key);
keysMap[key] = name;
if (!~blocks.indexOf(name)) {
blocks.push(name);
blocksMap[name] = blocks.length - 1;
}
});
asyncEach(blocks, getBlockByName, function(err, blocks) {
each(ops, function(op) {
var key = prepareKey(op.key);
var index = blocksMap[keysMap[op.key]];
var res = blocks[index];
op.type === 'put' ? put(res, key, op.value) : del(res, key);
});
asyncEach(blocks, saveBlock, cb);
});
});
/**
* Iterator
*/
exports.forEach = Promise.denodeify(function(fn, cb) {
asyncEach(getKeys(), getBlock, function(err, blocks) {
each(blocks, function(res) { each(res.values, fn) });
cb();
});
});
/**
* Helpers
*/
function prepareKey(key) {
return type(key) === 'string' ? key : JSON.stringify(key);
}
function getKeys() {
var keys = localStorage.getItem(KEYS);
return keys ? keys.split(SEPARATOR) : [];
}
function startNewBlock(key, keys) {
if (!keys) keys = getKeys();
keys.push(key);
localStorage.setItem(KEYS, keys.join(SEPARATOR));
}
function getBlockName(key) {
var keys = getKeys();
var current = keys[keys.length - 1];
if (keys.length === 0) {
startNewBlock(key, keys);
current = key;
} else {
for (var i = 0, len = keys.length; i < len; i++) {
if (keys[i] > key) break;
else current = keys[i];
}
}
return PREFIX + current;
}
function getBlock(key, cb) {
getBlockByName(getBlockName(key), cb);
}
function getBlockByName(name, cb) {
var raw = localStorage.getItem(name) || '';
LZString.decompress(raw, function(values) {
values ? values = JSON.parse(values) : values = {};
cb(null, { values: values, raw: raw, name: name });
});
}
function saveBlock(res, cb) {
LZString.compress(JSON.stringify(res.values), function(values) {
localStorage.setItem(res.name, values);
cb();
});
}
function put(res, key, val) {
if (res.raw.length > LIMIT) {
startNewBlock(key);
res.values = {};
}
res.values[key] = val;
}
function del(res, key) {
if (res.values[key] === undefined) return;
delete res.values[key];
if (Object.keys(res.values).length === 0) res.values = undefined;
}
| JavaScript | 0 | @@ -211,71 +211,24 @@
');%0A
-%0A// bug, see: https://github.com/paulmillr/
+var
async
--each/issues/2%0A
+Each =
requ
@@ -249,42 +249,8 @@
h');
-%0Avar asyncEach = window.asyncEach;
%0A%0A/*
|
5da7fca1ad5ac8541c282d0c2cc7c3b288bbf933 | fix registration logic | AdapterResolver.js | AdapterResolver.js | (function (define) {
define(function () {
"use strict";
var adapters;
adapters = {};
/**
* Finds an adapter for the given object and the role.
* This is overly simplistic for now. We can replace this
* resolver later.
* @param object {Object}
* @param type {String}
* @description Loops through all Adapters registered with
* AdapterResolver.register, calling each Adapter's canHandle
* method. Adapters added later are found first.
*/
function AdapterResolver (object, type) {
var adaptersOfType, i, Adapter;
adaptersOfType = adapters[type];
if (adaptersOfType) {
i = adaptersOfType.length;
while ((Adapter = adaptersOfType[--i])) {
if (Adapter.canHandle(object)) {
return Adapter;
}
}
}
}
AdapterResolver.register = function registerAdapter (Adapter, type) {
if (!type in adapters) adapters[type] = [];
adapters[type].push(Adapter);
};
return AdapterResolver;
});
}(
typeof define == 'function'
? define
: function (factory) { module.exports = factory(); }
)); | JavaScript | 0.000001 | @@ -819,16 +819,17 @@
%0A%09%09if (!
+(
type in
@@ -837,16 +837,17 @@
dapters)
+)
adapter
|
b926723724dfdd4563ca31b7abfaa16943a2e507 | read api key from environment | server/routes/spotsHW.js | server/routes/spotsHW.js | var express = require('express');
var uuid = require('uuid');
var router = express.Router();
var SPOTS_API_KEY;
if(process.env.BUILD == 'development') {
SPOTS_API_KEY = '1234';
} else {
SPOTS_API_KEY = uuid();
}
console.log("Using SPOTS_API_KEY = %s", SPOTS_API_KEY)
router.post('/update/:key/:lotID/:spotID/:vacancy/:cardID?', (req, res, next) => {
console.log(req.params);
key = req.params.key;
if(key != SPOTS_API_KEY) {
res.status(401).send({error:"invalid key"});
return;
}
if(req.params.cardID == '123456789') {
res.send({authorized: true});
} else {
res.send({authorized: false});
}
});
module.exports = router;
| JavaScript | 0 | @@ -108,13 +108,11 @@
_KEY
-;%0Aif(
+ =
proc
@@ -123,96 +123,22 @@
env.
-BUILD == 'development') %7B%0A SPOTS_API_KEY = '1234';%0A%7D else %7B%0A SPOTS_API_KEY = uuid();%0A%7D
+SPOTS_API_KEY;
%0Acon
|
370e4f4b2d9c7c7449389f3d47c5d985af8ee4b9 | add event for left arrow | Animals/js/main.js | Animals/js/main.js | //create a new Game instance
//set the game dimensions and set the Phaser.AUTO (OpenGL or Canvas)
var game = new Phaser.Game(640, 360, Phaser.AUTO);
//create a game state (this contains the logic of the game)
var GameState = {
//assets are loaded in this function
preload: function(){
//load the images from the assets folder
this.load.image('backgroundImageKey', 'assets/images/background.png');
this.load.image('chickenImageKey', 'assets/images/chicken.png');
this.load.image('horseImageKey', 'assets/images/horse.png');
this.load.image('pigImageKey', 'assets/images/pig.png');
this.load.image('sheepImageKey', 'assets/images/sheep.png');
this.load.image('arrowImageKey', 'assets/images/arrow.png');
},
//after preloading create function is called
create: function(){
//to make the game responsive i.e. make it viewable on different types of devices
//SHOW_ALL mode makes the game fit the screen
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
//to align the game in the center
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
//this will create a sprite for the background
this.background = this.game.add.sprite(0,0, 'backgroundImageKey');
//this will create a sprite for the chicken
this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chickenImageKey');
//by default the anchor point is top left corner of the image
//inorder to change it we do it so with the following code
this.chicken.anchor.setTo(0.5, 0.5);//takes two arguments for X and Y, if both X and Y values are same then one argument will do the job
//left arrow (previous)
this.leftArrow = this.game.add.sprite(this.game.world.centerX - 210, this.game.world.centerY - 50, 'arrowImageKey');
this.leftArrow.anchor.setTo = (0.5, 0.5);
this.leftArrow.scale.x = -1;//flip the right arrow to make the left arrow
this.leftArrow.customParams = {direction: 1};
//right arrow (next)
this.rightArrow = this.game.add.sprite(this.game.world.centerX + 210, this.game.world.centerY - 50, 'arrowImageKey');
this.rightArrow.anchor.setTo = (0.5, 0.5);
this.rightArrow.customParams = {direction: 1};
},
//this function is called multiple times to handle the requests when game is live
update: function(){
}
};
//add state to the main game
game.state.add('GameState', GameState);
//to launch the game
game.state.start('GameState'); | JavaScript | 0.000001 | @@ -2161,32 +2161,335 @@
n: 1%7D;%0A %0A
+ this.leftArrow.inputEnabled = true;//enable input%0A this.leftArrow.input.pixelPerfectClick = true;//this will the clickable area to shape of the sprite and not a regular rectangle%0A this.leftArrow.events.onInputDown.add(this.changeAnimal, this);//add event when user clicks%0A %0A
//right
@@ -2501,16 +2501,16 @@
(next)%0A
-
@@ -2850,19 +2850,151 @@
tion()%7B%0A
-%0A%09%7D
+ %0A%09%7D,%0A %0A //changeAnimal function%0A changeAnimal: function(sprite, event)%7B%0A console.log(sprite, event);%0A %7D%0A
%0A%7D;%0A%0A//a
|
4ef671e04c87c671bc6c9950cd5e5334553c906d | Fix syntax error according to eslint | modules/core/client/app/init.js | modules/core/client/app/init.js | 'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $httpProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$httpProvider.interceptors.push('authInterceptor');
}
]);
angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication) {
// Check authentication before changing state
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.data && toState.data.roles && toState.data.roles.length > 0) {
var allowed = false;
toState.data.roles.forEach(function (role) {
if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) {
allowed = true;
return true;
}
});
if (!allowed) {
event.preventDefault();
if (Authentication.user !== undefined && typeof Authentication.user === 'object') {
$state.go('forbidden');
} else {
$state.go('authentication.signin').then(function () {
storePreviousState(toState, toParams);
});
}
}
}
});
// Record previous state
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
if( (fromState.name !== 'authentication.signin' || toState.name !== 'authentication.signup') &&
(fromState.name !== 'authentication.signup' || toState.name !== 'authentication.signin') ) {
// The user may switch between sign-in and sign-up before been successfully authenticated
// Then we want to redirect him to the page he tried to access, not sign-in or sign-up again
storePreviousState(fromState, fromParams);
}
});
// Store previous state
function storePreviousState(state, params) {
// only store this state if it shouldn't be ignored
if (!state.data || !state.data.ignoreState) {
$state.previous = {
state: state,
params: params,
href: $state.href(state, params)
};
}
}
});
//Then define the init function for starting up the application
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash && window.location.hash === '#_=_') {
if (window.history && history.pushState) {
window.history.pushState('', document.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scroll.top;
document.body.scrollLeft = scroll.left;
}
}
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
| JavaScript | 0.000675 | @@ -1602,17 +1602,16 @@
%0A if(
-
(fromSta
@@ -1788,17 +1788,16 @@
signin')
-
) %7B%0A
@@ -1986,17 +1986,16 @@
up again
-
%0A s
|
31e4bddbca6b5e50a4958a956a48bdbf61045086 | Fix lint errors | lib/index.js | lib/index.js | // TODO: ES2015 maybe, baby?
var rollup = require('rollup');
var babel = require('rollup-plugin-babel');
var camelCase = require('camel-case');
var pkg = require('./package.json');
var name = pkg.name;
var moduleName = 'ReactLibStarterkit';
var formats = ['es6', 'cjs', 'umd'];
module.exports = function(options) {
// TODO: Hmm, a voice in my head says we shouldn't modify arguments
options = options || {};
options.name = options.name || 'mylibrary';
// TODO: If we go about using Object.assign instead of modifying `options`,
// we should have some way of taking `name` from `moduleName` without it
// being too hack-y
options.moduleName = options.moduleName || camelCase(options.name);
options.dest = options.dest || 'dist';
options.entry = options.entry || 'index.js';
options.format = options.format || ['es6', 'cjs', 'umd'];
options.plugins = options.plugins || [babel()];
var baseConfig = {
entry: options.entry,
plugins: options.plugins,
};
var builds = formats.map(function(format) {
var config = Object.assign({}, baseConfig);
config.format = format;
config.dest = options.dest + '/' + name;
if (format === 'es6') {
config.dest += '.es2015';
}
if (format === 'umd') {
config.dest += '.umd';
config.moduleName = options.moduleName;
}
config.dest += '.js';
return rollup.rollup(config).then(function(bundle) {
bundle.write(config);
});
});
return Promise.all(builds).then(function() {
console.log('All done!');
}).catch(function(err) {
console.log('Error while generating a build:');
console.log(err);
});
};
| JavaScript | 0 | @@ -143,106 +143,8 @@
);%0A%0A
-var pkg = require('./package.json');%0Avar name = pkg.name;%0Avar moduleName = 'ReactLibStarterkit';%0A%0A
var
@@ -202,16 +202,26 @@
function
+ rollupLib
(options
@@ -230,107 +230,108 @@
%7B%0A
-// TODO: Hmm, a voice in my head says we shouldn't modify arguments%0A options = options %7C%7C%C2%A0%7B%7D;%0A%0A o
+var rollupOptions = Object.assign(%7B%7D, options);%0A var baseConfig = %7B%7D;%0A var builds = %5B%5D;%0A%0A rollupO
ptio
@@ -336,25 +336,31 @@
ions.name =
-o
+rollupO
ptions.name
@@ -361,17 +361,17 @@
.name %7C%7C
-%C2%A0
+
'mylibra
@@ -554,17 +554,23 @@
ack-y%0A
-o
+rollupO
ptions.m
@@ -573,33 +573,39 @@
ns.moduleName =
-o
+rollupO
ptions.moduleNam
@@ -608,17 +608,17 @@
eName %7C%7C
-%C2%A0
+
camelCas
@@ -632,25 +632,31 @@
ns.name);%0A
-o
+rollupO
ptions.dest
@@ -649,33 +649,39 @@
pOptions.dest =
-o
+rollupO
ptions.dest %7C%7C%C2%A0'
@@ -678,17 +678,17 @@
.dest %7C%7C
-%C2%A0
+
'dist';%0A
@@ -685,25 +685,31 @@
%7C 'dist';%0A
-o
+rollupO
ptions.entry
@@ -711,17 +711,23 @@
entry =
-o
+rollupO
ptions.e
@@ -733,17 +733,17 @@
entry %7C%7C
-%C2%A0
+
'index.j
@@ -744,25 +744,31 @@
ndex.js';%0A
-o
+rollupO
ptions.forma
@@ -767,25 +767,31 @@
ns.format =
-o
+rollupO
ptions.forma
@@ -798,9 +798,9 @@
t %7C%7C
-%C2%A0
+
%5B'es
@@ -820,17 +820,23 @@
md'%5D;%0A
-o
+rollupO
ptions.p
@@ -844,17 +844,23 @@
ugins =
-o
+rollupO
ptions.p
@@ -884,20 +884,16 @@
)%5D;%0A%0A%0A
-var
baseConf
@@ -910,17 +910,23 @@
entry:
-o
+rollupO
ptions.e
@@ -944,17 +944,23 @@
lugins:
-o
+rollupO
ptions.p
@@ -975,20 +975,16 @@
%7D;%0A%0A
-var
builds =
@@ -1004,16 +1004,28 @@
function
+ buildFormat
(format)
@@ -1400,16 +1400,29 @@
function
+ rollupBundle
(bundle)
@@ -1509,16 +1509,26 @@
function
+ buildThen
() %7B%0A
@@ -1573,16 +1573,27 @@
function
+ buildCatch
(err) %7B%0A
|
6fb41f60c91166c9f72e3f32ac78dafa617bf5a8 | allow remote connections for socket | server/static/js/main.js | server/static/js/main.js | $(document).ready(function(){
var ws = new WebSocket('ws://127.0.0.1:9010');
ws.onopen = function(){
enableKeys();
$('#socket-status').removeClass('label-default label-success label-danger')
.addClass('label-success')
.text('online');
};
ws.onerror = function(){
clearScreen();
disableKeys();
$('#socket-status').removeClass('label-default label-success label-danger')
.addClass('label-danger')
.text('error');
};
ws.onclose = function(){
clearScreen();
disableKeys();
$('#socket-status').removeClass('label-default label-success label-danger')
.addClass('label-default')
.text('offline');
};
ws.addEventListener("message", function(event) {
var data = JSON.parse(event.data);
updateScreen(data.pixel);
});
var updateScreen = function(pixel){
for (var x=0; x<pixel.length; x++){ // rows
for (var y=0; y<pixel[x].length; y++){ // col
var id = '#pixel-'+y+'-'+x,
p = pixel[x][y];
$(id).css('background-color', rgbToHex(p[0], p[1], p[2]));
}
}
};
var clearScreen = function(){
$('.pixel').css('background-color', '#000000');
};
var disableKeys = function(){
$('.send-key').attr('disabled', true);
};
var enableKeys = function(){
$('.send-key').removeAttr('disabled');
};
$('body').on('click', '.send-key', function(e){
var $this = $(this),
key = $this.data('key'),
json = JSON.stringify({'key': key});
e.preventDefault();
ws.send(json);
});
function componentToHex(c) {
var hex = c.toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
$('body').on('click', '.fullscreen', toggleFullscreen);
function toggleFullscreen() {
if ((document.fullScreenElement && document.fullScreenElement !== null) ||
(!document.mozFullScreen && !document.webkitIsFullScreen)) {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
}); | JavaScript | 0 | @@ -61,17 +61,40 @@
s://
-127.0.0.1
+' + window.location.hostname + '
:901
|
ca055ec16fc2871e28cc9b8f2b0c9fc443e0f9b5 | Fix typo | modules/ext.thanks.corethank.js | modules/ext.thanks.corethank.js | ( function () {
'use strict';
function reloadThankedState() {
$( 'a.mw-thanks-thank-link' ).each( function ( idx, el ) {
var $thankLink = $( el );
if ( mw.thanks.thanked.contains( $thankLink ) ) {
$thankLink.before( mw.message( 'thanks-thanked', mw.user, $thankLink.data( 'recipient-gender' ) ).escaped() );
$thankLink.remove();
}
} );
}
// $thankLink is the element with the data-revision-id attribute
// $thankElement is the element to be removed on success
function sendThanks( $thankLink, $thankElement ) {
var source, apiParams;
if ( $thankLink.data( 'clickDisabled' ) ) {
// Prevent double clicks while we haven't received a response from API request
return false;
}
$thankLink.data( 'clickDisabled', true );
// Determine the thank source (history, diff, or log).
if ( mw.config.get( 'wgAction' ) === 'history' ) {
source = 'history';
} else if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Log' ) {
source = 'log';
} else {
source = 'diff';
}
// Construct the API parameters.
apiParams = {
action: 'thank',
source: source
};
if ( $thankLink.data( 'log-id' ) ) {
apiParams.log = $thankLink.data( 'log-id' );
} else {
apiParams.rev = $thankLink.data( 'revision-id' );
}
// Send the API request.
( new mw.Api() ).postWithToken( 'csrf', apiParams )
.then(
// Success
function () {
$thankElement.before( mw.message( 'thanks-thanked', mw.user, $thankLink.data( 'recipient-gender' ) ).escaped() );
$thankElement.remove();
mw.thanks.thanked.push( $thankLink );
},
// Fail
function ( errorCode ) {
// If error occured, enable attempting to thank again
$thankLink.data( 'clickDisabled', false );
switch ( errorCode ) {
case 'invalidrevision':
OO.ui.alert( mw.msg( 'thanks-error-invalidrevision' ) );
break;
case 'ratelimited':
OO.ui.alert( mw.msg( 'thanks-error-ratelimited', mw.user ) );
break;
case 'revdeleted':
OO.ui.alert( mw.msg( 'thanks-error-revdeleted' ) );
break;
default:
OO.ui.alert( mw.msg( 'thanks-error-undefined', errorCode ) );
}
}
);
}
/**
* Add interactive handlers to all 'thank' links in $content
*
* @param {jQuery} $content
*/
function addActionToLinks( $content ) {
var $thankLinks = $content.find( 'a.mw-thanks-thank-link' );
if ( mw.config.get( 'thanks-confirmation-required' ) ) {
$thankLinks.each( function () {
var $thankLink = $( this );
$thankLink.confirmable( {
i18n: {
confirm: mw.msg( 'thanks-confirmation2', mw.user ),
no: mw.msg( 'cancel' ),
noTitle: mw.msg( 'thanks-thank-tooltip-no', mw.user ),
yes: mw.msg( 'thanks-button-thank', mw.user, $thankLink.data( 'recipient-gender' ) ),
yesTitle: mw.msg( 'thanks-thank-tooltip-yes', mw.user )
},
handler: function ( e ) {
e.preventDefault();
sendThanks( $thankLink, $thankLink.closest( '.jquery-confirmable-wrapper' ) );
}
} );
} );
} else {
$thankLinks.click( function ( e ) {
var $thankLink = $( this );
e.preventDefault();
sendThanks( $thankLink, $thankLink );
} );
}
}
if ( $.isReady ) {
// This condition is required for soft-reloads
// to also trigger the reloadThankedState
reloadThankedState();
} else {
$( reloadThankedState );
}
$( function () {
addActionToLinks( $( 'body' ) );
} );
mw.hook( 'wikipage.diff' ).add( function ( $content ) {
addActionToLinks( $content );
} );
}() );
| JavaScript | 0.000001 | @@ -1650,16 +1650,17 @@
or occur
+r
ed, enab
|
035b23de64769966fc68e28f752311b40f0f11a0 | Flairs should be lowercase | modules/flair/DestinyTheGame.js | modules/flair/DestinyTheGame.js | const base = require( './base.js' );
module.exports = Object.assign( {}, base, {
isDev: function isDev ( user ) {
if ( !user[ this.type ] ) {
return false;
}
for ( const flairString of this.list ) {
if ( user[ this.type ].includes( flairString ) ) {
return true;
}
}
return false;
},
list: [
'Verified-Bungie-Employee',
],
type: 'author_flair_css_class',
} );
| JavaScript | 0.999999 | @@ -405,17 +405,17 @@
'
-V
+v
erified-
Bung
@@ -414,16 +414,16 @@
ied-
-B
+b
ungie-
-E
+e
mplo
|
94abbde4e9a58168089cb802c84f621420e5a2fa | Fix emit name | lib/index.js | lib/index.js | 'use strict';
var rump = module.exports = require('rump');
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
// TODO remove on next major core update
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
return rump;
};
rump.on('update:main', function() {
configs.rebuild();
rump.emit('update:server:dev');
});
rump.on('gulp:main', function(options) {
require('./gulp');
rump.emit('gulp:server:dev', options);
});
Object.defineProperty(rump.configs, 'browserSync', {
get: function() {
return configs.browserSync;
}
});
| JavaScript | 0.000007 | @@ -373,20 +373,16 @@
e:server
-:dev
');%0A%7D);%0A
@@ -472,12 +472,8 @@
rver
-:dev
', o
|
69c04f13abf149f929c9c248e123cadb3e5b35c2 | Update elite flairs | modules/flair/EliteDangerous.js | modules/flair/EliteDangerous.js | module.exports = {
getFlairs: function getFlairs () {
return this.list;
},
list: [
'bot img',
'cmdr img alliance',
'cmdr img cobra',
'cmdr img empire',
'cmdr img federation',
'cmdr img sidey',
'cmdr img skull',
'cmdr img viper',
'cmdr star',
'cmdr',
'competent cmdr',
'dangerous cmdr',
'empire cmdr img',
'empire',
'harmless cmdr',
'img sidey cmdr',
'img viper cmdr',
'mostlyharmless cmdr',
'novice cmdr',
'star',
],
type: 'author_flair_css_class',
};
| JavaScript | 0 | @@ -138,177 +138,750 @@
mg a
-lliance',%0A 'cmdr img cobra',%0A 'cmdr img empire',%0A 'cmdr img federation',%0A 'cmdr img sidey',%0A 'cmdr img skull',%0A 'cmdr img viper
+duval',%0A 'cmdr img alduval',%0A 'cmdr img alliance',%0A 'cmdr img antal',%0A 'cmdr img cobra',%0A 'cmdr img combat',%0A 'cmdr img coredyn',%0A 'cmdr img delaine',%0A 'cmdr img empire',%0A 'cmdr img explore',%0A 'cmdr img fdelacy',%0A 'cmdr img federation',%0A 'cmdr img galnet',%0A 'cmdr img grom',%0A 'cmdr img hudson',%0A 'cmdr img mahon',%0A 'cmdr img patreus',%0A 'cmdr img rescue',%0A 'cmdr img sidey',%0A 'cmdr img skull',%0A 'cmdr img snoo',%0A 'cmdr img thargint',%0A 'cmdr img thargsen',%0A 'cmdr img trade',%0A 'cmdr img viper',%0A 'cmdr img winters',%0A 'cmdr img yongrui',%0A 'cmdr img zorgpet
',%0A
|
941049a2cabb292f189a4496589eac834a5cf68f | Improve documentation | panopticon.js | panopticon.js | /*
Example schema:
var personSchema = mongoose.Schema({
name: String,
email: String,
pets: [{
name: String
}]
});
var pn = require('panopticon');
var rules = {
'name': function(newValue) {
this // the document at the point of post-save
},
'email': {
'surname': function() {
create new audit item when person changes their email.surname;
}
},
'pets': {
'name': function() {}
}
};
pn.watch(personSchema, rules);
*/
var jsondiffpatch = require('jsondiffpatch'),
_ = require('underscore');
/*
* watch()
* <schema> - a Mongoose schema
* <rules> - an object containing watch rules
*
*/
exports.watch = function(schema, rules) {
// SET UP ORIGINAL OBJECT
schema.pre('init', function (next, doc) {
// stringify prunes methods from the document
doc._original = JSON.parse(JSON.stringify(doc));
next();
});
// SET UP POST SAVE WITH DIFFING
/* Example diff:
diff: {
pets: {
name: ['berty', 'fred']
},
email: [oldEmail, newEmail].surname
}
*/
schema.post('save', function () {
var doc = this;
var original = doc.get('_original');
if (original) {
var updated = JSON.parse(JSON.stringify(doc));
var differ = jsondiffpatch.create({
// this is so the differ can tell what has changed for arrays of objects
objectHash: function(obj) {
return obj.name || obj.id || obj._id || obj._id || JSON.stringify(obj);
}
});
var diff = differ.diff(original, updated);
// FIRE RULES BEHAVIOURS
// iterate over keys of rules
// if value is function, call with document (as this) and newValue
// if value is object, iterate over value
/*
* getNewValue()
* <diffItem> - array representing diff of item.
* - Length 1 is addition [new]
* - Length 2 is update [old, new]
* - Length 3 is deletion [old, 0, 0]
*/
function getNewValue(diffItem){
if (!_.isArray(diffItem)) {
throw new TypeError('diffItem must be an array');
}
if (diffItem.length === 3) {
return null;
}
return _.last(diffItem);
}
/*
* applyRules()
* <rules>
* <diff>
*
* <throws> TypeError if <diff> is array (rule does not reflect model structure)
* <throws> TypeError if <rules> contains an array (invalid)
*/
function applyRules(rules, diff) {
if (_.isArray(diff)) {
throw new TypeError('diff cannot be an array')
}
_(rules).each(function(rule, key){
if(_.isArray(rule)) {
throw new TypeError('panopticon rule cannot be an array');
}
var diffItem = diff[key];
if (diffItem) {
if (typeof rule === 'function') {
newValue = getNewValue(diffItem);
rule.call(doc, newValue);
} else if (_.isObject(rule)) {
applyRules(rule, diffItem);
}
}
});
}
applyRules(rules, diff);
}
});
}; | JavaScript | 0.000004 | @@ -1981,110 +1981,68 @@
*
- %3CdiffItem%3E - array representing diff of item. %0A * - Length 1 is addition %5Bnew%5D
+%0A * Returns the new value of a document property
%0A
@@ -2044,32 +2044,33 @@
y%0A *
+%0A
- Le
@@ -2069,100 +2069,86 @@
-- Length 2 is update %5Bold, new%5D%0A * - Length 3 is deletion %5Bold, 0, 0%5D
+ * @param %7BArray%7D diffItem representing change to property (see jsondiffpatch)
%0A
@@ -2549,38 +2549,138 @@
*
- %3Crules%3E%0A * %3C
+%0A * Calls rules functions%0A *%0A * @param %7BObject%7D rules the functions to call when paths in
diff
-%3E
%0A
@@ -2695,32 +2695,109 @@
*
-%0A * %3C
+@param %7BObject%7D diff the diff between the old and new document%0A * %0A * @
throws
-%3E
Typ
@@ -2810,14 +2810,12 @@
if
-%3C
diff
-%3E
is
@@ -2879,16 +2879,15 @@
*
-%3C
+@
throws
-%3E
Typ
@@ -2896,23 +2896,21 @@
rror if
-%3C
rules
-%3E
contain
|
6451a9eb19509cd1335bd7accd58175cac30edee | load simple keyboard by default | addons/point_of_sale/static/src/js/keyboard.js | addons/point_of_sale/static/src/js/keyboard.js | openerp.point_of_sale.load_keyboard = function load_keyboard(instance, module){ //module is instance.point_of_sale
"use strict";
// ---------- OnScreen Keyboard Widget ----------
// A Widget that displays an onscreen keyboard.
// There are two options when creating the widget :
//
// * 'keyboard_model' : 'simple' | 'full' (default)
// The 'full' emulates a PC keyboard, while 'simple' emulates an 'android' one.
//
// * 'input_selector : (default: '.searchbox input')
// defines the dom element that the keyboard will write to.
//
// The widget is initially hidden. It can be shown with this.show(), and is
// automatically shown when the input_selector gets focused.
module.OnscreenKeyboardWidget = instance.web.Widget.extend({
template: 'OnscreenKeyboardSimple',
init: function(parent, options){
var self = this;
this._super(parent,options);
options = options || {};
this.keyboard_model = options.keyboard_model || 'full';
if(this.keyboard_model === 'full'){
this.template = 'OnscreenKeyboardFull';
}
this.input_selector = options.input_selector || '.searchbox input';
this.$target = null;
//Keyboard state
this.capslock = false;
this.shift = false;
this.numlock = false;
},
connect : function(target){
var self = this;
this.$target = $(target);
this.$target.focus(function(){self.show();});
},
generateEvent: function(type,key){
var event = document.createEvent("KeyboardEvent");
var initMethod = event.initKeyboardEvent ? 'initKeyboardEvent' : 'initKeyEvent';
event[initMethod]( type,
true, //bubbles
true, //cancelable
window, //viewArg
false, //ctrl
false, //alt
false, //shift
false, //meta
((typeof key.code === 'undefined') ? key.char.charCodeAt(0) : key.code),
((typeof key.char === 'undefined') ? String.fromCharCode(key.code) : key.char)
);
return event;
},
// Write a character to the input zone
writeCharacter: function(character){
var input = this.$target[0];
input.dispatchEvent(this.generateEvent('keydown',{char: character}));
if(character !== '\n'){
input.value += character;
}
input.dispatchEvent(this.generateEvent('keyup',{char: character}));
},
// Removes the last character from the input zone.
deleteCharacter: function(){
var input = this.$target[0];
input.dispatchEvent(this.generateEvent('keydown',{code: 8}));
input.value = input.value.substr(0, input.value.length -1);
input.dispatchEvent(this.generateEvent('keyup',{code: 8}));
},
// Clears the content of the input zone.
deleteAllCharacters: function(){
var input = this.$target[0];
if(input.value){
input.dispatchEvent(this.generateEvent('keydown',{code: 8}));
input.value = "";
input.dispatchEvent(this.generateEvent('keyup',{code: 8}));
}
},
// Makes the keyboard show and slide from the bottom of the screen.
show: function(){
$('.keyboard_frame').show().css({'height':'235px'});
},
// Makes the keyboard hide by sliding to the bottom of the screen.
hide: function(){
$('.keyboard_frame')
.css({'height':'0'})
.hide();
this.reset();
},
//What happens when the shift key is pressed : toggle case, remove capslock
toggleShift: function(){
$('.letter').toggleClass('uppercase');
$('.symbol span').toggle();
self.shift = (self.shift === true) ? false : true;
self.capslock = false;
},
//what happens when capslock is pressed : toggle case, set capslock
toggleCapsLock: function(){
$('.letter').toggleClass('uppercase');
self.capslock = true;
},
//What happens when numlock is pressed : toggle symbols and numlock label
toggleNumLock: function(){
$('.symbol span').toggle();
$('.numlock span').toggle();
self.numlock = (self.numlock === true ) ? false : true;
},
//After a key is pressed, shift is disabled.
removeShift: function(){
if (self.shift === true) {
$('.symbol span').toggle();
if (this.capslock === false) $('.letter').toggleClass('uppercase');
self.shift = false;
}
},
// Resets the keyboard to its original state; capslock: false, shift: false, numlock: false
reset: function(){
if(this.shift){
this.toggleShift();
}
if(this.capslock){
this.toggleCapsLock();
}
if(this.numlock){
this.toggleNumLock();
}
},
//called after the keyboard is in the DOM, sets up the key bindings.
start: function(){
var self = this;
//this.show();
$('.close_button').click(function(){
self.deleteAllCharacters();
self.hide();
});
// Keyboard key click handling
$('.keyboard li').click(function(){
var $this = $(this),
character = $this.html(); // If it's a lowercase letter, nothing happens to this variable
if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
self.toggleShift();
return false;
}
if ($this.hasClass('capslock')) {
self.toggleCapsLock();
return false;
}
if ($this.hasClass('delete')) {
self.deleteCharacter();
return false;
}
if ($this.hasClass('numlock')){
self.toggleNumLock();
return false;
}
// Special characters
if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
if ($this.hasClass('space')) character = ' ';
if ($this.hasClass('tab')) character = "\t";
if ($this.hasClass('return')) character = "\n";
// Uppercase letter
if ($this.hasClass('uppercase')) character = character.toUpperCase();
// Remove shift once a key is clicked.
self.removeShift();
self.writeCharacter(character);
});
},
});
}
| JavaScript | 0.000004 | @@ -342,17 +342,8 @@
le'
-%7C 'full'
(def
@@ -347,16 +347,25 @@
default)
+ %7C 'full'
%0A //
@@ -1051,20 +1051,22 @@
del %7C%7C '
-full
+simple
';%0A
|
12643745c29f46b214074383b2bd8c3a22b9b8ae | fix bug in usaa scrape/example | service/examples/usaa.js | service/examples/usaa.js | var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false, frame: false });
var path = require('path');
var getPrivateInfo = require('./getPrivateInfo').usaa;
nightmare
.goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1')
.click('#logOnButton a')
.type('input#input_onlineid', getPrivateInfo().username())
.type('input#input_password', getPrivateInfo().password())
.click('input[type="submit"]')
.wait('input#pinTextField')
.type('input#pinTextField', getPrivateInfo().pin())
.click('button[type="submit"]')
.wait('label[for="securityQuestionTextField"]')
.evaluate(() => document.querySelector('label[for="securityQuestionTextField"]').innerHTML)
.then(result => {
return nightmare
.type('#securityQuestionTextField', getPrivateInfo().answer(result))
.click('button[type="submit"]')
.wait('#menu')
.click('#menu li:first-child a')
.wait('.acct-group-list')
//TODO: get info from here then move on to the next step (for each account)
.screenshot(path.join(__dirname, 'usaa.png'))
.end()
})
.then(function (result) {
console.log(result)
})
.catch(function (error) {
console.error('Error:', error);
});
// nightmare
// .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1')
// .click('input#input_onlineid')
// .click('div#main-ctr > div.section-ctr:nth-child(4)')
// .click('input#input_password')
// .click('div#main-ctr > div.section-ctr:nth-child(4)')
// .click('div#main-ctr > div.section-ctr:nth-child(4) > div.button-ctr:nth-child(1) > div.yui3-g.padded:nth-child(1) > div.yui3-u-1:nth-child(1) > input.main-button:nth-child(1)')
// .click('input#pinTextField')
// .click('button#id4')
// .click('input#securityQuestionTextField')
// .click('div#flowWrapper')
// .click('button#id6')
// .click('div#id3 > ul.acct-group-list:nth-child(1) > li.acct-group-row:nth-child(1) > a.usaa-link.acct-info.clearfix:nth-child(1) > span.link-liner:nth-child(1) > span.acct-name:nth-child(1)')
// .end()
// .then(function (result) {
// console.log(result)
// })
// .catch(function (error) {
// console.error('Error:', error);
// });
| JavaScript | 0 | @@ -802,16 +802,30 @@
r(result
+.toLowerCase()
))%0A
|
183654150e87967e8d94a93fb39157061b5a970d | remove alert | PlatformProject.AdminConsole/app/Controllers/TenantController.js | PlatformProject.AdminConsole/app/Controllers/TenantController.js | angular.module('admin').controller('tenantController', ['$scope', '$window', 'TenantService', 'SharedServices', function ($scope, $window, TenantService, SharedServices)
{
$scope.isFormMode = false;
$scope.isEdit = false;
loadRecords();
//Function to load all Tenant records
function loadRecords() {
var promiseGet = TenantService.getTenants(); //The Method Call from service
promiseGet.then(function (pl) {
$scope.Tenants = pl.data;
alert(pl.data);
SharedServices.locateToWindow("http://localhost:40838/index.html#/TenantManagement");
},
function (errorPl) {
$log.error('failure loading Tenants', errorPl);
});
};
$scope.save = function () {
var tenant = {
tId: $scope.tId,
Name: $scope.tName,
tString: $scope.tString,
tLogo: $scope.tLogo,
tEnable: $scope.tEnable
};
if ($scope.isNew) {
var promisePost = TenantService.createTenant(tenant);
//promisePost.then(function (pl) {
// $scope.Id = pl.data.Id;
$scope.Message = "Created Successfuly";
// console.log($scope.Message);
$scope.clear();
loadRecords();
// }, function (err) {
// console.log("Err" + err);
// });
} else { //Else Edit the record
var promisePut = TenantService.updateTenant($scope.tId, tenant);
promisePut.then(function (pl) {
$scope.Message = "Updated Successfuly";
$scope.clear();
loadRecords();
}, function (err) {
console.log("Err" + err);
});
}
};
//Method to Delete
$scope.delete = function (tId) {
var promiseDelete = TenantService.removeTenant(tId);
promiseDelete.then(function (pl) {
$scope.Message = "Deleted Successfuly";
$scope.tId = 0;
$scope.tName = "";
$scope.tString = "";
$scope.tLogo = "";
$scope.tEnable = "";
loadRecords();
}, function (err) {
console.log("Err" + err);
});
}
//Method to Get Single tenant based on Id
$scope.get = function (tId) {
var promiseGetSingle = TenantService.getTenantData(tId);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.tId = res.id;
$scope.tName = res.name;
$scope.tString = res.tenantString;
$scope.tLogo = res.logoUrl;
$scope.tEnable = res.enable;
$scope.isNew = false;
},
function (errorPl) {
console.log('failure loading Tenant', errorPl);
});
};
$scope.clear = function () {
$scope.tId = "";
$scope.tName = "";
$scope.tString = "";
$scope.tLogo = "";
$scope.tEnable = "";
};
$scope.edit = function (Id) {
$scope.isNew = false;
$scope.isFormMode = true;
$scope.isEdit = true;
$scope.Message = "";
$scope.get(Id);
};
$scope.createNew = function () {
$scope.clear();
$scope.isFormMode = true;
$scope.isNew = true;
$scope.Message = "";
}
$scope.cancel = function () {
$scope.clear();
$scope.isFormMode = false;
$scope.isEdit = false;
$scope.isNew = false;
};
}]);
| JavaScript | 0.000001 | @@ -496,36 +496,8 @@
ta;%0A
- alert(pl.data);%0A
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.