_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11300
train
function(data) { var corners = []; for (var i = 0; i < data.length; i += 2) { corners.push({ x: data[i], y: data[i + 1] }); } this._image.addDetailData(corners); }
javascript
{ "resource": "" }
q11301
train
function () { if (!this._image instanceof IMSoftcrop.Image || !this._image.ready) { return; } this._waitForWorkers++; var _this = this; if (window.Worker) { // If workers are available, thread it var featureWorker = new Worker(this._detectWorkerUrl); featureWorker.postMessage([ 'features', this.getImageData(), this._image.w, this._image.h, this._detectStepSize ]); featureWorker.onmessage = function(e) { for(var n = 0; n < e.data.length; n++) { _this.addDetectedFeature(e.data[n]); } _this._waitForWorkers--; _this.autocropImages(); }; } else { // // Add function to tracking.js in order to track corners directly // on image data so that we do not need to access ui. // tracking.trackData = function(tracker, imageData, width, height) { var task = new tracking.TrackerTask(tracker); task.on('run', function() { tracker.track(imageData.data, width, height); }); return task.run(); }; var tracker = new tracking.ObjectTracker(['face']); tracker.setStepSize(this._detectStepSize); tracker.on('track', function (event) { event.data.forEach(function (rect) { _this.addDetectedFeature(rect); }); _this._waitForWorkers--; _this.autocropImages(); }); tracking.trackData(tracker, this.getImageData(), this._image.w, this._image.h); } }
javascript
{ "resource": "" }
q11302
train
function(rect) { var imageRadius = 0, imagePoint = { x: rect.x, y: rect.y }; if (rect.width / this._image.w > 0.45) { // Feature point (face) takes up a large portion of the image rect.height *= 1.2; imagePoint.x += rect.width / 2; imagePoint.y += rect.height / 2; if (rect.height > rect.width) { imageRadius = rect.height / 2; } else { imageRadius = rect.width / 2; } } else { // Feature point (face) takes up less of the image rect.height *= 1.4; imagePoint.x += rect.width / 2; imagePoint.y += rect.height / 4; if (rect.height > rect.width) { imageRadius = rect.height / 2; } else { imageRadius = rect.width / 2; } } this._image.addFocusPoint(imagePoint, imageRadius); }
javascript
{ "resource": "" }
q11303
train
function (redraw) { var cx, cy; this._keepCenter = true; cx = this._container.clientWidth / 2; cy = this._container.clientHeight / 2; var ix = ((this._image.w * this._zoomLevel) / 2) + (this._image.x * this._zoomLevel) + this._margin; var iy = ((this._image.h * this._zoomLevel) / 2) + (this._image.y * this._zoomLevel) + this._margin; var x = (cx == ix) ? 0 : (cx - ix) / this._zoomLevel; var y = (cy == iy) ? 0 : (cy - iy) / this._zoomLevel; this._image.move({x: x, y: y}); if (redraw === true) { this.redraw(); } }
javascript
{ "resource": "" }
q11304
train
function (zoomLevel, redraw) { this._zoomLevel = zoomLevel / 100; if (this._keepCenter) { this.centerImage(false); } if (redraw === true) { this.redraw(); } }
javascript
{ "resource": "" }
q11305
train
function (redraw) { var imgDim = this._image.getDimensions(); var vFactor = (this._container.clientHeight - this._margin * 2) / imgDim.h; var hFactor = (this._container.clientWidth - this._margin * 2) / imgDim.w; // Set correct zoom level if (vFactor < hFactor && vFactor < 1 && this._zoomLevel > vFactor) { // Fill vertical this._zoomLevel = vFactor; this.centerImage(false); } else if (hFactor < 1 && this._zoomLevel > hFactor) { // Fill horizontal this._zoomLevel = hFactor; this.centerImage(false); } else { // No need to redraw return; } if (redraw === true) { this.redraw(); } }
javascript
{ "resource": "" }
q11306
train
function () { var _this = this; window.addEventListener( 'resize', function () { _this.onResize(event); }, false ); this._canvas.addEventListener( 'dblclick', function(event) { return _this.onDoubleClick(event); } ); this._canvas.addEventListener( 'mousedown', function (event) { _this.onMouseDown(event); } ); this._canvas.addEventListener( 'mouseup', function (event) { _this.onMouseUp(event); } ); window.addEventListener( 'mouseup', function (event) { _this.onMouseUp(event); } ); this._canvas.addEventListener( 'mousemove', function (event) { _this.onMouseMove(event); } ); this._canvas.addEventListener( 'mousewheel', function (event) { event.stopPropagation(); event.preventDefault(); _this.onMouseWheel(event); return false; }, false ); document.addEventListener( 'keydown', function (e) { var keyCode = e.keyCode || e.which; // Handle escape key if (keyCode === 13) { _this._onSave( _this.getSoftcropData() ); e.preventDefault(); e.stopPropagation(); return false; } if (keyCode === 27) { _this._onCancel(); e.preventDefault(); e.stopPropagation(); return false; } // Handle tab key if (keyCode === 9) { var crops = _this._image.getSoftCrops(); var current; for (var n = 0; n < crops.length; n++) { if (_this._crop === crops[n]) { current = n; break; } } if (typeof current != 'undefined') { n += (!e.shiftKey) ? 1 : -1; if (n < 0) { n = crops.length - 1; } else if (n + 1 > crops.length) { n = 0; } _this.setActiveCrop(crops[n]); } e.preventDefault(); e.stopPropagation(); return false; } }, false ); }
javascript
{ "resource": "" }
q11307
train
function(event) { event.preventDefault(); event.stopPropagation(); if (typeof this._image == 'undefined') { return false; } this.toggleLoadingImage(true); var point = this.getMousePoint(event); this._image.addFocusPoint( this.canvasPointInImage(point.x, point.y), 40 ); if (this._image.autocrop()) { this.redraw(); this.toggleLoadingImage(false); } return false; }
javascript
{ "resource": "" }
q11308
train
function (event) { var point = this.getMousePoint(event); if (this._crop instanceof IMSoftcrop.Softcrop && typeof this.handle === 'string') { this.updateImageInfo(true); this._dragPoint = point; this._dragObject = this.handle; } else if (this._crop instanceof IMSoftcrop.Softcrop && this._crop.inArea(point)) { this.updateImageInfo(true); this._dragObject = this._crop; this._dragPoint = point; } else if (this._image instanceof IMSoftcrop.Image && this._image.inArea(point)) { this.updateImageInfo(false); this._dragObject = this._image; this._dragPoint = point; } }
javascript
{ "resource": "" }
q11309
train
function (event) { var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail))); var zoom = 0; if (delta < 0 && this._zoomLevel < this._zoomMax) { // Zoom in zoom = this._zoomLevel < 1 ? 0.01 : 0.03; } else if (delta > 0 && this._zoomLevel > this._zoomMin) { // Zoom out zoom = this._zoomLevel < 1 ? -0.01 : -0.03; } else { return; } // Calculate middle point change for zoom change var x = ((this._image.w / 2) + this._image.x) * zoom; var y = ((this._image.h / 2) + this._image.y) * zoom; // Adjust zoom this._zoomLevel += zoom; // Then move back to old middle point this._image.move({ x: -x / this._zoomLevel, y: -y / this._zoomLevel }); this.redraw(); }
javascript
{ "resource": "" }
q11310
train
function (event) { return { x: event.pageX - this._position.x, y: event.pageY - this._position.y }; }
javascript
{ "resource": "" }
q11311
train
function() { var offset = IMSoftcrop.Ratio.getElementPosition(this._canvas); this._position.x = offset.x; this._position.y = offset.y; }
javascript
{ "resource": "" }
q11312
train
function () { this._drawCross( 'red', { x: this._container.clientWidth / 2, y: this._container.clientHeight / 2 } ); this._drawCross( 'green', { x: ((this._image.w * this._zoomLevel) / 2) + (this._image.x * this._zoomLevel) + this._margin, y: ((this._image.h * this._zoomLevel) / 2) + (this._image.y * this._zoomLevel) + this._margin } ); if (typeof this._debugContainer != 'undefined') { var str = '<pre>'; str += 'Zoom level: ' + this._zoomLevel + "\n"; if (typeof this._image != 'undefined') { str += 'Image w: ' + this._image.w + "\n"; str += ' h: ' + this._image.h + "\n"; str += "\n"; if (typeof this._image.crop != 'undefined') { str += 'Crop x: ' + this._image.crop.x + "\n"; str += ' y: ' + this._image.crop.y + "\n"; str += ' w: ' + this._image.crop.w + "\n"; str += ' h: ' + this._image.crop.h + "\n"; } } str += '</pre>'; this._debugContainer.innerHTML = str; } }
javascript
{ "resource": "" }
q11313
train
function (color, point) { var ctx = this._canvas.getContext('2d'); ctx.beginPath(); ctx.fillStyle = color; ctx.strokeStyle = color; ctx.lineWidth = 0.5; ctx.arc(point.x, point.y, 5, 0, 2 * Math.PI, false); ctx.fill(); ctx.beginPath(); ctx.moveTo(point.x - 50, point.y); ctx.lineTo(point.x + 50, point.y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(point.x, point.y - 50); ctx.lineTo(point.x, point.y + 50); ctx.stroke(); }
javascript
{ "resource": "" }
q11314
globsToRegExpStr
train
function globsToRegExpStr(str) { return str.split(STRING_TESTS.GLOBSTAR) // => [ theWholeTextIfThereIsNoGlobstar, "**", everythingAfter ] .map((v, i) => (i + 1) % 2 === 0 ? // (**) part // Replace unescaped '**' glob v.replace(STRING_TESTS.GLOBSTAR, (_match, _p1, p2) => `([^\\/]+\/+)*${p2 ? `[^\\/]*${p2}` : ''}`) : (i + 1) % 3 === 0 ? // (everythingElse) part (v ? `[^\\/]*${v}` : '') : // Else // Replace unescaped '*' glob v.replace(STRING_TESTS.STAR, '$1([^\\/]*)')) .join(''); }
javascript
{ "resource": "" }
q11315
preparePatternStringSegment
train
function preparePatternStringSegment(str) { if (STRING_TESTS.ARRAY.test(str)) { const els = str.replace(/([^\\]),/g, "$1$1,") .split(/[^\\],/); return arrayToORRegExpStr(els.map(_transformSegment)) } else { return _transformSegment(str); } }
javascript
{ "resource": "" }
q11316
train
function(setting, value) { if (-1 === this._supportedPostParams.indexOf(setting)) { this.console.error('Parameter unsupported, may cause error:', setting); } this._reqParam[setting] = value; return this; }
javascript
{ "resource": "" }
q11317
train
function(settings) { for (var k in settings) { if (settings.hasOwnProperty(k)) { this.param(k, settings[k]); } } return this; }
javascript
{ "resource": "" }
q11318
train
function(varArgs) { for (var i = 0, m = arguments.length; i < m; i++) { this.addFile(arguments[i]); } return this; }
javascript
{ "resource": "" }
q11319
train
function(config) { var data, request; data = querystring.stringify(config); request = http.request(this._closureEndpoint, this._handleResponse.bind(this)); request.on('error', function(e) { this.console.error('Request error', e); this._errCallback('http_request_error', e); }.bind(this)); request.end(data); // For ease of use, GccRest exports an instance. Node.js caches exports. // We flush the cache here to prevent GccRest from returning a polluted // instance, in case GccRest is called multiple times. try { delete require.cache[__filename]; } catch(err){} }
javascript
{ "resource": "" }
q11320
train
function(response) { var chunks = []; response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { var json = JSON.parse(chunks.join('')); this._showOutputInfo(json); this._handleOutput(json); }.bind(this)); }
javascript
{ "resource": "" }
q11321
train
function(json) { if (json.serverErrors) { this._handleNoCompiledCode(json.serverErrors); } else { json.compiledCode = this._header + json.compiledCode; if (this.file) { this._writeOutputTofile(json.compiledCode); } if (this.callback) { this.callback((this._passJson) ? json : json.compiledCode); } if (!this.file && !this.callback) { this.console.info('Code:', json.compiledCode); } } }
javascript
{ "resource": "" }
q11322
train
function(response) { this.console.error('Server responded with error:'); this.console.error('Status', response.statusCode); this.console.error('Headers', response.headers); response.on('data', function(chunk) { this.console.info('Body', chunk); }.bind(this)); this._errCallback('server_error', response); }
javascript
{ "resource": "" }
q11323
train
function(err) { var file = fs.realpathSync(this.file); if (!err) { this.console.info('Compiled code saved to', file); } else { this.console.info('Saving code failed to', file); } }
javascript
{ "resource": "" }
q11324
MinHeap
train
function MinHeap(compareFn) { this._elements = [null]; this._comparator = new Comparator(compareFn); Object.defineProperty(this, 'n', { get: function () { return this._elements.length - 1; }.bind(this) }); }
javascript
{ "resource": "" }
q11325
parseUseragent
train
function parseUseragent(ua) { if (!ua) { return null; } let platform, webview = false, version, engine, result, major, minor, patch, float, index, name, temp, os; ua = ua.toLowerCase(); if (~ua.indexOf('mobile')) { platform = 'mobile'; } else if (~ua.indexOf('tablet')) { platform = 'tablet'; } else { platform = 'desktop'; } if (~(index = ua.indexOf('msie'))) { name = 'internet explorer'; platform = 'desktop'; } else if (~(index = ua.indexOf('trident/'))) { name = 'internet explorer'; platform = 'desktop'; index += 13; } else if (~(index = ua.indexOf('edge/'))) { name = 'edge'; engine = 'edgehtml'; } else if (~(index = ua.indexOf('chrome/'))) { name = 'chrome'; } else if (~(index = ua.indexOf('firefox/'))) { name = 'firefox'; engine = 'gecko'; } else if (~(index = ua.indexOf('safari/'))) { name = 'safari'; index = ua.indexOf('version/'); engine = 'webkit'; } if (~index) { version = version_rx.exec(ua.slice(index)); if (version) { float = parseFloat(version[0]); major = +version[1]; minor = +version[2]; patch = version[3] || ''; } } if (!engine) { switch (name) { case 'internet explorer': engine = 'trident'; break; case 'chrome': if (major < 28) { engine = 'webkit'; } else { engine = 'blink'; } break; } } if (platform != 'desktop') { if (~ua.indexOf('iphone') || ~ua.indexOf('ipad') || ~ua.indexOf('ipod')) { os = 'ios'; if (ua.indexOf('safari') == -1) { webview = true; } } else if (~ua.indexOf('; wv')) { webview = true; } } result = { family : name, version : { major : major, minor : minor, patch : patch, float : float }, platform : platform, engine : engine, webview : webview, os : os }; return result; }
javascript
{ "resource": "" }
q11326
clearAndDoTasks
train
function clearAndDoTasks(arr) { var tasks = arr.slice(0), i; // Clear the original array arr.length = 0; for (i = 0; i < tasks.length; i++) { tasks[i](); } }
javascript
{ "resource": "" }
q11327
checkNextRequire
train
function checkNextRequire(options) { if (!modulep) { return; } if (options.strict === false) { return; } // Overwrite the original wrap method modulep.wrap = function wrap(script) { var head; // Restore the original functions modulep.wrap = modulep.original_wrap; modulep._resolveFilename = modulep.original_resolve; if (options.add_wrapper !== false) { if (options.add_wrapper || script.slice(0, 14) != 'module.exports') { if (script.indexOf('__cov_') > -1 && script.indexOf('module.exports=function ') > 7) { // We're in coverage mode, just ignore } else { // Yes: "added_wrapper", as in "done" options.added_wrapper = true; head = 'module.exports = function('; if (options.arguments) { head += Blast.getArgumentConfiguration(options.arguments).names.join(','); } else { head += 'Blast, Collection, Bound, Obj'; } head += ') {'; script = head + script + '\n};'; } } } // Add the strict wrapper for this requirement return modulep.strict_wrapper + script + modulep.wrapper[1]; }; // Overwrite the original _resolveFilename method modulep._resolveFilename = function _resolveFilename(request, parent, is_main) { try { return modulep.original_resolve(request, parent, is_main); } catch (err) { modulep.wrap = modulep.original_wrap; modulep._resolveFilename = modulep.original_resolve; throw err; } }; }
javascript
{ "resource": "" }
q11328
Queue
train
function Queue (name, redisClient) { this.hasQuit = false this._name = name this.redisClient = redisClient this._key = Queue.PREFIX + this.name }
javascript
{ "resource": "" }
q11329
removeOne
train
function removeOne(array, item) { var found = array.indexOf(item); if (found > -1) { array.splice(found, 1); } }
javascript
{ "resource": "" }
q11330
copy
train
function copy(array, first, count) { first = valueOrDefault(first, 0); count = valueOrDefault(count, array.length); return Array.prototype.slice.call(array, first, count); }
javascript
{ "resource": "" }
q11331
find
train
function find(array, f, context) { var i, // iterative variable l; // array length variable for (i = 0, l = array.length; i < l; i += 1) { if (array.hasOwnProperty(i) && f.call(context, array[i], i, array)) { return array[i]; } } return null; }
javascript
{ "resource": "" }
q11332
batch
train
function batch(options) { var validationError = validateOptions(options); var settings = _.extend({ time: 0, count: 0 }, options); var cache = []; var lastWrite = 0; var timeout; /** * @private * @description * Writes all the collected data to the stream. * * @param {Stream} stream - The stream to write to. * @returns {undefined} */ function flushCache(stream) { lastWrite = Date.now(); if (timeout) { clearTimeout(timeout); timeout = null; } stream.push(cache.splice(0, settings.count || cache.length)); } /** * @private * @description * Flushes the cache using the defined timeout. * * @param {Stream} stream - The stream to write to. * @param {Function} onFlush - The function to call when * the cache is flushed. * @returns {undefined} */ function flushCacheTimed(stream, onFlush) { var nextWrite = lastWrite + settings.time; var now = Date.now(); // we are overdue for a write, so write now if (now >= nextWrite) { flushCache(stream); onFlush(); return; } // write after the remainder between now and when // the next write should be according to milliseconds // and the previous write timeout = setTimeout(function () { flushCache(stream); onFlush(); }, nextWrite - now); } /** * @private * @description * Flushes the cache if it is appropriate to do so. * * @param {Stream} stream - The stream to write to. * @returns {undefined} */ function writeIfPossible(stream) { if ( // we don't have a count or a time set, (!settings.count && !settings.time) || // the count has been met (settings.count && cache.length === settings.count) ) { flushCache(stream); return; } if (settings.time && !timeout) { flushCacheTimed(stream, _.noop); } } return through.obj(function Transform(data, enc, cb) { var self = this; if (validationError) { cb(validationError); return; } // initialize now if it is not yet initialized, so that we // start time batching from now on if (!lastWrite) { lastWrite = Date.now(); } cache.push(data); writeIfPossible(self); cb(); }, function Flush(cb) { var self = this; if (timeout) { clearTimeout(timeout); } if (cache.length === 0) { return cb(); } return flushCacheTimed(self, cb); }); }
javascript
{ "resource": "" }
q11333
ConditionalExpression
train
function ConditionalExpression(node, print) { print.plain(node.test); this.space(); this.push("?"); this.space(); print.plain(node.consequent); this.space(); this.push(":"); this.space(); print.plain(node.alternate); }
javascript
{ "resource": "" }
q11334
AssignmentPattern
train
function AssignmentPattern(node, print) { print.plain(node.left); this.push(" = "); print.plain(node.right); }
javascript
{ "resource": "" }
q11335
AssignmentExpression
train
function AssignmentExpression(node, print, parent) { // Somewhere inside a for statement `init` node but doesn't usually // needs a paren except for `in` expressions: `for (a in b ? a : b;;)` var parens = this._inForStatementInit && node.operator === "in" && !_node2["default"].needsParens(node, parent); if (parens) { this.push("("); } // todo: add cases where the spaces can be dropped when in compact mode print.plain(node.left); var spaces = node.operator === "in" || node.operator === "instanceof"; spaces = true; // todo: https://github.com/babel/babel/issues/1835 this.space(spaces); this.push(node.operator); if (!spaces) { // space is mandatory to avoid outputting <!-- // http://javascript.spec.whatwg.org/#comment-syntax spaces = node.operator === "<" && t.isUnaryExpression(node.right, { prefix: true, operator: "!" }) && t.isUnaryExpression(node.right.argument, { prefix: true, operator: "--" }); } this.space(spaces); print.plain(node.right); if (parens) { this.push(")"); } }
javascript
{ "resource": "" }
q11336
BindExpression
train
function BindExpression(node, print) { print.plain(node.object); this.push("::"); print.plain(node.callee); }
javascript
{ "resource": "" }
q11337
LinkedList
train
function LinkedList() { this._length = 0; this.head = null; this.tail = null; // Read-only length property Object.defineProperty(this, 'length', { get: function () { return this._length; }.bind(this) }); }
javascript
{ "resource": "" }
q11338
train
function(object, __type, parameters, args) { if (parameters) { object.id = parameters.id || (parameters.id = (processor.id_generator++).toString(16)); // set per session uid object.name = parameters.name; // default prime binds if ('' in args) { var prime = args['']; if (prime instanceof DataArray || prime instanceof DataObject) this.bind(prime); } object.parameters = parameters; } else { object.parameters = {id:(object.id = (parameters.id = (processor.id_generator++).toString(16)))}; // set per session uid } if (!__type) throw new TypeError('Invalid node type!'); object.__type = (__type.indexOf('.') < 0) ? ('default.' + __type) : __type; object.arguments = args || {}; object.state = Number.MIN_VALUE; // State id object.childs = []; // Child nodes collection object.onparent_reflected = 0; // On parent reflected state object.in = []; object.in_reflected = []; object.out = []; object.out_reflected = []; return object; }
javascript
{ "resource": "" }
q11339
train
function(type, factory) { var key_parameters = {}, __type = parse_type(type, key_parameters) .toLowerCase(); // normalize prop name, remove lead '/' for(var prop in key_parameters) if (prop[0] === '/') { key_parameters[prop.slice(1)] = key_parameters[prop]; delete key_parameters[prop]; } if (__type.length < type.length || Object.keys(key_parameters).length) { // type is subtype with parameters, register to processor.subtypes key_parameters.__ctr = factory; var subtypes_array = this.subtypes[__type] || (this.subtypes[__type] = []); subtypes_array.push(key_parameters); } else { // register as standalone type // check name conflict if (this[__type]) throw new TypeError('Type ' + type + ' already registered!'); this[__type] = factory; } }
javascript
{ "resource": "" }
q11340
train
function(alias, type) { var parameters = {}, __type = parse_type(type, parameters) .toLowerCase(), constructor = resolve_ctr(__type, parameters); if (!constructor) throw new TypeError('Type ' + __type + ' not registered!'); this[alias.toLowerCase()] = { __type: __type, parameters: parameters, isAlias: true }; }
javascript
{ "resource": "" }
q11341
train
function(type, parameters, args) { parameters = parameters || {}; args = args || {}; var __type = parse_type(type, parameters, args), constructor = resolve_ctr(__type, parameters); if (!constructor) throw new TypeError('Type ' + __type + ' not registered!'); for(var prop in parameters) if (parameters.hasOwnProperty(prop) && prop[0] === '$') args[prop.substr(1)] = parameters[prop]; // create object var new_control = (constructor.is_constructor) // constructor or factory method ? ? new constructor(parameters, args) : constructor(parameters, args); // reflect after creation if control only if (typeof new_control === 'object' && '__type' in new_control) new_control.raise('type'); return new_control; }
javascript
{ "resource": "" }
q11342
train
function(com) { var root_nodes = this.root_nodes; if (typeof com === 'string') { if (com in processor) { var object = processor[com]; if (typeof object === 'object' && '__type' in object) { delete processor[name]; var index = root_nodes.indexOf(object); if (index >= 0) root_nodes.splice(index, 1); } } } else { var index = root_nodes.indexOf(com), name = com.name; if (index >= 0) root_nodes.splice(index, 1); if (processor[name] === com) delete processor[name]; } return this; }
javascript
{ "resource": "" }
q11343
train
function(name, value) { var parameters = this.parameters; if (arguments.length < 1) return parameters[name] || parameters['/' + name]; if (value !== parameters[name]) { parameters[name] = value; } }
javascript
{ "resource": "" }
q11344
train
function(index, type, /*optional*/ $prime, /*optional*/ args, /*optional*/ callback, /*optional*/ this_arg) { if (!type) return; // normalize arguments if (typeof $prime === 'function') { this_arg = args; callback = $prime; $prime = undefined; args = undefined; } else { if (typeof $prime === 'object' && !Array.isArray($prime)) { this_arg = callback; callback = args; args = $prime; $prime = undefined; } if (typeof args === 'function') { this_arg = callback; callback = args; args = undefined; } } if (Array.isArray(type)) { // collection detected var result; for(var i = index, c = index + type.length; i < c; i++) result = this.insert(i, type[i], $prime, args, callback, this_arg); return result; } if (typeof type === 'object') { // it is a control? var add_task = type; if (add_task.hasOwnProperty('__type')) setParent.call(type, this, index); return add_task; } if (Array.isArray(args)) args = {'': args}; else if (!args) args = {}; var parameters = {}; // transfer inheritable parameters to the created object var this_parameters = this.parameters; for(var prop in this_parameters) if (this_parameters.hasOwnProperty(prop) && prop[0] === '/') parameters[prop] = this_parameters[prop]; // resolve constructor var __type = parse_type(type, parameters, args), constructor = resolve_ctr(__type, parameters); if ($prime !== undefined) args[''] = $prime; // load required components if (!constructor) { var parts = __type.split('.'), mod_path = './modules/' + parts[0] + '/' + parts[1]; console.log(__type + ' not loaded, try to load ' + mod_path); require(mod_path); constructor = resolve_ctr(__type, parameters); } if (!constructor) throw new TypeError('Type ' + __type + ' not registered!'); // move $parameters to attributes (unsafe) for(var prop in parameters) if (parameters.hasOwnProperty(prop) && prop[0] === '$') args[prop.substr(1)] = parameters[prop]; // create control var new_control = new constructor(parameters, args); // reflect after creation new_control.raise('type'); // set parent property setParent.call(new_control, this, index); // callback if (callback) callback.call(this_arg || this, new_control); return new_control; }
javascript
{ "resource": "" }
q11345
getIncludeFiles
train
function getIncludeFiles(glob) { var folders = settings.folders; var options = { read: false, cwd: path.resolve(folders.dest + '/' + folders.vendor) }; return gulp.src(glob, options); }
javascript
{ "resource": "" }
q11346
ObjectExpression
train
function ObjectExpression(node, parent) { if (t.isExpressionStatement(parent)) { // ({ foo: "bar" }); return true; } if (t.isMemberExpression(parent) && parent.object === node) { // ({ foo: "bar" }).foo return true; } return false; }
javascript
{ "resource": "" }
q11347
determineTabs
train
function determineTabs(line, tab){ let tabs = ''; for (let i = 0; i < line.depth; i++) { tabs += tab; } return tabs; }
javascript
{ "resource": "" }
q11348
train
function (fn) { var origError = console.error var origExit = process.exit var origLog = console.log console.error = error = jest.fn() console.log = print = jest.fn() process.exit = exit = jest.fn() return execPromise(fn).then( function (value) { console.error = origError console.log = origLog process.exit = origExit return value }, function (reason) { console.error = origError console.log = origLog process.exit = origExit throw reason } ) }
javascript
{ "resource": "" }
q11349
History
train
function History() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; classCallCheck(this, History); this.configuration = Object.assign({}, baseConfig, config); this.supported = checkSupport(window); var _configuration = this.configuration, hashbanged = _configuration.hashbanged, hashbangPrefix = _configuration.hashbangPrefix, location = _configuration.location; //Check if a location object in the configuration. if (location) { //If yes, build the location from that config depending on its type, //but do not redirect. this.location = (typeof location === 'undefined' ? 'undefined' : _typeof(location)) === 'object' ? location : { path: location, url: '' + (hashbanged ? hashbangPrefix : '') + location, pattern: location, params: {}, sender: '' }; } else { //If not, build the first location from the URL. this.setLocationFromHref(); } //Add an event listener to reset the location on hashbanged if (hashbanged) { window.addEventListener('hashchange', this.setLocationFromHref.bind(this)); } }
javascript
{ "resource": "" }
q11350
start
train
function start(callback) { var dbDeferred = Q.defer(); config = defaultConfig; if (typeof gmeConfig.rest.components[CONFIG_ID] === 'object' && gmeConfig.rest.components[CONFIG_ID].options) { config = gmeConfig.rest.components[CONFIG_ID].options; } mongodb.MongoClient.connect(config.mongo.uri, config.mongo.options, function (err, db) { if (err) { dbDeferred.reject(err); } else { dbConn = db; dbDeferred.resolve(); } }); return dbDeferred.promise.nodeify(callback); }
javascript
{ "resource": "" }
q11351
GLTFTextureDDSExtension
train
function GLTFTextureDDSExtension() { if ( ! THREE.DDSLoader ) { throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' ); } this.name = EXTENSIONS.MSFT_TEXTURE_DDS; this.ddsLoader = new THREE.DDSLoader(); }
javascript
{ "resource": "" }
q11352
send
train
function send(payload, promise) { if (typeof apostle.domainKey == 'undefined'){ promise.reject('invalid', [{error: 'No domain key defined. Please set a domain key with `apostle.domainKey = "abc123"`'}]) return; } (request || superagent) .post(apostle.deliveryEndpoint) .type('json') .send(payload) .set('Authorization', 'Bearer ' + apostle.domainKey) .set('Apostle-Client', 'JavaScript/v0.1.1') .end(function(err, res){ if(res.ok){ promise.fulfill() }else{ promise.reject('error', res) } }) }
javascript
{ "resource": "" }
q11353
train
function(template, options) { queue = apostle.createQueue(); queue.push(template, options); return queue.deliver(); }
javascript
{ "resource": "" }
q11354
train
function(template, options){ var payload = { data: {}, template_id: template }; // Add root attributes to the payload root for(var attr in rootAttributes){ if(!rootAttributes.hasOwnProperty(attr)){ continue; } if(typeof options[attr] === 'undefined'){ continue; } var key = rootAttributes[attr], val = options[attr]; payload[key] = val; delete options[attr]; } // Add any left over attribtues to the data object for(attr in options){ if(!options.hasOwnProperty(attr)){ continue; } payload.data[attr] = options[attr] } // Add to the list of emails this.mails.push(payload); }
javascript
{ "resource": "" }
q11355
train
function(){ var payload = { recipients: {} }, invalid = [], promise = new Promise(); for(var i=0, j=this.mails.length; i < j; i++){ var data = this.mails[i], email = data.email; if(!data.template_id){ invalid.push(data) data.error = "No template provided" continue; } if(typeof data.email === 'undefined'){ invalid.push(data) data.error = "No email provided" continue; } delete data['email']; payload.recipients[email] = data } if(invalid.length > 0){ promise.reject('invalid', invalid); }else{ apostle.send(payload, promise); } return promise; }
javascript
{ "resource": "" }
q11356
DeclareModule
train
function DeclareModule(node, print) { this.push("declare module "); print.plain(node.id); this.space(); print.plain(node.body); }
javascript
{ "resource": "" }
q11357
_interfaceish
train
function _interfaceish(node, print) { print.plain(node.id); print.plain(node.typeParameters); if (node["extends"].length) { this.push(" extends "); print.join(node["extends"], { separator: ", " }); } if (node.mixins && node.mixins.length) { this.push(" mixins "); print.join(node.mixins, { separator: ", " }); } this.space(); print.plain(node.body); }
javascript
{ "resource": "" }
q11358
TupleTypeAnnotation
train
function TupleTypeAnnotation(node, print) { this.push("["); print.join(node.types, { separator: ", " }); this.push("]"); }
javascript
{ "resource": "" }
q11359
TypeAlias
train
function TypeAlias(node, print) { this.push("type "); print.plain(node.id); print.plain(node.typeParameters); this.space(); this.push("="); this.space(); print.plain(node.right); this.semicolon(); }
javascript
{ "resource": "" }
q11360
ObjectTypeIndexer
train
function ObjectTypeIndexer(node, print) { if (node["static"]) this.push("static "); this.push("["); print.plain(node.id); this.push(":"); this.space(); print.plain(node.key); this.push("]"); this.push(":"); this.space(); print.plain(node.value); }
javascript
{ "resource": "" }
q11361
ObjectTypeProperty
train
function ObjectTypeProperty(node, print) { if (node["static"]) this.push("static "); print.plain(node.key); if (node.optional) this.push("?"); if (!t.isFunctionTypeAnnotation(node.value)) { this.push(":"); this.space(); } print.plain(node.value); }
javascript
{ "resource": "" }
q11362
responseErrorBuilder
train
function responseErrorBuilder(err, res) { if (res && res.body && _.isObject(res.body) && res.body.error) { // pass through error obj from API return res.body; } else { // build custom error return { error: { code: err.status || CL_CONSTANTS.RES_UNKNOWN, message: (res ? res.text : null) || err.toString(), } }; } }
javascript
{ "resource": "" }
q11363
signedRequestHeaders
train
function signedRequestHeaders(apiKey, apiSecretKey, apiUserToken, options) { if (!apiKey || !apiSecretKey || !apiUserToken) { return false; } var apiExpDate = Math.floor(Date.now() / 1000) + 600; var payload = apiKey + apiUserToken + apiExpDate; var hash = CryptoJS.HmacSHA256(payload, apiSecretKey); var headers = { 'x-api-key': apiKey, 'x-api-user-token': apiUserToken, 'x-api-signature': 'Method=HMAC-SHA256 Signature=' + hash, 'x-api-exp-date': apiExpDate, }; return headers; }
javascript
{ "resource": "" }
q11364
train
function(config){ // Do parse this.process = function(vinyl){ var data = vinyl.contents.toString('utf8'); // Parse var sections = parse(vinyl.path, data, config); // Format format(vinyl.path, sections, config); // Compute new title var first = marked.lexer(sections[0].docsText)[0]; var hasTitle = first && first.type === 'heading' && first.depth === 1; var title = hasTitle ? first.text : path.basename(vinyl.path); // Change extension vinyl.path = vinyl.path.replace(/([.][^.]+)?$/, '.html'); // Generate html from template var relativeIt = path.relative(path.dirname(vinyl.relative), '.') var relativeCss = path.join(relativeIt, path.basename(config.css)); var html = config.template({ sources: []/*config.sources*/, css: relativeCss, title: title, hasTitle: hasTitle, sections: sections, path: path/*, destination: vinyl.relative//.path*/ }); // Replace normalize bogus links: public/stylesheets/normalize.css html = html.replace(/(public\/stylesheets\/normalize\.css)/, path.join(relativeIt, "$1")); // Spoof it back in vinyl.contents = new Buffer(html); }; }
javascript
{ "resource": "" }
q11365
ContractRunner
train
function ContractRunner(config, data) { events.EventEmitter.call(this); var self = this; self.config = config; if (typeof data !== 'object' || typeof data.manifest !== 'object') { throw new Error('ApiHandler must be instantiated with the manifest'); } self._manifest = data.manifest; self._apis = {}; self._manifest_hash = data.manifest_hash; self._instance_id = data.instance_id; self._additional_libs = data.additional_libs || ''; self._env = data.env; self._nextFreeFileDescriptor = 4; // Add the manifest_hash to the manifest object so it will // be passed to the API modules when they are called self._manifest.manifest_hash = data.manifest_hash; // Setup sandbox instance self._sandbox = new Sandbox({ enableGdb: self.config.enableGdb, enableValgrind: self.config.enableValgrind, disableNacl: self.config.disableNacl }); self._sandbox.on('exit', self.handleExit.bind(self)); }
javascript
{ "resource": "" }
q11366
train
function (needsStitching) { var initData = { viewPort: {}, document: {}, bodyTransform: {} }, de = document.documentElement, el = document.createElement('div'), body = document.body; // Get current scroll-position initData.viewPort.x = window.pageXOffset || body.scrollLeft || de.scrollLeft; initData.viewPort.y = window.pageYOffset || body.scrollTop || de.scrollTop; // Get current view-port size el.style.position = "fixed"; el.style.top = 0; el.style.left = 0; el.style.bottom = 0; el.style.right = 0; de.insertBefore(el, de.firstChild); initData.viewPort.width = el.offsetWidth; initData.viewPort.height = el.offsetHeight; de.removeChild(el); //initData.viewPort.width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); //initData.viewPort.height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Get document size & state of scrollbar styles initData.document.width = Math.max(body.scrollWidth, body.offsetWidth, de.clientWidth, de.scrollWidth, de.offsetWidth); initData.document.height = Math.max(body.scrollHeight, body.offsetHeight, de.clientHeight, de.scrollHeight, de.offsetHeight); initData.document.cssHeight = body.style.height; initData.document.overflow = body.style.overflow; // See which transformation property to use and what value it has // Needed for scroll-translation without the page actually knowing about it if (body.style.webkitTransform !== undefined) { initData.bodyTransform.property = 'webkitTransform'; } else if (body.style.mozTransform !== undefined) { initData.bodyTransform.property = 'mozTransform'; } else if (body.style.msTransform !== undefined) { initData.bodyTransform.property = 'msTransform'; } else if (body.style.oTransform !== undefined) { initData.bodyTransform.property = 'oTransform'; } else { initData.bodyTransform.property = 'transform'; } initData.bodyTransform.value = body.style[initData.bodyTransform.property]; initData.needsStitching = needsStitching; // Change document // Reset scrolling through translate if (needsStitching) { body.style[initData.bodyTransform.property] = 'translate(' + initData.viewPort.x + 'px, ' + initData.viewPort.y + 'px)'; } return JSON.stringify(initData); }
javascript
{ "resource": "" }
q11367
train
function (initData) { var body = document.body; // Reset document height (if changed at all) body.style.height = initData.document.cssHeight; // Reset document offset if (initData.needsStitching) { body.style[initData.bodyTransform.property] = initData.bodyTransform.value; } }
javascript
{ "resource": "" }
q11368
compile
train
function compile(filename) { var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var result; opts.filename = filename; var optsManager = new _transformationFileOptionsOptionManager2["default"](); optsManager.mergeOptions(transformOpts); opts = optsManager.init(opts); var cacheKey = JSON.stringify(opts) + ":" + babel.version; var env = process.env.BABEL_ENV || process.env.NODE_ENV; if (env) cacheKey += ":" + env; if (cache) { var cached = cache[cacheKey]; if (cached && cached.mtime === mtime(filename)) { result = cached; } } if (!result) { result = babel.transformFileSync(filename, _lodashObjectExtend2["default"](opts, { sourceMap: "both", ast: false })); } if (cache) { result.mtime = mtime(filename); cache[cacheKey] = result; } maps[filename] = result.map; return result.code; }
javascript
{ "resource": "" }
q11369
shouldIgnore
train
function shouldIgnore(filename) { if (!ignore && !only) { return getRelativePath(filename).split(_path2["default"].sep).indexOf("node_modules") >= 0; } else { return util.shouldIgnore(filename, ignore || [], only); } }
javascript
{ "resource": "" }
q11370
istanbulLoader
train
function istanbulLoader(m, filename, old) { istanbulMonkey[filename] = true; old(m, filename); }
javascript
{ "resource": "" }
q11371
registerExtension
train
function registerExtension(ext) { var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"]; var loader = normalLoader; if (process.env.running_under_istanbul) loader = istanbulLoader; require.extensions[ext] = function (m, filename) { if (shouldIgnore(filename)) { old(m, filename); } else { loader(m, filename, old); } }; }
javascript
{ "resource": "" }
q11372
hookExtensions
train
function hookExtensions(_exts) { _lodashCollectionEach2["default"](oldHandlers, function (old, ext) { if (old === undefined) { delete require.extensions[ext]; } else { require.extensions[ext] = old; } }); oldHandlers = {}; _lodashCollectionEach2["default"](_exts, function (ext) { oldHandlers[ext] = require.extensions[ext]; registerExtension(ext); }); }
javascript
{ "resource": "" }
q11373
monthConfigs
train
function monthConfigs () { return [ [{ interval: Plottable.TimeInterval.month, step: 1, // full month name formatter: Plottable.Formatters.time('%B') }, { interval: Plottable.TimeInterval.year, step: 1, formatter: Plottable.Formatters.time('%Y') }], [{ interval: Plottable.TimeInterval.month, step: 1, // short month name formatter: Plottable.Formatters.time('%b') }, { interval: Plottable.TimeInterval.year, step: 1, formatter: Plottable.Formatters.time('%Y') }], [{ interval: Plottable.TimeInterval.month, step: 1, // month in numbers formatter: Plottable.Formatters.time('%m') }, { interval: Plottable.TimeInterval.year, step: 1, formatter: Plottable.Formatters.time('%Y') }], [{ interval: Plottable.TimeInterval.month, step: 1, // month in numbers formatter: Plottable.Formatters.time('%-m') }, { interval: Plottable.TimeInterval.year, step: 1, formatter: Plottable.Formatters.time('%Y') }] ] }
javascript
{ "resource": "" }
q11374
parseHeader
train
function parseHeader(value, name){ // Throw error if value is not array or string if(value && (!utils.isArray(value) && !utils.isString(value))){ throw new Error(`Default Header for "${name}" must be Array or String`); } // In case when no error was threw, check if value is array // Set all values to UpperCase and join the values into a string else if(utils.isArray(value)){ // Capitalize each string in the array value.forEach((element, index) => { var stringParts = element.split("-"); var arr = []; stringParts.forEach((e, i) => { arr.push(firstUpperCase(e)); }); value[index] = arr.join("-"); }); value = value.join(", "); } return value; }
javascript
{ "resource": "" }
q11375
ElementsEventHandler
train
function ElementsEventHandler(socket) { var _this = this; //Call EventEmmiter _contructor_ events.EventEmitter.call(this); this.socket = socket; // On every message event received by socket we get // an message event object like {event:, data:} // we emit a local event through an EventEmitter interface // with .event as event type and .data as // event data; this.socket.on('message', function(message, callback) { debug("Forwarding frontend message '%s', with data %j", message.event, message.data); if (message.event !== undefined) { _this.emit(message.event, message.data); if (typeof callback === 'function') { callback(); } } if (message.event === "userinput" && message.scope !== undefined) { debug("userinput received: %s", JSON.stringify(message)); _this.emit(message.scope, message.data); } }); this.socket.on("disconnect", function() { delete(this.socket); _this.emit("disconnect"); }); }
javascript
{ "resource": "" }
q11376
train
function (m, u) { return [ m[0][0] * u[0] + m[0][1] * u[1] + m[0][2] * u[2], m[1][0] * u[0] + m[1][1] * u[1] + m[1][2] * u[2], m[2][0] * u[0] + m[2][1] * u[1] + m[2][2] * u[2] ]; }
javascript
{ "resource": "" }
q11377
train
function (px, py, radius) { var cx = 0; var cy = 0; var dx = cx - px; var dy = cy - py; var dd = Math.sqrt(dx * dx + dy * dy); var a = Math.asin(radius / dd); var b = Math.atan2(dy, dx); var t1 = b - a; var t2 = b + a; return { p1: [radius * Math.sin(t1), radius * -Math.cos(t1)], p2: [radius * -Math.sin(t2), radius * Math.cos(t2)], center: [-radius * Math.cos(b), radius * -Math.sin(b)], arclength: 2 * a }; }
javascript
{ "resource": "" }
q11378
getChatboxElement
train
function getChatboxElement() { var content = h('div', { }); var keyPressHandler = (e) => { if (e.charCode === 13) { var messageText = e.srcElement.value; if (messageText.length > 0) { e.srcElement.value = ""; sendMessage(messageText); } } } var sendMessageBox = h('input', { onkeypress: keyPressHandler, className: 'ssb-embedded-chat-input-box', disabled: !chatboxEnabled }); var scroller = h('div', { style: { 'overflow-y': 'auto', 'overflow-x': 'hidden' }, className: 'ssb-embedded-chat-messages' }, content); pull( messagesSource(), aborter, pull.asyncMap(getNameAndChatMessage), Scroller(scroller, content, (details) => renderChatMessage(details.message, details.displayName, details.isOld), false, true) ); var chatBox = h('div', { className: 'ssb-embedded-chat', }, scroller, sendMessageBox) return chatBox; }
javascript
{ "resource": "" }
q11379
setupDebug
train
function setupDebug (driver, options) { var indentation = 0; function stringFill (filler, length) { var buffer = new Buffer(length); buffer.fill(filler); return buffer.toString(); } function getIndentation (add) { return stringFill(' ', (indentation + add) * 2); } if (options.debug) { if (options.httpDebug) { driver.on('request', function (req) { console.log(getIndentation(1) + "Request: ", JSON.stringify(req).substr(0, 5000)); }); driver.on('response', function (res) { console.log(getIndentation(1) + "Response: ", JSON.stringify(res).substr(0, 5000)); }); } driver.on('method-call', function (event) { var msg = event.target; indentation = event.indentation; if (event.selector) { msg += '(' + util.inspect(event.selector, {colors: true}) + ')'; } msg += '.' + event.name; msg += '(' + event.args.map(function (a) { return util.inspect(a, {colors: true}); }).join(', ') + ')'; if (event.result && typeof event.result !== 'object') { msg += ' => ' + util.inspect(event.result, {colors: true}); } console.log(getIndentation(0) + '[' + (event.state + stringFill(' ', 5)).substr(0, 5) + '] ' + msg); if (event.state.toLowerCase() !== 'start') { console.log(getIndentation(0) + stringFill('-', 50)); } }); } }
javascript
{ "resource": "" }
q11380
AdaptationEngine
train
function AdaptationEngine(node) { this.node = node; this.modelObjMapper = new ModelObjectMapper(); const factory = new kevoree.factory.DefaultKevoreeFactory(); this.compare = factory.createModelCompare(); this.alreadyProcessedTraces = {}; this.targetModel = null; }
javascript
{ "resource": "" }
q11381
SecretGenerator
train
function SecretGenerator(manifest, instance_id, secrets) { ApiModule.call(this); var self = this; self._manifest = manifest; self._secrets = secrets; self._instance_id = instance_id; }
javascript
{ "resource": "" }
q11382
_get_annotations_by_filter
train
function _get_annotations_by_filter(filter){ var anchor = this; var ret = []; each(anchor._annotations, function(ann){ var res = filter(ann); if( res && res === true ){ ret.push(ann); } }); return ret; }
javascript
{ "resource": "" }
q11383
_get_annotations_by_key
train
function _get_annotations_by_key(key){ var anchor = this; var ret = []; each(anchor._annotations, function(ann){ if( ann.key() === key ){ ret.push(ann); } }); return ret; }
javascript
{ "resource": "" }
q11384
_get_annotation_by_id
train
function _get_annotation_by_id(aid){ var anchor = this; var ret = null; each(anchor._annotations, function(ann){ if( ann.id() === aid ){ ret = ann; } }); return ret; }
javascript
{ "resource": "" }
q11385
_get_referenced_subgraphs_by_filter
train
function _get_referenced_subgraphs_by_filter(filter){ var anchor = this; var ret = []; each(anchor._referenced_subgraphs, function(g){ var res = filter(g); if( res && res === true ){ ret.push(g); } }); return ret; }
javascript
{ "resource": "" }
q11386
_get_referenced_subgraph_by_id
train
function _get_referenced_subgraph_by_id(iid){ var anchor = this; var ret = null; each(anchor._referenced_subgraphs, function(g){ if( g.id() === iid ){ ret = g; } }); return ret; }
javascript
{ "resource": "" }
q11387
noctua_graph
train
function noctua_graph(new_id){ bbop_graph.call(this); this._is_a = 'bbop-graph-noctua.graph'; // Deal with id or generate a new one. if( typeof(new_id) !== 'undefined' ){ this.id(new_id); } // The old edit core. this.core = { 'edges': {}, // map of id to edit_edge - edges not completely anonymous 'node_order': [], // initial table order on redraws 'node2elt': {}, // map of id to physical object id 'elt2node': {}, // map of physical object id to id // Remeber that edge ids and elts ids are the same, so no map // is needed. 'edge2connector': {}, // map of edge id to virtual connector id 'connector2edge': {} // map of virtual connector id to edge id }; this._annotations = []; //this._referenced_subgraphs = []; // not for graph yet, or maybe ever // Some things that come up in live noctua environments. These are // graph properties that may or may not be there. If unknown, // null; if positively true (bad), true; may be false otherwise. this._inconsistent_p = null; this._modified_p = null; }
javascript
{ "resource": "" }
q11388
_is_same_ann
train
function _is_same_ann(a1, a2){ var ret = false; if( a1.key() === a2.key() && a1.value() === a2.value() && a1.value_type() === a2.value_type() ){ ret = true; } return ret; }
javascript
{ "resource": "" }
q11389
is_iri_ev_p
train
function is_iri_ev_p(ann){ var ret = false; if( ann.key() === 'evidence' && ann.value_type() === 'IRI' ){ ret = true; } return ret; }
javascript
{ "resource": "" }
q11390
pull_seeds
train
function pull_seeds(entity, test_p){ each(entity.annotations(), function(ann){ //console.log(ann.key(), ann.value_type(), ann.value()); // Is it an evidence annotation. if( ! test_p(ann) ){ // Skip. //console.log('skip folding with failed test'); }else{ //console.log('start folding with passed test'); // If so, and the individual in question exists, it is // the jumping off point for the evidence folding // subgraph. var ref_node_id = ann.value(); var ref_node = anchor.get_node(ref_node_id); if( ref_node ){ seeds[ref_node_id] = entity; } } }); }
javascript
{ "resource": "" }
q11391
_unfold_subgraph
train
function _unfold_subgraph(sub){ // Restore to graph. // console.log(' unfold # (' + sub.all_nodes().length + ', ' + // sub.all_edges().length + ')'); each(sub.all_nodes(), function(node){ anchor.add_node(node); }); each(sub.all_edges(), function(edge){ anchor.add_edge(edge); }); }
javascript
{ "resource": "" }
q11392
noctua_node
train
function noctua_node(in_id, in_label, in_types, in_inferred_types){ bbop_node.call(this, in_id, in_label); this._is_a = 'bbop-graph-noctua.node'; var anchor = this; // Let's make this an OWL-like world. this._types = []; this._inferred_types = []; this._id2type = {}; // contains map to both types and inferred types this._annotations = []; this._referenced_subgraphs = []; this._embedded_subgraph = null; // Incoming ID or generate ourselves. if( typeof(in_id) === 'undefined' ){ this._id = bbop.uuid(); }else{ this._id = in_id; } // Roll in any types that we may have coming in. if( us.isArray(in_types) ){ each(in_types, function(in_type){ var new_type = new class_expression(in_type); anchor._id2type[new_type.id()] = new_type; anchor._types.push(new class_expression(in_type)); }); } // Same with inferred types. if( us.isArray(in_inferred_types) ){ each(in_inferred_types, function(in_inferred_type){ var new_type = new class_expression(in_inferred_type); anchor._id2type[new_type.id()] = new_type; anchor._inferred_types.push(new class_expression(in_inferred_type)); }); } }
javascript
{ "resource": "" }
q11393
noctua_edge
train
function noctua_edge(subject, object, predicate){ bbop_edge.call(this, subject, object, predicate); this._is_a = 'bbop-graph-noctua.edge'; // Edges are not completely anonymous in this world. this._id = bbop.uuid(); this._predicate_label = null; this._annotations = []; this._referenced_subgraphs = []; }
javascript
{ "resource": "" }
q11394
getStringValue
train
function getStringValue(value) { var return_value = ''; switch(typeof(value)) { case 'string': return_value = "'" + value + "'"; break; case 'number': return_value = value; break; case 'object': if(value==null) return_value = value; else { var valuestring = JSON.stringify(value); return_value = "'" + valuestring + "'"; } break; default: return_value = "'" + value + "'"; break; } return return_value; }
javascript
{ "resource": "" }
q11395
JSONparse
train
function JSONparse(string) { string = string.replace(/:\s*"([^"]*)"/g, function(match, p1) { return ': "' + p1.replace(/:/g, '@colon@') + '"'; }).replace(/:\s*'([^']*)'/g, function(match, p1) { return ': "' + p1.replace(/:/g, '@colon@') + '"'; }).replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": '); string = string.replace(/@colon@/g, ':'); return JSON.parse(string); }
javascript
{ "resource": "" }
q11396
KeyPair
train
function KeyPair(privkey) { if (!(this instanceof KeyPair)) { return new KeyPair(privkey); } if (privkey) { this._keypair = ecdsa.keyFromPrivate(privkey); } else { this._keypair = ecdsa.genKeyPair(); } }
javascript
{ "resource": "" }
q11397
parsePacket
train
function parsePacket(packet) { var parsedPacket = loopPacket.parse(packet); var convertedPacket = {}; for(var property in parsedPacket) { var value = parsedPacket[property]; switch (property){ case "BarTrend": value = _convertBarTrend(value); break; case "TempIn": case "TempOut": value = Convert(value/10).from('F').to('C'); break; case "BatteryVolts": value = _convertToVoltage(value); break; case "ForecastRuleNo": value = _getForecastString(value); break; case "ForecastIcon": value = _parseIconValue(value); break; case "SunRise": case "SunSet": value = _convertTime(value); break; case "WindSpeed": case "WindSpeed10Min": value = Convert(value).from('m/h').to('m/s'); break; } convertedPacket[property] = value; } return parsedPacket; }
javascript
{ "resource": "" }
q11398
writeToLogFile
train
function writeToLogFile(rawPacket, parsedPacket) { if (!debugMode) { return; } var now = new Date().toUTCString(); fs.appendFile(config.debugRawDataFile, 'Package received at ' + now + ':\n' + rawPacket + '\n\n', function (err) { if (err) { console.error('Could not write raw package to ' + config.debugRawDataFile); } }); fs.appendFile(config.debugParsedDataFile, 'Package received at ' + now + ':\n' + JSON.stringify(parsedPacket, true, 4) + '\n\n', function (err) { if (err) { console.error('Could not write parsed package to ' + config.debugParsedDataFile); } }); }
javascript
{ "resource": "" }
q11399
train
function (params) { var resourceObject = { url: resource.url(), method: method, headers: resource.headers }; if (typeof params === 'object') { resourceObject.json = true; resourceObject.body = params; } else if (typeof params === 'string') { resourceObject.body = params; } // Should this resource be mocked, or real? // It is ensured that you can define the mock before // or after the resource is defined var mock = self.mock(method, uri); if (mock) { mock.request = { body: params, method: method, pathname: slash(uri), headers: resource.headers }; return mock.fn()(); } else { return rawHttp(extend(resourceObject, resource.xhrOptions || {})); } }
javascript
{ "resource": "" }