_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q33200 | findContentNode | train | function findContentNode(el) {
if (!el) {
return;
}
var oldCebContentId = el.getAttribute(OLD_CONTENT_ID_ATTR_NAME);
if (oldCebContentId) {
return findContentNode(el.querySelector('[' + oldCebContentId + ']')) || el;
}
return el;
} | javascript | {
"resource": ""
} |
q33201 | cleanOldContentNode | train | function cleanOldContentNode(el) {
var oldContentNode = el.lightDOM,
lightFrag = document.createDocumentFragment();
while (oldContentNode.childNodes.length > 0) {
lightFrag.appendChild(oldContentNode.removeChild(oldContentNode.childNodes[0]));
}
return lightFrag;
} | javascript | {
"resource": ""
} |
q33202 | applyTemplate | train | function applyTemplate(el, tpl) {
var lightFrag = void 0,
handleContentNode = hasContent(tpl);
if (handleContentNode) {
var newCebContentId = 'ceb-content-' + counter++;
lightFrag = cleanOldContentNode(el);
tpl = replaceContent(tpl, newCebContentId);
el.setAttribute(OLD_CONTENT_ID_ATTR_NAME, newCebContentId);
}
el.innerHTML = tpl;
if (handleContentNode && lightFrag) {
el.lightDOM.appendChild(lightFrag);
}
} | javascript | {
"resource": ""
} |
q33203 | isAnImportantParamMissing | train | function isAnImportantParamMissing (obj) {
var i = 0
var l = Message._importantParams.length
for (; i < l; i++) {
var value = obj[Message._importantParams[i]]
if (value === null || value === undefined) {
return true
}
}
} | javascript | {
"resource": ""
} |
q33204 | Message | train | function Message (opts) {
if (!(this instanceof Message)) return new Message(opts)
this.type = opts.type || 0
this.clientReference = opts.clientReference || null
this.direction = opts.direction || 'out'
this.flashMessage = opts.flash || null
this.messageId = opts.messageId || null
this.networkId = opts.networkId || null
this.rate = opts.rate || null
this.registeredDelivery = opts.registeredDelivery || null
this.status = opts.status || null
this.time = opts.time || null
this.udh = opts.udh || null
this.units = opts.units || null
this.updateTime = opts.updateTime || null
if (isAnImportantParamMissing(opts)) {
throw new SMSGHError('Important message option missing. Required options are: `from`, `to` and `content`')
}
var i = 0
var l = Message._importantParams.length
for (i = 0; i < l; i++) {
this[Message._importantParams[i]] = opts[Message._importantParams[i]]
}
} | javascript | {
"resource": ""
} |
q33205 | val | train | function val(value) {
var first = this.get(0);
function getValue(el) {
var nm = el.tagName.toLowerCase()
, type = el.getAttribute('type');
if(nm === SELECT) {
return getSelectValues(el).join(
el.getAttribute('data-delimiter') || ',');
}else if(type === CHECKBOX) {
return Boolean(el.checked);
}
return el.value;
}
function setValue(el, value) {
var nm = el.tagName.toLowerCase()
, type = el.getAttribute('type');
if(nm === TEXTAREA) {
while(el.childNodes.length) {
el.removeChild(el.childNodes[0])
}
el.appendChild(document.createTextNode(value));
}else if(nm === SELECT) {
setSelectValues(el, value);
}else if(type === RADIO) {
el.setAttribute('checked', '');
}else if(type === CHECKBOX && Boolean(value)) {
el.checked = true;
}else{
el.value = value;
}
}
if(value === undefined && first) {
return getValue(first);
}else if(value) {
this.each(function(el) {
setValue(el, value);
})
}
return this;
} | javascript | {
"resource": ""
} |
q33206 | getView | train | function getView(app, viewName, defaultView='error'){
/*
* views could be an array...
*/
let views = app.get('views');
const ext = app.get('view engine');
if(!Array.isArray(views)) views = [views];
let view;
for(var i = 0; i < views.length; i++){
view = path.join(views[i], viewName + '.' + ext);
if (exists(view)) return view;
}
if (app.parent) return getView(app.parent, viewName, defaultView);
return defaultView;
} | javascript | {
"resource": ""
} |
q33207 | logSome | train | function logSome(env = 'dev', level = 'none') {
let levelNum = 3
const theme = {
normal: '#92e6e6',
error: '#ff5335',
info: '#2994b2',
warn: '#ffb400'
}
const setLevel = level => {
switch (level) {
case 'error':
levelNum = 1
break
case 'warn':
levelNum = 2
break
case 'info':
levelNum = 3
break
default:
levelNum = (env === 'development' || env === 'dev') ? 3 : 1
break
}
}
const getStyle = color => `color:${color || '#8b80f9'};font-weight:bold;`
const isLogEnable = (opts, force, env) => {
if (opts.level) {
return force
} else {
return force || env === 'development' || env === 'dev'
}
}
const logger = (info, force, opts = {}) => {
if (isLogEnable(opts, force, env)) {
if (opts.level && info instanceof Array && info.length === 2) {
console.log('%c%s%o', getStyle(opts.color), `${info[0]} `, info[1])
} else if (typeof info !== 'object' && typeof info !== 'function') {
console.log('%c' + info, getStyle(opts.color))
} else {
console.log('%c%s%o', getStyle(opts.color), `${opts.level || 'log'} `, info)
}
}
}
logger.info = (info, extra) => {
if (extra) info = [info, extra]
logger(info, levelNum >= 3, { color: theme.info, level: 'info' })
}
logger.warn = (info, extra) => {
if (extra) info = [info, extra]
logger(info, levelNum >= 2, { color: theme.warn, level: 'warn' })
}
logger.error = (info, extra) => {
if (extra) info = [info, extra]
logger(info, levelNum >= 1, { color: theme.error, level: 'error' })
}
logger.setLevel = setLevel
logger.toString = logger.valueOf = fstr('logger')
setLevel(level)
return logger
} | javascript | {
"resource": ""
} |
q33208 | train | function(err){
if(!err){
var address = app[serverNS].address();
if(config.port){
app.info('Server online at %s:%s', address.address, address.port);
}else if(config.file){
app.info('Server online via %s', config.file);
}else{
app.info('Server online!');
}
}
app.emit('app.register', 'express');
return callback(err);
} | javascript | {
"resource": ""
} | |
q33209 | ctzNumber | train | function ctzNumber(x) {
var l = ctz(db.lo(x))
if(l < 32) {
return l
}
var h = ctz(db.hi(x))
if(h > 20) {
return 52
}
return h + 32
} | javascript | {
"resource": ""
} |
q33210 | Strategy | train | function Strategy(options, verify) {
options = options || {};
options.requestTokenURL = options.requestTokenURL || 'https://api.familysearch.org/identity/v2/request_token';
options.accessTokenURL = options.accessTokenURL || 'https://api.familysearch.org/identity/v2/access_token';
options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.familysearch.org/identity/v2/authorize';
options.signatureMethod = options.signatureMethod || 'PLAINTEXT';
options.sessionKey = options.sessionKey || 'oauth:familysearch';
OAuthStrategy.call(this, options, verify);
this.name = 'familysearch';
this._userProfileURL = options.userProfileURL || 'https://api.familysearch.org/identity/v2/user';
// FamilySearch's OAuth implementation does not conform to the specification.
// As a workaround, the underlying node-oauth functions are replaced in order
// to deal with the idiosyncrasies.
this._oauth._buildAuthorizationHeaders = function(orderedParameters) {
var authHeader="OAuth ";
if( this._isEcho ) {
authHeader += 'realm="' + this._realm + '",';
}
for( var i= 0 ; i < orderedParameters.length; i++) {
// Whilst the all the parameters should be included within the signature, only the oauth_ arguments
// should appear within the authorization header.
if( this._isParameterNameAnOAuthParameter(orderedParameters[i][0]) ) {
if (orderedParameters[i][0] === 'oauth_signature') {
// JDH: This is a workaround for FamilySearch's non-conformant OAuth
// implementation, which expects the `oauth_signature` value to
// be unencoded
authHeader+= "" + this._encodeData(orderedParameters[i][0])+"=\""+ orderedParameters[i][1]+"\",";
} else {
authHeader+= "" + this._encodeData(orderedParameters[i][0])+"=\""+ this._encodeData(orderedParameters[i][1])+"\",";
}
}
}
authHeader= authHeader.substring(0, authHeader.length-1);
return authHeader;
}
this._oauth._isParameterNameAnOAuthParameter= function(parameter) {
// JDH: This is a workaround to force the `oauth_callback` parameter out of
// the Authorization header and into the request body, where
// FamilySearch expects to find it.
if (parameter === 'oauth_callback') { return false; }
var m = parameter.match('^oauth_');
if( m && ( m[0] === "oauth_" ) ) {
return true;
}
else {
return false;
}
};
} | javascript | {
"resource": ""
} |
q33211 | injectorInjectInvokers | train | function injectorInjectInvokers(injector) {
var invoke_ = injector.invoke;
injector.instantiate = instantiate;
injector.invoke = invoke;
return injector;
// pasted method that picks up patched 'invoke'
function instantiate(Type, locals, serviceName) {
var instance = Object.create((Array.isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
var returnedValue = invoke(Type, instance, locals, serviceName);
return (returnedValue !== null && typeof returnedValue === 'object') || (typeof returnedValue === 'function') ? returnedValue : instance;
}
function invoke() {
var argsLength = arguments.length;
var args = new Array(argsLength);
for (var i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
var nativeClassRegex = /^class/;
var classRegex = /class/i;
var invokeResult;
var fn = args[0];
var skipClassify = !angular.isFunction(fn) || fn.hasOwnProperty('$$classified');
if (!skipClassify) {
if (fn.$classify || nativeClassRegex.test(fn.toString())) {
classifyInvokee(args);
} else if (this.$classify || (this.$classify !== false && classRegex.test(fn.toString()))) {
try {
invokeResult = apply(injector, invoke_, args);
fn.$$classified = false;
} catch (e) {
if (e instanceof TypeError && classRegex.test(e.message)) {
classifyInvokee(args);
} else {
throw e;
}
}
}
}
return invokeResult || apply(injector, invoke_, args);
}
function classifyInvokee(args) {
var fn_ = args[0];
var fn = args[0] = function () {
var fnArgsLength = arguments.length + 1;
var fnArgs = new Array(fnArgsLength);
for (var i = 1; i < fnArgsLength; i++) {
fnArgs[i] = arguments[i - 1];
}
// fnArgs[0] === undefined
return new (apply(fn_, Function.prototype.bind, fnArgs));
};
injector.annotate(fn_);
fn.$inject = fn_.$inject;
fn.$$classified = true;
}
} | javascript | {
"resource": ""
} |
q33212 | _addReadCallback | train | function _addReadCallback(filename) {
return new Promise((resolve, reject)=> {
readFileCallbacks.get(filename).add((err, data)=> {
if (err) return reject(err);
return resolve(data);
});
});
} | javascript | {
"resource": ""
} |
q33213 | _addReadCallbacks | train | function _addReadCallbacks(filename, cache) {
const callbacks = new Set();
cache.set(filename, true);
readFileCallbacks.set(filename, callbacks);
return callbacks;
} | javascript | {
"resource": ""
} |
q33214 | _fireReadFileCallbacks | train | function _fireReadFileCallbacks(filename, data, error=false) {
const callbacks = readFileCallbacks.get(filename);
if (callbacks) {
if (callbacks.size) callbacks.forEach(callback=>error?callback(data, null):callback(null, data));
callbacks.clear();
readFileCallbacks.delete(filename);
}
} | javascript | {
"resource": ""
} |
q33215 | _runFileQueue | train | function _runFileQueue() {
if (!settings) settings = require('./settings');
const simultaneous = settings.get('load-simultaneously') || 10;
if ((loading < simultaneous) && (fileQueue.length)) {
loading++;
fileQueue.shift()();
}
} | javascript | {
"resource": ""
} |
q33216 | _readFileOnEnd | train | function _readFileOnEnd(filename, contents, cache) {
loading--;
const data = Buffer.concat(contents);
cache.set(filename, data);
_fireReadFileCallbacks(filename, data);
_runFileQueue();
} | javascript | {
"resource": ""
} |
q33217 | readFile | train | function readFile(filename, cache, encoding=null) {
if (cache.has(filename)) return _handleFileInCache(filename, cache);
_addReadCallbacks(filename, cache);
fileQueue.push(()=>{
const contents = [];
fs.createReadStream(filename, {encoding})
.on('data', chunk=>contents.push(chunk))
.on('end', ()=>_readFileOnEnd(filename, contents, cache))
.on('error', error=>_readFileOnError(filename, error))
});
_runFileQueue();
return _handleFileInCache(filename, cache);
} | javascript | {
"resource": ""
} |
q33218 | readFileSync | train | function readFileSync(filename, cache, encoding=null) {
if (cache.has(filename) && (cache.get(filename) !== true)) return cache.get(filename);
const data = fs.readFileSync(filename, encoding);
cache.set(filename, data);
return data;
} | javascript | {
"resource": ""
} |
q33219 | train | function (input) {
debug('booleanFilter(%s)', input);
if (_.isBoolean(input)) return input;
if (_.isString(input)) {
var lc = input.toLocaleLowerCase();
var pos = ['false', 'true'].indexOf(lc);
if (pos > -1) return (pos > 0);
}
return undefined;
} | javascript | {
"resource": ""
} | |
q33220 | train | function (input) {
debug('booleanTextFilter(%s)', input);
var retv = module.exports.booleanFilter(input);
return (retv === undefined
? undefined
: (retv === false
? 'false'
: 'true'));
} | javascript | {
"resource": ""
} | |
q33221 | train | function (input, list) {
debug('chooseOneFilter(%s, %s)', input, JSON.stringify(list));
if (input === true) return undefined;
if (_.isString(input)) {
if (_.isEmpty(input)) return undefined;
var ilc = input.toLocaleLowerCase();
for (var idx = 0; idx < list.length; idx++) {
var item = list[idx];
if (item.toLocaleLowerCase() === ilc) return item;
}
}
return undefined;
} | javascript | {
"resource": ""
} | |
q33222 | train | function (input, list) {
debug('chooseOneStartsWithFilter(%s, %s)', input, JSON.stringify(list));
if (input === true) return undefined;
var retv;
if (_.isString(input)) {
if (input === '') return undefined;
var ilc = input.toLocaleLowerCase();
_.forEach(list, function (item) {
var it = item.toLocaleLowerCase();
if (_.startsWith(it, ilc)) retv = retv || item;
if (it === ilc) retv = item;
});
}
return retv;
} | javascript | {
"resource": ""
} | |
q33223 | train | function (input, map) {
// TODO(bwavell): write tests
debug('chooseOneMapStartsWithFilter(%s, %s)', input, JSON.stringify(map));
if (input === true) return undefined;
var retv;
if (_.isString(input)) {
if (input === '') return undefined;
var ilc = input.toLocaleLowerCase();
_.forOwn(map, function (value, key) {
var kit = key.toLocaleLowerCase();
var vit = value.toLocaleLowerCase();
if (_.startsWith(kit, ilc)) retv = retv || value;
if (kit === ilc) retv = value;
if (vit === ilc) retv = value;
});
}
return retv;
} | javascript | {
"resource": ""
} | |
q33224 | train | function (input) {
debug('optionalTextFilter(%s)', input);
if (_.isString(input)) return input;
if (_.isBoolean(input)) return (input ? '' : undefined);
if (_.isNumber(input)) return '' + input;
return undefined;
} | javascript | {
"resource": ""
} | |
q33225 | train | function (input) {
debug('requiredTextFilter(%s)', input);
if (_.isString(input) && !_.isEmpty(input)) return input;
if (_.isNumber(input)) return '' + input;
return undefined;
} | javascript | {
"resource": ""
} | |
q33226 | train | function (input, sep, choices) {
debug('requiredTextListFilter(%s, %s, %s)', input, sep, (choices ? JSON.stringify(choices) : 'undefined'));
// if we already have a list, just return it. We may
// want to add validation that the items are in the
// choices list
if (_.isArray(input) && input.length > 0) return input;
if (!_.isString(input)) return undefined;
var retv = input.split(new RegExp('s*\\' + sep + '\\s*'));
// remove any empty input items
retv = retv.filter(function (r) {
return (!_.isEmpty(r));
});
// If a choice list is provided we will return only items
// that match the choice in a case insensitive way, using
// whatever case is provided in the choice list.
if (choices !== undefined) {
var lcretv = retv.map(function (lc) {
return lc.toLocaleLowerCase();
});
retv = choices.filter(function (c) {
return (lcretv.indexOf(c.toLocaleLowerCase()) > -1);
});
}
if (_.isEmpty(retv)) return undefined;
return retv;
} | javascript | {
"resource": ""
} | |
q33227 | train | function (input, sep, choices) {
debug('requiredTextStartsWithListFilter(%s, %s, %s)', input, sep, (choices ? JSON.stringify(choices) : 'undefined'));
// if we already have a list, just return it. We may
// want to add validation that the items are in the
// choices list
if (_.isArray(input) && input.length > 0) return input;
if (choices === undefined) return undefined;
if (!_.isString(input)) return undefined;
var inputs = input.split(new RegExp('s*\\' + sep + '\\s*'));
// remove any empty input items
inputs = inputs.filter(function (i) {
return (!_.isEmpty(i));
});
var lcis = inputs.map(function (i) {
return i.toLocaleLowerCase();
});
var retv = choices.filter(function (c) {
var lc = c.toLocaleLowerCase();
return (_.find(lcis, function (li) {
return (_.startsWith(lc, li));
}) !== undefined);
});
if (_.isEmpty(retv)) return undefined;
return retv;
} | javascript | {
"resource": ""
} | |
q33228 | train | function (input) {
debug('requiredTextFilter(%s)', input);
if (_.isString(input) && !_.isEmpty(input)) {
if (_.startsWith(input, 'VERSION-')) {
return input.substr(8);
}
return input;
}
if (_.isNumber(input)) return '' + input;
return undefined;
} | javascript | {
"resource": ""
} | |
q33229 | train | function (filterArray) {
return function (input) {
return filterArray.reduce(function (previousValue, filter) {
return filter.call(this, previousValue);
}.bind(this), input);
};
} | javascript | {
"resource": ""
} | |
q33230 | filterFiles | train | function filterFiles(files, recursive) {
var fileOrDir = function fileOrDir(lstat) {
return lstat.isFile() || lstat.isDirectory();
};
return files.filter(function (_ref) {
var lstat = _ref.lstat;
return recursive ? fileOrDir(lstat) : lstat.isFile();
});
} | javascript | {
"resource": ""
} |
q33231 | extractFolders | train | function extractFolders( files ) {
return files.data.files.map( function extractPath( file ) {
return path.parse( file ).dir;
}).filter( function extractUnique( path, index, array ) {
return array.indexOf( path ) === index;
});
} | javascript | {
"resource": ""
} |
q33232 | createFixtures | train | function createFixtures( path ) {
return parseKSS( path )
.then( extractFixturesData )
.then( function( data ) {
return saveFixture( data[0].name, data, path );
})
} | javascript | {
"resource": ""
} |
q33233 | extractFixturesData | train | function extractFixturesData( data ) {
return Promise.map( data.section(), function( section ) {
var markup = section.markup();
var ext = path.extname( markup );
var testDir = data.data.files[0].split("/")
.filter(function(dir, i) {
return i <= 2;
})
.concat([path.dirname( markup ), (path.basename( markup, ext ) + ext) ])
.join('/');
return Promise.props({
header : section.header(),
description : section.description(),
markup : fs.readFileAsync( testDir, 'utf8' ).then( mustache.render ),
name : path.basename( section.markup(), path.extname( section.markup() ) )
});
});
} | javascript | {
"resource": ""
} |
q33234 | saveFixture | train | function saveFixture( name, data, directory ) {
return fs.readFileAsync( template, 'utf8' )
.then( function renderTemplate( template ) {
return mustache.render( template, { stylesheets: stylesheets, sections: data } );
}).then( function saveTemplate( templateData ) {
return fs.outputFileAsync( destination + '/' + name + '.html', templateData );
});
} | javascript | {
"resource": ""
} |
q33235 | root | train | function root(node, options = {}) {
const {
fragment,
namespace: optionsNamespace,
} = options;
const { children = [] } = node;
const { length: childrenLength } = children;
let namespace = optionsNamespace;
let rootIsDocument = childrenLength === 0;
for (let i = 0; i < childrenLength; i += 1) {
const {
tagName,
properties: {
xmlns,
} = {},
} = children[i];
if (tagName === 'html') {
// If we have a root HTML node, we don't need to render as a fragment
rootIsDocument = true;
// Take namespace of first child
if (typeof optionsNamespace === 'undefined') {
if (xmlns) {
namespace = xmlns;
} else if (children[0].tagName === 'html') {
namespace = 'http://www.w3.org/1999/xhtml';
}
}
}
}
// The root node will be a Document, DocumentFragment, or HTMLElement
let el;
if (rootIsDocument) {
el = document.implementation.createDocument(namespace, '', null);
} else if (fragment) {
el = document.createDocumentFragment();
} else {
el = document.createElement('html');
}
// Transform children
const childOptions = Object.assign({ fragment, namespace }, options);
for (let i = 0; i < childrenLength; i += 1) {
const childEl = transform(children[i], childOptions);
if (childEl) {
el.appendChild(childEl);
}
}
return el;
} | javascript | {
"resource": ""
} |
q33236 | doctype | train | function doctype(node) {
return document.implementation.createDocumentType(
node.name || 'html',
node.public || '',
node.system || '',
);
} | javascript | {
"resource": ""
} |
q33237 | element | train | function element(node, options = {}) {
const { namespace } = options;
const { tagName, properties, children = [] } = node;
const el = typeof namespace !== 'undefined'
? document.createElementNS(namespace, tagName)
: document.createElement(tagName);
// Add HTML attributes
const props = Object.keys(properties);
const { length } = props;
for (let i = 0; i < length; i += 1) {
const key = props[i];
const {
attribute,
property,
mustUseAttribute,
mustUseProperty,
boolean,
booleanish,
overloadedBoolean,
// number,
// defined,
commaSeparated,
spaceSeparated,
// commaOrSpaceSeparated,
} = info.find(info.html, key) || {
attribute: key,
property: key,
};
let value = properties[key];
if (Array.isArray(value)) {
if (commaSeparated) {
value = value.join(', ');
} else if (spaceSeparated) {
value = value.join(' ');
} else {
value = value.join(' ');
}
}
try {
if (mustUseProperty) {
el[property] = value;
}
if (boolean || (overloadedBoolean && typeof value === 'boolean')) {
if (value) {
el.setAttribute(attribute, '');
} else {
el.removeAttribute(attribute);
}
} else if (booleanish) {
el.setAttribute(attribute, value);
} else if (value === true) {
el.setAttribute(attribute, '');
} else if (value || value === 0 || value === '') {
el.setAttribute(attribute, value);
}
} catch (e) {
if (!mustUseAttribute && property) {
el[property] = value;
}
// Otherwise silently ignore
}
}
// Transform children
const { length: childrenLength } = children;
for (let i = 0; i < childrenLength; i += 1) {
const childEl = transform(children[i], options);
if (childEl) {
el.appendChild(childEl);
}
}
return el;
} | javascript | {
"resource": ""
} |
q33238 | processCommand | train | function processCommand (cmd, options) {
var module = checkForModule(cmd);
// execute module if exists
if (module) {
return executeModule(module, options);
} else {
processInstallCommands(['install', cmd], options, function (err) {
if (err) {
noModuleFound(cmd);
}
module = checkForModule(cmd);
// execute module if exists now
if (module) {
executeModule(module, options);
}
});
}
} | javascript | {
"resource": ""
} |
q33239 | Phaser | train | function Phaser(element) {
check(element, 'element').is.anInstanceOf(Element)();
var priv = {};
priv.elem = element;
priv.phase = null;
priv.listeners = [];
priv.phaseTriggers = new MultiMap();
priv.started = false;
var pub = {};
var methods = [
getPhase,
nextPhase,
addPhaseListener,
removePhaseListener,
addPhaseTrigger,
removePhaseTrigger,
startTransition,
];
// This trick binds all methods to the public object
// passing `priv` as the first argument to each call.
methods.forEach(function(method) {
pub[method.name] = method.bind(pub, priv);
});
return pub;
} | javascript | {
"resource": ""
} |
q33240 | nextPhase | train | function nextPhase(priv) {
setPhase(priv, PHASE_VALUES[(PHASE_VALUES.indexOf(priv.phase) + 1) % PHASE_VALUES.length]);
} | javascript | {
"resource": ""
} |
q33241 | setPhase | train | function setPhase(priv, phase) {
check(phase, 'phase').is.oneOf(PHASE_VALUES)();
if (priv.phase !== null) {
priv.elem.classList.remove(priv.phase);
}
priv.phase = phase;
if (phase !== null) {
priv.elem.classList.add(phase);
}
priv.listeners.forEach(function(listener) {
listener(phase);
});
maybeStart(priv);
} | javascript | {
"resource": ""
} |
q33242 | addPhaseTrigger | train | function addPhaseTrigger(priv, target, propertyName) {
check(target, 'target').is.anEventTarget();
var property = propertyName || 'transform';
check(property, 'property').is.aString();
if (property === 'transform') {
property = feature.transformPropertyName;
}
priv.phaseTriggers.put(property, target);
maybeStart(priv);
} | javascript | {
"resource": ""
} |
q33243 | addPhaseListener | train | function addPhaseListener(priv, listener) {
priv.listeners.push(check(listener, 'listener').is.aFunction());
} | javascript | {
"resource": ""
} |
q33244 | removePhaseTrigger | train | function removePhaseTrigger(priv, target, propertyName) {
var property = propertyName || 'transform';
check(property, 'property').is.aString();
var triggerElements = priv.phaseTriggers.get(property);
check(target, 'target').is.instanceOf(EventTarget).and.is.oneOf(triggerElements, 'phase triggers')();
triggerElements.splice(triggerElements.indexOf(target), 1);
} | javascript | {
"resource": ""
} |
q33245 | removePhaseListener | train | function removePhaseListener(priv, listener) {
check(listener, 'listener').is.aFunction.and.is.oneOf(priv.listeners, 'registered listeners')();
priv.listeners.splice(priv.listeners.indexOf(listener), 1);
} | javascript | {
"resource": ""
} |
q33246 | maybeStart | train | function maybeStart(priv) {
if (priv.started) {
return;
}
priv.elem.addEventListener(feature.transitionEventName, handleTransitionEnd.bind(null, priv));
priv.started = true;
} | javascript | {
"resource": ""
} |
q33247 | handleTransitionEnd | train | function handleTransitionEnd(priv, evt) {
if (evt.propertyName in priv.phaseTriggers &&
priv.phaseTriggers[evt.propertyName].indexOf(evt.target) !== -1) {
nextPhase(priv);
}
} | javascript | {
"resource": ""
} |
q33248 | logChild | train | function logChild(child, slogan, write) {
if (child) {
logSocket(child.stdout, slogan, write)
logSocket(child.stderr, slogan, write)
}
} | javascript | {
"resource": ""
} |
q33249 | parseJsDoc | train | function parseJsDoc(filePath, jsdoc) {
return jsdoc.explain({files:[filePath]}).then(items=>{
const data = {};
items.forEach(item=>{
if (!item.undocumented && !data.hasOwnProperty(item.longname)) {
data[item.longname] = {
name: item.name,
description: item.classdesc || item.description
};
}
});
return data;
});
} | javascript | {
"resource": ""
} |
q33250 | build | train | function build (data, cache, scope) {
scope = scope || { var: '' }
return data
.map(function (item) {
return typeof item === 'string'
? item
: Buffer.isBuffer(item)
? item.toString()
: item.run(cache, scope)
})
.join('')
} | javascript | {
"resource": ""
} |
q33251 | train | function (err) {
if (err) {
reject(err);
} else if (arguments.length === 2) { // single param?
resolve(arguments[1]);
} else { // multiple params?
var cbArgsArray = self.toArgsArray(arguments);
resolve(cbArgsArray.slice(1)); // remove err arg
}
} | javascript | {
"resource": ""
} | |
q33252 | history | train | function history(params, cb) {
params.resourcePath = config.addURIParams(constants.STATS_BASE_PATH + "/history", params);
params.method = 'POST';
params.data = params.data || {};
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33253 | transpose | train | function transpose (M) {
return (
[[M[0][0], M[1][0], M[2][0]],
[M[0][1], M[1][1], M[2][1]],
[M[0][2], M[1][2], M[2][2]]]
);
} | javascript | {
"resource": ""
} |
q33254 | handleChange | train | function handleChange(bundleName) {
const bundle = module.exports.find(bundleName);
/* istanbul ignore if: It's rare for `bundle` to be undefined here, but it can happen when using black/whitelisting. */
if (!bundle) {
return;
}
if (backoffTimer) {
log.debug('Backoff active, delaying processing of change detected in', bundleName);
hasChanged[bundleName] = true;
resetBackoffTimer();
} else {
log.debug('Processing change event for', bundleName);
resetBackoffTimer();
let reparsedBundle;
const bundleCfgPath = path.join(root, '/cfg/', bundleName + '.json');
if (fs.existsSync(bundleCfgPath)) {
reparsedBundle = parseBundle(bundle.dir, bundleCfgPath);
} else {
reparsedBundle = parseBundle(bundle.dir);
}
module.exports.add(reparsedBundle);
emitter.emit('bundleChanged', reparsedBundle);
}
} | javascript | {
"resource": ""
} |
q33255 | extractBundleName | train | function extractBundleName(filePath) {
const parts = filePath.replace(bundlesPath, '').split(path.sep);
return parts[1];
} | javascript | {
"resource": ""
} |
q33256 | handleMismatch | train | function handleMismatch(results, config) {
if (results.length) {
var message = 'Out of date packages: \n' + results.map(function (p) {
return moduleInfo(p);
}).join('\n');
if (config.throw === undefined || config.throw !== undefined && config.throw) {
throw new _gulpUtil.PluginError('gulp-npm-check', {
name: 'NpmCheckError',
message: message
});
} else {
(0, _gulpUtil.log)(_gulpUtil.colors.yellow('gulp-npm-check\n', message));
}
} else {
(0, _gulpUtil.log)('All packages are up to date :)');
}
} | javascript | {
"resource": ""
} |
q33257 | format | train | function format(str, formats) {
let cachedFormats = formats;
if (!Ember.isArray(cachedFormats) || arguments.length > 2) {
cachedFormats = new Array(arguments.length - 1);
for (let i = 1, l = arguments.length; i < l; i++) {
cachedFormats[i - 1] = arguments[i];
}
}
let idx = 0;
return str.replace(/%@([0-9]+)?/g, function(s, argIndex) {
argIndex = (argIndex) ? parseInt(argIndex, 10) - 1 : idx++;
s = cachedFormats[argIndex];
return (s === null) ? '(null)' : (s === undefined) ? '' : Ember.inspect(s);
});
} | javascript | {
"resource": ""
} |
q33258 | train | function() {
const message = this.get('message');
const label = this.get('attributeLabel');
Ember.assert('Message must be defined for this Validator', Ember.isPresent(message));
const args = Array.prototype.slice.call(arguments);
args.unshift(label);
args.unshift(message);
return format.apply(null, args);
} | javascript | {
"resource": ""
} | |
q33259 | unique | train | function unique( target, arrays )
{
target = target || [];
var combined = target.concat( arrays );
target = [];
var len = combined.length,
i = -1,
ObjRef;
while(++i < len) {
ObjRef = combined[ i ];
if( target.indexOf( ObjRef ) === -1 && ObjRef !== '' & ObjRef !== (null || undefined) ) {
target[ target.length ] = ObjRef;
}
}
return target;
} | javascript | {
"resource": ""
} |
q33260 | html | train | function html(options) {
return Object.assign(function (context) {
var defaultOpts = {
filename: 'index.html',
template: 'templates/index.html',
showErrors: false
};
// Merge the provided html config into the context
var html = context.html || defaultOpts;
/* Warning: Thar be mutation ahead! */
/* eslint-disable fp/no-mutation */
context.html = (0, _deepmerge2.default)(html, options, { clone: true });
/* eslint-enable fp/no-mutation */
// Return empty config snippet (configuration will be created by the post hook)
return {};
}, { post: postConfig });
} | javascript | {
"resource": ""
} |
q33261 | ZNV2Swarm | train | function ZNV2Swarm (opt, protocol, zeronet, lp2p) {
const self = this
self.proto = self.protocol = new ZProtocol({
crypto: opt.crypto,
id: opt.id
}, zeronet)
log('creating zeronet swarm')
const tr = self.transport = {}
self.multiaddrs = (opt.listen || []).map(m => multiaddr(m));
(opt.transports || []).forEach(transport => {
tr[transport.tag || transport.constructor.name] = transport
if (!transport.listeners) {
transport.listeners = []
}
})
TRANSPORT(self)
DIAL(self, lp2p)
self.advertise = {
ip: null,
port: null,
port_open: null
}
let nat
if (opt.nat) nat = self.nat = new NAT(self, opt)
self.start = cb => series([
self.listen,
nat ? nat.doDefault : cb => cb()
], cb)
self.stop = cb => series([
self.unlisten
], cb)
} | javascript | {
"resource": ""
} |
q33262 | init | train | function init(cb) { // {{{2
if (typeof cb !== 'function') {
throw O.log.error(this, 'Callback must be a function', cb);
}
this.stream = new Readable();
this.stream._read = O._.noop;
this.stream.on('error', onError.bind(this));
cb(null, this.stream);
} | javascript | {
"resource": ""
} |
q33263 | Watcher | train | function Watcher(path, handler) {
this._ = Fs.watch(path, handler);
this.a_path = Abs(path);
this.handler = handler;
} | javascript | {
"resource": ""
} |
q33264 | FileWatcher | train | function FileWatcher(path, options, callback) {
if (typeof options === "function") {
callback = options;
}
if (typeof options === "boolean") {
options = { once: options };
}
options = Ul.merge(options, {
once: false
});
var watcher = null
, newWatcher = false
, check = function (cb) {
var inter = setInterval(function() {
IsThere(path, function (exists) {
if (!--tries || exists) {
clearInterval(inter);
}
if (exists) {
cb();
}
});
}, 500)
, tries = 5
;
}
, handler = function (ev) {
if (options.once) {
watcher.off();
}
if (newWatcher) { return; }
// Check the rename
if (ev === "rename" && !options.once) {
newWatcher = true;
check(function () {
watcher.off();
watcher._ = FileWatcher(path, options, callback)._;
});
}
callback.call(watcher, null, ev, watcher.a_path);
}
;
try {
watcher = new Watcher(path, handler);
} catch (e) {
callback(e);
}
return watcher;
} | javascript | {
"resource": ""
} |
q33265 | disasm1 | train | function disasm1(machine_code, offset=0) {
let di = decode_instruction(machine_code[offset]);
let opcode, operand;
let consumed = 1; // 1-tryte opcode, incremented later if operands
if (di.family === 0) {
opcode = invertKv(OP)[di.operation]; // inefficient lookup, but probably doesn't matter
// note: some duplication with cpu read_alu_operand TODO: factor out
// TODO: handle reading beyond end
let decoded_operand = decode_operand(di, machine_code, offset);
operand = stringify_operand(decoded_operand);
consumed += decoded_operand.consumed;
} else if (di.family === 1) {
opcode = 'BR';
opcode += invertKv(FLAGS)[di.flag];
opcode += {'-1':'L', 0:'E', 1:'N'}[di.direction];
opcode += {'-1':'N', 0:'Z', 1:'P'}[di.compare];
if (invertKv(BRANCH_INSTRUCTION_SHORTHANDS)[opcode]) {
// prefer the shorthand if there is one (BRSEZ -> BEQ)
opcode = invertKv(BRANCH_INSTRUCTION_SHORTHANDS)[opcode];
}
let rel_address = machine_code[offset + 1];
if (rel_address === undefined) {
operand = '???'
} else {
if (rel_address > 0) {
// always add +, since makes relativity clearer
operand = '#+' + rel_address.toString();
} else {
operand = '#' + rel_address.toString();
}
}
consumed += 1;
} else if (di.family === -1) {
opcode = invertKv(XOP)[di.operation];
// TODO: undefined opcodes
let decoded_operand = decode_operand(di, machine_code, offset);
operand = stringify_operand(decoded_operand);
consumed += decoded_operand.consumed;
console.log('XOP di.operation',di.operation,XOP_TO_ADDR_MODE[di.operation]);
if (XOP_TO_ADDR_MODE[opcode] !== undefined) {
// some extended opcodes can disassemble to alu special addressing modes
opcode = xop_operation_to_assembly_opcode_string(opcode);
}
}
let asm;
if (operand !== undefined) {
asm = opcode + ' ' + operand;
} else {
asm = opcode;
}
return {asm, consumed};
} | javascript | {
"resource": ""
} |
q33266 | train | function(files, next) {
var i = files.indexOf(id);
if (i < 0) {
return next({
error: 'NOT_FOUND',
description: 'Asset not available: ' + searchDir + id
});
}
next(null, files[i]);
} | javascript | {
"resource": ""
} | |
q33267 | train | function(dirname, next) {
// could be something
searchDir += dirname + '/';
var revPath = version && (searchDir + version + '.js');
return next(null, revPath || '');
} | javascript | {
"resource": ""
} | |
q33268 | train | function(filename, msg, $done) {
var __open = _.bind(fs.open, fs, filename, 'a')
, __write = util.partial.call(fs, fs.write, undefined, msg)
, __close = util.partial.call(fs, fs.close)
async.waterfall([__open, __write, __close], $done)
} | javascript | {
"resource": ""
} | |
q33269 | train | function (opts) {
var options = extend(true, defaults, opts);
requireDir(process.cwd() + options.path, {recurse: options.recurse});
} | javascript | {
"resource": ""
} | |
q33270 | train | function (type, tasks, folder) {
if ( !type ) {
throw Error('Error registering task: Please specify a task type');
}
if ( !tasks ) {
throw Error('Error registering task: Please specify at least one task.');
}
allTasks[type] = allTasks[type] || {tasks: [], requireFolders: !!folder};
if ( !folder && allTasks[type].requireFolders) {
throw Error('Error registering watch type task: Please specify (a) folder(s) to watch.');
}
if ( !!folder ) { // Folder specified, tasks is a watch task
// Convert argument to array if it's no array yet
if ( !(tasks.constructor === Array) ) {
tasks = [tasks];
}
allTasks[type].tasks = allTasks[type].tasks.concat({
tasks: tasks,
folders: folder
});
} else { // Regular tasks
allTasks[type].tasks = allTasks[type].tasks.concat(tasks);
}
} | javascript | {
"resource": ""
} | |
q33271 | mergeMessages | train | async function mergeMessages(locale, messages) {
const data_path = path.join(LOCALE_DATA_DIR, `${locale}/api_messages.json`);
let old_messages = {};
try {
old_messages = require(data_path);
} catch (err) {
console.log(`creating new messages for locale ${locale}`);
}
const merged_messages = { ...old_messages, ...messages };
const sorted_messages = Object.entries(merged_messages)
.sort((a, b) => a[0].localeCompare(b[0]))
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
const json = JSON.stringify(sorted_messages, undefined, 2);
await writeFile(data_path, json);
} | javascript | {
"resource": ""
} |
q33272 | consumeForward | train | function consumeForward(stream) {
const start = stream.pos;
if (stream.eat(DOT) && stream.eatWhile(isNumber)) {
// short decimal notation: .025
return true;
}
if (stream.eatWhile(isNumber) && (!stream.eat(DOT) || stream.eatWhile(isNumber))) {
// either integer or decimal: 10, 10.25
return true;
}
stream.pos = start;
return false;
} | javascript | {
"resource": ""
} |
q33273 | consumeBackward | train | function consumeBackward(stream) {
const start = stream.pos;
let ch, hadDot = false, hadNumber = false;
// NB a StreamReader insance can be editor-specific and contain objects
// as a position marker. Since we don’t know for sure how to compare editor
// position markers, use consumed length instead to detect if number was consumed
let len = 0;
while (!isSoF(stream)) {
stream.backUp(1);
ch = stream.peek();
if (ch === DOT && !hadDot && hadNumber) {
hadDot = true;
} else if (!isNumber(ch)) {
stream.next();
break;
}
hadNumber = true;
len++;
}
if (len) {
const pos = stream.pos;
stream.start = pos;
stream.pos = start;
return true;
}
stream.pos = start;
return false;
} | javascript | {
"resource": ""
} |
q33274 | MarantzDenonUPnPDiscovery | train | function MarantzDenonUPnPDiscovery(callback) {
var that = this;
var foundDevices = {}; // only report a device once
// create socket
var socket = dgram.createSocket({type: 'udp4', reuseAddr: true});
socket.unref();
const search = new Buffer([
'M-SEARCH * HTTP/1.1',
'HOST: 239.255.255.250:1900',
'ST: upnp:rootdevice',
'MAN: "ssdp:discover"',
'MX: 3',
'',
''
].join('\r\n'));
socket.on('error', function(err) {
console.log(`server error:\n${err.stack}`);
socket.close();
});
socket.on('message', function(message, rinfo) {
var messageString = message.toString();
console.log(messageString);
if (messageString.match(/(d|D)enon/)) {
location = messageString.match(/LOCATION: (.*?)(\d+\.\d+\.\d+\.\d+)(.*)/);
if (location) {
arp.getMAC(location[2], function(err, mac) { // lookup ip on the arp table to get the MacAddress
if (!err) {
if (foundDevices[mac]) { // only report foind devices once
return;
}
var device = {
friendlyName: '',
ip: location[2],
location: (location[1] + location[2] + location[3]).trim(),
mac: mac,
manufacturer: 'Unknown Manufacturer',
model: 'Unknown Model'
};
foundDevices[mac] = device;
that.getUPnPInfo(device, function() {
if (device.manufacturer == 'Unknown Manufacturer') { // still no info?
that.getDeviceInfo(device, function() {callback(null, device);}, 80);
} else {
callback(null, device);
}
});
}
});
}
}
});
socket.on('listening', function() {
socket.addMembership('239.255.255.250');
socket.setMulticastTTL(4);
const address = socket.address();
console.log(`server listening ${address.address}:${address.port}`);
socket.send(search, 0, search.length, 1900, '239.255.255.250');
setTimeout(function() {socket.close();}, 5000);
});
socket.bind(0);
} | javascript | {
"resource": ""
} |
q33275 | train | function(options) {
options = options || {};
this.host = options.host || 'localhost';
this.port = options.port || 8125;
if (!statsdClients[this.host + ':' + this.port]) {
statsdClients[this.host + ':' + this.port] = new StatsD(options);
}
this.client = statsdClients[this.host + ':' + this.port];
this.sampleRate = options.sampleRate || 1;
Writable.call(this, {objectMode: true});
} | javascript | {
"resource": ""
} | |
q33276 | add | train | function add(a, b, carryIn=0) {
let result = a + b + carryIn;
let fullResult = result;
let carryOut = 0;
// carryOut is 6th trit, truncate result to 5 trits
if (result > MAX_TRYTE) {
carryOut = 1;
result -= MAX_TRYTE * 2 + 1;
} else if (result < MIN_TRYTE) {
carryOut = -1; // underflow
result += MAX_TRYTE * 2 + 1;
}
// overflow is set if sign is incorrect
let overflow;
if (Math.sign(fullResult) === Math.sign(result)) {
overflow = 0;
} else {
overflow = Math.sign(fullResult) || Math.sign(result);
}
// note: for 5-trit + 5-trit + 1-trit will always V = C, but the logic above is generic
if (overflow !== carryOut) throw new Error(`unexpected overflow calculation: ${overflow} !== ${carryOut}`);
return {result, carryOut, fullResult, overflow};
} | javascript | {
"resource": ""
} |
q33277 | html | train | function html(markup, outer) {
if(!this.length) {
return this;
}
if(typeof markup === 'boolean') {
outer = markup;
markup = undefined;
}
var prop = outer ? 'outerHTML' : 'innerHTML';
if(markup === undefined) {
return this.dom[0][prop];
}
markup = markup || '';
this.each(function(el) {
el[prop] = markup;
});
// TODO: should we remove matched elements when setting outerHTML?
// TODO: the matched elements have been rewritten and do not exist
// TODO: in the DOM anymore: ie: this.dom = [];
return this;
} | javascript | {
"resource": ""
} |
q33278 | createEvent | train | function createEvent(params, cb) {
params.resourcePath = config.addURIParams(constants.EVENTS_BASE_PATH, params);
params.method = 'POST';
params.data = params.data || {};
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33279 | augment | train | function augment(el) {
// FIXME should always have a type
el.type = el.type || 'category';
el.icon = (typesIcons[el.type] || typesIcons.default).icon;
el.data = { value: el.text, type: el.type };
// branch
if (el.children && el.children.length > 0) {
el.state = { opened: el.children.length > 50 ? false : true };
el.children.forEach(function(c) {
c = augment(c);
});
el.text = el.text + ' [' + el.children.length + ']';
// value or category
} else if (el.size && el.size > 0) {
if (curAnnos.indexOf(el.text) > -1) {
el.state = { selected: true };
}
el.text = el.text + ' (' + el.size + ')';
}
return el;
} | javascript | {
"resource": ""
} |
q33280 | _tokenize | train | function _tokenize( prop ) {
var tokens = [],
patterns,
src = prop.source;
src = typeof src !== 'string' ? src : src.split(' ');
patterns = {
operator: /^[+\-\*\/\%]$/, // +-*/%
// @TODO Improve this regex to cover numbers like 1,000,000
number: /^\$?\d+[\.,]?\d+$/
};
function _pushToken( val, type ) {
var token = {
value: val,
type: type
};
tokens.push( token );
}
// Return early if it's a function.
if ( typeof src === 'function' ) {
_pushToken( src, 'function' );
return tokens;
}
// @TODO DRY this up.
for ( var i = 0, len = src.length; i < len; i++ ) {
if ( patterns.operator.test(src[i]) ) {
_pushToken( src[i].match(patterns.operator)[0], 'operator' );
} else if ( patterns.number.test(src[i]) ) {
_pushToken( parseFloat( src[i].match(patterns.number)[0] ), 'number' );
} else {
_pushToken( src[i], 'name' );
}
}
return tokens;
} | javascript | {
"resource": ""
} |
q33281 | _getDOMElement | train | function _getDOMElement( container, str ) {
var el = container.querySelector( '[name=' + str + ']' );
return el ? el : null;
} | javascript | {
"resource": ""
} |
q33282 | _deTokenize | train | function _deTokenize( container, arr ) {
var val,
tokens = [];
function _parseFloat( str ) {
return parseFloat( unFormatUSD(str) );
}
for ( var i = 0, len = arr.length; i < len; i++ ) {
var token = arr[i];
// @TODO DRY this up.
if ( token.type === 'function' ) {
tokens.push( token.value );
} else if ( token.type === 'operator' || token.type === 'number' ) {
tokens.push( token.value );
} else {
try {
// @TODO accommodate radio and other elements that don't use .value
val = _getDOMElement( container, token.value );
// Grab the value or the placeholder or default to 0.
val = unFormatUSD( val.value || val.getAttribute('placeholder') || 0 );
// Make it a number if it's a number.
val = isNaN( val ) ? val : _parseFloat( val );
tokens.push( val );
} catch ( e ) {}
}
}
// @TODO This feels a little repetitive.
if ( typeof tokens[0] === 'function' ) {
return tokens[0]();
}
val = tokens.length > 1 ? eval( tokens.join(' ') ) : tokens.join(' ');
return isNaN( val ) ? val : _parseFloat( val );
} | javascript | {
"resource": ""
} |
q33283 | update | train | function update( container, src, dest ) {
for ( var key in src ) {
// @TODO Better handle safe defaults.
dest[ key ] = _deTokenize( container, src[key] );
}
} | javascript | {
"resource": ""
} |
q33284 | objectify | train | function objectify( id, props ) {
// Stores references to elements that will be monitored.
var objectifier = {},
// Stores final values that are sent to user.
objectified = {},
container = document.querySelector( id );
for ( var i = 0, len = props.length; i < len; i++ ) {
if ( props[i].hasOwnProperty('source') ) {
objectifier[ props[i].name ] = _tokenize( props[i] );
} else {
objectifier[ props[i].name ] = undefined;
}
}
function _update() {
update( container, objectifier, objectified );
}
setListeners( container, _update );
objectified.update = _update;
return objectified;
} | javascript | {
"resource": ""
} |
q33285 | arrayHas | train | function arrayHas(value, array) {
error_if_not_array_1.errorIfNotArray(array);
return (array.length > 0 && (array_get_indexes_1.getFirstIndexOf(value, array) > -1));
} | javascript | {
"resource": ""
} |
q33286 | local_parseInt | train | function local_parseInt(str, from, to) {
var fn = assignFn(from, to);
return convert[fn](str + '');
} | javascript | {
"resource": ""
} |
q33287 | assignFn | train | function assignFn(from, to) {
from = setDefault(10, from);
to = setDefault(10, to);
from = numToWord(from);
to = capitalize(numToWord(to));
return from + 'To' + to;
// return a copy of a string with its first letter capitalized
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
// translate a number to its correlating module-specific namespace
function numToWord(num) {
num += '';
switch(num) {
case '2':
return 'bin';
case '8':
return 'oct';
case '10':
return 'dec';
case '16':
return 'hex';
default:
throw new Error('Base "' + num + '" is not supported');
}
}
// if `arg` is not provided, return a default value
function setDefault(defaultVal, arg) {
return (typeof arg === 'undefined' ? defaultVal : arg);
}
} | javascript | {
"resource": ""
} |
q33288 | processXML | train | function processXML(name, uri, processor, resp, callback) {
var parser = new xml2js.Parser();
parser.parseString(resp, function (err, xml) {
if (err) {
GLOBAL.error(name, err);
return;
} else {
processor.getAnnotations(name, uri, xml, function(err, annoRows) {
callback(err, {name: name, uri: uri, annoRows: annoRows});
});
}
});
} | javascript | {
"resource": ""
} |
q33289 | error | train | function error(err, req, res, next) {
if (err instanceof ModelAPIError) {
toSend = extend({error: true}, err);
res.status(err.code);
res.json(toSend);
} else {
toSend = {
error: true,
message: err.message,
stack: err.stack
};
res.status(500);
res.json(toSend);
}
} | javascript | {
"resource": ""
} |
q33290 | controls | train | function controls(data, options) {
return data.reduce(function reduce(controls, item, n) {
return controls + options.fn({
panel: 'panel' + n,
checked: !n ? ' checked' : ''
});
}, '');
} | javascript | {
"resource": ""
} |
q33291 | copyAttributes | train | function copyAttributes (templateAst, componentNode, preserveType) {
for (let attributeName in componentNode.attrs) {
if (!(attributeName in skippedAttributes)) {
templateAst[0].attrs = templateAst[0].attrs || {};
if (templateAst[0].attrs[attributeName] && attributeName === 'class') {
templateAst[0].attrs[attributeName][0].content += ' ' + componentNode.attrs[attributeName][0].content;
}
else {
templateAst[0].attrs[attributeName] = componentNode.attrs[attributeName];
}
}
if (preserveType) {
const typeAttribute = preserveType === true ? 'type' : preserveType;
const typeAttributeValue = componentNode.attrs.type;
if (typeAttributeValue) {
templateAst[0].attrs = templateAst[0].attrs || {};
templateAst[0].attrs[typeAttribute] = typeAttributeValue;
}
}
}
} | javascript | {
"resource": ""
} |
q33292 | replaceTokens | train | function replaceTokens (templateAst, componentNode) {
let promise;
if (componentNode.content) {
const tokenDefinitions = {};
componentNode.content.forEach(function (tokenDefinition) {
if (tokenDefinition.name) {
let tokenValue = '';
if (tokenDefinition.content) {
if (tokenDefinition.content.length === 1 && tokenDefinition.content[0].type === 'text') {
tokenValue = tokenDefinition.content[0].content;
}
else {
tokenValue = tokenDefinition.content;
}
}
tokenDefinitions[tokenDefinition.name] = tokenValue;
}
});
promise = modifyNodes(templateAst,
function (node) {
return node.attrs || (node.type === 'text' && tokenRegExp.test(node.content));
},
function (node) {
if (node.attrs) {
/**
* Take a node and do attribute replacement, e.g.:
* <div class="card ${state}" ${required} ${autocomplete} ${unused}></div>
* From the following component:
* <component>
* <state>active</state>
* <required/>
* <autocomplete>postal-address</autocomplete>
* </component>
* Produces the output (note that ${unused} has been trimmed):
* <div class="card active" required autocomplete="postal-address"></div>
*/
Object.keys(node.attrs).forEach(function (attributeName) {
// This code gets confusing fast:
// attributeName: this is the name of the attribute in the template node
// It is a token, e.g. ${pattern} and we are going to remove it from the node
tokenRegExp.lastIndex = 0;
const match = tokenRegExp.exec(attributeName);
if (match) {
// newAttributeName: this is the inner part of 'attributeName' and is going to be the name
// of the new attribute we add to the node, e.g. 'pattern'
const newAttributeName = match[1];
const newAttributeValue = tokenDefinitions[newAttributeName] ||
node.attrs[attributeName][0].content;
if (newAttributeValue || newAttributeName in tokenDefinitions) {
node.attrs[newAttributeName] = [
{
type: 'text',
content: newAttributeValue,
// TODO: this is not accurate, but should new nodes have no location?
location: node.attrs[attributeName].location,
},
];
}
delete node.attrs[attributeName];
}
else {
tokenRegExp.lastIndex = 0;
const attributeNode = node.attrs[attributeName][0];
replaceToken(attributeNode, tokenDefinitions, true);
}
});
}
else if (node.type === 'text') {
node = replaceToken(node, tokenDefinitions);
}
return node;
}
);
}
return promise;
} | javascript | {
"resource": ""
} |
q33293 | getMyVersion | train | function getMyVersion(buildDir) {
var builds = getBuildFiles(buildDir);
var chosen = builds[0];
for (var n=0; n<builds.length; n++) {
if (semvar.satisfies(getVersion(builds[n]), '<=' + process.versions.node)) chosen = builds[n];
}
return require(buildDir + '/' + chosen);
} | javascript | {
"resource": ""
} |
q33294 | swap | train | function swap(e, to) {
if ('preventDefault' in e) e.preventDefault();
var item = $(e.element || '[data-id="' + to + '"]');
if (!!~item.get('className').indexOf('active')) return;
var parent = item.parent()
, effect = item.get('effect').split(',')
, change = item.get('swap').split('@')
, current = $(change[0])
, show = $(change[1]);
//
// Check if the effect was actually a proper list.
//
if (effect.length < 2) effect = ['fadeOut', 'fadeIn'];
current.addClass(effect[0]).removeClass(effect[1]);
parent.find('.active').removeClass('active');
item.addClass('active');
setTimeout(function () {
current.addClass('gone');
//
// Redraw elements if they were not visible.
//
if (~show.get('className').indexOf('gone')) {
show.removeClass('gone ' + effect[0]).addClass(effect[1]);
}
//
// Append hash for correct routing, will also jump to element with id=data-id
//
location.hash = item.get('data-id');
}, 500);
} | javascript | {
"resource": ""
} |
q33295 | urlencoded | train | function urlencoded (options) {
var opts = options || {}
// notice because option default will flip in next major
if (opts.extended === undefined) {
deprecate('undefined extended: provide extended option')
}
var extended = opts.extended !== false
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/x-www-form-urlencoded'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate query parser
var queryparse = extended
? extendedparser(opts)
: simpleparser(opts)
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
return body.length
? queryparse(body)
: {}
}
return function urlencodedParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset
var charset = getCharset(req) || 'utf-8'
if (charset !== 'utf-8') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
debug: debug,
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | javascript | {
"resource": ""
} |
q33296 | extendedparser | train | function extendedparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('qs')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
var arrayLimit = Math.max(100, paramCount)
debug('parse extended urlencoding')
return parse(body, {
allowPrototypes: true,
arrayLimit: arrayLimit,
depth: Infinity,
parameterLimit: parameterLimit
})
}
} | javascript | {
"resource": ""
} |
q33297 | parameterCount | train | function parameterCount (body, limit) {
var count = 0
var index = 0
while ((index = body.indexOf('&', index)) !== -1) {
count++
index++
if (count === limit) {
return undefined
}
}
return count
} | javascript | {
"resource": ""
} |
q33298 | parser | train | function parser (name) {
var mod = parsers[name]
if (mod !== undefined) {
return mod.parse
}
// this uses a switch for static require analysis
switch (name) {
case 'qs':
mod = require('qs')
break
case 'querystring':
mod = require('querystring')
break
}
// store to prevent invoking require()
parsers[name] = mod
return mod.parse
} | javascript | {
"resource": ""
} |
q33299 | simpleparser | train | function simpleparser (options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('querystring')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse (body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
debug('parse urlencoding')
return parse(body, undefined, undefined, {maxKeys: parameterLimit})
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.