_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36900
sha1hex
train
function sha1hex(source) { var hash = crypto.createHash(SHA1); hash.update(new Buffer('' + source)); return hash.digest(ENCODING); }
javascript
{ "resource": "" }
q36901
load
train
function load(source) { var redis , method , script , name , digest; digest = sha1hex(source); if(this._cache[digest]) { return {script: this._cache[digest], sha: digest}; } name = 'f_' + digest; method = util.format( 'var method = function %s(KEYS, ARGS, cb) {%s}', name, source); // declare the method try { script = vm.createScript(method, name); }catch(e) { return process.send( { err: true, data: 'error compiling script (new function): user_script: ' + e.message}); } // cache the method by digest this._cache[digest] = script; log.debug('script load: %s', digest); return {sha: digest, script: script}; }
javascript
{ "resource": "" }
q36902
exec
train
function exec(script, numkeys) { var KEYS = slice.call(arguments, 2, 2 + numkeys); var ARGS = slice.call(arguments, numkeys + 2); function cb(err, reply) { if(err) reply = err.message; process.send( { err: (err instanceof Error), data: reply, str: (reply instanceof String) }); } var redis = { sha1hex: sha1hex, error_reply: function(err) { return new Error(err) }, status_reply: function(status) { return new String(status) }, call: function(cmd) { //console.dir('calling out with: ' + cmd); var args = slice.call(arguments, 1) , callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; function onMessage(msg) { if(cb) { if(msg.err) return cb(new Error(msg.data)); cb(null, msg.data); } } process.once('message', onMessage); process.send({event: 'call', cmd: cmd, args: args}); return callback || cb; }, LOG_DEBUG: logger.DEBUG, LOG_VERBOSE: logger.VERBOSE, LOG_NOTICE: logger.NOTICE, LOG_WARNING: logger.WARNING, log: function rlog() { return log.log.apply(log, arguments); } } //console.dir(redis); var sandbox = { Error: Error, Buffer: Buffer, JSON: JSON, crypto: crypto, util: util, redis: redis, KEYS: KEYS, ARGS: ARGS, cb: cb } script.runInNewContext(sandbox); process.send({event: 'eval', data: sandbox.method.name}); var result; try { result = sandbox.method(sandbox.KEYS, sandbox.ARGS, sandbox.cb); // coerce thrown errors }catch(e) { result = e; } //console.dir(result); if(Buffer.isBuffer(result)) { result = result.toString(); } if(result && !(result instanceof Error) && typeof result === 'object') { if(result.err) { result = new Error(result.err); }else if(result.ok) { result = new String(result.ok); } } //console.dir(result); return { result: result, sandbox: sandbox, script: script, name: sandbox.method.name }; }
javascript
{ "resource": "" }
q36903
run
train
function run(script, args) { var res, result, name; try { res = this.exec.apply(this, [script].concat(args)); result = res.result; //console.dir(result); //console.dir(result instanceof Error); if(typeof result === 'function') return; if(result === undefined) { throw new Error('undefined return value is not allowed'); }else if( result !== null && !(result instanceof String) && !(result instanceof Error) && typeof result === 'object' && !Array.isArray(result)) { throw new Error('object return value is not allowed'); } }catch(e) { name = res && res.name ? res.name : 'user_script'; result = new StoreError( null, 'error running script (call to %s): %s', name, e.message); } if(typeof result === 'boolean') { result = Number(result); } // TODO: check the return value is not an object!!! // var err = (result instanceof Error); if(err) result = result.message; process.send({err: err, data: result, str: (result instanceof String)}); }
javascript
{ "resource": "" }
q36904
exists
train
function exists(args) { var list = []; for(var i = 0;i < args.length;i++) { list.push(this._cache[args[i]] ? 1 : 0); } return list; }
javascript
{ "resource": "" }
q36905
fixContainer
train
function fixContainer ( container ) { var children = container.childNodes, doc = container.ownerDocument, wrapper = null, i, l, child, isBR, config = getSquireInstance( doc )._config; for ( i = 0, l = children.length; i < l; i += 1 ) { child = children[i]; isBR = child.nodeName === 'BR'; if ( !isBR && isInline( child ) ) { if ( !wrapper ) { wrapper = createElement( doc, config.blockTag, config.blockAttributes ); } wrapper.appendChild( child ); i -= 1; l -= 1; } else if ( isBR || wrapper ) { if ( !wrapper ) { wrapper = createElement( doc, config.blockTag, config.blockAttributes ); } fixCursor( wrapper ); if ( isBR ) { container.replaceChild( wrapper, child ); } else { container.insertBefore( wrapper, child ); i += 1; l += 1; } wrapper = null; } if ( isContainer( child ) ) { fixContainer( child ); } } if ( wrapper ) { container.appendChild( fixCursor( wrapper ) ); } return container; }
javascript
{ "resource": "" }
q36906
train
function ( node, exemplar ) { // If the node is completely contained by the range then // we're going to remove all formatting so ignore it. if ( isNodeContainedInRange( range, node, false ) ) { return; } var isText = ( node.nodeType === TEXT_NODE ), child, next; // If not at least partially contained, wrap entire contents // in a clone of the tag we're removing and we're done. if ( !isNodeContainedInRange( range, node, true ) ) { // Ignore bookmarks and empty text nodes if ( node.nodeName !== 'INPUT' && ( !isText || node.data ) ) { toWrap.push([ exemplar, node ]); } return; } // Split any partially selected text nodes. if ( isText ) { if ( node === endContainer && endOffset !== node.length ) { toWrap.push([ exemplar, node.splitText( endOffset ) ]); } if ( node === startContainer && startOffset ) { node.splitText( startOffset ); toWrap.push([ exemplar, node ]); } } // If not a text node, recurse onto all children. // Beware, the tree may be rewritten with each call // to examineNode, hence find the next sibling first. else { for ( child = node.firstChild; child; child = next ) { next = child.nextSibling; examineNode( child, exemplar ); } } }
javascript
{ "resource": "" }
q36907
compose
train
function compose(auto_template, dictionary, key, params) { var composer = dictionary[key]; // If auto_template is set to true, make dictionary value if (auto_template) { if (typeof composer === "string") { composer = _.template(composer); } else if (typeof composer !== "function" ) { var msg = 'Expected value to auto-template - "' + composer + '" - to be type "string"'; msg += ' but got "' + typeof composer + '".'; throw new Error(msg); } } switch (typeof composer) { case "string": return composer; case "function": return composer(params); default: { var msg = 'Unprocessable message "' + composer + '" of type "' + typeof composer; msg += '" for key "' + key + '".' throw new Error(msg); } } }
javascript
{ "resource": "" }
q36908
resolveSerializer
train
function resolveSerializer(key) { var serializer = SERIALIZERS[key] || key; if (!_.isFunction(serializer)) { grunt.fail.warn('Invalid serializer. Serializer needs to be a function.'); } return serializer; }
javascript
{ "resource": "" }
q36909
extractInfoFromAst
train
function extractInfoFromAst( ast ) { const output = { requires: [], exports: findExports( ast ) }; recursivelyExtractInfoFromAst( ast.program.body, output ); return output; }
javascript
{ "resource": "" }
q36910
findExports
train
function findExports( ast ) { try { const publics = {}, privates = {}, body = ast.program.body[ 0 ].expression.arguments[ 1 ].body.body; body.forEach( function ( item ) { if ( parseExports( item, publics ) ) return; if ( parseModuleExports( item, publics ) ) return; parseFunctionDeclaration( item, privates ); } ); const output = []; Object.keys( publics ).forEach( function ( exportName ) { const exportValue = publics[ exportName ], target = privates[ exportValue.target ]; if ( target ) { exportValue.comments = exportValue.comments || target.comments; exportValue.type = target.type; exportValue.params = target.params; } output.push( { id: exportName, type: exportValue.type, params: exportValue.params, comments: exportValue.comments } ); } ); return output; } catch ( ex ) { throw new Error( `${ex}\n...in module-analyser/findExports()` ); } }
javascript
{ "resource": "" }
q36911
exif
train
function exif (file) { "use strict"; var deferred = Q.defer(), o = {}; new ExifImage({ image : file }, function (error, data) { if (error) { // callback.call("error " + file); deferred.reject("ERROR"); } if (data) { o.file = file; o.data = data; deferred.resolve(o); } }); return deferred.promise; }
javascript
{ "resource": "" }
q36912
train
function(index) { //Check the index value if(index >= keys.length) { //Do the callback and exit return cb(null); } else { //Get the key var key = (is_array) ? index : keys[index]; //Get the value var value = list[key]; //Call the provided method with the element of the array return fn.call(null, key, value, function(error) { //Check the error if(error) { //Do the callback with the provided error return cb(error); } else { //Continue with the next item on the list return each_async(index + 1); } }); } }
javascript
{ "resource": "" }
q36913
train
function(field, val){ if (2 == arguments.length) { if (Array.isArray(val)) val = val.map(String); else val = String(val); this.res.setHeader(field, val); } else { for (var key in field) { this.set(key, field[key]); } } }
javascript
{ "resource": "" }
q36914
train
function(field, val){ var prev = this.get(field); if (prev) { val = Array.isArray(prev) ? prev.concat(val) : [prev].concat(val); } return this.set(field, val); }
javascript
{ "resource": "" }
q36915
train
function (options) { options = options || {} this.isTTY = process.stdout.isTTY || false this.useColors = options.useColors || this.isTTY }
javascript
{ "resource": "" }
q36916
from
train
function from(arg){ if(!_.isArray(arg) && !_.isArguments(arg)) arg = [arg]; return _.toArray(arg); }
javascript
{ "resource": "" }
q36917
joinLast
train
function joinLast(obj, glue, stick){ if(_.size(obj) == 1) return obj[0]; var last = obj.pop(); return obj.join(glue) + stick + last; }
javascript
{ "resource": "" }
q36918
getFromPath
train
function getFromPath(obj, path){ path = path.split('.'); for(var i = 0, l = path.length; i < l; i++){ if (hasOwnProperty.call(obj, path[i])) obj = obj[path[i]]; else return undefined; } return obj; }
javascript
{ "resource": "" }
q36919
setFromPath
train
function setFromPath(obj, path, value){ var parts = path.split('.'); for(var i = 0, l = parts.length; i < l; i++){ if(i < (l - 1) && !obj.hasOwnProperty(parts[i])) obj[parts[i]] = {}; if(i == l - 1) obj[parts[i]] = value; else obj = obj[parts[i]]; } return obj; }
javascript
{ "resource": "" }
q36920
eraseFromPath
train
function eraseFromPath(obj, path){ var parts = path.split('.'), clone = obj; for(var i = 0, l = parts.length; i < l; i++){ if (!obj.hasOwnProperty(parts[i])){ break; } else if (i < l - 1){ obj = obj[parts[i]]; } else if(i == l - 1){ delete obj[parts[i]]; break; } } return clone; }
javascript
{ "resource": "" }
q36921
keyOf
train
function keyOf(obj, value){ for(var key in obj) if(Object.prototype.hasOwnProperty.call(obj, key) && obj[key] === value) return key; return null; }
javascript
{ "resource": "" }
q36922
isLaxEqual
train
function isLaxEqual(a, b){ if(_.isArray(a)) a = _.uniq(a.sort()); if(_.isArray(b)) b = _.uniq(b.sort()); return _.isEqual(a, b); }
javascript
{ "resource": "" }
q36923
eachParallel
train
function eachParallel(obj, iterator, cb, max, bind){ if(!_.isFinite(max)) max = _.size(obj); var stepsToGo = _.size(obj), chunks = _.isIterable(obj) ? _.norris(obj, max) : _.chunk(obj, max); _.eachAsync(chunks, function(chunk, chunkKey, chunkCursor){ var chunkIndex = 0; _.each(chunk, function(item, key){ function cursor(){ stepsToGo--; if(chunkIndex + 1 == max || stepsToGo == 0) chunkCursor(); chunkIndex++; }; iterator.call(bind, item, key, cursor, obj); }); }, cb, bind); return obj; }
javascript
{ "resource": "" }
q36924
closest
train
function closest(obj, number){ if((current = obj.length) < 2) return l - 1; for(var current, previous = Math.abs(obj[--current] - number); current--;) if(previous < (previous = Math.abs(obj[current] - number))) break; return obj[current + 1]; var closest = -1, prev = Math.abs(obj[0] - number); for (var i = 1; i < obj.length; i++){ var diff = Math.abs(obj[i] - number); if (diff <= prev){ prev = diff; closest = obj[i]; } } return closest; }
javascript
{ "resource": "" }
q36925
attempt
train
function attempt(fn){ try { var args = _.from(arguments); args.shift(); return fn.apply(this, args); } catch(e){ return false; } }
javascript
{ "resource": "" }
q36926
straitjacket
train
function straitjacket(fn, defaultValue){ return function(){ try { var args = _.from(arguments); return fn.apply(this, args); } catch(e){ return defaultValue; } } }
javascript
{ "resource": "" }
q36927
encodeArray
train
function encodeArray(array, proto, offset, buffer, protos){ let i = 0; if(util.isSimpleType(proto.type)){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length)); for(i = 0; i < array.length; i++){ offset = encodeProp(array[i], proto.type, offset, buffer); } }else{ for(i = 0; i < array.length; i++){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = encodeProp(array[i], proto.type, offset, buffer, protos); } } return offset; }
javascript
{ "resource": "" }
q36928
flush
train
function flush(done) { if (checkWatchify(browserify)) { var full_paths = mutils.toResolvePaths([].concat(options.files).concat(options.getFiles())); // add require target files mcached.collectRequirePaths(full_paths, function (collect_file_sources) { var collect_full_paths = Object.keys(collect_file_sources); // NOTE : keep wildcard path watchFile(_.uniq(full_paths.concat(collect_full_paths))); watched = true; oncomplete(); }); } else { watched = true; } done(); }
javascript
{ "resource": "" }
q36929
RunnerContext
train
function RunnerContext(argv, config, env) { argv.tasks = argv._.length ? argv._ : ['default']; this.argv = argv; this.config = config; this.env = env; this.json = loadConfig(this.argv.cwd, this.env); this.pkg = loadPkg(this.argv.cwd, this.env); this.pkgConfig = this.pkg[env.name] || {}; this.options = merge({}, this.pkgConfig.options, this.json.options); }
javascript
{ "resource": "" }
q36930
validateRunnerArgs
train
function validateRunnerArgs(Ctor, config, argv, cb) { if (typeof cb !== 'function') { throw new Error('expected a callback function'); } if (argv == null || typeof argv !== 'object') { return new Error('expected the third argument to be an options object'); } if (config == null || typeof config !== 'object') { return new Error('expected the second argument to be a liftoff config object'); } if (typeof Ctor !== 'function' || typeof Ctor.namespace !== 'function') { return new Error('expected the first argument to be a Base constructor'); } }
javascript
{ "resource": "" }
q36931
train
function(err, stdout, stderr) { if(err) return callback(err); // Get the transformed source var source = stdout; // Compile the function eval(source) // Return the validation function callback(null, { validate: func }); }
javascript
{ "resource": "" }
q36932
train
function(object, methods, property) { for (var i = 0, ii = methods.length; i < ii; ++i) { this.addMethodToObject(methods[i], object, property); } }
javascript
{ "resource": "" }
q36933
train
function(name, object, property) { var method = this.createMethod(name, property); object[method.name] = method.body; }
javascript
{ "resource": "" }
q36934
train
function(name, property) { if (!(name in this._methods)) { throw new Error('Method "' + name + '" does not exist!'); } var method = this._methods[name](property); if (_.isFunction(method)) { method = { name: this.getMethodName(property, name), body: method } } return method; }
javascript
{ "resource": "" }
q36935
train
function(property, method) { var prefix = ''; property = property.replace(/^(_+)/g, function(str) { prefix = str; return ''; }); var methodName = 'is' === method && 0 === property.indexOf('is') ? property : method + property[0].toUpperCase() + property.slice(1); return prefix + methodName; }
javascript
{ "resource": "" }
q36936
train
function(property) { return function(fields) { fields = _.isString(fields) ? fields.split('.') : fields || []; return this.__hasPropertyValue([property].concat(fields)); } }
javascript
{ "resource": "" }
q36937
request
train
function request( url, args ) { return new Promise( function( resolve, reject ) { const xhr = new XMLHttpRequest(); xhr.open( "POST", url, true ); // true is for async. xhr.onload = () => { const DONE = 4; if ( xhr.readyState !== DONE ) return; console.info( "xhr.status=", xhr.status ); console.info( "xhr.responseText=", xhr.responseText ); if ( xhr.status === 200 ) resolve( xhr.responseText ); /* else reject( { id: exports.HTTP_ERROR, msg: "(" + xhr.status + ") " + xhr.statusText, status: xhr.status } ); */ }; xhr.onerror = function() { reject( { id: exports.HTTP_ERROR, err: "HTTP_ERROR (" + xhr.status + ") " + xhr.statusText, status: xhr.status } ); }; const params = Object.keys( args ) .map( key => `${key}=${encodeURIComponent(args[key])}` ) .join( "&" ); xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" ); xhr.send( params ); } ); }
javascript
{ "resource": "" }
q36938
loadJSON
train
function loadJSON( path ) { return new Promise( function( resolve, reject ) { var xhr = new XMLHttpRequest( { mozSystem: true } ); xhr.onload = function() { var text = xhr.responseText; try { resolve( JSON.parse( text ) ); } catch ( ex ) { reject( Error( "Bad JSON format for \"" + path + "\"!\n" + ex + "\n" + text ) ); } }; xhr.onerror = function() { reject( Error( "Unable to load file \"" + path + "\"!\n" + xhr.statusText ) ); }; xhr.open( "GET", path, true ); xhr.withCredentials = true; // Indispensable pour le CORS. xhr.send(); } ); }
javascript
{ "resource": "" }
q36939
logout
train
function logout() { currentUser = null; delete config.usr; delete config.pwd; Storage.local.set( "nigolotua", null ); exports.eventChange.fire(); return svc( "tfw.login.Logout" ); }
javascript
{ "resource": "" }
q36940
callWebService
train
function callWebService( name, args, url ) { return new Promise( function( resolve, reject ) { svc( name, args, url ).then( resolve, function( err ) { if ( typeof err === 'object' && err.id === exports.BAD_ROLE ) { // Echec de connexion, on retente de se connecter avant d'abandonner. login().then( function() { svc( name, args, url ).then( resolve, reject ); }, reject ); } else { reject( err ); } } ); } ); }
javascript
{ "resource": "" }
q36941
_reLayout
train
function _reLayout (context, virtualRect, ltbr) { const el = context.$el const rect = _getIndicatorRect(el) const rectWithPx = Object.keys(rect).reduce((pre, key) => { pre[key] = rect[key] + 'px' return pre }, {}) extend(el.style, rectWithPx) const axisMap = [ { dir: ltbr.left ? 'left' : ltbr.right ? 'right' : 'left', scale: 'width' }, { dir: ltbr.top ? 'top' : ltbr.bottom ? 'bottom' : 'top', scale: 'height' } ] Object.keys(axisMap).forEach(key => { const { dir, scale } = axisMap[key] el.style[dir] = ltbr[dir] + virtualRect[scale] / 2 - rect[scale] / 2 + 'px' }) }
javascript
{ "resource": "" }
q36942
ObjectSort
train
function ObjectSort(array, columns, order) { //Check the columns if(typeof columns === 'undefined') { //Create the columns array var columns = []; //Add the keys for(var key in array[0]){ columns.push(key); } } //Check if columns is not an array else if(Array.isArray(columns) === false) { //Convert it to array columns = [columns]; } //Check the order if(typeof order === 'undefined') { //Create the order array var order = []; //Add ASC order for(var i = 0; i < columns.length; i++){ order.push('ASC'); } } //Check if order is not an array else if(Array.isArray(order) === false) { //Convert it to array order = [order]; } //Else, check for lowercase else { //Add the order to uppercase for(var i = 0; i < order.length; i++){ order[i] = order[i].toUpperCase(); } } //Check the order array length if(order.length < columns.length) { //Complete the order array for(var i = order.length; i < columns.length; i++){ order.push('ASC'); } } //Sort the array array.sort(function(left, right){ return Compare(left, right, columns, order); }); //Return the array return array; }
javascript
{ "resource": "" }
q36943
Compare
train
function Compare(left, right, columns, order) { //Compare all for(var i = 0; i < columns.length; i++) { //Check if que difference is numeric var numeric = !isNaN(+left[columns[i]] - +right[columns[i]]); //Get the values var a = (numeric === true) ? +left[columns[i]] : left[columns[i]].toLowerCase(); var b = (numeric === true) ? +right[columns[i]] : right[columns[i]].toLowerCase(); //Check the values if(a < b) { //Check the order return (order[i] === 'ASC') ? -1 : 1; } else if(a > b) { //Check the order return (order[i] === 'ASC') ? 1 : -1; } } //Default, return 0 return 0; }
javascript
{ "resource": "" }
q36944
commands
train
function commands(req, res /*, next */) { req.app.commands.forEach(function(command) { res.writeln(command); }); res.end(); }
javascript
{ "resource": "" }
q36945
install
train
function install(req, res /*, next */) { res.writeln('Add the following to your profile:'); res.writeln('eval "$(%s --completion)"', req.program); res.end(); }
javascript
{ "resource": "" }
q36946
script
train
function script(req, res, next) { switch (req.get('SHELL')) { case '/bin/sh': case '/bin/bash': res.render(__dirname + '/init.bash'); break; default: next(new Error('Unsupported shell: ' + req.get('SHELL'))); } }
javascript
{ "resource": "" }
q36947
train
function () { var middlewares = Array.prototype.slice.apply(arguments) , req = middlewares.splice(0, 1) , next = middlewares.pop() // Check other middlewares for client objects. If we find one, merge // it and ours together. for (var i = 0; i < middlewares.length; i++) { var middleware_obj = middlewares[i] if (middleware_obj.type == 'client') { utils.merge(middlewares[i], hist_obj) return undefined } } // If we get this far, no other middlewares match client type. So pass // our middleware object. next({'history': hist_obj}) return undefined }
javascript
{ "resource": "" }
q36948
train
function (selector, hash) { if (selector !== null) { this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector)); } this.actionQueue.push(this.webdriverClient.frame.bind(this.webdriverClient)); this.actionQueue.push(this._frameCb.bind(this, selector, hash)); return this; }
javascript
{ "resource": "" }
q36949
SepiaFilter
train
function SepiaFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/sepia.frag', 'utf8'), // custom uniforms { sepia: { type: '1f', value: 1 } } ); }
javascript
{ "resource": "" }
q36950
remove
train
function remove( arr, searchElement, fromIndex ){ var pos = arr.indexOf( searchElement, fromIndex ); if ( pos > -1 ){ return arr.splice( pos, 1 )[0]; } }
javascript
{ "resource": "" }
q36951
removeAll
train
function removeAll( arr, searchElement, fromIndex ){ var r, pos = arr.indexOf( searchElement, fromIndex ); if ( pos > -1 ){ r = removeAll( arr, searchElement, pos+1 ); r.unshift( arr.splice(pos,1)[0] ); return r; } else { return []; } }
javascript
{ "resource": "" }
q36952
compare
train
function compare( arr1, arr2, func ){ var cmp, left = [], right = [], leftI = [], rightI = []; arr1 = arr1.slice(0); arr2 = arr2.slice(0); arr1.sort( func ); arr2.sort( func ); while( arr1.length > 0 && arr2.length > 0 ){ cmp = func( arr1[0], arr2[0] ); if ( cmp < 0 ){ left.push( arr1.shift() ); }else if ( cmp > 0 ){ right.push( arr2.shift() ); }else{ leftI.push( arr1.shift() ); rightI.push( arr2.shift() ); } } while( arr1.length ){ left.push( arr1.shift() ); } while( arr2.length ){ right.push( arr2.shift() ); } return { left : left, intersection : { left : leftI, right : rightI }, right : right }; }
javascript
{ "resource": "" }
q36953
unique
train
function unique( arr, sort, uniqueFn ){ var rtn = []; if ( arr.length ){ if ( sort ){ // more efficient because I can presort if ( bmoor.isFunction(sort) ){ arr = arr.slice(0).sort(sort); } let last; for( let i = 0, c = arr.length; i < c; i++ ){ let d = arr[i], v = uniqueFn ? uniqueFn(d) : d; if ( v !== last ){ last = v; rtn.push( d ); } } }else if ( uniqueFn ){ let hash = {}; for( let i = 0, c = arr.length; i < c; i++ ){ let d = arr[i], v = uniqueFn(d); if ( !hash[v] ){ hash[v] = true; rtn.push( d ); } } }else{ // greedy and inefficient for( let i = 0, c = arr.length; i < c; i++ ){ let d = arr[i]; if ( rtn.indexOf(d) === -1 ){ rtn.push( d ); } } } } return rtn; }
javascript
{ "resource": "" }
q36954
intersection
train
function intersection( arr1, arr2 ){ var rtn = []; if ( arr1.length > arr2.length ){ let t = arr1; arr1 = arr2; arr2 = t; } for( let i = 0, c = arr1.length; i < c; i++ ){ let d = arr1[i]; if ( arr2.indexOf(d) !== -1 ){ rtn.push( d ); } } return rtn; }
javascript
{ "resource": "" }
q36955
open
train
function open() { // If there is no remaining URI, fires `error` and `close` event as // it means that all connection failed. if (uris.length === 0) { self.emit("error", new Error()); self.emit("close"); return; } // Removes the first element and returns it. For example, // `[1,2].shift()` returns `1` and make the array `[2]`. var uri = uris.shift(); // Because transport can handle only the specific URI, URI // determines transport. It finds which transport can handle this // `uri` among transports specified by `transports` option. for (var i = 0; i < options.transports.length; i++) { // Each transport factory checks if the given URI can be handled // and creates and returns transport object if so and returns // nothing if not. trans = options.transports[i](uri, options); // If factory creates a transport, if (trans) { // it establishes a connection. trans.open(); // If it fails, it tries with next URI or other transport. trans.on("close", open); // If it succeeds, a process to find working transport is // terminated. At the socket level, the first message is // used to handshake the protocol. `once` registers one-time // event handler. trans.once("text", function(text) { // The handshake output is in the form of URI and uses // query part to get/set header. var result = url.parse(text, true).query; // To maintain alive connection, heartbeat is used. options.heartbeat = +result.heartbeat; // `_heartbeat` is usually for testing so it may be not // passed from the server. The default value is `5000`. options._heartbeat = +result._heartbeat || 5000; // Now that the working transport is found and // handshaking is completed, removes `close` // event's `open` handler which is used to find working // transport, trans.removeListener("close", open); // initializes the transport init(trans); // and fires `open` event which is the first event user // can handle socket. self.emit("open"); }); break; } } }
javascript
{ "resource": "" }
q36956
init
train
function init(trans) { // Assign `trans` to `transport` which is associated with the // socket. transport = trans; // When the transport has received a message from the server. transport.on("text", function(text) { // Converts JSON text to an event object. // // It should have the following properties: // * `id: string`: an event identifier. // * `type: string`: an event type. // * `data: any`: an event data. // * `reply: boolean`: true if this event requires the reply. var event = JSON.parse(text); // If the server sends a plain event, dispatch it. if (!event.reply) { self.emit(event.type, event.data); } else { var latch; // A function to create a function. function reply(success) { // A controller function. return function(value) { // The latch prevents double reply. if (!latch) { latch = true; self.send("reply", {id: event.id, data: value, exception: !success}); } }; } // Here, the controller is passed to the handler as 2nd // argument and calls the server's `resolved` or `rejected` // callback by sending `reply` event. self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)}); } }); // When any error has occurred. transport.on("error", function(error) { self.emit("error", error); }); // When the transport has been closed for any reason. transport.on("close", function() { self.emit("close"); }); }
javascript
{ "resource": "" }
q36957
DBRef
train
function DBRef(namespace, oid, db) { if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); this._bsontype = 'DBRef'; this.namespace = namespace; this.oid = oid; this.db = db; }
javascript
{ "resource": "" }
q36958
train
function (configuration, events, config) { var deferred = Q.defer(); // override desired capabilities, status & browser longname this.desiredCapabilities = this._generateDesiredCaps(configuration.name, config); this.driverDefaults.status = this._generateStatusInfo(this.desiredCapabilities); this.longName = this._generateLongName(configuration.name,config); // store injected configuration/log event handlers this.reporterEvents = events; this.configuration = configuration; this.config = config; // immediatly resolve the deferred deferred.resolve(); return deferred.promise; }
javascript
{ "resource": "" }
q36959
train
function (browserName, config) { var browsers = config.get('browsers'); // check if we couldnt find a configured alias, // set to defaults otherwise if (!browsers) { return {actAs: this.desiredCapabilities.browserName, version: this.desiredCapabilities['browser-version']}; } var browser = config.get('browsers')[0][browserName] || null; // check if we couldnt find a configured alias, // check and apply if there is a default config if (!browser && this.browsers[browserName]) { browser = this.browsers[browserName]; } // check if the actas property has been set, if not // use the given browser name if (!browser.actAs) { browser.actAs = browserName; } return browser; }
javascript
{ "resource": "" }
q36960
train
function (browser) { var isValid = this.platforms.reduce(function (previousValue, platform) { if (previousValue === browser.platform || platform === browser.platform) { return browser.platform; } }); return isValid || this.desiredCapabilities.platform; }
javascript
{ "resource": "" }
q36961
train
function (browserName, config) { var browser = this._verfiyBrowserConfig(browserName, config); var platform = this._verfiyPlatformConfig(browser); var driverConfig = config.get('driver.sauce'); var desiredCaps = { browserName: browser.actAs, platform: platform, 'screen-resolution': (browser['screen-resolution'] || null), version: (browser.version || this.desiredCapabilities['browser-version']), name: driverConfig.name || this.desiredCapabilities.name }; // check if the user added tags if (driverConfig.tags) { desiredCaps.tags = driverConfig.tags; } // check if the user added a build id if (driverConfig.build) { desiredCaps.build = driverConfig.build; } return desiredCaps; }
javascript
{ "resource": "" }
q36962
train
function (browserName, config) { var longName = null; if(this.browsers.hasOwnProperty(browserName)){ longName = this.browsers[browserName].longName; } if(config.get('browsers')[0].hasOwnProperty(browserName)){ longName = config.get('browsers')[0][browserName].longName; } return longName; }
javascript
{ "resource": "" }
q36963
onMenu
train
function onMenu( item ) { var squire = this.squire; var id = item.id; switch ( id ) { case 'undo': squire.undo(); break; case 'redo': squire.redo(); break; case 'eraser': squire.removeAllFormatting(); break; case 'link': makeLink.call( squire ); break; case 'image': this.insertImage(); break; case 'format-bold': if ( squire.hasFormat( 'b' ) ) { squire.removeBold(); } else { squire.bold(); } break; case 'format-italic': if ( squire.hasFormat( 'i' ) || squire.hasFormat( 'em' ) ) { squire.removeItalic(); } else { squire.italic(); } break; case 'format-underline': if ( squire.hasFormat( 'u' ) ) { squire.removeUnderline(); } else { squire.underline(); } break; case 'format-align-left': squire.setTextAlignment( 'left' ); break; case 'format-align-center': squire.setTextAlignment( 'center' ); break; case 'format-align-right': squire.setTextAlignment( 'right' ); break; case 'format-align-justify': squire.setTextAlignment( 'justify' ); break; case 'font': setFontFaceSizeColor.call( squire ); break; case 'format-float-left': setFloat.call( squire, 'left' ); break; case 'format-float-center': setFloat.call( squire, 'center' ); break; case 'format-float-right': setFloat.call( squire, 'right' ); break; case 'format-float-none': setFloat.call( squire, 'none' ); break; case 'format-header': setHeader.call( squire ); break; default: this.processButton( id ); } this.focus = true; }
javascript
{ "resource": "" }
q36964
ruleEnd
train
function ruleEnd(e){ var selectors ; if (e.old === 'ruleStart'){ selectors = this.get('selectors'); //delete the last selector selectors.pop(); var lines = this.get('lines'); lines.pop(); this.attributes.nest.pop(); return; } else if (e.old === 'valueStart') { this._addValue(e); } ruleEnd.recode = ruleEnd.recode || 0; ruleEnd.recode++; this.attributes.nest.pop(); if (!this.attributes.nest.length){ var num = this.getLen() - ruleEnd.recode; ruleEnd.recode = 0; var idList = this.get('idList'); idList.push(num); this.fire(this.get('RULE_END_EVT'), this.getRule(num)); } }
javascript
{ "resource": "" }
q36965
addValue
train
function addValue(e){ var len; if (e.old === 'valueStart') { var history = this.get('history'); len = history.length; var preStatus = history[len - 3]; isNew = preStatus == 'ruleStart'; value = this._getLast(isNew, 'values'); value && value.push(e.data); } else { var metas = this.get('metas'); var selectors = this.get('selectors'); len = selectors.length; metas[len] = metas[len] || []; var data = ''; /*when @import url("booya.css") print, screen;*/ if (e.old === 'selectorBreak'){ data = selectors.pop().join(', ') + ', '; var lines = this.get('lines'); lines.pop(); } data += e.data; metas[len].push(data); } }
javascript
{ "resource": "" }
q36966
getLast
train
function getLast(isNew, opt_key){ opt_key = opt_key || 'selectors'; var items = this.get(opt_key); var len = items.length; if (isNew){ len++; items.push([]); var nest = this.get('nest'); var nLen = nest.length; if (nLen > 1){ //console.log([nest, nest[nLen - 2], len - 1]); //push the new rule to is father items[nest[nLen - 2]].push(items[len - 1]); } } return items[len - 1]; }
javascript
{ "resource": "" }
q36967
read
train
function read(data){ var dismember = this.get('DISMEMBER'); var i = 0, j = 0; var comment = false; var len = data.length; var code = data[0]; var line = 1; var val; var slice = data.asciiSlice ? 'asciiSlice' : 'slice'; //console.log("one\n"); while(code){ if (typeof code == 'string') code = code.charCodeAt(); if (code === 10 || code === 13){ var isoneLine = code === 10 && data[i - 1] === 13; //isoneLine = isoneLine || (code === 10 && data[i - 1] === 13); if (!isoneLine) line = line + 1; } else if (code === 42 && (data[i + 1] === 47 || data[i + 1] == '/')){ //comment end comment = false; i++; j = i + 1; } else if (code === 47 && (data[i + 1] === 42 || data[i + 1] == '*')){ //comment start comment = true; i++; } else if (!comment && code in dismember){ var status = this.get('status'); //filter the condiction of semicolon(,) in css rule such as //_filter: xxx(src=url, sizingMethod='crop') var isFalseSelecterBreak = code === 44 && status == 'valueStart'; //filter the condiction of pseudo selector(:) var isPseudo = code == 58 && status != 'ruleStart' && status != 'valueEnd'; // var isInExpression = (code === 123 || code === 125) && status === 'valueStart' && data[slice](j, i).indexOf('expression') > -1; if (isPseudo || isFalseSelecterBreak || isInExpression){ code = data[++i]; continue; } val = data[slice](j, i).replace(this.get('TRIM_REG'), ''); this._addEvent(dismember[code], val, line); j = i + 1; } code = data[++i]; } }
javascript
{ "resource": "" }
q36968
train
function(sentences, options) { var voice = options.voice, callback = options.callback, iswrite = options.writetext; for (var i=0; i<sentences.length; i++) { speechList.push(sentences[i]); }; try{ tts(voice, iswrite, callback); return true; } catch(e) { throw new Error('error while speaking'); } }
javascript
{ "resource": "" }
q36969
AssertionException
train
function AssertionException(type, message, id) { var _this = _super.call(this, message) || this; _this.type = type; _this.id = id; if (Error.captureStackTrace) { Error.captureStackTrace(_this, _this.constructor); } return _this; }
javascript
{ "resource": "" }
q36970
fail
train
function fail(message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled) { throw new AssertionException(assertionTypes.FAIL, message, id); } }
javascript
{ "resource": "" }
q36971
isTruthy
train
function isTruthy(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !value) { throw LogicException.throw(assertionTypes.IS_TRUTHY, value, message, id); } }
javascript
{ "resource": "" }
q36972
isFalsy
train
function isFalsy(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value) { throw LogicException.throw(assertionTypes.IS_FALSY, value, message, id); } }
javascript
{ "resource": "" }
q36973
isEmpty
train
function isEmpty(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && ((typeof value === 'string' && value.length === 0) || (typeof value === 'number' && value === 0))) { throw LogicException.throw(assertionTypes.IS_EMPTY, value, message, id); } }
javascript
{ "resource": "" }
q36974
isNotEmpty
train
function isNotEmpty(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && ((typeof value === 'string' && value.length !== 0) || (typeof value === 'number' && value !== 0))) { throw LogicException.throw(assertionTypes.IS_NOT_EMPTY, value, message, id); } }
javascript
{ "resource": "" }
q36975
isUndefined
train
function isUndefined(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value !== undefined) { throw TypeException.unexpectedType(assertionTypes.IS_UNDEFINED, value, '<undefined>', message, id); } }
javascript
{ "resource": "" }
q36976
isBool
train
function isBool(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value !== 'boolean') { throw TypeException.unexpectedType(assertionTypes.IS_BOOL, value, '<boolean>', message, id); } }
javascript
{ "resource": "" }
q36977
isNotBool
train
function isNotBool(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value === 'boolean') { throw TypeException.expectedType(assertionTypes.IS_NOT_BOOL, value, '<boolean>', message, id); } }
javascript
{ "resource": "" }
q36978
isNumber
train
function isNumber(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !(typeof value === 'number' || value instanceof Number)) { throw TypeException.unexpectedType(assertionTypes.IS_NUMBER, value, '<number>', message, id); } }
javascript
{ "resource": "" }
q36979
isNotNumber
train
function isNotNumber(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && (typeof value === 'number' || value instanceof Number)) { throw TypeException.expectedType(assertionTypes.IS_NOT_NUMBER, value, '<number>', message, id); } }
javascript
{ "resource": "" }
q36980
isNaN
train
function isNaN(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !Number.isNaN(value)) { throw TypeException.unexpectedType(assertionTypes.IS_NAN, value, '<NaN>', message, id); } }
javascript
{ "resource": "" }
q36981
isNotNaN
train
function isNotNaN(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && Number.isNaN(value)) { throw TypeException.expectedType(assertionTypes.IS_NOT_NAN, value, '<NaN>', message, id); } }
javascript
{ "resource": "" }
q36982
isString
train
function isString(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !(typeof value === 'string' || value instanceof String)) { throw TypeException.unexpectedType(assertionTypes.IS_STRING, value, '<string>', message, id); } }
javascript
{ "resource": "" }
q36983
isNotString
train
function isNotString(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && (typeof value === 'string' || value instanceof String)) { throw TypeException.expectedType(assertionTypes.IS_NOT_STRING, value, '<string>', message, id); } }
javascript
{ "resource": "" }
q36984
isArray
train
function isArray(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !Array.isArray(value)) { throw TypeException.unexpectedType(assertionTypes.IS_ARRAY, value, '<array>', message, id); } }
javascript
{ "resource": "" }
q36985
isNotArray
train
function isNotArray(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && Array.isArray(value)) { throw TypeException.expectedType(assertionTypes.IS_NOT_ARRAY, value, '<array>', message, id); } }
javascript
{ "resource": "" }
q36986
isFunction
train
function isFunction(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value !== 'function') { throw TypeException.expectedType(assertionTypes.IS_FUNCTION, value, '<function>', message, id); } }
javascript
{ "resource": "" }
q36987
isNotFunction
train
function isNotFunction(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value === 'function') { throw TypeException.unexpectedType(assertionTypes.IS_NOT_FUNCTION, value, '<function>', message, id); } }
javascript
{ "resource": "" }
q36988
isSymbol
train
function isSymbol(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value !== 'symbol') { throw TypeException.unexpectedType(assertionTypes.IS_SYMBOL, value, '<symbol>', message, id); } }
javascript
{ "resource": "" }
q36989
isNotSymbol
train
function isNotSymbol(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && typeof value === 'symbol') { throw TypeException.expectedType(assertionTypes.IS_NOT_SYMBOL, value, '<symbol>', message, id); } }
javascript
{ "resource": "" }
q36990
isInstanceOf
train
function isInstanceOf(value, expectedInstance, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !(value instanceof expectedInstance)) { throw ValueException.unexpectedValue(assertionTypes.INSTANCE_OF, value, expectedInstance, message, id); } }
javascript
{ "resource": "" }
q36991
isNotInstanceOf
train
function isNotInstanceOf(value, excludedInstance, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value instanceof excludedInstance) { throw ValueException.expectedValue(assertionTypes.NOT_INSTANCE_OF, value, excludedInstance, message, id); } }
javascript
{ "resource": "" }
q36992
isTrue
train
function isTrue(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value !== true) { throw ValueException.unexpectedValue(assertionTypes.IS_TRUE, value, true, message, id); } }
javascript
{ "resource": "" }
q36993
isNotTrue
train
function isNotTrue(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value === true) { throw ValueException.expectedValue(assertionTypes.IS_NOT_TRUE, value, true, message, id); } }
javascript
{ "resource": "" }
q36994
isFalse
train
function isFalse(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value !== false) { throw ValueException.unexpectedValue(assertionTypes.IS_FALSE, value, false, message, id); } }
javascript
{ "resource": "" }
q36995
isNotFalse
train
function isNotFalse(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value === false) { throw ValueException.expectedValue(assertionTypes.IS_NOT_FALSE, value, false, message, id); } }
javascript
{ "resource": "" }
q36996
isNull
train
function isNull(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value !== null) { throw ValueException.unexpectedValue(assertionTypes.IS_NULL, value, null, message, id); } }
javascript
{ "resource": "" }
q36997
isNotNull
train
function isNotNull(value, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && value === null) { throw ValueException.expectedValue(assertionTypes.IS_NOT_NULL, value, null, message, id); } }
javascript
{ "resource": "" }
q36998
match
train
function match(value, regExp, message, id) { if (message === void 0) { message = ''; } if (id === void 0) { id = ''; } if (this.enabled && !regExp.test(value)) { throw LogicException.throw(assertionTypes.MATCH, value, message, id); } }
javascript
{ "resource": "" }
q36999
loadJsonFile
train
function loadJsonFile(filename, cache, cwd) { let _content = null; if (filename.toLowerCase().endsWith('.json')) { const _filename = path.resolve(cwd, filename); if (fs.existsSync(_filename)) { if (_filename in cache) { _content = cache[_filename]; } else { //------------------------------------------------------------------------------ // La doble asignación se hace para evitar recursividades ya que si se trata de // incluir el mismo archivo al estar en caché no se analizaría. // Es un caso que no debería darse pero lo contemplamos. //------------------------------------------------------------------------------ cache[_filename] = _content = fs.readFileSync(_filename, 'utf8'); cache[_filename] = _content = parseJson(_content, cache, path.dirname(_filename)); } } else { cache[_filename] = null; } } else { try { JSON.parse(filename); _content = parseJson(filename, cache, cwd); } catch (e) { } } return _content; }
javascript
{ "resource": "" }