_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q31300 | excludeElements | train | function excludeElements(exclude) {
return Array.isArray(exclude) ? exclude.forEach(function(selector) {
// Use querySelectorAll to hide all dom element with the specified selector
var selectorAll = document.querySelectorAll(selector);
if(selectorAll.length) {
// Interate throug... | javascript | {
"resource": ""
} |
q31301 | screenshot | train | function screenshot(name, options) {
var options = options || {};
var newPath = path;
// options to override
if(options.selector) { selector = options.selector; }
if(options.path) { newPath = path + '/' + options.path; }
if(Array.isArray(options.exclude)) { exclude = exclude.concat... | javascript | {
"resource": ""
} |
q31302 | PathPattern | train | function PathPattern(options) {
// The route string are compiled to a regexp (if it isn't already)
this.regexp = options.regexp;
// The query parameters specified in the path part of the route
this.params = options.params;
// The original routestring (optional)
this.routeString = options.route... | javascript | {
"resource": ""
} |
q31303 | detectWebEnvironment | train | function detectWebEnvironment(environments) {
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if (typeof enviro... | javascript | {
"resource": ""
} |
q31304 | train | function(ul) {
var prevLevel = {level: -1, index: -1, parent: -1, val: ''};
var levelParent = {0: -1};
tocList = ul.children("li");
tocList.each(function(i) {
var me = $(this).removeClass("toc-active");
var currentLevel = parseInt(me.attr('class').trim().slice(-1));
if (currentLevel > ... | javascript | {
"resource": ""
} | |
q31305 | train | function(key) {
var me = treeObject[key];
if (me.parent > -1) {
$(tocList[me.parent]).show();
showParents(me.parent);
}
} | javascript | {
"resource": ""
} | |
q31306 | train | function(searchVal) {
searchVal = searchVal.trim().toLowerCase();
for (var key in treeObject) {
var me = treeObject[key];
if (me.val.indexOf(searchVal) !== -1 || searchVal.length == 0) {
$(tocList[key]).show();
if ($(tocList[me.parent]).is(":hidden")) {
showParents(key);
... | javascript | {
"resource": ""
} | |
q31307 | encode | train | function encode(source, label) {
if (!Buffer.isBuffer(source)) {
throw new TypeError('Argument `source` should be a Buffer.')
}
if (typeof label !== 'string') {
throw new TypeError('Argument `label` should be a string in upper case.')
}
const prefix = before + ' ' + label + endline
const suffix = ... | javascript | {
"resource": ""
} |
q31308 | decode | train | function decode(pem) {
if (Buffer.isBuffer(pem)) {
pem = pem.toString('ascii')
}
const lines = pem.trim().split('\n')
if (lines.length < 3) {
throw new Error('Invalid PEM data.')
}
const match = header.exec(lines[0])
if (match === null) {
throw new Error('Invalid label.')
}
const labe... | javascript | {
"resource": ""
} |
q31309 | Browser | train | function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
} | javascript | {
"resource": ""
} |
q31310 | dev | train | function dev() {
return function logger(ctx, next) {
// request
const start = new Date();
/* eslint no-console: 0 */
console.log(` ${chalk.gray('<--')} ${chalk.bold(ctx.method)} ${chalk.gray(ctx.originalUrl)}`);
// calculate the length of a streaming response
// by intercepting the stream w... | javascript | {
"resource": ""
} |
q31311 | time | train | function time(start) {
let delta = new Date() - start;
delta = delta < 10000 ? `${delta}ms` : `${Math.round(delta / 1000)}s`;
return humanize(delta);
} | javascript | {
"resource": ""
} |
q31312 | isSea | train | function isSea(lat, lng) {
if (landLookup === null) {
const map = getMap();
landLookup = new GeoJsonLookup(map);
}
return landLookup.hasContainers({type: 'Point', coordinates: [lng, lat]});
} | javascript | {
"resource": ""
} |
q31313 | getRange | train | function getRange(node) {
if (isScope(node)) {
return node.nodes
.map(getRange)
.reduce(reduceRanges);
} else if (node.type === 'rule') {
return specificity.calculate(node.selector)
.map(result => {
return result.specificity.split(',').map(v =>... | javascript | {
"resource": ""
} |
q31314 | init | train | function init(defaultLocale, defaultLocaleAssetUrl, defaultCurrency) {
// Store default/initial settings.
_defaultLocale = defaultLocale;
_defaultLocaleAssetUrl = defaultLocaleAssetUrl;
_defaultCurrency = defaultCurrency;
// Store default currency against the Currency object.
Currency.currentCu... | javascript | {
"resource": ""
} |
q31315 | translateElement | train | function translateElement(element, locale) {
var $element = $(element),
keyPath = $element.data('translate');
var translation = getTranslation(keyPath, locale);
if(translation) {
$(element).text(translation);
}
} | javascript | {
"resource": ""
} |
q31316 | translate | train | function translate(locale) {
// Check to see if we have the locale translation data available. If not, fetch it via Ajax.
if(_locales[locale] === undefined) {
$.getJSON(getLocaleAssetUrl(locale), function (localeData) {
// Store the returned locale data.
_locales[locale] = localeData;
... | javascript | {
"resource": ""
} |
q31317 | convert | train | function convert(currency) {
// Store the current currency.
var oldCurrency = Currency.currentCurrency;
// Call convertAll with all possible formats. Currency.currentCurrency will be set as a side effect.
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money"]', 'money_format');... | javascript | {
"resource": ""
} |
q31318 | Factory | train | function Factory(name, model, attributes) {
this.name = name;
this.model = model;
this.attributes = attributes;
} | javascript | {
"resource": ""
} |
q31319 | train | function(name, model, attributes) {
if (name != null && model == null && attributes == null) return factories[name];
if (model == null) return;
if (attributes == null) attributes = {};
factories[name] = new Factory(name, model, attributes);
} | javascript | {
"resource": ""
} | |
q31320 | train | function(attr, lazyContext) {
var resolved;
if (helpers.isArray(attr)) {
resolved = helpers.map(attr, function(item) {
return resolve(item, lazyContext);
});
} else if (helpers.isFunction(attr)) {
if (attr._lazy === true) {
if (lazyContext != null) resolved =... | javascript | {
"resource": ""
} | |
q31321 | train | function(name, overrides) {
var factory = factories[name], resolved;
if (overrides == null) overrides = {};
if (factory == null) return;
// resolve "eager" properties first and leave lazy ones for a second pass
var resolved = resolve(factory.attributes);
// pass already resolved attributes as co... | javascript | {
"resource": ""
} | |
q31322 | train | function(name, arg1, arg2) {
var overrides, done, model;
if (helpers.isObject(arg1)) {
overrides = arg1;
done = arg2;
}
if (helpers.isFunction(arg1)) {
overrides = {};
done = arg1;
}
model = make(name, overrides);
if (model != null) model.save(done);
retur... | javascript | {
"resource": ""
} | |
q31323 | train | function(name, fn) {
if (name == null || fn == null) return;
generatorStore[name] = function() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(fn, args);
};
};
} | javascript | {
"resource": ""
} | |
q31324 | maybeSkip | train | function maybeSkip(path) {
if(path.__jsdoc_to_assert_checked__) {
return true;
}
const {node} = path;
if (node.leadingComments != null && node.leadingComments.length > 0) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q31325 | getBlockName | train | function getBlockName(node, lookup, prefix) {
let depth = prefix.length > 1 ? prefix.length : 0;
// NB don’t walk up to root node, stay at first root child in case of
// too deep prefix
while (node.parent && node.parent.parent && depth--) {
node = node.parent;
}
return lookup.get(node) || '';
} | javascript | {
"resource": ""
} |
q31326 | pluginFolder | train | function pluginFolder () {
const path = sketchtoolExec('show plugins');
invariant(path, 'Plugin folder not found!');
invariant(fs.existsSync(path), `Plugin folder does not exist at ${path}!`);
return path;
} | javascript | {
"resource": ""
} |
q31327 | runPluginWithIdentifier | train | function runPluginWithIdentifier (pluginName, identifier, options = {}) {
const pluginFolderPath = options.dir || pluginFolder();
// Append `.sketchplugin` if not passed in with the plugin name
if (!pluginName.endsWith('.sketchplugin')) {
pluginName += '.sketchplugin';
}
const pluginPath = `${pluginFolde... | javascript | {
"resource": ""
} |
q31328 | list | train | function list (type, filePath) {
invariant(
ALLOWED_LIST_TYPES.includes(type),
`Type '${type}' is not supported by sketchtool`
);
return JSON.parse(sketchtoolExec(`list ${type} ${escape(filePath)}`));
} | javascript | {
"resource": ""
} |
q31329 | train | function (options) {
this._oauth = new OAuth.OAuth(
endpoints.requestToken,
endpoints.accessToken,
options.consumerKey,
options.consumerSecret,
'1.0',
options.callbackUrl,
'HMAC-SHA1'
);
// Store authenticated access if it exists
if (options.acce... | javascript | {
"resource": ""
} | |
q31330 | CBObserver | train | function CBObserver() {
var EVENT = 'interval',
watched = [],
listeners = [],
intervals = {},
self = this;
/**
* Watch a circuit breaker
*
* @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.
*/
this.watc... | javascript | {
"resource": ""
} |
q31331 | findRepeater | train | function findRepeater(node) {
while (node) {
if (node.repeat) {
return node.repeat;
}
node = node.parent;
}
} | javascript | {
"resource": ""
} |
q31332 | replaceNumbering | train | function replaceNumbering(str, value, count) {
// replace numbering in strings only: skip explicit wrappers that could
// contain unescaped numbering tokens
if (typeof str === 'string') {
const ranges = getNumberingRanges(str);
return replaceNumberingRanges(str, ranges, value, count);
}
... | javascript | {
"resource": ""
} |
q31333 | unescapeString | train | function unescapeString(str) {
let i = 0, result = '';
const len = str.length;
while (i < len) {
const ch = str[i++];
result += (ch === '\\') ? (str[i++] || '') : ch;
}
return result;
} | javascript | {
"resource": ""
} |
q31334 | insertContentIntoPlaceholder | train | function insertContentIntoPlaceholder(node, content) {
const state = {replaced: false};
node.value = replacePlaceholder(node.value, content, state);
node.attributes.forEach(attr => {
if (attr.value) {
node.setAttribute(attr.name, replacePlaceholder(attr.value, content, state));
}
});
return state.replaced... | javascript | {
"resource": ""
} |
q31335 | replacePlaceholder | train | function replacePlaceholder(str, value, _state) {
if (typeof str === 'string') {
const ranges = findUnescapedTokens(str, placeholder);
if (ranges.length) {
if (_state) {
_state.replaced = true;
}
str = replaceRanges(str, ranges, value);
}
}
return str;
} | javascript | {
"resource": ""
} |
q31336 | setNodeContent | train | function setNodeContent(node, content) {
// find caret position and replace it with content, if possible
if (node.value) {
const ranges = findUnescapedTokens(node.value, caret);
if (ranges.length) {
node.value = replaceRanges(node.value, ranges, content);
return;
}
}
if ((node.name && node.name.toLower... | javascript | {
"resource": ""
} |
q31337 | NpmSubmodulePlugin | train | function NpmSubmodulePlugin(options) {
// initialize instance variables
this.commands = options.commands ? options.commands : [];
this.autoInstall = options.autoInstall ? options.autoInstall : false;
this.logger = options.logger ? options.logger : console.log;
this.path = 'node_modules' + path.sep + options.m... | javascript | {
"resource": ""
} |
q31338 | parseGitUrl | train | function parseGitUrl(giturl) {
var ref, uri, fileParts, filepath;
if (!checkGitUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
uri = new URI(giturl);
ref = uri.fragment() || 'master';
uri.fragment(null);
// Extract file inside the repo (after the .git)
fileParts =u... | javascript | {
"resource": ""
} |
q31339 | cloneGitRepo | train | function cloneGitRepo(host, ref) {
var isBranch = false;
ref = ref || 'master';
if (!validateSha(ref)) isBranch = true;
return Q()
// Create temporary folder to store git repos
.then(function() {
if (GIT_TMP) return;
return fs.tmp.dir()
.then(function(_tmp) {
... | javascript | {
"resource": ""
} |
q31340 | resolveFileFromGit | train | function resolveFileFromGit(giturl) {
if (_.isString(giturl)) giturl = parseGitUrl(giturl);
if (!giturl) return Q(null);
// Clone or get from cache
return cloneGitRepo(giturl.host, giturl.ref)
.then(function(repo) {
// Resolve relative path
return path.resolve(repo, giturl.filepath... | javascript | {
"resource": ""
} |
q31341 | resolveGitRoot | train | function resolveGitRoot(filepath) {
var relativeToGit, repoId;
// No git repo cloned, or file is not in a git repository
if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null;
// Extract first directory (is the repo id)
relativeToGit = path.relative(GIT_TMP, filepath);
repoId = _.... | javascript | {
"resource": ""
} |
q31342 | train | function(config) {
var hasParams = (typeof config.params === 'object');
var hasFiles = _.isArray(config.attachments);
if('GET' === config.method) {
if(hasParams) {
config.url = addParams(config.url, config.params);
}
if (hasFiles) {
throw new Error("Canno... | javascript | {
"resource": ""
} | |
q31343 | calculProgress | train | function calculProgress(navigation, current) {
var n = _.size(navigation);
var percent = 0, prevPercent = 0, currentChapter = null;
var done = true;
var chapters = _.chain(navigation)
// Transform as array
.map(function(nav, path) {
nav.path = path;
return nav;
})
// S... | javascript | {
"resource": ""
} |
q31344 | animate | train | function animate(source, target, options) {
var start = Object.create(null)
var diff = Object.create(null)
options = options || {}
// We let clients specify their own easing function
var easing = (typeof options.easing === 'function') ? options.easing : animations[options.easing]
// if nothing is specified... | javascript | {
"resource": ""
} |
q31345 | getFields | train | function getFields(def, obj) {
var a = {};
// if not an object, return the value
if (!_.isObject(obj)) {
return obj;
}
// check for type override
var defType = _.get(obj, 'attributes.xsi:type') || _.get(obj, 'attributes.type');
defType = defType ? defType.replace(/^vim25\:/i, '') : null;
/... | javascript | {
"resource": ""
} |
q31346 | sortArgs | train | function sortArgs(method, args) {
// get the method definition
var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType');
// if found create the definition by calling its function
if (def) {
return getFields(def(), args);
}
return args;
} | javascript | {
"resource": ""
} |
q31347 | train | function(resolve, reject) {
var fn = _client.client.VimService.VimPort[name];
fn(args, function(err, result, raw, soapHeader) {
if (err) {
// emit an error and handle the error
_client.emit('method.error', err);
_client.errorHandler(err, name, args, resolve, reject);
}
else {
... | javascript | {
"resource": ""
} | |
q31348 | getUpdates | train | function getUpdates() {
return _client.method('WaitForUpdatesEx', {
_this: _client._updatesCollector,
version: _client._updatesVersion,
options: {
maxWaitSeconds: 0
}
})
.then(function(set) {
if (set) {
// update the version
_client._updatesVersion = set.version;
// get only t... | javascript | {
"resource": ""
} |
q31349 | wrapComplete | train | function wrapComplete(instance, options) {
var complete = options.complete;
options.complete = function(response) {
if ( _.isFunction( complete ) ) {
complete.call( this, instance, response, options );
}
};
} | javascript | {
"resource": ""
} |
q31350 | putItem | train | function putItem(model, options) {
options || ( options = {} );
if ( options.serializeDates !== false ) {
// If serializeDates is NOT `false`, use `true` by default.
options.serializeDates = true;
}
var newKey, // If the model `isNew`, a new key is generated.
request,
hashName, // Name of the hash attribut... | javascript | {
"resource": ""
} |
q31351 | deleteItem | train | function deleteItem(model, options) {
var request,
deferred = new _.Deferred(),
params = {
Key: key.call( model ),
TableName: model._tableName()
};
options || ( options = {} );
wrapComplete( model, options );
_.extend( params, options.dynamodb );
if ( options.serializeDates !== false ) {
// If the ... | javascript | {
"resource": ""
} |
q31352 | fetchCollection | train | function fetchCollection(collection, options) {
options || ( options = {} );
var request,
deferred = new _.Deferred(),
// Determine the type of request: Query or Scan. Default is Scan.
fetchType = options.query ? 'query' : 'scan',
params = { TableName: collection._tableName() };
wrapComplete( collection, o... | javascript | {
"resource": ""
} |
q31353 | serializeAllDates | train | function serializeAllDates(model, json) {
_.each(json, function (value, name) {
if ( _.isDate( value ) ) {
json[ name ] = model.serializeDate( name, value );
} else if ( !isScalar( value ) && !isBackboneInstance( value ) && isRecursive( value ) ) {
serializeAllDates( model, value );
}
});
return json;
} | javascript | {
"resource": ""
} |
q31354 | deserializeAllDates | train | function deserializeAllDates(model, json) {
_.each(json, function (value, name) {
if ( !_.isDate( value ) && !isBackboneInstance( value ) ) {
if ( _.isString( value ) && model.isSerializedDate( name, value ) ) {
json[ name ] = model.deserializeDate( name, value );
} else if ( !isScalar( value ) && isRecurs... | javascript | {
"resource": ""
} |
q31355 | _tableName | train | function _tableName() {
if ( this.tableName ) {
return _.result( this, 'tableName' );
}
var urlAttributeName = this instanceof Backbone.DynamoDB.Model ? 'urlRoot' : 'url',
table = _.result( this, urlAttributeName ).replace( /^\//, '' );
return table.charAt( 0 ).toUpperCase() + table.substr( 1 );
} | javascript | {
"resource": ""
} |
q31356 | train | function() {
var hashKey = _.result( this, 'hashAttribute' ) || _.result( this, 'idAttribute' ),
rangeKey = _.result( this, 'rangeAttribute' ),
hashValue = this.get( hashKey ),
rangeValue = rangeKey ? this.get( rangeKey ) : null;
return hashValue == null || ( rangeKey && rangeValue == null );
} | javascript | {
"resource": ""
} | |
q31357 | train | function (dynamoDbParams, options) {
var _options = { query: dynamoDbParams };
_.extend( _options, options );
return this.fetch( _options );
} | javascript | {
"resource": ""
} | |
q31358 | train | function (dynamoDbParams, options) {
var _options = { scan: dynamoDbParams };
_.extend( _options, options );
return this.fetch( _options );
} | javascript | {
"resource": ""
} | |
q31359 | train | function (jsName, methodName) {
return function () {
var args = slice.call(arguments, 0);
var i = 0, max, arg, util, id, exportable;
for (max=args.length; i<max; i++) {
arg = args[i];
if (arg.kirin_bridgeUtils) {
util = arg.kirin_bridgeUtils;
... | javascript | {
"resource": ""
} | |
q31360 | handleError | train | function handleError(during, e) {
/*
* {
"message": "Can't find variable: cardObject",
"line": 505,
"sourceId": 250182872,
"sourceURL": "file:///Users/james/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/ADE774FF-B033-46A2-9CBA-DD362196E1F... | javascript | {
"resource": ""
} |
q31361 | resolveModule | train | function resolveModule(moduleName) {
if (loadedObjects[moduleName]) {
return loadedObjects[moduleName];
}
var aModule, anObject, MyModule;
if (gwtClasses) {
aModule = gwtClasses[moduleName];
}
if (!aModule) {
try {
aModule = myRequire(moduleName);
} ca... | javascript | {
"resource": ""
} |
q31362 | traversalSpec | train | function traversalSpec(args) {
return {
attributes: {
'xsi:type': 'TraversalSpec'
},
type: args.listSpec.type,
path: args.listSpec.path,
skip: false
};
} | javascript | {
"resource": ""
} |
q31363 | objectSpec | train | function objectSpec(args) {
var set = [];
if (!args.id) {
// create a base object
var spec = { attributes: { 'xsi:type': 'ObjectSpec' } };
// check for containerview
if (args.listSpec.type === 'ContainerView' && args.containerView) {
spec.obj = args.containerView;
}
else {
... | javascript | {
"resource": ""
} |
q31364 | propertySpec | train | function propertySpec(args) {
// create a basic specification
var spec = {
attributes: {
'xsi:type': 'PropertySpec'
},
type: args.type
};
// if an array of properties was passed, validate the properties
if (Array.isArray(args.properties) && args.properties.length > 0) {
var validPaths = ... | javascript | {
"resource": ""
} |
q31365 | isInActiveContentEditable | train | function isInActiveContentEditable(node) {
while (node) {
if ( node.getAttribute &&
node.getAttribute("contenteditable") &&
node.getAttribute("contenteditable").toUpperCase() === "TRUE" ) {
return true
}
node = node.parentNod... | javascript | {
"resource": ""
} |
q31366 | connectedToTheDom | train | function connectedToTheDom(node) {
// IE does not have contains method on document element, only body
var container = node.ownerDocument.contains ? node.ownerDocument : node.ownerDocument.body;
return container.contains(node);
} | javascript | {
"resource": ""
} |
q31367 | sign | train | function sign(value, pow) {
const msb = 1 << pow;
if ((value & msb) === 0) {
return value;
}
let neg = -1 * (value & msb);
neg += (value & (msb - 1));
return neg;
} | javascript | {
"resource": ""
} |
q31368 | renderDom | train | function renderDom($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
} | javascript | {
"resource": ""
} |
q31369 | convertImages | train | function convertImages(images, options) {
if (!options.convertImages) return Q();
var downloaded = [];
options.book.log.debug.ln('convert ', images.length, 'images to png');
return batch.execEach(images, {
max: 100,
fn: function(image) {
var imgin = path.resolve(options.boo... | javascript | {
"resource": ""
} |
q31370 | normalizePage | train | function normalizePage(sections, options) {
options = _.defaults(options || {}, {
// Current book
book: null,
// Do we need to convert svg?
convertImages: false,
// Current file path
input: '.',
// Navigation to use to transform path
navigation: {},... | javascript | {
"resource": ""
} |
q31371 | execEach | train | function execEach(items, options) {
if (_.size(items) === 0) return Q();
var concurrents = 0, d = Q.defer(), pending = [];
options = _.defaults(options || {}, {
max: 100,
fn: function() {}
});
function startItem(item, i) {
if (concurrents >= options.max) {
pend... | javascript | {
"resource": ""
} |
q31372 | train | function(filepath, source) {
var parser = parsers.get(path.extname(filepath));
var type = parser? parser.name : null;
return that.applyShortcuts(type, source);
} | javascript | {
"resource": ""
} | |
q31373 | createDropdownMenu | train | function createDropdownMenu(dropdown) {
var $menu = $('<div>', {
'class': 'dropdown-menu',
'html': '<div class="dropdown-caret"><span class="caret-outer"></span><span class="caret-inner"></span></div>'
});
if (_.isString(dropdown)) {
$menu.append(dropdown);
} else {
var ... | javascript | {
"resource": ""
} |
q31374 | createButton | train | function createButton(opts) {
opts = _.defaults(opts || {}, {
// Aria label for the button
label: '',
// Icon to show
icon: '',
// Inner text
text: '',
// Right or left position
position: 'left',
// Other class name to add to the button
... | javascript | {
"resource": ""
} |
q31375 | updateButton | train | function updateButton(opts) {
var $result;
var $toolbar = $('.book-header');
var $title = $toolbar.find('h1');
// Build class name
var positionClass = 'pull-'+opts.position;
// Create button
var $btn = $('<a>', {
'class': 'btn',
'text': opts.text? ' ' + opts.text : '',
... | javascript | {
"resource": ""
} |
q31376 | argsToObject | train | function argsToObject(args) {
var options = {};
options.address = args.shift();
options.output = args.shift();
// Pair two arguments, while transforming the key to camelCase
for (i = 0; i < args.length; i = i + 2) {
options[toCamelCase(args[i].substr(2))] = args[i + 1];
}
return options;
} | javascript | {
"resource": ""
} |
q31377 | getParent | train | function getParent(type, id, parentType, root) {
return _client.retrieve({
type: type,
id: id,
properties: ['parent']
})
.then(function(obj) {
if (obj.length > 0) {
obj = _.first(obj);
type = _.get(obj, 'parent.type');
id = _.get(obj, 'parent.id');
// if there is no pa... | javascript | {
"resource": ""
} |
q31378 | isDefaultPlugin | train | function isDefaultPlugin(name, version) {
if (!_.contains(DEFAULT_PLUGINS, name)) return false;
try {
var pluginPkg = require('gitbook-plugin-'+name+'/package.json');
return semver.satisfies(pluginPkg.version, version || '*');
} catch(e) {
return false;
}
} | javascript | {
"resource": ""
} |
q31379 | normalizePluginsList | train | function normalizePluginsList(plugins, addDefaults) {
// Normalize list to an array
plugins = _.isString(plugins) ? plugins.split(',') : (plugins || []);
// Remove empty parts
plugins = _.compact(plugins);
// Divide as {name, version} to handle format like 'myplugin@1.0.0'
plugins = _.map(plug... | javascript | {
"resource": ""
} |
q31380 | getFiles | train | function getFiles () {
const FUCK_ENV = process.env.FUCK_ENV
|| process.env.npm_package_config_FUCK_ENV
|| FUCK_ENV_DEFAULT
return FUCK_ENV.split(',').map(file => path.resolve(root, file))
} | javascript | {
"resource": ""
} |
q31381 | formatValue | train | function formatValue(value) {
var out;
var type = util.sType(value);
// if there is a type, check all sub items for types
if (_.has(value, 'attributes.type') && _.has(value, '$value') && _.keys(value).length === 2) {
out = util.moRef(value);
}
else if (type) {
if (util.isArray(value)) {
out ... | javascript | {
"resource": ""
} |
q31382 | formatProp | train | function formatProp(obj) {
var out = {};
var props = _.get(obj, 'propSet');
var moRef = _.has(obj, 'obj') ? util.moRef(obj.obj) : util.moRef(obj);
out.id = moRef.id;
out.type = moRef.type;
// loop through the propSet
if (Array.isArray(props)) {
_.forEach(props, function(prop) {... | javascript | {
"resource": ""
} |
q31383 | expandFields | train | function expandFields(obj) {
var out = {};
_.forEach(obj, function(val, key) {
if (_.includes(key, '.')) {
_.set(out, key, val);
}
else {
out[key] = val;
}
});
return out;
} | javascript | {
"resource": ""
} |
q31384 | format | train | function format(response) {
var newObj = [];
var objects = _.get(response, 'objects') || response;
if (objects) {
// check if objects is an array
if (Array.isArray(objects)) {
_.forEach(objects, function(obj) {
newObj.push(expandFields(formatProp(obj)));
});
}
else {
newObj = exp... | javascript | {
"resource": ""
} |
q31385 | filterSummary | train | function filterSummary(paths) {
var $summary = $('.book-summary');
$summary.find('li').each(function() {
var path = $(this).data('path');
var st = paths == null || _.contains(paths, path);
$(this).toggle(st);
if (st) $(this).parents('li').show();
});
} | javascript | {
"resource": ""
} |
q31386 | setOperations | train | function setOperations(operations, portType) {
_.forEach(portType.childNodes, node => {
if (node.localName === 'operation') {
operations[node.getAttribute('name')] = node;
}
});
} | javascript | {
"resource": ""
} |
q31387 | getUniqueFilename | train | function getUniqueFilename(base, filename) {
if (!filename) {
filename = base;
base = '/';
}
filename = path.resolve(base, filename);
var ext = path.extname(filename);
filename = path.join(path.dirname(filename), path.basename(filename, ext));
var _filename = filename+ext;
... | javascript | {
"resource": ""
} |
q31388 | listFiles | train | function listFiles(root, options) {
options = _.defaults(options || {}, {
ignoreFiles: [],
ignoreRules: []
});
var d = Q.defer();
// Our list of files
var files = [];
var ig = Ignore({
path: root,
ignoreFiles: options.ignoreFiles
});
// Add extra rules... | javascript | {
"resource": ""
} |
q31389 | cleanFolder | train | function cleanFolder(root) {
if (!fs.existsSync(root)) return fsUtils.mkdirp(root);
return listFiles(root, {
ignoreFiles: [],
ignoreRules: [
// Skip Git and SVN stuff
'.git/',
'.svn/'
]
})
.then(function(files) {
var d = Q.defer();
... | javascript | {
"resource": ""
} |
q31390 | validateMethod | train | function validateMethod (method) {
if (!method) {
return option.some('HTTP method is not specified')
}
if (typeof method !== 'string') {
return option.some('HTTP method should be type of string')
}
if (supportedMethods.indexOf(method.toUpperCase()) < 0) {
return option.some(`Http method ${method} ... | javascript | {
"resource": ""
} |
q31391 | validateUrl | train | function validateUrl (url) {
if (!url) {
return option.some('Url is not specified')
}
if (typeof url !== 'string') {
return option.some('Url should be type of string')
}
return option.none
} | javascript | {
"resource": ""
} |
q31392 | validateHeader | train | function validateHeader (key, value) {
if (typeof key !== 'string' || typeof value !== 'string')
return option.some(`Parts of header ${key}:${value} must be strings`)
return option.none
} | javascript | {
"resource": ""
} |
q31393 | validateResponseType | train | function validateResponseType (type) {
if (validTypes.indexOf(type) < 0)
return option.some(`Response content type ${type} is not supported`)
return option.none
} | javascript | {
"resource": ""
} |
q31394 | getResults | train | function getResults(result, objects) {
// if there are no results, resolve an empty array
if (!result) {
return new Promise(function(resolve, reject) {
resolve([]);
});
}
// if the result object is undefined or not an array, make it one
result.objects = result.objects || [];
result.objects =... | javascript | {
"resource": ""
} |
q31395 | ins | train | function ins(parent /* child1, child2, ... */) {
for (let i = 1, n = arguments.length; i < n; i++) {
parent.appendChild(arguments[i]);
}
return parent;
} | javascript | {
"resource": ""
} |
q31396 | train | function() {
let el = this.el;
if (el) {
clearTimeout(this.timeout);
if (el.parentNode) el.parentNode.removeChild(el);
this.el = null;
}
return this;
} | javascript | {
"resource": ""
} | |
q31397 | moRef | train | function moRef(type, id) {
if (type && id) {
return {
attributes: {
type: type
},
"$value": id
};
}
else if (typeof(type) === 'object') {
return {
id: _.get(type, '$value'),
type: _.get(type, 'attributes.type') || _.get(type, 'attributes.xsi:type')
};
}
return null;
} | javascript | {
"resource": ""
} |
q31398 | isArray | train | function isArray(obj) {
var type = sType(obj);
return (Array.isArray(obj) || (typeof(type) === 'string' && type.substring(0, 5) === 'Array'));
} | javascript | {
"resource": ""
} |
q31399 | isBoolean | train | function isBoolean(obj) {
var type = sType(obj);
return (_.has(obj, '$value') && (type === 'xsd:boolean' || type === 'boolean'));
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.