_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36400
renameFile
train
function renameFile (oldFile, newFile) { if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; } let item = fileRegistry[oldFile]; item.file = newFile; fileRegistry[newFile] = item; delete fileRegistry[oldFile]; }
javascript
{ "resource": "" }
q36401
onEvent
train
function onEvent (watcher) { // Wait for write stream to end if write has been delayed. if (writeDelayed) { return undefined; } // If any watch events occur while writing to dest then restart // write stream with new changes. if (stream.isWriting()) { writeDelayed = true; stream.endWriteStream(); // Initial write of files to dest. } else { writeStartTime = Date.now(); writeFiles(); } }
javascript
{ "resource": "" }
q36402
executioner
train
function executioner(commands, params, options, callback) { var keys, execOptions, collector = []; // optional options :) if (typeof options == 'function') { callback = options; options = {}; } // clone params, to mess with them without side effects params = extend(params); // copy options and with specified shell execOptions = extend(executioner.options || {}, options || {}); // use it as array if (typeof commands == 'string') { commands = [ commands ]; } // assume commands that aren't array are objects if (!Array.isArray(commands)) { keys = Object.keys(commands); } run(collector, commands, keys, params, execOptions, function(err, results) { // output single command result as a string callback(err, (results && results.length == 1) ? results[0] : results); }); return collector; }
javascript
{ "resource": "" }
q36403
parse
train
function parse (targets) { debug('Parse: start parsing'); targets = prepare.targets(targets); prepare_babelrc(); parse_targets(targets); }
javascript
{ "resource": "" }
q36404
parse_targets
train
function parse_targets (targets) { debug('Parse: parse targets'); for (let i = 0; i < targets.length; i++) { const target = targets[i]; const name = path.basename(target); if (is_special(name)) { special_targets.push(target); continue; } parse_target(target); } }
javascript
{ "resource": "" }
q36405
expand
train
function expand(file, root){ var items = file.orig.src; var category = file.dest; _debug("Expanding "+category+": ",items,"\n"); var expanded; switch(category){ case 'meta': //bypass expanding that would break expanded = items; break; case 'head': case 'body': //expand + retrieve file content expanded = grunt.file.expand({cwd:root,nonull:true},items); expanded = expanded.map(function(item){ var filePath = path.join(root,item); if(isFile(filePath)){ return grunt.file.read(filePath,{encoding:'utf8'}); } else{ _debug("File ",filePath," does not exist"); return item; } }); break; default: //expand expanded = grunt.file.expand({cwd:root,nonull:true},items); break; } _debug("Expanded "+category+": ",expanded,"\n"); return expanded; }
javascript
{ "resource": "" }
q36406
getPerformanceTimingData
train
function getPerformanceTimingData() { var PerformanceObj = { 'redirecting': performance.timing.fetchStart - performance.timing.navigationStart, 'dnsconnect': performance.timing.requestStart - performance.timing.fetchStart, 'request': performance.timing.responseStart - performance.timing.requestStart, 'response': performance.timing.responseEnd - performance.timing.responseStart, 'domprocessing': performance.timing.domComplete - performance.timing.responseEnd, 'load': performance.timing.loadEventEnd - performance.timing.loadEventStart }; /** * Obtaining the transferred kb of resources inluding estimated document size. */ if (window.performance && window.performance.getEntriesByType) { var resource; var resources = window.performance.getEntriesByType('resource'); var documentSize = unescape(encodeURIComponent(document.documentElement.innerHTML)).length / 4.2; var byteTotal = 0; for (var i = 0; i < resources.length; i++) { resource = resources[i]; byteTotal = byteTotal + resource.transferSize; } PerformanceObj.transferbytes = byteTotal + Math.round(documentSize); PerformanceObj.transferrequests = resources.length + 1; } return PerformanceObj; }
javascript
{ "resource": "" }
q36407
at
train
function at(index) { if (!this) { throw TypeError(); } const str = '' + this, len = str.length; if (index >= len) { return; } if (index < 0) { index = len - index; } let i = 0; for (let item of str) { if (i === index) { return item; } } return; }
javascript
{ "resource": "" }
q36408
trimHandle
train
function trimHandle(str, chars = ' ', position) { if (typeof str !== 'string') { return; } let cs = chars; if (Valid.isArray(chars)) { cs = chars.join(''); } const startReg = new RegExp(`^[${cs}]*`, 'g'), endReg = new RegExp(`[${cs}]*$`, 'g'); if (position === 'start') { return str.replace(startReg, ''); } else if (position === 'end') { return str.replace(endReg, ''); } return str.replace(startReg, '').replace(endReg, ''); }
javascript
{ "resource": "" }
q36409
train
function(a, length, msg) { return assert((this.assertIsArray(a, msg) && a.length <= length), msg); }
javascript
{ "resource": "" }
q36410
train
function(a, length, allowNumbers, msg) { allowNumbers = allowNumbers || true; return assert((this.assertIsString(a, allowNumbers) && a.length <= length), msg); }
javascript
{ "resource": "" }
q36411
train
function(a, min, max, allowNumbers, msg) { return assert((this.assertStringMinLength(a, min, allowNumbers, msg)&&this.assertStringMaxLength(a, max, allowNumbers, msg)), msg); }
javascript
{ "resource": "" }
q36412
train
function(a, start, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(start)===0), msg); }
javascript
{ "resource": "" }
q36413
train
function(a, end, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(end, a.length - end.length) !== -1), msg); }
javascript
{ "resource": "" }
q36414
train
function(value, assertionObject) { for(var name in assertionObject) { if (assertionObject.hasOwnProperty(name)) { args = [value]; args = args.concat(assertionObject[name]); this[name].apply(this, args); } } }
javascript
{ "resource": "" }
q36415
FbFloBrunch
train
function FbFloBrunch(config) { this.setOptions(config); // This plugin only makes sense if we're in watcher mode // (`config.persistent`). Also, we honor the plugin-specific `enabled` // setting, so users don't need to strip the plugin or its config to // disable it: just set `enabled` to `false`. if (!config || !config.persistent || false === this.config.enabled) { return; } this.resolver = this.resolver.bind(this); this.startServer(); }
javascript
{ "resource": "" }
q36416
resolver
train
function resolver(filePath, callback) { var fullPath = path.join(this.config.publicPath, filePath); var options = { resourceURL: filePath, contents: fs.readFileSync(fullPath).toString() }; // If we defined a custom browser-side message system, use it. if (this.update) { options.update = this.update; } // If we specified a `match` option for fb-flo notifications, use it. if (this.config.resolverMatch) { options.match = this.config.resolverMatch; } // If we defined an advanced reload mechanism (fb-flo only has true/false, // we also allow anymatch sets), use it. if (this.config.resolverReload) { options.reload = this.config.resolverReload(filePath); } // Hand the notification over to the fb-flo server. callback(options); }
javascript
{ "resource": "" }
q36417
startServer
train
function startServer() { this._flo = flo( // The path to watch (see `setOptions(…)`). this.config.publicPath, // The config-provided fb-flo options + a generic watch glob // (all JS/CSS, at any depth) inside the watched path. extend( pick(this.config, FB_FLO_OPTIONS), { glob: ['**/*.js', '**/*.css'] } ), // Our resolver method (it was properly bound upon construction). this.resolver ); }
javascript
{ "resource": "" }
q36418
isFloat
train
function isFloat (n, shouldCoerce) { if (shouldCoerce) { if (typeof n === "string") { n = parseFloat(n); } } return n === +n && n !== (n|0); }
javascript
{ "resource": "" }
q36419
writeExterns
train
function writeExterns (grunt, fileData, options) { let content = ''; // Default externs. content += 'var require = function () {};'; for (let i = 0, max = options.externs.length; i < max; i++) { content += `var ${options.externs[i]} = {};`; } grunt.file.write(fileData.tmpExterns, content); }
javascript
{ "resource": "" }
q36420
printHostnames
train
function printHostnames() { console.log(chalk.yellow.bold(`${indent(2)} Hostnames requested: `)); if (Object.keys(hostnames).length === 0) { console.log(chalk.yellow(`${indent(4)}none`)); return; } for (const key in hostnames) { if (!hostnames[key]) return; console.log(chalk.yellow(`${indent(4)}${key}: ${hostnames[key]}`)); } }
javascript
{ "resource": "" }
q36421
patchMocha
train
function patchMocha() { const _testRun = Mocha.Test.prototype.run; Mocha.Test.prototype.run = function (fn) { function done(ctx) { fn.call(this, ctx); if (testRequests.length) { printTestRequest(testRequests); testRequests = []; } } return _testRun.call(this, done); }; const _run = Mocha.prototype.run; Mocha.prototype.run = function(fn) { function done(failures) { printHostnames(hostnames); fn.call(this, failures); } return _run.call(this, done); }; }
javascript
{ "resource": "" }
q36422
getHostname
train
function getHostname(httpOptions) { if (httpOptions.uri && httpOptions.uri.hostname) { return httpOptions.uri.hostname; } else if (httpOptions.hostname) { return httpOptions.hostname; } else if (httpOptions.host) { return httpOptions.host; } return 'Unknown'; }
javascript
{ "resource": "" }
q36423
getHref
train
function getHref(httpOptions) { if (httpOptions.uri && httpOptions.uri.href) { return httpOptions.uri.href; } else if (httpOptions.hostname && httpOptions.path) { return httpOptions.hostname + httpOptions.path; } else if (httpOptions.host && httpOptions.path) { return httpOptions.host + httpOptions.path; } return 'Unknown'; }
javascript
{ "resource": "" }
q36424
patchHttpClient
train
function patchHttpClient() { const _ClientRequest = http.ClientRequest; function patchedHttpClient(options, done) { if (http.OutgoingMessage) http.OutgoingMessage.call(this); const hostname = getHostname(options); // Ignore localhost requests if (hostname.indexOf('127.0.0.1') === -1 && hostname.indexOf('localhost') === -1) { if (hostnames[hostname]) { hostnames[hostname]++; } else { hostnames[hostname] = 1; } testRequests.push(getHref(options)); } _ClientRequest.call(this, options, done); } if (http.ClientRequest) { inherits(patchedHttpClient, _ClientRequest); } else { inherits(patchedHttpClient, EventEmitter); } http.ClientRequest = patchedHttpClient; http.request = function(options, done) { return new http.ClientRequest(options, done); }; }
javascript
{ "resource": "" }
q36425
isTargetPath
train
function isTargetPath(srcPath, pathTest) { return !srcPath || (Array.isArray(pathTest) ? pathTest : [pathTest]).some(function(test) { return test && (test instanceof RegExp ? test.test(srcPath) : srcPath.indexOf(test) === 0); }); }
javascript
{ "resource": "" }
q36426
posts
train
function posts (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { allFiles.forEach(file => { if (file.name === each) { output[each] = file } }) }) return output }
javascript
{ "resource": "" }
q36427
gallery
train
function gallery (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { Object.keys(each).forEach(key => { output[key] = Object.assign({ title: each[key] }, allFiles.filter(file => file.name === key)[0]) }) }) return output }
javascript
{ "resource": "" }
q36428
activateField
train
function activateField(model, fields) { let activeFields = []; if (fields === true) { // activate all return Object.keys(model.def.fields); } else if (Array.isArray(fields)) { activeFields = fields; } else if (typeof fields === 'string') { if (fields.indexOf('*') >= 0) { // activate all activeFields = Object.keys(model.def.fields); } else { activeFields = fields.trim().split(/\s*,\s*/); } } if (activeFields.length <= 0) throw new QueryError(model.name, 'fields required in find'); // activate the related fields return Object.keys(activateRelatedFields(model, activeFields)); }
javascript
{ "resource": "" }
q36429
cfv
train
function cfv(model, set) { const cvs = {};// column values for (const fieldName in set) { const field = model.def.fields[fieldName]; if (!field || field.props.category !== 'entity') continue; const value = set[fieldName]; cvs[field.props.column] = value; } return cvs; }
javascript
{ "resource": "" }
q36430
zip
train
function zip(keys, values) { if (keys.length !== values.length) { throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`) } return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {}) }
javascript
{ "resource": "" }
q36431
PossibleStatesContainer
train
function PossibleStatesContainer({current, allStates, data}) { return { caseOf(clauses) { const casesCovered = Object.keys(clauses) const notCovered = allStates.map(({name}) => name).filter(state => !casesCovered.includes(state)) if (notCovered.length > 0 && !casesCovered.includes('_')) { throw Error('All cases are not covered in a "caseOf" clause') } const cb = clauses[current.name] || clauses['_'] return cb instanceof Function ? cb(data) : cb }, current() { return current.name }, data() { return {...data} }, ...generateTransitionHelpers(current, allStates), ...generateWhenAndNotHelpers(current, data, allStates), } }
javascript
{ "resource": "" }
q36432
PossibleStates
train
function PossibleStates(...allStates) { if (!allStates.length === 0) { throw Error('No values passed when constructing a new PossibleStates') } const containsData = typeDefinition => typeDefinition.match(/<.*>/) if (allStates[0].match(/<.*>/)) { throw Error('The initial state cannot contain data') } const parsedStates = allStates.map(state => { if (!containsData(state)) { return {name: state, data: []} } const [name, typeDefs] = state.match(/^(.*)<(.*)>$/).slice(1) return {name, data: typeDefs.split(',').map(def => def.trim())} }) return PossibleStatesContainer({current: parsedStates[0], allStates: parsedStates}) }
javascript
{ "resource": "" }
q36433
train
function(architectural, units, precision) { if (typeof architectural !== "string" && !(architectural instanceof String)) return false; if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null) return false; if(["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision) < 0) return false; if(["inches", "feet"].indexOf(units) < 0) return false; var decimal = 0; var feet = architectural.match(/^([0-9]+)\'[-\s]*/); if(feet !== null) decimal += parseInt(feet[1]) * 12; var inches = architectural.match(/([-\s\']+([0-9]+)|^([0-9]+))[-\s\"]+/); if(inches !== null) { if(feet !== null) decimal += parseInt(inches[2]); else decimal += parseInt(inches[3]); } var fraction = architectural.match(/([-\s\']+([0-9]+\/[0-9]+)|(^[0-9]+\/[0-9]+))\"/); if(fraction !== null) { if(feet !== null || inches !== null) decimal += divideFraction(fraction[2]); else decimal += divideFraction(fraction[3]); } if(units !== "inches") decimal = decimal / 12; decimal = roundNumber(decimal, ["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision)); return decimal; }
javascript
{ "resource": "" }
q36434
train
function(decimal, units, precision) { if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal)) return false; if(["inches", "feet"].indexOf(units) < 0) return false; if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0) return false; var architectural = ""; var precision = parseFloat(precision.replace("1/", "")); if(units !== "inches") decimal = decimal * 12; if(decimal < 0) { decimal = Math.abs(decimal); architectural += "-"; } var feet = Math.floor(decimal / 12); architectural += feet + "' "; var inches = Math.floor(decimal - (feet * 12)); architectural += inches + "\""; var fraction = Math.floor((decimal - (feet * 12) - inches) * precision); if(fraction > 0) architectural = architectural.replace("\"", " " + reduceFraction(fraction, precision) + "\""); return architectural; }
javascript
{ "resource": "" }
q36435
createByFacebook
train
function createByFacebook(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByFacebookID(profile.id, ok(callback, (user) => { if (user) { return updateUserByFacebookProfile(user, profile, callback); } this.create({ username: profile.username || null, firstName: profile.first_name, lastName: profile.last_name, name: profile.name, email: profile.email, locale: profile.locale, }, ok(callback, (newUser) => { newUser.addProvider('facebook', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
javascript
{ "resource": "" }
q36436
createByTwitter
train
function createByTwitter(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByTwitterID(profile.id, ok(callback, (user) => { if (user) { return callback(null, user); } this.create({ username: profile.username || null, name: profile.displayName, }, ok(callback, (newUser) => { newUser.addProvider('twitter', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
javascript
{ "resource": "" }
q36437
generateBearerToken
train
function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) { if (!tokenSecret) { throw new Error('Token secret is undefined'); } const data = { user: this._id.toString(), }; if (scope.length) { data.scope = scope; } const token = jwt.sign(data, tokenSecret, { expiresInMinutes, }); return { type: 'Bearer', value: token, }; }
javascript
{ "resource": "" }
q36438
comparePassword
train
function comparePassword(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) { return callback(err); } callback(null, isMatch); }); }
javascript
{ "resource": "" }
q36439
pushNode
train
function pushNode( /*handler1, handler2, ..., handlerN*/ ) { var node = { items: utils.slice(arguments), state: {} } var id = this.props._nodes.add(node) node.id = id return node }
javascript
{ "resource": "" }
q36440
pushHandlers
train
function pushHandlers (chain, args) { return pushNode.apply(chain, utils.type(args[0]) == 'array' ? args[0]:args) }
javascript
{ "resource": "" }
q36441
setAlltoNoop
train
function setAlltoNoop (obj, methods) { utils.each(methods, function (method) { obj[method] = noop }) }
javascript
{ "resource": "" }
q36442
LacesLocalModel
train
function LacesLocalModel(key) { var data = localStorage.getItem(key); var object = data && JSON.parse(data) || {}; Laces.Model.call(this, object); this.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); }); }
javascript
{ "resource": "" }
q36443
LacesLocalArray
train
function LacesLocalArray(key) { var data = localStorage.getItem(key); var elements = data && JSON.parse(data) || []; var array = Laces.Array.call(this); for (var i = 0, length = elements.length; i < length; i++) { array.push(elements[i]); } array.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); }); return array; }
javascript
{ "resource": "" }
q36444
createCompleteCallback
train
function createCompleteCallback(name) { return function(data) { _store[name] = data; var allCallbacksComplete = Object.keys(_store).reduce(isStoreValid, true); if (allCallbacksComplete) { clearTimeout(pageReadyWarning); ceddl.emitEvent('pageready', _store); } }; }
javascript
{ "resource": "" }
q36445
pageReadySetListeners
train
function pageReadySetListeners(eventNames) { // Reset the previous state _store = {}; _listeners.forEach(function(eventCallback) { ceddl.eventbus.off(eventCallback.name, eventCallback.markComplete); }); _listeners = []; // If there is no need to wait for anything dispatch event when the page is ready. if (!eventNames || eventNames.length === 0) { pageReady(function() { ceddl.emitEvent('pageready', _store); }); return; } startWarningTimeout(); if (!Array.isArray(eventNames)) { // Split on whitespace and remove empty entries. eventNames = eventNames.split(' ').filter(function(value) { return !!value; }); } if(_el) { _el.setAttribute('data-page-ready', eventNames.join(' ')); } // Create the new state eventNames.forEach(function(name) { _store[name] = false; }); _listeners = eventNames.map(setCompleteListener); }
javascript
{ "resource": "" }
q36446
_initFeed
train
function _initFeed(meta) { // create out feed feed = new RSS({ title: meta.title.replace(/^GoComics.com - /, ''), description: meta.description, generator: 'node-comics-scrape', feed_url: meta.xmlUrl, site_url: meta.link, pubDate: meta.pubDate, ttl: ONE_DAY_MINUTES }); }
javascript
{ "resource": "" }
q36447
merge
train
function merge(target, options) { var key; if (!target) { target = {}; } if (options) { for (key in options) { if (options.hasOwnProperty(key)) { var targetHasIt = target.hasOwnProperty(key), optionsValueType = typeof options[key], shouldReplace = !targetHasIt || (typeof target[key] !== optionsValueType); if (shouldReplace) { target[key] = options[key]; } else if (optionsValueType === 'object') { // go deep, don't care about loops here, we are simple API!: target[key] = merge(target[key], options[key]); } } } } return target; }
javascript
{ "resource": "" }
q36448
train
function (ary) { var shuffled = []; ary.reduce(function (acc, v) { var r = range(0, acc); shuffled[acc] = shuffled[r]; shuffled[r] = v; return acc + 1; }, 0); return shuffled; }
javascript
{ "resource": "" }
q36449
train
function($str, $checkColors) { var $regex = new RegExp(REGEXP_PLAIN, 'gm'); var $match = $str.match($regex); if (!!$match) { $str = $str.substr($match[0].length); $match = true; } else if ($checkColors !== false) { $regex = new RegExp(REGEXP_ANSI, 'gm'); $match = $str.match($regex); if (!!$match) { $str = $str.substr($match[0].length); $match = true; } } // trim extra seperator space when available if ($match && $str.substr(0, 1) === ' ') { $str = $str.substr(1); } return $str; }
javascript
{ "resource": "" }
q36450
run
train
function run(index) { if (index >= len || error) return Promise.resolve(); next += 1; try { return Promise.resolve(iterator(arr[index], index)).then((ret) => { result[index] = ret; return run(next); }, (err) => { error = err; return Promise.reject(err); }); } catch (e) { return Promise.reject(e); } }
javascript
{ "resource": "" }
q36451
updateCountSuccess
train
function updateCountSuccess(that) { if(that.expected !== undefined) { var countSuccess = that.count === that.expected that.countBlock.state.set("success", countSuccess) if(that.groupEnded) that.countBlock.results.state.set("late", true) if(countSuccess) { that.mainGroup.title.testTotalPasses++ that.title.passed++ if(that.groupEnded) { that.mainGroup.title.testTotalFailures-- that.groupEndCountSubtracted = true // marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be) } } else if(that.groupEndCountSubtracted || that.count - 1 === that.expected) { that.title.passed-- that.mainGroup.title.testTotalPasses-- if(that.groupEnded) { that.mainGroup.title.testTotalFailures++ } } } }
javascript
{ "resource": "" }
q36452
containsSingleMatch
train
function containsSingleMatch(str, arr) { var filtered = arr.filter(function(e) { return e.indexOf(str) === 0 }) return filtered.length === 1 }
javascript
{ "resource": "" }
q36453
objectEach
train
function objectEach(obj, fn, thisObj) { var keys = Object.keys(obj).sort(function (a,b) { a = a.toLowerCase() b = b.toLowerCase() return a === b ? 0 : a < b ? -1 : 1 }) for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i] fn.call(thisObj, obj[key], key, obj) } }
javascript
{ "resource": "" }
q36454
train
function($frag) { if(typeof $frag.parent().attr('jt-code-blur') !== 'string') { return; } if(typeof $frag.attr('jt-clear-blur') === 'string') { return $frag.parent().find('code').removeClass('blurred'); } if($frag.is('code') && $frag.hasClass('fragment')) { $frag.parent() .find('code').addClass('blurred') .filter('.current-fragment').removeClass('blurred'); } }
javascript
{ "resource": "" }
q36455
normalizeContent
train
function normalizeContent(content) { var fragment = document.createDocumentFragment(); var i, len; if (isNode(content)) { return content; } else { len = content.length; for (i = 0; i < len; i++) { fragment.appendChild(content[i]); } return fragment; } }
javascript
{ "resource": "" }
q36456
train
function (doc) { [ 'Returns', 'Emits', 'Access', 'Kind' ].forEach(function removeLine(preTag) { preTag = '**' + preTag; var start = doc.indexOf(preTag); if (start !== -1) { var end = doc.indexOf('\n', start) + 1; doc = doc.substring(0, start) + doc.substring(end); } }); return doc; }
javascript
{ "resource": "" }
q36457
train
function (doc, skipSignature, postHook) { var index = doc.indexOf('\n'); var functionLine = ''; if (!skipSignature) { functionLine = doc.substring(0, index).substring(4); //get first line and remove initial ### //wrap with "'", replace object#function to object.function, remove <code>, fix escape chars functionLine = '### \'' + functionLine.split('#').join('.').split('<code>').join('').split('</code>').join('').split('&.').join('&#') + '\''; //remove links var foundLinks = false; var field; var start; var end; do { end = functionLine.indexOf(']('); if (end !== -1) { start = functionLine.lastIndexOf('[', end); field = functionLine.substring(start + 1, end); end = functionLine.indexOf(')', start) + 1; functionLine = functionLine.substring(0, start) + field + functionLine.substring(end); foundLinks = true; } else { foundLinks = false; } } while (foundLinks); } if (functionLine && postHook && (typeof postHook === 'function')) { functionLine = postHook(functionLine); } doc = functionLine + doc.substring(index); return doc; }
javascript
{ "resource": "" }
q36458
train
function (grunt, apiDocs, apiDocLink, occurrence) { occurrence = occurrence || 1; var linkString = '<a name="' + apiDocLink + '"></a>'; var index = -1; var occurrenceIndex; for (occurrenceIndex = 0; occurrenceIndex < occurrence; occurrenceIndex++) { index = apiDocs.indexOf(linkString, index + 1); if (index === -1) { grunt.fail.warn(new Error('API link: ' + apiDocLink + ' not found.')); } } return index; }
javascript
{ "resource": "" }
q36459
train
function(callback) { dataIndex = {}; var pos = 0; enamdictData.split("\n").forEach(function(line) { var parts = line.split("|"); var cleanName = parts[0]; var romaji = parts[1]; if (!(cleanName in dataIndex)) { dataIndex[cleanName] = pos; } if (!(romaji in dataIndex)) { dataIndex[romaji] = pos; } // +1 for the \n pos += line.length + 1; }); callback(null, this); }
javascript
{ "resource": "" }
q36460
sendCsMessage
train
function sendCsMessage(csMessage){ var token = this.instance.getAccessToken(); var url = 'https://api.WeiXin.qq.com/cgi-bin/message/custom/send?access_token='+token; var fiber = fibext(); hr.post(url, {json: csMessage}, util.processResponse(function(err, body){ fiber.resume(err, body); })); return fiber.wait(); }
javascript
{ "resource": "" }
q36461
generate
train
function generate(spec) { createProjectDirectory(); spec = addHttpEndpointNames(spec); spec = addSocketEndpointFlag(spec); spec = addSocketEmitTypeFlag(spec); spec = isProxyEndpointAvailable(spec); writeFileSync('server.mustache', spec, 'server.js'); writeFileSync('package.mustache', spec, 'package.json'); }
javascript
{ "resource": "" }
q36462
addHttpEndpointNames
train
function addHttpEndpointNames(spec) { for(var i = 0; i < spec.endpoints.length; i++) { var endpoint = spec.endpoints[i]; if (endpoint.response.contentType.contentType.toLowerCase() === 'javascript') { endpoint.response.contentType.contentType = 'application/json'; endpoint.response.contentType.eval = true; } else { endpoint.response.content = endpoint.response.content.replace(/(\r\n|\n|\r)/gm,""); } endpoint.httpMethod = endpoint.method.toLowerCase(); } return spec; }
javascript
{ "resource": "" }
q36463
addSocketEmitTypeFlag
train
function addSocketEmitTypeFlag(spec) { for(var i = 0; i < spec.socketEndpoints.length; i++) { var endpoint = spec.socketEndpoints[i]; endpoint.isEmitSelf = endpoint.emitType === "self"; endpoint.isEmitAll = endpoint.emitType === "all"; endpoint.isEmitBroadcast = endpoint.emitType === "broadcast"; endpoint.payload = endpoint.payload.replace(/(\r\n|\n|\r)/gm,""); } return spec; }
javascript
{ "resource": "" }
q36464
writeFileSync
train
function writeFileSync(templateName, templateOption, filename) { var templateString = fs.readFileSync(path.join(__dirname, '/templates/' + templateName), 'utf8'); fs.writeFileSync(path.join(projectDirectory, filename), Mustache.render(templateString, templateOption)); }
javascript
{ "resource": "" }
q36465
getEvent
train
function getEvent(context, eventName) { if (!eventsMap.has(context)) { eventsMap.set(context, {}); } const events = eventsMap.get(context); if (!events[eventName]) { events[eventName] = { listeners: [], meta: new WeakMap() }; } return events[eventName]; }
javascript
{ "resource": "" }
q36466
addListener
train
function addListener(event, callback, meta) { event.listeners.push(callback); event.meta.set(callback, meta); }
javascript
{ "resource": "" }
q36467
deleteListener
train
function deleteListener(event, callback, idx) { if ((idx = event.listeners.indexOf(callback)) >= 0) { event.listeners.splice(idx, 1); event.meta.delete(callback); return true; } return false; }
javascript
{ "resource": "" }
q36468
generateStraitsFunctions
train
function generateStraitsFunctions( {template}, path ) { // testTraitSet( traitSet ) // it makes sure that all the `use traits * from` statements have a valid object as expression const testTraitBuilder = template(` function TEST_TRAIT_SET( traitSet ) { if( ! traitSet || typeof traitSet === 'boolean' || typeof traitSet === 'number' || typeof traitSet === 'string' ) { throw new Error(\`\${traitSet} cannot be used as a trait set.\`); } } `); // getSymbol( targetSymName, ...traits ) // looks for `targetSymName` inside `traits`, and returns the symbol, if found const getSymbolBuilder = template(` function GET_SYMBOL( targetSymName, ...traitSets ) { let symbol; traitSets.forEach( traitSet=>{ const sym = traitSet[targetSymName]; if( typeof sym === 'symbol' ) { if( !! symbol && symbol !== sym ) { throw new Error(\`Symbol \${targetSymName} offered by multiple trait sets.\`); } symbol = sym; } }); if( ! symbol ) { throw new Error(\`No trait set is providing symbol \${targetSymName}.\`); } return symbol; } `); // implSymbol( target, sym, value ): `target.*[sym] = value` const implSymbolBuilder = template(` function IMPL_SYMBOL( target, sym, value ) { Object.defineProperty( target, sym, {value, configurable:true} ); return target[sym]; } `); // generating identifiers for the above functions const identifiers = { testTraitSet: path.scope.generateUidIdentifier(`testTraitSet`), getSymbol: path.scope.generateUidIdentifier(`getSymbol`), implSymbol: path.scope.generateUidIdentifier(`implSymbol`), }; // adding to the AST the code for the above functions path.unshiftContainer('body', testTraitBuilder({ TEST_TRAIT_SET:identifiers.testTraitSet }) ); path.unshiftContainer('body', getSymbolBuilder({ GET_SYMBOL:identifiers.getSymbol }) ); path.unshiftContainer('body', implSymbolBuilder({ IMPL_SYMBOL:identifiers.implSymbol }) ); // returning the identifiers return identifiers; }
javascript
{ "resource": "" }
q36469
overwrite
train
function overwrite(obj, defaults) { var res = {}; var dFlat = collapse(defaults); var oFlat = collapse(obj); for (var key in dFlat) { val(res, key, dFlat[key]); } for (var key in oFlat) { val(res, key, oFlat[key]); } return res; }
javascript
{ "resource": "" }
q36470
train
function(req, res) { this.debug('preProcessor called'); // MAGIC ALERT: if no templateName is specified the framework looks for [module name].[template extension] (default=.jade) // example of specifying nodule properties at request time if (req.path.indexOf('special') > -1) { this.apiCalls[1].params = {isSpecial: true}; // add extra param to existing API call this.templateName = 'altHomePage.jade'; // select alternate template } }
javascript
{ "resource": "" }
q36471
train
function(req, res) { this.debug('postProcessor called'); // example of post API business logic var clientMsg = res.yukon.data2.specialMsg || res.yukon.data2.msg; // MAGIC ALERT: if no res.yukon.renderData isn't specified, the framework uses res.yukon.data1 // res.yukon.renderData is the base object sent to jade template res.yukon.renderData = { globalNav: res.yukon.globalNav, cmsData: res.yukon.data1, myData: res.yukon.data2, clientMsg: clientMsg }; }
javascript
{ "resource": "" }
q36472
train
function (context, next) { this._cache.read(context.cached._id, function (err, doc) { if (err || !doc) return next(err || new Error('Critical failure! A cache entry has mysteriously disappeared...')); context.cached = doc; // this should happen only for internal phantom errors, not client javascript errors. if (context.cached.error) { this.logger.warn('The last try gave us an error, try to recompute.', { error: context.cached.error }); context.options.force = true; context.options.wait = true; } next(null); }); }
javascript
{ "resource": "" }
q36473
train
function (context, next) { if (context.options.force || !context.cached.template) { this._tasksQueue.push(Processor._models.task( context.cached._id, context.pathname, context.cached, !context.options.wait ? null : function (err, cached) { if (err) return next(err); context.cached = cached; next(null); } )); if (!context.options.wait) next(null); } else next(null); }
javascript
{ "resource": "" }
q36474
train
function (context, next) { if (context.cached.error) return next(context.cached.error); if (!context.cached.template) return next(new errors.Internal("For unknowns reasons, the template couldn't have been processed.")); var opts = { requests: context.cached.requests, template: context.cached.template, context: context.options.solidifyContext, host: this.options.host, sessionID: context.options.sessionID }; // solidify the template by feeding it. return this._solidify.feed(opts, function (err, result) { if (err) return next(new errors.Internal('Solidify error: ' + err.message)); context.solidified = result; next(null); }); }
javascript
{ "resource": "" }
q36475
InstantDateView
train
function InstantDateView(props) { var empty = React.createElement("time", null, "-"); if (!props.date) { return empty; } var isoDate = props.date.substring(0, 20); if (!isoDate) { return empty; } //Control characters: //https://github.com/js-joda/js-joda/blob/e728951a850dae8102b7fa68894535be43ec0521/src/format/DateTimeFormatterBuilder.js#L615 //TODO js-joda should support locales soonish, //so we can default to system date format. var pattern = props.pattern || 'MM/dd/yyyy'; var formatter = js_joda_1.DateTimeFormatter.ofPattern(pattern); try { var localDate = js_joda_1.LocalDateTime.ofInstant(js_joda_1.Instant.parse(isoDate)); var formattedDate = localDate.format(formatter); return React.createElement("time", { dateTime: isoDate }, formattedDate); } catch (e) { dev_1.warn("Provided datetime was not in ISO8061 format (yyyy-MM-ddTHH:mm:ssZ): " + props.date); return empty; } }
javascript
{ "resource": "" }
q36476
morph
train
function morph (value, input) { const result = input || readable() const cb = map[type(value)] || end cb(result, value) return new Proxy(result, { get(target, key, receiver) { if (key !== 'pipe') return target[key] return function (dest) { pump(result, dest) return dest } } }) }
javascript
{ "resource": "" }
q36477
type
train
function type (value) { const proto = toString.call(value) return proto.substring(8, proto.length - 1) }
javascript
{ "resource": "" }
q36478
end
train
function end (input, value) { if (value != null) input.push(String(value)) input.push(null) }
javascript
{ "resource": "" }
q36479
object
train
function object (input, value) { if (value instanceof Stream) stream(input, value) else stringify(input, value) }
javascript
{ "resource": "" }
q36480
stringify
train
function stringify (input, value) { input.push(JSON.stringify(value)) input.push(null) }
javascript
{ "resource": "" }
q36481
stream
train
function stream (input, value) { value.on('data', data => input.push(data)) value.on('error', err => error(input, err)) value.on('end', () => input.push(null)) }
javascript
{ "resource": "" }
q36482
promise
train
function promise (input, value) { value.then(val => { morph(val, input) }, reason => { input.emit('error', reason) }) }
javascript
{ "resource": "" }
q36483
polymerize
train
function polymerize(src, filepath) { // Parse web-component source (extract dependency, optimize source, etc.) var result = parseSource(src, filepath); // Generate commonjs module source: var src = []; // Require imported web-components result.imports.forEach(function(imp) { src.push('require("'+imp+'");') }); // Once DOMContentLoaded src.push('document.addEventListener("DOMContentLoaded",function() {'); // Inject html source if(result.head) { src.push('var head = document.getElementsByTagName("head")[0];') src.push('head.insertAdjacentHTML("beforeend",'+JSON.stringify(result.head)+');') } if(result.body) { src.push('var body = document.getElementsByTagName("body")[0];') src.push('var root = body.appendChild(document.createElement("div"));') src.push('root.setAttribute("hidden","");') src.push('root.innerHTML=' + JSON.stringify(result.body)+ ';') } // Require scripts result.scripts.forEach(function(script) { src.push('require("'+script+'");') }) // Append inline sources result.inline.forEach(function(inline) { src.push(';(function() {\n'+inline+'\n})();') }) // End DOMContentLoaded src.push('\n})') return src.join('\n') }
javascript
{ "resource": "" }
q36484
parseSource
train
function parseSource(src, filepath) { var result = {}; // Use whacko (cheerio) to parse html source var $ = whacko.load(src); // Extract sources and remove tags result.imports = extractImports($); result.scripts = extractScripts($); result.inline = extractInline($) // Inline external stylesheets inlineStylesheet($, filepath) // Inline css minification and remove comments minifyHtml($) // Extract transformed html source: result.head = $("head").html().trim(); result.body = $("body").html().trim(); return result; }
javascript
{ "resource": "" }
q36485
extractImports
train
function extractImports($) { var imports = []; $('link[rel=import][href]').each(function() { var el = $(this); var href = el.attr('href'); if(ABS.test(href)) return; imports.push(/^\./.test(href) ? href : './' + href); el.remove(); }) return imports; }
javascript
{ "resource": "" }
q36486
extractScripts
train
function extractScripts($) { var scripts = []; $('script[src]').each(function() { var el = $(this); var src = el.attr('src'); if(ABS.test(src)) return; scripts.push(/^\./.test(src) ? src : './' + src); el.remove(); }) return scripts; }
javascript
{ "resource": "" }
q36487
extractInline
train
function extractInline($) { var scripts = []; $('script:not([src])').each(function() { var el = $(this); var src = el.text(); var closestPolymerElement = el.closest('polymer-element'); if(closestPolymerElement.length) { src = fixPolymerInvocation(src, $(closestPolymerElement).attr('name')) } scripts.push(src); el.remove(); }) return scripts; }
javascript
{ "resource": "" }
q36488
inlineStylesheet
train
function inlineStylesheet($, filepath) { $('link[rel=stylesheet][href]').each(function() { var el = $(this); var href = el.attr('href'); if(ABS.test(href)) return; var relpath = /^\./.test(href) ? href : './' + href; var srcpath = resolve.sync(relpath, { basedir : dirname(filepath), extensions : [extname(relpath)] }) var content = read(srcpath); var style = whacko('<style>' + content + '</style>'); style.attr(el.attr()); style.attr('href', null); style.attr('rel', null); el.replaceWith(whacko.html(style)); }) }
javascript
{ "resource": "" }
q36489
minifyHtml
train
function minifyHtml($) { $('style:not([type]), style[type="text/css"]').each(function() { var el = $(this); el.text( new cleancss({noAdvanced: true}).minify(el.text()) ) }); $('*').contents().filter(function(_, node) { if (node.type === 'comment'){ return true; } else if (node.type === 'text') { // return true if the node is only whitespace return !((/\S/).test(node.data)); } }).remove(); }
javascript
{ "resource": "" }
q36490
toJS
train
function toJS(entity) { let data = {}; Object.keys(entity).forEach(key => { if (_.some(customObjects, obj => entity[key] instanceof obj)) { data[key] = toJS(entity[key]) } else { data[key] = entity[key] } }); return data }
javascript
{ "resource": "" }
q36491
ui5Download
train
function ui5Download(sDownloadURL, sDownloadPath, sUI5Version, oOptions = {}) { // check params if (!sDownloadURL) { return Promise.reject('No download URL provided') } if (!sDownloadPath) { return Promise.reject('No download path provided') } if (!sUI5Version) { return Promise.reject('No UI5 version provided') } const oSteps = { download: { number: 1, details: { name: 'download' } }, unzip: { number: 2, details: { name: 'unzip' } } } const iTotalSteps = Object.keys(oSteps).length const sTargetPath = `${sDownloadPath}/${sUI5Version}` const sSuccessMessage = `UI5 download (${sUI5Version}) already exist at ${sDownloadPath}/${sUI5Version}` const fnProgressCallback = typeof oOptions.onProgress === 'function' ? oOptions.onProgress : () => {} // check if ui5 library was already downloaded and ectracted return fs.existsSync(sTargetPath) ? // download is already available Promise.resolve(sSuccessMessage) : // download and unzip sources new Promise((resolve, reject) => { progress( request.get( sDownloadURL, { encoding: null }, (oError, oResponse, oData) => { if (oError) { // reject promise return reject(oError) } // update progress information (start step 2) const oStep = oSteps['unzip'] fnProgressCallback(oStep.number, iTotalSteps, oStep.details) // Do something after request finishes const oBuffer = new Buffer(oData, 'binary') const zip = new Zip(oBuffer) const overwrite = true // extracts everything zip.extractAllTo(sTargetPath, overwrite) // if sap-ui-core.js is not located in extracted root, // we will rename the download directory to 'resources' if (!fs.existsSync(`${sTargetPath}/sap-ui-core.js`)) { // read all extracted files in current directory const aFiles = fs.readdirSync(sTargetPath) aFiles.forEach(sFileName => { if ( fs.statSync(`${sTargetPath}/${sFileName}`).isDirectory() ) { // rename download folder in root try { fs.renameSync( `${sTargetPath}/${sFileName}`, `${sTargetPath}/resources` ) } catch (e) { // skip renaming } } }) } // resolve promise return resolve(`UI5 download successful: ${sTargetPath}`) } ) ).on('progress', oProgressDetails => { // update progress information const oStep = oSteps['download'] fnProgressCallback( oStep.number, iTotalSteps, Object.assign({}, oStep.details, { progress: oProgressDetails.percent * 100 }) ) }) }) }
javascript
{ "resource": "" }
q36492
ui5CompileLessLib
train
function ui5CompileLessLib(oFile) { const sDestDir = path.dirname(oFile.path) const sFileName = oFile.path.split(path.sep).pop() const sLessFileContent = oFile.contents.toString('utf8') // options for less-openui5 const oOptions = { lessInput: sLessFileContent, rootPaths: [sDestDir], rtl: true, parser: { filename: sFileName, paths: [sDestDir] }, compiler: { compress: false } } // build a theme const oBuildThemePromise = builder .build(oOptions) .catch(oError => { // CSS build fails in 99% of all cases, because of a missing .less file // create empty LESS file and try again if build failed // try to parse error message to find out which missing LESS file caused the failed build const sMissingFileName = (oError.message.match( /((\.*?\/?)*\w.*\.\w+)/g ) || [''])[0] const sSourceFileName = oError.filename const sMissingFilePath = path.resolve( sDestDir, sSourceFileName.replace('library.source.less', ''), sMissingFileName ) let isIssueFixed = false // create missing .less file (with empty content), else the library.css can't be created if (!fs.existsSync(sMissingFilePath)) { try { fs.writeFileSync(sMissingFilePath, '') isIssueFixed = true } catch (e) { isIssueFixed = false } } if (!isIssueFixed) { // if this error message raises up, the build failed due to the other 1% cases return Promise.reject('Compile UI5 less lib: ') } // if missing file could be created, try theme build again return isIssueFixed ? ui5CompileLessLib(oFile) : Promise.reject() }) .then(oResult => { // build css content was successfull >> save result const aTargetFiles = [ { path: `${sDestDir}/library.css`, content: oResult.css }, { path: `${sDestDir}/library-RTL.css`, content: oResult.cssRtl }, { path: `${sDestDir}/library-parameters.json`, content: JSON.stringify( oResult.variables, null, oOptions.compiler.compress ? 0 : 4 ) || '' } ] const aWriteFilesPromises = aTargetFiles.map(oFile => { return new Promise((resolve, reject) => fs.writeFile( oFile.path, oFile.content, oError => (oError ? reject() : resolve()) ) ) }) // return promise return Promise.all(aWriteFilesPromises) }) .then(() => { // clear builder cache when finished to cleanup memory builder.clearCache() return Promise.resolve() }) return oBuildThemePromise }
javascript
{ "resource": "" }
q36493
transformPreloadJSON
train
function transformPreloadJSON(oFile) { const oJSONRaw = oFile.contents.toString('utf8') const sPrelaodJSON = `jQuery.sap.registerPreloadedModules(${oJSONRaw});` oFile.contents = new Buffer(sPrelaodJSON) return oFile }
javascript
{ "resource": "" }
q36494
replaceFilePlaceholders
train
function replaceFilePlaceholders(oFile, aReplacementRules) { // parse file const sRaw = oFile.contents.toString('utf8') const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => { return oResult.replace(oRule.identifier, oRule.content) }, sRaw) // update new raw content oFile.contents = new Buffer(sUpdatedFile) // return updated file return oFile }
javascript
{ "resource": "" }
q36495
arrive
train
function arrive(targetVec) { const desiredVelocity = targetVec.clone().subtract(position); desiredVelocity.normalize(); const distanceSq = position.distanceSq(targetVec); if (distanceSq > arriveThresholdSq) { desiredVelocity.scaleBy(maxSpeed); } else { const scalar = maxSpeed * distanceSq / arriveThresholdSq; desiredVelocity.scaleBy(scalar); } const force = desiredVelocity.subtract(velocity); steeringForce.add(force); force.dispose(); return boid; }
javascript
{ "resource": "" }
q36496
wander
train
function wander() { const center = velocity.clone().normalize().scaleBy(wanderDistance); const offset = Vec2.get(); offset.set(wanderAngle, wanderRadius); // offset.length = wanderRadius; // offset.angle = wanderAngle; wanderAngle += Math.random() * wanderRange - wanderRange * 0.5; const force = center.add(offset); steeringForce.add(force); offset.dispose(); force.dispose(); return boid; }
javascript
{ "resource": "" }
q36497
avoid
train
function avoid(obstacles) { for (let i = 0; i < obstacles.length; i++) { const obstacle = obstacles[i]; const heading = velocity.clone().normalize(); // vec between obstacle and boid const difference = obstacle.position.clone().subtract(position); const dotProd = difference.dotProduct(heading); // if obstacle in front of boid if (dotProd > 0) { // vec to represent 'feeler' arm const feeler = heading.clone().scaleBy(avoidDistance); // project difference onto feeler const projection = heading.clone().scaleBy(dotProd); // distance from obstacle to feeler const vecDistance = projection.subtract(difference); const distance = vecDistance.length; // if feeler intersects obstacle (plus buffer), and projection // less than feeler length, will collide if (distance < (obstacle.radius || 0) + avoidBuffer && projection.length < feeler.length) { // calc a force +/- 90 deg from vec to circ const force = heading.clone().scaleBy(maxSpeed); force.angle += difference.sign(velocity) * PI_D2; // scale force by distance (further = smaller force) const dist = projection.length / feeler.length; force.scaleBy(1 - dist); // add to steering force steeringForce.add(force); // braking force - slows boid down so it has time to turn (closer = harder) velocity.scaleBy(dist); force.dispose(); } feeler.dispose(); projection.dispose(); vecDistance.dispose(); } heading.dispose(); difference.dispose(); } return boid; }
javascript
{ "resource": "" }
q36498
followPath
train
function followPath(path, loop) { loop = !!loop; const wayPoint = path[pathIndex]; if (!wayPoint) { pathIndex = 0; return boid; } if (position.distanceSq(wayPoint) < pathThresholdSq) { if (pathIndex >= path.length - 1) { if (loop) { pathIndex = 0; } } else { pathIndex++; } } if (pathIndex >= path.length - 1 && !loop) { arrive(wayPoint); } else { seek(wayPoint); } return boid; }
javascript
{ "resource": "" }
q36499
inSight
train
function inSight(b) { if (position.distanceSq(b.position) > maxDistanceSq) { return false; } const heading = velocity.clone().normalize(); const difference = b.position.clone().subtract(position); const dotProd = difference.dotProduct(heading); heading.dispose(); difference.dispose(); return dotProd >= 0; }
javascript
{ "resource": "" }