query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Split a string of parameters.
function splitParameters(str) { var parameters = str.split(';'); for (var i = 1, j = 0; i < parameters.length; i++) { if (quoteCount(parameters[j]) % 2 == 0) { parameters[++j] = parameters[i]; } else { parameters[j] += ';' + parameters[i]; } } // trim parameters parameters.length = j...
[ "function splitArguments() {\r\n var splitedArray, ii;\r\n if (!arguments[0]) {\r\n throw new WrongArgumentException(\"Can't parse arguments, cause it doesn't exist!\");\r\n }\r\n splitedArray = new Array();\r\n for (ii = 0; ii < arguments[0].length; ii++) {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a New Post event to the Timeline Web API
function sendNewPostEvent(postData) { request.post(TIMELINE_POST_EVENT_URL, { json: postData }) .on('response', function (res) { if (res.statusCode != 200) { console.log("ERROR " + res.statusCode + ": Could not send New Post event!"); res.on('data', fu...
[ "async publishPost () {\n\t\tif (!this.post.get('teamId')) { return; }\n\t\tawait new PostPublisher({\n\t\t\tdata: this.responseData,\n\t\t\trequest: this,\n\t\t\tbroadcaster: this.api.services.broadcaster,\n\t\t\tteamId: this.post.get('teamId')\n\t\t}).publishPost();\n\t}", "function Post(tistoryObj) {\r\n th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles where...(not ) between... clauses.
_handleBetween(field, range, between = true, conj = "and") { if (this._where) this._where += ` ${conj} `; this._where += this.backquote(field) + (between ? "" : " not") + " between ? and ?"; this._bindings = this._bindings.concat(range); return this; }
[ "function addWhereNotsToQuery(query, whereNots, publicToModel) {\n _.each(whereNots, function(value, modelAttr) {\n var column = modelAttr;\n if (publicToModel) {\n column = _publicToColumn(modelAttr, publicToModel);\n }\n\n if (_.isArray(value)) {\n query = quer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to go to linus' twitter
function twitterButton () { window.location.assign('https://twitter.com/linus__torvalds?lang=en') }
[ "function postToTwitter(markovHeadline)\n{\n\tT.post('statuses/update', { status: markovHeadline }, function(err, data, response) {\n\t\tconsole.log(data);\n\t})\n}", "function changeTwitter() {\r\n userConfig.socialMedia.Twitter.searchTerm = $('#TWkwinput').val();\r\n $('#socialMenu .layer[data-layer=' + u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
randomFloat: generate a float random number between 0 and 1
randomFloat(){ return (this.randomUint32())/4294967295. ; }
[ "function getRandomFloat(min, max) {\r\n return Math.random() * (max - min + 1) + min;\r\n}", "function getRandomFloat(min, max)\n{\n return min + Math.random() * (max - min);\n}", "function getRandomFloat(min, max, fix) {\n\treturn ((Math.random() * (max - min)) + min).toFixedNumber(fix)\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a new Border that adheres to a specific height:width ratio. Will optionally ensure dimensions are integers (silly for WebMercator). (Less relevant for Latitude boundaries, since they are not regular).
stretchToMatch(ratio, integer = true) { let width = this.width; let height = this.height; let round = (x) => x; // To get integers, each dimension must at least be divisible by its ratio. if (integer) { round = Math.ceil; width += (ratio.width - width % ratio.width) % ratio.width; ...
[ "multiplyByFloats(w, h) {\n return new Size(this.width * w, this.height * h);\n }", "convert(verticalConversion, horizontalConversion) {\n if (verticalConversion == null) throw Error;\n if (horizontalConversion == null) horizontalConversion = verticalConversion;\n return new Border(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add here runtime validation for the environment file to avoid misconfigurations
function validateEnvFile() { // Validate DEPLOYMENT_PATH const deploymentPath = string('DEPLOYMENT_PATH', ''); const isValidDeploymentPath = deploymentPath === '' || (deploymentPath.charAt(0) === '/' && deploymentPath.charAt(deploymentPath.length - 1) !== '/'); if (!isValidDeploymentPath) { t...
[ "validateEnvironmentNames() {}", "checkEnvironment() {\n if (\n this.system.production &&\n Config.exists(path.join(this.dir, 'config.development.json')) &&\n !Config.exists(path.join(this.dir, 'config.production.json'))\n ) {\n this.ui.log('Running in dev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fixing flexbox gap property missing in some Safari versions
function checkFlexGap() { var flex = document.createElement("div"); flex.style.display = "flex"; flex.style.flexDirection = "column"; flex.style.rowGap = "1px"; flex.appendChild(document.createElement("div")); flex.appendChild(document.createElement("div")); document.body.appendChild(flex); var isSupp...
[ "ensureLineGaps(current) {\n let gaps = [];\n // This won't work at all in predominantly right-to-left text.\n if (this.heightOracle.direction != Direction.LTR)\n return gaps;\n this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a group with the given types. The `id` property of each / type should correspond to its position within the array.
function NodeGroup( /// The node types in this group, by id. types) { this.types = types; for (var i = 0; i < types.length; i++) if (types[i].id != i) throw new RangeError("Node type ids should correspond to array positions when creating a node group"); }
[ "constructor(\n /// The node types in this group, by id.\n types) {\n this.types = types;\n for (let i = 0; i < types.length; i++)\n if (types[i].id != i)\n throw new RangeError(\"Node type ids should correspond to array positions when creating a node group\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 143 Create a function that takes three integer arguments (a, b, c) and returns the number of equal values.
function equal(a, b, c) { let x = 0; for (let i = 0; i < arguments.length; i++) { if (arguments[i] === arguments[i+1] || arguments[i] === arguments[i-1] || arguments[i] === arguments[i+2] || arguments[i] === arguments[i-2]) { x++; } } return x; }
[ "function abcmath(a, b, c) {\n\treturn ((a * b) % c === 0);\n}", "function isWhole(a, b, c, d) {\n return ((a + b + c + d) / 4) % 1 === 0;\n // let avg = sum / arguments.length;\n // return (avg % 1 === 0)\n}", "function solution(number) {\n // set minimum parameter of zero\n let total = 0\n // iter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look at a URL Group to see of there are cases where the response total for a status code is zero. For all such cases found, remove that status code from the 'responses' object of both the URL Group and URLs associated with the URL Group. This should be refactored such that the logic that determines whether to update al...
function removeZeroResponseTotals(urlGroup, numGroup, ofTotalGroups) { var zeroTotalStatusCodes = []; // Array for status codes w/zero total var updatedGroupResponses = {}; // Replacement 'responses' object /* Iterate over the status codes in the URL Group 'responses' object ...
[ "function recalcUrlGroupTotals(urlGroup, numGroup, ofTotalGroups) {\n\n // Query all URLs associated with URL Group in order to get their\n // latest status code response totals\n UrlsByUrlGroup.query({ id: urlGroup._id }, function(urls) {\n\n // Iterate over each URL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : createMapDevToolTip AUTHOR : Apple Kem E. Eguia DATE : March 25, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : PARAMETERS : imgId,act
function createMapToolTip(imgId,act){ var myText = ""; switch(act){ case 'port': var prtArr = new Array(); if(globalInfoType == "JSON"){ var devices = getDevicesNodeJSON(); for(var s=0;s < devices.length; s++){ prtArr = getDeviceChildPort(devices[s],prtArr); } }else...
[ "function showTip(tipId) {\r\n\r\n assert(tipId < TipId.End, \"Invalid TipId\");\r\n\r\n var tip1 = document.getElementById('tipWindow');\r\n var img = \"<HR><img src='images/tip.jpg' width=16px height=16px>\";\r\n tip1.innerHTML = img + TipArr[tipId] + \"<BR><HR>\";\r\n}", "function createDeviceToolt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drag stop handler. Cancels scroll animations and resets state
[onDragStop]() { cancelAnimationFrame(this.scrollAnimationFrame); cancelAnimationFrame(this.findScrollableElementFrame); this.scrollableElement = null; this.scrollAnimationFrame = null; this.findScrollableElementFrame = null; this.currentMousePosition = null; }
[ "function stopDrag(){\n\t detector_container.removeEventListener(\"pressmove\", moveDrag); \n}", "cancelScroll() {\n this._isScrollLocked = false;\n }", "function swipeCancelHandler () {\n\n startCoords = null;\n }", "stopSlideAnimation() {\n if (this.__scrollAnimati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract the body of a function
function _getFunctionBody($function) { with (String($function)) return slice(indexOf("{") + 1, lastIndexOf("}")); }
[ "visitFunction_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function fun(body) {\n return \"async function foo() { \" + body + \" }\";\n}", "visitCreate_function_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parseFunc() {\n var fnName = t.identifier(getUniqueName(\"func\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a payment object.
function paymentFactory() { var payment = { cNumber: "", cType: "", CName: "", cExp: "", cCvv: "" } return payment; }
[ "function serializePayment(payment: Payment): Buffer {\n const toData = payment.to.converseToBuffer();\n const data = Buffer.alloc(8 + toData.length);\n data.writeUInt32LE(payment.amount, 0);\n toData.copy(data, 8);\n return data;\n}", "function paymentFromComponent(req, res, next) {\n const reqDataObj = JS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
12m. Declare a function named randomHexaNumberGenerator. When this function is called it generates and returns a random hexadecimal number. output: console.log(randomHexaNumberGenerator()); 'ee33df' console.log(randomHexaNumberGenerator()); '28def10' console.log(randomHexaNumberGenerator()); '38eeda'
function randomHexNumberGenerator() { return '#' + Math.random().toString(16).substr(2, 6).toUpperCase(); }
[ "function generateHex() {\n return chroma.random();\n\n}", "function getRandomNumber () {\n return String.fromCharCode(Math.floor(Math.random()*26) + 48)\n}", "generateCode() {\n return (Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4) + \"-\" \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
There are situations where we can't just sanitize a filename, because it only contains invalid characters (so sanitization would result in an empty string). As an alternative approach, this funciton will base64 encode the filename and remove any invalid characters (/)
function makeSafeFilename(file) { return sanitize(file) || new Buffer(file).toString('base64').replace(/\//g, ''); }
[ "static sanitizeUssPathForRestCall(ussPath) {\n let sanitizedPath = path.posix.normalize(ussPath);\n if (sanitizedPath.charAt(0) === \"/\") {\n // trim leading slash from unix files - API doesn't like it\n sanitizedPath = sanitizedPath.substring(1);\n }\n return enc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return hour angle of the sun at sunrise in radians for latitude of observer in degrees and declination angle of sun in degrees
function calcHourAngleSunrise(lat, solarDec) { var latRad = degToRad(lat); var sdRad = degToRad(solarDec); var HAarg = (Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sdRad))-Math.tan(latRad) * Math.tan(sdRad)); var HA = (Math.acos(Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sdRad))-Ma...
[ "function calcHourAngleSunset(lat, solarDec) {\n var latRad = degToRad(lat);\n var sdRad = degToRad(solarDec);\n var HAarg = (Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sdRad))-Math.tan(latRad) * Math.tan(sdRad));\n var HA = (Math.acos(Math.cos(degToRad(90.833))/(Math.cos(latRad)*Math.cos(sd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initiate ChatMessage With Parameters Params : languageCode, Chat Step Configuration Message returns : Chat text message
function initiateChatTextMessageWithParameters(languageCode, { message }, otherMessageParam = {}) { localization.setLocale(languageCode || constants.defaultLanguage.isoCode); const { key, params } = message; let mappedParams = []; for (let index = 0; index < params.length; index++) { const para...
[ "function pushMessage(text) {\n if (kony.net.isNetworkAvailable(constants.NETWORK_TYPE_ANY)) {\n kony.application.showLoadingScreen(\"\", \"\", constants.LOADING_SCREEN_POSITION_ONLY_CENTER, true, true, null);\n mobileFabricConfiguration.integrationObj = mobileFabricConfiguration.konysdkObject.getI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function uses current hour to compare against hour dataset value of all text boxes and changes css class appropriately.
function updateTextBoxColors(hour) { for (i = 0; i < $(".text-box").length; i++) { const currentTextBox = $(".text-box")[i]; if (parseInt(currentTextBox.dataset.value) < parseInt(hour)) { currentTextBox.classList.add("past"); currentTextBox.setAttribute("...
[ "function validateHour() {\n $(\".form-control\").each(function (index) {\n const hourTimeBlock = $(this).attr(\"aria-label\");\n const dateTimeBlock = moment(hourTimeBlock, \"ha\");\n const description = localStorage.getItem(hourTimeBlock);\n\n $(this).val(description);\n\n if (!currentDay.isBefore...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function creates a promise that will update the list of file export configs with the generated configID (generated by Connected Vision Server so we need to get it here)
function updateConfigListFileExport() { return Q.Promise(function(resolve, reject) { var url = viewModel.hostUrl() + "FileExport/configList"; logDebug("request config list (" + url + ")"); // get list of all configs running on the Connected Vision Server (all file export configs potentially including file exp...
[ "function afterFileExportConfigsCreated() {\n\treturn Q.Promise(function(resolve, reject) {\n\t\tgetConfigsPreStatus()\n\t\t.then(function(res) {return startFileExportConfigs()})\n\t\t.then(\n\t\t\tfunction () { return Q().delay(5000); } // wait some time - initial wait for 1 second\n\t\t)\n\t\t.then(\n\t\t\tfuncti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the experiment (check for Turk)
function StartExperiment () { if (IsOnTurk() && IsTurkPreview()) { alert("Please accept the HIT before continuing."); return false; } /* Loading totem images */ var loading = document.createElement('div'); loading.innerHTML = "Loading . . ."; loading.id = 'loading'; document.getElementById('wai...
[ "function start() {\n\tgetCurrentPatch()\n\t.then(getChampionIDs)\n\t.then(startScraping)\n\t.then(() => console.log(\"Done scraping.\"))\n\t.catch(function(err) {\n\t\tconsole.log(\"Error on promise chain: \" + err);\n\t\tconsole.log(\"Restarting...\");\n\t\tsleep(30000)\n\t\t.then(start);\n\t});\n}", "async sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read and set mods mods : OBJECT (optional) The mod element gives you control over how the modifier keys react. You can now define the params below for each object in the mods object. [valid, arg, icon, variables]
mods(key, config) { if (key && config) { if (key == "alt") { this._mods.alt = config; let old = this.items(); old[old.length - 1].mods = JSON.parse(JSON.stringify(this._mods)); return this; } else if (key == "cmd") { this._mods.cmd = config; let old = this...
[ "function Modifier(func, type) {\n func.id = guid();\n func.type = type || C.MOD_USER;\n func.$data = null;\n func.$band = func.$band || null; // either band or time is specified\n func.$time = is.defined(func.$time) ? func.$time : null; // either band or time is specified\n func.$easing = func.$e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a channel hash and a set of users, returns a hash for the service response.
function getChannelFromHash(channel_hash, users){ var channel = {}; if(channel_hash !== undefined){ channel = { id: channel_hash.id, name: channel_hash.name, description: channel_hash.description, createdAt: channel_hash.createdAt, ...
[ "hashedCacheKey(address, username, callbackHash) {\n return JSON.stringify([address, username, callbackHash]);\n }", "getIdFromChannel(channelName, callback){\n this.robot.http(`https://api.slack.com/api/users.conversations?token=${this.botToken}&user=${this.botSlackUserId}&types=public_channel,priva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This resets the test database and reseeds it.
function resetTestDatabase() { abortUnlessTest(); const pool = testPool(); return truncate(pool) .then(results => seed(pool)) .then(results => pool.end()) .catch(err => console.log('resetTestDatabase error:', err)); }
[ "resetDatabase() {\n const stmt = this._db.prepare('DROP TABLE redeem')\n stmt.run()\n this.initDatabase()\n }", "function seed() {\n process.env.ENVIRONMENT = 'test';\n const test = require('./config/db');\n const db = require('./db');\n\n return shared.importDB(test, sql_file).then(() => {\n //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the footer cell content using a renderer and then updates the visibility of the parent row depending on whether all its children cells are empty or not.
_renderFooterCellContent(footerRenderer, footerCell) { if (!footerCell || !footerRenderer) { return; } this.__renderCellsContent(footerRenderer, [footerCell]); if (this._grid) { this._grid.__updateHeaderFooterRowVisibility(footerCell.parentElement); } }
[ "_renderBodyCellsContent(renderer, cells) {\n if (!cells || !renderer) {\n return;\n }\n\n this.__renderCellsContent(renderer, cells);\n }", "_defaultFooterRenderer() {}", "render() {\n return (FooterJSX.call(this));\n }", "_renderHeaderCellContent(headerRenderer, headerCell...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As efficiently as possible, decorate the comment object with .precedingNode, .enclosingNode, and/or .followingNode properties, at least one of which is guaranteed to be defined.
function decorateComment(node, comment, lines) { var childNodes = getSortedChildNodes(node, lines); // Time to dust off the old binary search robes and wizard hat. var left = 0, right = childNodes.length; while (left < right) { var middle = (left + right) >> 1; var child = childNodes[mid...
[ "parseComment(tokenizer) {\n const token = tokenizer.advance();\n if (token === null) {\n return null;\n }\n return this.nodeFactory.comment(tokenizer.slice(token), { start: token.start, end: token.end });\n }", "tokenizeComment(offset) {\n const start = offset;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UTILITY: When this function is given 'il' for example, the function will return the socalled "type" of the pronoun which for 'il' is 'il/elle/on' This function is necessary because the database does not know 'il' but does know 'il/elle/on' similarly, the function does not know 'ils' but does know 'ils/elles' If given a...
function getTypeOfPronoun(pronoun){ var ret; _.each(pronouns, function(candidate){ if(_.contains(candidate.split(/\//g), pronoun)){ //splits string by slashes (/) ret = candidate; } }); return ret; }
[ "getTranslationString(type) {\n let userString;\n let tts = this.get('typeToString');\n userString = tts[type];\n\n if (userString === undefined) {\n for (let ts in tts) {\n if (type.toLowerCase().indexOf(ts) !== -1) {\n userString = tts[ts];\n break;\n }\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove file download from queue, delete downloaded file at the same time. fileHash: hash of file to remove from download queue callback: callback when complete
function removeFileDownload(fileHash, callback){ utils.assert(fileHash.length>0 && utils.isFunction(callback)); if(fileHash in fileDownloadStates){ //fileDownloadStates[fileHash]=DownloadState.CANCELED; delete fileDownloadStates[fileHash]; delete fileBlocksDownloadLeft[fileHash]; removeFileDownloadFrom...
[ "function downloadFile(fileHash){\n //unpack the download info\n var downloadInfo=allDownloadInfos[fileHash];\n var fileInfo=downloadInfo['fileInfo'];\n var fileOwners=downloadInfo['fileOwners'];\n var saveDir=downloadInfo['saveDir'];\n var downloadCallback=downloadInfo['downloadCallback'];\n var downloadPro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combined stream of all of the child chips' selection change events.
get chipSelectionChanges() { return this._getChipStream(chip => chip.selectionChange); }
[ "onSelectionChange(cb) {\n this.on('selection-change', cb)\n }", "selectionSetDidChange() {}", "onSelectionChange(func){ return this.eventSelectionChange.register(func); }", "_emitChangeEvent(option) {\n this.selectionChange.emit({\n source: this,\n option: option,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles setting up the device trust.
function handleDeviceTrust() { if (!this.declaration.Common.DeviceTrust) { return Promise.resolve(); } const deviceTrust = this.declaration.Common.DeviceTrust; let deviceInfo; return this.bigIp.deviceInfo() .then((response) => { deviceInfo = response; return...
[ "function handleDeviceTrustAndGroup() {\n const deviceGroups = pullDeviceGroup(this.declaration.Common);\n\n if (this.declaration.Common.DeviceTrust && deviceGroups.length > 0) {\n let convertedAddresses;\n const deviceTrust = this.declaration.Common.DeviceTrust;\n\n let promises = Promis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function that outputs every possible die combination of a 10 sided die when rolled 3 times.
function threeDiceRoll(i, j, k) { var count = 0; for (i = 1; i <= 10; i++) { for (j = 1; j <= 10; j++) { for (k = 1; k <= 10; k++) { console.log(i, j, k); count++; } } } console.log("count: ", count); }
[ "function dices(num, sides) {\n num = parseInt(num);\n sides = parseInt(sides);\n var sum = 0;\n if (num > 0 && sides > 0)\n for (var i = 0; i < num; i++)\n sum += dice(sides);\n else\n sum = 0;\n return sum;\n}", "function thirdRoll() {\r\n\tvar dice3 = [\"crown\", \"an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to print out a single draggable option row.
function tableDragRow(key, value, parent, indent, status) { var output = ''; output += '<tr class="draggable' + (indent > 0 ? ' indented' : '') + '">' output += '<td class="' + (hasDefault ? 'option-default-cell' : 'option-order-cell') + '">'; for (var n = 0; n < indent; n++) { output += Drupal.th...
[ "function generateOptionTable(options) {\n let text = dedent`\\n\n | Name | Type | Description |\n | ---- | ---- | ----------- |\n `;\n\n Object.entries(options).forEach(([option, value]) => {\n if (option.includes('-')) {\n return;\n }\n\n text += `\\n| ${option} | ${makeType(value)} | ${val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
open the playing queue channel
function queueChannel(){ var pushstream = new PushStream({ host: window.location.hostname, port: window.location.port, modes: GUI.mode }); pushstream.onmessage = getPlaylist; // pushstream.onstatuschange = function(status) { // force queue rendering (backend-call) // ...
[ "async processQueue() {\n if (this.queueLock || this.audioPlayer.state.status !== AudioPlayerStatus.Idle || this.queue.length === 0) return;\n this.queueLock = true;\n const nextTrack = this.queue.shift();\n try {\n const resource = await nextTrack.createAudioResource();\n this.audioPlayer.pla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch all notes by subtab id
static async listNotesBySubtab(sub_id, user) { const query = ` SELECT * FROM notes WHERE notes.sub_id = $1 AND notes.user_id = (SELECT id FROM users WHERE email=$2) ORDER BY created_at DESC; ` const result = await db.query(query, [sub_id, user.email]); ...
[ "function getNoteByID(id) {\n let db = note.notes\n for (let i = 0; i < db.length; i++) {\n let nte = db[i]\n if (nte._id == id) {\n return nte\n }\n }\n}", "function newsletterSubModal(obj, ids) {\r\n \tvar s = s_gi(s_account);\r\n \ts.linkTrackVars = 'eVar7,prop9,eVa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses time to find the index
function calcLastUpdateIndex() { var time = new Date(); return getIndexFromTime(time); }
[ "function calculateIndex(time) {\n let data = time.split(\":\");\n let currentTime = parseInt(data[0], 10) * 60 + parseInt(data[1], 10);\n let rangeMinutes = parseInt(process.env.rangeMinutes, 10);\n let timeStart = parseInt(process.env.timeStart, 10);\n return Math.floor((currentTime - timeStart) / rangeMinut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save color where the mouse is clicked in trackColor variable:
function mousePressed() { if (mouseY < dSlider.y) { // if you clicked above the slider, trackColor = video.get(mouseX,mouseY); // get the color you clicked } }
[ "function clickColor(event) {\n const target = event.target;\n selectedColor = target.style.fill;\n}", "function setPixelColor(event) {\n if (event.type === 'click') {\n event.target.style.backgroundColor = 'red';\n } else if (mousingDown) {\n event.target.sty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the fight with the opponent's army squad
fightWith(army) { this.getListOfActiveSquads().forEach((squad) => { if (!army.haveActiveSquads() || !squad.isActive()) { return; } let opponentSquad = army.getOpponent(this.strategy); squad.attack(opponentSquad); }); }
[ "function startBattle() {\n console.log(numBattles);\n if (numBattles < 0) {\n console.log(chalk.yellow(\"VICTORY!\"));\n console.log(player.name + \" moves further into the dungeon...\");\n numBattles++;\n }\n\n // if player hitpoints are less than or equal to 0 (dead), console log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all neighboring points within the distance of the epsilon given.
function RegionQuery(point, epsilon, dataSet) { var neighBourPoints = [] for (var j = 0; j < dataSet.length; j++) { var distance = Math.sqrt(Math.pow(dataSet[j][x] - point[x], 2) + Math.pow(dataSet[j][y] - point[y], 2)); if (distance < epsilon) { neighBourPoints....
[ "function getNeighbors(point){\n\t\treturn NODES.reduce((neighbors, node, i) => {\n\t\t\tlet distance = getDistance(point, node)\n\t\t\tif(distance > 0 && distance <= SETTINGS.NEIGHBORHOOD_RADIUS) neighbors.push(i)\n\t\t\treturn neighbors\n\t\t}, [])\n\t}", "function gatherNeighbors(point, max) {\n var n = []\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
called when you delete a movie to remove it from storage
function deleteMovie() { let movieList = JSON.parse(sessionStorage.getItem("movieList")); for (let i = 0; i < movieList.length; i++) { if (movieList[i].title == this.parentNode.id) { movieList.splice(i, 1); } } sessionStorage.setItem("movieList", JSON.stringify(movieList)); addMovies(); }
[ "removeMovieFromLS(target) {\n const movies = this.getMovieFromLS()\n movies.forEach((movie, index) => {\n if (movie.name === target) {\n movies.splice(index, 1)\n }\n })\n localStorage.setItem('movies', JSON.stringify(movies))\n }", "function de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set default SalesDog bot activity
function defaultActivity() { client.user.setActivity('?sd help', { type: 'Listening' }); }
[ "function resetActivity() {\n displayActivity(MESSAGE);\n }", "function extend() {\n //If the bot hasn't been loaded properly, try again in 1 second(s).\n if (!window.bot) {\n return setTimeout(extend, 1 * 1000);\n }\n\n //Precaution to make sure it is assigned pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch to the last window
static async switchToLastWindow() { const windows = await Browser.driver.getAllWindowHandles(); await Browser.driver.switchTo().window(windows.pop()); }
[ "focusNextWindow () {\n if (this.mailboxesWindow.isFocused()) {\n if (this.contentWindows.length) {\n this.contentWindows[0].focus()\n }\n } else {\n const focusedIndex = this.contentWindows.findIndex((w) => w.isFocused())\n if (focusedIndex === -1 || focusedIndex + 1 >= this.conten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion para remover el evento del teclado
function removerEventoTeclado(){ window.removeEventListener('keydown', eventoTeclado); }
[ "function removerEventos() {\n for (let i = 3; i < 8; i++) {\n div[i].removeEventListener('click', eventoClickDiv)\n }\n }", "function destroy_event() {\n event = null;\n events.pop();\n if (events.length > 0)\n event = events[events.length - 1];\n}", "eraseEvent(state, num) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Once the App is mounted, the API_HOST is fetched. All /api request can now be directed to that host. In this example it's stored on the window object but it might even be cleaner to store this in Redux. (no need to pollute the global object if we don't need to)
componentDidMount() { fetch("/backendapiroute") .then(rsp => rsp.json()) .then(rsp => { window.apiHost = rsp.apiHost; this.setState({ apiHost: rsp.apiHost }); }) .catch(e => console.error("failed to get the api host", e)); }
[ "function computeApiHostname() {\n switch (process.env.CONTEXT) {\n case 'production':\n return process.env.PROD_API;\n case 'branch-deploy':\n case 'deploy-preview': // TODO Find now.sh url for deploy-preview instead of staging API\n return process.env.STAGING_API;\n default:\n return '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
// functions for mainpage // ///////////////////////////// toggle art form
function toggleArtForm() { //Array.prototype can also we written only as [], so it could be [].slice.call...etc Array.prototype.slice .call(art_form_btn.children) .forEach((item) => item.classList.toggle("close")); art_form_wrapper.classList.toggle("show"); }
[ "function flip_edit_main(edit){\n if(edit){\n document.getElementById(\"main_section\").classList.add(\"hidden\");\n document.getElementById(\"edit_section\").classList.remove(\"hidden\");\n }else{\n document.getElementById(\"main_section\").classList.remove(\"hidden\");\n document...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
functions that multiplies 4 values from a grid giving an origin and a direction
function mult(x,y,g, dirx, diry){ let a = x let b = y let res = 1 let index = 0 while(index<4){ res *= parseInt(g[a][b]) a+=dirx b+=diry index+=1 } return res }
[ "multiplyByFloats(x, y, z, w) {\n return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);\n }", "function multiplizieren(a,b) {\r\n return a * b ;\r\n}", "function largestMult(x,y,grid,directions){\n let largest = 0\n directions.forEach((e)=>{\n let localRes = mult(x,y,grid,e[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show accordion and hide other containers in header panel
function ShowAccordion() { // Hide other commands if (dojo.coords("divAppContainer").h > 0) { dojo.replaceClass("divAppContainer", "hideContainerHeight", "showContainerHeight"); dojo.byId('divAppContainer').style.height = '0px'; } if (dojo.coords("divLayerContainer").h > 0) { doj...
[ "function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}", "_collapseHeading(heading) {\n heading.expanded = false;\n }", "_collapsePanel(panel) {\n panel.expanded = false;\n }", "function setupHea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only calls provided 'responseHandler' function if response is ready and not an error
function handleResponse(request, responseHandler) { if (request.readyState == 4 && request.status == 200) { responseHandler(request); } }
[ "function handleResponse(){\n\tif((request.status == 200)&&(request.readyState == 4))\n\t\treDirect(\"usr_home.html\");\n//\telse\n//\t\talert(\"There was an error with the application, please restart the app. Error: \"+request.status);\n}", "function handleXhrError(response, ioArgs) {\n if(response instanceof E...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emits a change event if the selected state of an option changed.
_emitChangeEvent(option) { this.selectionChange.emit(new MatSelectionListChange(this, option)); }
[ "_emitChangeEvent(option) {\n this.selectionChange.emit({\n source: this,\n option: option,\n });\n }", "function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }", "triggerOption(option) {\n if (option && !option.disabled...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
modify info of some area specified by id
async modifyArea() { const id = this.ctx.params.areaId; // area without id attribute const area = this.ctx.request.body; // add attribute id to area area.id = id; if (!await this.service.areas.update(area)) { this.response(403, '...
[ "function gui_removeArea(id) {\n\tif (props[id]) {\n\t\t//shall we leave the last one?\n\t\tvar pprops = props[id].parentNode;\n\t\tpprops.removeChild(props[id]);\n\t\tvar lastid = pprops.lastChild.aid;\n\t\tprops[id] = null;\n\t\ttry {\n\t\t\tgui_row_select(lastid, true);\n\t\t\tmyimgmap.currentid = lastid;\n\t\t}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lee los datos del curso
function leerDatosCurso(curso){ const infoCurso ={ imagen: curso.querySelector('img').src, titulo: curso.querySelector('h4').textContent, precio: curso.querySelector('.precio span').textContent, id: curso.querySelector('a').getAttribute('data-id') } insertarCarrito(infoCurso); ...
[ "function leerDatosCurso (curso) {\n //Crear objeto del curso\n const infoCurso = {\n imagen: curso.querySelector('img').src,\n titulo: curso.querySelector('h4').textContent,\n precio: curso.querySelector('.precio span').textContent,\n id: curso.querySelector('a').getAttribute('data-id')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes X button on a given tab's HTMLRep visible
function addXButtons (tabHTML) { var button = $(tabHTML).find(".geoLingTabButton")[0]; $(button).css("visibility", "visible"); }
[ "click_expertTipsTab(){\n this.expertTipsTab.waitForExist();\n this.expertTipsTab.click();\n }", "get meetingOne_ResultTab_FullReplayButton() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.widget.Button[1]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A property that contains an numeric value. Usually it contains an integer value: p = NumProperty(0); p.inc(); // p() == 1 p.dec(); // p() == 2
function NumProperty(value, reason) { var p = Property({ value: value, reason: reason }); // note, that p.asReadOnly() drops these // two methods which is fine because a read // only property cannot be incremented or // decremented ...
[ "function n(value) {\n this.value = parseFloat(value)\n}", "function createRecordingNumberObject(record, property, side = undefined) {\n return {\n [Symbol.toPrimitive](hint) {\n assert_equals(hint, 'number', `hint for ${property} should be 'number'`);\n if (record.recordAndCheck('tonumber', proper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return target node of an event.
function getTargetNode(event) { if (event.target) { return event.target; } else if (event.srcElement) { return event.srcElement; } else { return null; } }
[ "function getTarget(e)\r\n{\r\n\tvar value;\r\n\tif(checkBrowser() == \"ie\")\r\n\t{\r\n\t\tvalue = window.event.srcElement;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvalue = e.target;\r\n\t}\r\n\treturn value;\r\n}", "function getParent(eventTarget) {\n return isNode(eventTarget) ? eventTarget.parentNode : null;\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send updated bounds back to app. Takes a leaflet event object as input.
function updateBounds(map) { var id = map.getContainer().id; var bounds = map.getBounds(); Shiny.onInputChange(id + '_bounds', { north: bounds.getNorthEast().lat, east: bounds.getNorthEast().lng, south: bounds.getSouthWest().lat, west: bounds.getSouthWest().lng }); Shiny.onI...
[ "onItemBoundsModifiedNotification(bounds) {\n this._setBounds(bounds, false);\n }", "fitBounds() {\n const { map } = this.context\n\n if (this.layer.getBounds) {\n map.fitBounds(this.layer.getBounds(), {\n padding: 40,\n duration: 0,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Author: [M.C] Name: _lvCockpitsSelectionChanged Description: Manages the controls of bottom bar after the selection of an item Params: event selection changed Return:
function _lvCockpitsSelectionChanged(e) { var count = lv_cockpits.winControl.selection.count(); topAppBar.winControl.hide(); // Keep the app bar open after it's shown. //div_cockpits_bottomAppBar.winControl.sticky = true; if (count > 1) { div_cockpits_bottomAppBar.wi...
[ "function FileList::SelectionChanged() \r\n\t\t{\r\n\t\t\tSelChanged();\r\n\t\t}", "function lvCockpitsItemInvoked(e) {\n e.detail.itemPromise.done(function (item) {\n DataExplorer.drawTile(item.data);\n });\n }", "selectionSetDidChange() {}", "onSelectionChange(cb) {\n this.o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call an action. This function will call the action handler corresponding to the given action type, passing along any parameters given.
call(actionType, ...params) { const handler = this.actions.get(actionType); if (!handler) { throw new Error(`A handler for ${actionType} has not been registered`); } return handler(...params); }
[ "action(type, payload) {\n var action;\n if (payload) {\n action = _.extend({}, payload, {actionType: type});\n } else {\n action = {actionType: type};\n }\n debug('Action: ' + type, action);\n this.dispatch(action);\n }", "listenToAction(action, handler, deferExecution) {\n this.l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compacts consecutive buffer nodes into a single node
function compactBuffers(context, node) { var out = [node[0]], memo; for (var i=1, len=node.length; i<len; i++) { var res = dust.filterNode(context, node[i]); if (res) { if (res[0] === 'buffer') { if (memo) { memo[1] += res[1]; } else { memo = res; out.push...
[ "function buffer1(geometry) {\n return geometry.buffer(5000);\n}", "compress(upto) {\n let remap = new BranchRemapping\n let items = [], events = 0\n for (let i = this.items.length - 1; i >= 0; i--) {\n let item = this.items[i]\n if (i >= upto) {\n items.push(item)\n } else if (ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles hover events for ticker mode
function setTickerHover(){ // on hover stop the animation $parent.hover(function() { if(autoPlaying){ base.stopTicker(false); } }, function() { if(autoPlaying){ base.startTicker(false); } }); }
[ "onListItemMouseEnter() {\n // update the state\n this.setState({\n hover: true\n });\n }", "function HotArea1::OnMouseOver(){ hEvent_HotArea_MouseOver( HotArea1 ); }", "onLayerMouseLeave() {}", "_onDashToDockHoverChanged() {\n //Skip if dock is not in dashtodock hover mode\n if (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the height for a vertical tab filler. id return none Compatibility: IE, NS6
function i2uiSetTabFillerHeight(id) { var filler_obj = document.getElementById(id+"_filler"); var tab_table_obj = document.getElementById(id); if (filler_obj != null && tab_table_obj != null) { var container_table_obj = tab_table_obj.parentNode; while (container_table_obj != null) { i...
[ "set requestedHeight(value) {}", "function settaAltezzaRow(total_h) {\n var h = total_h / 2;\n $('.myf-row').height(h);\n}", "resizeTabContents() {\n let change = $(`#pcm-tabbedPandas`).height() - this.tabNavHeight;\n if (change !== 0 && this.tabContentsHeight > 0) { $('#pcm-pandaTabContents .pcm-ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new InlineResponse202.
constructor() { InlineResponse202.initialize(this); }
[ "constructor() { \n \n InlineResponse2001Resources.initialize(this);\n }", "constructor() { \n \n InlineResponse422.initialize(this);\n }", "constructor() { \n \n InlineResponse2001DataDocument.initialize(this);\n }", "function cloneStatus( targetResponse, so...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add fields to 'widget' for the given instr to support the widget just template.
function init_widget_data( req, instr, widget ) { }
[ "function TKR_addMultiFieldValueWidget(\n el, field_id, field_type, opt_validate_1, opt_validate_2) {\n var widget = document.createElement('INPUT');\n widget.name = 'custom_' + field_id;\n if (field_type == 'str') {\n widget.size = 90;\n }\n if (field_type == 'user') {\n widget.style = 'width:12em';\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change a random gene's weight slightly
adjustRandomWeight(){ var i = Math.floor(Math.random() * this.genes.length) //we can only use an available gene if (this.genes[i] != null){ var value = ((Math.random() - 0.5) * 2 / 5) //between -0.2 and 0.2 this.genes[i].weigth += value } else { this.adjustRandomWeight() } }
[ "changeRandomWeight(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null){\n\t\t\tthis.genes[i].weigth = (Math.random() * 2) - 1 //betwenn -1 and 1\n\t\t} else {\n\t\t\tthis.changeRandomWeight()\n\t\t}\n\t}", "function randomWeight...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Status of referral link for player
function updatePlayerRef(){ if(a_playerSnail >= 300){ a_refLink = window.location.protocol + '//' + window.location.host + window.location.pathname + "?ref=" + web3.eth.accounts[0]; playerreflinkdoc.innerHTML = "<br>" + a_refLink; } else { playerreflinkdoc.textContent = "NOT active. You must have at least ...
[ "get_linkState() {\n return this.liveFunc._linkState;\n }", "function updateStatus() {\n\tchrome.extension.sendRequest(\n\t\t\t{type: \"status?\"}\n\t\t, function(response) {\n\t\t\t$(\"ws_status\").textContent=response.ws_status;\n\t\t\t$(\"pn_status\").textContent=response.pn_status;\n\t\t\t});\t\t\n}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A manager for Instagram consumers.
function InstagramConsumerManager() { }
[ "function OAuthManager() {\n}", "function BannerManager(options) {\n this.banners = [];\n this.bannersIndex = [];\n this.server = null;\n this.displayBanner = false;\n this.rotationPeriod = 5000;\n this.carouselInitialised = false;\n \n this.bannerDialog = new BannerDialog();\n}", "fetch() {\n th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The main method providing an entry point for the Appium JAVA REPL scripting capabilities.
function main(repl){ $ = repl; iteration(); locators(); appInfo(); moreinfo(); deviceActions(); }
[ "function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tpr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the integer value of the specified Property from a [[Thing]]. If the Property is not present or its value is not of type integer, returns null. If the Property has multiple integer values, returns one of its values.
function getInteger(thing, property) { internal_throwIfNotThing(thing); const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.integer); if (literalString === null) { return null; } return deserializeInteger(literalString); }
[ "function intCss(elem, prop) {\r\n return parseInt(vendorCss(elem, prop), 10);\r\n}", "function getParamAsInt( name, defaultValue ) {\r\n\r\n // Try to parse the number.\r\n var valueAsInt = ( this.getParam( name, defaultValue || 0 ) * 1 );\r\n\r\n // Check to see if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cal start and end of tithi (len = 12)and karana (len = 6)
function tithi(jd, n1, tzone, len) { var s_t = {}; var flag; var jdt = jd; var knv = Math.floor(((jd - 2415020) / 365.25) * 12.3685); for (var itit = n1; itit < n1 + 2; ++itit) { var aspect = len * itit; // sun n moon in the early tithi flag = 0; if (aspect == 0) { jdt = novolun(jd, knv); ...
[ "function startend(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.startsWith(\"saya\"));\n\tconsole.log(aku.endsWith(\"di\"));\n\t}", "function alignTimeText(hours, mins)\n{ \n let digit_1_px = 12; // pixel amount of digit '1' \n let digit_default_px = 27; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function draw figure corresponding to regret
function draw_regret_graph(data) { var title = "Expected Regret per step" var y_title = "Expected Regret" var String_title = [title, y_title] var mean = data["regret_figure"][0] var std = data["regret_figure"][1] var input_data = {'String_title': String_title, 'mean': mean, 'std': std} draw_...
[ "function draw_accumulated_regret_graph(data) {\n var title = \"Accumulated Regret per step\"\n var y_title = \"Accumulated Regret\"\n var String_title = [title, y_title]\n var mean = data[\"accumulated_regret\"][0]\n var std = data[\"accumulated_regret\"][1]\n var input_data = {'String_title': St...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process deferred read request
readDeferred(request) { const readBuffer = this.s.read(request.length); if (readBuffer) { request.buffer.set(readBuffer, request.offset); request.deferred.resolve(readBuffer.length); this.deferred = null; } else { this.s.once('reada...
[ "function handleRequest() {\n // debugger;\n if (myReq.readyState === XMLHttpRequest.DONE) {\n // debugger;\n // check status here and proceed\n if (myReq.status === 200) {\n // 200 means done and dusted, ready to go with the dataset!\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A component for configuring a subscription field.
function SubscriptionFieldConfig({ field, onMove, onDelete, onChange }) { if (!SUBSCRIPTION_FIELD_TYPES.includes(field.type)) { console.warn(`Invalid field type: ${field.type}`); return <div style={{ display: 'none' }} />; } return ( <div className="activity-subscription-field"> <div className...
[ "PutSubscriberProperty(string, Variant) {\n\n }", "function SubscriptionFilter(props) {\n return __assign({ Type: 'AWS::Logs::SubscriptionFilter' }, props);\n }", "get suburb() {\n return 'input#BillingAddress_Suburb'\n }", "static get pubsub() {\n\t\treturn pubsub;\n\t}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a button used to gather data is pressed, record feature vectors along with class type to arrays.
function dataGatherLoop() { // Only gather data if webcam is on and a relevent button is pressed. if (videoPlaying && gatherDataState !== STOP_DATA_GATHER) { // Ensure tensors are cleaned up. let imageFeatures = calculateFeaturesOnCurrentFrame(); trainingDataInputs.push(imageFeatures); trainingData...
[ "buildFeatureVector() {\n // create empty feature vector\n let featureVector = [];\n // get all partial feature vectors and merge them together\n for (let i in this.nodes) {\n let dataAvailable = this.nodes[i].checkDataAvailability();\n if (dataAvailable == false) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to check if next cell is available (no playground border or snake's tail). It returns boolean value.
function nextCellAvailable() { var cellAvailable = true; var newSnakeCellX = newSnakeCell().x; var newSnakeCellY = newSnakeCell().y; /* Check if there is no border on X-axis. */ if (Math.floor(newSnakeCellX / ($scope.options.cellWidth + $scope.options.cellMargin)) === $scope.maxAvailabeCells.x || n...
[ "isFirstCell(): boolean {\n return this.isFirstRow() && this.isFirstColumn();\n }", "function is_next_to_blank(tile) {\n var isAdjacent = false;\n if (is_below_blank(tile) || is_above_blank(tile) || is_to_the_left_of_blank(tile) || is_to_the_right_of_blank(tile))\n {\n isAdjacent = true;\n }\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw all sub class node of give class node and connect them
function drawSubClassOf(node, classLvl, currentGraph) { var originObj = node.getIntellisenseObj(); var starty = 50; for(var i = classLvl + 1; i < inheritanceClassLvl.length; i++) { var startx = 50; for(var j = 0; j < inheritanceClassLvl[i].length;...
[ "function drawSupClassOf(node, classLvl, currentGraph) {\r\n var obj = node.getIntellisenseObj();\r\n var subNode = node;\r\n for(var superClassObj=get_class_obj(obj.super_classes[0]); superClassObj; superClassObj=get_class_obj(superClassObj.super_classes[0])) {\r\n v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checking isFull or not
isFull() { return this.size == this.maxSize; }
[ "isFull() {\r\n\t\treturn (this.emptyCells.size() == 0);\r\n\t}", "function checkLoad() {\n if (elevator.loadFactor() < maxLoad && elevator.maxPassengerCount() <= 5) {\n var elevatorFull = false;\n } else if (elevator.loadFactor() < maxLargeLoad && elevator.maxPassengerCount() > 5) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper method used to set up a joke. Selects a random knockknock joke from the jokes object and adds the stages of the joke to the conversationBacklog.
function setupJoke() { randomKnockKnockJoke().forEach( stageOfJoke => { conversationBacklog.push(stageOfJoke) }) }
[ "function generateJoke() {\n\t\t\t\trand = Math.floor(Math.random() * qty) + 1;\n\t\t\t\t$slip.find('.q').html( data[rand].q);\n\t\t\t\t$slip.find('.a').html( data[rand].a);\n\t\t\t}", "SET_JOKES (state, payload) {\n state.jokes = payload\n }", "function chuckJoke() {\n axios.get('https://api.icndb.com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the given SemVer diff is a major diff, i.e. "major" or "premajor".
function isMajorSemverDiff(diff) { return diff.includes(SemverReleaseTypes.Major); }
[ "function majorComparator(student1, student2) {\n if (student1.major.toLowerCase() > student2.major.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n}", "function compareSemVer(version, minimum) {\n version = parseSemVer(version);\n minimum = parseSemVer(minimum);\n\n var ve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ CRUDProcessor processes response data and errors returned by CRUDController / and produces content and or error object(s). Returned objects are consumed / by other components for further processing. For example, views utilize objects / for presentation. Usually a CRUDProcessor deals with a CRUDController, / a CRUDSou...
function CRUDProcessor(options) { var instance = this; /// <summary>Key is a unique identifier to differentiate between CRUDProcessor.</summary> instance.Key = options !== undefined ? options.key : null; /// <summary>CRUDController resposible for extracting response objects.</summary> inst...
[ "function createContent() {\n var objData = _buildDataObject();\n\n return CioContentService.createContent(objData,\n function(objErr, objResult, objPendingEvent) {\n\n if (objErr) {\n // do something\n }\n if (objPendingEvent) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push All Food Data to Firebase Database
function pushFood(){ for(var i = 0; i < data.length; i++){ nutrifit_db_food.push(data[i]); } }
[ "function storeTrainInfo() {\n database.ref(\"/trainData\").push({\n trainName: trainName\n ,destination: destination\n ,firstTrain: firstTrain\n ,frequency: freq\n })\n}", "function insertAll(foods) {\n return Food.create(foods)\n}", "function addVisitedRestaurant(name, date, cuisine, city) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
25.Write a function called clamp, which accepts three parameters: a number, a lower bound, and an upper bound. The function should return the number if it is in between the lower and upper bounds. Otherwise, the function should return lower if number is less than lower, or upper if number is greater than upper.
function clamp(num, lower, upper){ if (num >= lower && num <= upper) return num; else if (num < lower) return lower; else return upper; }
[ "clamp(number, lower, upper) {\r\n /* Initial version\r\n var leftBoundry = Math.max(number, lower);\r\n var clampedValue = Math.min(leftBoundry, upper);\r\n return clampedValue;\r\n */\r\n\r\n // Improved/Consise final version below\r\n return Math.min(Math.max(number, lower), upper);\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a timeout error if no response is received within a given amount of time
function throwTimeout() { if(!responseReceived) { throwError("The request timed out."); } }
[ "static makeTimeoutError() {\n const timeoutErr = new TypeError(HttpClient.TIMEOUT_ERROR_CODE);\n timeoutErr.code = HttpClient.TIMEOUT_ERROR_CODE;\n return timeoutErr;\n }", "function haltOnTimeout(req, res, next) {\n if (!req.timedout) {\n next();\n }\n}", "function timeout(sec) {\n return new ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function that replaces `stopImmediatePropagation_` for events.
function stopImmediatePropagation_() { var event = this; // eslint-disable-line event.stopped = true; event.stoppedImmediate = true; Event.prototype.stopImmediatePropagation.call(event); }
[ "function stopPropagationWrapper(fn) {\n return function(e) {\n if (e && e.stopPropagation) {\n e.stopPropagation();\n }\n fn.apply(this, arguments);\n };\n }", "function cancelbubbling(e) {\n Event.stop(e);\n }", "function cancelBubble(event) {\r\n\r\n if (event.stop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes a gif object, adds/removes it to/from favorited array and replaces localStorage if favorite is TRUE > add to local storage and state, if FALSE > remove
addOrRemoveFavorite(gifObj, favorite) { const newGif = {}; newGif[gifObj.id] = gifObj; let newFavorites; if (favorite) { newFavorites = { ...this.state.favoritedGifs, ...newGif }; this.setState({ favoritedGifs: newFavorites }); localStorage.setItem('favorites', JSON.stringify(newFavor...
[ "function removeFavourite(obj) {\n\tconst newFavArray = favArray.filter((item) => item.gif !== obj.gif);\n\tfavArray = [...newFavArray];\n\tlocalStorage.setItem(\"favourites\", JSON.stringify(favArray));\n\tlet isFavHidden = $favouriteSection.classList.contains(\"hidden\");\n\tif (!isFavHidden) {\n\t\t$maxGifSectio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set property type of numeric schema properties
function numericType (node, schema) { let type = node.value.type if (type === 'integer' || type === 'number') { schema.type = type } }
[ "function number() {\n return utils_1.createSymmetricSchema({\n type: 'number',\n validate: utils_1.toValidator(utils_1.isNumericString),\n map: utils_1.coerceNumericStringToNumber,\n });\n}", "enterNumericType(ctx) {\n\t}", "set_col(col, type) {\n this.df = this.df.map(x => {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds define as a global (potentially just temporarily)
function createDefine() { // ensure no NodeJS environment detection var oldModule = __global.module; var oldExports = __global.exports; var oldDefine = __global.define; __global.module = undefined; __global.exports = undefined; __global.define = define; return function(...
[ "function parseGlobal() {\n var name = t.identifier(getUniqueName(\"global\"));\n var type; // Keep informations in case of a shorthand import\n\n var importing = null;\n maybeIgnoreComment();\n\n if (token.type === _tokenizer.tokens.identifier) {\n name = identifierFromToken(token);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
capitalizer() takes a string, returns the string with all vowels capitalized
capitalizer(str) { return str.replace(/[aeiou]/g, char => char.toUpperCase()); }
[ "function capVowels(string) {\n var vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n var letters = string.toLowerCase().split(\"\");\n\n for (var i = 0; i < letters.length; i += 1) {\n var letter = letters[i];\n\n if (vowels.indexOf(letter) !== -1) {\n letters[i] = letter.toUpperCase();\n }\n }\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executed whenever any watched file changes. The task key matching the file that just changed is pushed onto a queue for debounced execution. The debouncing is necessary to avoid duplicate task execution and Karma crashes (see [TRFS38]( When a TypeScript source file is removed, delete its matching JavaScript file.
function handleFileEvent(touchedFile) { queue.push(_.find(sourceGlobs, _.partial(paths.match, touchedFile))); switch (touchedFile.event) { case 'add': case 'change': break; case 'unlink': deleteJSFile(touchedFile); break; default: ...
[ "function watchFiles() {\n watch('source/*.*', build);\n}", "function watchTask() {\n // watch(\n // [files.cssPath, files.jsPath, files.imgPath],\n // parallel(cssTask, jsTask, imgSquash)\n // );\n watch([files.cssPath, files.jsPath], parallel(cssTask, jsTask));\n}", "watch (fileChanged) {\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback that creates and populates a data table, instantiates the pie chart, passes in the data and draws it.
function drawChart() { // Create the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices'); data.addRows(chartData); // Set chart options var options = {'title':'Daily S...
[ "function drawPie(data){\n\t\tvar dataGender = new google.visualization.DataTable();\n\t\tdataGender.addColumn('string', 'Gender');\n\t\tdataGender.addColumn('number', 'Count');\n\t\tvar male = 0, female = 0;\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tif(data[i].gender == \"Male\"){\n\t\t\t\tmale++;\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
quickFetch Syntax: quickFetch(url, function(data))
function quickFetch(url, func, param){ fetch(url) .then(function(response){ if (response.status !== 200){ console.log('There was an error with your fetch. Response was not 200.') } return response.json() }) .then(function(data){ param = data; func(param) }) }
[ "async function fetchData() {\r\n await fetch(\"monLien\");\r\n // attend que le await soit exécuté avant sz faire la suite\r\n executeFonction();\r\n}", "function ajax(url) {\n fetch(url)\n .then(data => data.json())\n .then(data => dataGen.next(data)) // whatever we pass in next will be stor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If participant, goes to participant/participant. Otherwise checks if admin, then goes to admin/admin. Otherwise, gives error that you're not logged in.
function goHome() { let participant = JSON.parse(localStorage.getItem("participant")); if (participant !== null) { window.location.href = "../participant/participant.html?id=" + participant.id; } else { let admin = JSON.parse(localStorage.getItem("admin")); if (admin !== null) { ...
[ "rerouteIfPossible() {\n if (Meteor.user() && Meteor.user().username == this.username)\n Router.go(\"myprofileHead\");\n }", "function isLoggedInADMIN(req, res, next) {\n if (req.isAuthenticated())\n\t{\n\t\tif(req.user['local']['role'] == 'admin')\n\t\t\treturn next();\n\t\telse\n\t\t\tres.redirect('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A download progress event.
function HttpDownloadProgressEvent() { }
[ "function onProgress(e) {\n if (video.buffered.length > 0)\n {\n var end = video.buffered.end(0),\n start = video.buffered.start(0);\n load_bar.setAttribute(\"width\", Math.ceil((end - start) / video.duration * 100).toString());\n }\n}", "setupDownloadingUI() {\n this.downloadStatus = document....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the html source for the local Oauth2 redirect page
function getOauth2RedirectHTML() { return ` <!doctype html> <html lang="en"> <body onload="process()"> </body> </html> <script> \'use strict\'; function process () { var sentState = undefined; var redirectUrl = [...
[ "async getRedirectUrl() {\n return new Promise(async resolve => {\n const random = crypto.randomBytes(4).toString(\"hex\");\n this.states = [...this.states, random];\n\n const redirectUrl = `https://oauth.opskins.com/v1/authorize?state=${random}&client_id=${\n this.clientId\n }&respons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
any atom at all may want WaitForNewRootAtom (completed) WaitForNewMdat (ie, new chunks of real parsed data)
async WaitForNextAtom() { return this.NewAtomQueue.WaitForNext(); }
[ "async DecodeChildAtoms()\n\t{\n\t\tconst Reader = new AtomDataReader(this.Data,this.DataFilePosition);\n\t\twhile ( Reader.FilePosition < this.Data.length )\n\t\t{\n\t\t\tconst Atom = await Reader.ReadNextAtom();\n\t\t\tthis.ChildAtoms.push(Atom);\n\t\t}\n\t}", "async function fillRoot() {\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates worldTransform vertices, store it in vertexData
calculateVertices() { if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { return; } this._transformID = this.transform._worldID; this._textureID = this._texture._updateID; // set the vertex data co...
[ "vertexToGeometry () {\n\n let prim = this.prim;\n\n let geo = this.geo; \n\n console.log( 'Mesh::vertexToGeometry()' );\n\n let vertexArr = this.vertexArr;\n\n let numVertices = vertexArr.length;\n\n let indexArr = this.indexArr;\n\n // index array doesn't need to b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invokes the method by passing modulename, version, methodname and callback (if needed)
function invoke(modulename, version, methodname, param, callback) { var moduleObject = getModuleByVersion(modulename, version); if (typeof callback === 'function') { if (moduleObject[methodname]) { moduleObject[methodname](param, callback); } else { console.log("m...
[ "fire(name, ...args) {\n if (this._cb.hasOwnProperty(name)) {\n this._cb[name](...args);\n }\n }", "function callOpcuaMethod(nodeId, args, callback){\n var methodCallRequest = {\n\tobjectId: \"ns=1;i=1000\", // Node ID of the robot arm\n\tmethodId: nodeId,\n\tinputArguments: args\n };\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======================================================================== OTHER FUNCTIONS ======================================================================== function to localize where messages are sent Options: 1 = console.log (default) 2 = alert() 3 = both (console.log then alert)
function message(text, option) { if (!text) return; else { if (option === 1) { console.log(text); } else if (option === 2) { alert(text); } else if (option === 3) { console.log(text); alert(text); } else { // default message method - no valid 'option' specified console.log(text); } } }
[ "function message(str)\n{\n if(debug)\n {\n ///Rob Chadwick - 6/1/12 - Fixed bug where console.log is sometimes not available\n ///happens in IE 8 and 9\n if(output && output.log) \n output.log(str);\n }\n}", "function KLogger(options) {\r\n\t\r\n\tvar Level = KLogger.Level;\r\n\t\r\n\topti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a webdriver object using the Q promise wrap not chained
function promiseRemote() { const args = arguments.length >= 1 ? __slice.call(arguments, 0) : []; const rwc = parseRemoteWdConfig(args); return new PromiseWebdriver(rwc); }
[ "function promiseChainRemote() {\n const args = arguments.length >= 1 ? __slice.call(arguments, 0) : [];\n const rwc = parseRemoteWdConfig(args);\n return new PromiseChainWebdriver(rwc);\n}", "function remote() {\n const args = arguments.length >= 1 ? __slice.call(arguments, 0) : [];\n const driverProtos = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that the clientX and clientY we get from touch events respect the current zoom level. Makes it possible for draggables to accurately track touch events.
function patchTouchEvents() { var originalTouchEvent = Events.touchEvent; Events.touchEvent = function(event) { var e = originalTouchEvent(event); var zoomFactorFromScale = scale * (screenWidth/contentWidth), clientX = e.clientX / zoomFactorFromScale, clientY = e.clientY / zoomFa...
[ "initializeZoomer() {\n this.canvasRect = this.canvas.getBoundingClientRect();\n this.originX = 0; // the X origin of the canvas\n this.originY = 0; // the Y origin of the canvas\n this.image_left = 0; // the left position of the drawn image\n this.image...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Language: ERB (Embedded Ruby) Requires: xml.js, ruby.js
function erb(hljs) { return { name: 'ERB', subLanguage: 'xml', contains: [ hljs.COMMENT('<%#', '%>'), { begin: '<%[%=-]?', end: '[%-]?%>', subLanguage: 'ruby', excludeBegin: true, excludeEnd: true } ] }; }
[ "function ruby(hljs) {\n const RUBY_METHOD_RE = '([a-zA-Z_]\\\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\\\*\\\\*|[-/+%^&*~`|]|\\\\[\\\\]=?)';\n const RUBY_KEYWORDS = {\n keyword:\n 'and then defined module in return redo if BEGIN retry end for self when ' +\n 'next until do begin unless END rescue ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback function for 'ul' arrive.js watcher
function navListArrived() { // Test if the sidebar-nav-list has been created if (this.classList.contains("sidebar-nav-list")) { document.unbindArrive(navListArrived); // unbind the arrive.js watcher console.log("[DeezerSidebarArtists] nav-list arrived!"); console.log(this); sideb...
[ "function watchOptionList (listName, callBack, conditionFunc) {\n if (!directory.hasOwnProperty(listName)) {\n $log.error('No known option list with name: ', listName);\n return;\n }\n\n directory[listName].watcher.add(callBack, conditionFunc);\n }", "function sf_list_up(){\n\t\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }