_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q13300
Logger
train
function Logger() { this._level = LEVELS.NOTICE; this._out = process.stdout; this._err = process.stderr; /* istanbul ignore next: allow server to suppress logs */ if(process.env.NODE_ENV === Constants.TEST && !process.env.TEST_DEBUG) { this.log = function noop(){}; } }
javascript
{ "resource": "" }
q13301
level
train
function level(lvl) { if(!lvl) return this._level; if(!~LEVELS.indexOf(lvl)) { throw new Error('invalid log level: ' + lvl); } this._level = lvl; return this._level; }
javascript
{ "resource": "" }
q13302
warning
train
function warning() { var args = [LEVELS.WARNING].concat(slice.apply(arguments)); return this.log.apply(this, args); }
javascript
{ "resource": "" }
q13303
notice
train
function notice() { var args = [LEVELS.NOTICE].concat(slice.apply(arguments)); return this.log.apply(this, args); }
javascript
{ "resource": "" }
q13304
verbose
train
function verbose() { var args = [LEVELS.VERBOSE].concat(slice.apply(arguments)); return this.log.apply(this, args); }
javascript
{ "resource": "" }
q13305
createConfiguration
train
function createConfiguration (options) { const cfg = Object.assign({ followSymbolicLinks: false, cacheTimeInSeconds : 0, documentRoot : process.cwd(), parsedURLName : 'urlParsed', getFilePath : getFilePath, getFileStats : getFileStats, getResponseData : getResponseData, standardResponses : null }, options); try { let root = fs.realpathSync(cfg.documentRoot); cfg.documentRootReal = root; } catch (e) { return e; } return cfg; }
javascript
{ "resource": "" }
q13306
getFileStats
train
function getFileStats (cfg, filePath, callback) { fs.realpath(filePath, function (err, realpath) { // On Windows we can get different cases for the same disk letter :/. let checkPath = realpath; if (os.platform() === 'win32' && realpath) { checkPath = realpath.toLowerCase(); } if (err || checkPath.indexOf(cfg.documentRootReal) !== 0) { return callback(err || new Error('Access denied')); } fs[cfg.followSymbolicLinks ? 'stat' : 'lstat'](filePath, function (err, stats) { if (err || !stats.isFile()) { return callback(err || new Error('Access denied')); } stats.path = realpath; callback(null, stats); }); }); }
javascript
{ "resource": "" }
q13307
getResponseDataWhole
train
function getResponseDataWhole (fileStats/* , headers*/) { return { body : fs.createReadStream(fileStats.path), statusCode: HTTP_CODES.OK, headers : { 'Content-Type' : mime(fileStats.path), 'Content-Length': fileStats.size, 'Last-Modified' : fileStats.mtime.toUTCString() } }; }
javascript
{ "resource": "" }
q13308
createFileResponseHandler
train
function createFileResponseHandler (options) { const cfg = createConfiguration(options); if (cfg instanceof Error) { return cfg; } /** * @private * @param {!external:"http.IncomingMessage"} req * @param {!external:"http.ServerResponse"} res * @param {Function} [callback] called AFTER response is finished */ function serve (req, res, callback) { if (callback && callback instanceof Function) { res.once('finish', callback); } const filePath = cfg.getFilePath(cfg, req); prepareFileResponse(cfg, filePath, req.headers, (err, data) => { if (err) { data = { statusCode: HTTP_CODES.NOT_FOUND }; } serveFileResponse(cfg, data, res); }); } return serve; }
javascript
{ "resource": "" }
q13309
train
function(inputIndex) { _.each(tokens, function(token, index) { // determain whether or not this is a file reference or a string if(token.file) { // read the file and reset replacement to what was loaded fs.readFile(token.file, 'utf8', function(e, data) { if(e) { grunt.fail.warn("There was an error processing the replacement '" + token.file + "' file."); } tokens[index].contents = data; processTokenCompleteCallback(); }); } else if(token.string) { // we didn't need to load a file tokens[index].contents = token.string; processTokenCompleteCallback(); } else { processTokenCompleteCallback(); } }, this); }
javascript
{ "resource": "" }
q13310
train
function(inputIndex) { var inputPath = input[inputIndex].split("/"); inputPath = inputPath[inputPath.length - 1]; var path = outputIsPath ? output + inputPath : output; // write the input string to the output file name grunt.log.writeln('Writing Output: ' + (path).cyan); fs.writeFile(path, fileContents[inputIndex], 'utf8', function(err) { //console.log(fileContents[inputIndex]); if(err) { clearTimeout(timer); grunt.fail.warn("Could not write output '" + output + "' file."); } processedFiles++; if(processedFiles === fileContents.length) { processedFiles = 0; fileContents = []; var endtime = (new Date()).getTime(); grunt.log.writeln('Combine task completed in ' + ((endtime - starttime) / 1000) + ' seconds'); clearTimeout(timer); done(); } }); }
javascript
{ "resource": "" }
q13311
string_component
train
function string_component(self, message, component) { eventify(self); valuable(self, update, ''); var $c = $$().addClass('control'); var $l = $("<label>" + message + "</label>"); var $i = $(component); $c.append($l, $i); self.$el = $c; function update() { $i.val(self._data); } $i.on('change', function () { self._data = $i.val(); self.emit('change'); }) }
javascript
{ "resource": "" }
q13312
attributable
train
function attributable(form, c, name) { if (form._vals == null) form._vals = {}; if (form._update == null) form._update = function () { for (var p in form._vals) form._vals[p].data == form._data[p]; } form._vals[name] = c; c.on('change', function () { form._data[name] = c.data; form.emit('change'); }); }
javascript
{ "resource": "" }
q13313
UserVoiceSSO
train
function UserVoiceSSO(subdomain, ssoKey) { // For UserVoice, the subdomain is used as password // and the ssoKey is used as salt this.subdomain = subdomain; this.ssoKey = ssoKey; if(!this.subdomain) { throw new Error('No UserVoice subdomain given'); } if(!this.ssoKey) { throw new Error('No SSO key given. Find it '); } this.defaults = {}; }
javascript
{ "resource": "" }
q13314
getDomain
train
function getDomain(data, accessor) { return data .map(function (item) { return accessor.call(this, item); }) .filter(function (item, index, array) { return array.indexOf(item) === index; }); }
javascript
{ "resource": "" }
q13315
validateRule
train
function validateRule(rule, value) { // For a given rule, get the first letter of the string name of its // constructor function. "R" -> RegExp, "F" -> Function (these shouldn't // conflict with any other types one might specify). Note: instead of // getting .toString from a new object {} or Object.prototype, I'm assuming // that exports will always be an object, and using its .toString method. // Bad idea? Let me know by filing an issue var type = exports.toString.call(rule).charAt(8); // If regexp, match. If function, invoke. Otherwise, compare. Note that == // is used because type coercion is needed, as `value` will always be a // string, but `rule` might not. return type === "R" ? rule.test(value) : type === "F" ? rule(value) : rule == value; }
javascript
{ "resource": "" }
q13316
Dotfile
train
function Dotfile(basename, options) { this.basename = basename; this.extname = '.json'; this.dirname = (options && typeof options.dirname === 'string') ? options.dirname : Dotfile._tilde; this.filepath = path.join(this.dirname, '.' + this.basename + this.extname); }
javascript
{ "resource": "" }
q13317
transform
train
function transform(value) { if(typeof value === 'function') value = value() if(value instanceof Array) { var el = document.createDocumentFragment() value.map(item => el.appendChild(transform(item))) value = el } else if(typeof value === 'object') { if(typeof value.then === 'function') { var tmp = document.createTextNode('') value.then(function(data) { tmp.parentElement.replaceChild(transform(data), tmp) }) value = tmp } else if(typeof value.on === 'function') { var tmp = document.createTextNode('') value.on('data', function(data) { // need to transform? Streams are only text? tmp.parentElement.insertBefore(document.createTextNode(data), tmp) }) value = tmp } } else value = document.createTextNode(value) return value }
javascript
{ "resource": "" }
q13318
Requests
train
function Requests(apiUrl, version, publicKey) { this.apiUrl = stripSlashes(apiUrl); this.version = version.toString(); this.publicKey = publicKey; }
javascript
{ "resource": "" }
q13319
train
function(id) { var file; if (typeof id === 'number') { file = this.uploader.files[id]; } else { file = this.uploader.getFile(id); } return file; }
javascript
{ "resource": "" }
q13320
train
function(file) { if (plupload.typeOf(file) === 'string') { file = this.getFile(file); } this.uploader.removeFile(file); }
javascript
{ "resource": "" }
q13321
train
function(type, message) { var popup = $( '<div class="plupload_message">' + '<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' + '<p><span class="ui-icon"></span>' + message + '</p>' + '</div>' ); popup .addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight')) .find('p .ui-icon') .addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info')) .end() .find('.plupload_message_close') .click(function() { popup.remove(); }) .end(); $('.plupload_header', this.container).append(popup); }
javascript
{ "resource": "" }
q13322
train
function() { // destroy uploader instance this.uploader.destroy(); // unbind all button events $('.plupload_button', this.element).unbind(); // destroy buttons if ($.ui.button) { $('.plupload_add, .plupload_start, .plupload_stop', this.container) .button('destroy'); } // destroy progressbar if ($.ui.progressbar) { this.progressbar.progressbar('destroy'); } // destroy sortable behavior if ($.ui.sortable && this.options.sortable) { $('tbody', this.filelist).sortable('destroy'); } // restore the elements initial state this.element .empty() .html(this.contents_bak); this.contents_bak = ''; $.Widget.prototype.destroy.apply(this); }
javascript
{ "resource": "" }
q13323
measure
train
function measure() { if (!tw || !th) { var wrapper = $('.plupload_file:eq(0)', self.filelist); tw = wrapper.outerWidth(true); th = wrapper.outerHeight(true); } var aw = self.content.width(), ah = self.content.height(); cols = Math.floor(aw / tw); num = cols * (Math.ceil(ah / th) + 1); }
javascript
{ "resource": "" }
q13324
obv
train
function obv (fn, immediate) { if(!fn) return state listeners.push(fn) if(immediate !== false && fn(state) === true) obv.more() return function () { var i = listeners.indexOf(fn) listeners.splice(i, 1) } }
javascript
{ "resource": "" }
q13325
isValid
train
function isValid (type, value) { switch (type) { case 'email': return validator.isEmail(value); break; case 'url': return validator.isURL(value); break; case 'domain': return validator.isFQDN(value); break; case 'ip': return validator.isIP(value); break; case 'alpha': return validator.isAlpha(value); break; case 'number': return validator.isNumeric(value); break; case 'alphanumeric': return validator.isAlphanumeric(value); break; case 'base64': return validator.isBase64(value); break; case 'hexadecimal': return validator.isHexadecimal(value); break; case 'hexcolor': return validator.isHexColor(value); break; case 'int': return validator.isInt(value); break; case 'float': return validator.isFloat(value); break; case 'null': return validator.isNull(value); break; case 'uuid': return validator.isUUID(value); break; case 'date': return validator.isDate(value); break; case 'creditcard': return validator.isCreditCard(value); break; case 'isbn': return validator.isISBN(value); break; case 'mobilephone': return validator.isMobilePhone(value); break; case 'json': return validator.isJSON(value); break; case 'ascii': return validator.isAscii(value); break; case 'mongoid': return validator.isMongoId(value); break; default: return false; break; } }
javascript
{ "resource": "" }
q13326
_buildNamespace
train
function _buildNamespace(appName, depth) { var callerFile; // Our default depth needs to be 2, since 1 is this file. Add the user // supplied depth to 1 (for this file) to make it 2. callerFile = caller(depth + 1); // if for some reason we're unable to determine the caller, use the appName only if (!callerFile) { return appName; } // TODO in later versions of Node (v0.12.+), there is simple `path.parse` // which will provide us with the file name property. But until most have // moved up to that version, find the caller file name in this way... // find the filename from the path callerFile = path.basename(callerFile); // strip off the suffix (if any) if (path.extname(callerFile)) { callerFile = callerFile.slice(0, callerFile.indexOf(path.extname(callerFile))); } return appName + ":" + callerFile; }
javascript
{ "resource": "" }
q13327
logger
train
function logger(appName, options) { var namespace, log, error; options = options ? options : {}; // merge our default options with the user supplied options = xtend({ depth: 1, randomColors: false, logColor: 7, errorColor: 1, }, options); // get the filename which is used as the namespace for the debug module. namespace = _buildNamespace(appName, options.depth); // setup two debug'ers, one for console.log and one for console.error log = debug(namespace); // bind the log to console.log log.log = console.log.bind(console); error = debug(namespace); // this should happen by default, but just to be sure... error.log = console.error.bind(console); // if we don't want random colors, assign log to options.logColor (default: white (7)) // and error to options.errorColor (default: red (1)) if (!options.randomColors) { log.color = options.logColor; error.color = options.errorColor; } return { // return the two debug'ers under the log and error functions log: log, error: error, // include the namespace in case the client needs it namespace: namespace }; }
javascript
{ "resource": "" }
q13328
init_session
train
function init_session(req) { debug.assert(req.session).is('object'); if(!is.obj(req.session.client)) { req.session.client = {}; } if( (!is.obj(req.session.client.messages)) || is.array(req.session.client.messages) ) { req.session.client.messages = {}; } }
javascript
{ "resource": "" }
q13329
train
function (baseUrl, firebaseUrl, port, cardsDirectory) { // Set environment variables. process.env.BASE_URL = baseUrl || ''; process.env.FIREBASE_URL = firebaseUrl || 'https://hashdodemo.firebaseio.com/', process.env.CARDS_DIRECTORY = cardsDirectory || process.cwd(); process.env.PORT = port || 4000; var Path = require('path'), Favicon = require('serve-favicon'), Hpp = require('hpp'); App.use(Timeout('10s')); App.use(Favicon(Path.join(__dirname, '/public/favicon.ico'))); App.use(Express.static('public')); // Hacky, quick fix required for now. // ********************************** App.use('/js', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/js'))); App.use('/css', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/css'))); // ********************************** App.use(BodyParser.urlencoded({extended: false, limit: '5mb'})); App.use(Hpp()); App.use(Cors()); App.use(haltOnTimedout); function haltOnTimedout(req, res, next){ if (!req.timedout) next(); } // Assume cards directory is based off root if a full path is not provided. if (!Path.isAbsolute(process.env.CARDS_DIRECTORY)) { process.env.CARDS_DIRECTORY = Path.join(process.cwd(), process.env.CARDS_DIRECTORY); } HashDo.packs.init(baseUrl, process.env.CARDS_DIRECTORY); // Make public card directories static HashDo.packs.cards().forEach(function (card) { var packDirectory = Path.join(cardsDirectory, 'hashdo-' + card.pack); App.use('/' + card.pack + '/' + card.card, Express.static(Path.join(packDirectory, 'public', card.card))); }); }
javascript
{ "resource": "" }
q13330
train
function (callback) { var APIController = require('./controllers/api'), DefaultController = require('./controllers/index'), PackController = require('./controllers/pack'), CardController = require('./controllers/card'), WebHookController = require('./controllers/webhook'), ProxyController = require('./controllers/proxy'), JsonParser = BodyParser.json({strict: false}); // Disable caching middleware. var nocache = function (req, res, next) { res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); res.header('Expires', '-1'); res.header('Pragma', 'no-cache'); next(); }; // Setup routes late to give implementers routes higher priority and allow middleware as well. App.get('/api/count', nocache, APIController.count); App.get('/api/cards', nocache, APIController.cards); App.get('/api/card', nocache, APIController.card); App.post('/api/card/state/save', APIController.saveState); App.post('/api/card/state/clear', APIController.clearState); App.post('/api/card/analytics', APIController.recordAnalyticEvents); // Proxy App.post('/proxy/:pack/:card', ProxyController.post); // Web Hooks App.post('/webhook/:pack/:card', WebHookController.process); // Card Routes App.post('/:pack/:card', JsonParser, CardController.post); App.get('/:pack/:card', CardController.get); App.get('/:pack', PackController); App.get('/', DefaultController); var exit = function () { HashDo.db.disconnect(function () { process.exit(0); }); }; // Gracefully disconnect from the database on expected exit. process.on('SIGINT', exit); process.on('SIGTERM', exit); // Global error handler (always exit for programmatic errors). process.on('uncaughtException', function (err) { console.error('FATAL: ', err.message); console.error(err.stack); process.exit(1); }); // Connect to the database and start server on successful connection. HashDo.db.connect(function (err) { if (err) { console.error('FATAL: Could not connect to database.', err); process.exit(1); } else { console.log('WEB: Starting web server on port %d...', process.env.PORT); App.listen(process.env.PORT, function () { console.log(); console.log('Let\'s #Do'); callback && callback(); }); } }); }
javascript
{ "resource": "" }
q13331
run
train
function run(files, options) { // If translations or templates are not supplied then error if (options.translations.length === 0) { grunt.fail.fatal('Please supply translations'); } // If a missing translation regex has been supplied report the missing count if (options.missingTranslationRegex !== null) { linter.setMissingTranslationRegex(options.missingTranslationRegex); } // Add the translation keys to the linter options.translations.forEach(function(file) { var files = grunt.file.expand(file); files.forEach(function(file) { if (!grunt.file.exists(file)) { grunt.fail.fatal('File ' + file + ' does not exist'); } linter.addKeys(grunt.file.readJSON(file)); }); }); // Iterate through files and run them through the linter files.forEach(function(file) { if (!grunt.file.exists(file)) { grunt.fail.fatal('File ' + file + ' does not exist'); } linter.check(grunt.file.read(file)); }); }
javascript
{ "resource": "" }
q13332
logError
train
function logError(e) { e = e instanceof Error ? e : e ? new Error(e) : null; if (e) { if (options && util.isRegExp(options.hideTokenRegExp)) { e.message = e.message.replace(options.hideTokenRegExp, function(match, prefix, token, suffix) { return prefix + '[SECURE]' + suffix; }); } errors.unshift(e); rbot.log.error(e.stack || e.message); } }
javascript
{ "resource": "" }
q13333
loadFile
train
function loadFile(name, dir, options) { var pathname = path.normalize(path.join(options.prefix, name)); var obj = {}; var filename = (obj.path = path.join(dir, name)); var stats = fs.statSync(filename); var buffer = fs.readFileSync(filename); obj.cacheControl = options.cacheControl; obj.maxAge = obj.maxAge ? obj.maxAge : options.maxAge || 0; obj.type = obj.mime = mime.lookup(pathname) || "application/octet-stream"; obj.mtime = stats.mtime; obj.length = stats.size; obj.md5 = crypto.createHash("md5").update(buffer).digest("base64"); debug("file: " + JSON.stringify(obj, null, 2)); if (options.buffer) obj.buffer = buffer; buffer = null; return obj; }
javascript
{ "resource": "" }
q13334
on
train
function on(name, hdl) { var list = eventHandlers[name] || (eventHandlers[name] = []); list.push(hdl); return this; }
javascript
{ "resource": "" }
q13335
train
function(string){ var pattern = /(^|\W)(\w)(\w*)/g, result = [], match; while (pattern.exec(string)) { result.push(RegExp.$1 + RegExp.$2.toUpperCase() + RegExp.$3); } return result.join(''); }
javascript
{ "resource": "" }
q13336
train
function(module) { for (var i = 0; i < module.include.length; i++) { var curInclude = module.include[i]; if (curInclude.substr(0, 2) == '^!') { module.include[i] = curInclude.substr(2); attachBuildIds.push(curInclude.substr(2)); } } }
javascript
{ "resource": "" }
q13337
train
function(customEvent, callback, context, filter, prepend) { return this._addMultiSubs(false, customEvent, callback, context, filter, prepend); }
javascript
{ "resource": "" }
q13338
train
function(customEvent, callback, context, filter, prepend) { return this._addMultiSubs(true, customEvent, callback, context, filter, prepend); }
javascript
{ "resource": "" }
q13339
train
function (emitterName) { var instance = this, pattern; if (emitterName) { pattern = new RegExp('^'+emitterName+':'); instance._ce.itsa_each( function(value, key) { key.match(pattern) && (delete instance._ce[key]); } ); } else { instance._ce.itsa_each( function(value, key) { delete instance._ce[key]; } ); } }
javascript
{ "resource": "" }
q13340
train
function (e, checkFilter, before, preProcessor, subscribers) { // subscribers, plural var subs, passesThis, passesFilter; if (subscribers && !e.status.halted && !e.silent) { subs = before ? subscribers.b : subscribers.a; subs && subs.some(function(subscriber) { if (preProcessor && preProcessor(subscriber, e)) { return true; } // check: does it need to be itself because of subscribing through 'this' passesThis = (!subscriber.s || (subscriber.o===e.target)); // check: does it pass the filter passesFilter = (!checkFilter || !subscriber.f || subscriber.f.call(subscriber.o, e)); if (passesThis && passesFilter) { // finally: invoke subscriber subscriber.cb.call(subscriber.o, e); } if (e.status.unSilencable && e.silent) { console.warn(NAME, ' event '+e.emitter+':'+e.type+' cannot made silent: this customEvent is defined as unSilencable'); e.silent = false; } return e.silent || (before && e.status.halted); // remember to check whether it was halted for any reason }); } }
javascript
{ "resource": "" }
q13341
askForGithubAuth
train
function askForGithubAuth (options, cb) { if (typeof options === 'function') { cb = options; options = {}; } options = options || {}; options.store = options.store || 'default'; if (typeof options.store === 'string') { options.store = 'for-github-auth.' + options.store; } loadQuestions(options.store); var creds = {}; ask.once('github-auth.type', options, function (err, type) { if (err) return cb(err); creds.type = type; ask.once(['github-auth', type].join('.'), options, function (err, answer) { if (err) return cb(err); if (type === 'oauth') { creds.token = answer; } else { creds.username = answer.username; creds.password = answer.password; } cb(null, creds); }); }); }
javascript
{ "resource": "" }
q13342
StripMQ
train
function StripMQ(input, options, formatOptions) { options || (options = {}); formatOptions || (formatOptions = {}); options = { type: options.type || 'screen', width: options.width || 1024, 'device-width': options['device-width'] || options.width || 1024, height: options.height || 768, 'device-height': options['device-height'] || options.height || 768, resolution: options.resolution || '1dppx', orientation: options.orientation || 'landscape', 'aspect-ratio': options['aspect-ratio'] || options.width/options.height || 1024/768, color: options.color || 3 }; var tree = css.parse(input); tree = stripMediaQueries(tree, options); return css.stringify(tree, formatOptions); }
javascript
{ "resource": "" }
q13343
parseSpans
train
function parseSpans(text) { var links = parseLinks(text); /*Represented as [{ href: "http://yada", start: startIndex, end: endIndex }]*/ var spans = []; var lastSpan = null; function isPrefixedLinkSpan(span) { return span && "href" in span && span.prefix && "proposed" in span.prefix; } function isTextSpan(span) { return span && !("href" in span); } function addTextSpan(text) { //if the last span was a candidate if (isPrefixedLinkSpan(lastSpan)) { //make sure there is a valid suffix if (regexen.matchMarkdownLinkSuffix.test(text)) { //is there any valid whitespace remaining? text = RegExp.$3; //use the title (if specified) if (RegExp.$2) { lastSpan.title = RegExp.$2; } //use the proposed link text for the verified link lastSpan.text = lastSpan.prefix.proposed.linkText; //if there was valid prefix text, use it if (lastSpan.prefix.proposed.text) { lastSpan.prefix.text = lastSpan.prefix.proposed.text; delete lastSpan.prefix["proposed"]; //clean up proposal } else { spans.splice(spans.length - 2, 1); //remove prefix lastSpan = lastSpan.prefix; } } else { delete lastSpan.prefix["proposed"]; //clean up proposal...no match...no modification } delete lastSpan["prefix"]; //clean up prefix scratchwork } if (text) { lastSpan = { text : text }; spans.push(lastSpan); } } function addLinkSpan(linkSpan) { var span = { href : linkSpan.href }; if (isTextSpan(lastSpan) && regexen.matchMarkdownLinkPrefix.test(lastSpan.text)) { lastSpan.proposed = { text: RegExp.$1, linkText: RegExp.$2 }; span.prefix = lastSpan; } lastSpan = span; spans.push(lastSpan); } //No links found, all text if (links.length === 0) { addTextSpan(text); } //One or more links found else { var firstLink = links[0], lastLink = links[links.length - 1]; //Was there text before the first link? if (firstLink.start > 0) { addTextSpan(text.substring(0, firstLink.start)); } //Handle single link if (links.length === 1) { addLinkSpan(firstLink); } else { //push the firstLink addLinkSpan(firstLink); var prevLink = firstLink; //loop from the second for (var i = 1; i < links.length; i++) { //is there text between? if (links[i].start - prevLink.end >= 1) { addTextSpan(text.substring(prevLink.end, links[i].start)); } //add link addLinkSpan(prevLink = links[i]); } } //Was there text after the links? if (lastLink.end < (text.length)) { addTextSpan(text.substring(lastLink.end)); } } return spans; }
javascript
{ "resource": "" }
q13344
makeFuncAsciiDomainReplace
train
function makeFuncAsciiDomainReplace(ctx) { return function (asciiDomain) { var asciiStartPosition = ctx.domain.indexOf(asciiDomain, ctx.asciiEndPosition); ctx.asciiEndPosition = asciiStartPosition + asciiDomain.length; ctx.lastLink = { href : asciiDomain, start: ctx.cursor.start + asciiStartPosition, end: ctx.cursor.start + ctx.asciiEndPosition }; ctx.lastLinkInvalidMatch = asciiDomain.match(regexen.invalidShortDomain); if (!ctx.lastLinkInvalidMatch) { ctx.links.push(ctx.lastLink); } }; }
javascript
{ "resource": "" }
q13345
train
function(stdout, next) { var lines = stdout.split("\n"); var filenames = _.transform(lines, function(result, line) { var status = line.slice(0, 2); if (regExp.test(status)) { result.push(_.last(line.split(' '))); } }); next(null, filenames); }
javascript
{ "resource": "" }
q13346
train
function(filenames) { var isIn = _.some(filenames, function(line) { return file.path.indexOf(line) !== -1; }); if (isIn) { self.push(file); } callback(); }
javascript
{ "resource": "" }
q13347
Message
train
function Message(rawText){ this.rawText = rawText; this._parsed = false; this._isFetch = false; this._isNoop = false; this._list = []; this._search = []; this._fetch = { text: '' }; this._parse(); }
javascript
{ "resource": "" }
q13348
train
function () { if (this._lock) return this._lock = true let task = this._tasks.shift() let tstType = this.error ? ['catch', 'end'] : ['then', 'end'] while (task && !~tstType.indexOf(task.type)) { task = this._tasks.shift() } if (task) { let cb = (err, res) => { this.error = err this.result = res || this.result this._lock = false this._run() } let fn = task.fn if (task.type === 'end') { // .end fn(this.error, this.result) } else { try { if (task.type === 'catch') { // .catch fn(this.error, this.result, cb) } else { // .then fn(this.result, cb) } } catch (e) { cb(e) } } } else { this._lock = false } }
javascript
{ "resource": "" }
q13349
train
function(time) { var self = this; self.eventDetection.recordRelease(time); if (self.eventDetection.isLongPress()) { // this is a "long-press" - reset detection states and notify the "long-press" observers self.eventDetection.reset(); self._notifyObservers(self.onLongPressCallbackRegistry); } else { if (self.eventDetection.onReleaseCount >= 2) { // this is a double-press (or more) event, so notify the "double-press" observers self.eventDetection.reset(); self._notifyObservers(self.onDoublePressCallbackRegistry); } setTimeout(function(){ if (self.eventDetection.onReleaseCount == 1) { // second press did not occur within the allotted time, so notify the "short-press" observers self.eventDetection.reset(); self._notifyObservers(self.onShortPressCallbackRegistry); } }, 300); // @-@:p0 make this configurable? } }
javascript
{ "resource": "" }
q13350
longWait
train
function longWait (message, timer, cb) { setTimeout(function () { console.log(message); cb("pang"); //always return "pang" }, timer); //wait one second before logging }
javascript
{ "resource": "" }
q13351
resolveDeps
train
function resolveDeps (args) { return deps.map(function (dep) { if (args && args.length && typeof dep === 'number') { return args[dep]; } dep = that[dep]; if (dep) { return dep; } }); }
javascript
{ "resource": "" }
q13352
getInst
train
function getInst (bind, args) { args = resolveDeps(args); return isCtor ? applyCtor(func, args) : func.apply(bind, args); }
javascript
{ "resource": "" }
q13353
resolveInst
train
function resolveInst (bind, args) { return isTransient ? getInst(bind, args) : cache || (cache = getInst(bind)); }
javascript
{ "resource": "" }
q13354
init
train
function init (func) { func = ensureFunc(func); cache = undefined; deps = parseDepsFromFunc(func); }
javascript
{ "resource": "" }
q13355
getItemDefinedGroups
train
function getItemDefinedGroups() { var groups = {}, itemName, item, itemToolbar, group, order; for ( itemName in editor.ui.items ) { item = editor.ui.items[ itemName ]; itemToolbar = item.toolbar || 'others'; if ( itemToolbar ) { // Break the toolbar property into its parts: "group_name[,order]". itemToolbar = itemToolbar.split( ',' ); group = itemToolbar[ 0 ]; order = parseInt( itemToolbar[ 1 ] || -1, 10 ); // Initialize the group, if necessary. groups[ group ] || ( groups[ group ] = [] ); // Push the data used to build the toolbar later. groups[ group ].push( { name: itemName, order: order } ); } } // Put the items in the right order. for ( group in groups ) { groups[ group ] = groups[ group ].sort( function( a, b ) { return a.order == b.order ? 0 : b.order < 0 ? -1 : a.order < 0 ? 1 : a.order < b.order ? -1 : 1; } ); } return groups; }
javascript
{ "resource": "" }
q13356
train
function (query, page, callback) { var History = exports.get('History'); History.paginate(query, { page: page, limit: vulpejs.app.pagination.history, }, function (error, items, pageCount, itemCount) { if (error) { vulpejs.log.error('HISTORY', error); } else { callback(error, { items: items, pageCount: pageCount, itemCount: itemCount, }); } }, { sortBy: { version: -1, }, }); }
javascript
{ "resource": "" }
q13357
Request
train
function Request(server, keys, rejectable, config) { if (!config) config = {}; if (typeof config !== 'object') config = { path: config }; const promise = new Promise((resolve, reject) => { let fulfilled = false; this.on('res-complete', () => { if (fulfilled) { req.log('fulfilled', 'Already fulfilled'); } else { fulfilled = true; req.log('fulfilled'); resolve(res.state); } }); this.on('error', err => { req.log('error', err.stack.replace(/\n/g, '\n ')); if (fulfilled) { req.log('fulfilled', 'Already fulfilled'); } else { fulfilled = true; res.reset().set('content-type', 'text/plain').status(500).body(httpStatus[500]); req.log('fulfilled'); if (rejectable) { reject(err); } else { resolve(res.state); } } }); }); // initialize variables const id = uuid(); const hooks = {}; const req = this; const res = new Response(this, keys.response); /** * Get the unique ID associated with this request. * @name Request#id * @type {string} * @readonly */ Object.defineProperty(this, 'id', { configurable: false, enumerable: true, value: id }); /** * Get the response object that is tied to this request. * @name Request#res * @type {Response} */ Object.defineProperty(this, 'res', { configurable: false, enumerable: true, value: res }); /** * Get the server instance that initialized this request. * @name Request#server * @type {SansServer} */ Object.defineProperty(this, 'server', { enumerable: true, configurable: false, value: server }); /** * Get the request URL which consists of the path and the query parameters. * @name Request#url * @type {string} * @readonly */ Object.defineProperty(this, 'url', { configurable: false, enumerable: true, get: () => this.path + buildQueryString(this.query) }); /** * Add a rejection handler to the request promise. * @name Request#catch * @param {Function} onRejected * @returns {Promise} */ this.catch = onRejected => promise.catch(onRejected); /** * Produce a request log event. * @param {string} message * @param {...*} [args] * @returns {Request} * @fires Request#log */ this.log = this.logger('sans-server', 'request', this); /** * Add request specific hooks * @param {string} type * @param {number} [weight=0] * @param {...Function} hook * @returns {Request} */ this.hook = addHook.bind(this, hooks); /** * @name Request#hook.run * @param {Symbol} type * @param {function} [next] * @returns {Promise|undefined} */ this.hook.reverse = (type, next) => runHooksMode(req, hooks, 'reverse', type, next); /** * @name Request#hook.run * @param {Symbol} type * @param {function} [next] * @returns {Promise|undefined} */ this.hook.run = (type, next) => runHooksMode(req, hooks, 'run', type, next); /** * Add fulfillment or rejection handlers to the request promise. * @name Request#then * @param {Function} onFulfilled * @param {Function} [onRejected] * @returns {Promise} */ this.then = (onFulfilled, onRejected) => promise.then(onFulfilled, onRejected); /** * The request body. * @name Request#body * @type {string|Object|Buffer|undefined} */ /** * The request headers. This is an object that has lower-case keys and string values. * @name Request#headers * @type {Object<string,string>} */ /** * This request method. The lower case equivalents of these value are acceptable but will be automatically lower-cased. * @name Request#method * @type {string} One of: 'GET', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT' */ /** * The request path, beginning with a '/'. Does not include domain or query string. * @name Request#path * @type {string} */ /** * An object mapping query parameters by key. * @name Request#query * @type {object<string,string>} */ // validate and normalize input Object.assign(this, config, normalize(req, config)); // wait one tick for any event listeners to be added process.nextTick(() => { // run request hooks this.hook.run(keys.request) .then(() => { if (!res.sent) { req.log('unhandled', 'request not handled'); if (res.state.statusCode === 0) { res.sendStatus(404); } else { res.send(); } } }) .catch(err => { this.emit('error', err) }); }); }
javascript
{ "resource": "" }
q13358
Migrate
train
function Migrate (grunt, adapter, config, steps) { this.grunt = grunt; this.adapter = adapter; this.path = path.resolve(config.path); this.steps = steps; }
javascript
{ "resource": "" }
q13359
train
function(parent, protoProps, staticProps) { var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your extend definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ parent.apply(this, arguments); }; } // Inherit class (static) properties from parent. copyProps(child, parent); // Set the prototype chain to inherit from parent, without calling // parent's constructor function. ctor.prototype = parent.prototype; child.prototype = new ctor(); // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) copyProps(child.prototype, protoProps); // Add static properties to the constructor function, if supplied. if (staticProps) copyProps(child, staticProps); // Correctly set child's 'prototype.constructor'. child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed later. child.__super__ = parent.prototype; return child; }
javascript
{ "resource": "" }
q13360
train
function (finder) { if (mongo_query_options && mongo_query_options.sort) { finder.sort(mongo_query_options.sort).toArray(cb); } else { finder.toArray(cb); } }
javascript
{ "resource": "" }
q13361
train
function( editor ) { var selection = editor.getSelection(); var selectedElement = selection.getSelectedElement(); if ( selectedElement && selectedElement.is( 'a' ) ) return selectedElement; var range = selection.getRanges()[ 0 ]; if ( range ) { range.shrink( CKEDITOR.SHRINK_TEXT ); return editor.elementPath( range.getCommonAncestor() ).contains( 'a', 1 ); } return null; }
javascript
{ "resource": "" }
q13362
loadTemplate
train
function loadTemplate(template, name, callback) { async.waterfall([ cb => source(template.path, template.filter, template.readMode, cb), (files, cb) => asDataMap(files, template.mapping, cb), ], (error, result) => { async.nextTick(callback, error, result); }); }
javascript
{ "resource": "" }
q13363
Headers
train
function Headers (size, type, ttl, enc) { if (!(this instanceof Headers)) return new Headers(size, type, ttl, enc) if (size) this['Content-Length'] = size if (type) this['Content-Type'] = type if (!isNaN(ttl)) this['Cache-Control'] = 'max-age=' + ttl if (enc) this['Content-Encoding'] = enc }
javascript
{ "resource": "" }
q13364
train
function (next) { async.each(input, function (path, done) { fs.stat(path, function (err, stats) { if (err) return done(err); if (stats.isDirectory()) return done("Cannot have a directory as input"); done(); }); }, next); }
javascript
{ "resource": "" }
q13365
train
function( name ) { if ( ! munit.isString( name ) || ! name.length ) { throw new Error( "Name not found for removing formatter" ); } if ( render._formatHash[ name ] ) { delete render._formatHash[ name ]; render._formats = render._formats.filter(function( f ) { return f.name !== name; }); } }
javascript
{ "resource": "" }
q13366
train
function( path, callback ) { var parts = ( path || '' ).split( /\//g ), filepath = '/'; // Trim Left if ( ! parts[ 0 ].length ) { parts.shift(); } // Trim right if ( parts.length && ! parts[ parts.length - 1 ].length ) { parts.pop(); } // Handle root '/' error if ( ! parts.length ) { return callback( new Error( "No directory path found to make" ) ); } // Make sure each branch is created async.mapSeries( parts, function( dir, callback ) { fs.stat( filepath += dir + '/', function( e, stat ) { if ( stat && stat.isDirectory() ) { callback(); } else { fs.mkdir( filepath, callback ); } }); }, callback ); }
javascript
{ "resource": "" }
q13367
train
function( path, callback ) { var match = munit.isRegExp( render.options.file_match ) ? render.options.file_match : rtestfile; path += '/'; fs.readdir( path, function( e, files ) { if ( e ) { return callback( e ); } async.each( files || [], function( file, callback ) { var fullpath = path + file; fs.stat( fullpath, function( e, stat ) { if ( e ) { callback( e ); } else if ( stat.isDirectory() ) { render._renderPath( fullpath, callback ); } else { if ( stat.isFile() && match.exec( file ) ) { munit.require( fullpath ); } callback(); } }); }, callback ); }); }
javascript
{ "resource": "" }
q13368
train
function( nspath ) { var found = true, nsparts = nspath.split( rpathsplit ), focus = render.options.focus; // Allow single path string if ( munit.isString( focus ) ) { focus = [ focus ]; } // If set, only add modules that belong on the focus path(s) if ( munit.isArray( focus ) && focus.length ) { found = false; focus.forEach(function( fpath ) { var fparts = fpath.split( rpathsplit ), i = -1, l = Math.min( fparts.length, nsparts.length ); // Check that each namespace of the focus path // exists inside the modules path for ( ; ++i < l; ) { if ( fparts[ i ] !== nsparts[ i ] ) { return; } } // Paths line up found = true; }); } return found; }
javascript
{ "resource": "" }
q13369
train
function( required, startFunc ) { if ( required !== render.state ) { render._stateError( startFunc || render.requireState ); } }
javascript
{ "resource": "" }
q13370
train
function( ns ) { munit.each( ns, function( assert, name ) { if ( render.focusPath( assert.nsPath ) ) { munit.tests.push( assert ); } else { assert.trigger(); } // Traverse down the module tree render._renderNS( assert.ns ); }); return munit.tests; }
javascript
{ "resource": "" }
q13371
train
function( assert ) { var stack = [], depends, i, l, module; // Should only be checking dependencies when in compile mode render.requireMinState( munit.RENDER_STATE_COMPILE, render.checkDepency ); // Build up the list of dependency paths do { depends = assert.option( 'depends' ); // Allow single path if ( munit.isString( depends ) ) { stack.push( depends ); } // Add to stack of module dependencies else if ( munit.isArray( depends ) ) { stack = stack.concat( depends ); } } while ( assert = assert.parAssert ); // Check each dependency for completion for ( i = -1, l = stack.length; ++i < l; ) { if ( munit( stack[ i ] || '' ).state < munit.ASSERT_STATE_CLOSED ) { return false; } } return true; }
javascript
{ "resource": "" }
q13372
train
function(){ var options = render.options, path = options.render = render._normalizePath( options.render ); // Ensure render path actually exists fs.stat( path, function( e, stat ) { if ( e || ! stat || ! stat.isDirectory() ) { return munit.exit( 1, e, "'" + path + "' is not a directory" ); } // Check for root munit config file fs.exists( path + '/munit.js', function( exists ) { if ( exists ) { munit.require( path + '/munit.js' ); } // Initialize all files in test path for submodule additions render._renderPath( path, function( e ) { if ( e ) { return munit.exit( 1, e, "Unable to render test path" ); } render._compile(); }); }); }); }
javascript
{ "resource": "" }
q13373
train
function(){ // Swap render state to compile mode for priority generation render.requireState( munit.RENDER_STATE_READ, render._compile ); render.state = munit.RENDER_STATE_COMPILE; render._renderNS( munit.ns ); // Just in case triggers set off any undesired state render.requireState( munit.RENDER_STATE_COMPILE, render._compile ); render.state = munit.RENDER_STATE_TRIGGER; // Sort modules on priority munit.tests.sort(function( a, b ) { if ( a.options.priority === b.options.priority ) { return a._added > b._added ? 1 : -1; } else { return a.options.priority > b.options.priority ? -1 : 1; } }) // Trigger modules based on priority .forEach(function( assert ) { // Stack modules waiting on a queue if ( assert.options.queue ) { munit.queue.addModule( assert ); } else if ( render.checkDepency( assert ) ) { assert.trigger(); } }); // All modules triggered, check to see if we can close out render.state = munit.RENDER_STATE_ACTIVE; render.check(); }
javascript
{ "resource": "" }
q13374
train
function(){ var color = munit.color.get[ munit.failed > 0 ? 'red' : 'green' ], callback = render.callback; // Can only complete a finished munit state // (dont pass startFunc, we want _complete as part of the trace here) render.requireState( munit.RENDER_STATE_FINISHED ); render.state = munit.RENDER_STATE_COMPLETE; // Print out final results munit.log([ "\n", color( "Tests Passed: " + munit.passed ), color( "Tests Failed: " + munit.failed ), color( "Tests Skipped: " + munit.skipped ), color( "Time: " + munit._relativeTime( munit.end - munit.start ) ), "\n" ].join( "\n" )); // Only exit if there is an error (callback will be triggered there) if ( munit.failed > 0 ) { munit.exit( 1, "Test failed with " + munit.failed + " errors" ); } // Trigger callback if provided else if ( callback ) { render.callback = undefined; callback( null, munit ); } }
javascript
{ "resource": "" }
q13375
train
function( dir ) { // Make the root results directory first render._mkdir( dir, function( e ) { if ( e ) { return munit.exit( 1, e, "Failed to make root results directory" ); } // Make a working directory for each format async.each( render._formats, function( format, callback ) { var path = dir + format.name + '/'; render._mkdir( path, function( e ) { if ( e ) { callback( e ); } else { format.callback( path, callback ); } }); }, function( e ) { if ( e ) { munit.exit( 1, e ); } else { render._complete(); } } ); }); }
javascript
{ "resource": "" }
q13376
train
function(){ var finished = true, now = Date.now(), options = render.options, results = options.results ? render._normalizePath( options.results ) : null; // Wait until all modules have been triggered before checking states if ( render.state < munit.RENDER_STATE_ACTIVE ) { return; } // Can only check an active munit render.requireState( munit.RENDER_STATE_ACTIVE, render.check ); // Check each module munit.each( munit.ns, function( mod, name ) { if ( mod.state < munit.ASSERT_STATE_FINISHED ) { return ( finished = false ); } }); // Check dependency chains if test suite isn't yet finished if ( ! finished ) { munit.queue.check(); // Check each untriggered module to see if it's dependencies have been closed munit.tests.forEach(function( assert ) { if ( assert.state === munit.ASSERT_STATE_DEFAULT && ! assert.option( 'queue' ) && render.checkDepency( assert ) ) { assert.trigger(); } }); } // Only flush full results once all modules have completed else { render.state = munit.RENDER_STATE_FINISHED; munit.end = now; // Print out test results if ( results && results.length ) { render._renderResults( results + '/' ); } else { render._complete(); } } }
javascript
{ "resource": "" }
q13377
train
function(api, id, key, data) { // get storage object var obj = _getStorageObject(api, id); if(obj === null) { // create a new storage object obj = {}; } // update key obj[key] = data; // set storage object _setStorageObject(api, id, obj); }
javascript
{ "resource": "" }
q13378
train
function(api, id, key) { // get storage object var rval = _getStorageObject(api, id); if(rval !== null) { // return data at key rval = (key in rval) ? rval[key] : null; } return rval; }
javascript
{ "resource": "" }
q13379
train
function(api, id, key) { // get storage object var obj = _getStorageObject(api, id); if(obj !== null && key in obj) { // remove key delete obj[key]; // see if entry has no keys remaining var empty = true; for(var prop in obj) { empty = false; break; } if(empty) { // remove entry entirely if no keys are left obj = null; } // set storage object _setStorageObject(api, id, obj); } }
javascript
{ "resource": "" }
q13380
train
function(func, args, location) { var rval = null; // default storage types if(typeof(location) === 'undefined') { location = ['web', 'flash']; } // apply storage types in order of preference var type; var done = false; var exception = null; for(var idx in location) { type = location[idx]; try { if(type === 'flash' || type === 'both') { if(args[0] === null) { throw new Error('Flash local storage not available.'); } else { rval = func.apply(this, args); done = (type === 'flash'); } } if(type === 'web' || type === 'both') { args[0] = localStorage; rval = func.apply(this, args); done = true; } } catch(ex) { exception = ex; } if(done) { break; } } if(!done) { throw exception; } return rval; }
javascript
{ "resource": "" }
q13381
train
function(b) { var b2 = b.getByte(); if(b2 === 0x80) { return undefined; } // see if the length is "short form" or "long form" (bit 8 set) var length; var longForm = b2 & 0x80; if(!longForm) { // length is just the first byte length = b2; } else { // the number of bytes the length is specified in bits 7 through 1 // and each length byte is in big-endian base-256 length = b.getInt((b2 & 0x7F) << 3); } return length; }
javascript
{ "resource": "" }
q13382
_reseedSync
train
function _reseedSync() { if(ctx.pools[0].messageLength >= 32) { return _seed(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.collect(ctx.seedFileSync(needed)); _seed(); }
javascript
{ "resource": "" }
q13383
_seed
train
function _seed() { // create a plugin-based message digest var md = ctx.plugin.md.create(); // digest pool 0's entropy and restart it md.update(ctx.pools[0].digest().getBytes()); ctx.pools[0].start(); // digest the entropy of other pools whose index k meet the // condition '2^k mod n == 0' where n is the number of reseeds var k = 1; for(var i = 1; i < 32; ++i) { // prevent signed numbers from being used k = (k === 31) ? 0x80000000 : (k << 2); if(k % ctx.reseeds === 0) { md.update(ctx.pools[i].digest().getBytes()); ctx.pools[i].start(); } } // get digest for key bytes and iterate again for seed bytes var keyBytes = md.digest().getBytes(); md.start(); md.update(keyBytes); var seedBytes = md.digest().getBytes(); // update ctx.key = ctx.plugin.formatKey(keyBytes); ctx.seed = ctx.plugin.formatSeed(seedBytes); ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; ctx.generated = 0; }
javascript
{ "resource": "" }
q13384
defaultSeedFile
train
function defaultSeedFile(needed) { // use window.crypto.getRandomValues strong source of entropy if available var getRandomValues = null; if(typeof window !== 'undefined') { var _crypto = window.crypto || window.msCrypto; if(_crypto && _crypto.getRandomValues) { getRandomValues = function(arr) { return _crypto.getRandomValues(arr); }; } } var b = forge.util.createBuffer(); if(getRandomValues) { while(b.length() < needed) { // max byte length is 65536 before QuotaExceededError is thrown // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); var entropy = new Uint32Array(Math.floor(count)); try { getRandomValues(entropy); for(var i = 0; i < entropy.length; ++i) { b.putInt32(entropy[i]); } } catch(e) { /* only ignore QuotaExceededError */ if(!(typeof QuotaExceededError !== 'undefined' && e instanceof QuotaExceededError)) { throw e; } } } } // be sad and add some weak random data if(b.length() < needed) { /* Draws from Park-Miller "minimal standard" 31 bit PRNG, implemented with David G. Carta's optimization: with 32 bit math and without division (Public Domain). */ var hi, lo, next; var seed = Math.floor(Math.random() * 0x010000); while(b.length() < needed) { lo = 16807 * (seed & 0xFFFF); hi = 16807 * (seed >> 16); lo += (hi & 0x7FFF) << 16; lo += hi >> 15; lo = (lo & 0x7FFFFFFF) + (lo >> 31); seed = lo & 0xFFFFFFFF; // consume lower 3 bytes of seed for(var i = 0; i < 3; ++i) { // throw in more pseudo random next = seed >>> (i << 3); next ^= Math.floor(Math.random() * 0x0100); b.putByte(String.fromCharCode(next & 0xFF)); } } } return b.getBytes(needed); }
javascript
{ "resource": "" }
q13385
spawnPrng
train
function spawnPrng() { var ctx = forge.prng.create(prng_aes); /** * Gets random bytes. If a native secure crypto API is unavailable, this * method tries to make the bytes more unpredictable by drawing from data that * can be collected from the user of the browser, eg: mouse movement. * * If a callback is given, this method will be called asynchronously. * * @param count the number of random bytes to get. * @param [callback(err, bytes)] called once the operation completes. * * @return the random bytes in a string. */ ctx.getBytes = function(count, callback) { return ctx.generate(count, callback); }; /** * Gets random bytes asynchronously. If a native secure crypto API is * unavailable, this method tries to make the bytes more unpredictable by * drawing from data that can be collected from the user of the browser, * eg: mouse movement. * * @param count the number of random bytes to get. * * @return the random bytes in a string. */ ctx.getBytesSync = function(count) { return ctx.generate(count); }; return ctx; }
javascript
{ "resource": "" }
q13386
train
function(plan) { var R = []; /* Get data from input buffer and fill the four words into R */ for(i = 0; i < 4; i ++) { var val = _input.getInt16Le(); if(_iv !== null) { if(encrypt) { /* We're encrypting, apply the IV first. */ val ^= _iv.getInt16Le(); } else { /* We're decryption, keep cipher text for next block. */ _iv.putInt16Le(val); } } R.push(val & 0xffff); } /* Reset global "j" variable as per spec. */ j = encrypt ? 0 : 63; /* Run execution plan. */ for(var ptr = 0; ptr < plan.length; ptr ++) { for(var ctr = 0; ctr < plan[ptr][0]; ctr ++) { plan[ptr][1](R); } } /* Write back result to output buffer. */ for(i = 0; i < 4; i ++) { if(_iv !== null) { if(encrypt) { /* We're encrypting in CBC-mode, feed back encrypted bytes into IV buffer to carry it forward to next block. */ _iv.putInt16Le(R[i]); } else { R[i] ^= _iv.getInt16Le(); } } _output.putInt16Le(R[i]); } }
javascript
{ "resource": "" }
q13387
train
function(input) { if(!_finish) { // not finishing, so fill the input buffer with more input _input.putBuffer(input); } while(_input.length() >= 8) { runPlan([ [ 5, mixRound ], [ 1, mashRound ], [ 6, mixRound ], [ 1, mashRound ], [ 5, mixRound ] ]); } }
javascript
{ "resource": "" }
q13388
train
function(pad) { var rval = true; if(encrypt) { if(pad) { rval = pad(8, _input, !encrypt); } else { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); _input.fillWithByte(padding, padding); } } if(rval) { // do final update _finish = true; cipher.update(); } if(!encrypt) { // check for error: input data not a multiple of block size rval = (_input.length() === 0); if(rval) { if(pad) { rval = pad(8, _output, !encrypt); } else { // ensure padding byte count is valid var len = _output.length(); var count = _output.at(len - 1); if(count > len) { rval = false; } else { // trim off padding bytes _output.truncate(count); } } } } return rval; }
javascript
{ "resource": "" }
q13389
bnGetPrng
train
function bnGetPrng() { // create prng with api that matches BigInteger secure random return { // x is an array to fill with bytes nextBytes: function(x) { for(var i = 0; i < x.length; ++i) { x[i] = Math.floor(Math.random() * 0xFF); } } }; }
javascript
{ "resource": "" }
q13390
getPrime
train
function getPrime(bits, callback) { // TODO: consider optimizing by starting workers outside getPrime() ... // note that in order to clean up they will have to be made internally // asynchronous which may actually be slower // start workers immediately var workers = []; for(var i = 0; i < numWorkers; ++i) { // FIXME: fix path or use blob URLs workers[i] = new Worker(workerScript); } var running = numWorkers; // initialize random number var num = generateRandom(); // listen for requests from workers and assign ranges to find prime for(var i = 0; i < numWorkers; ++i) { workers[i].addEventListener('message', workerMessage); } /* Note: The distribution of random numbers is unknown. Therefore, each web worker is continuously allocated a range of numbers to check for a random number until one is found. Every 30 numbers will be checked just 8 times, because prime numbers have the form: 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) Therefore, if we want a web worker to run N checks before asking for a new range of numbers, each range must contain N*30/8 numbers. For 100 checks (workLoad), this is a range of 375. */ function generateRandom() { var bits1 = bits - 1; var num = new BigInteger(bits, state.rng); // force MSB set if(!num.testBit(bits1)) { num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); } // align number on 30k+1 boundary num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); return num; } var found = false; function workerMessage(e) { // ignore message, prime already found if(found) { return; } --running; var data = e.data; if(data.found) { // terminate all workers for(var i = 0; i < workers.length; ++i) { workers[i].terminate(); } found = true; return callback(null, new BigInteger(data.prime, 16)); } // overflow, regenerate prime if(num.bitLength() > bits) { num = generateRandom(); } // assign new range to check var hex = num.toString(16); // start prime search e.target.postMessage({ e: state.eInt, hex: hex, workLoad: workLoad }); num.dAddOffset(range, 0); } }
javascript
{ "resource": "" }
q13391
_bnToBytes
train
function _bnToBytes(b) { // prepend 0x00 if first byte >= 0x80 var hex = b.toString(16); if(hex[0] >= '8') { hex = '00' + hex; } return forge.util.hexToBytes(hex); }
javascript
{ "resource": "" }
q13392
evpBytesToKey
train
function evpBytesToKey(password, salt, dkLen) { var digests = [md5(password + salt)]; for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { digests.push(md5(digests[i - 1] + password + salt)); } return digests.join('').substr(0, dkLen); }
javascript
{ "resource": "" }
q13393
_extensionsToAsn1
train
function _extensionsToAsn1(exts) { // create top-level extension container var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); // create extension sequence (stores a sequence for each extension) var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); rval.value.push(seq); var ext, extseq; for(var i = 0; i < exts.length; ++i) { ext = exts[i]; // create a sequence for each extension extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); seq.value.push(extseq); // extnID (OID) extseq.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ext.id).getBytes())); // critical defaults to false if(ext.critical) { // critical BOOLEAN DEFAULT FALSE extseq.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(0xFF))); } var value = ext.value; if(typeof ext.value !== 'string') { // value is asn.1 value = asn1.toDer(value).getBytes(); } // extnValue (OCTET STRING) extseq.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); } return rval; }
javascript
{ "resource": "" }
q13394
_CRIAttributesToAsn1
train
function _CRIAttributesToAsn1(csr) { // create an empty context-specific container var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); // no attributes, return empty container if(csr.attributes.length === 0) { return rval; } // each attribute has a sequence with a type and a set of values var attrs = csr.attributes; for(var i = 0; i < attrs.length; ++i) { var attr = attrs[i]; var value = attr.value; // reuse tag class for attribute value if available var valueTagClass = asn1.Type.UTF8; if('valueTagClass' in attr) { valueTagClass = attr.valueTagClass; } if(valueTagClass === asn1.Type.UTF8) { value = forge.util.encodeUtf8(value); } // FIXME: handle more encodings // create a RelativeDistinguishedName set // each value in the set is an AttributeTypeAndValue first // containing the type (an OID) and second the value var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AttributeType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ // AttributeValue asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) ]) ]); rval.value.push(seq); } return rval; }
javascript
{ "resource": "" }
q13395
train
function(filter) { var rval = {}; var localKeyId; if('localKeyId' in filter) { localKeyId = filter.localKeyId; } else if('localKeyIdHex' in filter) { localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); } // filter on bagType only if(localKeyId === undefined && !('friendlyName' in filter) && 'bagType' in filter) { rval[filter.bagType] = _getBagsByAttribute( pfx.safeContents, null, null, filter.bagType); } if(localKeyId !== undefined) { rval.localKeyId = _getBagsByAttribute( pfx.safeContents, 'localKeyId', localKeyId, filter.bagType); } if('friendlyName' in filter) { rval.friendlyName = _getBagsByAttribute( pfx.safeContents, 'friendlyName', filter.friendlyName, filter.bagType); } return rval; }
javascript
{ "resource": "" }
q13396
train
function(secret, label, seed, length) { var rval = forge.util.createBuffer(); /* For TLS 1.0, the secret is split in half, into two secrets of equal length. If the secret has an odd length then the last byte of the first half will be the same as the first byte of the second. The length of the two secrets is half of the secret rounded up. */ var idx = (secret.length >> 1); var slen = idx + (secret.length & 1); var s1 = secret.substr(0, slen); var s2 = secret.substr(idx, slen); var ai = forge.util.createBuffer(); var hmac = forge.hmac.create(); seed = label + seed; // determine the number of iterations that must be performed to generate // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 var md5itr = Math.ceil(length / 16); var sha1itr = Math.ceil(length / 20); // do md5 iterations hmac.start('MD5', s1); var md5bytes = forge.util.createBuffer(); ai.putBytes(seed); for(var i = 0; i < md5itr; ++i) { // HMAC_hash(secret, A(i-1)) hmac.start(null, null); hmac.update(ai.getBytes()); ai.putBuffer(hmac.digest()); // HMAC_hash(secret, A(i) + seed) hmac.start(null, null); hmac.update(ai.bytes() + seed); md5bytes.putBuffer(hmac.digest()); } // do sha1 iterations hmac.start('SHA1', s2); var sha1bytes = forge.util.createBuffer(); ai.clear(); ai.putBytes(seed); for(var i = 0; i < sha1itr; ++i) { // HMAC_hash(secret, A(i-1)) hmac.start(null, null); hmac.update(ai.getBytes()); ai.putBuffer(hmac.digest()); // HMAC_hash(secret, A(i) + seed) hmac.start(null, null); hmac.update(ai.bytes() + seed); sha1bytes.putBuffer(hmac.digest()); } // XOR the md5 bytes with the sha1 bytes rval.putBytes(forge.util.xorBytes( md5bytes.getBytes(), sha1bytes.getBytes(), length)); return rval; }
javascript
{ "resource": "" }
q13397
train
function(key, seqNum, record) { /* MAC is computed like so: HMAC_hash( key, seqNum + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length + TLSCompressed.fragment) */ var hmac = forge.hmac.create(); hmac.start('SHA1', key); var b = forge.util.createBuffer(); b.putInt32(seqNum[0]); b.putInt32(seqNum[1]); b.putByte(record.type); b.putByte(record.version.major); b.putByte(record.version.minor); b.putInt16(record.length); b.putBytes(record.fragment.bytes()); hmac.update(b.getBytes()); return hmac.digest().getBytes(); }
javascript
{ "resource": "" }
q13398
encrypt_aes_cbc_sha1
train
function encrypt_aes_cbc_sha1(record, s) { var rval = false; // append MAC to fragment, update sequence number var mac = s.macFunction(s.macKey, s.sequenceNumber, record); record.fragment.putBytes(mac); s.updateSequenceNumber(); // TLS 1.1+ use an explicit IV every time to protect against CBC attacks var iv; if(record.version.minor === tls.Versions.TLS_1_0.minor) { // use the pre-generated IV when initializing for TLS 1.0, otherwise use // the residue from the previous encryption iv = s.cipherState.init ? null : s.cipherState.iv; } else { iv = forge.random.getBytesSync(16); } s.cipherState.init = true; // start cipher var cipher = s.cipherState.cipher; cipher.start({iv: iv}); // TLS 1.1+ write IV into output if(record.version.minor >= tls.Versions.TLS_1_1.minor) { cipher.output.putBytes(iv); } // do encryption (default padding is appropriate) cipher.update(record.fragment); if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { // set record fragment to encrypted output record.fragment = cipher.output; record.length = record.fragment.length(); rval = true; } return rval; }
javascript
{ "resource": "" }
q13399
decrypt_aes_cbc_sha1_padding
train
function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { var rval = true; if(decrypt) { /* The last byte in the output specifies the number of padding bytes not including itself. Each of the padding bytes has the same value as that last byte (known as the padding_length). Here we check all padding bytes to ensure they have the value of padding_length even if one of them is bad in order to ward-off timing attacks. */ var len = output.length(); var paddingLength = output.last(); for(var i = len - 1 - paddingLength; i < len - 1; ++i) { rval = rval && (output.at(i) == paddingLength); } if(rval) { // trim off padding bytes and last padding length byte output.truncate(paddingLength + 1); } } return rval; }
javascript
{ "resource": "" }