_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41200
train
function(href) { var _this = this; return Q.nfcall(request, href).then(function(data) { var $ = cheerio.load(data); var serviceName = $('.collection') .first() .text() .trim() .replace(/\./g, ''); var serviceDescription = $('h1').nextAll('p').first().text(); _this.services.push(serviceName); var ret = { serviceName: serviceName, description: serviceDescription, methods: [] }; // Extract method information $('.full_method').each(function() { var $el = $(this); var collection = $el.find('.collection') .text().replace('.','').trim(); var method = $el.find('.method').text().trim(); var description = $el.nextAll('p').first().text(); var $table = $el.nextAll('table.table-striped').first(); var methodInfo = { name: method, description: description, params: [] }; // Fix for documentation not having api keys if (serviceName == 'DiscountService') methodInfo.params.push('apiKey'); // iterate over all the paramters $table.find('tbody tr').each(function() { var td = $(this).find('td').first().text().trim(); if (td != 'Key' && td != 'privateKey' && td != 'key') methodInfo.params.push(td); else methodInfo.params.push('apiKey'); }); ret.methods.push(methodInfo); }); return ret; }); }
javascript
{ "resource": "" }
q41201
generateLockName
train
function generateLockName() { let subMark = Math.floor(Math.random() * 1000).toString(36) return `Lock:${Date.now().toString(36)}:${subMark}` }
javascript
{ "resource": "" }
q41202
parseResponse
train
function parseResponse(mystemResponse) { var mystemResponseFacts = mystemResponse.slice(mystemResponse.indexOf("{") + 1, -1), factRegexp = /([^,]+\([^)]+\)|[^,]+)/g, facts = [], fact; while (fact = factRegexp.exec(mystemResponseFacts)) { facts.push(fact[0]); } var result = { mystemResponse: mystemResponse, facts: facts.concat() }; var firstFact = facts.shift().split('='); result.stem = firstFact[0].replace(/\?*$/, ""); return result; }
javascript
{ "resource": "" }
q41203
applyEvents
train
function applyEvents(context, child, data) { var events = context.events[child.name]; if (events !== undefined && child.el !== undefined && child.data.type !== 'cp') { events.forEach((event)=> { context._events.push(child.on(event.name, event.action, context, data)); }); } }
javascript
{ "resource": "" }
q41204
train
function (file) { var match = pattern.exec(basename(file)); return { date: match[1], url: match[2] }; }
javascript
{ "resource": "" }
q41205
train
function (userOptions) { var defaultOptions = { ignore: [], collection: null, jekyllStyleLayout: true }; for (var opt in userOptions) defaultOptions[opt] = userOptions[opt]; return defaultOptions; }
javascript
{ "resource": "" }
q41206
getClosestFormName
train
function getClosestFormName(element) { var parent = element.parent(); if(parent[0].tagName.toLowerCase() === 'form') { return parent.attr('name') || null; } else { return getClosestFormName(parent); } }
javascript
{ "resource": "" }
q41207
Subscriber
train
function Subscriber(opts) { opts = opts || {}; this._channel = opts.channel || 'default'; this._subscribers = []; /* for mocking */ var addEventListener = opts.addEventListener || window.addEventListener; var attachEvent = opts.attachEvent || window.attachEvent; var _this = this; function onMessage(e) { var event = parse(e.data); if (event.channel === _this._channel) { for (var i = 0, len = _this._subscribers.length; i < len; i++) { _this._subscribers[i].apply({}, event.args); } } } if (addEventListener) { addEventListener('message', onMessage, false); } else { attachEvent('onmessage', onMessage, false); } }
javascript
{ "resource": "" }
q41208
train
function(keys){ console.log('\nInitializing keys in Redis...\n') keys.forEach(function(el,i){ client.get(el.key, function(e,d){ if(e) { console.log("Error trying to get %s ", el.key) return console.error(e) } // checking for falsey values only is a bad idea if(typeof d === 'undefined'){ console.log("Not OK trying to get %s ", el.key) client.set(el.key, el.initialValue, function(e,d){ if(e) { console.log("Error trying to set %s ", el.key) return console.error(e) } if(d !== 'OK') { console.log("Not OK trying to set %s ", el.key) return console.warn(el.key + " was not set.") } if(d === 'OK') { console.log("OK setting %s ", el.key) client.get(el.key, function(e,d){ console.log(d) }) } }) // end set. } console.log("The value for key %s is %s", el.key.yellow, d.green) }) // end get }) }
javascript
{ "resource": "" }
q41209
train
function(userObj, setname, hashPrefix, cb){ console.log("\nCreating new user account %s", userObj.network.username) /* userObj = { network: { type : 'facebook', first_name: 'Joe', last_name: 'McCann', username: 'joemccann', full_name: 'Joe McCann' }, email_address: 'joseph.isaac@gmail.com', oauth: {} } */ // TODO: CHECK IF HASH EXISTS // Schema should be: var schema = { uuid: null, networks: { twitter: {}, facebook: {}, instagram: {}, flickr: {}, dropbox: {}, google_drive: {} }, email_addresses: [], cache: { twitter: null, facebook: null, instagram: null, flickr: null, dropbox: null, google_drive: null } } // Generate unique user id schema.uuid = sha1(redisConfig.salt, userObj.email_address) // "Official" email address is schema.email_addresses[0] // Add it to the email addresses for the user schema.email_addresses.push(userObj.email_address) // Let's client.sadd(setname, schema.uuid, function(e,d){ if(cb){ return cb(e,d) } userSetAddHandler(e,d) client.hmset(hashPrefix +":"+schema.uuid, userObj, hmsetCb || userSetHashHandler) }) }
javascript
{ "resource": "" }
q41210
train
function(userObj, setname, hashPrefix, cb){ // client.srem('users',userObj.uuid, redis.print) var _uuid = sha1('photopipe', userObj.email_address) client.srem(setname, _uuid, function(e,d){ if(cb){ return cb(e,d) } userSetRemoveHandler(e,d) client.hdel(hashPrefix+':'+_uuid, userObj, userDeleteHashHandler) }) }
javascript
{ "resource": "" }
q41211
train
function(e,d){ if(e){ console.log("User set add data response: %s", d) e && console.error(e) return } console.log("User set add data response with no error: %s", d) }
javascript
{ "resource": "" }
q41212
decorate
train
function decorate (fn) { return async function (...args) { try { return fn.call(this, ...args); } catch (err) { this.logger && this.logger.error(err.message); throw err; } }; }
javascript
{ "resource": "" }
q41213
start
train
function start() { proc = spawn(procCommand, procArgs, procOptions); var onClose = function (code) { if (!restarting) { process.exit(code); } start(); restarting = false; }; proc.on('error', function () { debug('restarting due error'); restarting = true; proc.kill('SIGINT'); }); proc.on('close', onClose); }
javascript
{ "resource": "" }
q41214
commonSequence
train
function commonSequence(a, b){ var result = []; for (var i = 0; i < Math.min(a.length, b.length); i++){ if (a[i] === b[i]){ result.push(a[i]); } else { break; } } return result; }
javascript
{ "resource": "" }
q41215
generator
train
function generator(url) { var randomnesss = Crypto.randomBytes(24); randomnesss.writeDoubleBE(Date.now(), 0); randomnesss.writeUInt32BE(process.pid, 8); var output = randomnesss.toString('base64'); // URL safe if (url) { output = output.replace(/\//g, '_'); output = output.replace(/\+/g, '-'); } return output; }
javascript
{ "resource": "" }
q41216
Confirm
train
function Confirm(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
javascript
{ "resource": "" }
q41217
mixin
train
function mixin(rework, declarations, mixins) { for (var i = 0; i < declarations.length; ++i) { var decl = declarations[i]; if ('comment' == decl.type) continue; var key = decl.property; var val = decl.value; var fn = mixins[key]; if (!fn) continue; // invoke mixin var ret = fn.call(rework, val); // apply properties for (var key in ret) { var val = ret[key]; if (Array.isArray(val)) { val.forEach(function(val){ declarations.splice(i++, 0, { type: 'declaration', property: key, value: val }); }); } else { declarations.splice(i++, 0, { type: 'declaration', property: key, value: val }); } } // remove original declarations.splice(i--, 1); } }
javascript
{ "resource": "" }
q41218
generateKey
train
function generateKey (args, strictArgMatch = true) { args = Array.from(args) if (strictArgMatch) return args return args.map(arg => maybeStringify(arg)) }
javascript
{ "resource": "" }
q41219
train
function(model) { var fields = _.keys(model); var updated = {}; _.each(fields, function(field) { var updatedField = {}; var modelField = {}; if (!(field === Object(field))) { updatedField.field = field; if (!(model[field] === Object(model[field]))) { modelField = { type: model[field] }; } else { modelField = model[field]; } updatedField = _.defaults(updatedField, modelField); } else { updatedField = field; } updated[updatedField.field] = updatedField; }); return updated; }
javascript
{ "resource": "" }
q41220
rgbToHex
train
function rgbToHex(r, g, b) { var integer = ((Math.round(r) & 0xFF) << 16) + ((Math.round(g) & 0xFF) << 8) + (Math.round(b) & 0xFF); var string = integer.toString(16).toUpperCase(); return '#' + ('000000'.substring(string.length) + string); }
javascript
{ "resource": "" }
q41221
nthWeekDay
train
function nthWeekDay(countDays, weekDay, year, month, day) { let countedDays = 0 if (countDays >= 0) { month = month || 1 let monthStr = String(month) if (monthStr.length === 1) { monthStr = "0" + monthStr } day = day || 1 let dayStr = String(day) if (dayStr.length === 1) { dayStr = "0" + dayStr } // We stay a minute off midnight to avoid dealing with leap seconds. let timestamp = +new Date(`${year}-${monthStr}-${dayStr}T00:01:00Z`) let time for (let i = 0; i < 366; i++) { time = new Date(timestamp) if (time.getDay() === weekDay) {countedDays++} if (countedDays === countDays) {break} timestamp += 24 * 3600 * 1000 } return time } else if (countDays < 0) { countDays = -countDays month = month || 12 let monthStr = String(month) if (monthStr.length === 1) { monthStr = "0" + monthStr } day = day || 31 let dayStr = String(day) if (dayStr.length === 1) { dayStr = "0" + dayStr } // Starting moment, ms. let timestamp = +new Date(`${year}-${monthStr}-${dayStr}T00:01:00Z`) let time for (let i = 366; i >= 0; i--) { time = new Date(timestamp) if (time.getDay() === weekDay) {countedDays++} if (countedDays === countDays) {break} timestamp -= 24 * 3600 * 1000 } return time } }
javascript
{ "resource": "" }
q41222
lastDayOfMonth
train
function lastDayOfMonth(time) { let year = time.getUTCFullYear() let nextMonth = time.getUTCMonth() + 2 if (nextMonth > 12) { year++ nextMonth = 1 } let nextMonthStr = String(nextMonth) if (nextMonthStr.length === 1) { nextMonthStr = '0' + nextMonthStr } let date = new Date(`${year}-${nextMonthStr}-01T00:00:00Z`) return (new Date(+date - 1000)).getUTCDate() }
javascript
{ "resource": "" }
q41223
processKeyProperty
train
function processKeyProperty(propDesc, keyPropContainer) { // get the key property descriptor const keyPropName = propDesc._keyPropertyName; if (!keyPropContainer.hasProperty(keyPropName)) throw invalidPropDef( propDesc, 'key property ' + keyPropName + ' not found among the target object properties.'); const keyPropDesc = keyPropContainer.getPropertyDesc(keyPropName); // validate the key property type if (!keyPropDesc.isScalar() || (keyPropDesc.scalarValueType === 'object')) throw invalidPropDef( propDesc, 'key property ' + keyPropName + ' is not suitable to be map key.'); // set key value type in the map property descriptor propDesc._keyValueType = keyPropDesc.scalarValueType; if (keyPropDesc.isRef()) propDesc._keyRefTarget = keyPropDesc.refTarget; }
javascript
{ "resource": "" }
q41224
train
function(opts) { opts = opts || {}; this.userHandshake = opts.handshake; if(opts.heartbeat) { this.heartbeatSec = opts.heartbeat; this.heartbeat = opts.heartbeat * 1000; } this.checkClient = opts.checkClient; this.useDict = opts.useDict; this.useProtobuf = opts.useProtobuf; this.useCrypto = opts.useCrypto; }
javascript
{ "resource": "" }
q41225
formatError
train
function formatError(err, input) { var msg = err.message.replace(/\s*\(\d*\:\d*\)\s*$/i, ''); // remove line number / col number var bm = ('' + input.slice(0, err.pos)).match(/.*$/i); var am = ('' + input.slice(err.pos)).match(/.*/i); var before = bm ? bm[0] : ''; var after = am ? am[0] : ''; // Prepare line info for txt display var cursorPos = before.length; var lineStr = before + after; var lncursor = []; for (var i = 0, sz = lineStr.length; sz > i; i++) { lncursor[i] = (i === cursorPos) ? '\u005E' : '-'; } var lineInfoTxt = lineStr + '\n' + lncursor.join(''); return { description: msg, lineInfoTxt: lineInfoTxt, code: lineStr, line: err.loc ? err.loc.line : -1, column: err.loc ? err.loc.column : -1 }; }
javascript
{ "resource": "" }
q41226
sn_ui_pixelWidth
train
function sn_ui_pixelWidth(selector) { if ( selector === undefined ) { return undefined; } var styleWidth = d3.select(selector).style('width'); if ( !styleWidth ) { return null; } var pixels = styleWidth.match(/([0-9.]+)px/); if ( pixels === null ) { return null; } var result = Math.floor(pixels[1]); if ( isNaN(result) ) { return null; } return result; }
javascript
{ "resource": "" }
q41227
create
train
function create(loader, shouldReload = defaultShouldReload, mapper = defaultMapper, initialCtx = defaultInitialCtx) { // Initialise context, which is passed around and holds the lastData. const ctx = initialCtx; // TODO: instead of providing a full initial context, the redata() function below should receive // a third argument, initialData, which is stored in the ctx. This allows for composed // redatas to be fed initially. function redata(params, onUpdate) { // console.log('redata()', params); // If should not reload the data. if (!shouldReload(params)) { console.log('will not reload'); // Inform any subscriber. onUpdate && onUpdate(ctx.lastData); // Resolve with last data. return Promise.resolve(ctx.lastData); } console.log('will reload'); // Data not valid, will load new data and subscribe to its updates. // Reset lastData, since it is no longer valid. ctx.lastData = { ...defaultInitialData }; // debugger; // Update any subscriber about new data. onUpdate && onUpdate(ctx.lastData); // Store promise reference in order to check which is the last one if multiple resolve. ctx.promise = load(ctx, loader, params, onUpdate); // console.log('storing ctx promise', ctx.promise); ctx.promise.loader = loader; return ctx.promise; } // Store shouldReload and mapper for future reference in redata compositions. redata.shouldReload = shouldReload; redata.map = mapper; return redata; }
javascript
{ "resource": "" }
q41228
onConnection
train
function onConnection() { var endpoint = new http2.Endpoint(log, 'CLIENT', {}); endpoint.pipe(socket).pipe(endpoint); // Sending request var stream = endpoint.createStream(); stream.headers({ ':method': 'GET', ':scheme': url.protocol.slice(0, url.protocol.length - 1), ':authority': url.hostname, ':path': url.path + (url.hash || '') }); // Receiving push streams stream.on('promise', function(push_stream, req_headers) { var filename = path.join(__dirname, '/push-' + push_count); push_count += 1; console.error('Receiving pushed resource: ' + req_headers[':path'] + ' -> ' + filename); push_stream.pipe(fs.createWriteStream(filename)).on('finish', finish); }); // Receiving the response body stream.pipe(process.stdout); stream.on('end', finish); }
javascript
{ "resource": "" }
q41229
iterateElements
train
function iterateElements(array) { return { __iterator__: function() { var index = 0; var current; return { get current() { return current; }, moveNext: function() { if (index < array.length) { current = array[index++]; return true; } return false; } }; } }; }
javascript
{ "resource": "" }
q41230
validate
train
function validate(method) { var decorated = function validateDecorator() { var params = method.params; var schema = method.schema; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var value = _combineObject(params, args); var normalized = void 0; try { normalized = _joi2.default.attempt(value, schema); } catch (e) { if (method.sync) { throw e; } return _promise2.default.reject(e); } var newArgs = []; // Joi will normalize values // for example string number '1' to 1 // if schema type is number _lodash2.default.each(params, function (param) { newArgs.push(normalized[param]); }); return method.apply(undefined, newArgs); }; return _keepProps(method, decorated); }
javascript
{ "resource": "" }
q41231
decorate
train
function decorate(service, serviceName) { var logger = _config.loggerFactory(serviceName, _config); _lodash2.default.map(service, function (method, name) { method.methodName = name; if (!method.params) { method.params = (0, _getParameterNames2.default)(method); } service[name] = log(validate(method), logger, method); }); }
javascript
{ "resource": "" }
q41232
Interval
train
function Interval(func, options) { this.func = func; this.delay = options.delay || 16; this.lifetime = options.lifetime; this.useRequestAnimationFrame = options.useRequestAnimationFrame && window.requestAnimationFrame && window.cancelAnimationFrame; this.interval = null; this.gcTimeout = null; }
javascript
{ "resource": "" }
q41233
Device
train
function Device (device, sp) { if (!(device && sp)) throw new Error('a Device and a SerialPort must be passed'); for (var i in device) this[i] = device[i]; this._open = false; this._sp = sp; EventEmitter.call(this); }
javascript
{ "resource": "" }
q41234
Exchange
train
function Exchange(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
javascript
{ "resource": "" }
q41235
sortByAttributeNameComparitor
train
function sortByAttributeNameComparitor(a,b) { if (a.attributes.name < b.attributes.name) return -1; if (a.attributes.name > b.attributes.name) return 1; return 0; }
javascript
{ "resource": "" }
q41236
turnOn
train
function turnOn(device) { return api.request('/device/turnOn?' + querystring.stringify({id: device.id || device})); }
javascript
{ "resource": "" }
q41237
turnOff
train
function turnOff(device) { return api.request('/device/turnOff?' + querystring.stringify({id: device.id || device})); }
javascript
{ "resource": "" }
q41238
history
train
function history(device, from, to) { return api.request('/device/history?' + querystring.stringify({id: device.id || device, from: from, to: to})); }
javascript
{ "resource": "" }
q41239
multipart
train
function multipart(options) { options = options || {}; DEBUG && debug('configure http multipart middleware', options); return function (req, res, next) { if (req._body || !req.is('multipart/form-data') || 'POST' !== req.method) { return next(); } DEBUG && debug('got multipart request', req.path); req.form = new multiparty.Form(options); req.form.parse(req, function(err, fields, files) { if (err) { DEBUG && debug('err', err); return next(err); } DEBUG && debug('fields', fields); DEBUG && debug('files', files); req._body = true; req.body = fields; req.files = files; return next(); }); }; }
javascript
{ "resource": "" }
q41240
add
train
function add(appName, domain, callback) { commons.post(format('/%s/apps/%s/domains/', deis.version, appName), { domain: domain.toString() }, callback); }
javascript
{ "resource": "" }
q41241
remove
train
function remove(appName, domain, callback) { var url = format('/%s/apps/%s/domains/%s', deis.version, appName, domain); commons.del(url, callback); }
javascript
{ "resource": "" }
q41242
getAll
train
function getAll(appName, callback) { var url = format('/%s/apps/%s/domains/', deis.version, appName); commons.get(endpoint, callback); }
javascript
{ "resource": "" }
q41243
getDomain
train
function getDomain(domain, callback) { getAll(function onGetAll(err, domains) { if (err) { return callback(err); } callback(null, domains.results.filter(function onGetDomain(domain_obj) { return domain_obj.domain == domain; })[0]); }); }
javascript
{ "resource": "" }
q41244
train
function (target) { var inst = this._getInst(target); if (!inst) { return FALSE; } $("#sbHolder_" + inst.uid).remove(); $.data(target, PROP_NAME, null); $(target).show(); }
javascript
{ "resource": "" }
q41245
train
function (target, value, text) { var inst = this._getInst(target), onChange = this._get(inst, 'onChange'); $("#sbSelector_" + inst.uid).text(text); $(target).find("option[value='" + value + "']").attr("selected", TRUE); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [value, inst]); } else if (inst.input) { inst.input.trigger('change'); } }
javascript
{ "resource": "" }
q41246
train
function (target) { var inst = this._getInst(target); if (!inst || !inst.isDisabled) { return FALSE; } $("#sbHolder_" + inst.uid).removeClass(inst.settings.classHolderDisabled); inst.isDisabled = FALSE; $.data(target, PROP_NAME, inst); }
javascript
{ "resource": "" }
q41247
train
function (target) { var inst = this._getInst(target); if (!inst || inst.isDisabled) { return FALSE; } $("#sbHolder_" + inst.uid).addClass(inst.settings.classHolderDisabled); inst.isDisabled = TRUE; $.data(target, PROP_NAME, inst); }
javascript
{ "resource": "" }
q41248
train
function (target, name, value) { var inst = this._getInst(target); if (!inst) { return FALSE; } //TODO check name inst[name] = value; $.data(target, PROP_NAME, inst); }
javascript
{ "resource": "" }
q41249
train
function (target) { var inst = this._getInst(target); //if (!inst || this._state[inst.uid] || inst.isDisabled) { if (!inst || inst.isOpen || inst.isDisabled) { return; } var el = $("#sbHolder_" + inst.uid), viewportHeight = parseInt($(window).height(), 10), offset = $("#sbHolder_" + inst.uid).offset(), scrollTop = $(window).scrollTop(), height = el.height(), diff = viewportHeight - (offset.top - scrollTop) - height / 2, onOpen = this._get(inst, 'onOpen'); // Commented this out, let html/css handle this // el.css({ // "maxHeight": (diff - height) + "px" // }); el.find(".sbContent").attr('style', 'display: block'); inst.settings.effect === "fade" ? el.fadeIn(inst.settings.speed) : el.slideDown(inst.settings.speed); el.removeClass('closed'); el.addClass('open'); $("#sbToggle_" + inst.uid).addClass(inst.settings.classToggleOpen); this._state[inst.uid] = TRUE; inst.isOpen = TRUE; if (onOpen) { onOpen.apply((inst.input ? inst.input[0] : null), [inst]); } $.data(target, PROP_NAME, inst); }
javascript
{ "resource": "" }
q41250
train
function (target) { var inst = this._getInst(target); //if (!inst || !this._state[inst.uid]) { if (!inst || !inst.isOpen) { return; } var onClose = this._get(inst, 'onClose'); inst.settings.effect === "fade" ? $("#sbOptions_" + inst.uid).fadeOut(inst.settings.speed) : $("#sbOptions_" + inst.uid).slideUp(inst.settings.speed); $("#sbToggle_" + inst.uid).removeClass(inst.settings.classToggleOpen); var holder = $("#sbHolder_" + inst.uid); holder.removeClass('open'); holder.addClass('closed'); this._state[inst.uid] = FALSE; inst.isOpen = FALSE; if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [inst]); } $.data(target, PROP_NAME, inst); }
javascript
{ "resource": "" }
q41251
train
function(target) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); return { id: id, input: target, uid: Math.floor(Math.random() * 99999999), isOpen: FALSE, isDisabled: FALSE, settings: {} }; }
javascript
{ "resource": "" }
q41252
checkHttpCode
train
function checkHttpCode(expected, res, body, callback) { if (res.statusCode !== expected) { if (!body) { return callback(new Error(format('Unexpected deis response (expected %s but %s was returned)', expected, res.statusCode))); } var error = body.hasOwnProperty('detail') ? body.detail : JSON.stringify(body); return callback(new Error(error)); } return callback(null, body); }
javascript
{ "resource": "" }
q41253
compareVersions
train
function compareVersions(versions) { // 1) get common precision for both versions, for example for "10.0" and "9" it should be 2 var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1])); var chunks = map(versions, function (version) { var delta = precision - getVersionPrecision(version); // 2) "9" -> "9.0" (for precision = 2) version = version + new Array(delta + 1).join(".0"); // 3) "9.0" -> ["000000000"", "000000009"] return map(version.split("."), function (chunk) { return new Array(20 - chunk.length).join("0") + chunk; }).reverse(); }); // iterate in reverse order by reversed chunks array while (--precision >= 0) { // 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true) if (chunks[0][precision] > chunks[1][precision]) { return 1; } else if (chunks[0][precision] === chunks[1][precision]) { if (precision === 0) { // all version chunks are same return 0; } } else { return -1; } } }
javascript
{ "resource": "" }
q41254
isUnsupportedBrowser
train
function isUnsupportedBrowser(minVersions, strictMode, ua) { var _bowser = bowser; // make strictMode param optional with ua param usage if (typeof strictMode === 'string') { ua = strictMode; strictMode = void(0); } if (strictMode === void(0)) { strictMode = false; } if (ua) { _bowser = detect(ua); } var version = "" + _bowser.version; for (var browser in minVersions) { if (minVersions.hasOwnProperty(browser)) { if (_bowser[browser]) { if (typeof minVersions[browser] !== 'string') { throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions)); } // browser version and min supported version. return compareVersions([version, minVersions[browser]]) < 0; } } } return strictMode; // not found }
javascript
{ "resource": "" }
q41255
sendCommand
train
function sendCommand(method, url, payload, skipQueue) { if (!self.connected) { debug('Queueing %s %s', method, url); return new P(function(resolve, reject) { var p = P.method(function() { debug('Dequeueing %s %s', method, url); return _sendCommand(method, url, payload) .then(resolve) .catch(reject); }); if (skipQueue) { pendingCommands.splice(0, 0, p); } else { pendingCommands.push(p); } }); } return _sendCommand(method, url, payload); }
javascript
{ "resource": "" }
q41256
sequencer
train
function sequencer (ctx, callback) { var timer, iterable, iterator, nextTick, tempo, tickInterval, lookahead function emit (event, data, time, duration) { setTimeout(function () { callback(event, data, time, duration) }, 0) } function sequence (data) { if (!data) iterator = rangeIterator(0, Infinity) else if (typeof data === 'function') iterator = data else if (Math.floor(data) === data) iterator = rangeIterator(0, data) else if (typeof data === 'string') iterator = arrayIterator(data.split(' ')) else if (Array.isArray(data)) iterator = arrayIterator(data) else iterator = arrayIterator([ data ]) return sequence } sequence.tempo = function (newTempo) { if (arguments.length === 0) return tempo tempo = newTempo tickInterval = 60 / tempo lookahead = tickInterval * 0.1 return sequence } sequence.start = function () { if (!timer) { iterable = iterator() nextTick = ctx.currentTime + lookahead emit('start', null, nextTick) timer = setInterval(schedule, lookahead) } return sequence } sequence.stop = function () { if (timer) { clearInterval(timer) timer = null emit('stop') } return sequence } function schedule () { var current = ctx.currentTime var ahead = current + lookahead if (nextTick >= current && nextTick < ahead) { var n = iterable.next() if (n.done) { sequence.stop() } else { callback('data', n.value, nextTick, tickInterval) } nextTick += tickInterval } } return sequence().tempo(120) }
javascript
{ "resource": "" }
q41257
_checkExitCode
train
function _checkExitCode(result, test) { var actual = result.exitcode; var expect = test.exitcode; var error; if (typeof expect === 'string') { expect = parseInt(expect, 10); } if (expect !== undefined && expect !== actual) { error = util.format('Exit code %d does not match expected %d', actual, expect); } return error; }
javascript
{ "resource": "" }
q41258
check
train
function check(result, test) { const CHECKERS = [ _checkExitCode, _checkOutput, _checkStdout, _checkStderr ]; var errors = []; CHECKERS.forEach(function (checker) { var error = checker(result, test); if (error) { errors.push(error); } }); return errors; }
javascript
{ "resource": "" }
q41259
train
function (obj) { if (typeof obj === 'undefined') { obj = this.getConfig(); delete obj.class; } if (typeof obj == 'object') { delete obj.autoInit; delete obj.id; delete obj.serverID; delete obj.modulePath; for (o in obj) { this.exportConfig(obj[o]); } } return JSON.stringify(obj, null, '\t'); }
javascript
{ "resource": "" }
q41260
train
function (filePath) { if (typeof arguments[1]=='function') var cb = arguments[1]; if (typeof arguments[2]=='function') var cb = arguments[2]; var binary = typeof arguments[1]=='boolean' ? arguments[1] : false, realPath = this.instanceOf('wnModule')?this.modulePath+filePath:filePath, cmd = !cb ? 'readFileSync' : 'readFile'; try { var _cb = cb ? function (err,file) { cb&&cb(!err ? ((binary===true) ? file : file.toString()) : false); } : null, file = fs[cmd](realPath,_cb); } catch (e) { if (_cb) cb&&cb(false); else return false; } return (file ? (binary===true) ? file : file.toString() : false); }
javascript
{ "resource": "" }
q41261
train
function (filePath,cb) { var realPath = this.instanceOf('wnModule')?this.modulePath+filePath:filePath, cmd = !cb ? 'statSync' : 'stat'; if (!fs.existsSync(realPath)) return (cb&&cb(false) == true); var _cb = cb ? function (err,stat) { cb&&cb(!err ? stat : false); } : null, stat = fs[cmd](realPath,_cb); return stat; }
javascript
{ "resource": "" }
q41262
train
function () { this.e.log&&this.e.log('Preloading events...','system'); var preload = {}; _.merge(preload,this.defaultEvents); _.merge(preload,this.getConfig().events); if (preload != undefined) this.setEvents(preload); for (e in preload) { this.getEvent(e); } this.attachEventsHandlers(); return this; }
javascript
{ "resource": "" }
q41263
train
function (className,config,path,npmPath) { var source = this.c || process.wns; var instance; var builder = this.getComponent&&this.getComponent('classBuilder'); if (!source || !source[className]) { return false; } if (config.id) source[className].build.id = config.id; if (source[className].build.extend.indexOf('wnModule')!==-1) { instance = new source[className](self,config,path,npmPath,builder.classesPath); } else instance = new source[className](config,source); if (WNS_TEST && builder) { console.log('- Testing '+className) var tests = builder.classes[className].test; for (t in tests) { //console.log('Testing: '+t); tests[t](instance); } } return instance; }
javascript
{ "resource": "" }
q41264
train
function () { this.e.log&&this.e.log("Attaching default event's handlers...",'system'); var events = this.getEvents(); for (e in events) { var eventName = e.split('-').pop(), event = this.getEvent(eventName), evtConfig = event.getConfig(); if (evtConfig.handler != null && this[evtConfig.handler] && typeof this[evtConfig.handler] == 'function') { event.addListener(this[evtConfig.handler]); event.setConfig({ handler: null }); } if (evtConfig.listenEvent != null && e.indexOf('event-module') == -1 && this.hasEvent(evtConfig.listenEvent)) { var listenTo = this.getEvent(evtConfig.listenEvent), listenName = evtConfig.listenEvent+''; listenTo.addListener(function (e) { if (typeof e == 'object' && e.stopPropagation == true) return false; this.event.emit.apply(this.event,arguments); }.bind({ event: event })); event.setConfig({ listenEvent: null }); } } }
javascript
{ "resource": "" }
q41265
train
function (events) { var event = {}; for (e in events) { var ref=events[e], e = 'event-'+e.replace('-','.'); event[e]=ref; event[e].class=ref.class || 'wnEvent'; event[e].eventName = e.split('-').pop(); if (this.hasEvent(e)) { _.merge(event[e],this.getEvent(e)); } _eventsConfig[e]=_eventsConfig[e] || {}; _.merge(_eventsConfig[e], event[e]); } return this; }
javascript
{ "resource": "" }
q41266
train
function (name,hidden) { var eventName = 'event-'+name; if (_events[eventName] != undefined) return _events[eventName]; else { if (!_eventsConfig[eventName] || !this.c) return false; var config = _eventsConfig[eventName] || {}, _class = config.class; config.id = eventName; config.autoInit = false; var evt = this.createClass(_class,config); if (evt) { evt.setParent(this); evt.init(); if (hidden != false) { _events[eventName] = evt; this.e[name]=evt.emit; } else { Object.defineProperty(_events[eventName],{ value: evt, enumerable: false }); } return evt; } return false; } }
javascript
{ "resource": "" }
q41267
train
function (eventName,handler) { var event; if (event = this.getEvent(eventName)) { if (!event.addListener(handler)) this.e.log('Invalid handler sent to event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); } else this.e.log('Not existent event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); return this; }
javascript
{ "resource": "" }
q41268
train
function (eventName,handler) { var event; if (event = this.getEvent(eventName)) { if (!event.prependListener(handler)) this.e.log('Invalid handler sent to event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); } else this.e.log('Not existent event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); return this; }
javascript
{ "resource": "" }
q41269
train
function (eventName,handler) { var event; if (event = this.getEvent(eventName)) { if (!event.once(handler,true)) this.e.log('Invalid handler sent to event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); } else this.e.log('Not existent event `'+eventName+'` on `'+this.getConfig('id')+'`','warning'); return this; }
javascript
{ "resource": "" }
q41270
train
function () { var _export = {}, merge = {}; _.merge(merge,this.getConfig()); _.merge(merge,this); var proto = this._proto.public; for (p in proto) if (!((typeof proto[p] == 'object' || typeof proto[p] == 'function') && proto[p] != null && proto[p].instanceOf!=undefined)) _export[p] = proto[p]; for (p in merge) if (!((typeof merge[p] == 'object' || typeof merge[p] == 'function') && merge[p] != null && merge[p].instanceOf!=undefined)) _export[p] = merge[p]; return _export; }
javascript
{ "resource": "" }
q41271
train
function (msg,verbosity) { if (!_debug || verbosity>_verbosity) return false; this.e.log.apply(this,[msg||'','debug',verbosity||0]); return self; }
javascript
{ "resource": "" }
q41272
train
function () { arguments[arguments.length+'']='info'; arguments.length++; this.e.log.apply(this,arguments); return self; }
javascript
{ "resource": "" }
q41273
train
function (cmd,context,silent) { var ctx = (context!=undefined?context:this); try { return (function () { var result = eval(cmd); if (!silent) self.e.log&&self.e.log(util.inspect(result),'result'); return result; }.bind(ctx))(); } catch (e) { this.e.exception&&this.e.exception(e); } return; }
javascript
{ "resource": "" }
q41274
rehydrateAggregate
train
function rehydrateAggregate(ARObject){ return when.try(eventSink.rehydrate.bind(eventSink), ARObject, ARID, ARObject.getNextSequenceNumber()); }
javascript
{ "resource": "" }
q41275
train
function() { this.anchor = this.view.env.document.createTextNode(''); var el = this.view.element; if(el.parentNode) { el.parentNode.insertBefore(this.anchor, el.nextSibling); el.parentNode.removeChild(el); } this.boundViews = []; // Boundview options: this.boundViewName = this.view.element.getAttribute(settings.DATA_VIEW_ATTR); var opt = this.view.element.getAttribute(settings.DATA_OPTIONS_ATTR); this.boundViewOptions = opt ? JSON.parse(opt) : {}; this.boundViewOptions.parentView = this.view; this.boundViewOptions.env = this.view.env; this.boundViewOptions.isBoundView = true; this.refreshBoundViews(); }
javascript
{ "resource": "" }
q41276
train
function() { var boundView, i, l; // Destroy boundviews if(this.boundViews !== null) { for(i = 0, l = this.boundViews.length; i < l; i++) { boundView = this.boundViews[i]; boundView.destroyAll(); if(boundView.element && boundView.element.parentNode) boundView.element.parentNode.removeChild(boundView.element); } this.boundViews = null; } if(this.anchor) { if(this.anchor.parentNode) { this.anchor.parentNode.insertBefore(this.view.element, this.anchor.nextSibling); this.anchor.parentNode.removeChild(this.anchor); } this.anchor = null; } if(this.elementTemplate) { if(this.elementTemplate.parentNode) { this.elementTemplate.parentNode.removeChild(this.elementTemplate); } this.elementTemplate = null; } this.viewTemplate = null; if(this.collection) this.collection = null; }
javascript
{ "resource": "" }
q41277
train
function(from, to) { if(!from) from = 0; if(!to || to > this.boundViews.length) to = this.boundViews.length; // Reindex subsequent boundviews: for(var i = from; i < to; i++) { this.boundViews[i].setBindingIndex(i); this.boundViews[i].refreshBinders(true); } }
javascript
{ "resource": "" }
q41278
train
function(item) { var boundView, element, i; if(!this.viewTemplate) { element = this.view.element.cloneNode(true); this.boundViewOptions.element = element; boundView = new this.view.constructor(this.boundViewOptions); boundView._collectionBinder = null; boundView._modelBindersMap = this.view._modelBindersMap.clone(); this.boundViews.push(boundView); i = this.boundViews.length - 1; boundView.scope['*'] = this.cursor.refine([i]); if(this.view._itemAlias) boundView.scope[this.view._itemAlias] = boundView.scope['*']; boundView.setBindingIndex(i); boundView.renderAll(); this.viewTemplate = boundView._clone(); this.elementTemplate = element.cloneNode(true); } else { element = this.elementTemplate.cloneNode(true); boundView = this.viewTemplate._clone(); boundView._setParentView(this.view); this.boundViews.push(boundView); i = this.boundViews.length - 1; boundView.scope['*'] = this.cursor.refine([i]); if(this.view._itemAlias) boundView.scope[this.view._itemAlias] = boundView.scope['*']; boundView.setBindingIndex(i); boundView._rebindElement(element); } element.setAttribute(settings.DATA_RENDERED_ATTR, true); boundView._itemAlias = this.view._itemAlias; boundView._modelBindersMap.setView(boundView); return boundView; }
javascript
{ "resource": "" }
q41279
normalize
train
function normalize(acc, val) { if (typeof val === 'string') { var value = val.trim().replace(acc.refIgnoreRegExp, REF_MAGIC); if (value.indexOf(acc.refLabel) === 0 && value.indexOf(acc.refLabel + acc.macroBegin) === -1) { value = value.substring(acc.refLabel.length); this.update(acc.get(value)); } else if (value.indexOf(acc.refLabel + 'disable') === 0) { this.remove(); } else { value = value.replace(acc.refRegExp, function replaceMacro(val, path) { return acc.get(path); }); this.update(value.replace(REF_MAGIC_REGEXP, acc.refLabel)); } } var key = this.key; if (key && key.indexOf(acc.annotationLabel) === 0) { normalizer = acc.normalizers[key.substring(acc.annotationLabel.length)]; if (normalizer) { normalizer(acc, val, this); } } return acc; }
javascript
{ "resource": "" }
q41280
HyperConfig
train
function HyperConfig(options) { this.name = 'HyperConfig'; if (!(this instanceof HyperConfig)) { return new HyperConfig(options); } options = options || {}; this._refLabel = options.refLabel || '~'; this._annotationLabel = options.annotationLabel || '@'; this._macroBegin = options.macroBegin || '{'; this._macroEnd = options.macroEnd || '}'; this._config = traverse({}); this._isBuilded = false; this._normalizers = {}; this.addNormalizer('tags', extractTags); }
javascript
{ "resource": "" }
q41281
isEmpty
train
function isEmpty(ptr, propDesc, value) { if ((value === undefined) || (value === null)) return true; if (propDesc.isArray() && !ptr.collectionElement && Array.isArray(value)) { if (value.length === 0) return true; } else if (propDesc.isMap() && !ptr.collectionElement && ((typeof value) === 'object')) { if (Object.keys(value).length === 0) return true; } else if ((propDesc.isScalar() || ptr.collectionElement) && (propDesc.scalarValueType === 'string') && ((typeof value) === 'string')) { if (value.length === 0) return true; } return false; }
javascript
{ "resource": "" }
q41282
hasMatchingSibling
train
function hasMatchingSibling(ctx, propName, testValue, whenErrors) { const containerDesc = ctx.currentPropDesc.container; const propDesc = containerDesc.getPropertyDesc(propName); let propPtr; if (containerDesc.parentContainer && containerDesc.parentContainer.isPolymorphObject()) { const pathParts = containerDesc.nestedPath.split('.'); propPtr = ctx.currentPointer.parent.createChildPointer( `${pathParts[pathParts.length - 2]}:${propName}`); } else { propPtr = ctx.currentPointer.parent.createChildPointer(propName); } if (ctx.hasErrorsFor(propPtr)) return whenErrors; const container = ctx.containersChain[ctx.containersChain.length - 1]; const propValue = container[propName]; if (testValue !== undefined) { if (((testValue instanceof RegExp) && testValue.test(propValue)) || (propValue === testValue)) return true; } else { if (!isEmpty(propPtr, propDesc, propValue)) return true; } return false; }
javascript
{ "resource": "" }
q41283
addDepsError
train
function addDepsError(ctx, type, propName, testValue) { let depsErrors = ctx[DEPS_ERRORS]; if (!depsErrors) depsErrors = ctx[DEPS_ERRORS] = {}; const curPtrStr = ctx.currentPointer.toString(); if (depsErrors[curPtrStr]) return; depsErrors[curPtrStr] = true; const hasTestValue = (testValue !== undefined); const testValueIsPattern = (testValue instanceof RegExp); ctx.addError( ( hasTestValue ? ( testValueIsPattern ? `{${type}Pattern}` : `{${type}Value}` ) : `{${type}}` ), { prop: propName, [testValueIsPattern ? 'pattern' : 'value']: testValue } ); }
javascript
{ "resource": "" }
q41284
Credentials
train
function Credentials (options) { EventEmitter.call(this) options.keys.apiVersion = 'latest' options.keys.sslEnabled = true if (options.hasOwnProperty('upgrade')) { // Update with the MFA token passed in with the credentials this.upgrade(options) return } let awsConfig = Object.assign({}, options.keys) // Else not using a MFA token this._awsConfig = new AWS.Config(awsConfig) // Upgrade creditials not necessary. Tell the caller ready. internals.emitAsync.call(this, internals.EVENT_INITIALIZED, null, { state: 'ok' }) }
javascript
{ "resource": "" }
q41285
train
function (controlPoint, uuid, location, desc, localAddress) { EventEmitter.call(this); if (TRACE) { logger.info({ method: "UpnpDevice", uuid: uuid, }, "new device object"); } this.controlPoint = controlPoint; this.uuid = uuid; this.udn = desc.UDN[0]; this.forgotten = false this.last_seen = (new Date()).getTime(); this.location = location; this.deviceType = desc.deviceType ? desc.deviceType[0] : null; this.friendlyName = desc.friendlyName ? desc.friendlyName[0] : null; this.manufacturer = desc.manufacturer ? desc.manufacturer[0] : null; this.manufacturerUrl = desc.manufacturerURL ? desc.manufacturerURL[0] : null; this.modelNumber = desc.modelNumber ? desc.modelNumber[0] : null; this.modelDescription = desc.modelDescription ? desc.modelDescription[0] : null; this.modelName = desc.modelName ? desc.modelName[0] : null; this.modelUrl = desc.modelURL ? desc.modelURL[0] : null; this.softwareVersion = desc.softwareVersion ? desc.softwareVersion[0] : null; this.hardwareVersion = desc.hardwareVersion ? desc.hardwareVersion[0] : null; this.serialNum = desc.serialNum ? desc.serialNum[0] : null; var u = url.parse(this.location); this.host = u.hostname; this.port = u.port; this.localAddress = localAddress; this.devices = {}; // sub-devices this.services = {}; this._handleDeviceInfo(desc); if (seend[this.uuid] === undefined) { seend[this.uuid] = true; logger.info({ method: "UpnpDevice", device: { loction: this.location, uuid: this.uuid, deviceType: this.deviceType, friendlyName: this.friendlyName, manufacturer: this.manufacturer, manufacturerUrl: this.manufacturerURL, modelNumber: this.modelNumber, modelDescription: this.modelDescription, modelName: this.modelName, modelUrl: this.modelURL, } }, "previously unseen UPnP device"); } // var self = this; // this._getDeviceDetails(function(desc) { // self._handleDeviceInfo(desc); // }); }
javascript
{ "resource": "" }
q41286
extendHttpRequest
train
function extendHttpRequest(req) { req = req || express.request; /** * get param value from path-variable or query or body or headers. * @param {string} paramName * @param {*} [fallback] * @returns {*} */ req.anyParam = function (paramName, fallback) { return (this.params && this.params[paramName]) || // path-variable (this.query && this.query[paramName]) || (this.body && this.body[paramName]) || (this.get && this.get(paramName)) || // header fallback; }; /** * get string param from http request. * * @param {String} paramName * @param {String} [fallback] * @returns {String} param value * @throws {errors.BadRequest} no string param acquired and no fallback provided * @memberOf {express.request} */ req.strParam = function (paramName, fallback) { var paramValue = this.anyParam(paramName); if (paramValue !== undefined) { return paramValue; } if (fallback !== undefined) { return fallback; } throw new errors.BadRequest('param_required:' + paramName); }; /** * get integer param from http request. * * @param {String} paramName * @param {Number} [fallback] * @returns {Number} param value * @throws {errors.BadRequest} no integer param acquired and no fallback provided * @memberOf {express.request} */ req.intParam = function (paramName, fallback) { var paramValue = utils.toInt(this.anyParam(paramName), fallback); if (paramValue !== undefined) { return paramValue; } if (fallback !== undefined) { return fallback; } throw new errors.BadRequest('int_param_required:' + paramName); }; /** * get number(float) param from http request. * * @param {String} paramName * @param {Number} [fallback] * @returns {Number} param value * @throws {errors.BadRequest} no number param acquired and no fallback provided * @memberOf {express.request} */ req.numberParam = function (paramName, fallback) { var paramValue = utils.toNumber(this.anyParam(paramName)); if (paramValue !== undefined) { return paramValue; } if (fallback !== undefined) { return fallback; } throw new errors.BadRequest('number_param_required:' + paramName); }; /** * get boolean param from http request. * * @param {String} paramName * @returns {Boolean} [fallback] * @returns {Boolean} param value * @throws {errors.BadRequest} no boolean param acquired and no fallback provided * @memberOf {express.request} */ req.boolParam = function (paramName, fallback) { var paramValue = utils.toBoolean(this.anyParam(paramName)); if (paramValue !== undefined) { return paramValue; } if (fallback !== undefined) { return fallback; } throw new errors.BadRequest('bool_param_required:' + paramName); }; /** * get date param from http request. * * @param {String} paramName * @param {Date} [fallback] * @returns {Date} param value * @throws {errors.BadRequest} no date param acquired and no fallback provided * @memberOf {express.request} */ req.dateParam = function (paramName, fallback) { var paramValue = Date.parse(this.anyParam(paramName)); if (!isNaN(paramValue)) { return new Date(paramValue); } if (fallback !== undefined) { return fallback; } throw new errors.BadRequest('date_param_required:' + paramName); }; /** * collect params from http request. * * @param {Array.<String>} paramNames * @returns {Object.<String,String>} */ req.collectParams = function (paramNames) { var self = this; return paramNames.reduce(function (params, paramName) { var paramValue = self.strParam(paramName); if (paramValue) { params[paramName] = paramValue.trim(); } return params; }, {}); }; }
javascript
{ "resource": "" }
q41287
extendHttpResponse
train
function extendHttpResponse(res) { res = res || express.response; function callbackFnFn(verbFunc) { return function (next, status) { var res = this; return function (err, result) { if (err) { return next(err); } if (status) { return res.status(status); } return verbFunc.call(res, result); }; }; } function laterFnFn(verbFunc) { return function (promise, next, status) { var res = this; return Q.when(promise).then(function (result) { if (status) { res.status(status); } return verbFunc.call(res, result); }).fail(next).done(); }; } // // callback helpers // /** * create generic node.js callback function to invoke 'express.response.send()'. * * ex. * ``` * var fs = require('fs'); * app.get('/foo', function(req, res, next) { * fs.readFile('foo.txt', res.sendCallbackFn(next)); * }); * ``` * @param {function} next * @param {number} [status] * @returns {function(err, result)} generic node.js callback which send response. * @method * @memberOf {express.request} */ res.sendCallbackFn = callbackFnFn(res.send); /** * create generic node.js callback function to invoke 'express.response.json()'. * * @param {function} next * @param {number} [status] * @returns {function(err, result)} generic node.js callback which send 'json' response. * @method * @memberOf {express.request} */ res.jsonCallbackFn = callbackFnFn(res.json); /** * create generic node.js callback function to invoke 'express.response.jsonp()'. * * @param {function} next * @param {number} [status] * @returns {function(err, result)} generic node.js callback which send 'jsonp' response. * @method * @memberOf {express.request} */ res.jsonpCallbackFn = callbackFnFn(res.jsonp); /** * create generic node.js callback function to invoke 'express.response.sendFile()'. * * @param {function} next * @param {number} [status] * @returns {function(err, result)} generic node.js callback which send 'sendFile' response. * @method * @memberOf {express.request} */ res.sendFileCallbackFn = callbackFnFn(res.sendFile); /** * create generic node.js callback function to invoke 'express.response.redirect()'. * * @param {function} next * @param {number} [status] * @returns {function(err, result)} generic node.js callback which send 'redirect' response. * @method * @memberOf {express.request} */ res.redirectCallbackFn = callbackFnFn(res.redirect); /** * ex. * ``` * fs.stat('foo.txt', res.renderCallbackFn('stat_view', next)); * ``` * * @param {string} view * @param {function} next * @param {number} [status] * @returns {function(err, result)} * @memberOf {express.response} */ res.renderCallbackFn = function (view, next, status) { var res = this; return function (err, result) { if (err) { return next(err); } if (status) { res.status(status); } return res.render(view, result); }; }; // // promise helpers // /** * promise version to invoke `express.response.send()`. * * ex. * ``` * var FS = require('q-io/fs'); * app.get('/foo', function (req, res, next) { * res.sendLater(FS.readFile('foo.txt'), next); * }) * ``` * * @param {promise|*} promise of response. * @param {function} next * @param {number} [status] * @method * @memberOf {express.request} */ res.sendLater = laterFnFn(res.send); /** * promise version of `express.response.json()`. * * @param {promise|*} promise of 'json' response. * @param {function} next * @param {number} [status] * @method * @memberOf {express.request} */ res.jsonLater = laterFnFn(res.json); /** * promise version of `express.response.jsonp()`. * * @param {promise|*} promise of 'jsonp' response. * @param {function} next * @param {number} [status] * @method * @memberOf {express.request} */ res.jsonpLater = laterFnFn(res.jsonp); /** * promise version of `express.response.sendFile()`. * * @param {promise|*} promise of 'sendFile' response. * @param {function} next * @param {number} [status] * @method * @memberOf {express.request} */ res.sendFileLater = laterFnFn(res.sendFile); /** * promise version of `express.response.redirect()`. * * @param {promise|*} promise of 'redirect' response. * @param {function} next * @param {number} [status] * @method * @memberOf {express.request} */ res.redirectLater = laterFnFn(res.redirect); /** * * ex. * ``` * var FS = require('q-io/fs'); * res.renderLater('stat_view', FS.stat('foo.txt'), next); * ``` * * @param {string} view * @param {promise|*} promise of 'render' model. * @param {function} next * @param {number} [status] * @memberOf {express.response} */ res.renderLater = function (view, promise, next, status) { var res = this; return Q.when(promise).then(function (result) { if (status) { res.status(status); } return res.render(view, result); }).fail(next).done(); }; }
javascript
{ "resource": "" }
q41288
matches
train
function matches(el, target, selector) { var elements = el.querySelectorAll(selector); return arrayIndexOf(elements, target) !== -1; }
javascript
{ "resource": "" }
q41289
tumblr
train
function tumblr(hostname, key, secret, access_key, access_secret) { if (!(this instanceof tumblr)) return new tumblr(hostname, key, secret, access_key, access_secret); var obj = (typeof hostname !== 'object') ? { hostname : hostname, secret : secret, key : key, access_secret : access_secret, access_key : access_key } : hostname; // reference if (obj && obj.hostname) this.hostname = !/\./.test(obj.hostname) ? obj.hostname + '.tumblr.com' : obj.hostname; this.key = obj.key; this.secret = obj.secret; this.access_key = obj.access_key; this.access_secret = obj.access_secret; // output the log to console this.debug = false; // keeping the logs even if debug is false this.log = []; // caching requests this.caches = false; this._cache = {}; // oauth access this._oauth_access = this.access_key && this.access_secret; // if response should omit "meta" this.onlyResponse = true; if (this.key && this.secret && this._oauth_access) { this._oa = oa = new OAuth('http://www.tumblr.com/oauth/request_token', 'http://www.tumblr.com/oauth/access_token', this.key, this.secret, '1.0A', null, 'HMAC-SHA1'); var self = this; oa.getOAuthRequestToken(function(err, req_key, req_secret, res) { if (!err) { var url = ['http://www.tumblr.com/oauth/authorize/?oauth_token=', req_key].join(''); self.OAuthAuthorizationURL = url; self._oa.session = self._oa.session || {}; self._oa.session.key = req_key; self._oa.session.secret = req_secret; } else { debug(err); } }); } return this; }
javascript
{ "resource": "" }
q41290
create
train
function create(requestObj, callback) { var storage = this; callback = callback || function defaultPostCallback() { //setup Error Notification here }; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(); return this; } requestObj.data.id = this._generateUid(); for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } this.storage[requestObj.data.id] = requestObj.data; var data = this.storage[requestObj.data.id]; for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data); } callback(data); return this; }
javascript
{ "resource": "" }
q41291
find
train
function find(requestObj, callback) { var found, storedData, property; var storage = this; callback = callback || function defaultGetCallback() { //nothing here maybe put error notification }; for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } found = []; storedData = this.storage; Object.keys(storedData).forEach(function (property) { found.push(storedData[property]); }); var data = found; for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); return this; }
javascript
{ "resource": "" }
q41292
update
train
function update(requestObj, callback) { var storage = this; callback = callback || function defaultPutCallBack() { //setup Error notification }; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.storage[requestObj.data.id] = requestObj.data; var data = this.storage[requestObj.data.id]; for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }
javascript
{ "resource": "" }
q41293
remove
train
function remove(requestObj, callback) { var storageInstance = this; var storage = this; callback = callback || function defaultRemoveCallBack() { //setup Error Notification }; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } if (requestObj.data && requestObj.data.id) { delete storageInstance.storage[requestObj.data.id]; } callback(null); return this; }
javascript
{ "resource": "" }
q41294
log
train
function log ( object, symbol ) { var message = (object.plugin ? ("(" + (object.plugin) + " plugin) " + (object.message)) : object.message) || object; stderr( ("" + symbol + (index$3.bold( message ))) ); if ( object.url ) { stderr( index$3.cyan( object.url ) ); } if ( object.loc ) { stderr( ((relativeId( object.loc.file )) + " (" + (object.loc.line) + ":" + (object.loc.column) + ")") ); } else if ( object.id ) { stderr( relativeId( object.id ) ); } if ( object.frame ) { stderr( index$3.dim( object.frame ) ); } stderr( '' ); }
javascript
{ "resource": "" }
q41295
train
function(into, from) { for (var key in from) { if (into[key] instanceof Object && !(into[key] instanceof Array) && !(into[key] instanceof Function)) { merge_(into[key], from[key]); } else { into[key] = from[key]; } } return into; }
javascript
{ "resource": "" }
q41296
split
train
function split( command ) { if ( typeof command !== 'string' ) { throw new Error( 'Command must be a string' ); } var r = command.match( /[^"\s]+|"(?:\\"|[^"])*"/g ); if ( ! r ) { return []; } return r.map( function ( expr ) { var isQuoted = expr.charAt( 0 ) === '"' && expr.charAt( expr.length - 1 ) === '"'; return isQuoted ? expr.slice( 1, -1 ) : expr; } ); }
javascript
{ "resource": "" }
q41297
splitToObject
train
function splitToObject( command ) { var cmds = split( command ); switch( cmds.length ) { case 0: return {}; case 1: return { command: cmds[ 0 ] }; default: { var first = cmds[ 0 ]; cmds.shift(); return { command: first, args: cmds }; } } }
javascript
{ "resource": "" }
q41298
train
function(params, callback) { if (!params.url) return (callback || function() {})(new Error(utils.i18n.webhooks.url)); if (!params.events || !params.events.length) return (callback || function() {})(new Error(utils.i18n.webhooks.events)); if (!params.secret) return (callback || function() {})(new Error(utils.i18n.webhooks.secret)); utils.debug('Webhooks register: ' + params.url); request.post({ path: '/webhooks', body: { target_url: params.url, events: params.events, secret: params.secret, config: params.config || {}, version: version, } }, function(err, res) { if (!err) res.body.secret = params.secret; if (callback) callback(err, res); }); }
javascript
{ "resource": "" }
q41299
train
function(webhookId, callback) { utils.debug('Webhooks disable: ' + webhookId); request.post({ path: '/webhooks/' + utils.toUUID(webhookId) + '/deactivate', }, callback || utils.nop); }
javascript
{ "resource": "" }