_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q11700
copyNewerSingle
train
async function copyNewerSingle(srcpath, destpath, opts) { let { interval = 1000, verbose = false } = opts let stat = await FS.stat(srcpath) // Stat and check the filesystem entry type. if (stat.isDirectory()) { // Directory, ensure destination exists and return. let made = await mkdirp(destpath) i...
javascript
{ "resource": "" }
q11701
train
function(database, callback){ var dbName = database.databaseName || database.name; var options = {
javascript
{ "resource": "" }
q11702
train
function(collection, callback){ // Prep the collection name. var colName = collection.name.split('.'); var dbName = colName.shift(); colName = colName.join('.'); var database = amityMongo.db.db(dbName); var options = {
javascript
{ "resource": "" }
q11703
loadFileContents
train
function loadFileContents(filePath, preloaded) { //use pre-supplied contents? if (typeof preloaded !== 'undefined' && preloaded !== null) { //return a promise which will get resolved with the preloaded value
javascript
{ "resource": "" }
q11704
returnClient
train
function returnClient(options, ignoreCache) { if (typeof options === 'string') { options = { url: options, usePromise: true }; } if (ignoreCache === true) { return generateClient(options); } const optionsJSON = JSON.stringify(options); if (cachedClients[optionsJSON] instanceof Swag...
javascript
{ "resource": "" }
q11705
parse
train
function parse(data, callback) { var parsed; try { parsed = JSON.parse(data); } catch (e) {
javascript
{ "resource": "" }
q11706
BindingIdentifier
train
function BindingIdentifier(node, parent, scope, state) { if (node.name === state.name)
javascript
{ "resource": "" }
q11707
train
function(name, zoneLetter, cf, vpc, routeTable) { var self = this; self.isPublic = false; base.Base.call(this, cf, 'EC2::Subnet', name); self.addProperty('VpcId', vpc.ref()); self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter)); self.cidrBlock = function(cidr) { self.cidr = v...
javascript
{ "resource": "" }
q11708
stringifyStackTrace
train
function stringifyStackTrace (stackTrace) { var i, len, result = []; for (i = 0, len = stackTrace.length; i < len; i++) { if (stackTrace[i]) {
javascript
{ "resource": "" }
q11709
createInternalConnection
train
function createInternalConnection (mode) { var result; switch (mode) { case 'async': result = require('then-request'); break;
javascript
{ "resource": "" }
q11710
branch
train
function branch () { const headpath = path.join(process.cwd(), '.git/HEAD') if (!fs.existsSync(headpath)) { console.warn('No HEAD found, aborting.') return null } const headcontent = fs.readFileSync(headpath, 'utf8')
javascript
{ "resource": "" }
q11711
train
function(topic, message) { /* * so should a filter manage the last message it has? and give it an ID and store it... * to prevent duplicates... * or should this filter do it... * this shold just execute 1 filter -- NO more than 1. But if a topic matches * multiple filters then we n...
javascript
{ "resource": "" }
q11712
train
function(config) { var em = new RtcConnector(config); var unique = (config && config.unique) ? true : false; l('DEBUG') && console.log('createRtcConnector() config is: ',config); var key = em.key = createKey(em.config.user||null, em.config.password || null, em.config.server || null, em.config.port || null, ...
javascript
{ "resource": "" }
q11713
stringify
train
function stringify() { return map(function (chunk, next) { var stringified; try { stringified = JSON.stringify(chunk); } catch (e) {
javascript
{ "resource": "" }
q11714
deriveSecret
train
function deriveSecret(parent_secret, child_name, hash_algorithm) { if (!hash_algorithm) {
javascript
{ "resource": "" }
q11715
deriveKeypair
train
function deriveKeypair(parent_secret, child_name, signature_scheme) { if (!signature_scheme) { signature_scheme = 'ec_secp256k1'; } var pair = {}; if (signature_scheme === 'ec_secp256k1') { pair.private = deriveSecret(parent_secret, child_name, 'sha256'); // If the private key is greater than th...
javascript
{ "resource": "" }
q11716
sign
train
function sign(private_key, data) { var key = new bitcoinjs.ECKey(new BigInteger(private_key,
javascript
{ "resource": "" }
q11717
verify
train
function verify(public_key, data, signature) { var pubkey = bitcoinjs.ECPubKey.fromHex(public_key); var hash = bitcoinjs.crypto.hash256(new
javascript
{ "resource": "" }
q11718
getSpecificity
train
function getSpecificity(text, parsed) { var expressions = parsed || parse(text), spec = [ 0, 0, 0, 0 ], nots = [], i, expression, pseudos, p, ii, not, jj; for (i = 0; i < expressions.length; i++) { expression = expressions[i]; ...
javascript
{ "resource": "" }
q11719
selectVersion
train
function selectVersion(v1, v2) { return function (firstParam) { // the v1 API took a stream as the first argument if (firstParam instanceof stream.Stream) { return v1.apply(v1, arguments);
javascript
{ "resource": "" }
q11720
evalPromise
train
function evalPromise(promise) { // wrap in `countdown` exports.countdown(promise, timeout) .then(function(resolvedValue) {
javascript
{ "resource": "" }
q11721
train
function (rules) { if (!_.isArray(rules)) { rules = [ rules ]; } var that = this; return _.map(rules, function (rule) { if (typeof rule === 'string') { return that._parseString(rule); } if
javascript
{ "resource": "" }
q11722
train
function (ruleStr) { var name; var params = ''; ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) { name = _name; params = _params.trim(); });
javascript
{ "resource": "" }
q11723
train
function (jsonSource) { var json = null; try { json = JSON.parse(jsonSource); } catch (err) {
javascript
{ "resource": "" }
q11724
eventData
train
function eventData(emitter) { return emitter[eventEmitter.EVENT_DATA_PROPERTY] || Object.defineProperty(emitter, eventEmitter.EVENT_DATA_PROPERTY, {
javascript
{ "resource": "" }
q11725
_createClient
train
function _createClient (name, options, callback) { const log = logger.child({ redis: name }) log.debug('Redis creating client: ' + name) let isReady = false const config = {} deepAssign(config, _defaults, options) let client = redis.createClient(config) callback = _once(callback) _clients[ name ] = cl...
javascript
{ "resource": "" }
q11726
getFileMIME
train
function getFileMIME(file) { var idx = file.lastIndexOf('.') var ext = idx > -1 ? file.slice(idx) : null if
javascript
{ "resource": "" }
q11727
isCharEnglishPunctuation
train
function isCharEnglishPunctuation(char = '') { if (isEmpty(char)) return false; return
javascript
{ "resource": "" }
q11728
expand
train
function expand(property, value, recurse) { ASSERT(arguments.length, 'property argument is required'); if (arguments.length < 3) { if (typeof value === 'boolean') {
javascript
{ "resource": "" }
q11729
normalizeEntity
train
function normalizeEntity(base, input) { if (!input) return {}; var result = Object.assign(clone(input), { class: normalizeClass(input.class), properties: normalizeProperties(input.properties), entities: normalizeEntities(base, input.entities), links: normalizeLinks(base, input.links), actions:
javascript
{ "resource": "" }
q11730
normalizeRel
train
function normalizeRel(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return
javascript
{ "resource": "" }
q11731
normalizeProperties
train
function normalizeProperties(input) { if (!input) return; if (Array.isArray(input)) {
javascript
{ "resource": "" }
q11732
normalizeEntities
train
function normalizeEntities(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (entity) { assert(entity.rel, 'sub-entities must have a rel'); var ret
javascript
{ "resource": "" }
q11733
normalizeLinks
train
function normalizeLinks(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return
javascript
{ "resource": "" }
q11734
normalizeAction
train
function normalizeAction(base, input) { assert(input.name, 'actions must have a name'); assert(input.href, 'actions must have an href'); var ret = clone(input); ret.href =
javascript
{ "resource": "" }
q11735
normalizeActions
train
function normalizeActions(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return
javascript
{ "resource": "" }
q11736
normalizeFields
train
function normalizeFields(input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return
javascript
{ "resource": "" }
q11737
registerExtension
train
function registerExtension(extension) { try { var ext; // Actual extension if (is(extension, 'buildCore', 'function')) { // If extension has buildCore function then give it an instance of the core. extension.buildCore(self); addOne(extensions, extension); ...
javascript
{ "resource": "" }
q11738
buildSandbox
train
function buildSandbox(id) { if (!has(id)) { throw new Error('Sandbox name is required to build a sandbox.'); } // Create module instance specific sandbox var sandbox = { type: self.type, object: self.object, array: self.array, log: self.log }; // Add ext...
javascript
{ "resource": "" }
q11739
handleErrorRequest
train
function handleErrorRequest(result, req, res) { const err = _.isError(result.msg) ? result.msg : result; const finalResp = STATUSES[result.status] || STATUSES[err.message] || STATUSES['error']; finalResp.msg = err.message; if (isDebug) finalResp.ext = err;
javascript
{ "resource": "" }
q11740
json
train
function json (opts) { return { ...opts, headers: { ...opts.headers,
javascript
{ "resource": "" }
q11741
error
train
function error (response, status, message) { let e = new Error(`${status}: ${message}`)
javascript
{ "resource": "" }
q11742
getJSON
train
function getJSON (response) { return response.json().then((body) => { if (body.status !== 'ok') {
javascript
{ "resource": "" }
q11743
getSessionCookie
train
function getSessionCookie (headers) { if (!headers) return
javascript
{ "resource": "" }
q11744
getCsrf
train
function getCsrf (opts) { // for testing if (opts._simulateMaintenance) { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Could not find CSRF
javascript
{ "resource": "" }
q11745
doLogin
train
function doLogin (opts, csrf, email, password) { return fetch(`${opts.host}/_/auth/login`, json({ ...opts, method: 'post', body: { csrf, email, password } })).then((response) => props({
javascript
{ "resource": "" }
q11746
modifyProperties
train
function modifyProperties(schema, paths) { if (!paths.length) { return; } const options = paths[0].options; /** * Modify document enum (string) properties to an object, with (original) value and * values (enumValues) * */ function populatePropertyFor (documents, next) { if (this._mongooseOptions.l...
javascript
{ "resource": "" }
q11747
reformatUpdateProperty
train
function reformatUpdateProperty(next) { const document = this._update['$set']; if (document) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); if (document[key] === undefined) { return;
javascript
{ "resource": "" }
q11748
findPaths
train
function findPaths(schema, options) { const paths = []; schema.eachPath(function(path, type) { if (type.enumValues && type.enumValues.length) { paths.push( { path: path,
javascript
{ "resource": "" }
q11749
setVirtuals
train
function setVirtuals(schema, paths) { paths.forEach(path => { const props = path.options.virtual.properties; if (props[path.path]) {
javascript
{ "resource": "" }
q11750
attachProperties
train
function attachProperties(schema, paths) { paths.forEach(path => { const props = path.options.attach.properties; if (props[path.path]) { (props[path.path].on || []).forEach(on => { /** * Setup post callbacks */ schema.post(on, function(documents, next) {
javascript
{ "resource": "" }
q11751
determineValue
train
function determineValue(keys, doc) { try { for (const key of keys) { doc = doc[key]; } /** the keys array should transition through any nesting, so any object is assumed to be enumValues:
javascript
{ "resource": "" }
q11752
nest
train
function nest(array, insert) { let obj; array.reverse().forEach(key => { obj = {
javascript
{ "resource": "" }
q11753
setOptions
train
function setOptions(schema, options) { function setDefaults(array) { if (!array.length) { if (options.find) { array.push('find'); } if (options.findOne || !options.find) { array.push('findOne'); } } } options = options || {}; options.only = options.only || []; options.validateBeforeSave ...
javascript
{ "resource": "" }
q11754
parse
train
function parse(options) { var settings = _.extend({ error: true }, options); return map(function (chunk, next) { var parsed;
javascript
{ "resource": "" }
q11755
lerp
train
function lerp (vX, vY, x) { if (x < vX[0]) { // Don't interpolate leftward, Cuellar says this is done on purpose return vY[0]; } var i = search(vX, x, function (a, b) {return a - b;}); if (i >= 0) { // found exact match, no need to interpolate return vY[i]; } else { // when not found, bi...
javascript
{ "resource": "" }
q11756
eliminate
train
async function eliminate(dir) { const stat = await lstat(dir); if (!stat.isDirectory()) { await unlink(dir); return; } const files = await readdir(dir); for (const file of files) { const path =
javascript
{ "resource": "" }
q11757
JSXAttribute
train
function JSXAttribute(node, print) { print.plain(node.name); if (node.value) {
javascript
{ "resource": "" }
q11758
JSXElement
train
function JSXElement(node, print) { var open = node.openingElement; print.plain(open); if (open.selfClosing) return; this.indent(); var _arr = node.children;
javascript
{ "resource": "" }
q11759
JSXOpeningElement
train
function JSXOpeningElement(node, print) { this.push("<"); print.plain(node.name); if (node.attributes.length > 0) { this.push(" ");
javascript
{ "resource": "" }
q11760
BlockStatement
train
function BlockStatement(node, print) { this.push("{"); if (node.body.length) { this.newline(); print.sequence(node.body, { indent: true }); if
javascript
{ "resource": "" }
q11761
getTransformer
train
function getTransformer(name) { if (name in transformers) { return transformers[name] } const transformer = toTransformer(name)
javascript
{ "resource": "" }
q11762
renderPartial
train
function renderPartial(name) { // The name is a required input. if (!name) { throw new Error('When calling .partial(), name is required.') } // Ensure the partial is available in the metadata. if (!(name in metalsmith.metadata().partials)) {
javascript
{ "resource": "" }
q11763
filterFile
train
function filterFile(file, done) { if (files[file].partial) { // Discover whether it is explicitly declared as a partial. return done(null, files[file].partial) } else if (opts.pattern) { // Check if it matches the partial pattern.
javascript
{ "resource": "" }
q11764
addPartial
train
function addPartial(filename, done) { // Create a copy of the file and delete it from the database. const file = clone(files[filename]) delete files[filename] // Compile the partial. const info = path.parse(filename) const transform = info.ext ? info.ext.substring(1) : null co...
javascript
{ "resource": "" }
q11765
publishRobotsTxt
train
function publishRobotsTxt () { var path = 'robots.txt'; return fs .statAsync(path) .then(function (pStat) { if (!pStat.isFile()) { // go to our default course of action, that is create robots.txt file throw new Error (); } }) ...
javascript
{ "resource": "" }
q11766
train
function () { var self = this; return function () { var status = self.statusCode; if (status === 0 || (status >= 400 && status < 600)) {
javascript
{ "resource": "" }
q11767
parseURL
train
function parseURL(s) { var url = null; try { url = new URL(s); } catch (error) {
javascript
{ "resource": "" }
q11768
firstObj
train
function firstObj(stream, onEnd) { var data; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); }
javascript
{ "resource": "" }
q11769
first
train
function first(stream, onEnd) { firstObj(stream, function (err, data) { if (err) { return onEnd(err);
javascript
{ "resource": "" }
q11770
firstJson
train
function firstJson(stream, onEnd) { first(stream, function (err, data)
javascript
{ "resource": "" }
q11771
parallel
train
function parallel (promiseFunctions, limit = Infinity, silenceErrors = false) { const contraMethod = (tasks, callback) => concurrent(tasks, limit, callback)
javascript
{ "resource": "" }
q11772
generatePromise
train
function generatePromise (promiseFunctions, contraMethod, silenceErrors) { return new Promise((resolve, reject) => { // Generate a function that executes the promise function and // calls back in a way that the contra library requires for (let i in promiseFunctions) { let promiseFunction = promiseFu...
javascript
{ "resource": "" }
q11773
createSeekPathSrc
train
function createSeekPathSrc(target) { return ( '"use strict";\n' + //go fast sauce! target.map(function (e, i) { return ' var k'+i+' = Buffer.from('+ JSON.stringify(e) +');' //strings only! }).join('\n') + '\n'+ " return function
javascript
{ "resource": "" }
q11774
Module
train
function Module(moduleId, ctx, combineConfig) { this.moduleId = moduleId; this.compiler = ctx; this.combineConfig = combineConfig
javascript
{ "resource": "" }
q11775
train
function(files) { var collection = {}; files.forEach(function(file) { var filename = file.name; if (!collection.hasOwnProperty(filename) || collection[filename].version < file.version) { collection[filename]
javascript
{ "resource": "" }
q11776
plugin
train
function plugin(options) { return function(files, metalsmith, done) { Object.keys(files).forEach(function(file) {
javascript
{ "resource": "" }
q11777
KevoreeCore
train
function KevoreeCore(resolver, kevscript, loggerFactory) { if (!resolver || !kevscript || !loggerFactory) { throw new Error('KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory'); } this.resolver = resolver; this.loggerFactory = loggerFactory; this.log = loggerFactory.create('Cor...
javascript
{ "resource": "" }
q11778
filter
train
function filter(condition) { var cb = makeAsync(condition, 2); return through.obj(function (chunk, enc, next) { cb(chunk, function (err, keep) { if (err) { return next(err); }
javascript
{ "resource": "" }
q11779
fromArray
train
function fromArray(source) { var data; if (!Array.isArray(source)) { throw new TypeError('Expected `source` to be an array.'); } // Copy the source array so we
javascript
{ "resource": "" }
q11780
Delegate
train
function Delegate(subscribed, unsubscribed) { var handlers = []; function callable(handler) { if (arguments.length !== 1) { throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)'); } else if (typeof handler !== 'function') { throw new Error('Delegate argument must ...
javascript
{ "resource": "" }
q11781
_decompressName
train
function _decompressName(buf, offset) { var name = ''; var bytes = 0; var octet = buf.readUInt8(offset + bytes); bytes += 1; // The name is made up of a variable number of labels. Each label begins // with a length octet. The string of labels is ended by a zero length octet. while (octet) { var la...
javascript
{ "resource": "" }
q11782
_decodeName
train
function _decodeName (name) { var encoded = name; var periodIndex = name.indexOf('.'); if (periodIndex > -1) { encoded = name.slice(0, periodIndex); } var decoded = ''; var suffix = 0; var charValue = 0;; for (var i = 0, n = encoded.length; i < n; ++i) { // decode char to first nibble if ...
javascript
{ "resource": "" }
q11783
fromPromise
train
function fromPromise(source) { var callCount = 0; // Throw an error if the source is not a promise if ( typeof source !== 'object' || source === null || typeof source.then !== 'function' ) { throw new TypeError('Expected `source` to be a promise.'); } return new Readable({ objectMode: ...
javascript
{ "resource": "" }
q11784
wait
train
function wait(type) { var that = this, config = this.asyncConfig; if (type !== 'series') { type = 'parallel'; } // Indicate we're going to have to wait config.async = type; function next(err) {
javascript
{ "resource": "" }
q11785
parse
train
function parse (str) { if (Buffer.isBuffer(str)) str = str.toString(); type('str', str, 'String'); try { return JSON.parse(str); } catch (ex) { ex.message
javascript
{ "resource": "" }
q11786
train
function (obj) { obj = obj || {}; var exts = Array.prototype.slice.call(arguments, 1); for (var k=0; k<exts.length; k++) {
javascript
{ "resource": "" }
q11787
train
function (time, n) { time = Number(time) || 0; n = n || 2; if (n === 2) { time = time < 10 ? time + '0' : time; } else if (n === 3) { time = time < 10 ? time + '00'
javascript
{ "resource": "" }
q11788
train
function (level) { if (!level || typeof level !== 'object') { throw new Error('The first parameter must be an object describing the level.'); } if (typeof level.name !== 'string' || !level.name.length) {
javascript
{ "resource": "" }
q11789
IssueFinder
train
function IssueFinder(options) { this.octo = options.octo; this.repo = options.repo; this.owner = options.owner;
javascript
{ "resource": "" }
q11790
_setupSerialConnection
train
function _setupSerialConnection() { var port = availablePorts[0]; debug.log('Trying to connect to Davis VUE via port: ' + port); // Open serial port connection var sp = new serialPort(port, config.serialPort); var received = ''; sp.on('open', function () { debug.log('Serial connection established, w...
javascript
{ "resource": "" }
q11791
doSign
train
function doSign(params, xKey, message, generateHash) { // Let H be the hashing function and m the message: // Generate a random per-message value k where 1<k<q // Calculate r = (g^k mod p) mod q // In the unlikely case that r=0, start again with a different random k // Calculate s = k^(-1) * ( H (m)...
javascript
{ "resource": "" }
q11792
verify
train
function verify(params, yKey, sign, message, generateHash) { // Reject the signature if 0<r<q or 0<s<q is not satisfied. // Calculate w = s ^ (-1) mod q // Calculate u_1 = H(m) * w mod q // Calculate u_2 = r * w mod q // Calculate v = ( (g^u_1 * y^u_2) mod p) mod q // The signature is valid if a...
javascript
{ "resource": "" }
q11793
createAggregator
train
function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray_1(collection) ?
javascript
{ "resource": "" }
q11794
stringJSON2YAML
train
function stringJSON2YAML (doc, compact = false) { if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) { throw new TypeError('Argument must be a string or object, and not empty: ' + doc) }
javascript
{ "resource": "" }
q11795
stringYAML2JSON
train
function stringYAML2JSON (doc, compact = false) { if (!doc || typeof doc !== 'string') { throw new TypeError('Argument must be a string or object, and not empty: '
javascript
{ "resource": "" }
q11796
stringJSON2JSON
train
function stringJSON2JSON (doc, compact = false) { if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) { throw new TypeError('Argument must be a string or object, and not empty: ' + doc) }
javascript
{ "resource": "" }
q11797
stringYAML2YAML
train
function stringYAML2YAML (doc, compact = false) { if (!doc || typeof doc !== 'string') { throw new TypeError('Argument must be a string or object, and not empty: '
javascript
{ "resource": "" }
q11798
fuzzyStringCompare
train
function fuzzyStringCompare(a, b, tolerence) { if (a == b) return true; var as = stripNoise(a); as = as.toLowerCase(); if (as.length > 255) as = as.substr(0, 255); var bs = stripNoise(b); bs = bs.toLowerCase(); if (bs.length > 255) bs =
javascript
{ "resource": "" }
q11799
splitAuthor
train
function splitAuthor(author) { return author .split(/\s*[,\.\s]\s*/) .filter(function(i) { return !!i }) // Strip out blanks .filter(function(i)
javascript
{ "resource": "" }