query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
gear ratio: spur / pinion trans
function calculateGear() { let transmission = getElementByID("modelsGears").value, spur = getElementByID("spur").value, pinion = getElementByID("pinion").value, tire = getElementByID("tire").value; setTextByID("final","---"); setTextByID("rollout","---"); if (validateNumber([spur, pinion])) { let finalGear ...
[ "function goodres(r) {\n return Math.round(r * renderVR.ratio / 4) * 4;\n}", "static saturationMixingRatio(p,t) {\n // ratio molecular weight of water vapour/dry air = 0.622\n var rr = 0.622; // MeteoMath.Rd/MeteoMath.Rv\n var Es = MeteoMath.saturationVaporPressure(t);\n // saturation mixing ratio\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to match and apply the given arguments to this mapping. / / returns a type if successful / returns null if there is a type variable argument / returns false if it doesn't match
matchApply (tys) { if (tys.length !== this.patterns.length) return new ErrorType('argc'); let hasVarArg = false; // Bindings. Mapping our own type variables (found in this.bindings) to types from `tys`. const bindings = new Map(); // Matches a type pattern. const matchP...
[ "monomorph(args) {\n return (false\n // TODO: Maybe use non primitive types first?\n || this.overloads.get(Typer.asConcreteTypes(args))\n || this.overloads.get(Typer.asTermTypes(args))\n || this.overloads.get(Typer.asGenericTerms(args)));\n }", "monomorph(args...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function then creates the necessary fields required in the databse to store the correct information relating to a milk recording 1. Selects "milkRecordings" collection. 2. Creates a new document with a randomy generated ID. 3. Adds field tagNum with value of tagNum variable from above. Same for rest. 4. .then if s...
function addRecord() { addMilkRecording(route.params.tagNum, date, parseFloat(milkProduced), parseFloat(protein), parseFloat(butterfat), parseFloat(cellCount), notes) .then(() => { ToastAndroid.show('Added Successfully', ToastAndroid.SHORT) navigation.goBack() ...
[ "function addFoodAndWater() {\n // initialize and set vars\n var requiredInputs = document.querySelectorAll(\".required\");\n // var error = false;\n // // this is a 'check' var for if just 1 of all required inputs is empty \n // var error2 = false;\n\n // *****************************************...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compare the bot's pnpId with all of the bots in our database if a pnpId exists, lost the bot with those settings, otherwise pull from a generic bot
checkForPersistentSettings(port, botPreset) { try { const availableBots = Bots.find().fetch(); const savedDbProfile = availableBots.find(bot => port.pnpId && bot.endpoint === port.pnpId); if (savedDbProfile) { return savedDbProfile; } // If pnpid or serial number, need to add...
[ "soloBot() {\n let uuid;\n\n _.entries(this.botList).forEach(([botKey, bot]) => {\n if (bot.fsm.current !== 'unavailable') {\n uuid = bot.settings.uuid;\n }\n });\n\n if (uuid === undefined) {\n throw new Error('No bot is currently available');\n }\n\n return uuid;\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a moment object to a moment representing the first of the month.
function convertToFirstOfMonth(momentObj) { const dayValue = momentObj.format('DD') - 1; const newMoment = momentObj.subtract(dayValue, 'days'); return moment(newMoment.format('YYYY-MM-DD')); }
[ "function getFirstOfMonth(currDate) {\n const firstOfMonth = moment({\n year: currDate.get('year'),\n month: currDate.get('month'),\n day: 0\n });\n\n return firstOfMonth;\n}", "function getFirstMonthsDate(dt){\n return new Date(dt.getFullYear(), dt.getMonth(), 1);\n }", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invokes `util.format()` with the specified arguments and writes to stderr.
function log(...args) { return process.stderr.write(util$2.format(...args) + '\n'); }
[ "function log(...args) {\n return process.stderr.write(util.format(...args) + \"\\n\");\n }", "function log() {\n\t return process.stderr.write(util.format.apply(util, arguments) + '\\n');\n\t}", "function log(...args) {\n return process.stderr.write(util.format(...args) + '\\n');\n }", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pulls ingredients with name of the meal createShoppingList Input: Array of meal names Output: Array of ingredients of each meal
createShoppingList(mealNames, database) { let shoppingList = []; if (mealNames != undefined) { for (let mealNameIndex = 0; mealNameIndex < mealNames.length; mealNameIndex++) { for (let recipeIndex = 0; recipeIndex < database.length; recipeIndex++) { if (database[recipeIndex].name == meal...
[ "createShoppingList(mealNames) {\n let shoppingList = [];\n for (let mealNameIndex = 0; mealNameIndex < mealNames.length; mealNameIndex++ ) {\n for (let recipeIndex = 0; recipeIndex < recipeDb.length; recipeIndex++) {\n if (recipeDb[recipeIndex].name == mealNames[mealNameIndex]) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a function call getCardNumericValues that get the card numeric value
function getCardNumericValues(card) { switch(card.value) { case "Ace": return 1; case "Two": return 2; case "Three": return 3; case "Four": return 4; case "Five": return 5; case "Six": return 6; case "Seven": return 7; case "Eight": return 8; case "Ni...
[ "function getCardNumericValue(card) {\n\tswitch(card.values) {\n\t\tcase \"Ace\":\n\t\treturn 1;\n\t\tbreak;\n\t\tcase \"Two\":\n\t\treturn 2;\n\t\tbreak;\n\t\tcase \"Three\":\n\t\treturn 3;\n\t\tbreak;\n\t\tcase \"Four\":\n\t\treturn 4;\n\t\tbreak;\n\t\tdefault:\n\t\treturn 10;\n\t\tbreak;\n\t}\n}", "function ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for updating an appointment given its id
function updateAppointment(id) { const url = baseURL + "/appointment/" + id; $.ajax({ type: 'PUT', url: url, contentType: 'application/json', data: formToJSON(), success: function(data, textStatus, xhr) { alert(xhr.responseText); }, error: function(xhr, textStatus, errorThrown) { alert('updateA...
[ "updateAppointment(id) {\n return axios.put(`/api/appointments/${id}`);\n }", "function updateAppointment(id) {\n\t\tvar url = baseURL + \"/appointment/\" + id; // URL of service, notice that ID is part of URL path\n\t\tvar description = $(\"#editAppointmentDescription\").val();\n\t\tvar date = $(\"#editAppoi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paging query alarm group list
getAlertgroupP ({ state }, payload) { return new Promise((resolve, reject) => { io.get(`alert-group/list-paging`, payload, res => { resolve(res.data) }).catch(e => { reject(e) }) }) }
[ "static allAdmPagination(page = 1, query = '') {\n let req = request.get(`/products/pagination_admin/${page}.json?${query}`).set('AUTHORIZATION', `Bearer ${sessionStorage.jwt}`)\n return req.then(response => {\n return response\n }, error => {\n return error\n })\n }", "function searchGroup...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates h = f g Can overlap h with f or g. Preconditions: |f| bounded by 1.12^26,1.12^25,1.12^26,1.12^25,etc. |g| bounded by 1.12^26,1.12^25,1.12^26,1.12^25,etc. Postconditions: |h| bounded by 1.12^25,1.12^24,1.12^25,1.12^24,etc. Notes on implementation strategy: Using schoolbook multiplication. Karatsuba would save...
mul(f, g) { const f0 = BigInt(f.data[0]); const f1 = BigInt(f.data[1]); const f2 = BigInt(f.data[2]); const f3 = BigInt(f.data[3]); const f4 = BigInt(f.data[4]); const f5 = BigInt(f.data[5]); const f6 = BigInt(f.data[6]); const f7 = BigInt(f.data[7...
[ "mul(f, g) {\r\n const f0 = bigInt__default[\"default\"](f.data[0]);\r\n const f1 = bigInt__default[\"default\"](f.data[1]);\r\n const f2 = bigInt__default[\"default\"](f.data[2]);\r\n const f3 = bigInt__default[\"default\"](f.data[3]);\r\n const f4 = bigInt__d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
manufacturer, model, price,screenSize, operatingSystem TODO id??
constructor(manufacturer, model, price, screenSize, operatingSystem) { super(manufacturer, model, price); this.screenSize = screenSize; this.operatingSystem = operatingSystem; }
[ "constructor(manufacturer, model, price) {\n\t\t\tthis.manufacturer = manufacturer;\n\t\t\tthis.model = model;\n\t\t\tthis.price = price;\n\t\t\tthis._id = getNextId();\n\t\t}", "function processOS(id, o, system, manager, num) {\n var name;\n if(o == 'Red Hat 6 64-bit') {\n name = 'RedHat';\n } el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
discover component with most ports (bigger) then go on both sides and assign components to columns
function findBiggestComponent(nodes) { // find component with biggest no of // ports var biggestComponent = null; nodes.forEach(function(c) { if (biggestComponent) { var portCnt = biggestComponent.inputs.length + biggestComponent.outputs.length; var thisCompPortCnt = c.inputs.length + c.outputs.l...
[ "_count_ports_workaround ()\n\t{\n\t\t// first we fill this._poss with just the ports\n\t\tthis._patch.split(\"\\n\").forEach((line)=>{\n\t\t\tlet m = line.match(/^#X connect (.*);$/);\n\t\t\tif (!m) return;\n\t\t\tlet d = m[1].split(\" \");\n\t\t\tlet source = parseInt(d[0]);\n\t\t\tlet outlet = parseInt(d[1]);\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the commandPrefix variable
function loadCommandPrefix() { pool.getConnection(function(err, connection) { connection.query("SELECT * FROM commandprefix", function(err, results) { for(var i in results) { commandPrefix["server" + results[i].serverID] = results[i].commandPrefix; } console.log(localDateString() + " | " + colors.green...
[ "initializePrefix(){\n if(this._sigil && !this._prefix.includes(this._sigil))\n this._prefix = this._sigil + this._prefix;\n }", "function setPrefix(value) {\n prefix = value;\n checkForCommand();\n }", "set prefix(prefix) {\n prefix = prefix.trim();\n if (pre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
name : fnRemoveOption description : remove option item author : minyeong kim
function fnRemoveOption(e) { //remove option item e.parentNode.remove(); //reset option num var optionNum = document.getElementsByClassName('option-num'); for(var i=0;i<optionNum.length;i++){ optionNum[i].innerHTML = i+1; } }
[ "function fnRemoveFabric(e) {\n\n //remove option item\n e.parentNode.remove();\n\n}", "removeOption(value, silent) {\n\t const self = this;\n\t value = get_hash(value);\n\t self.uncacheValue(value);\n\t delete self.userOptions[value];\n\t delete self.options[value];\n\t self.lastQuery = n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows modal with cover letter.
function showModal(text) { document.getElementsByClassName("modal")[0].style.display = "flex"; document.getElementById("cover-letter").innerHTML = text; }
[ "function showCover(cover){\n //injetar imagem\n const imgCover = querySelector(\"#imgCover\")\n imgCover.src = cover\n //display da janela\n const dlgCover = querySelector(\"#dlgCover\")\n dlgCover.showModal()\n }", "function showModal() {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Operation: $max Only updates the field if the specified value is greater than the existing field value.
function fieldMax(doc, field, value) { // Requires(doc !== undefined) // Requires(field !== undefined) // Requires(value !== undefined) fieldSet(doc, field, value, function (oldValue) { if (oldValue === undefined) ...
[ "set _max(value){Helper$2.UpdateInputAttribute(this,\"max\",value)}", "function max(document, update) {\r\n var fields, i;\r\n\r\n if (update.$max) {\r\n fields = Object.keys(update.$max);\r\n for (i = 0; i < fields.length; i++) {\r\n if (update.$max[fields[i]] >...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iterating to find the most searched zip code
function mostVisitedZip(zipArray, length){ // sorting the array using a built-in function zipArray.sort(); // find the maximum frequency by visiting each array element once let maxCount = 1, result = zipArray[0]; let actualCount = 1; for (let i = 1...
[ "function zipBinarySearch(zips, target) {\n let start = 0;\n let endIdx = zips.length - 1;\n let idx;\n let currEl;\n target = Number(target);\n\n while (start <= endIdx) {\n idx = (start + endIdx) / 2 | 0;\n currEl = Nu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should only be used when there's no jsconfig/tsconfig at all
function getDefaultJsConfig() { return { compilerOptions: { maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }, // Necessary to not flood the initial files // with potentially completely unrelated .ts/.js files: ...
[ "function fixTsConfig() {\n var tsConfig={}, tsFile = '../../../tsconfig.json';\n if (fs.existsSync(tsFile)) {\n tsConfig = require(tsFile);\n }\n if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.typeRoots) {\n tsConfig.compilerOptions = {\n target: \"es5\",\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Quantity slected from the drop down list
function changeQuantity() { var number = document.getElementById("quantityList"); var quantity = number.value; return quantity; } // end function
[ "function setQuantity() {\n var quantityOptions = '', maxQuantityOptions = (parseInt(product['dvdQuantity']) >= 5) ? 5 : parseInt(product['dvdQuantity']);\n\n if (maxQuantityOptions !== 0) {\n for (i = 0; i < maxQuantityOptions; i++) {\n quantityOptions += '<b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set X translation of target.
set targetTranslateX(value) { const newValue = (Math.round(+value) || 0).toString(); this.setAttribute('target-translate-x', newValue); }
[ "function xTranslateSetter(target, value){\n target.setAttributeNS(null, \"transform\", \"translate(\" + value + \", 0)\");\n}", "function setTargetTransformX(elem, x) {\n setTargetTransform(elem, x, 0);\n }", "function yTranslateSetter(target, value){\n target.setAttributeNS(null, \"transform\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy image as data uri.
copyImageAsDataUri() { const { mimeType, text, encoding } = this.selectedRequest.responseContent.content; getString(text).then(string => { let data = formDataURI(mimeType, encoding, string); copyToClipboard(data); }); }
[ "function imgToDataUrl(img) {\n var $img = artoo.$(img);\n\n // Do we know the mime type of the image?\n var mime = imageMimes[getExtension($img.attr('src')) || 'png'];\n\n // Creating dummy canvas\n var canvas = document.createElement('canvas');\n canvas.width = $img[0].naturalWidth;\n canvas....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eyeballs swinging up and down
function swingUpDown(ctx) { ctx.beginPath(); ctx.moveTo(eye1_x, eye1_y); ctx.arc(eye1_x, eye1_y, eye_radius, 0, Math.PI*2); ctx.fill(); ctx.beginPath(); ctx.moveTo(eye2_x, eye2_y); ctx.arc(eye2_x, eye2_y, eye_radius, 0, Math.PI*2); ctx.fill(); eye1_y += eye_speed; eye2_y += eye_speed; if(eye1_y >= eye1_...
[ "edgeBounce() {\n if (this.y > windowHeight || this.y < 0) {\n \t \t this.yspeed = -this.yspeed;\n \t}\n\n if (this.x > windowWidth || this.x < 0) {\n this.x = width/2;\n//recreated\n this.xspeed = 0;\n }\n\n}", "function setSway(){\r\n if (SWAYY > -300){\r\n --SWAYY;\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: verifyValidLanguage Description: verifyValidLanguage verifies if the language passed is an element in the array suppportedLanguages. If it is then language is returned. If it is not a supported language then 'en' is returned. The language can be composed of only a language code (i.e. 'en', 'fr', ...) or a languag...
function findSupportedLanguage(language, suppportedLanguages) { // English is the default if the language passed in is unsupported var defaultLanguage = 'en'; if (language == null || language == 'ERROR') { return defaultLanguage; } var lang = language; var...
[ "function validateLanguage( lang ){ return languages.indexOf( lang ) > -1 ? lang : ''; }", "validateLanguage(language) {\n const validLanguages = ['en', 'es', 'de', 'fr', 'ja', 'pt-br', 'ru', 'zh'];\n let valid = (!validLanguages.find(lan => lan === language)) ? false : true;\n return valid;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows the tab with passed content div id..paramter tabid indicates the div where the content resides
function showTab(tabId) { $('#TabAdm a[href="#' + tabId + '"]').tab('show'); }
[ "function showTab(tabId) {\r\n $('#contentwrapper .nav-tabs a[href=\"#' + tabId + '\"]').tab('show');\r\n}", "function showTab(tabId) {\n $('#mainTab a[href=\"#' + tabId + '\"]').tab('show');\n}", "function showTab( tabId )\n{\n $currentTab = $('#myTab a[href=\"#' + tabId + '\"]');\n $currentTab.tab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawharry() Draw the harry as an ellipse with alpha based on health
function drawharry() { image(harryImage, harryX, harryY); }
[ "function setupharry() {\n harryX = 4*width/5;\n harryY = height/2;\n harryHealth = harryMaxHealth;\n}", "function drawHealth() {\n ctx.lineWidth = 1\n // Draw empty health circles\n for (let i = hero.maxhealth; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'white', 'black', 0, 2 * Math.PI, [5, 5])...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to post an array onebyone; returns successful elements.
function _safeArrayPost(array, url, callback) { var x = 0; var successfulElements = []; if(array.length == 0) { callback([]); return; } function loopArray(array) { _postRemote(array[x],url,function(response) { if(response == 200) successfulElements.push(array[x]); x++...
[ "function _safeArrayPost(array, url, callback) {\n var x = 0;\n var toPop = [];\n var toRetry = [];\n var toReplace = [];\n var noChange = [];\n\n if(array.length == 0) { callback({\"toPop\": [], \"toRetry\": [], \"toReplace\": [], \"noChange\": []}); return; }\n function loopArra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note: monitorPrinting() still works but is too complicated and outdated. Instead create a JavaScript function called "jzebraDonePrinting()" and handle your next steps there.
function monitorPrinting() { var applet = document.jzebra; if (applet != null) { if (!applet.isDonePrinting()) { window.setTimeout('monitorPrinting()', 100); } else { var e = applet.getException(); //alert(e == null ? "Printed Successfully" : "Exception occured: " + e.getLocalizedM...
[ "function jzebraDonePrinting() { }", "function monitorPrinting() {\n\tvar applet = document.jZebra;\n\tif (applet != null) {\n\t\tif (!applet.isDonePrinting()) {\n\t\t\twindow.setTimeout('monitorPrinting()', 100);\n\t\t} else {\n\t\t\tvar e = applet.getException();\n\t\t\talert(e == null ? \"Printed Successfully\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redraws dependencies when a dependency has changed
onDependencyChange({ action, record, records }) { const me = this; if (!me.scheduler.rendered || me.disabled) { return; } switch (action) { case 'dataset': me.dependencyGridCache = {}; // dataset should fall through to add after clearing the cache // eslint disable no-f...
[ "async onDependencyChange({\n action,\n record,\n records\n }) {\n const me = this,\n {\n client\n } = me; // bail out in case:\n // - client is not painted yet\n // - client has rendering suspended\n // - or we are finalizing the propagation caused by project loading\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Created By: Jared Nichols Date: 12192016 Purpose: This postflow action dictates whether 703: Domestic Violence Shelters is selected under GQTypes in order to determine the flow. User Story: US596.
function postFlowAction$CollectGQInformation() { /* retrieve data */ try { var locationAddress = pega.ui.ClientCache.find('pyWorkPage.BCU.SelectedUnitPage.LocationAddress'); var workPage = pega.ui.ClientCache.find('pyWorkPage'); var gqCategory = locationAddress.get('GQCategory') ? locationAddress.get(...
[ "function EnumCB_RefusalReason_POST() { \n \n /*Get pages */\n var questFlags = pega.ui.ClientCache.find(\"pyWorkPage.QuestFlags\");\n var responsePage = pega.ui.ClientCache.find(\"pyWorkPage.Respondent.Response\")\n var refusalReasonPG = pega.ui.ClientCache.find(\"pyWorkPage.Respondent.RefusalReason\");\n \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove all users from conversation....
removeAllUserFromConversation(conversation_id, users) { console.log() var q = knex('conversationUser').where({'conversation_id': conversation_id}).whereIn('user_id', users).update({ 'date_left': new Date().toISOString().slice(0, 19).replace('T', ' ') }).toString(); console.log(q, "users array") return th...
[ "function removeAllUsers() {\n User.remove({}, function(err) {\n //console.log(\"ALL USERS REMOVED\");\n if (err) {\n throw err;\n }\n });\n}", "static clearOldConversations(bot, usersWithOldConvos) {\n\t\t//iterate the users\n\t\tusersWithOldConvos.forEach(async (user) => {\n\t\t\tconst conversat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the ID path to the configured form.
function getConfiguredFormPath($scope) { var path = $scope.conFormPath; if (!path) { path = []; } return path; }
[ "form_id()\n\t\t\t{\n\t\t\t\treturn form_id(this.props)\n\t\t\t}", "getFormId() { return `ib-${this.cmdName}-details-form`; }", "function getFormId() { return window.location.hash.substring(1); }", "getFormId() {\n if (this.payload.form) {\n // return value of `form` field\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the currently referenced [[Coat]] instance
getCoat() { return this.coat; }
[ "createCoatMatchingShader() {\n let coat = new (this.shaderType.getCoat())();\n return coat;\n }", "function getCurrentConnCell()\n{\n var modelId = currentObject.attr(\"model-id\");\n cell = graph.getCell(modelId);\n return cell; \n}", "getObject(){\n return this.chemical...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler for incoming sensor values.
handleSensorValue(value, id) { if (!this.sensors[id]) return; this.log.debug(`got value ${value} from sensor ${this.sensors[id].address}`); this.setStateAsync(id, { ack: true, val: value }); }
[ "function handleSensorDataMessage(macAddress, payload) {\n\t// Parse sensor data, convert to ints\n var sensorValues = payload.split(',').map(value => parseInt(value));\n\n // We're expecting five values: power, temp, light, (eventually status).\n if (sensorValues.length !== 3) {\n throw new Error(`Not enough...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User message/command processing ExecuteClientMessage
function ExecuteClientMessage(client, msg) { var serverid = msg.readInt32(); client.messageAcknowledge = msg.readInt32(); if (client.messageAcknowledge < 0) { // Usually only hackers create messages like this // it is more annoying for them to let them hanging. return; } client.reliableAcknowledge = msg.re...
[ "function processCommand(message) {\n\n\t\t\t\t\t}", "executeMessage(message){\n this.instance.executeMessage(message);\n }", "execute(message) {\n // Send Message\n message.channel.send('Welcome employer! We currently have \"x\" employees, please state the minimum age, location and time...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks user answer selected. If correct, increases score. Changes STORE value to indicate if answer is correct or wrong. If no answer selected, display alert message. Dependancy: getCorrectAnswer updateUserScore
function checkAnswer() { //console.log('Answer is being checked') const currentAnswer = $( "input:checked" ).val(); const correctAnswerText = getCorrectAnswer(); if (currentAnswer === correctAnswerText) { STORE.currentAnswer = 'correctAnswer'; updateUserScore(); } else { ...
[ "function checkAnswer() {\n const qIdx = currentQ - 1;\n const correct = STORE[qIdx].answer;\n const answer = $(\"input[name=option]:checked\").val();\n const selected = $(\".selected\");\n\n if (!answer) {\n return alert(\"Please select an answer before submitting\");\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the address from local storage
function getAddressFromLocalStorage (mapped = true) { if (window.localStorage) { const storedLocation = window.localStorage.getItem(storedLocationKey); if (storedLocation) { return mapped ? getMappedLocalStorageAddress(JSON.parse(storedLocation)) : JSON.parse(storedLocation); } ...
[ "function getAddress() {\n 'use strict';\n var address = sessionStorage.getItem('address');\n return JSON.parse(address);\n }", "function getAddressFromLocalStorage(key) {\n return localStorage.getItem(key);\n}", "function loadAddress(){\n if(localStorageEnabled()){\n var localStr =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function about Unpaid invoice list
function Unpaid_invoice() { $("#InvoiceTableInfo tbody").html(''); let userData = { "action": "load_Unpaid_list" } let tableBody = ''; let html = ''; $.ajax({ url: "../api/invoice.php", dataType: "JSON", method: "POST", ...
[ "function getInvoiceList() {\n var criteria = {\n dVendno: base.criteria.vendorNumber,\n dPostdt: base.criteria.postDate\n };\n\n DataService.post('api/ap/asapentry/apemagetinvoices', { data: criteria, busy: true }, function (data) {\n if (data) {\n base.datasetInvo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve a namespace prefix.
resolve(prefix) { var _a, _b; let uri = this.topNS[prefix]; if (uri !== undefined) { return uri; } const { tags } = this; for (let index = tags.length - 1; index >= 0; index--) { uri = tags[index].ns[prefix]; if (uri !== undefined) { ...
[ "resolve(prefix) {\n var _a, _b;\n let uri = this.topNS[prefix];\n if (uri !== undefined) {\n return uri;\n }\n const {tags: tags} = this;\n for (let index = tags.length - 1; index >= 0; index--) {\n uri = tags[index].ns[prefix];\n if (uri !== undefined) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Subject and the ability to add, remove or notify observers on the observer list:
function Subject(){ this.observers = new ObserverList(); }
[ "function Subject () {\n this.observers = new ObserversList();\n}", "function Subject() {\n this.observers = new ObserverList();\n}", "function Subject() {\n this.observers = [];\n }", "function Subject() {\n this.observers = [];\n}", "subscribe(observer) {\n this.observers.push(observer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is used to stop the autosave process. If an autosave request is currently being processed, this function does not stop it. It only stops the timer from being reset to run again by those processes.
function stopAutoSaveTimer(index) { if (autoSaveTimers[index] != null) clearTimeout(autoSaveTimers[index]); autoSaveTimers[index] = null; }
[ "function stopTimer() {\n if (timeoutStore) {\n clearInterval(timeoutStore);\n uploadTime();\n }\n }", "stopBackupTimer(){\n if(this.timerRef===null) return;\n clearInterval(this.timerRef);\n this.timerRef=null;\n }", "function stop () {\n stopTimerAndResetCounters();...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets all the images back to the down image
function resetAll(){ for(var x in images){ images[x].src = "img/down.png"; } }
[ "function resetImages(){\n resetButtonHolders();\n changeImageBackTank();\n changeImageBackAA();\n changeImageBackPlane();\n changeImageBackUCS();\n}", "function ResetImages() {\n\tfor(var i = 0; i < sourceFiles.length; i++) {\n\t\tsourceFiles[i].posX = NaN;\n\t\tsourceFiles[i].posY = NaN;\n\t\tsou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the html of the page with all the mission data (i.e., rank boxes with mission buttons).
function renderMissions() { if (isListActive()) { // A bit of a hack. List-mode does its own thing. renderListStyleMissions(); return; } let missionHtml = ""; let eventScheduleInfo; let sortedRanks; if (currentMode == "event") { eventScheduleInfo = SCHEDULE.Schedule.find(s => s.LteI...
[ "function renderMissions() {\n if (isListActive()) {\n // A bit of a hack. List-mode does its own thing.\n renderListStyleMissions();\n return;\n }\n \n let missionHtml = \"\";\n \n let missionEtas = getMissionEtas();\n \n let sortedRanks;\n if (currentMode == \"event\") {\n sortedRanks = Obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An utility method allowing to extract latitude/longitude from the specified attribute of the given element
function getLatLng(e, attr) { var s = e.attr(attr); if (!s) return null; var array = s.split(/;/); var point = L.latLng(array); return point; }
[ "function getLatLonFromVCard(el) {\n var els = el.getElementsByTagName(\"*\");\n for (var i = 0, j = els.length; i<j; ++i) {\n if (els[i].className.indexOf(\"geo\") !== -1) {\n var coords = els[i].title.split(\";\");\n return new L.LatLng(parseFloat(coords[0]),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make an input inside of a td element with given value and checked.
function makeTD(type, value, checked) { var td = document.createElement('td'), inp = document.createElement('input'); inp.type = type; if (value) inp.value = value; if (checked) inp.checked = checked; td.insertBefore(inp, td.firstChild) return td; }
[ "function setInputValue(input, value) {\r\n\tif (input.attr('type') === 'checkbox'){\r\n\t\tinput.prop('checked', value);\r\n } else {\r\n input.val(value);\r\n }\r\n}", "function input_checkbox(field){\n //\n //Inherit the input element\n input_element.call(this, field);\n \n //Settin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grants read/write permissions for this bucket and it's contents to an IAM principal (Role/Group/User). If an encryption key is used, permission to use the key for encrypt/decrypt will also be granted.
grantReadWrite(identity, objectsKeyPattern = '*') { const bucketActions = perms.BUCKET_READ_ACTIONS.concat(perms.BUCKET_WRITE_ACTIONS); const keyActions = perms.KEY_READ_ACTIONS.concat(perms.KEY_WRITE_ACTIONS); return this.grant(identity, bucketActions, keyActions, this.bucketArn, this.arnForObj...
[ "grantRead(grantee) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_iam_IGrantable(grantee);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.grantRead);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens for all translation data/files to be loaded and ready and then fires "dataReady" event.
function setupTranslationsReadyListener () { IBM.common.util.queue.push(function(){ return translations.v18.ready; }, function(){ // Merge all the translations into our local single data object "me.data" (public). // Keep any existing ones (merge in first) in case some other main module wants to share this...
[ "function onTranslationsLoad() {\n evme.info(NAME, 'all translations loaded, parse and fire load event');\n\n if (!localStrings) {\n localStrings = {};\n }\n if (!defaultStrings) {\n defaultStrings = {};\n }\n\n renderTranslations();\n\n // fire a custom event alerti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the authToken to return the logged in user's public key
getPublicKey() { const token = this.getAuthKey(); if (!token) return null; const content = window.atob(token.split('.')[1]); return JSON.parse(content).public_key; }
[ "parsePublicToken(token) {\n const parts = token.split('.');\n /**\n * Ensure the token has two parts\n */\n if (parts.length !== 2) {\n throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);\n }\n /**\n * Ensure the fir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle when the user adds a new task.
handleAddNewTask() { this.addNewTask(this.state.newTaskName); }
[ "async function handleAddNewTask() {\n const stDate = startDate ? moment(startDate, true) : null;\n const edDate = endDate ? moment(endDate, true) : null;\n\n // Validate user input (task name, start date and end date are mandatory)\n if (!name) {\n setError(\"Please add a task name.\");\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the list of choices, calling makeChoices.
updateChoices() { let value = this._widgetCall('getValue') this._widgetCall('updateChoices') if (value != null) { this._widgetCall('setValue', value) } }
[ "function updatechoices(result, choices) {\n if (result.length) {\n if (choices.length > result[0].length) return;\n if (choices.length < result[0].length) result.length = 0;\n }\n result.push(choices);\n}", "function changeChoices() {\n for (let j = 0; j < choicesGroup.children.length; j++) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that enables or disables child inputs of a "checkable" based on whether the checkable input (a radio button or checkbox) is checked. `this` must refer to the actual input element representing the checkable. Called from a click handler installed globally, and also when a modal popup is shown (see effRegModal.js...
function enableChildren() { console.log('Checkable.enableChildren'); var $children = $(this).parents('.pnl-Checkable').find('input,select,textarea').not(this); if (this.checked) { // TODO only re-enable if we don't have the 'disabled' class $children.not('.disabled').removeAttr('disabled'); $child...
[ "function activer_checkbox()\n{\n /*$('input:checkbox').iCheck({\n checkboxClass: 'icheckbox_square-green',\n }).on('ifClicked', function(ev){\n $(this).parent().click();\n });*/\n\n $('input:radio').iCheck({\n radioClass: 'iradio_square-green',\n });\n}", "checkboxChangeListen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cambia el estado de las tareas o las elimina
function accionesTareas(e) { e.preventDefault(); // console.log(e.target); if (e.target.classList.contains('fa-check-circle')) { if (e.target.classList.contains('completo')) { e.target.classList.remove('completo'); cambiarEstadoTarea(e.target, 0); } else { ...
[ "eliminarCompletados(){ //se van a eliminar todas las tareas que tengan en el campo completado = true.\n this.todos = this.todos.filter( tarea => !tarea.completado ); //necesito todas las tareas que NO esten completadas, de esta forma se mantienen\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If `str` is in valid 3digit hex format with prefix, returns an RGB color (with alpha 100). Otherwise returns undefined.
function _hex3(str) { if ('#' === str[0] && 4 === str.length && /^#[\da-fA-F]{3}$/.test(str)) { return { r: parseInt(str[1] + str[1], 16), g: parseInt(str[2] + str[2], 16), b: parseInt(str[3] + str[3], 16), a: MAX_COLOR_ALPHA }; } }
[ "function _hex3(str) {\n if ('#' === str[0] && 4 === str.length && /^#[\\da-fA-F]{3}$/.test(str)) {\n return {\n r: parseInt(str[1] + str[1], 16),\n g: parseInt(str[2] + str[2], 16),\n b: parseInt(str[3] + str[3], 16),\n a: MAX_COLOR_ALPHA\n };\n }\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the texts for the "userjoins" section depending on the event's category (past, current or upcoming).
function setJoinsItems(obj, event_category) { event_category = obj.closest('.social_data_all').attr('data-category').substring(0, 11); if (event_category == 'past_events') { obj.closest('.social_data_all').find("#side_panel_join_text").html(t("did you join?")); } else { obj.closest('.social...
[ "function setJoinsItems(obj, event_category) {\n event_category = obj.closest('.social_data_all').attr('data-category').substring(0, 11);\n\n if (event_category == 'past_events') {\n obj.closest('.social_data_all').find(\"#side_panel_join_text\").html(\"did you join?\");\n } else {\n obj.clos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
===================================================================================================== This function returns the names of all strong beverages (i.e. all that contain a percentage of alcohol higher than the strength given in percent.
allStrongBeverages(strength) { // Using a local variable to collect the items. // var collector = []; // The DB is stored in the variable DB2, with "spirits" as key element. If you need to select only certain // items, you may introduce filter functions in the loop... see the te...
[ "function resistanceNames(data){\n const weight = getWeightTotals(data);\n const names = weight.combinedPounds.map(exercise => exercise.name);\n return names;\n}", "function getBeverages() {\n return getItem('beverages');\n}", "getstrengtheffect() {\n var totalstrength = 0;\n for (var buff in th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changeColor method changes the color and animation of the marker element that is passed in based on the value of marker clicked. Input: marker Changes color to Green when marker is clicked, does a bounce animation for 5 secs Changes color to red on initialization and when infoWindow is closed
function changeColor(marker) { if(marker.clicked===true){ map.panTo(marker.getPosition()); marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png'); marker.setAnimation(google.maps.Animation.BOUNCE); setTimeout(function(){marker.setAnimation(null);},3000); setTimeout(function(){mar...
[ "function markerColor(e) {\n if (whoseTurn === 0) {\n e.target.style.color = \"blue\";\n } else {\n e.target.style.color = \"red\";\n }\n}", "setColor_(newColor) {\n this.myMarker_.setColor(newColor);\n }", "function markerColor(marker, changecolor) {\n (function() {\n for (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start each individual Worm
function startWorms() { for(var i = 0; i < colors.length; i++) { if(players[i]) startWorm(colors[i]); } drawScore(); }
[ "start() {\n this._scheduleSpawnMonster(1, 5, 'spawnMonster1');\n this._scheduleSpawnMonster(2, 5, 'spawnMonster2');\n this._scheduleDespawnMonster(5, 15, 'despawnMonster');\n }", "function launchMoreFireworks() {\n for(var i = 0; i < numberRockets / 2; i++)\n {\n launch();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send out projstat for every projectile to everyone (for creation on connect)
function emitAllProjectiles(targetID){ var projectiles = ships.getActiveProjectiles(); var out = {}; for (var id in projectiles){ var proj = projectiles[id]; out[id] = { shipID: proj.shipID, status: 'create', pos: proj.pos, noSound: true, // Don't play the sound for bulk create ...
[ "function emitProjectilePositionUpdates(){\n var projectiles = ships.getActiveProjectiles();\n var out = {};\n\n // Filter out non-moving projectiles, and simplify output to just positions\n for (var i in projectiles) {\n var proj = projectiles[i];\n if (proj.data.speed){\n out[i] = {\n x: Mat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
main method that displays a specified page for a short time in an iFrame, captures the image and gives it to an OCR that shows the recognized text. logs occuring errors to console.
function main(){ preloadExternalPage(getUrl()) .then(getScreenCapture) .then(function(stream){ return showExternalPage(200).then(function(){ return stream; }); // show the page for at least 200 ms }) .then(getImageFromStream) .then(function(image){ re...
[ "function running() {\n // Display the webcam\n image(video, 0, 0, width, height);\n\n // Check if there currently predictions to display\n if (predictions) {\n // If so run through the array of predictions\n for (let i = 0; i < predictions.length; i++) {\n // Get the object predicted\n let obje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var p2Moves = document.getElementById("p2Moves"); p2Moves.addEventListener("click", selectItem,true);
function selectItem(e) { for (var i = 0; i < e.currentTarget.parentNode.children.length; i++) { e.currentTarget.parentNode.children[i].classList.remove("selected"); } e.currentTarget.classList.add("selected"); console.log($(e.currentTarget).children().eq(1).text()); ...
[ "function selecionarItem(event) {\n TrocarSelecionado();\n event.target.classList.add('selected');//adicionar a classe selected\n \n //essa classe é colocada \n}", "function clickOptiontoSelect(){\n\n}", "function itemClicked(event)\n{\n \n var list = document.getElementById(\"list\").object;\n var b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines a CloudWatch event rule which triggers for repository events. Use `rule.addEventPattern(pattern)` to specify a filter.
onEvent(id, options = {}) { const rule = new events.Rule(this, id, options); rule.addEventPattern({ source: ['aws.codecommit'], resources: [this.repositoryArn], }); rule.addTarget(options.target); return rule; }
[ "onCommentOnCommit(id, options = {}) {\n const rule = this.onEvent(id, options);\n rule.addEventPattern({ detailType: ['CodeCommit Comment on Commit'] });\n return rule;\n }", "onEvent(id, options = {}) {\n const rule = new events.Rule(this, id, options);\n rule.addEventPatte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an Azure Storage Client.
constructor( accountName = requiredParameter('AzureStorageAdapter requires an account name'), container = requiredParameter('AzureStorageAdapter requires a container'), { accessKey = '', directAccess = false } = {} ) { this._accountName = accountName this._accessKey = accessKey this._con...
[ "createClient() {\n switch (this.config.type) {\n case 'azureBlob': return new __1.AzureBlobClient(this.config);\n default: throw new Error(`NotImplemented`);\n }\n }", "async function storageAccountCreate() {\n const subscriptionId = process.env[\"STORAGE_SUBSCRIPTION_ID\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if this token contains any text
get containsText(){ return this.textContent.trim().length > 0; }
[ "isEmpty() {\n const text = this.editorState.getCurrentContent().getPlainText();\n return !text || _.trim(text).length === 0;\n }", "static containsAnyTokens (string) {\n\t\treturn !!Object.keys(PeerUtilV0._getTokensFromText(string)).length;\n\t}", "function checkText( bodyText, sigText ){\r\n\tvar ret =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load Gifs Returns: GIFImages[]
function loadGifImages(gifsData) { return Promise.all(gifsData.map((gifData) => loadGIFImage(gifData))).catch( (error) => { console.error(error); } ); }
[ "function loadGIF() {\n var oReq = new XMLHttpRequest()\n oReq.open('GET', url.value, true)\n oReq.responseType = 'arraybuffer'\n\n oReq.onload = function(oEvent) {\n var arrayBuffer = oReq.response // Note: not oReq.responseText\n if (arrayBuffer) {\n gif = parseGIF(arrayBuffer)\n var frames = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcao que limpa todos os conteudos carregados na edit_pet page, deixando apenas a contentSection renderizada na tela.
function clearEditPetPage(){ $('#contentSection').empty(); removeCSS('edit_pet'); }
[ "sectionDescontos() {\n\t\t\tconst $listItem = $('#descontos .list-items'),\n\t\t\t\t$overlay = $('.overlay'),\n\t\t\t\t$selectedItem = $('.item-selected'),\n\t\t\t\ttab = new Tab('descontos'),\n\t\t\t\tslickConfig = {\n\t\t\t\t\tslidesToShow: 4,\n\t\t\t\t\tslidesToScroll: 1,\n\t\t\t\t\tinfinite: true,\n\t\t\t\t\tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flash Detection // INDEX PAGE Shows swfs depending on screen size
function showFlash(){ var SWidth = screen.width; var stmt_swf = ""; if (!useRedirect) { if(hasRightVersion) { if (SWidth > 800) { stmt_swf += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" wi...
[ "function showFlashISeminar(id,ref,vWidth,vHeight)\n{\n if(!vHeight) vHeight = 600;\n if(!vWidth) vWidth = 800;\n var vTop = Math.ceil((screen.availHeight - vHeight)/2) - 25;\n var vLeft = Math.ceil((screen.availWidth - vWidth)/2);\n if(screen.width <= 800) {\n if(screen.width < 700) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prompts for riddle answers and updating score
function riddleFunc(){ var txt; var riddleAnswer = prompt("Your answer, please..."); if (riddleAnswer.toLowerCase() == "fire"){ txt = currentPlayer.name + " "+ ", well done. Correct answer and you have earned a point!"; if(currentPlayer == player1){ p1RiddleScore +=1; } else if(currentPl...
[ "function answerIsCorrect () {\r\n feedbackForCorrect();\r\n updateScore();\r\n}", "function updateScoreForCorrectAnswer() {\n score = score + question[0].value;\n document.querySelector('h2#score').innerText = score.toString();\n}", "function submitAnswer() {\r\n// x,y,z represent the input radio butto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the total number of traffic traces from a mesh
getTrafficTracesFromMeshTotalCount ({ commit }, mesh) { return api.getAllTrafficTracesFromMesh(mesh) .then(response => { const total = response.items.length commit('SET_TOTAL_TRAFFIC_TRACES_COUNT_FROM_MESH', total) }) .catch(error => { console.e...
[ "getTrafficRoutesFromMeshTotalCount ({ commit }, mesh) {\n return api.getAllTrafficRoutesFromMesh(mesh)\n .then(response => {\n const total = response.items.length\n\n commit('SET_TOTAL_TRAFFIC_ROUTES_COUNT_FROM_MESH', total)\n })\n .catch(error => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries the DB for issue statistics such as number of comments, followers, and views
function getStats(thisIssueId, callback) { // find number of followers var queryFollowers= "SELECT count (*) FROM follows WHERE issue_id = " + thisIssueId; // find number of comments var queryComments= "SELECT count (*) FROM comments WHERE issue_id = " + thisIssueId; // find view count var queryViews= "SELECT vi...
[ "getBugCounts() {\n for (const query of this.config.bugQueries) {\n // Use an inner `async` so the loop continues\n (async () => {\n const { bug_count } = await this.getJSON(`${query.url}&count_only=1`);\n\n if (bug_count !== undefined) {\n query.count = bug_count;\n thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ADVANCED MENU / DASHBOARD
function advancedMenu() { if (advancedMenuIsOpen) { closeAdvancedMenu(); } else { openAdvancedMenu(); } }
[ "function menuOptions() {}", "function DWMenu() {}", "function menuControls() {\n\n\t}", "function onOpen() { CUSTOM_MENU.add(); }", "function showMenu() {\n\t\tshowStats();\n\t\tsuper.showMenu();\n\t}", "function Venus() {}", "function showMainMenu() {\n\tconsole.log('What would you like to do today: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorders the items by their indexes when the accordion is initialized.
_reorderItemsByIndex() { const that = this; let items = that.enableShadowDOM && that.shadowRoot ? that.shadowRoot.querySelectorAll('jqx-accordion-item') : that.getElementsByTagName('jqx-accordion-item'), itemsArray = Array.from(items), hasInitialIndexes = false, items...
[ "_reorderItemsByIndex() {\n const that = this;\n let items = that.enableShadowDOM && that.shadowRoot ? that.shadowRoot.querySelectorAll('smart-accordion-item') : that.getElementsByTagName('smart-accordion-item'),\n itemsArray = Array.from(items),\n hasInitialIndexes = false,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event handler for when a geoJson layer is zoomed into.
function zoomInHandler(e) { plugin.updateStaticLayers(); }
[ "function zoomOutHandler(e) {\n var geoJsonLayer = e.target;\n // For desktop, we have to make sure that no features remain\n // highlighted, as they might have been highlighted on mouseover.\n geoJsonLayer.eachLayer(function(layer) {\n if (!plugin.selectionLegend.isSe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: tryReadVariableName Tries to read the name of a variable starting at the given index in the string. If a variable name can be read, it is returned. If not, this function returns null.
function tryReadVariableName(input, index) { /* Need to start with a letter or underscore. */ if (!/[A-Za-z_]/.test(input.charAt(index))) return null; /* Keep reading characters while it's possible to do so. */ var result = ""; while (/[A-Za-z_0-9]/.test(input.charAt(index))) { result += input.charAt(index); ...
[ "function scanVariable(input, index, variableSet) {\n\tvar variableName = tryReadVariableName(input, index);\n\t/* variableName should not be null here, by contract. */\n\t\n\tvariableSet[variableName] = true;\n\treturn variableName;\n}", "function readVariable(noPrintVarName){\r\n\t\tvar ret={name:\"\",indexes:[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback function for when a tag is changed.
function onTagChange() { }
[ "tagChange(tag) {\n let tagPos = this.tags.indexOf(tag);\n if (tagPos === this.tags.length-1 && (tag.name !== '' || tag.value !== '')) this.addEmptyTag();\n }", "updateTag(event) {\n this.onUpdateTag({\n $event: {\n tag: event.tag\n }\n })\n }", "function tag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get the list of opportunities that the email is interested
function getListOpportunitiesInterestedEmail(email){ return new Promise((resolve, reject) => { pool.query(`SELECT opportunity, objective AS name FROM EmailFollowOpportunity WHERE email = ? AND active = 1 `, [email], function(error, results, fields...
[ "function getContactOpportunities(req, res) {\n Opportunity.find({ companyId: req.body.companyId, individualId: req.body.contactId, deleted: false })\n .populate('companyId', 'company')\n .populate('categoryId', '_id categoryName')\n .populate('departmentId', '_id departmentName')\n ....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isPadding :: Cell > Boolean
function isPadding(cell) { return cell[3]; }
[ "_addPadding(cells, padRows) {\n let out = cells.slice(0);\n for (let x = -padRows; x < this.xDim + padRows; x++) {\n for (let y = -padRows; y < this.yDim + padRows; y++) {\n // Only add the padding cells\n if (x < 0 || x >= this.xDim || y <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
podPress_is_v1_gtoreq_v2 checks whether v1 is greater than or equal to v2 or not
function podPress_is_v1_gtoreq_v2(v1, v2) { var vc = podPress_compare_v1_v2(v1, v2); if ('gt' == vc || 'eq' == vc) { return true; } else { return false; } }
[ "function podPress_compare_v1_v2(v1, v2) {\r\n\t\tif ( ((typeof v1 == 'string' && false == podPress_is_emptystr(v1)) || typeof v1 == 'number') && ((typeof v2 == 'string' && false == podPress_is_emptystr(v1)) || typeof v2 == 'number') ) {\r\n\t\t\tvar v1_parts = String(v1).split('.');\r\n\t\t\tvar v2_parts = String(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function abstracts the expected structure of any Kinesis payload, which is a base64encoded string of a JSON object, passing the data to a private function.
function handlePayload(record, callback) { encodedPayload = record.kinesis.data; rawPayload = new Buffer(encodedPayload, 'base64').toString('utf-8'); handleData(JSON.parse(rawPayload), callback); }
[ "function parsePayload(record) {\n const json = new Buffer.from(record.kinesis.data, 'base64').toString('utf8');\n return JSON.parse(json);\n}", "function prepare_payload(payload, secret) {\r\n var payloadJson = JSON.stringify(payload);\r\n return new Buffer(payloadJson).toString('base64');\r\n}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the quad buffers
function initQuad() { quad.texBuffer = bufferData(2, quad.tex); quad.centerBuffer = bufferData(3, quad.center); }
[ "function initQuadBuffer() {\n const new_buffer = G_glCtx.createBuffer();\n G_glCtx.bindBuffer(G_glCtx.ARRAY_BUFFER, new_buffer);\n G_glCtx.bufferData(G_glCtx.ARRAY_BUFFER, new Float32Array(getQuadBufferData()), G_glCtx.STATIC_DRAW);\n G_quadBuffer = new_buffer;\n}", "function init() {\n\t\tvertexBuff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the fields for the article preview
function setPreview(article){ // Preview Display $('#ce-side-title').text(article.data('title')); $('#ce-side-speaker').text(article.data('speaker')); document.getElementById("ce-side-bio").innerHTML = article.data('bio'); document.getElementById("ce-side-prelude").innerHTML = article.data('prelude'); document.ge...
[ "function setPreview(article){\n\t// Preview Display\n\t$('#ne-side-title').text(article.data('title'));\n\t$('#ne-side-article').text(article.data('article'));\n\t// Edit Display\n\t$('#ne-title-edit').val(article.data('title'));\n\t$('#ne-intro-edit').val(article.data('intro'));\n\t$('#ne-article-edit').val(artic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find all songs forked by user
getAllForks(userId) { var obj = {userId: userId}; Utils.postJSON('/myForks', obj) .then((response) => { console.log("dispatch forked songs ", response); Dispatcher.dispatch({ type: ActionType.GET_USER_FORKS, songs: response }) }) .catch((err) => { console.erro...
[ "static async getAllSongs(username){\n const res = await this.request(`users/allSongs/${username}`);\n return res.songs;\n }", "async function getCurrentUserSongs() {\n let body = 'getUserSongs=true';\n\n let getCurrentUserSongsQuery = await fetch('http://music.loc/', {\n method: 'PO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send XMLHttpRequest through a Proxy, and load website in DOM element if accessible. If not, dislay failure message. If yes, process the website with source reader.
function loadSource() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) { loadSrc.innerHTML = this.responseText; readSource(); } if (this.status == 404) { ...
[ "function doit() {\n document.getElementById(\"message\").innerHTML = \"flXHR doit\"; \n var flproxy = new flensed.flXHR({ autoUpdatePlayer:true, instanceId:\"myproxy1\", onerror:handleError, onreadystatechange:handleLoading, loadPolicyURL:\"http://osc-intweb1.gsc.riken.jp/edgeexpress-devel/cgi/crossdomain....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::CodeDeploy::DeploymentConfig` resource
function cfnDeploymentConfigPropsToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnDeploymentConfigPropsValidator(properties).assertSuccess(); return { ComputePlatform: cdk.stringToCloudFormation(properties.computePlatform), DeploymentConfi...
[ "function cfnDeploymentPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeploymentPropsValidator(properties).assertSuccess();\n return {\n RestApiId: cdk.stringToCloudFormation(properties.restApiId),\n DeploymentCanarySettings: c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find all possible ways to solve the challenge
function findSolutions(challenge) { return []; }
[ "function solve(nums,goal){\n fullSolutions = {}\n for(let z=0; z<=6; z++){\n fullSolutions[z]={}\n }\n // console.log(goal)\n var ordering=[-1,-1,-1,-1,-1,-1]\n for(let n0=0; n0<6; n0++){\n ordering[0]=n0\n for(let n1=0; n1<6; n1++){\n ordering[1]=n1\n for(let n2=0; n2<6; n2++){\n o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reduce a stream over time this will pass the last output value to the calculation function reads like the array reduce function
function reduce(parent$, fn, startValue) { var aggregate = startValue; var newStream = stream(); function reduceValue(value) { aggregate = fn(aggregate, parent$.value); newStream(aggregate); } if (parent$.value !== undefined) { reduceValue(parent$.value); } parent$.listeners.push(reduceValue);...
[ "function reduce(parent$, fn, startValue) {\n var aggregate = startValue;\n var newStream = stream();\n\n function reduceValue(value) {\n aggregate = fn(aggregate, parent$.value);\n newStream(aggregate);\n }\n\n if (parent$.value !== undefined) {\n reduceValue(parent$.value);\n }\n\n parent$.listene...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the member variables to invalid values
function setInvalid() { gregDate = moment.utc({'year': 0, 'month': 0, 'date': 0}); badiYear = -1; badiMonth = -1; badiDay = -1; ayyamiHaLength = -1; nawRuz = moment.utc('0000-00-00'); valid = false; }
[ "_invalidateProperties() {\n this.__isInvalid = true;\n super._invalidateProperties();\n }", "_invalidateProperties() {\n this.__isInvalid = true;\n super._invalidateProperties();\n }", "_setInvalidState() {\n if (this.isInputElement) {\n AutoNumericHelp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
animate Leo to mimic running motion
function runningMotionLeo() { if (!isGameEnded) { if (leoVision) { cameraLeo.position.x = MeshLeoTorso.position.x; cameraLeo.position.y = MeshLeoTorso.position.y + 5.5; cameraLeo.position.z = MeshLeoTorso.position.z; } var currentTime = clock.getElapsedTime(); if (currentT...
[ "animate(){\n this.x += this.delta(3.1416*2.0,10);\n }", "animateMove(){\n\t\tthis._state = \"walking\"\n\t\tthis.currentMoveFkt();\n\t\tthis._animationTimer--;\n\t}", "function animate() {\n\t\t// millis\n\t\tvar t = Date.now()\n\t\t\t,iDeltaTms = t-iLastT\n\t\t\t// deltaT min max deviation\n\t\t\t,f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: dwscripts.escServerQuotes DESCRIPTION: Escape quotes in a quoted string ARGUMENTS: theString string the string RETURNS: string the string with quotes escaped
function dwscripts_escServerQuotes(theString) { var retVal = theString; var serverObj = dwscripts.getServerImplObject(); if (serverObj != null && serverObj.escServerQuotes != null) { retVal = serverObj.escServerQuotes(theString); } return retVal; }
[ "function dwscripts_unescServerQuotes(theString)\n{\n var retVal = theString;\n\n var serverObj = dwscripts.getServerImplObject();\n\n if (serverObj != null && serverObj.unescServerQuotes != null)\n {\n retVal = serverObj.unescServerQuotes(theString);\n }\n\n return retVal;\n}", "function encodeQuotes(aS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set on initialization defaults to TestAppConfig
constructor(configType = '') { if (configType === 'heroku') this.config = HerokuAppConfig; else this.config = TestAppConfig; this.init(); }
[ "function initConfigPreAppLoadHelpers() {\n if (!config) {\n throw new Error('missing config');\n }\n // Attach an object that will hold any setup we need to do before\n // the angular app loads / any external requests are made\n config.preAppLoad = {\n queryparams: {},\n clearQuerypar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Individual function to get random suit
function getRandomSuit() { var s = Math.floor((Math.random() * 3) + 0); return cards[s][0]; }
[ "function pickCard(){ \r\n    var suit = Math.round(Math.random()*3); \r\n    if (suit === 0) suit = \"Hearts\"; \r\n    else if (suit === 1) suit = \"Diamonds\"; \r\n    else if (suit === 2) suit = \"Clubs\"; \r\n    else suit = \"Spades\"; \r\n \r\n    //your code here \r\n \r\n    return suit; \r\n \r\n} \r\n \r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Production PrintStatement ::== print ( Expr )
function parse_PrintStatement() { tree.addNode('PrintStatement', 'branch'); match('print', parseCounter); parseCounter++; match('(', parseCounter); parseCounter++; parse_Expr(); //tree.endChildren(); match(')', parseCounter); parseCounter++; tree.endChildren(); }
[ "function parsePrintStatement() {\n CST.addBranchNode(\"PrintStatement\");\n if (match([\"T_keywordPrint\"], false, false)) {\n if (match([\"T_openList\"], false, false)) {\n parseExpr();\n if (match([\"T_closeList\"], false, false)) {\n log(\"Print Statement\");\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contactsconfig.js Contacts API for Yahoo! Copyright (c) 2012 AppsAttic Ltd
function pathContacts(options, args) { return '/' + this.version() + '/user/' + this.yahooGuid() + '/contacts'; }
[ "function loadContacts() {\n\n\t\t/**\n\t\t * retrievePersonalAddressBook(success, failure) Retrieve all entries of\n\t\t * the user's personal address book\n\t\t * \n\t\t * @params <function> success, <function> failure\n\t\t */\n\t\tKandyAPI.Phone\n\t\t\t\t.retrievePersonalAddressBook(\n\t\t\t\t\t\tfunction(resul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set client testing flags to change behavior
setTestFlag(flag, options) { this.client.setTestFlag(flag, options); }
[ "function testAppClient(fakeLD, baseOptions) {\n let app;\n let numClients;\n const timeout = 2000;\n const options = Object.assign({}, baseOptions);\n const me = {};\n\n async function waitForClientStatus(status) {\n for (let i = 0; i < numClients; i++) {\n await app.client.waitUntilTextExists('#stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
redirect to home after post delete
function deletePostCallback() { props.history.push('/'); }
[ "function deletePost() {\n dispatch(removePostFromAPI(postId));\n history.push(\"/\");\n }", "delete(post) {\n if (confirm('Are you sure?')) {\n this.sendAction('destroyPost', post);\n }\n }", "function deleteThisPost(){\n handleDelete(post)\n }", "async handleDelete() {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tunnel2_vgw_inside_address computed: true, optional: false, required: false
get tunnel2VgwInsideAddress() { return this.getStringAttribute('tunnel2_vgw_inside_address'); }
[ "get tunnel1VgwInsideAddress() {\n return this.getStringAttribute('tunnel1_vgw_inside_address');\n }", "get tunnel2CgwInsideAddress() {\n return this.getStringAttribute('tunnel2_cgw_inside_address');\n }", "get tunnel1CgwInsideAddress() {\n return this.getStringAttribute('tunnel1_cgw_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Because we want to be highlight text directions steps and make them clickable we must render them ourselves rather than let GDirections do so as normal.
function renderTextDirections() { /* Get the addresses to display at the start and end of the directions */ var startAddress = route.getStartGeocode().address; var endAddress = route.getEndGeocode().address; /* Write the start address title, marker, and summary */ var html = getDirec...
[ "addDirectionsText(legs, routeKey) {\n const olContents = legs[0].steps.reduce((acc, step) => {\n const {\n maneuver: { instruction },\n } = step;\n const li = `<li class=\"mb-2\">${instruction}</li>`;\n return `${acc}${li}`;\n }, '');\n $('#directions-text ol').html(olContents);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a table of the given FeatureCollection of countries by name.
function makeResultsTable(countries) { var table = ui.Chart.feature.byFeature(countries, 'Name'); table.setChartType('Table'); table.setOptions({allowHtml: true, pageSize: 5}); table.style().set({stretch: 'both'}); return table; }
[ "function createTableCountries() {\n\n var countryCases = \"\";\n\n countryList.forEach((entry) => {\n //Construction of rows\n countryCases += \"<tr><td>\" + entry.country + \"</td><td>\" + numeral(entry.cases).format(\"0,0\") + \"</td></tr>\";\n });\n //Insert rows into table\n $(\"#table...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns `content` if its a string, or `content.description` if it can. Used for getting the nested `description` key in glossary files.
function getContent(content) { if (typeof content === 'string') return content if (typeof content.description === 'string') return content.description return null }
[ "function resolveContent( content ) {\n switch( content.mimeType ) {\n case 'application/vnd.innerfunction-semo.document':\n case 'application/vnd.innerfunction-semo.snippet':\n // TODO: What is the data property in this case? How is the underlying item resolved?\n case 'text/html':\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ObjectField[Const] : Name : Value[?Const]
function parseObjectField(lexer, isConst) { var start = lexer.token; var name = parseName(lexer); expectToken(lexer, TokenKind.COLON); return { kind: Kind.OBJECT_FIELD, name: name, value: parseValueLiteral(lexer, isConst), loc: loc(lexer, start) }; }
[ "function parseObjectField(lexer$$1, isConst) {\n var start = lexer$$1.token;\n return {\n kind: kinds.OBJECT_FIELD,\n name: parseName(lexer$$1),\n value: (expect(lexer$$1, lexer.TokenKind.COLON), parseValueLiteral(lexer$$1, isConst)),\n loc: loc(lexer$$1, start)\n };\n}", "parseObjectField(isConst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the value of the notes field for a point
function getNotes (index) { if (typeof ga !== 'undefined') { var label = $(".marker-point-item").eq(index).find(".marker-point-notes").val(); ga('send', { 'hitType': 'event', // Required. 'eventCategory': 'User Generated Points', // Required. 'eventAction':...
[ "function getNote(primitive) {\n\treturn map(primitive, function(primitive) {\n\t\treturn primitive.getAttribute(\"Note\");\n\t});\n}", "function getNotesProperty(series, x, property) {\n var track = tracksMap[series.name];\n var notes = track.notes;\n for (var i = 0; i < notes.length; i++) {\n if (notes[i]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }