query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Handles the user clicking the image controls menu save button.
function imageControlsSaveClick() { Settings.Filters.Brightness = Data.Controls.Brightness.value; Settings.Filters.Contrast = Data.Controls.Contrast.value; Settings.Filters.Hue = Data.Controls.Hue.value; Settings.Filters.Saturation = Data.Controls.Saturation.value; saveSettings(); Data.Controls.Open = fal...
[ "function menuSaveClick() {\n requestSave();\n}", "function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}", "function save() {\n dialogOut.dialog( \"close\" );\n }", "function check_set_save_inspirations(current_img_id,save_img_btn) {\n $.post(RELATIVE_PAT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic validation of the actions's structure: It should have an intent, an array of dependencies and notions
validate () { if (typeof this.intent !== 'string') { return false } if (!Array.isArray(this.dependencies) || !Array.isArray(this.notions)) { return false } const dependenciesValidity = this.dependencies.every(dep => { if (typeof dep.isMissing !== 'object') { return false ...
[ "dependenciesAreComplete (actions, conversation) {\n return this.dependencies.every(dependency => dependency.actions.some(a => {\n const requiredAction = actions[a]\n if (!requiredAction) {\n throw new Error(`Action ${a} not found`)\n }\n return requiredAction.isDone(conversation)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a number to the list of allowed numbers Should not have any duplicates in allowedNums
addAllowedNum(num) { if (!this.allowedNums.has(num)) { this.allowedNums.add(num); return `${num} added to allowedNums`; } else { return `${num} already in allowedNums`; } }
[ "function addGuess(num) {\n guesses.push(num);\n }", "function roboNumbers(number) {\n const numbersArray = [];\n for(let i = 0; i <= number; i++){\n if (checkIfContains3(i)){\n numbersArray.push(\"Won't you be my neighbor?\");\n } else if(checkIfContains2(i)) {\n numbersArray.push(\"Boop!\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the headless horseman property for an object, creating it first, if necessary.
function getHH(obj) { if (!obj.hasOwnProperty(_HH_PROPERTY)) { obj[_HH_PROPERTY] = {}; } return obj[_HH_PROPERTY]; }
[ "_firstHeading() {\n const headings = this._allHeadings();\n return headings[0];\n }", "function objOrCreate(obj, prop) {\n\tif (!obj.hasOwnProperty(prop)) {\n\t\tobj[prop] = {};\n\t}\n\treturn obj[prop];\n}", "function randomProperty (obj, random) {\n\t\t\tvar keys = Object.keys(obj);\n\t\t\tretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to load grid when exiting from attack room
function loadGrid() { attRoom = -1; document.removeEventListener('keyup',moveAttPlayer); $.post("ajax/setAttackPlayer.php", { id: teamId, room: '-1', row: '0', col: '0' }, function(data,status){} ); $('#attackTitle').text('Attack player: Grid'); $('#attackBox').load('grid.php'); ...
[ "function loadGrid(roster, seed, classType) {\n\tvar sessionRoster = JSON.parse(sessionStorage.getItem('roster'));\n\tvar sessionClass = JSON.parse(sessionStorage.getItem('classroom'));\n\tvar sessionSeat = JSON.parse(sessionStorage.getItem('seats'))\n\tgrid = JSON.parse(sessionStorage.getItem('finalGridContainer')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use potions as neccesary
function UsePotion() { if (currentTime<parent.next_pot) return false; // default health potions heal 200 if (character.hp < 100) { parent.use('hp'); Sleep(UsePotion, 500); } else if (character.mp < 100) { parent.use('mp'); Sleep(UsePotion, 500); } else if (character.max_hp - character.hp > 20...
[ "function buy_potions()\n{\n\tvar potionTypes = [\"hpot0\", \"mpot0\"];\n\tvar purchaseAmount = 50;\n\n\tif(empty_slots() > 0)\n\t{\n\t\tfor(typeID in potionTypes)\n\t\t{\n\t\t\tvar type = potionTypes[typeID];\n\t\t\t\n\t\t\tvar item_def = parent.G.items[type];\n\t\t\t\n\t\t\tif(item_def != null)\n\t\t\t{\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the sum of the chip counts and counts the number of splitting players then calculates the split percentage each player gets.
function setSplits(pay_3, pay_2, pay_1) { var check_box = document.getElementsByName('splits[]'); var chip_count = document.getElementsByName('chipcounts[]'); var original_splits = document.getElementsByName('original_splits[]'); var split_count = 0; var chip_count_value = 0; var preceeding_chip_count = 0; var c...
[ "calculatePercentage(player) {\n\t\t\tplayer.percentage = (parseFloat(player.wins) / parseFloat(player.games)).toFixed(3);\n\t\t}", "function getTotalScore() {\n\n let ai = 0;\n let human = 0;\n\n //Calculate pawn penalties\n //Number of pawns in each file\n let human_pawns = [];\n let ai_pawns ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close this handle. NOTE: After closing the handle, it must not be used anymore. Doing so will throw an error. Official libcurl documentation: [`curl_easy_cleanup()`](
close() { curlInstanceMap.delete(this.handle); this.removeAllListeners(); if (this.handle.isInsideMultiHandle) { multiHandle.removeHandle(this.handle); } this.handle.setOpt(Curl.option.WRITEFUNCTION, null); this.handle.setOpt(Curl.option.HEADERFUNCTION, null);...
[ "close() {\r\n // clear recorder cache\r\n return new Promise((resolve, reject) => {\r\n if (this.httpProxyServer) {\r\n // destroy conns & cltSockets when closing proxy server\r\n for (const connItem of this.requestHandler.conns) {\r\n const key = connItem[0];\r\n const c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
total is equal to experience. To reach the next level your XP should be at least at threshold. If you kill the monster in front of you, you will gain more experience points in the amount of the reward.
function reachNextLevel(experience, threshold, reward) { return experience + reward >= threshold; }
[ "getTotalXpForLevel(player, level) {\n return this.xpTable[level]\n }", "damage(damagePoints){\n this.hp -= damagePoints\n return damagePoints\n }", "checkTotal(hand){\n if(hand.total >= 10){\n hand.total -= 10;\n }\n }", "getTnl(player) {\n const requiredXp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests removing a root.
function testRemoveRoot() { delegate.addRoot(document.body); delegate.registerHandlers({ 'mousedown .foo': f1, 'mousemove .quix': f2 }, {}); delegate.removeRoot(document.body); el1.dispatchEvent(createMouseEvent('mousedown')); el2.dispatchEvent(createMouseEvent('mousemove')); thermo.scheduler....
[ "delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a promise to get all inview features across all viewports. Used for group autoscaling.
async getInViewFeatures() { if (!(this.browser && this.browser.referenceFrameList)) { return [] } let allFeatures = [] const visibleViewports = this.viewports.filter(viewport => viewport.isVisible()) for (let vp of visibleViewports) { const referenceFra...
[ "function getFeatures() {\n // set up query\n var q = new Query();\n // only within extent\n q.geometry = map.extent;\n q.returnGeometry = true;\n q.outFields = [\"*\"];\n \n // give me all of them!\n q.where = \"1=1\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts list of objects containing a numeric values, given a valuekey
function numericListSort(listitems, valuekey) { listitems.sort(function(a, b) { var compA = parseFloat(a[valuekey]); var compB = parseFloat(b[valuekey]); return (compA > compB) ? -1 : (compA <= compB) ? 1 : 0; }) return listitems; }
[ "function numericLengthSort(listitems, valuekey) {\n listitems.sort(function(a, b) {\n var compA = a[valuekey].length;\n var compB = b[valuekey].length;\n return (compA > compB) ? -1 : (compA <= compB) ? 1 : 0;\n })\n return listitems;\n}", "function sortArrayOfObjects (arr, key) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the effective permissions for the current user
async function getCurrentUserEffectivePermissions() { return SPQueryable(this, "EffectiveBasePermissions")(); }
[ "get effectiveBasePermissionsForUI() {\n return SPQueryable(this, \"EffectiveBasePermissionsForUI\");\n }", "get effectiveBasePermissions() {\n return SPQueryable(this, \"EffectiveBasePermissions\");\n }", "async function getPermissionsFor (acl, user, req) {\n const accesses = MODES.map(mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fungsi untuk cloud mask dari band Fmask data Landsat 8 SR.
function maskL8sr(image) { // Bit 3 dan 5 masing-masing adalah cloud shadow dan cloud. var cloudShadowBitMask = ee.Number(2).pow(3).int(); var cloudsBitMask = ee.Number(2).pow(5).int(); // Dapatkan band pixel QA (Quality Assessment) // Landsat 8 SR mempunyai sr_aerosol band, pixel_qa band, d...
[ "function fMask(img){\n var fmsk = img.select('cfmask');\n var cloudAndShadow = fmsk.eq(2).or(fmsk.eq(4)).eq(0);\n return img.updateMask(img.mask().and(cloudAndShadow));\n}", "function computeSlopeMask(threshold) {\n var minWaterMask = mndwiMax.gt(ndwiMinWater) // maximum looks like water\n var maxLandMa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET PENCIL SHADE, A RETANGLE PATH
function getPencilHolderShade(x,y,w,h){ var result="M"+x+" "+y+","; result=result+"L"+(x+w)+" "+y+","; result=result+"L"+(x+w)+" "+(y+h)+","; result=result+"L"+x+" "+(y+h)+","; result=result+"Z"; return result; }
[ "function getPencilHead(x,y,s){\n\tvar result=\"M\"+(x+s)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s/6)+\",\";\n\tresult=result+\"S\"+(x-s/3)+\" \"+(y+s/2)+\" \"+(x+s/3)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s)+\",\";\n\tresult=res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that we fail gracefully if we try to attach() a on a newwindow event after the opener has been destroyed.
function testNewWindowAttachAfterOpenerDestroyed() { var testName = 'testNewWindowAttachAfterOpenerDestroyed'; var webview = embedder.setUpGuest_('foobar'); var onNewWindow = function(e) { embedder.assertCorrectEvent_(e, ''); // Remove the opener. webview.parentNode.removeChild(webview); // Pass...
[ "function testNewWindowDiscardAfterOpenerDestroyed() {\n var testName = 'testNewWindowDiscardAfterOpenerDestroyed';\n var webview = embedder.setUpGuest_('foobar');\n\n var onNewWindow = function(e) {\n embedder.assertCorrectEvent_(e, '');\n\n // Remove the opener.\n webview.parentNode.removeChild(webvie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: onRead( error, actual ) Read event handler. Checks for errors and compares streamed data to expected data.
function onRead( error, actual ) { expect( error ).to.not.exist; assert.strictEqual( actual[ 0 ], 2 ); done(); }
[ "checkPendingReads() {\n this.fillBuffer();\n\n let reads = this.pendingReads;\n while (reads.length && this.dataAvailable &&\n reads[0].length <= this.dataAvailable) {\n let pending = this.pendingReads.shift();\n\n let length = pending.length || this.dataAvailable;\n\n let result;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only the keys data contains person > person relationships (supervisor > keyholder)
function findSupervisorEdges ( personCollection, supervisorPersonEdges, keysData ) { return Promise.each(keysData, function (row, i) { let keyholder = { name: row['FIRST'] + ' ' + row['LAST NAME'] } if (row['SUPERVISOR'] && row['SUPERVISOR'].trim().length > 0) { let supervisor = row['SUPERVISOR']....
[ "function findKeysDataRoomPersonEdges (\n roomCollection,\n personCollection,\n roomKeyholderEdges,\n keysData\n) {\n return Promise.each(keysData, function (row, i) {\n let room = { name: row['BUILDING'] + ' ' + row['ROOM NUMBER'] }\n let keyholder = { name: row['FIRST'] + ' ' + row['LAST NAME'] }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NEXT PROBLEM / As of this point you should have a makePerson and a makeCard function which returns you either a person or a credit card object. Now, create a bindCard function that takes in a person object as its first parameter and a creditcard object as its second parameter. Have bindCard merge the two parameters tog...
function bindCard(person, creditcard) { var both = {} for(var key in person){ both[key] = person[key]; for (var key in creditcard){ both[key] = creditcard[key]; } } return both; }
[ "function bindCard(personObj, creditcardObj) {\n let combinedObj = {};\n combinedObj = Object.assign(combinedObj, personObj, creditcardObj)\n return combinedObj;\n }", "function makeCard(cardNumber, expirationDate, securityCode) {\n var card = {\n cardNumber: cardNumber,\n expirationDate: e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to open and close the portfolio section slider
function portfolioSlider() { $('#portfolio .section-title').click(function(e) { e.preventDefault(); $('#portfolio-section-slider').slideToggle(300); }); $('.portfolio-link').click(function(e) { e.preventDefault(); $('#portfolio-section-slider').slideToggle(300); }); }
[ "function hideSliders() {\r\n $('#about-section-slider, #portfolio-section-slider').hide();\r\n}", "function exitSlider () {\nmainWrapper.style.display = 'none';\n}", "function CloseSilder(){\n modelBG.style.display = \"none\";\n modelSlider.style.display = \"none\";\n }", "function setupPor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that displays the information on nodes
function display_nodes_info( node ) { while( node != null ) { console.log( "Data : ",node.data ) node = node.next } }
[ "printNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n document.writeln(this.nodes[layer][node].number + \" | \");\n }\n document.writeln(\"</br>\");\n }\n document.writeln(\n \"---------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserautogenerated_sequence_definition.
visitAutogenerated_sequence_definition(ctx) { return this.visitChildren(ctx); }
[ "visitCreate_sequence(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAlter_sequence(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "_generate(ast) {}", "visitSequence_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether this content has any settings.
get hasSettings() { return !!this.settings.findSetting(() => true); }
[ "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}", "any() {\n return Object.keys(this.datos).length > 0;\n }", "hasLoadedAnyDataFiles() {\n return this.loadedDataFiles.length > 0;\n }", "isEmpty() {\n return (this.queue.length == 0);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
post username and passwword to api to signin
function signin(){ var payload = { "username": username.value, "password": password.value }; send_post_request(window.location.origin + '/api/rest-auth/login/', payload, function (data, status){ if (status == 200 || status == 201){ signin_message.innerHTML = "Welcome, "...
[ "login(username, password) {\r\n return this._call(\"post\", \"login\", { username, password });\r\n }", "login (email, password) {\n assert.equal(typeof email, 'string', 'email must be string')\n assert.equal(typeof password, 'string', 'password must be string')\n const ctx = this\n return this._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
using promises I first find a user and get their votes array and add the newst vote in after, I update the db entry with new array of votes
function usersUpdate(req, res) { User.findOne({username: req.body.username}).exec() .then( user => { if (!user) return res.status(404).json({ message: 'User not found.'}); updateCandidate(req); user.votes.push(req.body.votes); return user; }) .then(user => { User.findOneAndUp...
[ "function vote() {\n for (party in total_votes_per_party) {\n if (total_votes_per_party[party] > 0) {\n // Calculate the increment for this party\n var increment = Math.round(multiplier * Math.random());\n // Vote and then remove those votes from the counters\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a TG products array and extracts all the product IDs and returns them in an array
async function _extract_variant_ids (products){ if (products.length == 0 || typeof products === 'undefined' || products === null || !Array.isArray(products)){ throw new VError(`products parameter not usable`); } let ids = []; for (let i = 0; i < products.length; i++){ ids = ids.concat(products[i].var...
[ "async function _extract_related_product_variant_ids (products, line_item_variants){\n let all_product_variants = [];\n \n for (let i = 0; i < products.length; i++){\n for (let j = 0; j < line_item_variants.length; j++){\n if (products[i].variant_ids.includes(line_item_variants[j])){\n all_product...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AdminFeedbacks Fetch all Feedbacks
getFeedbacks() { return this.http.get('feedback'); }
[ "async function getFeedback(where, attributes) {\n const highlights = await FeedbackRepository.findAll({\n where,\n attributes,\n });\n\n return highlights;\n}", "async getAllLessons() {\n const lessonCollection = await lessons();\n const lessonList = await lessonCollection.find({}).toArray...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refreshes the channel members text element based on the states of connectionData[profileName].channels[channelName].members and activeWindow. Types: Result is void.
function redrawChannelMembers() { utilsModule.clearChildren(memberListElem); var profile = self.activeWindow[0]; var party = self.activeWindow[1]; var show = profile in connectionData && party in connectionData[profile].channels; if (show) { var members = connectionData[profile].channels[party].members; ...
[ "function updateMemberList() {\n people_list = RTMchannel.getMembers().toString(); // gets list of channel members\n document.getElementById(\"people_list\").innerHTML = \"<u>People</u>: \" + people_list.toString();\n}", "onUpdatedChannels () {\n //OnX modules\n this._privMsg = new PrivMsg(this.bot)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MAIN FUNCTIONS We will build the current targets into a JSON structure. The reason: its the only way i found to pass them thru the message without altering its contents very much. This way I can add the targets to "roll" parameter (the only one that i could find) and it will be send. The "roll" parameter is a JSON dict...
function attachTargetsToMessage(messageData) { let settings = game.settings.get(MOD_ID, "targetsSendToChat"); if( settings === "none" ) { return; } else if( settings === "explicit" && messageData.type != CONST.CHAT_MESSAGE_TYPES.ROLL ) { return; } else if( settings === "implicit" && messageData.type != CONST...
[ "function renderToMessage_Targets(html, messageData) {\n // Return cases\n if( game.settings.get(MOD_ID, \"targetsSendToChat\") === \"none\" ) { return; }\n if( !messageData.message.roll ) { return; }\n \n var rollDict = JSON.parse(messageData.message.roll);\n let targetedTokens = getTokenObjsFromIds(rollDict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a member to a subcollection in a room
async addMemberToRoomSubCollection(roomId, userId, playerType, userName, botType) { let path = "room/" + roomId + "/members" await this.db.collection(path).doc(userId).set({ inroomState: true, memberId: userId, name: userName, type: playerType, ...
[ "async addRoomListToUser(fieldCurrent, fieldOwner, collectionPath, docId, itemId) {\n if (fieldCurrent === \"currentRoom\" && fieldOwner === \"isRoomOwner\") {\n await this.db.collection(collectionPath).doc(docId).update({\n currentRoom: itemId,\n isRoomOwner: true,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to determine flow of regime
function regime(reynum) { var reg=document.getElementById("flow"); if(reynum<2000) { reg.innerHTML="Laminar Flow"; } else if(reynum>2000 && reynum<4000) { reg.innerHTML="Transitional Flow"; } else { reg.innerHTML="Turbulent Flow"; } }
[ "function patientFlowP2(patient){\n\tvar state = patient.state\n\tvar hasArrived = (Math.abs(patient.target.row-patient.location.row)\n\t\t\t\t\t +Math.abs(patient.target.col-patient.location.col))==0;\n\tvar receptionistsAvail = receptionistAvailable()\n\tvar P2_bed = P2_in_bed();\n\tswitch(state){\n\t\tcase RECEP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the exchange responseObjects of this event readonly attribute jsval responseObjects; / // part of my own items.
get responseObjects() { return this._responseObjects; }
[ "get jsons() {\n\t\treturn this[root_json] ? this[root_json].$proxy() : null\n\t}", "function getEvents(){\nreturn events;\n}", "function getAllItemsCallback(response){\n\t\n}", "function loadResponse(){\n var APODObject = JSON.parse(this.response)\n APODList.push(APODObject)\n}", "get eventReceivers(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the global flag on a RegExp (you have to create a new one)
function _globalize($regexp) { return new RegExp(String($regexp).slice(1, -1), "g"); }
[ "function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }", "function addFlags(regexp, flags) {\n\n var reg = core.interpretRegExp(regexp);\n var regFlags = core.arrayUnique(\n reg.flags.split(\"\"),\n flags.split(\"\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function builds a curve factory from a standard curves object
function buildCurve(curve) { var base = d3['curve' + curve.name]; // The base curve without any arguments var args = curve.args; var built; if (args !== false) { var x; built = base; for (var i = 0; i < args.length; i++) { x = args[i]; built = built[x.nam...
[ "get curve() {}", "getCurve( startX, startY, endX, endY ) {\n let middleX = startX + (endX - startX) / 2;\n return `M ${startX} ${startY} C ${middleX},${startY} ${middleX},${endY} ${endX},${endY}`;\n }", "static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n // tslint:disa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the user projection if set. Note that this method is not yet a part of the stable API. Support for user projections is not yet complete and should be considered experimental.
function clearUserProjection() { userProjection = null; }
[ "function unproject(coord) {\n return map.unproject(coord, map.getMaxZoom());\n}", "unproject(xy) {\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n return viewport.unproject(xy);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function compares the LEDs in pending to those in active and if there is a difference it will send them via MIDI message If there is more than 30 lights changed it sends the MIDI in a single message ("optimized mode") rather than individually
function flushLEDs() { // changedCount contains number of lights changed var changedCount = 0; // count the number of LEDs that are going to be changed by comparing pendingLEDs to activeLEDs array for(var i=0; i<80; i++) { if (pendingLEDs[i] != activeLEDs[i]) changedCount++; } // e...
[ "function updateStatus(devices, new_status)\n{\n\tfor (var i in new_status )\t\t\t//for each status\n\t{\n\t\tfor(var j in devices)\t\t\t//look for the match ID\n\t\t{\n\t\t\tif( devices[j].deviceID == new_status[i].deviceID )\n\t\t\t{\n\t\t\t\tvar status = devices[j].status;\t\t//access the status array\t\t\t\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
allow a user to delete a habit
async function deleteHabit(req, res) { await Habit.findByIdAndDelete(req.params.id); show(req, res); }
[ "'click .delete'() {\n\t\tMeteor.call('tasks.remove', this._id, (error) => {\n\t\t\tif (error)\n\t\t\t\tBert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );\n\t\t\telse\n\t\t\t\tBert.alert( 'Task removed successfully!', 'success', 'growl-t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
chat equivalents : To = 2 Today = 2day Tomorrow = 2mrw Please = pls Because = b/c With = w/ Without = w/o Before = b4 Great = gr8 Ate = 8 Okay/Ok = k People = ppl For = 4 Be = b See = c Owe = o Are = r You = u Why = y About = abt Awesome = awsm Birthday = b/day Check = chk Could = cd Should = shd Would = wd Disconnect ...
function chatify( tweetSize , words ){ chatEq = {}; for( i =0; i < words.length; i++ ){ chatWord = getChatWord( words[i] ); if( chatWord != words[i] ){ chatEq[ words[i] ] = chatWord; reducedWordSize = words[ i ].length - chatWord.length; tweetSize = tweetSize - reducedWordSize; } if( tweetSize <= 1...
[ "function processSentence(nama, age, address, hobby){\n \n return 'Nama saya ' + nama +', umur saya '+ age +' tahun, alamat saya di ' +address +', dan saya punya hobby yaitu '+ hobby\n \n}", "function messageData(user, text){\n text = text.replace(':)', '\\uD83D\\uDE00')\n text = text.replace(':(', '\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append additional headers, e.g., xgooguserproject, shared across the classes inheriting AuthClient. This method should be used by any method that overrides getRequestMetadataAsync(), which is a shared helper for setting request information in both gRPC and HTTP API calls.
addSharedMetadataHeaders(headers) { // quota_project_id, stored in application_default_credentials.json, is set in // the x-goog-user-project header, to indicate an alternate account for // billing and quota: if (!headers['x-goog-user-project'] && // don't override a value the user sets....
[ "function TrackerSetHeader(\n Authorization = '',\n ppr = '',\n deltaId = '',\n deltamatic = '',\n channelId = '',\n appId = '',\n sessionId = ''\n ) {\n _HEADER = {\n Authorization: Authorization,\n UserAgent: `PPR|${ppr}, DL|${deltaId}, DLM|${deltamatic}`,\n channeId: channelId,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HAND STATE RELATED isBettingDone checks if a round of betting has completed.
isBettingDone(lineup, dealer, state, bbAmount) { if (this.isHandComplete(lineup, dealer, state)) { return true; } const activePlayers = activeLineup(lineup, dealer, state, this.rc); let maxBet; if (state === 'waiting' || state === 'preflop') { try { maxBet = this.getMaxBet(active...
[ "function isTournamentCompleted(tournament){\n console.log(tournament.tournament.progressMeter);\n return tournament.tournament.progressMeter == 100\n}", "isHandComplete(lineup, dealer, state) {\n const activePlayers = activeLineup(lineup, dealer, state, this.rc);\n const allInPlayerCount = this.countAllI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this function to populate DB with orders from ../assets/orders.json
async function populateOrders() { let orderNarrators = []; let advertisers = []; let customers = []; let contacts = []; let narrators = []; try { advertisers = await Advertiser.find(); customers = await Customer.find(); contacts = await Contact.find(); narrators = await Narrator.find(); } ...
[ "function update_orders() {\n\t$.ajax({\n\t\tcontentType: 'application/json; charset=UTF-8',\n\t\tdata: null,\n\t\tdataType: 'json',\n\t\terror: function (jqXHR, textStatus, errorThrown) {\n\t\t\tfailure('Failed to get order data', jqXHR.statusText);\n\t\t},\n\t\tsuccess: function (data, textStatus, jqXHR) {\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies client authentication on the request's header if either basic authentication or bearer token authentication is selected.
injectAuthenticatedHeaders(opts, bearerToken) { var _a; // Bearer token prioritized higher than basic Auth. if (bearerToken) { opts.headers = opts.headers || {}; Object.assign(opts.headers, { Authorization: `Bearer ${bearerToken}}`, }); ...
[ "function setHeaderWithToken() {\n var cookie = $.cookie(\"accessToken\");\n\n $(document).ajaxSend(function (event, jqxhr, settings) {\n jqxhr.setRequestHeader('Authorization', 'bearer ' + cookie);\n });\n }", "function authorize(request, token) {\n return Object.assign(\n { he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
consolidateHtml takes in a string of html gotten from curl on genius lyric page and splices out only the lyrics section defined by content between .lyrics_container and .song_footer
function consolidateHtml(str) { var relevantHtml = str.substring(str.indexOf("<lyrics *>")+1); relevantHtml = relevantHtml.substring(0,relevantHtml.indexOf("</lyrics>")); return relevantHtml; }
[ "function addLyricsToPage(lyrics, title) {\n var str = consolidateHtml(lyrics);\n //console.log(str);\n var links = addOnClicks(str);\n //console.log(links);\n var output = \"<div class='lyric-title-container'>\" + \n \"<h2 class='lyric-title'>\" + title + \"</h2>\" + \"</div>\";\n links[0].id ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve Available Payment Options Retrieves all payment types available within the requested Infusionsoft account
async getAllPaymentOptions () { return this._api.request('InvoiceService.getAllPaymentOptions') }
[ "ListAvailablePaymentMethodsInThisNicCountry() {\n let url = `/me/availableAutomaticPaymentMeans`;\n return this.client.request('GET', url);\n }", "RetrieveAvailablePaymentMethod() {\n let url = `/me/payment/availableMethods`;\n return this.client.request('GET', url);\n }", "pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a request to refresh the captcha image.
function _refreshCaptcha() { $.getJSON(config.captchaRefreshURL, {}, function(json) { $captcha_image[0].src = json.image_url; $captcha_image.next()[0].value= json.key; }); return false; }
[ "function vpb_refresh_aptcha()\r\n{\r\n\treturn $(\"#vpb_captcha_code\").val('').focus(),document.images['captchaimg'].src = document.images['captchaimg'].src.substring(0,document.images['captchaimg'].src.lastIndexOf(\"?\"))+\"?rand=\"+Math.random()*1000;\r\n}", "function Refresh_Image(the_id)\n{\n var dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changes the price of a stock to a random new one, in a given range
CHANGE_PRICES(state) { // use a forEach() because it's an array // otherwise if it was an object you'd for(x in y) state.stocks.forEach(stock => { // doesn't make sense for the volatility to vary between a large range, // so it should only be a growth or shrinkage of the original price con...
[ "changeStockPrices(state) {\n state.stocks.forEach(stock => {\n stock.price = Math.round(stock.price * (1 + Math.random() - 0.5));\n });\n }", "function priceChange() {\n\tfor (var i = 0; i < fruits.length; i++) {\n\t\tvar randomPrice = randomNumber(-.50, .50);\n\t\tvar currentPrice = fruits[i][1];\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the function is used to handle the event onkeyUpInput when user press any kay the method check if the length of the input is greater than 0 and the enable reply button if the input length is equal to 0 the reply button is disabled
function onKeyUpInputReply(e) { /** * the id of the replyButton * */ var inputBtn = "#comment-" + e.currentTarget.id.split('-')[1] + "-reply-btn"; /** * Get the reply input * */ var reply = $("#" + e.currentTarget.id).val().trim(); /** * check the reply lengt...
[ "function checkCommentLength(textareaObj) {\n let key = event.keyCode || event.which;\n //check the number of character in textbox\n if (textareaObj.value.length > 0) {\n $(textareaObj).siblings('.comment-submit').removeAttr('disabled');\n /*I'm not sure if I should add the 'hit enter' featur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function called odds that accepts an array as a parameter and returns an array of just the odd numbers. If you wrote it using each, great! If you used anything else, refactor it to use a for loop.
function odds(arr) { oddArr = []; each(arr, function(element) { if (element % 2 !==0) { oddArr.push(element); }; }); return oddArr; }
[ "function arrayodd() {\n var oddarray = [];\n for (var i = 1; i <= 50; i = i + 2) {\n oddarray.push(i);\n }\n return oddarray;\n}", "function arrayOfOdds (arr){\n var arr = [];\n for(var i = 0; i <= 50; i++){\n if(i % 2 !== 0){\n arr.push(i);\n }\n }\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
END Purpose: This function handles ajax put request. It takes the id for the row that will be updated. Inputs: Id. Output: None.
function put() { // Create a url for the ajax request. $.each(editObject, function(index, value) { if(index == 'id') { url += index+"="+value; } else { url += "&"+index+"="+value; } }); $.ajax({ url: 'api/?'+url, method: 'PUT', da...
[ "updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }", "function putToDos(id, data) {\n\n var defer = $q.defer();\n\n $http({\n method: 'PUT',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id,\n data: data\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the patient id from the reference
get patientId() { // subject.reference = 'Patient/{patientId}' return ( this._subject && this._subject.reference && this._subject.reference.split('/')[1] ); }
[ "function getPatientByID(patientID) {\r\n return self.patients[patientID];\r\n }", "id() {\n \n // implementation should be inside the child class, but below implementation\n // if for simplicity in many occasions\n if (typeof this.data.id != 'undefined') return this.data.id;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the CanIUse database to see if targets are supported
function canIUseSupported(stats, _ref) { var version = _ref.version, target = _ref.target, parsedVersion = _ref.parsedVersion; var targetStats = stats[target]; return versionIsRange(version) ? (0, _keys2.default)(targetStats).some(function (statsVersion) { return versionIsRange(statsVersion) && c...
[ "function getUnsupportedTargets(node, targets) {\n var stats = _data2.default.data[node.id].stats;\n\n return targets.filter(function (target) {\n return canIUseSupported(stats, target);\n }).map(formatTargetNames);\n}", "function needTarget(effect,other_data){\n return (!other_data.isLS && !other_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads an XML document a processes it with a processor function
function ProcessableXML() { }
[ "function loadXMLDoc(url, element_id)\r\n{\r\nif (url !=\"\")\r\n{\r\nvar xhttp;\r\nif (window.XMLHttpRequest)\r\n {\r\n xhttp=new XMLHttpRequest();\r\n }\r\nelse\r\n {\r\n xhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n }\r\nxhttp.open(\"GET\",url,false);\r\nxhttp.send();\r\ndocument.getElementById(eleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DataField and DataPack system : default DataField (customisable), many of which constitute a DataPack
function DefaultDataField(){ return { questionname:"???", //Display name of the field question qfield:"question", //Field name must be unique qvalue:"", //Field value, by default qid:GenerateId(), //id of the field question qchoices:"", //answer options list executeChoice:Identity, ...
[ "function fieldFromDerivedFieldConfig(derivedFieldConfigs) {\n var dataLinks = derivedFieldConfigs.reduce(function (acc, derivedFieldConfig) {\n // Having field.datasourceUid means it is an internal link.\n if (derivedFieldConfig.datasourceUid) {\n acc.push({\n // Will be filled out later\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The graph should contain a list of vertices and an object for building an adjacency list.
function Graph() { this.vertices = []; this.adjacencyList = {}; }
[ "constructor(value) {\n this.value = value;\n this.adjacents = []; // Adjacency List\n }", "constructor() {\n this.graph = {};\n }", "function buildGraph(edges) {\r\n let graph = Object.create(null); // graph is created as a null Object\r\n function addEdge(from, to) {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
note of component: Title: displays the title of the page FormContainer: displays the form and takes in user input WordCloud: curates user input and displays the word cloud alert: appears when the user tries to submit without text input
render() { return ( <LayoutDiv> <Title/> <CenterDiv> <FormContainer dataReturnHandler={this.handleData}/> {this.state.FormInputData === '' ? null : <WordCloudDisplay rawData={this.state.FormInputData}/>} </Center...
[ "function submitWord() {\n\tif (player != \"\" && room != -1 && word != \"\") {\n\t\tdebug(\"-\");\n\t\tvar word = document.myForm.word.value.toUpperCase().replace(/Ä/g, \"a\").replace(/Ö/g, \"o\");\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=submitword&player=\" + player + \"&passcode=\" + passcode + \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the AdSize for the slot.
function adSize(slot) { if (slot.params.cf) { var size = slot.params.cf.toUpperCase().split('X'); var width = parseInt(slot.params.cw || size[0], 10); var height = parseInt(slot.params.ch || size[1], 10); return [width, height]; } return [1, 1]; }
[ "function get_item_size() {\n var sz = 220;\n return sz;\n}", "function banner(slot) {\n var size = adSize(slot);\n return slot.nativeParams || slot.params.video ? null : {\n w: size[0],\n h: size[1],\n battr: slot.params.battr\n };\n}", "function computeLaneSize(lane) {\n\t\t // assert(lane inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mira si existe la carpeta ebooks, de no existir, la crea
verificaSiExisteEbooks() { let verificaGenerador = (function *() { let existeCarpeta = yield this.existe( EBOOKS, true, verificaGenerador ); if (!existeCarpeta) { yield this.creaCategoriaNueva( EBOOKS, verificaGenerador ); /* eslint no-console: "off" */ console.log( 'Carpeta ebooks...
[ "findBookIndex(book) {\n let bookIndex = this.allBooks.indexOf(book);\n if (bookIndex == -1) {\n console.error(\"Book does not exist in allBooks array\")\n return false\n } else {\n return bookIndex;\n }\n\n }", "function createWorkbook() {\n cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reward user with badge.
function rewardBadge(codename, params){ // Remove from checkers. delete params._userCheckers[codename]; // Add badge to user. User.findOne({_id:params.user.id}, function(err, user){ if(err || !user) return; // Add badge. user.badges.push(params.badge._id); user.markModified('badges'); // ...
[ "function achievements_grant(id, close_payload){\n\tif (this.tsid == 'PCRN0MDLUUT195N' || config.is_dev) log.info(this+' achievements_grant '+id);\n\tif (this.achievements_has(id)) return;\n\t\n\tvar achievement = this.achievements_get(id);\n\tif (!achievement){\n\t\tlog.error(this+' unlocked invalid achievement: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In general, you can call encodeURIComponent directly since all browsers support it
function encode(text) { return encodeURIComponent(text); }
[ "function encodeURL(path)\n{\n return encodeURIComponent(path).replace(/%2F/g,'/');\n}", "encodeParams(params) {\n return Object.entries(params).map(([k, v]) => `${k}=${encodeURI(v)}`).join('&')\n }", "buildQuerry (query){\n var ecodedQuery = encodeURIComponent(query);\n return ecodedQuery;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send data to background script through runtime port.
function sendDataToBackground(data) { chromePort.postMessage(data) }
[ "function sendToSerial(data) {\n console.log(\"sending to serial: \" + data);\n myPort.write(data);\n}", "function sendData() {\n\n // Get all PID input data and store to right index of charVal\n for(var i = 1; i <= 18; i++) {\n txCharVal[i] = select(inputMap[i]).value;\n }\n\n // Get all contr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The timestamp of this data
timestamp() { return this._d.get("time"); }
[ "get timestamp() {\n if (this._timestamp == null) {\n this._timestamp = new Date(this.ts);\n }\n\n return this._timestamp;\n }", "function YDataStream_get_startTime()\n {\n return this._timeStamp;\n }", "function getTimeStamp() {\r\n\treturn extractStamp(new Date());\r\n}", "get st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
================================ Takes the thing to append and the location to append the thing to (elem) as parameters Removes hide class from the elem
function showAndDisplay(thing, elem){ $(elem).append(thing).addClass("show", function(){ $(this).removeClass("hide"); }); }
[ "function hideHelper(event, element) {\n element.removeAttribute(\"visible\");\n element.style.visibility = \"hidden\";\n }", "function makeInvisible(element) {\n\telement.className = \"invisible\";\n}", "function addWidget(id, x, y, src, hide) {\n var elt = docum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main public function that is called to // parse the XML string and return a root element object
function cXparse(src) { var frag = new _frag(); // remove bad \r characters and the prolog frag.str = _prolog(src); // create a root element to contain the document var root = new _element(); root.name = "ROOT"; // main recursive function to process the xml frag = _compile(frag); ...
[ "lesx_parseElement() {\n var startPos = this.start,\n startLoc = this.startLoc;\n\n this.next();\n\n return this.lesx_parseElementAt(startPos, startLoc);\n }", "function ProcessableXML() {\n\n}", "parseElement() {\n const name = this.tok.take();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: validateData Check the data to geocode
function validateData() { hideGeoportalView(); var geocoder= viewer.getVariable('geocoder'); geocoder.checkData(); }
[ "function hasValidPoint(data) {\n return (typeof data.latitude != \"undefined\" && data.longitude != \"undefined\" && data.latitude != null && data.longitude != null && !isNaN(data.latitude) && !isNaN(data.longitude));\n }", "function validateAddress() {\n return checkPersonalInfo(\"address\", \"Addr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logs one row of log data.
async log(logRow) { const client = await this.queue.client; const logsKey = this.toKey(this.id) + ':logs'; return client.rpush(logsKey, logRow); }
[ "function writeLog(message, rowNumber)\n{\n Logger.log( \"Row: \" + rowNumber + \" : \" + message);\n}", "_log() {\n let args = Array.prototype.slice.call(arguments, 0);\n\n if (!args.length) {\n return;\n }\n\n if (args.length > 1)\n this.emit('log', args.join('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
seeMore method loops over topSongsItems array and displays all items
seeMore(){ let i = 0; for(i=0; i<topSongsItems.length; ++i){ helper.hideOrShow(topSongsItems[i], false); } //Remove class used to determine buttons state seeMoreBtn.classList.remove('see-more-js'); //Swap text out on button seeMoreBtn.innerHTML = 'See Less'; }
[ "seeLess(){\n let i = 0;\n for(i=0; i<topSongsItems.length; ++i){\n if(i>2){\n helper.hideOrShow(topSongsItems[i], true);\n }\n }\n //Add class used to determine buttons state\n seeMoreBtn.classList.add('see-more-js');\n //Swap text out on button\n seeMoreBtn.innerHTML = 'See M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads key/value store from file.
function readStore(storeFile) { var data = fs.readFileSync(storeFile, 'utf8', function(error) { if (error) { console.log('Unable to read store file: ' + error); console.log('Cleaning and resetting store file.') } }); return JSON.parse(data); }
[ "function load (file) {\n var map = {};\n // read the file synchronously, this isn't a server\n var content = fs.readFileSync(file, encodingOptions);\n // split out the lines\n var lines = content && content.split(/[\\r\\n]+/g);\n if (lines) {\n // For every line\n lines.forEach(function (line) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an existing area.
function deleteArea(axios$$1, areaToken, force) { var query = ''; if (force) { query += '?force=true'; } return restAuthDelete(axios$$1, 'areas/' + areaToken + query); }
[ "async removeAreas() {\n const areas = this.ctx.request.body;\n let del = true;\n\n for (const area of areas.areas) {\n if (!await this.service.areas.delete({ id: area.id })) {\n del = false;\n }\n }\n\n if (!del...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new waypoint (as a LatLng object).
function addLocation() { let newWaypoint = currentRoute.routeMarker.getPosition(); currentRoute.waypoints.push(newWaypoint); currentRoute.displayPath(); }
[ "function handleAddWaypointClick(e) {\n //id of prior to last waypoint:\n var waypointId = $(e.currentTarget).prev().attr('id');\n var oldIndex = parseInt(waypointId);\n addWaypointAfter(oldIndex, oldIndex + 1);\n theInterface.emit('ui:selectWaypointType', oldIndex);\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a handler Create a handler for a given effect
function _new_handlerx( effect_name, reinit_fun, return_fun, finally_fun, branches0, handler_kind, handler_tag, wrap_handler_tag) { // initialize the branches such that we can index by `op_tag` // regardless if the `op_tag` is a number or string. const branches = new Array(branches0.length...
[ "createEffect() {\n return new FilterEffect()\n }", "function createHandler(eventType) {\n xhr['on' + eventType] = function (event) {\n copyLifecycleProperties(lifecycleProps, xhr, fakeXHR);\n dispatchEvent(fakeXHR, eventType, event);\n };\n }", "get effect() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the TeamTelephone settings per Team if it's not a TeamTelephone team, the activate form will be shown This form will show up only if you have the role of coordinator
function show(options) { //TODO fix directive var tabs = angular.element('.nav-tabs-app li:not(:last)'); if (!options || !options.adapterId) { if (angular.isDefined(self.activateTTForm)) {//Empty form validation by changing the team ...
[ "function showSetDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }", "function showCompanyForm(mode, callback) {\n\n }", "function goToTeam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the values to the appropriate types before saving the hotel
function parseValues(hotelToSave) { hotelToSave.noOfRooms = parseInt(hotelToSave.noOfRooms); hotelToSave.ratePerRoom = parseInt(hotelToSave.ratePerRoom); /*hotelToSave.noOfAvailableRooms = parseInt(hotelToSave.noOfRooms);*/ hotelToSave.location = hotel.selectedLocation; hotelToSave.contact.phone1 = parseInt(h...
[ "function dataCleanUp(data,type){\n\t\tif(type == 'places'){\n\t\t\tfor (var i = 0; i < data.features.length; i++) { /*[1]*/\n\t\t\t\tvar feature = data.features[i];\n\t\t\t\tif(feature.properties.tags.constructor !== Array){/*[2]*/\n\t\t\t\t\tvar tagsAarray = feature.properties.tags.split(',');\n\t\t\t\t\tfeature....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of energy resource this creep could harvest in the same / duration of moving dist.
function totalPotentialHarvests(creep, dist){ var workParts = creep.getActiveBodyparts(WORK) var harvestsPerTick = workParts * 2 // Debug log //console.log('workParts: ' + workParts + ', totalPotentialHarvests: ' + totalPotentialHarvests) return harvestsPerTic...
[ "function energySpent() {\n // Calculate distance moved since last subtraction.\n var moved = ballBody.position.vsub(lastPos);\n\n // Only return if moved move than one square!\n if (moved.length() >= 0.98) {\n // Also update the path in map scene.\n updateLinePath();\n lastPos.copy(ballBody.position);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export graph to a PNG
function exportToPNG(graphName, target) { var plot = $("#"+graphName).data('plot'); var flotCanvas = plot.getCanvas(); var image = flotCanvas.toDataURL(); image = image.replace("image/png", "image/octet-stream"); var downloadAttrSupported = ("download" in document.createElement("a")); ...
[ "function exportPngClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n const background = window.getComputedStyle(document.body).backgroundColor;\n exportPng(filename + '.png', svgXml, background);\n}", "_do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Card Helper Function Referenced In: addInterest() uses cloneNode() to create a duplicate of the main card with id = 0 updates the id of all the objects for unique and separate calculations
function add(identification) { // Get card div object and create duplicate, reassign unique id var installmentCard = document.getElementById("card0"); var duplicate = installmentCard.cloneNode(true); duplicate.id = "card" + identification; var idString = '\'' + duplicate.id + '\''; //converts id to...
[ "function addCard(clickedCard){\n matches.push(clickedCard)\n}", "function addCard(){\n\tvar id = storage.id();\n\tvar newNode = document.createElement('div');\n\tnewNode.className = \"flashcard-set\";\n\tnewNode.id = id;\n\tnewNode.innerHTML = '<div class=\"term\"><textarea name=\"card-term\" data-card-term=\"'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all products. Optional: if inStock is true, only products will available inventory will be shown.
function getAllProducts(parent, args) { if (args.inStock) { return productList.filter(product => product.inventory_count > 0); } else { return productList } }
[ "function getAllProducts () {\r\n return db.query(`SELECT * from products`).then(result => {\r\n return result.rows\r\n })\r\n}", "function getProducts() {\n var params = getParams();\n params[\"categoryID\"] = $scope.categoryId;\n categoryApiService.getProductsByCategoryId(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if node is ObjectPattern
function isObjectPattern(node) { return node.type === "ObjectPattern"; }
[ "function object (thing) {\n return typeof thing === 'object' && thing !== null && array(thing) === false && date(thing) === false;\n }", "function is_tagged_object(stmt,the_tag) {\n return is_object(stmt) && stmt.tag === the_tag;\n}", "static isInstance(obj) {\n if (obj === undefined || obj ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replace single dots, but not multiple consecutive dots
function dotsReplacer(match) { if (match.length > 1) { return match; } return ''; }
[ "function addDot(value, selection) {\n if (config.currencyCents === 0) {\n return value;\n }\n var dotPos = value.length - config.currencyCents;\n if (selection.start > dotPos) {\n selection.start = selection.start + 1;\n }\n if (selection.end > dotPos) {\n selection.end = selection...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the csv and import the data to elasticsearch
function importData() { let heroes = []; // Read CSV file fs.createReadStream('all-heroes.csv') .pipe(csv({ separator: ',' })) .on('data', (data) => { heroes.push({ 'id': data.id, 'name': data.name, 'description': data.description, 'imageUrl': data.imageUrl...
[ "function import_data_from_csv() {\n fetch(\"input.csv\")\n .then(v => v.text())\n .then(data => init_table_from_data(data))\n}", "function readCSV(csv) {\n logger.info(\"Reading input CSV...\");\n\n csvtojson()\n .fromFile(csv)\n .on('json', (jsonObj) => {\n posts....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If it's not 'staging' or 'production', then it should be 'staging'
function defaultStage(stage) { let staging = 'staging' let production = 'production' if (stage !== staging && stage !== production) stage = staging return stage }
[ "_is_testing() {\n return this.env != \"production\" && this.env != \"prod\";\n }", "getUrl() {\n return process.env.ENVIRONMENT === \"DEV\" ? \"http://localhost:3001\" : \"prod\";\n }", "function getStage(){\n return process.env['ALICE_STAGE'];\n}", "function toggleStatusInProduction( commit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for the spinner change event
function onSpinnerChange() { var $spinner = $(this); var value = $spinner.spinner('value'); // If the value is null and the real value in the textbox is string we empty the textbox if (value === null && typeof $spinner.val() === 'string') { $spinner.val(''); return; } // Now check that the number is in the ...
[ "on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles error message on form fields that are not completed when other fields below are onChange
function handleFormGridError(event) { // Checks which required fields to not hold a value let fieldsWithoutValue = []; let selectedField = false; // Gets all fields without value props.fields.map((field, index) => { field.required && fieldsWithoutValue.push(index); if (event.target.name ...
[ "function validateForm(event) {\n var success = true;\n\n if (!validateName('input[name=\"billFirstName\"]', 'input[name=\"billLastName\"]', \"#error_bill_names_div\")) {\n success = false;\n }\n if (!validateAddress('input[name=\"billAddress\"]', 'input[name=\"billCity\"]', 'input[name=\"billSta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
event handler for "participantVideo added/updated/deleted in participant|localParticipant" events tracks session video state (on/off), participant video state and shows/removes video when video modality is activated/deactivated.
function onParticipantVideo(status, resource, event) { var scope = event['in']; if (event.sender.href == rConversation.href && scope) { if (scope.rel == 'localParticipant') { switch (event.type) {...
[ "function videoToggle() {\n // set video state.\n setVideoState(!videoState);\n\n // toggle the video track.\n toggleTracks(userStream.getVideoTracks());\n\n // send update to all user, to update the status.\n sendUpdate(!videoState, audioState);\n }", "onParticipantLeft(message)\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of global script metadata for a microservice.
function listGlobalScriptMetadata(axios$$1, identifier) { return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/scripting/scripts'); }
[ "function listTenantScriptMetadata(axios$$1, identifier, tenantToken) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts');\n }", "async function getScripts() {\n const url = '/api/scripts';\n const response = await fetch(url);\n const s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIE...
function ZeroCloudClient() { this._token = null; }
[ "async function createBackupVaultWithMsi() {\n const subscriptionId =\n process.env[\"DATAPROTECTION_SUBSCRIPTION_ID\"] || \"0b352192-dcac-4cc7-992e-a96190ccc68c\";\n const resourceGroupName = process.env[\"DATAPROTECTION_RESOURCE_GROUP\"] || \"SampleResourceGroup\";\n const vaultName = \"swaggerExample\";\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor creates a new vector drawer. Parameters: astroMap the map to draw the vectors on layer the layer to draw the vectors on (should be an OL vector layer)
function AstroVector(astroMap, layer) { this.astroMap = astroMap; this.layer = layer; // for storing vectors and their state this.storedVectors = []; this.styles = []; this.selectStyle = new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 128, 0, 0.2)' }), stroke...
[ "constructor(options, labelOptions, map) {\n //If certain options were not set then provide a default value for them\n options.style = options.style || ol.style.arcLabelStyleFunction;\n options.updateWhileAnimating = options.updateWhileAnimating || false;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delegates requests to internalManager:RoomManager Emits events handled by NotificationRoomHandler
function NotificationRoomManager(notificationService, kcProvider) { var self = this EventEmitter.call(this) self.notificationRoomHandler = new NotificationRoomHandler(notificationService) self.internalManager = new RoomManager(self.notificationRoomHandler, kcProvider) }
[ "handleEvents() {\n\t\tif (this.events) {\n\t\t\tfor (let event in this.events) {\n\t\t\t\tComponent.pubsub.on(event, (data) => {\n\t\t\t\t\t// We're only interested in events which match this instance's unique identifeir\n\t\t\t\t\tif (data.props.uid === this.uid) {\n\t\t\t\t\t\tthis.events[event](data);\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to return even numbers
function evenNumbers(numbers) { return numbers % 2 == 0; }
[ "function is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\n}", "function ifevenorzero(n){\n if (n == 0){\n return 1\n }\n\n else{\n if(n % 2 == 0 ){\n return 1;\n }\n else{\n return 0;\n }\n }\n}", "function evenNumbers (randomInteger) {\n if ( randomInte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Boot mock server and redirect to random, unused endpoint TODO: This code introduces codependencies between application and test code. Refactor!
redirect(options, cb) { if (this.constructor.name === "BasicAuth") { /* start basic auth server on 3001 */ /* no mock for basic auth yet, leaving empty */ cb(options); } else if (this.constructor.name === "IdmAuth") { /* start idm auth server on 3002 */ mocks.IdmMockServer.run( ...
[ "request(options, callback) {\n if (server.app.get('mock_auth') === true) {\n /* redirect to mock */\n this.redirect(options, redirected => {\n request(\n redirected,\n callback\n );\n });\n } else {\n request(\n options,\n callback\n );\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new options objects with the given fontFamily.
withTextFontFamily(fontFamily) { return this.extend({ fontFamily, font: "" }); }
[ "public FontFamily(string familyName) : this(null, familyName)\r\n {}", "function updateFontOptions() {\n styleSelectFont.innerHTML = \"\";\n for (let i = 0; i < fonts.length; i++) {\n const opt = document.createElement(\"option\");\n opt.value = i;\n const font = fonts[i].split(\":\")[0].replac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make and insert a plot.ly object into the container in the HTML. Package the data into JS objects that are passed to plot.ly. Inputs: target target HTML container slew_traces line segments, already as a plot.ly object x,y,z,size,text star plot attributes, placed into a plot.ly object here x_way, y_way, text_way waypoin...
function insertPlotly(target, slew_traces, x, y, z, size, text, x_way, y_way, text_way) { // var plotDiv = document.getElementById('plotDiv'); // default title labels var legend_cbar = 'Mean Cumulative Characterizations'; var plot_title = [ 'Mean Cumulative Characterizations and Slew Paths Over E...
[ "function createTracesAndLayout(arr, title, jitter='all'){\n // Iterate through the formatted array [[name_of_trace, expression_data]...]\n // and create the response plotly objects, returning [plotly data object, plotly layout object]\n var data = Array();\n for(x=0;x<arr.length;x++){\n // plotl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inser a library function in the currently active grid
function insertLibFunc() { var pO = CurProgObj; var sel1 = document.getElementById('selWin'); var libind = sel1.selectedIndex; var sel2 = document.getElementById('selWin2'); var funcind = sel2.selectedIndex; // alert("TODO: Lib ind:" + libind + " funcind:" + funcind); displa...
[ "function addLibFuncExpr() {\r\n\r\n drawLibSelWin(0);\r\n}", "function addFeature() {\n\n}", "function addNewFuncExpr() {\r\n\r\n // if any grid is currently highlighted, remove that highlight first\r\n // This is important if the user replaces a grid expression with an\r\n // operator\r\n //\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a location with at least `lat` and `lng`, compute its `octant` and its first `x`, `y`, `max`; then set `levels` to an empty array.
function computeOctant(location) { if (location.lat > 0) { if (location.lng < -90) { location.octant = 0; } else if (location.lng < 0) { location.octant = 1; } else if (location.lng < 90) { location.octant = 2; } else { location.octant = 3; } } else { if (location.lng < -90) { location.oc...
[ "function computeLatLng(location) {\n\tlet l = location.levels.length;\n\tlet x = location.x;\n\tlet y = location.y;\n\t\n\tfor (let i=l-1; i>=0; i--) {\n\t\tlet level = +location.levels[i];\n\t\tif (level === 1) {\n\t\t\tx /= 2;\n\t\t\ty = y/2 + 0.5;\n\t\t} else if (level === 2) {\n\t\t\tx /= 2;\n\t\t\ty /= 2;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all persons in a person group, and retrieve person information (including personId, name, userData and persistedFaceIds of registered faces of the person). Http Method GET
personListPersonsInAPersonGroupGet(queryParams, headerParams, pathParams) { const queryParamsMapped = {}; const headerParamsMapped = {}; const pathParamsMapped = {}; Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonListPersonsInAPersonGroupGetQueryParametersN...
[ "async index({ params, response }) {\n const group = await Group.find(params.group_id)\n if (!group) return response.notFound({ message: 'group not found!' })\n\n return group.users()\n .orderBy('id', 'desc')\n .fetch()\n }", "personGroupGetAPersonGroupGet(queryParams, headerParams, pathParams...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getNotificationRequest: Build GetNotification's request
getNotificationRequest() { let operation = { 'api': 'GetBucketNotification', 'method': 'GET', 'uri': '/<bucket-name>?notification', 'params': { }, 'headers': { 'Host': this.properties.zone + '.' + this.config.host, }, 'elements': { }, 'properties':...
[ "static getClientNotification(entryId, type){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('notification', 'getClientNotification', kparams);\n\t}", "deleteNotificationRequest() {\n let operation = {\n 'api': 'DeleteBucketNotificat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates a new keyboard pre info. This class is used to store keyboard related info for the onPreKeyboardObservable event.
function KeyboardInfoPre(/** * Defines the type of event (BABYLON.KeyboardEventTypes) */type,/** * Defines the related dom event */event){var _this=_super.call(this,type,event)||this;_this.type=type;_this.event=event;_this.skipOnPointerObservable=false;return _this;}
[ "function KeyboardInfo(/**\n * Defines the type of event (BABYLON.KeyboardEventTypes)\n */type,/**\n * Defines the related dom event\n */event){this.type=type;this.event=event;}", "function PointerInfoPre(type,event,localX,localY){var _this=_super.call(this,type,event)||this;/**\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
resolve orgs into repos before processing
function load_orgs() { if (orgs.length > 0) { var org_list = []; orgs.forEach(function(item) { (item.type === 'repo') ? repos.push(item) : org_list.push(item); }); if (org_list.length > 0) { org_list.forEach(function(item){ var t = new Object();...
[ "fetchOrgs() {\n this.orgsSerivce.find({query: this.defaultQuery})\n .then(message => {\n this.setState({orgs: message.data, orgsLoaded: true});\n })\n .catch(err => {\n printToConsole(err);\n displayErrorMessages('fetch', 'organizers', err, this.updateMessagePanel, 'reload');...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accounts for the exemption phaseout at high incomes. It should return the defaultExemptionAmount at lower incomes and 0 for very high incomes, while returning a value in between the two if income is in the phaseout range.
function calculateExemptionAmount(year, filingStatus, income){ var incomeAbovePhaseoutStart = Math.max(0, income - exemptionPhaseoutStart[year][filingStatus]); var stepsAbovePhaseoutStart = Math.ceil(incomeAbovePhaseoutStart / 2500); var exemptionPercent = Math.max(0, 1 - (stepsAbovePhaseoutStart * .02)); ...
[ "salaryFromTakeHome(income) {\n let salary;\n\n const nILowerLimit = this.nILowerLimit * 12;\n const nIUpperLimit = this.nIUpperLimit * 12;\n\n // 1) Income less than NI lower limit\n if (income <= nILowerLimit) {\n salary = income;\n }\n\n // 2) Income within NI Lower limit\n // 2a) In...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New Perspectives on HTML5 and CSS3, 7th Edition Tutorial 10 Case Problem 3 Author: Date: Filename: ah_report.js Functions: calcSum(donorAmt) A callback function that adds the current donation amount in the array to the donationTotal variable findMajorDonors(donorAmt) A callback function that returns the value true only...
function calcSum(donorAmt) { donationTotal += donorAmt[9]; }
[ "function outliers_summary(aggregator_id) {\n var start_date = new Date(payments_start_date);\n var start_date_time = new Date(start_date.getFullYear() + \"-\" + (start_date.getMonth() + 1) + \"-\" + start_date.getDate()).getTime();\n var diff = start_date.getTime() - start_date_time;\n var end_date = n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a [HammerJS Manager]( and attaches it to a given HTML element.
buildHammer(element) { const mc = new Hammer(element, this.options); mc.get('pinch').set({ enable: true }); mc.get('rotate').set({ enable: true }); for (const eventName in this.overrides) { mc.get(eventName).set(this.overrides[eventName]); } return mc; }
[ "function addHammerRecognizer(theElement) {\n // We create a manager object, which is the same as Hammer(), but without \t //the presetted recognizers.\n //alert(\"dfadfad\");\n var mc = new Hammer.Manager(theElement);\n \n \n // Tap recognizer with minimal 2 taps\n mc.add(new Hammer.Tap({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }