_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q42100 | train | function() {
if (_.keys(children).length == 0) {
that.stop(process.exit);
}
else {
setImmediate(checkExit); // keep polling for safe shutdown.
}
} | javascript | {
"resource": ""
} | |
q42101 | resize | train | function resize(e) {
var deltaSize, doc, body, docElm, resizeHeight, myHeight,
marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom;
doc = editor.getDoc();
if (!doc) {
return;
}
body = doc.body;
docElm = doc.documentElement;
resizeHeight = settings.autoresize_min_height;
if (!body || (e && e.type === "setcontent" && e.initial) || isFullscreen()) {
if (body && docElm) {
body.style.overflowY = "auto";
docElm.style.overflowY = "auto"; // Old IE
}
return;
}
// Calculate outer height of the body element using CSS styles
marginTop = editor.dom.getStyle(body, 'margin-top', true);
marginBottom = editor.dom.getStyle(body, 'margin-bottom', true);
paddingTop = editor.dom.getStyle(body, 'padding-top', true);
paddingBottom = editor.dom.getStyle(body, 'padding-bottom', true);
borderTop = editor.dom.getStyle(body, 'border-top-width', true);
borderBottom = editor.dom.getStyle(body, 'border-bottom-width', true);
myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) +
parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) +
parseInt(borderTop, 10) + parseInt(borderBottom, 10);
// Make sure we have a valid height
if (isNaN(myHeight) || myHeight <= 0) {
// Get height differently depending on the browser used
// eslint-disable-next-line no-nested-ternary
myHeight = Env.ie ? body.scrollHeight : (Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight);
}
// Don't make it smaller than the minimum height
if (myHeight > settings.autoresize_min_height) {
resizeHeight = myHeight;
}
// If a maximum height has been defined don't exceed this height
if (settings.autoresize_max_height && myHeight > settings.autoresize_max_height) {
resizeHeight = settings.autoresize_max_height;
body.style.overflowY = "auto";
docElm.style.overflowY = "auto"; // Old IE
} else {
body.style.overflowY = "hidden";
docElm.style.overflowY = "hidden"; // Old IE
body.scrollTop = 0;
}
// Resize content element
if (resizeHeight !== oldSize) {
deltaSize = resizeHeight - oldSize;
DOM.setStyle(editor.iframeElement, 'height', resizeHeight + 'px');
oldSize = resizeHeight;
// WebKit doesn't decrease the size of the body element until the iframe gets resized
// So we need to continue to resize the iframe down until the size gets fixed
if (Env.webKit && deltaSize < 0) {
resize(e);
}
}
} | javascript | {
"resource": ""
} |
q42102 | wait | train | function wait(times, interval, callback) {
Delay.setEditorTimeout(editor, function () {
resize({});
if (times--) {
wait(times, interval, callback);
} else if (callback) {
callback();
}
}, interval);
} | javascript | {
"resource": ""
} |
q42103 | lazy | train | function lazy(key, get) {
const uninitialized = {};
let _val = uninitialized;
Object.defineProperty(exports, key, {
get() {
if (_val === uninitialized) {
_val = get();
}
return _val;
},
});
} | javascript | {
"resource": ""
} |
q42104 | Connection | train | function Connection(options) {
if (!(this instanceof Connection)){
return new Connection(options);
}
this.prefixCounter = 0;
this.serverMessages = {};
this._options = {
username: options.username || options.user || '',
password: options.password || '',
host: options.host || 'localhost',
port: options.port || 143,
secure: options.secure === true ? { // secure = true means default behavior
rejectUnauthorized: false // Force pre-node-0.9.2 behavior
} : (options.secure || false),
timeout: options.timeout || 10000, // connection timeout in msecs
xoauth: options.xoauth,
xoauth2: options.xoauth2
};
this._messages = {};
this._messages = {};
if (options.debug===true){
this.debug = function(msg){
console.log(msg);
}
}
if (options.chainDebug===true){
this.chainDebug = function(msg){
console.log(msg);
}
}
this.socket = null;
this._messages_prefix_key={};
this._messages_key_prefix={};
this._messages={};
this._msg_buffer = '';
this._resetChainCommands();
} | javascript | {
"resource": ""
} |
q42105 | makeId | train | function makeId(length = RANDOM_CHARACTER_LENGTH) {
let text = "";
for (let i = 0; i < length; i++) {
text += RANDOM_CHARACTER_SOURCE.charAt(Math.floor(Math.random() * RANDOM_CHARACTER_SOURCE.length));
}
return text;
} | javascript | {
"resource": ""
} |
q42106 | merge_config | train | function merge_config(top_config, base_config)
{
for (var option in top_config)
{
if (Array.isArray(top_config[option])) // handle array elements in the same order
{
if (!Array.isArray(base_config[option]))
base_config[option] = top_config[option];
else
{
for(var i=0;i<top_config[option].length;i++)
{
if (base_config[option].length <= i)
base_config[option].push(top_config[option][i]);
else
merge_config(top_config[option][i],base_config[option][i]);
}
}
}
else if (typeof top_config[option] === "Object") // recurseively handle complex configurations
{
if (base_config[option] === undefined)
base_config[option] = top_config[option];
else
merge_config(top_config[option], base_config[option]);
}
else
base_config[option] = top_config[option];
}
} | javascript | {
"resource": ""
} |
q42107 | getWatches | train | function getWatches (directory) {
var package_path = resolve(directory || './')
var pkg = read(package_path)
var watches = extract(pkg)
return Array.isArray(watches) ? watches : []
} | javascript | {
"resource": ""
} |
q42108 | Context | train | function Context() {
/**
* @member {Object}
* @property {Object} client
* @property {Object<Call>} client.map - map from call name and call id
* @property {Array<Call>} client.list
* @property {Object} server
* @property {Object<Call>} server.map - map from call name and call id
* @property {Array<Call>} server.list
* @private
*/
this._calls = {
client: {
map: Object.create(null),
list: []
},
server: {
map: Object.create(null),
list: []
}
}
/**
* @member {Object}
* @property {Object} client
* @property {Object<Message>} client.map - map from message name and message id
* @property {Array<Message>} client.list
* @property {Object} server
* @property {Object<Message>} server.map - map from message name and message id
* @property {Array<Message>} server.list
* @private
*/
this._messages = {
client: {
map: Object.create(null),
list: []
},
server: {
map: Object.create(null),
list: []
}
}
} | javascript | {
"resource": ""
} |
q42109 | Person | train | function Person(firstname, lastname, middlenames) {
Person.super_.call(this);
var _priv = {
first: firstname || '-unknown-',
last: lastname || '-unknown-',
middle: middlenames || '-unknown-'
};
this.defines
.value('_state', {})
.property('first_name',
function() { return _priv.first; },
function(first) {
first = first || '-unknown-';
if (first !== _priv.first) {
var change = {
what: 'first_name',
from: _priv.first,
to: first
};
_priv.first = first;
this.emit('property-changed', change);
}
})
.property('last_name',
function() { return _priv.last; },
function(last) {
last = last || '-unknown-';
if (last !== _priv.last) {
var change = {
what: 'last_name',
from: _priv.last,
to: last
};
_priv.last = last;
this.emit('property-changed', change);
}
})
.property('middle_names',
function() { return _priv.middle; },
function(middle) {
middle = middle || '-unknown-';
if (middle !== _priv.middle) {
var change = {
what: 'middle_names',
from: _priv.middle,
to: middle
};
_priv.middle = middle;
this.emit('property-changed', change);
}
})
;
} | javascript | {
"resource": ""
} |
q42110 | fullnameFormatter | train | function fullnameFormatter( first, last, middle ) {
return ''.concat(first,
(last) ? ' '.concat(last) : '',
(middle) ? ' '.concat(middle) : '');
} | javascript | {
"resource": ""
} |
q42111 | printLogHeader | train | function printLogHeader (e) {
if (e.show && logHeader) {
logHeader = false;
grunt.log.header('Task "acetate:' + target + '" running');
}
} | javascript | {
"resource": ""
} |
q42112 | attached | train | function attached(context) {
if (DEBUG_DISPATCHER) log.info('ATTACHED: ' + ((!!context.dispatcher) ? 'yes' : 'no'));
if (!context) {
return false;
}
return !!context.dispatcher;
} | javascript | {
"resource": ""
} |
q42113 | subscribe | train | function subscribe(event, callback) {
/*jshint validthis: true */
if (DEBUG_DISPATCHER) log.info('SUBSCRIBE: ' + event);
if (!event || !callback) {
return this;
}
if (this._callbacks[event]) {
this._callbacks[event].push(callback);
}
else {
this._callbacks[event] = [ callback ];
}
this._client.subscribe(event);
return this;
} | javascript | {
"resource": ""
} |
q42114 | publish | train | function publish(event) {
/*jshint validthis: true */
if (DEBUG_DISPATCHER) log.info('PUBLISH: ' + event);
if (!event) {
return;
}
redisPublisher.publish(event, '');
return this;
} | javascript | {
"resource": ""
} |
q42115 | handleMessage | train | function handleMessage(event, message) {
/*jshint validthis: true */
if (DEBUG_DISPATCHER) log.info('MESSAGE: ' + event);
if (!event) {
return;
}
if (message && message !== '') {
throw 'A message payload was sent across Redis. We intentionally do not support this to avoid security issues.';
}
var callbacks = this.dispatcher._callbacks[event];
if (DEBUG_DISPATCHER) log.info('MESSAGE: CALLBACK LENGTH: ' + (callbacks && callbacks.length));
for (var i = 0, iL = callbacks && callbacks.length; i < iL; i++) {
callbacks[i].call(this.dispatcher._context, event);
}
} | javascript | {
"resource": ""
} |
q42116 | unsubscribe | train | function unsubscribe(event, callback) {
/*jshint validthis: true */
if (DEBUG_DISPATCHER) log.info('UNSUBSCRIBE: ' + event);
if (!event || !callback) {
return;
}
var callbacks = this._callbacks[event];
if (callbacks) {
for (var i = callbacks.length - 1; i >= 0; i--) {
if (callbacks[i] === callback) {
callbacks.splice(i, 1);
}
}
}
if (!callbacks || callbacks.length === 0) {
this._client.unsubscribe(event);
}
return this;
} | javascript | {
"resource": ""
} |
q42117 | detach | train | function detach(context) {
/*jshint validthis: true */
if (DEBUG_DISPATCHER) log.info('DETACHED.');
if (!context) {
return;
}
if (!attached(context)) {
return;
}
context.dispatcher._client.quit();
context.dispatcher._client.dispatcher = null;
context.dispatcher = null;
return this;
} | javascript | {
"resource": ""
} |
q42118 | train | function(query) {
var result = {};
if (!_.isObject(query) || _.isEmpty(query)) {
return result;
}
// timestamp might be in `ms` or `s`
_.forEach(query, function(timestamp, operator) {
if (!_.includes(['gt', 'gte', 'lt', 'lte', 'ne'], operator)) {
return;
}
// Timestamp must be an integer
timestamp = _.parseInt(timestamp);
if (_.isNaN(timestamp)) {
return;
}
// Convert seconds to milliseconds
timestamp = Mixins.isUnixTime(timestamp) ? timestamp * 1000 : timestamp;
result['$' + operator] = timestamp;
});
debug.info(
'#_buildTimestampQuery with query: %s and result: %s',
JSON.stringify(query),
JSON.stringify(result)
);
return result;
} | javascript | {
"resource": ""
} | |
q42119 | train | function(fields, data) {
if (!_.isString(fields)) {
return data;
}
// If a field is specified as `foo.bar` or `foo.bar.baz`,
// Convert it to just `foo`
var map = {};
_.forEach(fields.split(','), function(field) {
map[field.split('.')[0]] = 1;
});
var keys = _.keys(map);
if (_.isArray(data)) {
data = _.map(data, function(object) {
return _.pick(object, keys);
});
} else if (_.isObject(data)) {
data = _.pick(data, keys);
}
return data;
} | javascript | {
"resource": ""
} | |
q42120 | train | function() {
// Routes
this.routes = {
all: {},
get: {},
post: {},
put: {},
patch: {},
delete: {}
};
// Middleware(s)
this.pre = []; // run before route middleware
this.before = []; // run after route middleware but before route handler
this.after = []; // run after route handler
// Setup middleware and route handlers
this.setupPreMiddleware();
this.setupBeforeMiddleware();
this.setupRoutes();
this.setupAfterMiddleware();
// Response/error handler middleware
this.after.push(this.successResponse);
this.after.push(this.errorResponse);
this.after.push(this.finalResponse);
} | javascript | {
"resource": ""
} | |
q42121 | train | function(req, res, next) {
return function(modelOrCollection) {
this.prepareResponse(modelOrCollection, req, res, next);
}.bind(this);
} | javascript | {
"resource": ""
} | |
q42122 | train | function(modelOrCollection, req, res, next) {
if (!modelOrCollection) {
return next();
}
if (modelOrCollection instanceof Model) {
// Data is a Model
res.data = modelOrCollection.render();
} else if (modelOrCollection instanceof Collection) {
// Data is a Collection
res.data = modelOrCollection.render();
} else {
// Data is raw
res.data = modelOrCollection;
}
return next();
} | javascript | {
"resource": ""
} | |
q42123 | train | function(req, res, next) {
var data = res.data || null;
var code = 200;
if (_.isNumber(res.code)) {
code = res.code;
}
var envelope = {
meta: {
code: code
},
data: data
};
// Optional paging meta
if (res.paging) {
envelope.meta.paging = res.paging;
}
// Set code and data
res.code = code;
if (res.code !== 204) {
res.data = envelope;
}
return next();
} | javascript | {
"resource": ""
} | |
q42124 | train | function(err, req, res, next) {
err.message = err.message || 'Internal Server Error';
err.code = err.code || res.code || 500;
if (!_.isNumber(err.code)) {
err.code = 500;
}
try {
err.line = err.stack.split('\n')[1].match(/\(.+\)/)[0];
} catch (e) {
err.line = null;
}
var envelope = {
meta: {
code: err.code,
error: {
code: err.code,
message: err.message,
line: err.line
}
},
data: err.message
};
// Set code and data
res.code = err.code;
res.data = envelope;
return next();
} | javascript | {
"resource": ""
} | |
q42125 | train | function(req, res, next) {
// If we timed out before managing to respond, don't send the response
if (res.headersSent) {
return;
}
// Look for `.json` or `.xml` extension in path
// And override request accept header
if (/.json$/.test(req.path)) {
req.headers.accept = 'application/json';
} else if (/.xml$/.test(req.path)) {
req.headers.accept = 'application/xml';
}
// Use request accept header to determine response content-type
res.format({
json: function() {
res.status(res.code).jsonp(res.data);
},
xml: function() {
var xml;
try {
var xmlData = JSON.parse(JSON.stringify(res.data));
xml = this.xmlBuilder.buildObject(xmlData);
res.set('Content-Type', 'application/xml; charset=utf-8');
res.status(res.code).send(xml);
} catch (e) {
res.status(500).end();
}
}.bind(this)
});
} | javascript | {
"resource": ""
} | |
q42126 | train | function(req) {
var fields = {};
// Fields
if (_.isString(req.query.fields)) {
_.forEach(req.query.fields.split(','), function(field) {
fields[field] = 1;
});
}
return fields;
} | javascript | {
"resource": ""
} | |
q42127 | Link | train | function Link(props) {
// Handle clicks of the link
const onClick = e => {
e.preventDefault();
routeTo(path);
};
// If link is for a new tab
if(props.openIn === 'new') {
return (
<a href={props.to} target="_blank" rel="noopener noreferrer">
{props.children}
</a>
);
}
return (
<a href={props.to} onClick={onClick}>
{props.children}
</a>
);
} | javascript | {
"resource": ""
} |
q42128 | getQuery | train | function getQuery(path = '') {
const query = {};
// Check if the path even has a query first
if(!path.includes('?')) {
return query;
}
const queryString = path.split('?')[1];
// Check if the query string has any values
if(!queryString.includes('=')) {
return query;
}
const values = queryString.split('&');
// Loop over the query string values and add to the query object
for (let i = values.length - 1; i >= 0; i--) {
// Check that the current query string section has a value
if(!values[i].includes('=')) {
continue;
}
// Get the key and value to add to the query object
const [ key, value ] = values[i].split('=');
query[key] = value;
}
return query;
} | javascript | {
"resource": ""
} |
q42129 | normalizePath | train | function normalizePath(path = '') {
// Remove the trailing slash if one has been given
if(path.length > 1 && path.endsWith('/')) {
path = path.slice(0, -1);
}
// Remove the first slash
if(path.startsWith('/')) {
path = path.slice(1);
}
// Remove the query if it exists
if(path.includes('?')) {
path = path.split('?')[0];
}
// Decode the url
path = decodeURIComponent(path);
return path;
} | javascript | {
"resource": ""
} |
q42130 | match | train | function match(routes, path) {
// Get the query object before it gets stripped by the normalizer
const query = getQuery(path);
const pathname = path;
// Normalize the path
path = normalizePath(path);
// Loop over each route to find the match
for (let i = 0; i < routes.length; i++) {
// Normalize the current route
const currentRoute = normalizePath(routes[i].route);
// Create the params object
const params = {};
// Check if it's a straight match first
if(currentRoute === path) {
return Object.assign({}, routes[i], {params, query, pathname, path});
}
// If there are no dynamic/optional/match-all parts then this route cannot match
if(!isDynamicRoute.test(routes[i].route)) {
continue;
}
// Split up the route by it's slashes so that we may match by section
const routeSections = currentRoute.split('/');
const pathSections = path.split('/');
// Loop over each section looking for a full match
for (let j = routeSections.length - 1; j >= 0; j--) {
// If the route is to match everything, then return
if(j === 0 && routeSections[j] === '*') {
return Object.assign({}, routes[i], {params, query, pathname, path});
}
// If this section is optional
if(optionalSectionRegex.test(routeSections[j])) {
const currentSection = routeSections[j].replace(removeOptionalRegex, '');
// If it's a param, add it to the params
if(paramRegex.test(currentSection)) {
params[currentSection.replace(paramRegex, '')] = pathSections[j];
continue;
}
// If it's a star then skip to next
if(currentSection === '*') {
continue;
}
// If the optional section can possible be missing skip to next section
if(routeSections.length === pathSections.length + 1) {
continue;
}
// If the path and route sections have same number of sections and this does match, skip to next
if(routeSections.length === pathSections.length && currentSection === pathSections[j]) {
continue;
}
// Reject this route as the possible match to the path
break;
}
// If it's a param, add it to the params
if(paramRegex.test(routeSections[j])) {
params[routeSections[j].replace(paramRegex, '')] = pathSections[j];
if(j === 0) {
return Object.assign({}, routes[i], {params, query, pathname, path});
}
continue;
}
// If it's a star then skip to next
if(routeSections[j] === '*') {
continue;
}
// If this doesn't match then go to next route
if(routeSections[j] !== pathSections[j]) {
break;
}
// If the last item matches strictly then return that match
if(j === 0 && routeSections[j] === pathSections[j]) {
return Object.assign({}, routes[i], {params, query, pathname, path});
}
}
}
// No match found
return {path: '', params: {}, query};
} | javascript | {
"resource": ""
} |
q42131 | distances | train | function distances (tonic, gamut) {
if (!tonic) {
if (!gamut[0]) return []
tonic = gamut[0]
}
tonic = op.setDefaultOctave(0, tonic)
return gamut.map(function (p) {
return p ? op.subtract(tonic, op.setDefaultOctave(0, p)) : null
})
} | javascript | {
"resource": ""
} |
q42132 | uniq | train | function uniq (gamut) {
var semitones = heights(gamut)
return gamut.reduce(function (uniq, current, currentIndex) {
if (current) {
var index = semitones.indexOf(semitones[currentIndex])
if (index === currentIndex) uniq.push(current)
}
return uniq
}, [])
} | javascript | {
"resource": ""
} |
q42133 | getItemId | train | function getItemId(_existingItem) {
if (_.has(_existingItem, 'id')) {
itemToUpdate.id = _existingItem.id;
return String(_existingItem.id);
} else {
return itemToUpdate._localuid;
}
} | javascript | {
"resource": ""
} |
q42134 | encode | train | function encode(password, cb) {
var secret_key = conf.secret_key
, iterations = conf.pbkdf2_iterations
, keylen = conf.pbkdf2_keylen;
crypto.pbkdf2(password, secret_key, iterations, keylen, function(err, derivedKey) {
var str;
if(err) {
cb(err);
} else {
str = new Buffer(derivedKey).toString('base64');
cb(null, str);
}
});
} | javascript | {
"resource": ""
} |
q42135 | chain | train | function chain(tasks) {
return function() {
var pipeline = fullPipeline();
_.each(tasks, function(task) {
pipeline = pipeline.pipe(task.callback(options)());
});
return pipeline;
};
} | javascript | {
"resource": ""
} |
q42136 | parse | train | function parse(str) {
let res = {};
str.split(constants.REGEX.newline).map(line => {
line = line.trim();
// ignore empty lines and comments
if (!line || line[0] === '#') {
return;
}
// replace variables that are not escaped
line = line.replace(constants.REGEX.args, (match, $1, $2) => {
let key = $1 !== undefined ? $1 : $2;
if (match.slice(0, 2) === '\\\\') {
return match.slice(2);
}
return process.env[key] !== undefined ? process.env[key] : res[key];
});
// find the line split index based on the first occurence of = sign
let index = line.indexOf('=') > -1 ? line.indexOf('=') : line.length;
// get key/val and trim whitespace
let key = line.slice(0, index).trim();
let val = line.slice(index +1).trim();
val = parseComment(val).replace(constants.REGEX.quotes, '');
res[key] = unescape(val);
});
return res;
} | javascript | {
"resource": ""
} |
q42137 | checkPort | train | function checkPort(port, cb) {
var server = new net.Server();
server.on('error', function (err) {
server.removeAllListeners();
cb(err);
});
server.listen(port, function () {
server.on('close', function () {
server.removeAllListeners();
cb(null, port);
});
server.close();
});
} | javascript | {
"resource": ""
} |
q42138 | find | train | function find(ports, callback) {
if (_.isEmpty(ports)) {
callback(new Error('no free port available'));
} else {
var port = ports.shift();
checkPort(port, function (err, found) {
if (!err) {
callback(null, found);
} else {
find(ports, callback);
}
});
}
} | javascript | {
"resource": ""
} |
q42139 | authenticate | train | function authenticate(req, cb) {
request.post(
'https://github.com/login/oauth/access_token',
{ form:
{ client_id: process.env.GHID, // don't store credentials in opts
client_secret: process.env.GHCS, // get them straight from process.env
code: req.query.code } },
function(err, resp, body) {
if (err) return cb(err);
var result = qs.parse(body);
getUser(req, result, function() {
cb(null, result);
});
}
);
} | javascript | {
"resource": ""
} |
q42140 | train | function (value, elem) {
var tmpl = elem.firstElementChild
elem.removeChild(tmpl)
value.forEach(function (text) {
var clone = tmpl.cloneNode(true)
clone.textContent = text
elem.appendChild(clone)
})
} | javascript | {
"resource": ""
} | |
q42141 | isOk | train | function isOk(err, res, body) {
if (err) {
return callback(err);
}
var statusCode = res.statusCode.toString(),
error;
//
// Emit response for debug purpose
//
self.emit('debug::response', { statusCode: statusCode, result: body });
if (Object.keys(self.failCodes).indexOf(statusCode) !== -1) {
error = new Error('composer Error (' + statusCode + '): ' + self.failCodes[statusCode]);
if (body) {
try { error.result = JSON.parse(body) }
catch (ex) {}
}
error.status = res.statusCode;
callback(error);
return false
}
return true;
} | javascript | {
"resource": ""
} |
q42142 | train | function(attributes, isPermanent) {
if(isPermanent) attributes.permanent = true;
if(attributes === 'reset') this.markerAttributes = {
background: undefined,
color: undefined,
style: undefined,
verbosity: undefined
}; else _.defaults(this.__super__.markerAttributes, attributes);
return this;
} | javascript | {
"resource": ""
} | |
q42143 | binarySearch | train | function binarySearch(o, v, i, compareFunction){
var h = o.length, l = -1, m
while(h - l > 1)
if(compareFunction(o[m = h + l >> 1], v) < 1) l = m
else h = m
return o[h] != v ? i ? h : -1 : h
} | javascript | {
"resource": ""
} |
q42144 | train | function (n1, n2) {
var isOk1 = _isNumber(n1),
isOk2 = _isNumber(n2);
if (isOk1 && isOk2) {
// both are finite numbers
return (n1 - n2);
}
else if (isOk1)
return -1;
else if (isOk2)
return 1;
else
return 0;
} | javascript | {
"resource": ""
} | |
q42145 | train | function (itr, noError) {
if ( typeof itr.hasNext !== 'function'
|| typeof itr.next !== 'function' )
throw "IllegalArgumentException: itr must implement methods hasNext() and next().";
var prec = 0;
while (itr.hasNext()) {
var p = _getPrecision(itr.next(), noError);
if (p > prec)
prec = p;
}
return prec;
} | javascript | {
"resource": ""
} | |
q42146 | train | function (num) {
if (typeof num !== 'number')
throw "TypeMismatch: num: Number";
else if (!isFinite(num))
return num.toString();
else {
var p = _getPrecision(num);
return num.toFixed(Math.max(0, p));
}
} | javascript | {
"resource": ""
} | |
q42147 | train | function (format) {
_validFormat(format);
var fn = null;
if (_formatFnAll.hasOwnProperty(format))
fn = _formatFnAll[format];
else {
var m = _regexDecFormat.exec(format);
if (m !== null)
fn = _getDecFormatter( ( (typeof m[3] === 'string')
? m[3].length
: 0 ),
(m[1] === '+'),
(m[4] === '%') );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
fn = _getFractFormatter( parseInt(m[2], 10),
(m[1] === '+') ); // isPlus
}
_formatFnAll[format] = fn;
}
if (fn !== null)
return fn;
else // Throw an exception every time
throw "IllegalArgumentException: unsupported number format (" + format + ")";
} | javascript | {
"resource": ""
} | |
q42148 | train | function (format) {
_validFormat(format);
var m = _regexDecFormat.exec(format);
if (m !== null)
return ( (typeof m[3] === 'string') ? m[3].length : 0 )
+ ( (m[4] === '%') ? 2 : 0 );
else {
m = _regexFracFormat.exec(format);
if (m !== null)
return _getPrecision(1 / parseInt(m[2], 10));
}
throw "IllegalArgumentException: format is not recognized (" + format + ")";
} | javascript | {
"resource": ""
} | |
q42149 | unify | train | function unify(options) {
const map = {
height: 'barHeight',
background: 'bgColor',
text: 'showHRI'
};
return Object.keys(options).reduce(
(carry, key) => ({
...carry,
[key in map ? map[key] : key]: options[key]
}),
{}
);
} | javascript | {
"resource": ""
} |
q42150 | applyAuth | train | function applyAuth(authContexts, server, callback) {
if (authContexts.length === 0) return callback();
// Get the first auth context
var authContext = authContexts.shift();
// Copy the params
var customAuthContext = authContext.slice(0);
// Push our callback handler
customAuthContext.push(function(/* err */) {
applyAuth(authContexts, server, callback);
});
// Attempt authentication
server.auth.apply(server, customAuthContext);
} | javascript | {
"resource": ""
} |
q42151 | train | function(self, op, ns, ops, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Pick a server
let server = pickProxy(self);
// No server found error out
if (!server) return callback(new MongoError('no mongos proxy available'));
if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) {
// Execute the command
return server[op](ns, ops, options, callback);
}
// increment and assign txnNumber
options.willRetryWrite = true;
options.session.incrementTransactionNumber();
server[op](ns, ops, options, (err, result) => {
if (!err) return callback(null, result);
if (!isRetryableError(err)) {
return callback(err);
}
// Pick another server
server = pickProxy(self);
// No server found error out with original error
if (!server || !isRetryableWritesSupported(server)) {
return callback(err);
}
// rerun the operation
server[op](ns, ops, options, callback);
});
} | javascript | {
"resource": ""
} | |
q42152 | ordered | train | function ordered (ondelay) {
var clk = 0
var queue = []
var checking = 0
function check () {
if (checking++) return
setImmediate(function () {
var o = queue.shift()
clk = o[1]
ondelay(function () {
checking = 0
if (queue.length) check()
o[0]()
}, o[2])
})
}
function delay (fn, ms) {
var len = queue.length, i = 0
while (queue.length === len) {
if (queue[i]) {
if (queue[i][1] > clk + ms) {
queue.splice(i, 0, [fn, clk + ms, ms])
}
} else queue.push([fn, clk + ms, ms])
++i
}
check()
}
return delay
} | javascript | {
"resource": ""
} |
q42153 | markdown | train | function markdown(options) {
options = _.extend({
depth: 1,
indent: true
}, options || {})
var isFirst = true;
return through2.obj(function(doc, encoding, done) {
var out = [];
if(isFirst) { isFirst = false } else { out.push('\n\n') }
var depth = options.depth;
if(options.indent && !doc.isClass && !doc.isFunction && !doc.isExport) {
depth++;
}
out.push(repeat('#',depth) + ' ' + doc.signature + '')
out.push('> ' + doc.summary)
if(doc.body) {
out.push('\n' + doc.body)
}
// Parameters
if(~doc.flags.indexOf('param')) {
out.push('')
out.push('**Parameters:**\n')
var isFirstParam = true;
doc.tags.forEach(function(tag) {
if(tag.type != 'param') return;
if(isFirstParam) { isFirstParam = false } else { out.push('') }
var description = '\n' + tag.description.trim().split('\n').map(function(line) {
return line.trim() == '' ? '' : ' ' + line
}).join('\n')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
out.push(sprintf(' - **%s**%s%s', tag.token, types, description))
})
}
var isFirstTag = true;
doc.tags.forEach(function(tag) {
if(~['param', 'memberOf'].indexOf(tag.type)) return;
out.push('')
var types = tag.types ? ' {' + tag.types.map(function(type) { return '`' + type + '`' }).join('|') + '}' : '';
var description = '\n' + tag.description.trim()
out.push(sprintf('**%s**%s%s', tag.type, types, description))
})
done(null, out.join('\n'))
})
} | javascript | {
"resource": ""
} |
q42154 | post | train | function post(argv, callback) {
if (!argv[2]) {
console.error("url is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
if (!argv[3]) {
console.error("data is required");
console.error("Usage : post <url> <data>");
process.exit(-1);
}
util.post(argv[2], argv[3], function(err, val) {
if (!err) {
callback(null, argv[2]);
} else {
callback(err);
}
});
} | javascript | {
"resource": ""
} |
q42155 | DbWriter | train | function DbWriter(db,errorLogObject,successLogObject) {
this.db = db;
this.errorLogObject = errorLogObject;
this.successLogObject = successLogObject;
} | javascript | {
"resource": ""
} |
q42156 | handleError | train | function handleError(note,needsReconnect) {
writer.logError({
src_id: streamConfig.src_id,
ts: Date.now(),
error: note
});
if(needsReconnect) {
setTimeout(function() { doIoStream(streamConfig); }, 1000*streamConfig.error_wait_secs);
}
} | javascript | {
"resource": ""
} |
q42157 | setup | train | function setup(settings) {
if (!settings) {
return _.cloneDeep(SETTINGS);
}
_.merge(SETTINGS, settings);
return _.cloneDeep(SETTINGS);
} | javascript | {
"resource": ""
} |
q42158 | parseResponse | train | function parseResponse(response) {
var code = response.statusCode;
var type = code / 100 | 0;
response.type = type;
// basics
switch (type) {
case 1:
response.info = type;
break;
case 2:
response.ok = type;
break;
case 3:
// ???
break;
case 4:
response.clientError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
case 5:
response.serverError = type;
response.error = type;
response.ErrorClass = errors.HttpStatusError;
break;
}
// error classes and sugar
switch (code) {
case 201:
response.created = code;
break;
case 202:
response.accepted = code;
break;
case 204:
response.noContent = code;
break;
case 400:
response.badRequest = code;
break;
case 401:
response.unauthorized = code;
response.ErrorClass = errors.AuthenticationRequiredError;
break;
case 403:
response.forbidden = code;
response.ErrorClass = errors.NotPermittedError;
break;
case 404:
response.notFound = code;
response.ErrorClass = errors.NotFoundError;
break;
case 406:
response.notAcceptable = code;
break;
case 500:
response.internalServerError = code;
break;
}
// using body (and not status code)
if (response.body && response.body.success === false) {
if (!response.error) {
response.error = 4; // assume is client error
response.ErrorClass = errors.HttpStatusError;
}
}
// null bodies
if (_.includes([null, undefined, ""], response.body)) {
if (!response.error) {
response.error = 5; // assume the server fucked up
response.ErrorClass = errors.HttpStatusError;
}
}
return response;
} | javascript | {
"resource": ""
} |
q42159 | passResponse | train | function passResponse(callback, options) {
options = options || {};
return function handleResponse(error, response, body) {
if (error) {
return callback(new errors.io.IOError(error.mesage, error));
}
response = parseResponse(response);
body = body || { };
if (response.error) {
var message = response.body ? response.body.message : "received an empty body";
var err = new response.ErrorClass(response.statusCode, message);
if (options.post || options.put) return callback(err, body, response);
return callback(err, body.data, body.meta, response);
}
if (options.post || options.put) return callback(null, body, response);
return callback(null, body.data, body.meta, response);
};
} | javascript | {
"resource": ""
} |
q42160 | allowOptionalParams | train | function allowOptionalParams(params, callback) {
if (!callback) {
callback = params;
params = { };
}
return {
params: params,
callback: callback,
};
} | javascript | {
"resource": ""
} |
q42161 | getOptions | train | function getOptions(sources, keys, dest) {
var options = dest || { };
// allow source be an array
if (!_.isArray(sources)) {
sources = [ sources ];
}
// using the keys for lookup
keys.forEach(function(key) {
// from each source
sources.forEach(function(source) {
if (source && source[key]) {
options[key] = source[key];
}
});
});
return options;
} | javascript | {
"resource": ""
} |
q42162 | removeOptions | train | function removeOptions(args, keys) {
if (!_.isArray(keys)) {
keys = [ keys ];
}
for (var index = 0; index < args.length; index++) {
var arg = args[index];
for (var key in arg) {
if (_.includes(keys, key)) {
delete arg[key];
}
}
}
} | javascript | {
"resource": ""
} |
q42163 | pickParams | train | function pickParams(params, keys) {
params = _.cloneDeep(params);
// decamelize all options
for (var key in params) {
var value = params[key];
delete params[key];
// TODO: handle this inconsistency consistently in the library :(
// 'base64String': introduced by 'image.upload()'
if (["base64String"].indexOf(key) === -1) {
key = decamelize(key, "_");
}
params[key] = value;
}
if (SETTINGS.enforce_params_filter) {
return _.pick(params, keys);
}
return params;
} | javascript | {
"resource": ""
} |
q42164 | collectPages | train | function collectPages(func, callback) {
var items = [];
var lastReadId = 0;
function __collect() {
return func(lastReadId, function(error, page) {
if (error) {
return callback(error);
}
if (!page.length) {
return callback(null, items);
}
items = items.concat(page);
lastReadId = page[page.length - 1].id;
return __collect();
});
}
return __collect();
} | javascript | {
"resource": ""
} |
q42165 | LevDist | train | function LevDist (s, t) {
var d = []
, n = s.length
, m = t.length
, i
, j
, s_i
, t_j
, cost
, mi
, b
, c
;
if (n == 0) return m;
if (m == 0) return n;
// Step 1
for (i = n; i >= 0; --i) { d[i] = []; }
// Step 2
for (i = n; i >= 0; --i) { d[i][0] = i; }
for (j = m; j >= 0; --j) { d[0][j] = j; }
// Step 3
for (i = 1; i <= n; ++i) {
s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; ++j) {
// Check the jagged ld total so far
if (i == j && d[i][j] > 4) { return n; }
t_j = t.charAt(j - 1);
// Step 5
cost = (s_i == t_j) ? 0 : 1;
//Calculate the minimum
mi = d[i - 1][j] + 1;
b = d[i][j - 1] + 1;
c = d[i - 1][j - 1] + cost;
if (b < mi) { mi = b; }
if (c < mi) { mi = c; }
// Step 6
d[i][j] = mi;
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
} | javascript | {
"resource": ""
} |
q42166 | readTokenFile | train | function readTokenFile(tokenFile) {
return new Promise((resolve, reject) => {
fs.readFile(tokenFile, 'utf8', (err, token) => {
if (err) {
reject(err);
}
resolve(token.slice(0, 40));
});
});
} | javascript | {
"resource": ""
} |
q42167 | createGithubCredentials | train | function createGithubCredentials(token) {
return new Promise((resolve, reject) => {
if (token) {
resolve({ type: 'oauth', token: token });
}
else {
reject('Missing token');
}
});
} | javascript | {
"resource": ""
} |
q42168 | getUserCredentials | train | function getUserCredentials() {
return new Promise((resolve) => {
print(clc.bold('Sign in to authorize this app to find open pull-requests'), true);
gitUser.email((err, email) => {
prompt.message = '';
prompt.delimiter = '';
prompt.start();
prompt.get({
properties: {
username: {
description: 'Github username',
default: email,
message: 'Name must be only letters, spaces, or dashes',
required: true
},
password: {
description: 'Github password',
hidden: true
}
}
}, (err, result) => {
resolve(result);
});
});
});
} | javascript | {
"resource": ""
} |
q42169 | authorizeApp | train | function authorizeApp(user, tokenName, scope) {
return new Promise((resolve, reject) => {
request.post('https://api.github.com/authorizations', {
auth: {
user: user.username,
pass: user.password,
sendImmediately: true
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'User-Agent': tokenName
},
body: JSON.stringify({
scopes: scope,
note: tokenName
})
}, (err, response, body) => {
if (err) {
reject(err);
}
const returnBody = JSON.parse(body);
if (returnBody.token) {
resolve(returnBody.token);
}
else if (returnBody.errors) {
console.log(returnBody.errors);
reject(returnBody.errors);
}
});
});
} | javascript | {
"resource": ""
} |
q42170 | createTokenFile | train | function createTokenFile(token, tokenFile) {
return new Promise((resolve, reject) => {
fs.writeFile(tokenFile, token, (err) => {
if (err) {
reject(err);
}
resolve(token);
});
});
} | javascript | {
"resource": ""
} |
q42171 | scrape | train | function scrape(dyn, url, scope, selector) {
return new Promise(function(dresolve, dreject) {
var scraper = dyn ? dx : x;
scraper(url, scope, selector)(function(err, res) {
dresolve(res);
})
})
} | javascript | {
"resource": ""
} |
q42172 | Sensor | train | function Sensor(key, params) {
var p = params || {};
// The sensor primary key [String]
this.key = key;
// Human readable name of the sensor [String] EG - "Thermometer 1"
this.name = p.name || "";
// Indexable attributes. Useful for grouping related sensors.
// EG - {unit: "F", model: 'FHZ343'}
this.attributes = p.attributes || {};
} | javascript | {
"resource": ""
} |
q42173 | splitNext | train | function splitNext(source, cb, rules) {
var matchPos = source.search( makeRegExp( joinProperties( rules ) ) );
if (matchPos != -1) {
var match = source.substr( 0, matchPos + 1 )
for (property in rules) {
var rule = rules[property]
, re = makeRegExp( rule );
if (source.search(re) == matchPos) {
var token = source.match( re )
, response = {
lhs: source.substr( 0, matchPos ),
rhs: source.substr( matchPos + token[0].length ),
token: token[0]
};
cb( property, response );
return;
}
}
}
cb( 'end', { lhs: source } );
function makeRegExp( rules ) {
return new RegExp( '(' + rules + ')' );
}
function joinProperties(properties) {
var result = [];
for(property in properties) {
result.push( properties[property] );
}
return result.join( '|' );
}
} | javascript | {
"resource": ""
} |
q42174 | splitAll | train | function splitAll(source, cb, rules) {
var done = false
, stash = '';
do {
splitNext( source, function(event, response) {
response.stash = stash;
if (event == 'end') done = true;
else {
source = response.rhs;
stash += response.lhs + response.token;
response.consume = function(length) {
stash += source.substr( 0, length );
source = source.substr( length, source.length );
};
response.resetStash = function() {
stash = '';
};
response.break = function() {
done = true;
};
}
cb( event, response );
},
rules );
}
while(!done);
} | javascript | {
"resource": ""
} |
q42175 | send | train | function send(method, params, callback) {
if (typeof params === "function") {
callback = params;
params = [];
}
self.web3.currentProvider.sendAsync({
jsonrpc: "2.0",
method,
params: params || [],
id: new Date().getTime(),
}, callback);
} | javascript | {
"resource": ""
} |
q42176 | underscoreToCamel | train | function underscoreToCamel (str) {
str = str.charAt(0).toUpperCase() + str.slice(1);
return str.replace(/\_(.)/g, function (x, chr) {
return chr.toUpperCase();
})
} | javascript | {
"resource": ""
} |
q42177 | find3rdPartyCaveatParts | train | function find3rdPartyCaveatParts(macaroonWithCaveat, secretPem) {
var macaroonSerialized = macaroonWithCaveat.macaroon;
var discharge = macaroonWithCaveat.discharge;
var key = new NodeRSA();
key.importKey(secretPem);
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getDischargeParts = getMacPartsFn(" = ");
var macObj = macaroonPairsToObj(key.decrypt(discharge).toString('utf8'), getDischargeParts);
var caveatKey = macObj.caveat_key;
var message = macObj.message;
var macaroon = MacaroonsBuilder.deserialize(macaroonSerialized);
var getMacaroonParts = getMacPartsFn(" ");
var stringMacPairs = macStringToPairs(macaroon.inspect(), getMacaroonParts);
var identifierLoc = _.findIndex(stringMacPairs, function (pair) {
return pair[0] === "cid" && pair[1] === "enc = " + discharge;
});
var caveatIdentifier = stringMacPairs[identifierLoc][1];
var caveatLocation = stringMacPairs[identifierLoc + 2][1];//kind of a hack
return {
caveatKey: caveatKey,
macRaw: macaroonSerialized,
thirdParty: {
messageObj: macaroonPairsToObj(macObj.message, getDischargeParts),
identifier: caveatIdentifier,
location: caveatLocation
}
};
} | javascript | {
"resource": ""
} |
q42178 | train | function() {
serviceFactory.optionalDeps = {}
_.each(arguments, function(depName) {
serviceFactory.optionalDeps[depName] = true
})
} | javascript | {
"resource": ""
} | |
q42179 | value | train | function value(dsv, obj) {
dsv = dsv || '';
obj = obj || {};
var props = dsv.split('.'),
_value;
for (var i = 0, ln = props.length; i < ln; i += 1) {
_value = (_value) ? _value[props[i]] : obj[props[i]];
if (_value === undefined) {
break;
}
}
return _value;
} | javascript | {
"resource": ""
} |
q42180 | train | function (value) {
var type = typeof value,
checkLength = false;
if (value && type != 'string') {
// Functions have a length property, so we need to filter them out
if (type == 'function') {
// In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
// to explicitly check them here.
// if (Ext.isSafari) {
// checkLength = value instanceof NodeList || value instanceof HTMLCollection;
// }
} else {
checkLength = true;
}
}
return checkLength ? value.length !== undefined : false;
} | javascript | {
"resource": ""
} | |
q42181 | _getDateMillis | train | function _getDateMillis (epoc) {
// Use highres time if available as JS date is +- 15ms
try {
var microtime = require('microtime');
// Time in microsecs, convert to ms
return (Math.round(microtime.now() / 1000) - epoc.getTime()).toString(2);
} catch (err) {}
return ((new Date()) - epoc).toString(2);
} | javascript | {
"resource": ""
} |
q42182 | _identity | train | function _identity (ndate, nrandom, nchecksum, epoc) {
// ms since EPOC (1 Jan 1970)
var since = _getDateMillis(epoc);
// Max of ndate
if (since.length > ndate) {
throw new Error('Date too big');
}
// Pad to ndate
since = bitString.pad(since, ndate);
// Add nrandom Random bits
since += bitString.randomBits(nrandom);
// Add checksum bits
since += bitString.checksum(since, nchecksum);
// Convert to BaseURL
return baseURL.encode(since);
} | javascript | {
"resource": ""
} |
q42183 | _isValid | train | function _isValid (ndate, nrandom, nchecksum, id) {
// Guard
if (!baseURL.isValid(id)) return false;
if (id.length !== (ndate + nrandom + nchecksum) / 6) return false;
// Test
var bits = baseURL.decode(id),
main = bits.slice(0, bits.length - nchecksum),
check = bits.slice(bits.length - nchecksum, bits.length);
return bitString.checksum(main, nchecksum) === check;
} | javascript | {
"resource": ""
} |
q42184 | _toDate | train | function _toDate (ndate, nrandom, nchecksum, epoc, id) {
// Guard
if (!_isValid(ndate, nrandom, nchecksum, id)) throw new Error('identity#toDate: Invalid Id');
// Calculate
var bits = baseURL.decode(id),
dateBits = bits.slice(0, ndate);
return new Date(parseInt(dateBits, 2) + epoc.getTime());
} | javascript | {
"resource": ""
} |
q42185 | createIdentity | train | function createIdentity (ndate, nrandom, nchecksum, epoc) {
var def = function identity () {
return _identity(ndate, nrandom, nchecksum, epoc);
};
def.EPOC = epoc;
def.dateLength = ndate;
def.randomLength = nrandom;
def.checksumLength = nchecksum;
def.size = ndate + nrandom + nchecksum;
def.isValid = function isValid(id) {
return _isValid(ndate, nrandom, nchecksum, id);
};
def.toDate = function toDate(id) {
return _toDate(ndate, nrandom, nchecksum, epoc, id);
};
return def;
} | javascript | {
"resource": ""
} |
q42186 | rpt_cb | train | function rpt_cb (err, data) {
if (err) return logger.error(err)
if (data.error) return logger.error(data.error)
if (!data.package) {
logger.warn('`data.package` not defined. Initializing placeholder.')
data.package = {}
}
var dependencyReport = {}
if (!data.package || !data.package.name) logger.warn('`data.package.name` missing')
dependencyReport.name = data.package.name
if (!data.package || !data.package.version) logger.warn('`data.package.version` missing')
dependencyReport.version = data.package.version
if (options.meta) {
dependencyReport.meta = {
nodeVersions: process.versions,
date: Date.now()
}
}
buildDependencyReport(dependencyReport, data, options, 0)
// Finally, return gatherDependencies callback
callback(null, dependencyReport)
} | javascript | {
"resource": ""
} |
q42187 | buildDependencyReport | train | function buildDependencyReport (report, data, options, depth) {
if (!report) report = {}
if (!data) data = {}
if (!options) options = {}
if (!depth) depth = 0
var lookup = {}
var npmDependencyTypes = depth ? depthNpmDependencyTypes : topLevelNpmDependencyTypes
// build list of all dependencies
npmDependencyTypes.forEach(function types (type) {
if (data.package[type] && Object.keys(data.package[type]).length) {
report[type] = data.package[type]
// remap versions as objects instead of a string
Object.keys(report[type]).forEach(function dep (name) {
// build lookup to reference back to build off of
lookup[name] = type
report[type][name] = { requestedVersion: report[type][name] }
})
}
})
data.children.forEach(function childDeps (depData) {
if (!lookup[depData.package.name]) return // not a relevant dependency (probably devDep)
var entry = report[lookup[depData.package.name]][depData.package.name]
entry.version = depData.package.version
entry.from = depData.package._from
entry.realpath = depData.realpath
buildDependencyReport(entry, depData, options, depth + 1)
})
return report
} | javascript | {
"resource": ""
} |
q42188 | SmD | train | function SmD(ms_per_unit, range) {
this.ms_per_unit = ms_per_unit;
this.range = range;
this.range_in_ms = ms_per_unit * range;
} | javascript | {
"resource": ""
} |
q42189 | train | function( digest ) {
var signature = ECDSASignature.decode( digest, 'der' )
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
var r = Buffer.from( signature.r.toString( 'hex', length ), 'hex' )
var s = Buffer.from( signature.s.toString( 'hex', length ), 'hex' )
return Buffer.concat([ r, s ], r.length + s.length )
} | javascript | {
"resource": ""
} | |
q42190 | train | function( input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( this.type === 'PLAIN' )
return Buffer.allocUnsafe(0)
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
var signature = this.type === 'HS' ?
crypto.createHmac( this.algorithm + this.bits, key ) :
crypto.createSign( this.algorithm + this.bits )
signature.update( input )
var digest = this.type === 'HS' ?
signature.digest() :
signature.sign( key )
if( this.type === 'ES' )
digest = this._signECDSA( digest )
return digest
} | javascript | {
"resource": ""
} | |
q42191 | train | function( signature, input, key ) {
var check = this.sign( input, key )
return signature.toString( 'hex' ) ===
check.toString( 'hex' )
} | javascript | {
"resource": ""
} | |
q42192 | train | function( signature, input, key ) {
var verifier = crypto.createVerify( this.algorithm + this.bits )
return verifier.update( input )
.verify( key, signature )
} | javascript | {
"resource": ""
} | |
q42193 | train | function( signature, input, key ) {
var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )
if( signature.length !== length * 2 )
return false
var sig = ECDSASignature.encode({
r: new BigNum( signature.slice( 0, length ), 10, 'be' ).iabs(),
s: new BigNum( signature.slice( length ), 10, 'be' ).iabs(),
}, 'der' )
return crypto.createVerify( this.algorithm + this.bits )
.update( input )
.verify( key, sig, 'base64' )
} | javascript | {
"resource": ""
} | |
q42194 | train | function( signature, input, key ) {
if( !Buffer.isBuffer( input ) )
throw new TypeError( 'Input must be a buffer' )
if( !Buffer.isBuffer( signature ) )
throw new TypeError( 'Signature must be a buffer' )
if( this.type === 'PLAIN' )
return signature.length === 0
if( !Buffer.isBuffer( key ) )
throw new TypeError( 'Key must be a buffer' )
switch( this.type ) {
case 'HS': return this._verifyHMAC( signature, input, key )
case 'RS': return this._verifyRSA( signature, input, key )
case 'ES': return this._verifyECDSA( signature, input, key )
default:
throw new Error( 'Unsupported type "' + this.type + '"' )
}
} | javascript | {
"resource": ""
} | |
q42195 | isAffineMatrix | train | function isAffineMatrix(object) {
return isObject(object) && object.hasOwnProperty('a') && isNumeric(object.a) && object.hasOwnProperty('b') && isNumeric(object.b) && object.hasOwnProperty('c') && isNumeric(object.c) && object.hasOwnProperty('d') && isNumeric(object.d) && object.hasOwnProperty('e') && isNumeric(object.e) && object.hasOwnProperty('f') && isNumeric(object.f);
} | javascript | {
"resource": ""
} |
q42196 | train | function (filePath) {
var name = ES6ModuleFile.prototype.getModuleName.apply(this, arguments);
if (_.isFunction(this.opts.moduleName)) {
name = this.opts.moduleName(name, filePath);
}
return name;
} | javascript | {
"resource": ""
} | |
q42197 | init | train | function init(config){
var logger = new LogglyLogger(config);
logger.validateConfig();
logger.config = config;
logger.client = loggly.createClient({
token: config.token,
subdomain: config.application,
auth: config.auth,
// TOOD: pushing more tags onto this array, or not using them, should be configurable
tags: [
config.domain,
config.machine
]
// Loggly docs say it uses json stringify if json:true
// JSON stringify does not handle Errors or circulare references well
// Logger.createEntry handles them well
});
return logger;
} | javascript | {
"resource": ""
} |
q42198 | writeLog | train | function writeLog(type, category){
return function(messages) {
var funcs = [];
_.each(messages, function(message){
funcs.push(this.client.logAsync(message, [type, category]));
}.bind(this));
return BB.all(funcs);
};
} | javascript | {
"resource": ""
} |
q42199 | FileResource | train | function FileResource( pkg, config ) {
var key,
resource = this,
dir = pkg.getDirectory(),
cfg = { files: [] };
// Normalize configuration
if ( typeof config === 'string' ) {
cfg.files.push( config );
} else if ( Array.isArray( config ) ) {
cfg.files = cfg.files.concat( config );
} else {
for ( key in config ) {
if ( key === 'file' || key === 'files' ) {
cfg.files = cfg.files.concat(
Array.isArray( config[key] ) ? config[key] : [ config[key] ]
);
} else {
cfg[key] = config[key];
}
}
}
cfg.files = cfg.files.map( function ( file ) {
return path.join( dir, file );
} );
// Parent constructor
FileResource.super.call( this, pkg, cfg );
// Properties
this.versionGenerator = function *() {
return yield ay( cfg.files )
.reduce( resource.reduceFileToMaximumModifiedTime, 1 );
};
this.contentGenerator = function *( options ) {
return yield ay( cfg.files )
.map( function *( file ) {
return yield resource.mapFileToContent( file, options );
} )
.reduce( resource.reduceContentToConcatenatedContent, '' );
};
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.