query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Pings the server to wake it up and handle messages
function wakeUpServer() { var h = require("http"); h.get(SERVER_URL); }
[ "function ping() {\n primus.clearTimeout('ping').write('primus::ping::'+ (+new Date));\n primus.emit('outgoing::ping');\n primus.timers.pong = setTimeout(pong, primus.options.pong);\n }", "function messageLoop()\r\n{\r\n\tvar timeNow = new Date();\r\n\tvar year = timeNow.getFullYear();\r\n\tvar month = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define the function to return custom filter
function customFilterFactory(){ return function(input){ //change input return 'customFilter applied'; } }
[ "function custom1FilterFactory(){\n //this filter will take extra argument:arg1 along with the input on which this filter works on.\n return function(input,arg1){\n //change input\n return 'customFilter applied from html with '+ arg1 ;\n }\n }", "createEffect() {\n return new FilterEffect()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert an epoch timestamp into a calendar object with the given offset
function tsToObj(ts, offset) { ts += offset * 60 * 1000; var d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; }
[ "function epochToDate(epoch) {\n const date = new Date(0)\n date.setUTCSeconds(epoch)\n return date\n}", "function dateToEpoch(date) {\n return date.getTime() / 1000\n}", "function getDay(offset) {\n var d = new Date();\n return new Date(d.setDate(d.getDate() + offset)).setHours(0,0,0,0);\n}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deletes the selected file from local storage
function removeFile() { var listbox = document.getElementById("mySavedFiles2"); // get selected filename var fileName = undefined; for (var i = 0; i < listbox.options.length; i++) { if (listbox.options[i].selected) fileName = listbox.options[i].text; // selected file } if (fileName !== undefined) { // removes file from local storage window.localStorage.removeItem(fileName); // the current document remains open, even if its storage was deleted } closeElement("removeDocument"); }
[ "function handleDeleteUpload() {\n setFiles([])\n deleteFile(document)\n handleDocumentDelete(document)\n fileInputField.current.value = null\n }", "remove () {\n removeFile(this._filePath)\n }", "function removeMediaFile() {\n vm.modelContentNew.mediaFile = null;\n }", "vaciarLocal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search for last name in database takes last name to be searched for
function searchDatabaseLast(lastNameFind) { // for each person in array for (let people = 0; people < users.length; people++) { // if current person's last name matches last name to be found if (users[people].lastName.toLowerCase() === lastNameFind.toLowerCase()) { // return true return true; } } // if nothing found, return false return false; }
[ "function searchDatabaseFirst(firstNameFind) {\n for (let people = 1; people < users.length; people++) {\n if (users[people].firstName.toLowerCase() === firstNameFind.toLowerCase()) {\n return true;\n }\n }\n return false;\n}", "static async findProfile(string){\n const result=await...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the Date of yesterday
function yesterday() { var curLocDate = new Date(); curLocDate.setDate(curLocDate.getDate() - 1); return curLocDate; }
[ "function getYesterdaysDate() {\n var date = new Date();\n date.setDate(date.getDate()-1);\n return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();\n}", "function getPreviousSunday(date) {\n // Using midday avoids any possibility of Daylight Savings Time (DST) messing thin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper for all showing/hiding of game prizes/completion certificates
function toggleCertAndPrizes() { showOrHide('game_enable_completion_certificates', 'game_completion_certificate_template_field') showOrHide('game_prizes_available', 'game_prizes_text_field') }
[ "function paymentOptions(option) {\r\n const ccDIV = document.getElementById(\"credit-card\");\r\n const ppDIV = document.getElementById(\"paypal\");\r\n const bitcoinDIV =document.getElementById(\"bitcoin\");\r\n if(option == \"credit card\"){\r\n ccDIV.style.display = \"inherit\";\r\n pp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JSON Breed API Endpoints GET /api documentation
function apiDoc(req, res) { //console.log('GET /api'); res.json({ message: 'Welcome to the stashy sheep breed list!', documentation_url: 'https://github.com/SpindleMonkey/project-2/api.md', base_url: 'http://localhost:3000', notes: 'If you search for a breed with more than one word in it\'s name, use \'%20\' for the space between words. If you\'re updating the infoSources field, use \', \' to separage multiple sources.', endpoints: [ {method: 'GET', path: '/api', description: 'Describes available endpoints'}, {method: 'GET', path: '/api/breed', description: 'Lists all sheep breeds'}, {method: 'GET', path: '/api/breed/:name', description: 'Lists info for a single breed'}, {method: 'GET', path: '/api/breed/all', description: 'Lists all info for all breeds'}, {method: 'POST', path: '/api/breed', description: 'Add a new sheep breed'}, {method: 'PUT', path: 'api/breed/:name', description: 'Update one of the breeds in the db'}, {method: 'DELETE', path: '/api/breed/:name', description: 'Delete a sheep breed by name'} ] }); }
[ "function apiShow(req, res) {\n //console.log('GET /api/breed/:name');\n // return JSON object of specified breed\n db.Breed.find({name: req.params.name}, function(err, oneBreed) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: oneBreed});\n }\n });\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that saves challenge infos
function saveChallengeInfo(challengeData, reSubmission) { return new Promise((resolve, reject) => { dashboardModel.saveChallengeInfo(challengeData, reSubmission).then((data) => { resolve(true); }).catch((err) => { if (err.message === message.INTERNAL_SERVER_ERROR) reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} }) else reject({ code: code.BAD_REQUEST, message: err.message, data: {} }) }) }) }
[ "function SaveHourInfo(hour, data){\n localStorage.setItem(hour, data);\n}", "buildDungeonPrompts() {\n let dataToWrite = {};\n\n Object.values(DungeonManagersList.ByID).forEach((dungeonManager) => {\n // Add this dungeon info to the catalogue.\n dataToWrite[dungeonManager.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register event handlers so element can be selected, dragged and resized.
registerEventHandlers() { this.el .dblclick(event => { this.handleDoubleClick(event); }) .mousedown(event => { this.handleClick(event, false); }) .on('touchstart', event => { if (!this.rb.isSelectedObject(this.id)) { this.handleClick(event, true); } else { let absPos = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__utils__["c" /* getEventAbsPos */])(event); this.rb.getDocument().startDrag(absPos.x, absPos.y, this.id, this.containerId, this.linkedContainerId, this.getElementType(), DocElement.dragType.element); event.preventDefault(); } }) .on('touchmove', event => { if (this.rb.isSelectedObject(this.id)) { this.rb.getDocument().processDrag(event); } }) .on('touchend', event => { if (this.rb.isSelectedObject(this.id)) { this.rb.getDocument().stopDrag(); } }); }
[ "registerContainerEventHandlers() {\n this.el\n .dblclick(event => {\n if (!this.rb.isSelectedObject(this.id)) {\n this.rb.selectObject(this.id, true);\n event.stopPropagation();\n }\n })\n .mousedown(event =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test opening embeded flash content
function testFlashViaEmbedTag() { controller.open(TEST_DATA); controller.waitForPageLoad(TIMEOUT_PAGE); }
[ "function onFlashContentEmbedded(e)\r\n{\r\n\tfocusRef = e.ref;\r\n}", "function TinyMCE_flash_execCommand(editor_id, element, command, user_interface, value) {\n // Handle commands\n switch (command) {\n case \"mceFlash\":\n var template = new Array();\n template['file'] = '....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
triangles /////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// function that logs a triangel out of hashs based on given parameter
function triangles(number) { var hash = ''; // for each number below the given one run the loop for (let i = 0; i < number; i++){ // add another hash in each loop hash += '#'; // print the hash var each loop console.log(hash); } }
[ "function triangles(val) {\n //init string to contain character passed in while converting number data types to a string data type\n var str = \"\";\n //for loop to run until i = 7 not inclusive. 0 to 6 is 7 steps \n for (var i = 0; i < val; i++){\n // concatenate '#' to \n str += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To set permit mode, set a timeout to confirm staying in it, and also set the flag.
function set_permit () { if (unset_permit_timeout != null) clearTimeout(unset_permit_timeout); // Set the flag. current_mode = 'permit'; // Set timeout to only permit for 1 minute at a time. unset_permit_timeout = setTimeout( () => { if (confirm('You are in whitelist permit mode. Continue in permit mode?')) { set_permit(); } else { unset_permit(); } }, 1000 * 60 ); }
[ "function unset_permit () {\n current_mode = 'forbid';\n if (unset_permit_timeout != null) {\n clearTimeout(unset_permit_timeout);\n unset_permit_timeout = null;\n }\n}", "function Limit(delay /* ms */) {\n _ResetTimeout(delay, `Resetting active global timeout to ${delay}ms.`);\n}", "setMode() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates whether a vertical position property matches the expected values.
function validateVerticalPosition(property, value) { if (value !== 'top' && value !== 'bottom' && value !== 'center') { throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` + `Expected "top", "bottom" or "center".`); } }
[ "function validateVerticalAlignment(align) {\n var ALIGNMENTS = ['top', 'center', 'bottom'];\n var DEFAULT = 'top';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function isVertOrHorz(startCoordinate, endCoordinate){ \n let status;\n var startE = startCoordinate[0];\n var startN = st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the scoped slots from `node` template children. Templates for default slots are processed as regular children in `processNode`.
function slotsToData(node, h, doc) { const data = {}; const children = node.children || []; children.forEach(child => { // Regular children and default templates are processed inside `processNode`. if (!isTemplate(child) || isDefaultTemplate(child)) { return; } // Non-default templates are converted into slots. data.scopedSlots = data.scopedSlots || {}; const template = child; const name = getSlotName(template); const vDomTree = template.content.map(tmplNode => processNode(tmplNode, h, doc)); data.scopedSlots[name] = function () { return vDomTree; }; }); return data; }
[ "function shiftSlotNodeDeeper(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n const vslotShorthandName = getVslotShorthandName(child);\n if (vslotShorthandName && child.name !== 'template') {\n const newSlotNode = cheerio.parseHTML('<template></template>')[0];...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getters Getter of the damage caused by hardware components.
get hardwareDamage () { return this._hardwareDamage }
[ "get softwareDamage () {\n return this._softwareDamage\n }", "getEnergyPercent() {\n return this.getNetEnergy() / this.maxEnergy\n }", "set hardwareDamage (hardwareDamage) {\n this._hardwareDamage = hardwareDamage\n }", "getNetEnergy() {\n return this.maxEnergy - this.fatigue\n }", "receiveD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manually update the remaining timeout seconds
function updateTimeout() { $timeout(function () { if ($scope.remainingAuthSeconds > 0) { $scope.remainingAuthSeconds--; $scope.$digest(); //recurse updateTimeout(); } }, 1000, false); // 1 second, do NOT execute a global digest }
[ "function _tickRemaining() {\n remainingSeconds--;\n \n if(remainingSeconds <= 0 && vm.promoted) {\n vm.promoted = false;\n _Load();\n } else if (remainingSeconds <= 0) {\n vm.promoted = false;\n } else {\n vm.promoted = true;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks how many STs & TTs there are by counting titles (there's always 1 title per group) Tracking total count for sequencing; panel count for labeling
function countTexts(frameX, objectStyle) { if(objectStyle === "National Title") { totalST++; panelST++; } else if(objectStyle === "Veterans Title") { totalTT++; panelTT++; } }
[ "function reportSummary(teams) {\n var count = {};\n if ($(\"#summary-resistor-change\")[0].checked) {\n for (var k = 0; k < teams.length; k++) {\n var team = teams[k];\n if ($(\"#team-\" + team.name + team.classID)[0].checked) {\n count[team.name] = {};\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filterting rules: 1. Should be at least as severe as the global level 2. Should be at least as severe as the local level 3. logger's name should pass name filter
function allow(logger, level){ if (level < gLevel) return false; if (level < logger.level) return false; if (gNameFilter && !gNameFilter.test(logger.name)) return false; return true; }
[ "visitLogging_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSupplemental_logging_props(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSupplemental_log_grp_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function printFilterRestrictionHint () {\n console.log(' The \"res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
35 Write a limit function that allows a binary function to be called a limited amount of times.
function limit(binaryFunction, limit){ var round = 0; return function (first, second){ if (round < limit){ round += 1; return binaryFunction(first, second); }; } return undefined; }
[ "function powersOfTwo(limit, f) {\n powers(2, limit, f);\n}", "function looptoNumber (limit) {\n for (var i = 0; i<limit; i++) {\n console.log(i);\n }\n}", "function throttleUpdateGauge(func, limit){\n var lastRunTime;\n var lastFunctionCalled;\n return function () {\n //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the equivalent islamic(civil) date value for a give input Gregorian date. `gDate` is a JS Date to be converted to Hijri.
fromGregorian(gDate) { const gYear = gDate.getFullYear(), gMonth = gDate.getMonth(), gDay = gDate.getDate(); let julianDay = GREGORIAN_EPOCH - 1 + 365 * (gYear - 1) + Math.floor((gYear - 1) / 4) + -Math.floor((gYear - 1) / 100) + Math.floor((gYear - 1) / 400) + Math.floor((367 * (gMonth + 1) - 362) / 12 + (gMonth + 1 <= 2 ? 0 : isGregorianLeapYear(gDate) ? -1 : -2) + gDay); julianDay = Math.floor(julianDay) + 0.5; const days = julianDay - ISLAMIC_EPOCH; const hYear = Math.floor((30 * days + 10646) / 10631.0); let hMonth = Math.ceil((days - 29 - getIslamicYearStart(hYear)) / 29.5); hMonth = Math.min(hMonth, 11); const hDay = Math.ceil(days - getIslamicMonthStart(hYear, hMonth)) + 1; return new NgbDate(hYear, hMonth + 1, hDay); }
[ "function toJalali() {\n\n const DATE_REGEX = /^((19)\\d{2}|(2)\\d{3})-(([1-9])|((1)[0-2]))-([1-9]|[1-2][0-9]|(3)[0-1])$/;\n\n if (DATE_REGEX.test(mDate)) {\n\n let dt = mDate.split('-');\n let ld;\n\n let mYear = parseInt(dt[0]);\n let mMonth = parseInt(dt[1]);\n let mDay =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Patches the 'scroll' method on the Window prototype
function patchWindowScroll() { window.scroll = function (optionsOrX, y) { handleScrollMethod(this, "scroll", optionsOrX, y); }; }
[ "handleWindowScroll() {\n const sectionHTMLElement = this.sectionHTMLElement.current;\n const { top } = sectionHTMLElement.getBoundingClientRect();\n\n const shouldUpdateForScroll = Section.insideScrollRangeForUpdates.call(this, top);\n if ( shouldUpdateForScroll ) {\n\n this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all recipients in airtable (all pages) Resolves with a list of airtable recipient objects
findAll() { return new Promise((resolve, reject) => { let results = [] base('Recipients') .select() .eachPage( (records, fetchNextPage) => { results = [...results, ...records] fetchNextPage() }, async (err) => { if (err) return reject(err) resolve(results) } ) }) }
[ "getRecipients() {\n return new Promise((resolve, reject) => {\n Action.find().distinct('toAddress', (error, address) => {\n if(error) { reject; return; }\n resolve(address)\n })\n })\n }", "createRecipients() {\n const recipientsCount = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this fucntion make a nComb random combinations of a matrix spectra
function generator(spectra, options) { let options = Object.assign({}, {nComb: 1, threshold: 0.5}, options) var weights = new Array(options.nComb); var combinations = new Array(options.nComb); for (var i = 0; i < options.nComb; i++) { var tmp = new Array(spectra[0].length).fill(0); var weight = new Array(spectra.length); for(var j = 0; j < spectra.length; j++) { weight[j] = Math.random(); if (Math.random() > options.threshold) { for (var k = 0; k < spectra[0].length; k++) { tmp[k] += spectra[j][k]*weight[j]; } } else weight[j] = 0; } weights[i] = weight; combinations[i] = tmp; } return {weights: weights, combinations: combinations}; }
[ "function indcpaGenMatrix(seed, transposed, paramsK) {\r\n var a = new Array(3);\r\n var output = new Array(3 * 168);\r\n const xof = new SHAKE(128);\r\n var ctr = 0;\r\n var buflen, offset;\r\n for (var i = 0; i < paramsK; i++) {\r\n\r\n a[i] = polyvecNew(paramsK);\r\n var transpose...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function resets messages in chat box
resetChatBox() { $('#chat-message-box').val(""); }
[ "function sendChatMessege()\n{\n var chat = cleanInput($(\"#chat-box\").val().substring(0, 100));\n\n if($.isBlank(chat))\n return;\n\n socket.emit('chat', chat);\n setPlayerMessege(player, chat);\n $(\"#chat-box\").val(\"\");\n}", "function clearPlayerOneChat(i) {\n if (i.toLowerCase() =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[animation] blink the counter display
function displayBlink() { $("#countDisplay").animate({ opacity: '0.5', }, "slow"); $("#countDisplay").animate({ opacity: '1', },"slow"); }
[ "function timer() {\n number--\n $(\"#show-number\").html(\"<h2>\" + number + \"</h2>\");\n if (number === 0) {\n stop();\n }\n }", "function blink(){\n\nlet blinked = document.querySelector('#colon');\nblinked.style.color = (blinked.style.color ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3. Write a function named countOdds that accepts an array of numbers and returns the number of odd numbers in the array.
function countOdds(array) { var total = 0; for(var i = 0; i < array.length; i++) { if(array[i] % 2 != 0) { total++; } } return total; }
[ "function how_many_even(arr){\n count = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 0){\n count ++;\n }\n }\n return count;\n}", "function how_many_even(arr){\n var count = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 0){\n count++;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The saveUser function submits the username and password to a generated alphanumerical key in Firebase
function saveUser(username, password) { //This newUserRef allows for a NEW user to be submitted rather than replaced var newUserRef = usersRef.push(); //Sets the data into the database under a randomly generated key newUserRef.set({ username: username, password: password }); }
[ "dbSaveUser(user) {\n let userInfo = {\n email: user.email ? user.email : null,\n displayName: user.displayName ? user.displayName : null\n };\n // Overrides any key data given, which is cool for us\n firebase.database().ref('users/' + user.uid).update(userInfo);\n }", "storeUser (authData,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates Triangular distributed numbers
distribution(n: number): RandomArray { let triangularArray: RandomArray = [], random: RandomArray = (prng.random(n): any); for(let i: number = 0; i < n; i += 1){ triangularArray[i] = this._random(random[i]); } return triangularArray; }
[ "function loadTris(n){\n for(var i = 0; i < n; i++){\n tris[i] = new Triangle(20,60,random(-8,8),random(-8,8));\n }\n}", "function eightTriangleGenerator() {\n\n // step 1\n // generate 3 three random points between 0 to 45 degree\n var pointOne = randomPointGenerator();\n var pointTwo = randomPo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an array of data with the selected energy company. Then it wil show a donut chart. value; selected energy company.
function createData(value) { d3.json("data/suppliers/suppliers.json", function(error, data) { // error checking if (error) { console.log("We cannot retrieve the data."); d3.select(".donut-chart") .html("<div class='text-center'><h3>Sorry.<br><br> Wij kunnen geen data ophalen.</h3></div>"); throw error; }; // push the data into a list dataList = []; data.forEach(function(d){ if(value == d.company) { dataList.push({"composition": d.composition, "value": parseFloat(d.score)}); } }); // makes the actual donut makeDonut(dataList); }); }
[ "function draw_g_cake(data) {\n let series = [];\n let labels = [];\n for (let i = 0; i < data.length; i++) {\n series.push(data[i]['n_avistamientos'])\n labels.push(data[i]['tipo'])\n }\n // console.log(series);\n // console.log(labels);\n\n let options = {\n chart: {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resume level or go to a new level.
function resumeGame() { if (player.life == 0) { restartGame(); return; } // if it's playing, just resume if (!screen.paused) { screen.state = "running"; return; } // go to next level or restart if (currentLevel < levelFiles.length - 1) gotoNextLevel(); else restartGame(); }
[ "function advanceLevel(){\n\n\t\t\tjewel.audio.play(\"levelUp\"); //p.306\n\n\t\t\tgameState.level++;\n\t\t\tannounce(\"Level \" + gameState.level);\n\t\t\tupdateGameInfo();\n\t\t\t//level value on gameInfo obj is 0 at beginning of game\n\t\t\tgameState.startTime = Date.now();\n\t\t\tgameState.endTime = jewel.setti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion para evaluar el medio y forma de pago
function evaluarMetodoYFormaPago () { if ($metodoPago.val() === '') { bootbox.alert('Por favor, seleccione el método de pago'); return false; } // en efectivo if ($metodoPago.val() === '1') { // en efectivo $('#cobroEfectivo').removeClass('hide'); $('#montoPago').rules('add', { required: true, min: Number($('#costo').val()), messages: { required: 'Campo obligatorio', min: 'Ingrese una cantidad igual o mayor a ' + costo } }); $('#cambio').rules('add', { required: true, min: 0, messages: { required: 'Campo obligatorio', min: 'Ingrese una cantidad igual o mayor a 0' } }); } else { $('#cobroEfectivo').addClass('hide'); $('#montoPago').rules('remove'); $('#cambio').rules('remove'); } // parcial /*if ($formaPago.val() === '2') { // calcular el costo minimo a cubrir var costoMinimo = costo * 0.5; if ($metodoPago.val() === '1') { // en efectivo $('#abono').removeClass('hide'); $('#cobroEfectivo').removeClass('hide'); $('#cantidadAAbonar').rules('add', { required: true, min: costoMinimo, max: costo, messages: { required: 'Campo obligatorio', min: 'Ingrese una cantidad igual o mayor a ' + costoMinimo, max: 'Ingrese una cantidad menor a ' + costo } }); $('#montoPago').rules('add', { required: true, messages: { required: 'Campo obligatorio' } }); $('#cambio').rules('add', { required: true, messages: { required: 'Campo obligatorio' } }); } else { $('#cobroEfectivo').addClass('hide'); $('#montoPago').rules('remove'); $('#cambio').rules('remove'); // tarjeta de crédito $('#abono').removeClass('hide'); $('#cantidadAAbonar').rules('add', { required: true, min: costoMinimo, max: costo, messages: { required: 'Campo obligatorio', min: 'Ingrese una cantidad igual o mayor a ' + costoMinimo, max: 'Ingrese una cantidad menor a ' + costo } }); } }*/ }
[ "function calcularProm(filas)\n{\n let promedio = document.getElementById('promedio');\n let max = document.getElementById('precioMaximo');\n let min = document.getElementById('precioMinimo');\n if(filas.length != 0 )\n {\n let celdas = traerColumna(filas,'name','CELDAPRECIO').map((e)=>parse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
look for secondary buttons misused, and convert them if needed
convertButtons() { // if on the small design, or on the large design + white background // replace white buttons by blue ones if ( window.matchMedia('(max-width: 64rem)').matches || (window.matchMedia('(min-width: 64rem)').matches && this.design === 'bow') ) this.querySelectorAll('.a-button--secondary--white').forEach(e => { e.classList.replace( 'a-button--secondary--white', 'a-button--secondary' ) }) // if on large design + blue background, replace secondary blue by white buttons if ( window.matchMedia('(min-width: 64rem)').matches && this.design === 'wob' ) this.querySelectorAll('.a-button--secondary').forEach(e => { e.classList.replace( 'a-button--secondary', 'a-button--secondary--white' ) }) }
[ "ensureButtonsHidden() {\n // TODO(fanlan1210)\n }", "function disableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = false;\n\t\t\t\tev.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = false;\n\t\t\t\tcu.bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handel on canvas scroll
onCanvasScroll(e){ let conavasScrollPos = document.getElementById("canvas").scrollLeft; let endWinPos = document.getElementById("endWindow"); endWinPos.style.right = - conavasScrollPos+"px"; this.props.jsPlumbRef ? this.props.jsPlumbRef.repaintEverything() : '' }
[ "handleScroll_() {\n this.resetAutoAdvance_();\n }", "function onScroll(e) {\n if (cameraZoom >= 1 && cameraZoom <= cameraMaxZoom) {\n if (cameraZoom + -e.deltaY / 500 < 1 || cameraZoom + -e.deltaY / 500 > cameraMaxZoom) { return; }\n cameraZoom += -e.deltaY / 500;\n }\n}", "function scr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. Note persistedFaceId is different from faceId which represents the detected face by Face Detect. The persistedFaceId of face list is used in Face List Delete a Face from a Face List to remove face from a face list, or the output JSON of Face Find Similar JPEG, PNG, GIF(the first frame), and BMP are supported. The image file size should be larger than or equal to 1KB but no larger than 4MB. The detectable face size is between 36x36 to 4096x4096 pixels. The faces out of this range will not be detected. Rectangle specified by targetFace should contain exactly one face. Zero or multiple faces will be regarded as an error. Out of detectable face size, large headpose, or very large occlusions will also result in fail to add a person face. The given rectangle specifies both face location and face size at the same time. There is no guarantee of correct result if you are using rectangle which are not returned from Face Detect. Face list is a group of faces, and these faces will not expire. Face list is used as a parameter of source faces in Face Find Similar. Face List is useful when to find similar faces in a fixed face set very often, e.g. to find a similar face in a face list of celebrities, friends, or family members. A face list can have a maximum of 1000 faces. Http Method POST
faceListAddAFaceToAFaceListPost(queryParams, headerParams, pathParams) { const queryParamsMapped = {}; const headerParamsMapped = {}; const pathParamsMapped = {}; Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListAddAFaceToAFaceListPostQueryParametersNameMap)); Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListAddAFaceToAFaceListPostHeaderParametersNameMap)); Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListAddAFaceToAFaceListPostPathParametersNameMap)); return this.makeRequest('/facelists/{faceListId}/persistedFaces', 'post', queryParamsMapped, headerParamsMapped, pathParamsMapped); }
[ "faceListCreateAFaceListPut(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListCreateAFaceListPutQueryParametersNameMap)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handler for when thumbnailsBox is resized
_thumbnailsBoxResized() { this._updateSize(); this._redisplay(); }
[ "function resizedw(){\n loadSlider(slider);\n }", "function resizeHandler() {\n\tvar contentHeight = $('.content').height(),\n\t\tboxHeight = $('.info_box').height(),\n\t\tpageData = CLUB.pageData,\n\t\tpageSize = Math.floor(contentHeight/(boxHeight + 15));\n\tif(pageData.pageSize !== pageSize) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an AWS/ACMPrivateCA metric with the requested [metricName]. See for list of all metricnames. Note, individual metrics can easily be obtained without supplying the name using the other [metricXXX] functions.
function metric(metricName, change = {}) { return new cloudwatch.Metric(Object.assign({ namespace: "AWS/ACMPrivateCA", name: metricName }, change)); }
[ "function metric(metricName, change = {}) {\n const dimensions = {};\n if (change.fileSystem !== undefined) {\n dimensions.FileSystemId = change.fileSystem.id;\n }\n return new cloudwatch.Metric(Object.assign({ namespace: \"AWS/EFS\", name: metricName }, change)).withDimension...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows all answers for a cloze field 'inputs' is an option argument containing a list of the 'input' elements for the field
function fillClozeInputs(ident, inputs) { if (!inputs) { var inputs = getCloseInputs(ident) } for (var i=0; i<inputs.length; i++) { input = inputs[i]; input.value = getClozeAnswer(input); markClozeWord(input, CORRECT); // Toggle the readonlyness of the answers also input.setAttribute('readonly', 'readonly'); } }
[ "function allInputs () {\n let inputs = _.select(ractive.get('inputs'), function (input) {\n return (input.fragment === 'publicationOf' || input.fragment === 'recordId')\n })\n\n const addInput = function (input, groupIndex, inputIndex, subInputIndex) {\n inputs.push(input)\n con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Multistroke class: a container for unistrokes
function Multistroke(name, useBoundedRotationInvariance, strokes) // constructor { this.Name = name; this.NumStrokes = strokes.length; // number of individual strokes var order = new Array(strokes.length); // array of integer indices for (var i = 0; i < strokes.length; i++) order[i] = i; // initialize var orders = new Array(); // array of integer arrays HeapPermute(strokes.length, order, /*out*/ orders); var unistrokes = MakeUnistrokes(strokes, orders); // returns array of point arrays this.Unistrokes = new Array(unistrokes.length); // unistrokes for this multistroke for (var j = 0; j < unistrokes.length; j++) this.Unistrokes[j] = new Unistroke(name, useBoundedRotationInvariance, unistrokes[j]); }
[ "function DrawHelperStrokes(){\n context.strokeStyle = 'green'\n context.beginPath();\n context.arc(Dx, Dy, 5, 0, Math.PI*2, false);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Ax, Ay);\n context.lineTo(Dx-(Ax-Dx)*0.6, Dy-(Ay-Dy)*0.6);\n cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the selected Veggies
function addVeggies(runningPrice) { var veggiePrice = 0; var veggieCount = 0; var veggieText = ""; var veggieOptions = document.getElementsByClassName('veggie'); for (var i = 0; i < veggieOptions.length; i++) { if (veggieCount >= 1) { if (veggieOptions[i].checked) { veggieText += "<p>" + veggieOptions[i].value + " +$1.00</p>"; veggieCount += 1; veggiePrice += 1; } } else { if (veggieOptions[i].checked) { veggieText += "<p>" + veggieOptions[i].value +"</p>"; veggieCount += 1; } } } document.getElementById('selectedVeggies').innerHTML = veggieText; runningPrice += veggiePrice; updateRunning(runningPrice); }
[ "function appendNewVehicleToSelect(vehicle){\n $(\"#selectCar\").append($(\"<option>\").val(vehicle.vehicleID).text(vehicle.licensePlate));\n}", "addLenses(lenses){\n let selectLenses = document.getElementById('select_lenses');\n for (let i in lenses){\n selectLenses.innerHTML += `...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts the player list. Resets the spinners. Displays players.
function sortPlayers() { "use strict"; list.sort(compareByScore); resetSpinners(); displayPlayers(); }
[ "function sortPlayers() {\n var orderHTML = '<br><table id=\"orderlist\" >';\n orderHTML+= '<caption><b>Player Order</b></caption>';\n orderHTML+= '<tr style=\"background-color: #ddffdd\">';\n orderHTML+= '<th>Player<br>Name</th></tr>';\n $.each(BID18.bid.players,function(index,listInfo) {\n if (listInfo.bi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interrupt a kernel. Notes Uses the [Jupyter Notebook API]( The promise is fulfilled on a valid response and rejected otherwise. It is assumed that the API call does not mutate the kernel id or name. The promise will be rejected if the kernel status is `Dead` or if the request fails or the response is invalid.
interrupt() { return Private.interruptKernel(this, this.serverSettings); }
[ "function interruptAs(fiberId, __trace) {\n return (0, _core3.haltWith)(trace => Cause.traced(Cause.interrupt(fiberId), trace()), __trace);\n}", "function unsafe_cancel_exn() /* () -> exception */ {\n return exception(\"computation is canceled\", Cancel);\n}", "function createKernel(options, id) {\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make the life sprites with the heart images after a given number of frameCount (similar to createAlien()) Give them a velocity, add them to a life group (make a new coin group in function setup()) give them a lifetime, make sure their vertical positions are random
function BoostLife() { if(frameCount%1000 === 0) { lifeBoost=createSprite(0,40,10,10); lifeBoost.addImage(lifeboostImg); lifeBoost.scale=0.5 lifeBoostn.velocityX=2; lifeBoost.y=random(20,height-20); lifeBoost.lifetime=1000; lifeBoostgroup.add(lifeBoost); } }
[ "function generateZerg() {\n if (frames % 70 === 0) {\n enemies.push(new Zerg())\n }\n }", "function createExplosion() {\n function rand( size ) {\n return size * Math.random() - (size/2);\n }\n var num = 150;\n particleGroup.triggerPoolEmitter( 1, (pos.set( rand(num/10), rand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loading more sequences for species multiselect
function loadMore() { var jobid = $('#jobinfo').val(); var loadedSeqs = $('#speciessel > option').length - jsonOrgs["queryorgs"].length; // amount of species loaded, minus user-submitted species //console.log(loadedSeqs); $.ajax({ // Your server script to process the upload contentType: 'application/json', url: '/results/'+jobid+'/step2/orgs?start='+loadedSeqs, async: true, cache: false, contentType: false, processData: false, success: moreSeqsSuccess, error: moreSeqsError}); }
[ "selection() {\n // console.log(this.matingpool.length);\n let newAgents = [];\n for (let i = 0; i < this.agents.length; i++) {\n let parentAdna = random(this.matingpool).dna;\n let parentBdna = random(this.matingpool).dna;\n let childDna = parentAdna.crossOver(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asynchronous function that can be used to set the snowflake_support flag on a given warehouse.
function setWhSnowflakeSupportFlag( conn, warehouseId, snowflakeSupportFlag, callback) { var sqlText = util.format( 'select system$set_wh_snowflake_support_flag(%s, %s);', warehouseId, snowflakeSupportFlag); conn.execute( { sqlText: sqlText, complete: function (err, statement, rows) { assert.ok(!err); callback(); } }); }
[ "function setMssqlHandler(){\n\treturn new Promise( function(resolve, reject){\n\t\ttry{\n\t\t\tif( __mssqlHandlerUsage ){\n\n\t\t\t\tglobal.mssqlHandler = require( __mssqlHandler );\n\n\t\t\t\tmssqlHandler.getPool()\n\t\t\t\t.then( function(_pool){\n\t\t\t\t\tglobal.pool = _pool;\n\t\t\t\t\tpool.dbms = \"mssql\";\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when a bid is rejected
function bidRejected(bid) { importer.node.account.release(bid.getValue()); }
[ "function stateRejected() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n\n si.Reason = \"\";\n var x = document.getElementById(\"smRejectR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build xml string from the ControlManifest's json object
getManifestXmlString() { const jsonToXmlbuilder = new Builder(); const xml = jsonToXmlbuilder.buildObject(this.data); return xml; }
[ "function createManifest () {\n fs.writeFile(manifestPath + 'manifest.json', JSON.stringify(manifest))\n}", "function createMeta() {\n\t\ttry {\n\t\t\tvar manifestData = chrome.runtime.getManifest();\n\t\t\tvar obj = {\n\t\t\t\tversion: manifestData.version, // set in manifest\n\t\t\t\tinstall: {\n\t\t\t\t\tdate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function For Adding New Entry Creates two span leader and scor and two buttons and set there respective id Adds them to both the divs Appends them to scores and names array and increment the count The id of each set of item is based on the current value of count, which indeed is related to there current position in the array O(1)process
function Add(){ var name = "Leader"+count; var leader = document.createElement('span'); leader.innerHTML=name; leader.id="1a"+count; leader.className="col-md-6"; var scor = document.createElement('span'); scor.innerHTML=0; scor.className="col-md-2"; scor.id="1b"+count; var btn1 = document.createElement('button'); btn1.innerHTML="INC"; btn1.className="col-md-2"; btn1.addEventListener ("click", increase); btn1.id="1c"+count; var btn2 = document.createElement('button'); btn2.innerHTML="DEC"; btn2.className="col-md-2"; btn2.addEventListener ("click", decrease); btn2.id="1d"+count; div1.appendChild(leader); div1.appendChild(scor); div1.appendChild(btn1); div1.appendChild(btn2); name1 = "Leader"+count; leader = document.createElement('span'); leader.innerHTML=name; leader.className="col-md-6"; leader.id="2a"+count; scor = document.createElement('span'); scor.innerHTML=0; scor.className="col-md-2"; scor.id="2b"+count; btn1 = document.createElement('button'); btn1.innerHTML="INC"; btn1.className="col-md-2"; btn1.id="2c"+count; btn1.addEventListener ("click", increase); btn2 = document.createElement('button'); btn2.innerHTML="DEC"; btn2.className="col-md-2"; btn2.id="2d"+count; btn2.addEventListener ("click", decrease); div2.appendChild(leader); div2.appendChild(scor); div2.appendChild(btn1); div2.appendChild(btn2); count++; names.push(name); scores.push(0); }
[ "function increase(){\n \n var str=event.target.id;\n var str=str.substr(2,str.length-2);\n var x=parseInt(str);\n console.log(x);\n scores[x-1]+=1;\n \n while(x>1 && scores[x-1]>scores[x-2]){\n var lead=names[x-1],sco=scores[x-1];\n names[x-1]=names[x-2];\n scores[x-1]=scores[x-2];\n names[x-2]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method clicks on the wishlist icon
clickWishlistIcon() { return this .waitForElementVisible('@wishListBtn') .assert.visible('@wishListBtn') .click('@wishListBtn'); }
[ "function openFriendsMenuForSelectedFriend() {\n document.querySelectorAll('div[aria-label=\"Friends\"]')[0]\n .click();\n}", "function addIconClickListener(callBack) {\n browserAction.onClicked.addListener(callBack);\n}", "function clickThatCow(imageElement) {\n\tsetSaving();\n\n\t// get the image...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endpoint_configuration computed: true, optional: false, required: false
endpointConfiguration(index) { return new DataAwsApiGatewayRestApiEndpointConfiguration(this, 'endpoint_configuration', index); }
[ "function EndpointConfig(props) {\n return __assign({ Type: 'AWS::SageMaker::EndpointConfig' }, props);\n }", "constructAxiosRequestConfig() {\n const input = this._getInput(this.edge);\n const config = {\n url: this._getUrl(this.edge, input),\n params: this._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
divContent(divId,divContent) Change the content of the div.
function divContent(divId,divContent) { //console.log('divContent('+divId+','+divContent+')'); if ( document.getElementById(divId) ) { document.getElementById(divId).innerHTML = divContent; } else { console.warn('document.getElementById('+divId+') == udefined'); } }
[ "updateDivContent() {\n var server = getServer(this.serverKey);\n\n if(this.type == 'status') {\n this.#updateStatusContent(server);\n }\n\n if(this.type == 'queue') {\n this.#updateQueueContent(server);\n }\n\n if(this.type == 'controls') {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function for generating and loading a robot energy sprite
function newBattleRobotEnergySprite(battleTeam, robotKey, robotSpriteKey){ //console.log('thisGame.newBattleRobotEnergySprite()', battleTeam, robotKey, robotSpriteKey); // Define a pointer to the appropriate team if exists, else create it if (typeof thisGame.battleRobots[battleTeam] === 'undefined'){ thisGame.battleRobots[battleTeam] = []; } var battleTeamRobots = thisGame.battleRobots[battleTeam]; // Create the status bar icon for this robot var energySpriteKey = robotSpriteKey + '/energy'; var robotEnergySprite = { filePath: thisGame.gameSettings.baseCorePath + 'images/robot-status_'+battleTeamRobots[robotKey].robotDirection+'.png', basePosition: [0, 0, 0, 1], currentPosition: [0, 0, 0, 1], frameWidth: 26, frameHeight: 71, frameSpeed: 1, frameLayout: 'vertical', frameSequence: [0], frameAnimationSequence: [{ // pan up startPosition: [0, 0], endPosition: [0, -5], frameDuration: 30 }, { // pan down startPosition: [0, -5], endPosition: [0, 0], frameDuration: 30 }] }; var statusPositionMod = function(){ var battleRobot = battleTeamRobots[robotKey]; var positionMod = battleRobot.robotDirection == 'left' ? 1 : -1; return positionMod; } var statusPositionOffset = function(){ var battleRobot = battleTeamRobots[robotKey]; var positionMod = statusPositionMod(); var overflowValue = battleRobot.robotSprite.frameSize - 80; var positionOffset = positionMod * Math.ceil(battleRobot.robotSprite.frameSize * 0.5); if (overflowValue > 0){ positionOffset -= Math.ceil(overflowValue / 4) * positionMod; //positionOffset -= positionMod * Math.ceil(robotEnergySprite.frameWidth / 2); } return positionOffset; }; var statusPositionX = function(){ var battleRobot = battleTeamRobots[robotKey]; var positionMod = statusPositionMod(); var positionX = battleRobot.robotSprite.currentPosition[0] + statusPositionOffset(); var overflowValue = battleRobot.robotSprite.frameSize - 80; positionX += robotEnergySprite.frameWidth; if (overflowValue > 0){ positionX += Math.ceil(overflowValue / 2); positionX -= positionMod * Math.ceil(robotEnergySprite.frameWidth / 2); } //positionX -= return positionX; }; var statusPositionY = function(){ var battleRobot = battleTeamRobots[robotKey]; var positionMod = statusPositionMod(); var positionY = battleRobot.robotSprite.currentPosition[1] - 20; var overflowValue = battleRobot.robotSprite.frameSize - 80; if (overflowValue > 0){ positionY += overflowValue; } return positionY; }; var statusPositionZ = function(){ var battleRobot = battleTeamRobots[robotKey]; var positionZ = battleRobot.robotSprite.currentPosition[2] + 1; return positionZ; }; robotEnergySprite.basePosition = [statusPositionX, statusPositionY, statusPositionZ]; robotEnergySprite.globalFrameStart = thisGame.gameState.currentFrame; robotEnergySprite.currentFrameKey = 0; robotEnergySprite.spriteObject = thisGame.newCanvasSprite( energySpriteKey, robotEnergySprite.filePath, robotEnergySprite.frameWidth, robotEnergySprite.frameHeight, robotEnergySprite.frameLayout, robotEnergySprite.frameSpeed, robotEnergySprite.frameSequence ); thisGame.gameSpriteIndex[energySpriteKey] = robotEnergySprite; thisGame.updateCanvasSpriteRenderOrder() }
[ "function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for postV3ProjectsIdRepositoryTagsTagNameRelease
postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions, cb) { const Gitlab = require('./dist'); let defaultClient = Gitlab.ApiClient.instance; // Configure API key authorization: private_token_header let private_token_header = defaultClient.authentications['private_token_header']; private_token_header.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //private_token_header.apiKeyPrefix = 'Token'; // Configure API key authorization: private_token_query let private_token_query = defaultClient.authentications['private_token_query']; private_token_query.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //private_token_query.apiKeyPrefix = 'Token'; let apiInstance = new Gitlab.ProjectsApi() /*let id = "id_example";*/ // String | The ID of a projec /*let tagName = "tagName_example";*/ // String | The name of the ta /*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | apiInstance.postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions.id, incomingOptions.tagName, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => { if (error) { cb(error, null) } else { cb(null, data) } }); }
[ "postV3ProjectsIdRepositoryTags(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.api...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by Java9ParsercompilationUnit.
exitCompilationUnit(ctx) { }
[ "exitOrdinaryCompilation(ctx) {\n\t}", "exitModularCompilation(ctx) {\n\t}", "visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitStatementWithoutTrailingSubstatement(ctx) {\n\t}", "function Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a contact with matching UID from the contact list and updates te list of letters that can be used to filter contacts
deleteContact ({ commit, state }, data) { state.contacts = state.contacts.filter(({ uid }) => { return uid !== data.uid }) const letters = getLettersForFilter(state.contacts) commit('updateFilterLetters', letters) }
[ "function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }", "function deleteContact(){\n\tif(!confirm(\"Are you sure you want to delete this contact?\")){\n\t\treturn;\n\t}\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepends provided base to provided path
function addBase (base, path) { var result = path // add if exists if (base) result = `${base}/${path}` return result }
[ "mergeBasePath(base, force = false) {\n if (base == null) {\n return;\n }\n\n if (!this.isAbsolute) {\n if (this.parentPath === '') {\n this.parentPath = base;\n } else {\n this.parentPath = `${base}/${this.parentPath}`;\n }\n\n this.path = `${this.parentPath}/${name}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build the DOM structure that makes up the suggestion box and content containers.
_renderContentContainers() { // container of all suggestion elements this._suggestionContainer = document.createElement('div'); this._suggestionContainer.classList.add(this.options.classNames.container); // child elements that will be populated by consumer this._header = document.createElement('h4'); this._header.classList.add(this.options.classNames.header); this._setHeader(this.state.header); this._suggestionContainer.appendChild(this._header); this._listContainer = document.createElement('ul'); this._listContainer.setAttribute('role', 'listbox'); this._listContainer.classList.add(this.options.classNames.list); this._suggestionContainer.appendChild(this._listContainer); // put the suggestions adjacent to the input element // firefox does not support insertAdjacentElement if (HTMLElement.prototype.insertAdjacentElement) { this._input.insertAdjacentElement('afterend', this._suggestionContainer); } else { this._input.parentNode.insertBefore( this._suggestionContainer, this._input.nextSibling, ); } }
[ "function createElements() {\r\n _dom = {};\r\n createElementsForSelf();\r\n if (_opts.placement.popup) {\r\n createElementsForPopup();\r\n }\r\n createElementsForColorWheel();\r\n createElementsForNumbersMode();\r\n createE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the connect to Sauce Labs.
function startSauce() { console.log( 'Local server listening to', STATIC_SERVER_PORT ); console.log( 'Sauce Connect ready.' ); const opts = { url: `https://${ SAUCE_LABS_USERNAME }:${ SAUCE_LABS_ACCESS_KEY }@saucelabs.com/rest/v1/cct-sauce/js-tests`, method: 'POST', json: { platforms: [ [ 'Windows 7', 'internet explorer', '11' ], [ 'Windows 7', 'firefox', '27' ] ], url: 'http://localhost:' + STATIC_SERVER_PORT + '/?ci_environment=' + NODE_ENV, framework: 'custom', name: testName } }; request.post( opts, function( reqErr, httpResponse, body ) { if ( reqErr ) { console.error( 'An error occurred:', reqErr ); } console.log( 'Tests started.' ); sauceTests = body['js tests']; checkSauce(); } ); }
[ "async function initialize() {\n simulator = new Simulator(credentials);\n\n await new Promise((resolve, reject) => {\n simulator\n .on('error', (err) => {\n reject(err);\n })\n .on('connected', () => {\n resolve();\n })\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter de l'attribut difficulte retour: La valeur de difficulte
getDifficulte() { return this.difficulte; }
[ "get fieldValue(){}", "get nombre(){\n return this._nombreMascota\n }", "getData() {\n return PRIVATE.get(this).opt.data;\n }", "get VisibilityMi() {\n return this.visibilityMi;\n }", "getCapacidad() {\n return this.capacidad;\n }", "get payerPhone() {\n return this[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creating the function 'addInitals'
function addInitals(first, last){ console.log ('Your Initals:', (first + last)); }
[ "function init() {\n id(\"add\").addEventListener(\"click\", newList);\n }", "function initRolesTabs(rolesToInit) {\n for(var role in rolesToInit) {\n tabsByRoles[role] = [];\n sortTabsByRoles(tabs[role], role);\n }\n }", "function init(){\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
10 Use an HTML element event to call a function you wrote for the player object to update the yearInLeague data. Display the result (a confirmation of the update).
function updatePlayer() { initializePlayer(); newPlayer.setYearsInLeague("16"); newPlayer.display(); }
[ "function updateSlotDisplays(player){\n\t\tdocument.getElementById(\"header\").innerHTML = \n\t\t\t\t\t\"<h3>3-of-a-Kind Slot-o-Rama</h3>\" + \n\t\t\t\t\t\"<h4>$\" + payout + \" per credit bet<br>\" +\n\t\t\t\t\t\"Max bet = \" + multiplierMax + \" credits</h4>\";\n\t\tdocument.getElementById(\"credit_cost\").innerH...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an RGBa, RGB, or hex color value, return the alpha channel value.
function acp_get_alpha_value_from_color( value ) { var alphaVal; // Remove all spaces from the passed in value to help our RGBa regex. value = value.replace( / /g, '' ); if ( value.match( /rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/ ) ) { alphaVal = parseFloat( value.match( /rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/ )[1] ).toFixed(2) * 100; alphaVal = parseInt( alphaVal ); } else { alphaVal = 100; } return alphaVal; }
[ "function rgba( r, g, b, a ) {\n\tvar alph = parseFloat( a );\n\tif( r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 || alph < 0 || alph > 1 ) {\n\t\tconsole.log( \"rgba called with wrong params. r: \" + r + \", g: \" + g + \", b: \" + b + \", a:\" + a );\n\t}\n\telse {\n\t\treturn \"rgba(\" + r + \", \" +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Blocks the GOOGLE_APPLICATION_CREDENTIALS by default. This is necessary in case it is actually set on the host machine executing the test.
function blockGoogleApplicationCredentialEnvironmentVariable(auth) { return insertEnvironmentVariableIntoAuth(auth, 'GOOGLE_APPLICATION_CREDENTIALS', null); }
[ "async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when the user wants to switch between route options for cars/bikes/pedestrians and clicks the button to switch views
function switchRouteOptionsPane(e) { // hide options $('#optionsContainer').hide(); var parent = $('.ORS-routePreferenceBtns').get(0); var optionType = e.currentTarget.id; //switch the buttons above var allBtn = parent.querySelectorAll('button'); for (var i = 0; i < allBtn.length; i++) { var btn = allBtn[i]; if (btn == e.currentTarget) { btn.addClassName('active'); //set the selected entry as currently selected route option var options = $('#' + btn.id + 'Options').get(0).querySelector('input[checked="checked"]'); /* adapt global settings information */ updateGlobalSettings(optionType, options.id); theInterface.emit('ui:routingParamsChanged'); } else { btn.removeClassName('active'); } } // update options updateProfileOptions(e.currentTarget.id); }
[ "function navigateTo() {\n let viewName = $(this).attr('data-target');\n showView(viewName)\n }", "function setRouteOption(routeOption) {\n //set radioButton with $('#' + routeOption) active\n var el = $('#' + routeOption);\n if (el) {\n el.attr('checked', true);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
an internal function that will add/remove a hidden element called "addl_query" to the participant search form. The element will contain filtering information that will be used by lunr in the participant search to filter out the found results based on the additional filter items.
function updateSearchFormFields(ev) { let searchForm = document.getElementById("participant_search_form"); let form = ev.target.closest("[data-js-search-filter]"); let checked = [...form.querySelectorAll(":checked")]; let queries = {}; for (let i = 0; i < checked.length; i++) { if (!queries[checked[i].name]) { queries[checked[i].name] = []; } queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`); } newQueries = Object.values(queries).map((q) => q.join(" ")); searchForm .querySelectorAll("input[type='hidden']") .forEach((e) => e.remove()); for (let i = 0; i < newQueries.length; i++) { let input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", "addl_query"); input.setAttribute("value", newQueries[i]); searchForm.append(input); } searchForm.querySelector("[type='submit']").click(); }
[ "function setupSearchFilter() {\n // an internal function that will add/remove a hidden element called \"addl_query\" to the\n // participant search form. The element will contain filtering information that will be used by\n // lunr in the participant search to filter out the found results based on the additiona...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A UI method to revert a draft document to the last published version or, if the document has never been published, delete the draft entirely. The user is advised of the difference. Returns an object if a change was made, or false if an error was reported to the user. If the draft document still exists the returned object will have a `doc` property containing its newly reverted contents.
async discardDraft(doc) { const isPublished = !!doc.lastPublishedAt; try { if (await apos.confirm({ heading: isPublished ? 'apostrophe:discardDraft' : 'apostrophe:deleteDraft', description: isPublished ? 'apostrophe:discardDraftDescription' : 'apostrophe:deleteDraftDescription', affirmativeLabel: isPublished ? 'apostrophe:discardDraftAffirmativeLabel' : 'apostrophe:deleteDraftAffirmativeLabel', interpolate: { title: doc.title } })) { const action = window.apos.modules[doc.type].action; if (isPublished) { const newDoc = await apos.http.post(`${action}/${doc._id}/revert-draft-to-published`, { body: {}, busy: true }); apos.notify('apostrophe:draftDiscarded', { type: 'success', dismiss: true, icon: 'text-box-remove-icon' }); apos.bus.$emit('content-changed', { doc: newDoc, action: 'revert-draft-to-published' }); return { doc: newDoc }; } else { await apos.http.delete(`${action}/${doc._id}`, { body: {}, busy: true }); apos.notify('apostrophe:draftDeleted', { type: 'success', dismiss: true }); apos.bus.$emit('content-changed', { doc, action: 'delete' }); return {}; } } } catch (e) { await apos.alert({ heading: this.$t('apostrophe:error'), description: e.message || this.$t('apostrophe:errorWhileRestoringPrevious'), localize: false }); } }
[ "async revert(_cancellation) {\r\n const diskContent = await vscode.workspace.fs.readFile(this.uri);\r\n this._bytesize = diskContent.length;\r\n this._documentData = diskContent;\r\n this._unsavedEdits = [];\r\n this._edits = [];\r\n // // If we revert then the edits are e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Do we need both validateWire and trySelectWire?
function validateWire () { if (wire.requests.length) return var i = self._selections.length while (i--) { var next = self._selections[i] var piece if (self.strategy === 'rarest') { var start = next.from + next.offset var end = next.to var len = end - start + 1 var tried = {} var tries = 0 var filter = genPieceFilterFunc(start, end, tried) while (tries < len) { piece = self._rarityMap.getRarestPiece(filter) if (piece < 0) break if (self._request(wire, piece, false)) return tried[piece] = true tries += 1 } } else { for (piece = next.to; piece >= next.from + next.offset; --piece) { if (!wire.peerPieces.get(piece)) continue if (self._request(wire, piece, false)) return } } } // TODO: wire failed to validate as useful; should we close it? // probably not, since 'have' and 'bitfield' messages might be coming }
[ "selectInputSourceNet() {\n this._selectInputSource(\"i_net\");\n }", "checkValidity() {\n this.select.checkValidity();\n }", "async _validateAndConnectDevice(rethrowErrors) {\r\n this.epIn = null;\r\n this.epOut = null;\r\n\r\n let ife = this.device.configurations[0].interfac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Implement the logic to check if the user is still supposed to be waiting (now < TTL for waitingRoomCookieTTL)
function isUserStillWaiting(request) { return false; //Allow user to return the pool for selection. }
[ "function C101_KinbakuClub_RopeGroup_WaitingForFriend() {\n\tif (C101_KinbakuClub_RopeGroup_FriendWaitCount == 0) C101_KinbakuClub_RopeGroup_FriendWaitCount = CurrentTime + 300000;\n\tC101_KinbakuClub_RopeGroup_FriendWaitCount++\n\tif (CurrentTime >= C101_KinbakuClub_RopeGroup_FriendWaitCount && !C101_KinbakuClub_R...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determines if a cell contains a valid station name.
function isValidStation(s) { return s.match(/^\s*\S+\s*$/) }
[ "function checkName(str) {\n for (var i=0; i < trains.length; i++) {\n if (trains[i]===str) {\n return false;\n }\n }\n return true;\n}", "function validName(input) {\n return input.length > 0\n }", "function fn_CheckLoginName ( strLogin )\n\t{\n\t\tstrLogin = trimString( s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
apply a width value, possibly adjusting the height value along with it, depending on the size/options chosen This is triggered by user editing 'input_width' and may or may not end up updating 'height' and 'width' depending on whether input_height and input_width seem acceptable. This is also called manually with the existing width value when changing major options in order to use this logic to select a nice default height.
function _applyWidth(width) { if(self._applying_dimensions) return; if(self.layout() == "video") { // for video, a given width implies a specific height, so just set it and done if(width < VIDEO_MIN_WIDTH || width > VIDEO_MAX_WIDTH) { // width invalid, don't apply it return; } var height = _videoHeight(width); self.height(height); self.width(width); self._applying_dimensions = true; self.input_height(height); self._applying_dimensions = false; return; } var sizekey = self.sizekey(); var defaults = DEFAULT_SIZES[sizekey]; if(width < defaults.min_width || width > defaults.max_width) { return; } // extra special min width for smallart players if(self.size() == "large" && self.artwork_option() != "large" && width < STANDARD_SMALLART_WIDTH_MIN) { return; } // passed the check, so use this width in the embed self.width(width); if ( width == "100%" ) { // if the width is set to "100%", continue as if the width // was set to defaults.min_width, since you can't do a height // calculation with the string "100%" width = defaults.min_width; } // calculate range of allowable heights var range = self.heightRange(width); var inp_height = self.input_height(); // by default, update input_height to the closest value in its allowed range var new_height = pin(inp_height, range); // however, if we are showing a tracklist, default the height to // show exactly DEFAULT_NUM_LIST_ITEMS list items by default (unless there are fewer tracks // than that, in which case, default to the number of tracks). // Calculate this by knowing that range.min shows MIN_LIST_ITEMS, so add // enough height for an additional 1 or 2 if appropriate if(self.size() == "large" && self.layout() != "minimal" && self.show_tracklist()) { var nitems = Math.min(DEFAULT_NUM_LIST_ITEMS, opts.num_tracks || 0); if(nitems > MIN_LIST_ITEMS) { Log.debug("showing " + nitems + " tracks by default"); new_height = range.min + LIST_ITEM_HEIGHT * (nitems - MIN_LIST_ITEMS); } } if(new_height != inp_height) { self.height(new_height); self._applying_dimensions = true; self.input_height(new_height); self._applying_dimensions = false; } }
[ "set requestedWidth(value) {}", "set width(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.width[set]\");\n this._width = aValue;\n }", "onWidthChange(width) {\n // Set new breakpoint\n var newState = {width: width};\n newState.breakpoint = this.getBreakpointFromWidth(newState.width);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if saving to redis is enabled and performs save if it is
function saveToRedis(redisKey, redisValue, isEnabled) { if (typeof isEnabled === "undefined") { isEnabled = config.redis.enableRedisInsert; } if (isEnabled) { redisClient.setAsync(redisKey, redisValue); } }
[ "function syncRedis() {\n // if memStore has changed...\n if(JSON.stringify(memCache) !== JSON.stringify(memStore)) {\n return when.promise((resolve, reject) => {\n var serializedStore = JSON.stringify(memStore);\n redis.set(name, serializedStore, err => {\n if(err) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows you to add an audit trail object and audit trail content associated with Kaltura object.
static add(auditTrail){ let kparams = {}; kparams.auditTrail = auditTrail; return new kaltura.RequestBuilder('audit_audittrail', 'add', kparams); }
[ "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('audit_audittrail', 'get', kparams);\n\t}", "function addObjectTab(wnd, node, data, tab)\n{\n if (!node.parentNode)\n return;\n\n // Click event handler\n tab.setAttribute(\"href\", data.location);\n tab.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all notes for a lesson: returns [note, ...]
static async getAll(lessonId) { const result = await db.query( `SELECT * FROM notes WHERE lesson_id = $1`, [lessonId]); if (result.rows.length === 0) { throw new ExpressError(`No notes`, 404); }; return result.rows.map(n => new Note(n.id, n.lesson_id, n.note)); }
[ "async getAllLessons() {\n const lessonCollection = await lessons();\n const lessonList = await lessonCollection.find({}).toArray();\n return lessonList;\n }", "async getNotes() {\n\t\ttry {\n\t\t\tconst notes = await readFileAsync(\"db/db.json\", \"utf8\");\n\t\t\treturn JSON.parse(notes)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the minimum distance vertex
getMinVertex() { let minVertex = -1; for (let i = 0; i < this.graph.length; i++) { if ( !this.visited[i] && (minVertex === -1 || this.dist[i] < this.dist[minVertex]) ) { minVertex = i; } } return minVertex; }
[ "function findMinDist() {\n let smallestV;\n let smallestDist = Number.MAX_VALUE;\n\n for (let v in Q) {\n v = +v; // Convert to int\n if (dist[v] <= smallestDist) {\n smallestDist = dist[v];\n smallestV = v;\n }\n }\n\n return smallestV;\n }", "selectMinDFromVS(){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region twilio handlers
function incomingTwilioHandler(connection) { twilioConnection = connection; connection.on("accept", function () { socket.emit('status', 1); callGoing(); Teamlab.saveVoipCall({}, currentCall.id, { answeredBy: Teamlab.profile.id }, { async: true, success: function (params, call) { currentCall = call; renderView(); } }); }); connection.on("disconnect", function () { if (!pause) { socket.emit('status', 0); } callCompleted(); }); connection.accept(); }
[ "function webhook(req, res, next) {\n\n console.log(\"Made it to the webhook!\")\n\n switch(req.body.type) {\n case \"message-created\":\n messageCreated(req.body);\n console.log(\"Message created!\")\n break;\n case \"space-members-added\":\n spaceMembersAdded(req.body);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refresh the transformation matrix on the page with the current matrix values
function updateTransformationMatrixDisplay () { // Divide by 1 to remove trailing zeroes $('#matrixElemA').val(matrix.a.toFixed(decimalPlaces) / 1) $('#matrixElemB').val(matrix.b.toFixed(decimalPlaces) / 1) $('#matrixElemC').val(matrix.c.toFixed(decimalPlaces) / 1) $('#matrixElemD').val(matrix.d.toFixed(decimalPlaces) / 1) }
[ "function mResetMatrix() {\n resetMatrix();\n mPage.resetMatrix();\n}", "function updateTransform() {\n scope.style.transform = 'translate(0,' + current + 'px)';\n }", "identity() { \n this.internal.gridTransformationList = [];\n this.internal.linearTransformation.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a single line of ABC notes (i.e., not a header line). We process an ABC song stream by dividing it into tokens, each of which is a pitch, duration, or special decoration symbol; then we process each decoration individually, and we process each stem as a group using parseStem. The structure of a single ABC note is something like this: NOTE > STACCATO? PITCH DURATION? TIE? I.e., it always has a pitch, and it is prefixed by some optional decorations such as a (.) staccato marking, and it is suffixed by an optional duration and an optional tie () marking. A stem is either a note or a bracketed series of notes, followed by duration and tie. STEM > NOTE OR '[' NOTE ']' DURAITON? TIE? Then a song is just a sequence of stems interleaved with other decorations such as dynamics markings and measure delimiters.
function parseABCNotes(str) { var tokens = str.match(ABCtoken), parsed = null, index = 0, dotted = 0, beatlet = null, t; if (!tokens) { return null; } while (index < tokens.length) { // Ignore %comments and !markings! if (/^[\s%]/.test(tokens[index])) { index++; continue; } // Handle inline [X:...] information fields if (/^\[[A-Za-z]:[^\]]*\]$/.test(tokens[index])) { handleInformation( tokens[index].substring(1, 2), tokens[index].substring(3, tokens[index].length - 1).trim() ); index++; continue; } // Handled dotted notation abbreviations. if (/</.test(tokens[index])) { dotted = -tokens[index++].length; continue; } if (/>/.test(tokens[index])) { dotted = tokens[index++].length; continue; } if (/^\(\d+(?::\d+)*/.test(tokens[index])) { beatlet = parseBeatlet(tokens[index++]); continue; } if (/^[!+].*[!+]$/.test(tokens[index])) { parseDecoration(tokens[index++], accent); continue; } if (/^.?".*"$/.test(tokens[index])) { // Ignore double-quoted tokens (chords and general text annotations). index++; continue; } if (/^[()]$/.test(tokens[index])) { if (tokens[index++] == '(') { accent.slurred += 1; } else { accent.slurred -= 1; if (accent.slurred <= 0) { accent.slurred = 0; if (context.stems && context.stems.length >= 1) { // The last notes in a slur are not slurred. slurStem(context.stems[context.stems.length - 1], false); } } } continue; } // Handle measure markings by clearing accidentals. if (/\|/.test(tokens[index])) { for (t in accent) { if (t.length == 1) { // Single-letter accent properties are note accidentals. delete accent[t]; } } index++; continue; } parsed = parseStem(tokens, index, key, accent); // Skip unparsable bits if (parsed === null) { index++; continue; } // Process a parsed stem. if (beatlet) { scaleStem(parsed.stem, beatlet.time); beatlet.count -= 1; if (!beatlet.count) { beatlet = null; } } // If syncopated with > or < notation, shift part of a beat // between this stem and the previous one. if (dotted && context.stems && context.stems.length) { if (dotted > 0) { t = (1 - Math.pow(0.5, dotted)) * parsed.stem.time; } else { t = (Math.pow(0.5, -dotted) - 1) * context.stems[context.stems.length - 1].time; } syncopateStem(context.stems[context.stems.length - 1], t); syncopateStem(parsed.stem, -t); } dotted = 0; // Slur all the notes contained within a strem. if (accent.slurred) { slurStem(parsed.stem, true); } // Start a default voice if we're not in a voice yet. if (context === result) { startVoiceContext(firstVoiceName()); } if (!('stems' in context)) { context.stems = []; } // Add the stem to the sequence of stems for this voice. context.stems.push(parsed.stem); // Advance the parsing index since a stem is multiple tokens. index = parsed.index; } }
[ "function parseStem(tokens, index, key, accent) {\n var notes = [],\n duration = '', staccato = false,\n noteDuration, noteTime, velocity,\n lastNote = null, minStemTime = Infinity, j;\n // A single staccato marking applies to the entire stem.\n if (index < tokens.length && '.' == toke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a CloudFormation stack artifact from this assembly.
getStackArtifact(artifactId) { const artifact = this.tryGetArtifactRecursively(artifactId); if (!artifact) { throw new Error(`Unable to find artifact with id "${artifactId}"`); } if (!(artifact instanceof cloudformation_artifact_1.CloudFormationStackArtifact)) { throw new Error(`Artifact ${artifactId} is not a CloudFormation stack`); } return artifact; }
[ "getStackByName(stackName) {\n const artifacts = this.artifacts.filter(a => a instanceof cloudformation_artifact_1.CloudFormationStackArtifact && a.stackName === stackName);\n if (!artifacts || artifacts.length === 0) {\n throw new Error(`Unable to find stack with stack name \"${stackName}\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cursor / Layout IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
function Separator() { bind.Separator(); }
[ "function VERTICAL_SEPARATOR_ELEMENT_ITEM$static_(){SeparatorBEMEntities.VERTICAL_SEPARATOR_ELEMENT_ITEM=( SeparatorBEMEntities.VERTICAL_SEPARATOR_BLOCK.createElement(\"item\"));}", "_containsSeparator() {\n return this.separator ? 'container-items-with-separator' : '';\n }", "get seperator() { return this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the specified guest is invited to the specified event. If so it returns the answer, otherwise it returns false.
function is_in_guest_list(event, guest){ var guests = event.getGuestList(); for (var j=0; j<guests.length; j++) { //Logger.log("Check guest "+guests[j].getEmail()); if(guests[j].getEmail()==guest){ var answer = guests[j].getGuestStatus(); //Logger.log("Answer of "+guest+": "+answer) return answer; } } return false; }
[ "function responseGameInvitation(e){\n\tvar recipientName = $(this).data(\"name\");\n\tif(recipientName == undefined || localStorage.gameTurn != undefined){\n\t\treturn false;\n\t}\n\tif(userNameChecker(recipientName)){\n\t\tvar recipientGameObject = getGameObject(recipientName);\n\t\tvar data = {\n\t\t\t\"recipien...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load transactions for the main chart graph.
loadGraph(){ var current = this; var servicePathAPI = baseURL+'/api/transactions/all/'+ this.dataToken; $.getJSON(servicePathAPI, function (data) { var result = data; if(result){ var series = []; var categories = []; for(var i=0;i < result.length;i++){ var item = result[i]; var transDate = new Date(item[0]); var transAmount = item[1]; categories.push( moment( transDate.getTime() ).format("MM/DD/YYYY") ); current._chartData.push( [ transDate, transAmount] ); } } // Create the transactions chart this._transactionChart = Highcharts.chart('mainChart', { rangeSelector : { selected : 1, allButtonsEnabled: true }, chart: { zoomType: 'x', alignTicks: false }, title : { text : 'Transaction Volume' }, xAxis: { type: 'datetime', categories: categories }, yAxis: { title: { text: 'USD' } }, tooltip: { formatter: function() { return 'Date: <b>' + moment(this.x).format("MM/DD/YYYY") + '</b> <br/> Amount: <b>$' + accounting.format(this.y) + '</b>'; } }, series : [{ name : 'Transactions', fillColor : { linearGradient : { x1: 0, y1: 0, x2: 0, y2: 1 }, stops : [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, data : current._chartData }] }); }); }
[ "async function OnLoadTransactions() {\n const write_key = JSON.parse(localStorage.getItem('microprediction_key_current'))[0];\n const url = base_url+write_key+\"/\";\n resp = await get(url);\n await LoadTransactions();\n document.getElementById(\"box-href\").href = \"transactions/\" + write_key + \"/\";\n do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HTML get element's HTML
get html() { return this.element.innerHTML; }
[ "get html() {\n return (this._htmlElement || this._element).innerHTML;\n }", "elementFromHTML(html) {\n const div = document.createElement('div');\n div.innerHTML = html.trim();\n return div.firstChild;\n }", "function getHtmlContent(){\n \n }", "function getHtml(elem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a position, calculate the best move using Stockfish Returns a deffered variable
function calcBestMove(game) { var engine = new UCI(STOCK_PATH); var deferred = Q.defer(); engine.runProcess().then(function () { return engine.uciCommand(); }).then(function (idAndOptions) { return engine.isReadyCommand(); }).then(function () { return engine.uciNewGameCommand(); }).then(function () { return engine.positionCommand(game.fen()); }).then(function () { return engine.goInfiniteCommand(console.log); }).delay(500).then(function () { return engine.stopCommand(); }).then(function (bestMove) { //TODO: Maybe need to translate this to a correct {to, from} dictionary. Maybe not deferred.resolve(bestMove); return engine.quitCommand(); }).then(function () { console.log('Stopped'); }).fail(function (error) { console.log(error); deferred.reject(error); process.exit(); }).done(); return deferred.promise; }
[ "function makeBestMove() {\n\t\t\t// look for winning move\n\t\t\t//then findBestCorner();\n\t}", "function computer_move(state) {\n // sends the state to the alphabeta() function to look 4 moves ahead and\n // determine the best move to make\n var moves = alphabeta(state, 4, 'red', Number.MIN_VALUE, Num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an OSS session. Providing aliyun access, secret keys and bucket are mandatory Region will use sane defaults if omitted
function OSSAdapter() { var options = optionsFromArguments(arguments); this._region = options.region; this._internal = options.internal; this._bucket = options.bucket; this._bucketPrefix = options.bucketPrefix; this._directAccess = options.directAccess; this._baseUrl = options.baseUrl; this._baseUrlDirect = options.baseUrlDirect; let ossOptions = { accessKeyId: options.accessKey, accessKeySecret: options.secretKey, bucket: this._bucket, region: this._region, internal: this._internal }; this._ossClient = new OSS(ossOptions); this._ossClient.listBuckets().then((val)=> { var bucket = val.buckets.filter((bucket)=> { return bucket.name == this._bucket }).pop(); this._hasBucket = !!bucket; }); }
[ "function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark an assignment as missing.
function missingAssignment(axios$$1, token) { return restAuthPost(axios$$1, '/assignments/' + token + '/missing', null); }
[ "function createNewAssignment(assignmentName,totalPointValue,assignmentData,gradebookData){\n var assignment = new Assignment(assignmentName,totalPointValue,assignmentData);\n assignmentData.push(assignment);//update the assignmentData array\n //task 9: set the default assignment score\n for (var i=0 ;i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find an macro argument without expanding tokens and append the array of tokens to the token stack. Uses Token as a container for the result.
scanArgument(isOptional: boolean): ?Token { let start; let end; let tokens; if (isOptional) { this.consumeSpaces(); // \@ifnextchar gobbles any space following it if (this.future().text !== "[") { return null; } start = this.popToken(); // don't include [ in tokens ({tokens, end} = this.consumeArg(["]"])); } else { ({tokens, start, end} = this.consumeArg()); } // indicate the end of an argument this.pushToken(new Token("EOF", end.loc)); this.pushTokens(tokens); return start.range(end, ""); }
[ "expandMacro(name) {\n if (!this.macros.get(name)) {\n return undefined;\n }\n\n const output = [];\n const oldStackLength = this.stack.length;\n this.pushToken(new Token(name));\n\n while (this.stack.length > oldStackLength) {\n const expanded = this.expa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replace a pattern in a word. if a replacement occurs an optional callback can be called to postprocess the result. if no match is made NULL is returned.
function attemptReplace(token, pattern, replacement, callback) { var result = null; if((typeof pattern == 'string') && token.substr(0 - pattern.length) == pattern) result = token.replace(new RegExp(pattern + '$'), replacement); else if((pattern instanceof RegExp) && token.match(pattern)) result = token.replace(pattern, replacement); if(result && callback) return callback(result); else return result; }
[ "function attemptReplace(token, pattern, replacement, callback) {\n\tvar result = null;\n\n\tif((typeof pattern == 'string') && token.substr(0 - pattern.length) == pattern)\n\t\tresult = token.replace(new RegExp(pattern + '$'), replacement);\n\telse if((pattern instanceof RegExp) && token.match(pattern))\n\t\tresul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove last row if state matches
removeRow(state) { if (this._rows.length > 0 && this._rows[this._rows.length - 1].state === state) { this._rows = this._rows.slice(0, -1); } }
[ "function removeLastRow() {\n let rows = $('#table tr');\n if (rows.length > 1) {\n rows.last().remove();\n }\n rowIndex--;\n}", "disposeRows() {\n // keep rows still in use, remove the others\n const keepers = [];\n this.rows.forEach((row) => {\n if (row.updateReference === this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the end index of the excerpt for the specified mention.
function excerptEnd(mention) { var i = mention.section.j, match; sentenceRe.lastIndex = mention.j + 40; match = sentenceRe.exec(mention.section.speech.text); return match ? Math.min(match.index + match[1].length, i) : i; }
[ "endIndex()\n\t{\n\t\tlet endIndex=0;\n\t\tlet startIndex=this.startIndex();\n\t\tif(this.pageCount()===this.props.currentPage)\n\t\t\tendIndex=this.pageCount();\n\t\telse if(startIndex+(this.props.buttonsCount-1)<=this.pageCount())\n\t\t\tendIndex=startIndex+(this.props.buttonsCount-1);\n\t\telse\n\t\t\treturn thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
13. Write a program to take user input and store username in a variable. If the username contains any special symbol
function validUsername() { var userName = prompt("Enter username"); var len = userName.split(""); for(i = 0; i < len.length; i++) { if( (userName.slice(i,i+1) == "@") || (userName.slice(i,i+1) == ".") || (userName.slice(i,i+1) == "!") ) { document.write("Invalid"); break; } } }
[ "function getUsername() {\n let userName = document.getElementById('username_input_field').value;\n\n // if username supplied is invalid, alert user, and return null\n const validUsernameRegExp = new RegExp('^([a-zA-Z0-9_-]{3,16})$');\n if (!validUsernameRegExp.test(userName)) {\n alert('Your username can on...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates document title to flag current spent time
_updateTitle() { document.head.querySelector('title').innerText = `[${this._toString('HH:mm:ss')}] @amjs/working-on`; }
[ "_updateTitle() {\n let ttl = '';\n if (this._curPage) {\n ttl = this._curPage.title();\n }\n document.title = this._rootArea.title(ttl);\n }", "function modify_title()\n{\n if( title != undefined ) document.title = \"Scheduler - \" + title;\n\n var title_state;\n \n if( document.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a command to the server to power off the stb
function powerOff() { sendPowerCommand('off'); }
[ "function reboot() {\n sendPowerCommand('reboot');\n}", "function powerOn() {\n sendPowerCommand('on');\n}", "function sendPowerCommand(command) {\n var deviceIds = LayoutUtil.getCheckedDevices();\n\n var cmdPattern = \"command:\"+ command;\n updateEventLog(\"Sending POWER \"+ cmdPattern, deviceI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When function is called, fn executes 2 things 1. Puts info together so that User is able to view the module added 2. Stores info in an array so that info can be send over to server 3. Removes selected option This event is not only binded to the button, it is also binded to the main form element. Currently, solving this problem unelegantly (LOOK AT THE IF STATEMENT)
function addEventForButton(button){ // Event Number 4 - Adds Module chosen // along with tut/lab/etc.. info button.on('click',function(){ var content = ''; //content holds info to be printed on the page for the user to see //module-info var moduleInfo; content += $('.control-group:first select').select2('val'); moduleInfo = $('.control-group:first select').select2('val').split(' ')[0]; $('#mod-code option').each(function(){ if($(this).text() === content){ $(this).remove(); } }); //Lecture Info var lec = []; $('.mod-info').find('div.lecture').each(function(){ var l = { type: $(this).find('label').text(), group: $(this).find('span').text() }; lec.push(l); }); // Other Info var tut = []; $('.mod-info').find('div.non-lecture').each(function(){ var t = { type:$(this).find('label').text(), group: $(this).find('span').text() }; tut.push(t); }); var allInfo = { label : moduleInfo, lectures: lec, tutorials: tut, }; $('.mod-pane').addClass('well'); addModuleButton(); $('.mod-pane table').append('<tr><td>' + content + '</td></tr>'); $('.mod-pane table tbody tr:last td').append('<button>&times;</button>'); $('.mod-pane table tbody tr:last td').find('button').addClass('close'); addEventForModuleTags(); allocModList.push(allInfo); $('#mod-code').trigger('select2-removed'); $("#mod-code").select2("val", ""); }); }
[ "function toggleTeam()\n{\n var pickedTeam = $('#teamNum').val() + \" \" + $('#event option:selected').text();\n if($('#list').hasClass('btn-success'))\n {\n userData.teamList.push(pickedTeam)\n changeToRemove();\n }\n else\n {\n removeFromTeamList(pickedTeam);\n change...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the dimension that is the largest
function largestAxisVec(dimensions) { var dimensionArray = []; for (var key in dimensions) { dimensionArray.push(dimensions[key]); } return Math.max.apply(null, dimensionArray); }
[ "findMax() { \n if(this.isEmpty()) return Number.MIN_VALUE;\n return this.heap[0];\n }", "_getMaxPointSize() {\n const e = this.encoders.size;\n if (e.constant) {\n return e(null);\n } else {\n return /** @type {number[]} */ (e.scale.range()).reduce((a, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the below functions create the different sized grid boards by adding new li DOM elements and then resizing them as a percentage of their container so create the correct grid shape.
function create8X8 () { for (i=0;i<64;i++){ var newSquare = "<li id="+parseInt(i)+"></li>"; $(".grid").append(newSquare); } $tileArray = $("li"); row_length = Math.sqrt($tileArray.length); $tileArray.css("height", "10%").css("width", "10%"); }
[ "function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicates if the filter is cached (via the cache method).
get isCached() { return this._cached }
[ "hasCache(identifier) {\n validation_1.CacheValidation.validateIdentifier(identifier);\n return this._resources.has(identifier);\n }", "function isCachedMIMEType(mimeType) {\n\t\tswitch (mimeType) {\n\t\t\tcase 'application/pdf':\n\t\t\t\treturn true;}\n\n\t\treturn false;\n\t}", "isCachedInMem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loops an array replacing one char w/ another
function charReplacer(array, oldChar, newChar) { for (let i = 0; i < array.length; i++) { array[i] = array[i].replace(oldChar, newChar); }; }
[ "function censorString(str, arr, char) {\n\treturn str.split(\" \").map(x => x.replace(new RegExp(arr.join('|'), 'g'), char.repeat(x.length))).join(\" \");\n}", "function replaceArray(original, replacement, av)\n {\n\tfor (var i = 0; i < original.size(); i++)\n\t{\n\t\toriginal.value(i, replacement.value(i));\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
react to sensor update
on_sensor_update(sensor){ // sensor.pitch // sensor.roll }
[ "notify_speed_update() {\n this.speed_update = true;\n }", "update_drone_stats(){\n this.update_location(new_location);\n this.update_sensor();\n this.update_battery(); // send drone info to remote maybe\n }", "function onStartSensor(sensor){\n\t\tconsole.log(\"Sensor\" + sensor + \"start\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the tree navigation content
function buildTreeNavigation() { var html = ''; html += '<div class="tree_roles">'; for (var i = 0; i < roles.length; i++) { var role = roles[i]; html += '<div class="tree_role">'; html += '<a href="' + i + '" class="tree_role_link"><img src="' + role.headshot + '" class="tree_role_img"/></a>'; html += ' <a href="' + i + '" class="tree_role_link tree_link_text">' + role.shortTitle + '</a>'; html += '</div>'; html += '<div class="tree_lessons">'; for (var j = 0; j < role.lessons.length; j++) { var lesson = role.lessons[j]; html += '<div class="tree_lesson">'; html += '<a href="' + j + '" class="tree_lesson_link"><img src="' + lesson.icon + '" class="tree_lesson_img"/></a>'; html += ' <a href="' + j + '" class="tree_lesson_link tree_link_text">' + lesson.title + '</a>'; html += '</div>'; } html += '</div>'; } html += '</div>'; $('#tree').html(html); $('#tree a.tree_role_link').bind('click', function(event) { event.preventDefault(); showLessons(getRole($(this).attr('href'))); }); $('#tree a.tree_lesson_link').bind('click', function(event) { event.preventDefault(); showLesson(getLesson( $(this).parent().parent().prevAll('.tree_role:first').children('a.tree_role_link').attr('href'), $(this).attr('href') )); }); }
[ "function buildNav() {\n for (section of sections) {\n target = section.id;\n sectionTitle = section.dataset.nav;\n createMenuItem(target, sectionTitle);\n }\n}", "function build_child_links(data) {\n // FIXME this code is disgusting, rewrite it\n var nav = $.map(data, function(it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get own property names from Node prototype, but only the first time `Node` is instantiated
function lazyKeys() { if (!ownNames) { ownNames = Object.getOwnPropertyNames(Node.prototype); } }
[ "getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }