_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39800 | toBoolean | train | function toBoolean(val, def) {
if (is_1.isBoolean(val))
return val;
if (!is_1.isValue(val))
return toDefault(null, def);
val = val.toString();
return (parseFloat(val) > 0 ||
is_1.isInfinite(val) ||
val === 'true' ||
val === 'yes' ||
val === '1' ||
... | javascript | {
"resource": ""
} |
q39801 | toDate | train | function toDate(val, format, def) {
if (is_1.isDate(format)) {
def = format;
format = undefined;
}
var opts = format;
// Date format options a simple timezine
// ex: 'America/Los_Angeles'.
if (is_1.isString(opts)) {
opts = {
timeZone: format
};
}
... | javascript | {
"resource": ""
} |
q39802 | canParse | train | function canParse() {
return !/^[0-9]+$/.test(val) &&
(is_1.isString(val) && /[0-9]/g.test(val) &&
/(\.|\/|-|:)/g.test(val));
} | javascript | {
"resource": ""
} |
q39803 | toDefault | train | function toDefault(val, def) {
if (is_1.isValue(val) && !(is_1.isEmpty(val) && !is_1.isEmpty(def)))
return val;
return is_1.isValue(def) ? def : null;
} | javascript | {
"resource": ""
} |
q39804 | toEpoch | train | function toEpoch(val, def) {
return toDefault((is_1.isDate(val) && val.getTime()), def);
} | javascript | {
"resource": ""
} |
q39805 | toFloat | train | function toFloat(val, def) {
if (is_1.isFloat(val))
return val;
if (!is_1.isValue(val))
return toDefault(null, def);
var parsed = function_1.tryWrap(parseFloat, val)(def);
if (is_1.isFloat(parsed) || is_1.isNumber(parsed))
return parsed;
if (toBoolean(val))
return 1;
... | javascript | {
"resource": ""
} |
q39806 | toJSON | train | function toJSON(obj, pretty, def) {
if (is_1.isString(pretty)) {
def = pretty;
pretty = undefined;
}
var tabs = 0;
pretty = is_1.isBoolean(pretty) ? 2 : pretty;
tabs = pretty ? pretty : tabs;
if (!is_1.isObject(obj))
return toDefault(null, def);
return function_1.tryW... | javascript | {
"resource": ""
} |
q39807 | toInteger | train | function toInteger(val, def) {
if (!is_1.isValue(val))
return toDefault(null, def);
var parsed = function_1.tryWrap(parseInt, val)(def);
if (is_1.isInteger(parsed))
return parsed;
if (toBoolean(val))
return 1;
return 0;
} | javascript | {
"resource": ""
} |
q39808 | toMap | train | function toMap(val, id, def) {
if (is_1.isValue(id) && !is_1.isString(id)) {
def = id;
id = undefined;
}
if (is_1.isPlainObject(val))
return val;
if (!is_1.isValue(val) || (!is_1.isString(val) && !is_1.isArray(val)))
return toDefault(null, def);
// Default id key.
... | javascript | {
"resource": ""
} |
q39809 | toNested | train | function toNested(val, def) {
function nest(src) {
var dest = {};
for (var p in src) {
if (src.hasOwnProperty(p))
if (/\./g.test(p))
object_1.set(dest, p, src[p]);
else
dest[p] = src[p];
}
return dest... | javascript | {
"resource": ""
} |
q39810 | toRegExp | train | function toRegExp(val, def) {
var exp = /^\/.+\/(g|i|m)?([m,i,u,y]{1,4})?/;
var optsExp = /(g|i|m)?([m,i,u,y]{1,4})?$/;
if (is_1.isRegExp(val))
return val;
if (!is_1.isValue(val) || !is_1.isString(val))
return toDefault(null, def);
function regExpFromStr() {
var opts;
... | javascript | {
"resource": ""
} |
q39811 | toUnnested | train | function toUnnested(obj, prefix, def) {
if (is_1.isValue(prefix) && !is_1.isBoolean(prefix)) {
def = prefix;
prefix = undefined;
}
var dupes = 0;
function unnest(src, dest, pre) {
dest = dest || {};
for (var p in src) {
if (dupes > 0)
return;
... | javascript | {
"resource": ""
} |
q39812 | toWindow | train | function toWindow(key, val, exclude) {
/* istanbul ignore if */
if (!is_1.isBrowser())
return;
exclude = toArray(exclude);
var _keys, i;
// key/val was passed.
if (is_1.isString(key)) {
if (!is_1.isPlainObject(val)) {
window[key] = val;
}
else {
... | javascript | {
"resource": ""
} |
q39813 | train | function(child, parent, protoProps, staticProps) {
// Inherit prototype properties from parent
// Set the prototype chain to inherit without calling parent's constructor function.
SharedConstructor.prototype = parent.prototype;
child.prototype = new SharedConstructor();
child.prototype.constructor =... | javascript | {
"resource": ""
} | |
q39814 | train | function(opts) {
EventEmitter.call(this);
this.reqId = 1;
this.opts = opts;
this.id = opts.id;
this.socket = null;
this.callbacks = {};
this.type = opts.type;
this.info = opts.info;
this.state = ST_INITED;
this.consoleService = opts.consoleService;
} | javascript | {
"resource": ""
} | |
q39815 | call | train | function call(handle, route, err, req, res, next) {
var arity = handle.length;
var hasError = Boolean(err);
debug('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
try {
if (hasError && arity === 4) {
// error-handling middleware
handle(err, req, res, next);
return;
... | javascript | {
"resource": ""
} |
q39816 | lintAllFiles | train | function lintAllFiles (src, options)
{
glob(src,
function (err, files)
{
if (err) throw err;
for (var i = 0, l = files.length; i < l; i++)
{
jsHintHelper.lintFile(files[i], options.rules);
}
}
);
} | javascript | {
"resource": ""
} |
q39817 | mergeRecursive | train | function mergeRecursive(key, defaults, app) {
key = key ? key.toUpperCase() : null
if (app === undefined || app == undefine || process.env[key] == undefine)
return undefine
var config = defaults
var atOverrideVal = app === null ? false : atLeaf(app)
var atDefaultVal = defaults === null || atLeaf(defau... | javascript | {
"resource": ""
} |
q39818 | s3streamer | train | function s3streamer(s3, opts) {
var headers = (opts || {}).headers || { }
return function (file, filename, mimetype, encoding, callback) {
headers['Content-Type'] = mimetype
var buf = Buffer(0)
file.on('data', function (chunk) {
buf = Buffer.concat([buf, chunk])
})
file.on('end', function... | javascript | {
"resource": ""
} |
q39819 | train | function () {
'use strict';
// default options for angularTemplatecache gulp task
var options = {
config: {
compilePatternsOnImport: false,
dataSource: 'pattern',
dataFileName: 'pattern.yml',
htmlTemplateDest: './source/_patterns',
stylesDest: './source/css/scss',
scriptsD... | javascript | {
"resource": ""
} | |
q39820 | Pool | train | function Pool(config) {
if(!(this instanceof Pool)) {
return new Pool(config);
}
var self = this;
if(!config) { throw new TypeError("config not set"); }
self._pool = require('mysql').createPool(config);
self._get_connection = Q.nfbind(self._pool.getConnection.bind(self._pool));
db.Pool.call(this);
} | javascript | {
"resource": ""
} |
q39821 | _filesToString | train | function _filesToString (files, encoding, separator, callback) {
if ("undefined" === typeof files) {
throw new ReferenceError("missing \"files\" argument");
}
else if ("object" !== typeof files || !(files instanceof Array)) {
throw new TypeError("\"files\" argument is not an Array");
}
else i... | javascript | {
"resource": ""
} |
q39822 | insert | train | function insert (table, object, fields) {
var input = this
if (input instanceof Array) {
insertArray.call(input, table, object, fields)
} else {
insertObject.call(input, table, object, fields)
}
} | javascript | {
"resource": ""
} |
q39823 | insertArray | train | function insertArray (table, object, fields) {
var input = this
input.forEach(function addRow (entry, rowNo) {
var tableRow = fields.map(function cell (fieldName) {
return getCellContent.call(entry, object.fields[fieldName], rowNo)
})
table.push(tableRow)
})
} | javascript | {
"resource": ""
} |
q39824 | insertObject | train | function insertObject (table, object, fields) {
var input = this
fields.forEach(function addField (field) {
var cells = {}
cells[field] = getCellContent.call(input, object.fields[field])
table.push(cells)
})
} | javascript | {
"resource": ""
} |
q39825 | getCellContent | train | function getCellContent (field) {
var entry = this
var args = Array.prototype.slice.call(arguments, 1)
if (typeof field === 'string') {
return field
}
if (typeof field === 'function') {
var value
try {
value = field.apply(entry, args)
} catch (e) {
value = '(err)'
}
if (va... | javascript | {
"resource": ""
} |
q39826 | readBuffer | train | async function readBuffer(path) {
const rs = createReadStream(path)
/** @type {Buffer} */
const res = await collect(rs, { binary: true })
return res
} | javascript | {
"resource": ""
} |
q39827 | train | function(data, done) {
this._data.push(this._clone(data));
var ret = this._data.length;
done(null, ret);
} | javascript | {
"resource": ""
} | |
q39828 | train | function(data, done) {
if(!this._key) {
done('no key found for metadata');
return;
}
var key = data[this._key.getName()];
var ix = -1;
for(var i = 0; i < this._data.length; i++) {
if(this._data[i][this._key.getName()] === key) {
ix = i;
break;
... | javascript | {
"resource": ""
} | |
q39829 | train | function(key, done) {
if(!this._key) {
done('no key found for metadata');
return;
}
var ret = null; // if not found return null
for(var i = 0; i < this._data.length; i++) {
if(this._data[i][this._key.getName()] === key) {
ret = this._clone(this._data[i]);
... | javascript | {
"resource": ""
} | |
q39830 | purgeResource | train | function purgeResource(resource, archive) {
if (!resource.purge) { return true; }
var criteria = resource.purge();
var deferred = Q.defer();
archive.bind(resource.name);
archive[resource.name].remove(criteria, function (err, results) {
err ? deferred.reject(err) : d... | javascript | {
"resource": ""
} |
q39831 | MandrillProvider | train | function MandrillProvider(apiKey, options) {
if (typeof apiKey !== 'string') {
throw new Error('Invalid parameters');
}
options = options || {};
if (typeof options.async === 'undefined')
options.async = false;
if (typeof options.apiSecure === 'undefined')
options.apiSecure = true;
options.apiHostname = ... | javascript | {
"resource": ""
} |
q39832 | train | function (event){
//IE compatibility
event = event || window.event;
//Mozilla, Opera, & Legacy
if(event && event.type && (/DOMContentLoaded|load/).test(event.type)) {
fireDOMReady();
//Legacy
} else if(document.readyState) {
if ((/loaded|complete/).test(doc.readyState)) {
fireDOMReady();
//IE,... | javascript | {
"resource": ""
} | |
q39833 | train | function() {
if (!ready) {
ready = true;
//Call the stack of onload functions in given context or window object
for (var i=0, len=stack.length; i < len; i++) {
stack[i][0].call(stack[i][1]);
}
//Clean up after the DOM is ready
if (document.removeEventListener) {
document.removeEventListener... | javascript | {
"resource": ""
} | |
q39834 | runScript | train | function runScript(script, context) {
if (typeof script.useModuleLoader == 'undefined') {
// if it is not explicitly defined whether we should use modeule loader or not
// we assume we should use module loader for .js files
script.useModuleLoader = path.extname(script.path).toLowerCase() == ... | javascript | {
"resource": ""
} |
q39835 | runScriptViaModuleLoader | train | function runScriptViaModuleLoader(script, context) {
if(!fs.existsSync(script.fullPath)) {
events.emit('warn', 'Script file does\'t exist and will be skipped: ' + script.fullPath);
return Q();
}
var scriptFn = require(script.fullPath);
context.scriptLocation = script.fullPath;
contex... | javascript | {
"resource": ""
} |
q39836 | runScriptViaChildProcessSpawn | train | function runScriptViaChildProcessSpawn(script, context) {
var opts = context.opts;
var command = script.fullPath;
var args = [opts.projectRoot];
if (fs.statSync(script.fullPath).isDirectory()) {
events.emit('verbose', 'Skipped directory "' + script.fullPath + '" within hook directory');
... | javascript | {
"resource": ""
} |
q39837 | extractSheBangInterpreter | train | function extractSheBangInterpreter(fullpath) {
var fileChunk;
var octetsRead;
var fileData;
var hookFd = fs.openSync(fullpath, 'r');
try {
// this is a modern cluster size. no need to read less
fileData = new Buffer(4096);
octetsRead = fs.readSync(hookFd, fileData, 0, 4096, 0... | javascript | {
"resource": ""
} |
q39838 | train | function (options) {
var self = this
PPUnit.super_.call(self)
options = options || {}
self.concurrency = options.concurrency || -1
self.rootSuite = new Suite(undefined)
self.rootSuite.timeout(2000)
self.rootSuite.globallyExclusive()
self.rootSuite.locallyExclusiveTests()
self.all... | javascript | {
"resource": ""
} | |
q39839 | addAdapter | train | function addAdapter (state, name, config, logger) {
if (_.isFunction(name)) {
logger = name
name = logger.name
config = config || {}
} else if (_.isFunction(config)) {
logger = config
if (_.isObject(name)) {
config = name
name = logger.name
} else {
config = {}
}
} el... | javascript | {
"resource": ""
} |
q39840 | addFilter | train | function addFilter (config, filter) {
if (filter) {
if (filter[ 0 ] === '-') {
config.filters.ignore[ filter ] = new RegExp('^' + filter.slice(1).replace(/[*]/g, '.*?') + '$')
} else {
config.filters.should[ filter ] = new RegExp('^' + filter.replace(/[*]/g, '.*?') + '$')
}
}
} | javascript | {
"resource": ""
} |
q39841 | addLogger | train | function addLogger (state, name, config, adapter) {
config = Object.assign({}, defaultConfig, config)
setFilters(config)
const logger = {
name: name,
config: config,
adapter: adapter,
addFilter: addFilter.bind(null, config),
removeFilter: removeFilter.bind(null, config),
setFilter: setFilt... | javascript | {
"resource": ""
} |
q39842 | attach | train | function attach (state, logger, namespace) {
_.each(levels, function (level, name) {
logger[ name ] = prepMessage.bind(null, state, name, namespace)
})
} | javascript | {
"resource": ""
} |
q39843 | init | train | function init (state, namespace) {
namespace = namespace || 'deftly'
const logger = { namespace: namespace }
attach(state, logger, namespace)
return logger
} | javascript | {
"resource": ""
} |
q39844 | log | train | function log (state, type, namespace, message) {
const level = levels[ type ]
_.each(state.loggers, function (logger) {
logger.log({
type: type,
level: level,
namespace: namespace,
message: message
})
})
} | javascript | {
"resource": ""
} |
q39845 | prepMessage | train | function prepMessage (state, level, namespace, message) {
if (_.isString(message)) {
const formatArgs = Array.prototype.slice.call(arguments, 3)
message = format.apply(null, formatArgs)
}
log(state, level, namespace, message)
} | javascript | {
"resource": ""
} |
q39846 | removeFilter | train | function removeFilter (config, filter) {
if (filter) {
if (config.filters.ignore[ filter ]) {
delete config.filters.ignore[ filter ]
} else {
delete config.filters.should[ filter ]
}
}
} | javascript | {
"resource": ""
} |
q39847 | setFilters | train | function setFilters (config) {
const parts = config.filter.split(/[\s,]+/)
config.filters = {
should: {},
ignore: {}
}
_.each(parts, addFilter.bind(null, config))
} | javascript | {
"resource": ""
} |
q39848 | shouldRender | train | function shouldRender (config, entry) {
// if we're below the log level, return false
if (config.level < entry.level) {
return false
}
// if we match the ignore list at all, return false
const ignoreMatch = _.find(_.values(config.filters.ignore), ignore => {
return ignore.test(entry.namespace)
})
... | javascript | {
"resource": ""
} |
q39849 | initTerminateHandlers | train | function initTerminateHandlers() {
var readLine;
if (process.platform === "win32"){
readLine = require("readline");
readLine.createInterface ({
input: process.stdin,
output: process.stdout
}).on("SIGINT", function () {
process.emit("SIGINT");
});
}
// handle INTERRUPT (CTRL+... | javascript | {
"resource": ""
} |
q39850 | fetch_object_by_uuid | train | function fetch_object_by_uuid(data, prop, uuid) {
if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was no... | javascript | {
"resource": ""
} |
q39851 | setDomAttrs | train | function setDomAttrs(attrs, el) {
for (let attr in attrs) {
if (!attrs.hasOwnProperty(attr)) { continue; }
switch (attr) {
case 'className':
case 'id':
el[attr] = attrs[attr];
break;
default:
el.setAttribute(attr, attrs[attr]);
break;
}
}
return el;
} | javascript | {
"resource": ""
} |
q39852 | del | train | async function del(owner, repo) {
const endpoint = `/user/starred/${owner}/${repo}`
const { statusCode } = await this._request({
method: 'PUT',
data: {},
endpoint,
})
if (statusCode != 204) {
throw new Error(`Unexpected status code ${statusCode}.`)
}
} | javascript | {
"resource": ""
} |
q39853 | objCleaner | train | function objCleaner(obj, removeTypes) {
var defaultRemoveTypes = [null, 'undefined', false, '', [], {}];
var key;
function allowEmptyObject() {
var i;
for (i = 0; i < removeTypes.length; i++) {
if (removeTypes[i] instanceof Object && Object.keys(removeTypes[i]).length === 0) {
... | javascript | {
"resource": ""
} |
q39854 | createClient | train | function createClient(redisClientOptions) {
const client = redis.createClient(redisClientOptions);
if (!client._options) {
client._options = redisClientOptions;
}
return client;
} | javascript | {
"resource": ""
} |
q39855 | PactPublisher | train | function PactPublisher (configOrVersion, brokerBaseUrl, pacts) {
var _version, _brokerBaseUrl, _pacts;
if (!_.contains(['object', 'string'], typeof configOrVersion)) {
throw new TypeError('Invalid first parameter provided constructing Pact Publisher. Expected a config object or version string for first paramete... | javascript | {
"resource": ""
} |
q39856 | train | function(opts) {
Widget.call(this);
var input = Widget.tag("input");
this._input = input;
var that = this;
this.addClass("wdg-input");
if (typeof opts !== 'object') opts = {};
if (typeof opts.type !== 'string') opts.type = 'text';
input.attr("type", opts.type);
if (typeof op... | javascript | {
"resource": ""
} | |
q39857 | train | function( fileName ) {
// console.log('Read configuration from ' + fileName);
var pathSep = require('path').sep;
var inFileName = process.cwd() + pathSep + fileName;
var config = require( inFileName );
// TODO: validate config
for ( var procs in config ) {
... | javascript | {
"resource": ""
} | |
q39858 | saveSync | train | function saveSync(store, conf) {
try {
this.save(store, conf);
}catch(e) {
log.warning('failed to save rdb snapshot: %s', e.message);
}
} | javascript | {
"resource": ""
} |
q39859 | train | function () {
var emptyFunction = new RegExp(/(\{\s\})|(\{\})/),
publicMethods = {};
for (property in this.settings) {
if (typeof this.settings[property] == 'function' &&
typeof this[property] == 'function') {
var method = t... | javascript | {
"resource": ""
} | |
q39860 | train | function(name) {
if (/[A-Z]/.test(name.charAt(0)))
return "default" + name;
var firstLetter = name.charAt(0);
return "default" + firstLetter.toUpperCase() + name.substring(1);
} | javascript | {
"resource": ""
} | |
q39861 | train | function (primary, secondary) {
var primary = primary || {};
for (var property in secondary)
if (secondary.hasOwnProperty(property))
primary[property] = secondary[property];
return primary;
} | javascript | {
"resource": ""
} | |
q39862 | train | function (event) {
var self = this;
if (this.invalidElements.length > 0)
event.preventDefault();
// Even if the invalidElements count
// does not indicate any invalidated
// elements, the plugin should make
// sure that there are no... | javascript | {
"resource": ""
} | |
q39863 | train | function(event) {
var target = event.target;
if (this.checkElementByPattern(target)) {
if (this.invalidElements.indexOf(target) > -1)
this.invalidElements.splice(this.invalidElements.indexOf(target), 1);
this.publicInterface.onValidation([targe... | javascript | {
"resource": ""
} | |
q39864 | train | function (event) {
// Check if the node is a child of the plugin's element.
if (event.relatedNode === this.element) {
var attributeValues = event.target.getAttribute("data-validate");
if (attributeValues !== null) {
attributeValues = this.split... | javascript | {
"resource": ""
} | |
q39865 | train | function (elements, legend) {
var elements = elements || [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].classList.contains(this.stylings.error) === false)
elements[i].classList.add(this.stylings.error);
var legend = elements[i]... | javascript | {
"resource": ""
} | |
q39866 | train | function (elements) {
var elements = elements || [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].classList.contains(this.stylings.error)) {
elements[i].classList.remove(this.stylings.error);
var parent = elements[i].parentNo... | javascript | {
"resource": ""
} | |
q39867 | train | function (elements, attribute, value) {
var foundElements = [], value = value || null;
for (i = 0; i < elements.length; i++) {
// If the value parameter is set, return only the
// elements that has the given attribute value.
if (value !== null) {
... | javascript | {
"resource": ""
} | |
q39868 | train | function (elements, attribute) {
var foundElements = {};
for (i = 0; i < elements.length; i++) {
var attributeValues = elements[i].getAttribute(attribute);
if (attributeValues === undefined || attributeValues === null)
continue;
... | javascript | {
"resource": ""
} | |
q39869 | train | function (element) {
// Begin with checking the validate
var elementAsArray = [ element ],
validationType = element.getAttribute("data-validate") || null;
invalidElement = [];
if (validationType !== null) {
validationType = this.splitSt... | javascript | {
"resource": ""
} | |
q39870 | requireDependencies | train | function requireDependencies(dependencies) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var promise = new _es6Promise.Promise(function (succeed, fail) {
var requirements = {};
// no requirements
if (!(dependencies instanceof Array)) {
... | javascript | {
"resource": ""
} |
q39871 | definePackage | train | function definePackage(name, dependencies, callback) {
// Adjust arguments
if (typeof name === "function") {
callback = name;
name = null;
dependencies = null;
} else if (typeof dependencies === "function") {
callback = dependencies;
dependencies = null;
if (... | javascript | {
"resource": ""
} |
q39872 | wrapAll | train | function wrapAll(callback) {
// Prepare packages
var packs = {};
packages.forEach(function (pack, name) {
packs[name] = pack;
});
return callback(packs);
} | javascript | {
"resource": ""
} |
q39873 | isEmptyObject | train | function isEmptyObject(obj) {
if (obj === null) {
return true;
}
if (!isObject(obj)) {
return false;
}
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q39874 | dashToCamelCase | train | function dashToCamelCase(dashCase) {
if (!dashCase) { return dashCase; }
var parts = dashCase.split('-');
var camelCase = parts[0];
var part;
for (var i = 1; i < parts.length; i++) {
part = parts[i];
camelCase += part.substring(0, 1).toUpperCase() + part.substring(1);
}
re... | javascript | {
"resource": ""
} |
q39875 | train | function (route, parameters) {
return new Promise((resolve, reject) => {
request.get({
url: baseUrl + route + '?' + querystring.stringify(parameters)
}, (error, response, body) => {
if (error) {
reject(error);
} else ... | javascript | {
"resource": ""
} | |
q39876 | train | function (route, parameters) {
return new Promise((resolve, reject) => {
request.post({
url: baseUrl + route,
qs: parameters
}, (error, response, body) => {
if (error) {
reject(error);
} else { resolve... | javascript | {
"resource": ""
} | |
q39877 | GET | train | function GET(uri, params) {
const reqUrl = `${uri}${url.format({ query: params })}`;
log(`request URL: ${reqUrl}`);
return fetch(reqUrl)
.then(function handleGetRequest(res) {
const status = res.status;
const statusText = res.statusText;
log(`status code: ${status}`);
log(`status text: ${statusText}... | javascript | {
"resource": ""
} |
q39878 | jsonSchemaTypeToGraphQL | train | function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) {
if (jsonSchemaType === "array") {
if (graphQLObjectTypes[schemaName]) {
return new GraphQLList(graphQLObjectTypes[schemaName]);
} else {
const translated = {
pilots: "people",
characters: "people",
residents: "p... | javascript | {
"resource": ""
} |
q39879 | fetchPageOfType | train | function fetchPageOfType(typePluralName, pageNumber) {
let url = `http://swapi.co/api/${typePluralName}/`;
if (pageNumber) {
url += `?page=${pageNumber}`;
};
return restLoader.load(url).then((data) => {
// Paginated results have a different shape
return data.results;
});
} | javascript | {
"resource": ""
} |
q39880 | rgb2hsl | train | function rgb2hsl() {
const
R = this.R,
G = this.G,
B = this.B,
min = Math.min( R, G, B ),
max = Math.max( R, G, B ),
delta = max - min;
this.L = 0.5 * ( max + min );
if ( delta < 0.000001 ) {
this.H = 0;
this.S = 0;
} else {... | javascript | {
"resource": ""
} |
q39881 | getConf | train | function getConf( path, environment, callback, context ) {
// relative paths need to be auto-prefixed with the environment
if ( path.match( /^[^\.]/ ) ) {
path = "." + environment + "." + path;
}
if ( !context ) {
context = {
pathsSeen: {}
};
}
// avoid circular references
if ( context.pathsSeen[path... | javascript | {
"resource": ""
} |
q39882 | getPath | train | function getPath( req, res, next ) {
var path = req.path.replace( /\..*$/, '' ).replace( /\//g, '.' ).replace( /^\.conf/, '' ).replace( /\.$/, '' ).trim();
if ( path.length < 1 ) {
path = null;
}
var outputFilter = req.path.trim().match( /\.(.*)$/ );
if ( outputFilter ) {
outputFilter = outputFilter[1].trim... | javascript | {
"resource": ""
} |
q39883 | configureExpress | train | function configureExpress() {
// create configuration routes
moduleConfig.express.get( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onGetConf ) );
moduleConfig.express.post( /^\/conf.*/, storeRequestBody, checkAuth, getPath, getMiddlewareWrapper( onPostConf ) );
moduleConfig.express.delete( /^\/conf.*/, ... | javascript | {
"resource": ""
} |
q39884 | getMiddlewareWrapper | train | function getMiddlewareWrapper( middleware ) {
return function ( req, res, next ) {
try {
middleware( req, res, next );
}
catch ( e ) {
getResponder( req, res )( 500 );
}
};
} | javascript | {
"resource": ""
} |
q39885 | getResponder | train | function getResponder( req, res ) {
return function ( code, body, contentType ) {
if ( code !== 200 ) {
body = "";
contentType = "text/html; charset=utf-8";
}
if ( !contentType ) {
contentType = "text/html; charset=utf-8";
}
res.writeHead( code, {
"Content-type": contentType
} );
res.end... | javascript | {
"resource": ""
} |
q39886 | SendgridProvider | train | function SendgridProvider(apiUser, apiKey, options) {
if (typeof apiUser !== 'string'
|| typeof apiKey !== 'string') {
throw new Error('Invalid parameters');
}
options = options || {};
if (typeof options.apiSecure === 'undefined')
options.apiSecure = true;
options.apiHostname = options.apiHostname || 'api... | javascript | {
"resource": ""
} |
q39887 | consume | train | function consume(exchangeName, topics, handler) {
// Setup chain
var messageHandler = function(message) {
// make sure we don't have things like buffers
message.content = JSON.parse(message.content.toString());
topics.forEach(function(topic){
statusProvider.setEventConsumeEx... | javascript | {
"resource": ""
} |
q39888 | consumeShared | train | function consumeShared(exchangeName, topics, queueName, handler, fetchCount = 1) {
var messageHandler = function(message) {
// make sure we don't have things like buffers
message.content = JSON.parse(message.content.toString());
topics.forEach(function(topic){
statusProvider.set... | javascript | {
"resource": ""
} |
q39889 | upper | train | function upper (value) {
if (value === null || value === undefined) {
return value
}
return String.prototype.toUpperCase.call(value)
} | javascript | {
"resource": ""
} |
q39890 | iftr | train | function iftr(conditionResult, trueValue, falseValue) {
if (conditionResult && (0, _is.isDefined)(trueValue)) return trueValue;
if (!conditionResult && (0, _is.isDefined)(falseValue)) return falseValue;
} | javascript | {
"resource": ""
} |
q39891 | train | function() {
switch(self.command) {
case constants.WHOIS:
return (self.params[0][0] == 'A');
case constants.PASSWORD:
return true;
case constants.NUMERICINFO:
case constants.GENERALINFO: // client-to-server
... | javascript | {
"resource": ""
} | |
q39892 | merge | train | function merge(need, options, level){
// 如果没有传第三个参数,默认无限递归右边覆盖左边
if (level == undefined) level = -1;
if (options === undefined) options = {};
if (need.length == 1) return need[0];
var res = {};
for (var i = 0; i < need.length; i++){
_merge(res, need[i], options, level - 1);
}
ret... | javascript | {
"resource": ""
} |
q39893 | Loop | train | function Loop(name, deps, fragment, loopFn, options) {
if (!(this instanceof Loop)) {
return new Loop(name, deps, fragment, loopFn, options);
}
Task.apply(this, Array.prototype.slice.call(arguments));
this.fragment = fragment;
this.loopFn = (_.isFunction(loopFn)) ? loopFn : function (input) { return [i... | javascript | {
"resource": ""
} |
q39894 | createTables | train | function createTables() {
// setup config
var config = require('../config/config.js')
var db = wc_db.getConnection(config.db)
var sql = fs.readFileSync('model/Media.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.re... | javascript | {
"resource": ""
} |
q39895 | addMedia | train | function addMedia(uri, contentType, safe) {
if (!uri || uri === '') {
return 'You must enter a valid uri'
}
safe = safe || 0
return new Promise((resolve, reject) => {
var config = require('../config/config.js')
var conn = wc_db.getConnection(config.db)
// sniff content type
if (!contentTyp... | javascript | {
"resource": ""
} |
q39896 | addRating | train | function addRating(rating, config, conn) {
// validate
if (!rating.uri || rating.uri === '') {
return 'You must enter a valid uri'
}
if (!rating.reviewer || rating.reviewer === '') {
return 'You must enter a valid reviewer'
}
if (isNaN(rating.rating)) {
return 'You must enter a valid rating'
... | javascript | {
"resource": ""
} |
q39897 | addMeta | train | function addMeta(params, config, conn) {
params = params || {}
// validate
if (!params.uri || params.uri === '') {
return 'You must enter a valid uri'
}
// defaults
config = config || require('../config/config.js')
debug(params)
// main
// main
return new Promise((resolve, reject) => {
... | javascript | {
"resource": ""
} |
q39898 | addFragment | train | function addFragment(params, config, conn) {
// validate
if ( (!params.id || params.id === '') && (!params.uri || params.uri === '') ) {
return 'You must enter a valid id or uri'
}
// defaults
config = config || require('../config/config.js')
debug(params)
// main
return new Promise((resolve, re... | javascript | {
"resource": ""
} |
q39899 | insertRating | train | function insertRating(rating, config, conn) {
// validate
if ( (!rating.uri || rating.uri === '') && (!rating.cacheURI || rating.cacheURI === '') ) {
return 'You must enter a valid uri'
}
if (!rating.reviewer || rating.reviewer === '') {
return 'You must enter a valid reviewer'
}
// defaults
co... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.