query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
feature 3 and 4 : Filter by recent products and reasonable price object "currentFilter" has been created function to update the status of the check box associated with the filters
function setCurrentFilter(currentFilter) { if(filterRelease.checked==true){ currentFilter["release"]=true; } else{ currentFilter["release"]=false; } if(filterPrice.checked==true){ currentFilter["price"]=true; } else{ currentFilter["price"]=false; } if(filterFavorites.checked==true){ cu...
[ "function UpdateProductDetailsHelper(bNeedFilter) {\n //\n // Calcultae count & remove filter options with zero count when filter options has preset values\n //\n var bFilterStorage = HasFilterStorage();\n if (g_bFirstLoad && IsFilterCountEnabled() && (g_bHasPresetOptions || bFilterStorage)) // has p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the user id from the JWT payload.
function userId(jwtPayload) { return jwt_1.readPropertyWithWarn(jwtPayload, exports.mappingUserFields.id.keyInJwt); }
[ "function extractUserID(jwtToken){\n\tvar payload = jwt.decode(token);\n return payload.user_id;\n}", "function getUserId(req) {\n var idToken = req.headers.authorization;\n return jwt.decode(idToken).sub;\n}", "function getUserId (){\n let user = parseToken();\n return user._id;\n}", "getUserId() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets selected check box values separated by "|"
function getSelectedCheckBoxValues(frmObj) { var checked = ""; for (var i = 0; i < frmObj.elements.length; i++) { var elm = frmObj.elements[i]; if ((elm.checked) && (elm.type == 'checkbox')) { checked = checked + elm.value + "|"; } } return checked; }
[ "function checkBoxSelected(checkBoxName){\r\n\tvar array=new Array();\r\n\tvar checkName='input[name='+checkBoxName+']:checked';\r\n\t$(checkName).each(function(index){\r\n\t\tarray[index]=$(this).attr('value');\r\n\t});\t\r\n\treturn array.join(',');\r\n}", "function getSelectedCheckBoxValues(frmObj) {\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of MorphVertexes for this morphtarget.
getVertexCount() { return this.vertices.length; }
[ "_getMorphVertexCount(modelData, morphIndex, vertexBuffers) {\n for (let i = 0; i < modelData.meshes.length; i++) {\n const meshData = modelData.meshes[i];\n\n if (meshData.morph === morphIndex) {\n const vertexBuffer = vertexBuffers[meshData.vertices];\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test equality for arrays of strings or a string.
function equalArraysOrString(a, b) { if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; var aSorted = _toConsumableArray(a).sort(); var bSorted = _toConsumableArray(b).sort(); return aSorted.every(function (val, index) { re...
[ "function equalArraysOrString(a, b) {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length != b.length)\n return false;\n return a.every(function (aItem) { return b.indexOf(aItem) > -1; });\n }\n else {\n return a === b;\n }\n}", "function equalArraysOrString(a,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the game is reset, reshuffle the cards, flip any cards that have been flipped, remove any guesses from the cardsInPlay, and the cardInPlayId.
function resetGame() { cardShuffle(); resetBoard(); cardsInPlay = []; cardInPlayId = -1; }
[ "function resetGame() {\n\tresetClockAndTime();\n\tresetMoves();\n\tresetStars();\n\tshuffleDeck();\n\tresetCards();\n\tmatched = 0;\n\ttoggledCards = [];\n}", "function resetShuffle() {\n\t\t// put all the cards together and shuffle\n\t\tcards = cards.concat(drawn, discard);\n\t\tdrawn = [];\n\t\tdiscard = [];\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encodes a value the same way eosjs (de)serializes names eosjs name (de)serialization of names is different from the one that EOSIO uses
function convertName2ValueSerialized(name) { if (typeof name !== `string`) { throw new TypeError(`Expected string containing name`); } function charToSymbol(c) { if (c >= `a`.charCodeAt(0) && c <= `z`.charCodeAt(0)) { return c - `a`.charCodeAt(0) + 6; } if (c >= `...
[ "encodeNode(value, fnamesSeg) {\n\n // handle null\n if (value === undefined || value === null) {\n this.writeUInt8(constants.TNS_JSON_TYPE_NULL);\n\n // handle booleans\n } else if (typeof value === 'boolean') {\n if (value) {\n this.writeUInt8(constants.TNS_JSON_TYPE_TRUE);\n } e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transition animations on navigating to the add page
function addPageTransition(){ var habitList = document.getElementById('habit-list').children; var delay = 0; for (var i = 0; i < habitList.length; i++){ if (i != habitList.length - 1){ $(habitList[i]).delay(delay).animate({right: '1500px'}, 500); delay+=100; } ...
[ "function pageTransition() {\n let tl = gsap.timeline();\n\n tl.to('.transition-item', {\n duration: 0.3,\n scaleY: 1,\n transformOrigin: 'bottom left',\n stagger: 0.15,\n ease: 'power2.easeInOut',\n });\n tl.to('.transition-item', {\n duration: 0.3,\n scaleY: 0,\n tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a `ChainedInterceptorFn` which wraps and invokes a functional interceptor in the given injector.
function chainedInterceptorFn(chainTailFn, interceptorFn, injector) { // clang-format off return (initialRequest, finalHandlerFn) => injector.runInContext(() => interceptorFn(initialRequest, downstreamRequest => chainTailFn(downstreamRequest, finalHandlerFn))); // clang-format on }
[ "function legacyInterceptorFnFactory() {\n let chain = null;\n return (req, handler) => {\n if (chain === null) {\n const interceptors = (0,_angular_core__WEBPACK_IMPORTED_MODULE_4__.inject)(HTTP_INTERCEPTORS, {\n optional: true\n }) ?? [];\n // Note: interceptors are wrapped right-to-lef...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to decrypt data(password)
function decrypt(password) { var decipher = crypto.createDecipher(algorithm, privateKey); var dec = decipher.update(password, 'hex', 'utf8'); dec += decipher.final('utf8'); return dec; }
[ "function PasswordDecryption(password) {\n return actualPassword;\n}", "function decrypt(password) {\n var decipher = crypto.createDecipher(algorithm, privateKey);\n console.log(\"decipher\",decipher,password);\n var dec = decipher.update(password, 'hex', 'utf8');\n dec += decipher.final('utf8');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new IntegrationType.
constructor() { IntegrationType.initialize(this); }
[ "function createIntegration() {\n const integration = new VitalSourceContentIntegration(document.body, {\n bookElement: fakeBookElement,\n });\n integrations.push(integration);\n return integration;\n }", "constructor() { \n \n IntegrationId.initialize(this);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcion para Confirmar Cerrar Sesion
function confirmCerrar() { var respuesta = confirm("¿Seguro que deseas Salir?"); if (respuesta == true) { return true; }else if (respuesta == false) { return false; }else{ alert("¡Error de Confirmacion!"); } }
[ "function confirmBorrar() {\r\n var respuesta = confirm(\"¿Seguro que deseas Borrar el Registro?\");\r\n if (respuesta == true) {\r\n return true;\r\n }else if (respuesta == false) {\r\n return false;\r\n }else{\r\n alert(\"¡Error de Confirmacion!\");\r\n }\r\n}", "function con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a function to add the user to a property called user on the requests object aka req.user
function addUserToRequest(req, res, next) { // check if user is added to request if (req.user) return next(); // check to see if there is a session created if(req.session && req.session.userId){ // find the user based on there id and then add them to the request object User.findById(req.ses...
[ "function AddUser(req, res, next) {\n if (!req.userContext) {\n return next();\n }\n\n auth.oktaClient.getUser(req.userContext.userinfo.sub)\n .then(user => {\n req.user = user;\n res.locals.user = user;\n next();\n }).catch(err => {\n next(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format Array for highlighting
function format4highlight(inputArray){ let changes = {}; //for each row select which columns will be highlight and what style //CSS file controls actual color output inputArray.forEach(function(d){ changes[d]={ user_name: "current-user", user_location: "current-user",...
[ "function highlightUserSpecified(){\n\n\n\n var userSpecifiedArray = new Array();\n var newArray = new Array();\n\n //Quads for word \"For\" --word Quad\n //236.90859985351562,458.2436828613281,265.9341125488281,458.2436828613281,236.90859985351562,425.3403625488281,265.9341125488281,425.3403625488281\n\n //Qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of elements in an arraymap type of object
function count_map_el(array_map) { "use strict"; var prop, counter = 0; for (prop in array_map) { if (array_map.hasOwnProperty(prop)) { counter += 1; } } return counter; }
[ "function size$1(map) {\r\n var acc = 0;\r\n var _map_keys = Object.keys(map);\r\n for (var i = 0; i < _map_keys.length; i++) {\r\n var row = Number(_map_keys[i]);\r\n var columns = map[row];\r\n acc += Object.keys(columns).length;\r\n }\r\n return acc;\r\n}", "function count(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
arrayFor([1, 2, 3]) > 1 2 3 Write a function called arrayWhile that takes an array as a parameter, loops through all the elements using While Loop and prints all elements of the array in the console using console.log.
function arrayWhile(array) { //Write your code here }
[ "function bucle5DoWhile(array){\n var i = 0;\n do {\n console.log(array[i]);\n i++;\n }while (i < array.length);\n\n}", "function whileLoop(arr) {\n let i = 0;\n while (arr[i]) {\n console.log(arr[i]);\n i++\n }\n}", "function looper (array){\n var i = 0;\n while( i < array.len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
~ if (activeDocument.bitsPerChannel != BitsPerChannelType.SIXTEEN || activeDocument.bitsPerChannel != BitsPerChannelType.THIRTYTWO) activeDocument.bitsPerChannel = BitsPerChannelType.EIGHT; ~ SavePSD(saveFile, 8);
function SavePSD(saveFile){ psdSaveOptions = new PhotoshopSaveOptions(); psdSaveOptions.embedColorProfile = true; psdSaveOptions.alphaChannels = true; activeDocument.saveAs(saveFile, psdSaveOptions, false, Extension.LOWERCASE); }
[ "function saveFile()\n{\n // Save document\n var tmpFile = new File( '/tmp/temp.psd');\n psdOpts = new PhotoshopSaveOptions();\n psdOpts.embedColorProfile = true;\n psdOpts.alphaChannels = true;\n psdOpts.layers = true;\n app.activeDocume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a gateway query parameter is added, remove it.
function stripGatewayAuthenticationParameter (aUrl) { if (aUrl.query && aUrl.query.useGateway) { delete aUrl.query.useGateway } if (aUrl.query.nextUrl) { var theNextUrl = decodeURIComponent(aUrl.query.nextUrl) aUrl.query.nextUrl = decodeURIComponent(theNextUrl) } var theUrl = url.format(aUrl) r...
[ "[types.UNSELECT_API_PARAM](state, paramName) {\n const i = _.findIndex(state.queryParams, param => !_.isUndefined(param[paramName]));\n\n if (i >= 0) {\n state.queryParams.splice(i, 1);\n }\n }", "clearOptionalQueryParams() {\n const url = new URL(window.location.href);\n for (const param in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds themes to options of theme select menu
function createThemeOptions (theme, currentIndex) { // populate theme select menu $('#selectTheme').append(` <option value="${currentIndex}">${theme}</option> `); }
[ "function createThemeChanger(){\n var selectElement = document.createElement('select'),\n optionElement = null;\n\n _(themes).forEach(function (theme){\n optionElement = createOptionElementByTheme(theme);\n selectElement.appendChild(optionElement);\n }).value();...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BUTTON PLUGIN DEFINITION ========================
function Plugin(option){return this.each(function(){var $this=$(this);var data=$this.data('bs.button');var options=(typeof option==='undefined'?'undefined':_typeof(option))=='object'&&option;if(!data)$this.data('bs.button',data=new Button(this,options));if(option=='toggle')data.toggle();else if(option)data.setState(opt...
[ "function Plugin(option){return this.each(function(){var $this=$(this);var data=$this.data('bs.button');var options=(typeof option===\"undefined\"?\"undefined\":(0,_typeof4.default)(option))=='object'&&option;if(!data)$this.data('bs.button',data=new Button(this,options));if(option=='toggle')data.toggle();else if(op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Can we borrow the code from the Person function and use it in the Student function? We can use call() or apply() rewrite Student
function Student() { Person.apply(this, arguments); }
[ "function Student() {}", "function Person(name, job, age){ //1\n this.name = name;\n this.job = job;\n this.age = age; //1\n this.exercise = function(){ //2\n return console.log('Basketball is fun!') //2\n }\n this.fetchJob = function(){ //3\n return console.log(`${this.name} is a ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to display the repeat box
function showRepeat(which) { // checkboxk object var checkObj = document.getElementById("clsRepeat" + which); // checked means setting up a repeat if (checkObj.checked) { // save which one we're repeating in global repeatWhich = which; // detect position of repeat box ...
[ "roundRepeat() {\n $('#repeat-button').html('Try Round ' + round.roundNumber + \" Again\");\n $('.game-container').css('display', 'none');\n $('#modal-repeat').css('display', 'block');\n eventHandlers.repeatRound();\n }", "function showPattern(increment){\n\t//First lock the game\n\tlockGam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a row to the roles table
function addRoleToRolesTable(role){ //turn permission array into string and remove the front and back quotation marks let permsString = role.perms.toString(); permsString = permsString.replaceAll('"', ''); let rolesTableRow = '<tr>' + '<th scope="row">' + role.roleId + '</th>' + ...
[ "addRole(role) {\n return this.connection.query(\"INSERT INTO roles SET ?\", role);\n }", "addRole(role) {\n return this.connection.query(\n \"INSERT INTO role SET ?\", role\n );\n }", "function addRole(role) {\n roles.push(role);\n}", "addRole(Role) {\n return connec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=> 3 Under the hood: 1. Global Execution Context => includes variables 'buildFunctions' and 'fs' 2. buildFunctions() Execution Context => includes variables 'i' and 'arr' => the loop runs and creates 3 anonymous functions and pushes them to arr the buildFunctions() Execution Context is popped off stack back inside the ...
function buildFunctions2() { var arr = []; for (var i = 0; i < 3; i++) { let j = i; // this var j will be scoped to the block arr.push(function() { // and will be a new var in memory console.log(j); } ) } return ar...
[ "function buildFunctions2() {\n var arr = [];\n\n for (var i = 0; i < 3; i++) {\n arr.push( // pushing the result of the funciton(j)\n (function(j) { // creation of the IIFE (new Ex Context)\n return function() {\n console.log(j)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of Image. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Image.__pulumiType; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === GalleryImage.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show Lizard Spock is called when the user clicks on the play Lizard Spock button. It makes the main area appear and hides the main menu area and any classic game related elements.
function showLizardSpock() { document.getElementById("rock-paper-scissors-h1").style.display = "none"; document.getElementById("classic-rules").style.display = "none"; document.getElementsByClassName("main-menu-area")[0].style.display = "none"; document.getElementsByClassName("main-area")[0].style.displ...
[ "function showClassic() {\n document.getElementById(\"lizard-spock-h1\").style.display = \"none\";\n document.getElementById(\"lizard-button\").style.display = \"none\";\n document.getElementById(\"spock-button\").style.display = \"none\";\n document.getElementById(\"lizard-rules\").style.display = \"no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change 5: Wrapping jsPsych.init() in a function
function initExp() { // push all the procedures, which are defined in stop-it_main.js to the overall timeline var timeline = []; // this array stores the events we want to run in the experiment // use the full screen // also playing sound only works after an interaction with user, like...
[ "function initializeJsPsych(experiment) {\n\n experiment.createTimeline()\n experiment.addPropertiesTojsPsych()\n experiment.setStorageLocation()\n\n jsPsych.init({\n timeline: experiment.getTimeline(),\n show_progress_bar: true,\n display_element: $('#jspsych-target'),\n on_finish: function() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this just reads and stores the file 'users.json' on initGame
function fillUpUserObj() { fs.readFile('users.json', function (err, data) { if (!err) { try { userObj = JSON.parse(data); } catch (e) { console.error(e); } } }); }
[ "function readUsers() {\n return readJsonFile(USER_FILE_PATH, []);\n}", "function readUsersFile() {\n try {\n users = jsonfile.readFileSync(FILE_PATH) || [];\n } catch(ex) {\n if (ex.code === 'ENOENT') {\n console.log('Users file not exists, no problem I will make it for you');\n writeUsersFi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
simple throttling function for playing sounds
function throttleSound (name, volume, wait = 300) { let throttled; return () => { if (!throttled && isGameRunning) { playSound(name, volume); throttled = true; setTimeout(() => { throttled = false; }, wait); } }; }
[ "play (opts) {\n const index = this.playCount % this.sounds.length;\n this.playCount ++;\n const sound = this.sounds[index];\n sound.play(opts);\n }", "play() {}", "function playSilenceForMillis(length) {\n var iterations = length / 2;\n for (var i = 0; i < iterations * 30; i++) {\n soundData....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a listener to call when the HookSession receive a HookMessage with match=true
addMatchListener(hookid,callback,weight=-1){ if(this.listeners[hookid]==null) this.listeners[hookid] = []; this.listeners[hookid].push(callback); return this; }
[ "eventListener() {\n // UNCOMMENT THIS LINE TO DEBUG ALL SLACK EVENTS\n // this.rtm.on('slack_event', (event, info) => console.log(info));\n this.rtm.on('ready', () => console.log('Slack RTM connected.'));\n this.rtm.on('message', (event) => {\n if (event.channel[0] === 'D' && event.user !== this.b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plugin for HtmlPlugin which inlines the Webpack runtime code and chunk manifest into the HTML in a tag before other emitted asssets are injected by HtmlPlugin itself.
function inlineRuntimePlugin() { this.hooks.compilation.tap('inlineRuntimePlugin', compilation => { compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tapAsync('inlineRuntimePlugin', (data, cb) => { Object.keys(compilation.assets).forEach(key => { if (!/^runtime\.[a-z\d]+\.js$/.test(key)) retur...
[ "function injectManifestPlugin() {\n this.plugin('compilation', function (compilation) {\n compilation.plugin('html-webpack-plugin-before-html-processing', function (data, cb) {\n Object.keys(compilation.assets).forEach(function (key) {\n if (!key.startsWith('manifest.')) return;\n var childr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================= Funcion para insertar datos en la tabla consecutivo_ascensores ==============================================
function addItemConsecutivoAscensores(codigo, consecutivo) { var inspeccion = "ASC"+codigo+"-00"+consecutivo+"-"+anio; db.transaction(function (tx) { var query = "INSERT INTO consecutivo_ascensores (k_codusuario, k_consecutivo, n_inspeccion) VALUES (?,?,?)"; tx.executeSql(query, [codigo,"00"+con...
[ "function crearTablaConsecutivoAscensores(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE consecutivo_ascensores (k_codusuario, k_consecutivo unique, n_inspeccion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert input sheet data to objects
function converter(inputDataSheet) { let data = []; for (let i = 2;; i++) { if (inputDataSheet.getRange(`A${i}`).getValue() == 0) break; data[i - 2] = { query: inputDataSheet.getRange(`A${i}`).getValue(), click: inputDataSheet.getRange(`B${i}`).getValue(), impr: inputDataSheet.getRange(`...
[ "function sheetToObject(sheet) {\n return sheet.sheets.reduce(function(prev,cur){\n prev[cur.properties.title] = tableToObject(trimFlat(worksheetToFlat(cur)));\n return prev;\n }, {});\n}", "convertSpreadSheetDataToArrayOfObjects() {\n console.log('Entering convertSpreadSheetDataToArrayOfObjects....');...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
used internaly, to check collection properties Function accepts single parameter (collectionObject_sPropertie) Returns boolean (true === 'valid collection object')
function _isCollection(collectionObject_sPropertie) { // init var valid, validProperties, collection_sProperties; // Check if configuration object valid = typeof collectionObject_sPropertie === 'object'; collection_sProperties = ['db', 'topology', 'dbName', 'options', 'namespace', 'serializeF...
[ "function CfnCollectionPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert 'nbr' to a 'len' hexadecimal string.
function toHex(nbr, len) { return ("0"+(Number(nbr).toString(16))).slice(-len).toUpperCase() }
[ "function toFixedHex(num, len) {\n return num.toString(16).toUpperCase().padStart(len, '0').substring(0, len)\n}", "function intToHex(num, length) {\n\tvar ret = num.toString(16);\n\twhile (ret.length < length) {\n\t\tret = '0' + ret;\n\t}\n\treturn ret;\n}", "function hexStr(num, length, prefix) {\n let st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load Meal Plan page
async function loadMealPlanPage() { cleanUp(); // show($mealPlan); drawMealPlanTable(); setColorBgForMealPlanTable(); await fillMealPlanTable(); }
[ "function loadMealPlan(e){\n // Grab meal plan container\n const container = getSection(e);\n // Clear previous meal plan\n cleanSectionData(container);\n\n // Grab date from target button\n const date = e.target.dataset.firstDay;\n let passedDate;\n // Get Pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the values for each path to determine its best word
findPathValues(){ gridPaths.forEach(function(path){ var pathCharacters = path.split(''); var highPoint = BadBoggle.charValue(pathCharacters[0]); var currValue = 0; var bestWord = ''; // Find the high point pathC...
[ "displayBestWord(){\n var bestValue = pathValues[0].value;\n var bestWord = '';\n\n pathValues.forEach(function(pathValue){\n if(pathValue.value > bestValue){\n bestValue = pathValue.value;\n bestWord = pathValue.word;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the field formats for various part screens
static partFieldFormat(sectionProxy, key = '') { let section = sectionProxy.getName(); let property = sectionProxy.getProperty(); let binding = sectionProxy.binding; let textCategory = libCom.getAppParam(sectionProxy, 'PART', 'TextItemCategory'); let textDescription = sectionPro...
[ "_formatField() {\n const cards = JSON.parse(this.model.getDraftField(\n this.jsonFieldName || this.fieldID, {\n useExtraData: this.useExtraData,\n }));\n this._renderValue(cards);\n }", "_formatField() {\n const value = this._loadValue();\n\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts processed commits to markdown
function generateMarkdown(allCommits) { var output = ""; for (const type in allCommits) { const typeLabel = typeLabels[type]; const commits = allCommits[type]; // Check if there are any commits of this type if (commits && commits.length > 0) { output += `## ${typeLabel}\n`; commits.fo...
[ "function generateMarkdown(allCommits) {\n var output = \"\"\n\n for (const type in allCommits) {\n const typeLabel = typeLabels[type]\n const commits = allCommits[type];\n\n // Check if there are any commits of this type\n if (commits && commits.length > 0) {\n output +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes a linked list and returns true if the list is sorted and false otherwise e.g. 1 > 2> 3> 5> 10 returns true 3 > 1 > 4 returns false list is sorted if for each element e, e.data <= e.next.data (if e.next exists)
function isSorted(list) { let n = list; let check = null; let tmp = []; while (n != null && n.next != null) { if (n.data <= n.next.data) { if (tmp != 0) { for (let i = 0; i < tmp.length; i++) { if (n.data < tmp[i]) { check =...
[ "function isSortedR(linkedList) {\n}", "function isListSorted(arr){\n let lastPriority = 6;\n for(let obj of arr){\n let todoPriorety = obj.priority;\n if(todoPriorety > lastPriority){\n return false;\n }\n lastPriority = todoPriorety;\n }\n return true;\n}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Triggered in the check images modal to close it
function closeImages() { vm.modal.hide(); screen.unlockOrientation(); }
[ "function closing(){\n modal.style.display = \"none\";\n \n $(Info_Open).css(\"display\",\"none\");\n }", "function close() {\n bulmaModal.destroy();\n }", "onClickCloseModal() {\n this.template.querySelector(\"c-modal\").hide();\n }", "closePerformChecksMod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for previous and next challenge and return their name and url
function getNearbyChallenges (challengeNumber) { const previousNumber = parseInt(challengeNumber, 10) - 1 const nextNumber = parseInt(challengeNumber, 10) + 1 let previousUrl = '' let previousName = '' let nextUrl = '' let nextName = '' if (previousNumber === 0) { previousName = 'All Challenges' ...
[ "_challengeURLMatches() {\r\n return window.location.pathname.match(/challenges\\/(\\d+)\\/(?:train|edit)\\/([a-zA-Z-_\\+#]+)/);\r\n }", "load_next_challenge() {\r\n this.success(\"Good JOB! You solved the question\", \"green\");\r\n if (this.challenges.has_next_challenge()) {\r\n con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a fake birthdate for this age
getFakeBirthdate(age) { age = parseInt(age); if (!age) { return ''; } return moment().subtract(age, 'years').startOf('year').format('YYYY-MM-DD'); }
[ "get birthdate() {\n return new Date();\n }", "function childBirthDate() {\n return moment().subtract(Math.pow(365.25*18,Math.random()),'days').format(\"YYYY-MM-DD\");\n }", "SetBirthday()\n {\n let year = this.date.getUTCFullYear();\n let month = this.date.getUTCMonth();\n let day = this.date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expands all rows (in tree mode).
expandAllRows() { const that = this; if (!that.hasAttribute('hierarchy') || that.grouping) { return; } function expand(siblings) { for (let i = 0; i < siblings.length; i++) { const sibling = siblings[i]; if (sibling.le...
[ "expandAll() {\n this.expansionModel.clear();\n const allNodes = this.dataNodes.reduce((accumulator, dataNode) => [...accumulator, ...this.getDescendants(dataNode), dataNode], []);\n this.expansionModel.select(...allNodes);\n }", "function expandAll() {\n expand(root);\n //ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the activities array with City and Country
function updateActivityLocation(header, data){ var activities = data.activities; var cityIndex = header.indexOf('City'); var countryIndex = header.indexOf('Country'); var latIndex = header.indexOf('Latitude'); var lngIndex = header.indexOf('Longitude'); var updatedActivities = 0; // Loop through the da...
[ "function updateElementOfVisitArray(initialEntityObj, newEntityObj) {\n var start_date = (initialEntityObj.start_date != newEntityObj.start_date) ? true : false;\n var end_date = (initialEntityObj.end_date != newEntityObj.end_date) ? true : false;\n var city = (initialEntityObj.city != newEntityObj.city) ?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a ECDSA key pair over curve secp256k1
function generateECDSA() { // generate key pair with bitcoinjs-lib var mnemonic = bip39.generateMnemonic(160); var seed = bip39.mnemonicToSeed(mnemonic); var hdnode = bitcoin.HDNode.fromSeedBuffer(seed); // public key: generate an uncompressed key with Q = d*G var ecparams = KJUR.crypto.ECPara...
[ "function generateECDSA$1(curve) {\n var parts = [];\n var key;\n if (CRYPTO_HAVE_ECDH) {\n /*\n \t\t * Node crypto doesn't expose key generation directly, but the\n \t\t * ECDH instances can generate keys. It turns out this just\n \t\t * calls into the OpenSSL generic key generator, and we c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handling the timer of Infinity Section
function timer() { if (sec === 59) { min = min + 1; sec = 0; } else { sec = sec + 1; } if (sec < 10 && min < 10) { document.querySelector(".infinity-min").innerText = "0" + min; document.querySelector(".infinity-sec").innerText = "0" + sec; } else if (sec < 10 && min >= 10) { document....
[ "function infiniteTimer() {\n hideTimerBtns(); \n m, resetTime = 0;\n pos = true; \n startTime = 0; \n changedTmr = false; \n changedTimer(this);\n }", "function tick_infinity(){\n\t\tlogic();\n\t\tif(counter_stop == 1){\n\t\t\tcounter_stop = 0;\n\t\t\tclearInterv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
comparator which implements sorting by: db.fieldOrders.dedup must calculate it's own digest
function dedupOrderComparator(item) { const { __user, __type, uuid, __stamp, __sourceType } = item const digest = utils.digest(JSON.stringify(item)) return [__user, __type, uuid, __stamp, __sourceType, digest] }
[ "_keyFieldComparator(i) {\n const invert = !this._sortSpecParts[i].ascending;\n return (key1, key2) => {\n const compare = LocalCollection._f._cmp(key1[i], key2[i]);\n\n return invert ? -compare : compare;\n };\n }", "_key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles start button action: creates local MediaStream.
function startAction() { startButton.disabled = true; navigator.mediaDevices.getUserMedia(mediaStreamConstraints) .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); console.log('Requesting local stream.'); }
[ "function startAction() {\n startButton.disabled = true;\n acceptButton.disabled = true;\n console.log(\"Local stream added\");\n navigator.mediaDevices.getUserMedia(constraints)\n .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);\n}", "function startAction() {\n startButton.disabled = true;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the mouse button of an event to the list of currently pressed buttons
static _HandleButtonDown(e) { if (!Mouse._button_down.includes(e.button)) Mouse._button_down.push(e.button) }
[ "function mousePressed() {\n const curr_mouse_pos = createVector(mouseX, mouseY);\n\n for (const [key, button] of Object.entries(buttons)) {\n if (button.r.dist(curr_mouse_pos) < button.m) {\n state.prev_mouse_pos = null;\n state.pressed_button_key = key;\n return;\n }\n }\n\n // Change cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates role questions based on current departments available
async function generateRoleQuestions() { // First two questions are static let roleQuestions = [ { name: "roleName", type: "input", message: "What is the name of the role?" }, { name: "salary", type: "input", messag...
[ "function createDepartmentQuestionList(departments) {\n let choices = [];\n for (const { name, id } of departments) {\n const choice = {\n name,\n value: id,\n };\n choices.push(choice);\n }\n return {\n type: \"list\",\n name: \"department_id\",\n message: \"Select the Department\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Centers each element of given class on their frets.
function center(elementClass) { $(elementClass).each(function() { var yPos = ($(this).parent().width() / 2) - ($(this).width() / 2); $(this).css("left", yPos); }); }
[ "function centerElements(ev)\r\n{\r\n var elementsToCenter = document.getElementsByClassName(\"js-vertical-center-child\");\r\n var childSizes = new Array();\r\n var parentSizes = new Array();\r\n var curParent = undefined;\r\n for (var i = 0; i < elementsToCenter.length; i++)\r\n {\r\n curParent = undefin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive blocks referred to group id
function getGroupBlocks(group_id, callback = function(){}) { var req = $.ajax({ type: "GET", url: "ajax.php", data: "group_id=" + group_id + "&type=blocks", success: function(msg) { blocks.push(JSON.parse(msg)); var index = ajaxreqs.indexOf(this); if (index > -1) { array.splice(index, 1); }...
[ "addReceiveToConnector (groupAddressReferenceID) {\n _.last(_.last(_.last(_.last(_.last(this.project.topology.areas).lines).devices).communicationObjectReference).connectors).receive.push({\n __groupAddressRefID: groupAddressReferenceID\n })\n }", "async function onGroupReceived(ev) {\n const d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update rights for sharing with the gallery
function updateShareWithGallery(action) { var progName = $('#share-with-gallery').data('progName'); PROGRAM.shareProgramWithGallery(progName, function(result) { if (result.rc === 'ok') { LOG.info("share program " + progName + " with Gallery"); $('#progList').f...
[ "function updatePermissions(){\n\n}", "function saveShare(resource) {\n setPermissions(resource);\n }", "function addShareAndRights() {\n\tvar alias = $(\"#shareAlias\").val();\n\tvar folder = $(\"#pathInput1\").val();\n\tvar user = $(\"#userInput\").val();\n\tvar right = $(\"#right\").val()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processes the accessibility analsysis response; map zooms to the resulting area, area is shown on the map
function accessibilitySuccessCallback(result) { result = result.responseXML ? result.responseXML : util.parseStringToDOM(result.responseText); //when the service gives response but contains an error the response is handeled as success, not error. We have to check for an error tag here: var responseError = uti...
[ "function handleAnalyzeAccessibility(atts) {\n\t\t\tvar pos = atts.position;\n\t\t\tif (pos) {\n\t\t\t\t//assuming we have a position set...\n\t\t\t\tpos = util.convertPositionStringToLonLat(pos);\n\t\t\t\tpos = util.convertPointForDisplay(pos);\n\t\t\t\tvar dist = atts.distance;\n\n\t\t\t\tui.showAccessibilityErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for updating or creating a Lambda function
function updateOrCreateFunction(name, code, role) { const Lambda = new AWS.Lambda(); return new Promise(function(resolve, reject) { Lambda.getFunction({ FunctionName: name }, function(err, data) { if (err) { if (err.code === 404 || err.code === 'ResourceN...
[ "function createLambda() {\n var lambdaFunction = deployedLambdaFunctions.find(function (f) {\n return f.FunctionName === lambdaFunctionName;\n }) || null;\n\n if (lambdaFunction === null) {\n return lambda.createFunction(Obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When deleting we do not fix up indices but simply remove the according table row and add an invisible input element with the name varprefix + "_deleted_%nr"
function valuespec_listof_delete(oA, varprefix, nr) { var oTr = oA.parentNode.parentNode; // TR var oTbody = oTr.parentNode; oInput = document.createElement("input"); oInput.type = "hidden"; oInput.name = "_" + varprefix + '_deleted_' + nr oInput.value = "1" var oTable = oTbody.parentNode; ...
[ "function deleteEntryFromTable(indexNumToDelete){\n var tableRows = $('#weight-table').find('tr');\n tableRows[indexNumToDelete*2].remove(); \n tableRows[indexNumToDelete*2+1].remove(); \n \n}", "function btn_del_tr(index) {\n $(index).parent().parent().remove();\n GenerarArregloPagos();\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets actual selected lava display index.
function GetDisplayIndex() { return actualDisplayIndex; }
[ "get displayIndex() {}", "get selectedIndex() {\n var tree = this.getElement({type: \"engine_list\"});\n var treeNode = tree.getNode();\n\n return treeNode.view.selection.currentIndex;\n }", "set displayIndex(value) {}", "getSelectedIndex() {\n const defaultSelectedIndex = this.getStoredValue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add tabs functionality to the right side content
function jgtContentTabs(){ var tabsNav = $('#menu'), tabsWrap = $('#main'); tabsWrap.find('.main-section:gt(0)').hide(); //~ tabsNav.find('li:first').addClass('active'); tabsNav.find('a').click(function(e){ tabsWrap.find('.main-section').hide(); tabsWrap.find($($(this).attr('href'))).fadeIn(800); //~ tabsN...
[ "function tabsRight() {\n\tcallOnActiveTab((tab, tabs) => {\n\t\tdebug(`Starting at id: ${tab.id}, index: ${tab.index}`);\n\t\tlet next = tab.index;\n\t\tif(ACTIVE_TAB == false) {\n\t\t\tif((tab.index+1) == tabs.length) {\n\t\t\t\t// already at last tab\n\t\t\t\tdebug(\"Nothing to do.\");\n\t\t\t\treturn;\n\t\t\t}\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates how overdue an item is
function calculate_overdue(item) { return (Date.now()-Date.parse(item.available_at))/(1000*60*60)/srs_intervals[item.srs]; }
[ "function totalFine(items) {\n return items.reduce(function (total, item) {\n return total + item.fine_due - item.fine_paid;\n }, 0);\n }", "getTournamentOverdueCnt() {\n var cnt = 0, i; \n var d = Date.now();\n if (this.tournament.paymentdeadline != \"0\") {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A simple example > Here we are going to find the power of a number using recursion
function pow(number, power) { if (power == 1) { console.log("number",number) return number; } else { console.log("power",power) console.log("number",number) return number * pow(number, power - 1) } }
[ "function powerCalculator(base, power){\n if(power === 0) return 1\n return base * powerCalculator(base, power -1)\n \n }", "function power(base, n) {\n \n}", "function numberToPower(number, power) {\n // return number ** power;\n if (power === 0) return 1;\n console.log(10);\n let ans = number;\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the model with the given data without considering the data as "changed".
initialize(data) { this.$exists = false; this.$changed = {}; this.$attributes = {}; this.fill(data); this.$initialized = true; return this; }
[ "initialize(data) {\n this.$exists = false;\n this.$changed = {};\n this.$attributes = {};\n this.fill(data);\n this.$initialized = true;\n return this;\n }", "beforeInitialize(component, data) {\n data.shape = null;\n\n data.model = new Model();\n data.model.graph = new Gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the number of animation cycles.
get animationCycles() { return this._animationCycles; }
[ "getFrameCount () {\n return this.curves.length / CurveTimeline.BEZIER_SIZE + 1;\n }", "getFrameCount () {\r\n return this.curves.length / CurveTimeline.BEZIER_SIZE + 1;\r\n }", "getFramesNum() {\n const fps = this.rootConf('fps');\n return Math.floor(fps * this.duration);\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render new list of favorites after an update
updateFavs() { document.getElementById('favorites_results').innerHTML = this.render(); }
[ "function putFavoritesOnPage() {\n $favStoriesList.empty();\n let favorites = currentUser.favorites;\n for (let favorite of favorites) {\n favorite.favorite = true;\n putNewFavoriteOnPage(favorite);\n }\n\n $favStoriesList.show();\n}", "function renderFavorites() {\r\n removeBooksFromDOM();\r\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update cookies with HTTP response httpHeader Value of HTTP SetCookie header (string/array) domain Set from hostname path Set from pathname
update(httpHeader, domain, path) { // One Set-Cookie is a string, multiple is an array const headers = isArray(httpHeader) ? httpHeader : [httpHeader]; headers.map(cookie => Cookie.parse(cookie)).filter(cookie => cookie).forEach(cookie => { cookie.domain = cookie.domain || domain; cookie.path = ...
[ "_setCookieHeaders() {\n\t\tfor (var [name, param] of this._internalCookieStorage) {\n\t\t\tthis._response.cookie(name, param.value, param.options);\n\t\t}\n\t}", "setCookie(name, value, hostname, httpOnly = true) {\n const expires = new Date(2100, 1, 1).toUTCString();\n const hostport = hostname || this.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determines more accurately if a grid cell (x,y) is within cursor radius
function intersectRadius(x, y, mouseX, mouseY) { var minX = x * gridSize; var maxX = (x + 1) * gridSize; var minY = y * gridSize; var maxY = (y + 1) * gridSize; // case distinction to determine the closest corner of the grid cell to // the mouse cursor /* * 1 | 2 | 3 * ---|-----|--- * 8 |Mo...
[ "_testHit(x, y) {\n const displayedValues = this._values.displayed;\n const radius = this.params.radius;\n\n for (let i = 0; i < displayedValues.length; i++) {\n const dot = displayedValues[i];\n const dx = dot[0] - x;\n const dy = dot[1] - y;\n const mag = Math.sqrt(dx * dx + dy * dy);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================================== TASK 4 =========================================================================== 1. Create a function called 'describePopulation'. Use the function type you like the most. This function takes in two arguments: 'country' and 'population', and ...
function describePopulation(country, population){ const percentageDescribe = percentageOfWorld1(population); return console.log(`${country} has ${population} million people, which is about ${percentageDescribe} % of the world.`); }
[ "function describePopulation(country, population) {\n return `${country} has ${population} million people, which is about ${percentageOfWorld1(population)} of the world.`;\n}", "function describePopulation(countrys,population) {\n percentageofWorld1.call(this,countrys,population)\n this.percentage = population...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that reacts on new events, inserts it into main data and mutate it this function receives new object as param and make all work according to it
function saveNewData(obj) { // if current user is interpreter if (currentRole === 1) { // if the new event is apply, decline, reject or reward if(obj.type === "apply" || obj.type === "decline_offer" || obj.type === "reject_interpreter" || obj.type === "reward") { // we set "past" property ...
[ "processEvent(obj,changes) {\n var id = new ID(Object.keys(obj)[0],Object.values(obj)[0]);\n this.log(\"processing changes on \"+id);\n if ( this.scene.has(id.toString())) {\n var object = this.scene.get(id.toString());\n Object.assign(object,changes);\n // TODO: route event to mesh/script\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset round and wait for enough players
function wait() { game.sendMessage('Too few players. Resetting round...', 'info'); reset(); io.to(game.id).emit('roundStatus', status()); }
[ "function setPlayerNotReadyForNextRound() {\n GameLobby.unreadyPlayers();\n}", "roundReset() {\n this.deck = new Deck()\n this.currentRound = 0\n this.players.forEach((p) => {\n p.isOut = false\n p.isProtected = false\n p.hand = []\n })\n this.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Observe that the following progression of types cannot correspond to a valid program: (1 + 1) x ((x > x) + (x > x)) x introduce tautologies (x > x) x behMerge x behCall The problem is that we can't determine which (x > x) is called at any given time offset, because that information (1 + 1) is not observable in th...
function behMerge( type ) { var informantsAvailable = makeOffsetMillisMap(); var informantsNeeded = makeOffsetMillisMap(); eachTypeLeafNodeOver( type, function ( type, unused ) { if ( type.op === "atom" ) { informantsAvailable.set( type.offsetMillis, true ); } else if ( typ...
[ "function inputOutputComparator(a, b) {\n // must have same input and output token for comparison\n !currencyEquals(a.inputAmount.currency, b.inputAmount.currency) ? invariant(false, 'INPUT_CURRENCY') : void 0;\n !currencyEquals(a.outputAmount.currency, b.outputAmount.currency) ? invariant(false, 'OUTPUT_CURR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to use the keyboard Better way to code this?
function useKeyboard(e) { if (e.keyCode === 48) getNumber(0); if (e.keyCode === 49) getNumber(1); if (e.keyCode === 50) getNumber(2); if (e.keyCode === 51) getNumber(3); if (e.keyCode === 52) getNumber(4); if (e.keyCode === 53) getNumber(5); if (e.keyCode === 54) getNumber(6); if...
[ "function makeKeyboardFunction(keys) {\n var UP = asciiCode(keys[0]);\n var LT = asciiCode(keys[1]);\n var DN = asciiCode(keys[2]);\n var RT = asciiCode(keys[3]);\n var CHC_LT = asciiCode(keys[4]);\n var CHC_RT = asciiCode(keys[5]);\n var JMP = asciiCode(keys[6]);\n var ACT1 = asciiCode(keys...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sendEmails sends an email to each user in the users table in the weather table with tomorrow's weather in the user's city and a discount. Optionally, the message praises the good weather tomorrow if that is the case and cheers the user up if there is bad weather tomorrow. Precondition: there exists a database weather.s...
function sendEmails() { const path = './weather.sqlite3' try { if (fs.existsSync(path)) { sendEmailsHelper(); } else {console.log('weather db does not exist');} } catch(err) {console.error(err);} }
[ "function emailMonthly(){\n connection.getConnection(function(err, connect) {\n if (err) throw err;\n connection.query('SELECT * FROM users', function (err, rows, fields) {\n if (err) throw err;\n\n var mailOptions = {\n from: 'lunchforfour@gmail.com',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the mouse is over the checkBoxes list
function mouseOverCheckBox(name) { if (!load.loading) { name = unescape(name); for (var i = 0; i < bubbles.length; ++i) { if (bubbles[i].name == name) { if (!bubbles[i].draw) return; highlight.bubble = i; highlight.in...
[ "function mousePressed(){\n for (var i=0; i<Items.length; i++) {\n Items[i].mousePressedOver = Items[i].mouseIsOver;\n }\n\n if (tabSelected>-1){\n for (var i=0; i<Items[tabSelected].mouseIsOverList.length; i++){\n Items[tabSelected].mousePressedOverList[i] = Items[tabSelected].mou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The two functions below will disclose the causality chain operation from CAUSALITY_CHAIN_STATE.
function onStateChange(arg) { if ( arg.partitionName == CAUSALITY_CHAIN_STATE ) console.log(`State Change: ${arg.type}.`); }
[ "function StateParent(ccode) {\r\n\tif (ccode>=usa_from && ccode<=usa_upto) return ccode_usa;\r\n\tif (ccode>=ind_from && ccode<=ind_upto) return ccode_ind;\r\n\tif (ccode>=can_from && ccode<=can_upto) return ccode_can;\r\n\tif (ccode>=aus_from && ccode<=aus_upto) return ccode_aus;\r\n\tif (ccode>=mex_from && ccode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a browser to give credit to news api
function openBrowser(args) { utilityModule.openUrl("https://newsapi.org"); }
[ "open() {\n browser.url(this.url);\n }", "open() {\n browser.url(this.url);\n }", "open () {\n super.open('https://authops-dev.gateway.aws.athenahealth.com/authops-835-agent/worklist');\n browser.pause(8000);\n Action.waitForPageToLoad(this.authorizationWorklistT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse :: String > LJSON Parses a LJSON String into a LJSON value. The value returned is guaranteed to be safe i.e., all functions inside it are pure and have no access to the global scope. TODO : tests, add more comments.
function parse(str){ // Note: Unfortunatelly, JavaScript doesn't provide any way to create // functions dynamically other than using `eval` on strings, so LJSON's // parser can't return JS values directly and needs to instead produce // a string to use `eval` on. This is perfectly safe a...
[ "function parse(string) {\n return JSONparse.call(JSON, stripJsonComments(string));\n}", "function parseJSON(str) {\n try {\n return JSON.parse(str);\n } catch (err) {\n return null;\n }\n }", "function parseJSON(str) {\n try {\n return JSON.parse(str)\n } catch (e) {\n return str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
close all autocomplete lists in the document
function closeAllLists() { var autocompleteItems = document.getElementsByClassName("autocomplete-items"); for (var i = 0; i < autocompleteItems.length; i++) { autocompleteItems[i].parentNode.removeChild(autocompleteItems[i]); } }
[ "function closeAllLists(elmnt, inp) {\n\t// Close all autocomplete lists in the document except for the elmnt variable.\n\tvar x = document.getElementsByClassName(\"autocomplete-items\");\n\n\tfor (var i = 0; i < x.length; i++) {\n\t\tx[i].parentNode.removeChild(x[i]);\n\t}\n}", "closeAllGeoSuggestions() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import content for all the labors
async function importLabors() { const module = game.modules.get("<module_name>"); let scenes = null; let actors = null; for ( let p of module.packs ) { const pack = game.packs.get("<module_name>."+p.name); if ( p.entity !== "Playlist" ) await pack.importAll(); else { const music = await pack.getContent();...
[ "function loadJobLabors()\n\t{\n\t\t//Get all jobs id\n\t\tvar count = 0, ids = \"\", sizeValue = \"\";\n\t\t\n\t\tcount = dsJob.getCount();\n\t\tsizeValue = size.getRawValue();\n\t\t\n\t\tfor (var i = 0; i < count; i++)\n\t\t{\n\t\t\trecord = dsJob.getAt(i);\n\t\t\t\t\t\t\n\t\t\tids += \"\" + record.get('id_job') ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a list of nested functions inside the specified function
function get_nested_functions(f, i){ var match = false; //Array to store all nested functions var result = []; //Flag for nesting tester var nested_nested_flag = false; //Variable to store nested function name(s) var nnv = ''; while(match == false){ i++; // If the program stack if fully iterated, stop iter...
[ "function check_program_trace_for_nested_functions(){\n\tfor(i=0; i<program_stack.length; i++){\n\t\tif(program_stack[i].includes('invoke-fun-pre')){\n\t\t\tvar f = program_stack[i].split('_').splice(-1)[0];\n\t\t\tvar f_nested_functions = get_nested_functions(f, i);\n\t\t\t//console.log(f + ' has these nested func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by Grammar19Parsera38.
exitA38(ctx) { }
[ "exitParse(ctx) {\n\t}", "function translator_terminate()\n{\n this.parser.terminate();\n}", "exitSyntaxBracketRa(ctx) {\n\t}", "exitNestedExpressionAtom(ctx) {\n\t}", "exitA39(ctx) {\n\t}", "exitBinaryExpressionAtom(ctx) {\n\t}", "exitSyntaxBracketLa(ctx) {\n\t}", "visitExitStatement(ctx) {\n\t ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for BUGID 3311. Stores the size of the current window to a cookie with the given name.
function storeWindowSize(windowname) { var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth); var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight); var expires = new Date(); // Expires...
[ "function saveWindowSize()\n{\n\twidth = $(window).width() \n\theight = $(window).height()\n\t$.cookie(\"windowWidth\", width)\n\t$.cookie(\"windowHeight\", height)\n}", "function setIBWindowCoordCookie() {\n\tvar ibWinSize = \"\";\n\tvar exp = new Date();\n\tvar currDate = exp.getTime();\n\tvar newExpDate = cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save temp variable table on block enter
function blockEnter() { temp_table = {}; Object.keys(var_table).forEach(_var => temp_table[_var] = JSON.parse(JSON.stringify(var_table[_var]))); }
[ "function blockExit() {\n Object.keys(temp_table).forEach(_var => var_table[_var] = JSON.parse(JSON.stringify(temp_table[_var])));\n temp_table = {};\n}", "function enterBlock(){\n blockContext = Object.create(blockContext)\n }", "function renderStoredData(block, eventHour) {\n var event = JSON...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: loadSetting () Parameters: setting: setting being loaded element: name of the HTML input text being updated defualtSetting: if setting fails to load, sets it at defualt value Precondition: Options page is loaded Postcondition: input text box matched saved value
function loadSetting(setting, element, defaultSetting) { if (setting !== undefined){ document.getElementById(element).value = setting; } else { document.getElementById(element).value = defaultSetting; } }
[ "function import_setting_field()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tinit_dialog_error()\r\n\t\t\t\r\n\t\t\t$(\"#wizard_dialog\").dialog({title: TITLE_SETTING_FIELDS ,autoOpen: false ,modal: true,width:520});\r\n\t\t\t\r\n\t\t\t$.get(url_import_setting,data,function(result)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (result.stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the given style as a default theme style.
static setDefaultThemeStyle(style) { defaultTheme = new Theme(style); }
[ "function resetStyles() {\n // Geom_types now is default_styles\n geometry_style = default_style;\n\n // Come back to defaults in the tools\n _.each(default_style,function(value,type){\n $('span[css=\"'+type+'\"]').find('input').val(value);\n\n if (isNaN(val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getgeneral subject result function get result sheet starts down here$
function getGeneralSubjectResult() { var session= document.getElementById('session').value; var term= document.getElementById('term').value; var subjectname=document.getElementById('subjectname').value; if(subjectname ==''){ alert("Please select a subject name."); } else { $.ajax({ url:'getGeneralSubjectResu...
[ "function getSubjectResultPerExamDetail(src, cl_id, si_id, sub_id, exsub_id){\n\t\t\n\t\tvar academic_year = $(\"#academic_year\").val();\n\t\tvar at_id = $(\"#at_id\").val();\n\t\t\t\t\n\t\t$(\"#subject_detail\").html(\"<div style=\\\"width: 100%\\\" align=\\\"center\\\"><img align=\\\"center\\\" src=\\\"\"+ src +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context menu for Model Reference and Schema Mapping, but already with lowering schema mapping and model reference annotations
function createContextMenuForModelReferenceAndSchemaMappingWithLoweringSchemaMappingAndModelReferenceAnnotated(cy) { cy.cxtmenu({ selector: '.node-model-reference-and-schema-mapping-with-lowering-and-model-reference-annotated', commands: [ { content: 'Add Model Reference...
[ "function createContextMenuForModelReferenceAndSchemaMappingWithLoweringSchemaMappingAnnotated(cy) {\n cy.cxtmenu({\n selector: '.node-model-reference-and-schema-mapping-with-lowering-annotated',\n\n commands: [\n {\n content: 'Add Model Reference',\n select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets conference details from create conf form roomName is the conf name with spaces replaced by selected is an array of easyrtc.usernames of selected members selectedstring is a string containing all names and positions of selected members to display for confirmation
function getConferenceDetails(){ var roomName = document.getElementById("rmName").value; if(!roomName){ var box = document.getElementById("infoBox"); box.style.display = "block"; console.log(box); var info = document.createTextNode("Please provide a conference name"); var...
[ "function createConference() {\n\n console.log('Create conference');\n\n var enterprise = ua.getEnterprise();\n enterprise.createPrivateConference()\n .then(function(conversation) {\n\n console.log('Conference created successfully');\n\n // Keep actual c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: function refresh() DATE: March 13, 2015 REVISIONS: (Date and Description) DESIGNER: Alex Lam PROGRAMMER: Alex Lam INTERFACE: function refresh() RETURNS: void NOTES: Removes all markers and repopulates them
function refresh() { removeMarkers(); if (mode == "allCurrent") mostRecentMarkers(); else macHistoryMarkers(mode); }
[ "function reloadMarkers() {\n for (var i=0; i<markers.length; i++) {\n markers[i].setMap(null);\n }\n\n markers = [];\n\n setMarkers(bicycles);\n}", "function refreshAllMarkers() {\n/* markerList.forEach(marker => {\n marker.refreshIcon();\n }); */\n}", "function refresh2() {\n updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Consume chars matched by the pattern and return them as a string. Starts matching at the current position, so users should drop the current char otherwise.
function getMatchingChars(pattern) { pattern.lastIndex = nextchar - 1; var match = pattern.exec(chars); if (match && match.index === nextchar - 1) { match = match[0]; nextchar += match.length - 1; /* Careful! Make sure we haven't matched the EOF character! */ if (input_complete && n...
[ "lookChar(){\n\t\tif (this.isEOF()){\n\t\t\treturn \"\";\n\t\t}\n\t\treturn this.parser.getContentPos(this.pos);\n\t}", "function scan(pattern, iterator) {\n this.gsub(pattern, iterator);\n return String(this);\n }", "tryConsume(str) {\n if (this.i + str.length > this.length) {\n return null;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate pubkey extraction parameter. When extracting a pubkey from a signature, we have to distinguish four different cases. Rather than putting this burden on the verifier, Bitcoin includes a 2bit value with the signature. This function simply tries all four cases and returns the value that resulted in a successful ...
function calcPubKeyRecoveryParam (e, signature, Q) { typeforce(types.tuple( types.BigInt, types.ECSignature, types.ECPoint ), arguments) for (var i = 0; i < 4; i++) { var Qprime = recoverPubKey(e, signature, i) // 1.6.2 Verify Q if (Qprime.equals(Q)) { return i } ...
[ "function deriveP2PKPubKey(publicKey) {\n // const pubkey = typeConverter.hexStrToBuffer(publicKey);\n // bitcoinjs.payments.p2pk({pubkey}).pubkey;\n return publicKey\n}", "function recoverPubKey(curve,e,signature,i){assert.strictEqual(i&3,i,'Recovery param is more than two bits');var n=curve.n;var G=cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compress a number representation, e.g.: VIIII > IX, LXXXX > XC, etc.
function compress(nb) { return nb .replace(/VV/g, 'X') .replace(/LL/g, 'C') .replace(/DD/g, 'M') .replace(/DCCCC/g, 'CM') .replace(/CCCC/g, 'CD') .replace(/LXXXX/g, 'XC') .replace(/XXXX/g, 'XL') ...
[ "function compress(unStr) {\n var ex = unStr[0] + unStr[1];\n var why = unStr[2] + unStr[3];\n var length = ex * why;\n var toCompress = \"\";\n\n for (i = 0; i < length; i++) {\n toCompress = toCompress.concat(unStr[4 + i]);\n }\n //console.log(toCompress);\n var compressed = BigInt(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a new Window.
function Window() { _super.call(this); /** * The mousedown event handler. */ this.evtMouseDown = new porcelain.EventBinder("mousedown", this.element()); this._content = null; this._windowState = 0 /* Normal */; this.addClass...
[ "function createWindow() {\n var newWindow = document.createElement(\"div\");\n newWindow.setAttribute(\"class\",\"window\");\n var newPane = document.createElement(\"div\");\n newPane.setAttribute(\"class\",\"pane\");\n newWindow.appendChild(newPane);\n return newWindow;\n }", "f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ObjectDef arraybuffer at xmlhttprequest.ceylon (9:09:77)
function $3gf(){ var arraybuffer$=new $3gf.$$;XMLHttpRequestResponseType("arraybuffer",arraybuffer$); return arraybuffer$; }
[ "get buffer(){\n return typeof(this._buffer)==='object' ? JSON.parse(JSON.stringify(this._buffer)) : this._buffer;\n }", "static writeBuffer(objects) {\n return StructuredPrototype.writeBuffer({\n schema: CurrencySchema,\n data: {\n id: CURRENCY_IMPORT_IDENTIFIER,\n version: CURRENC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Press the X button
*pressButtonX() { yield this.sendEvent({ type: 0x01, code: 0x133, value: 1 }); }
[ "*releaseButtonX() {\n yield this.sendEvent({ type: 0x01, code: 0x133, value: 0 });\n }", "function drawX()\n\t{\n\t\texitWid = that.add('button', {\n\t\t\tid: 'exitButton',\n\t\t\timage: 'VideoExit',\n\t\t\talpha: 0.7,\n\t\t\tdepth: that.depth + 1,\n\t\t\tclick: close\n\t\t},{\n\t\t\twid: vidWid,\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to get the id of an random episode
function getRandomEpisode( series, json ) { var episodes = json[series]['Episodes']; //get one random episode from the series defined before var episode = episodes[Math.floor( Math.random() * episodes.length )]; return episode; }
[ "function pickRandomEpisode(){\n\tvar episodesArr = []; //will fill this with possible episodes\n\tfor (var key in episodes){\n\t\tepisodesArr = episodesArr.concat(episodes[key]);\n\t}\n\tvar randomIndex = Math.floor(Math.random()*episodesArr.length);\n\treturn episodesArr[randomIndex];\n}", "function random_epis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an item to the customers order.
function addToOrder(itemId, instructions) { const dataToSend = JSON.stringify({ menuItemId: itemId, instructions: instructions, orderId: sessionStorage.getItem("orderId") }); post("/api/authTable/addItemToOrder", dataToSend, function (data) { if (data !== "failure") { const item = JSON.pars...
[ "function addItemToPurchase() {}", "_addNewItem() {\n // Add new Item from Order's Items array:\n this.order.items = this.order.items.concat([this.item]);\n // Update current Order:\n this.orderService.setCurrentOrder(this.order);\n this._closeAddNewItem();\n }", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class ActionListener [comments are taken from java] The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the ac...
function ActionListener(){ var argv = ActionEvent.arguments; var argc = ActionEvent.length; this.className = "ActionEvent"; this.className="ActionListener"; }
[ "function ActionListener(options) {\n var that = this;\n options = options || {};\n this.ros = options.ros;\n this.serverName = options.serverName;\n this.actionName = options.actionName;\n this.timeout = options.timeout;\n this.omitFeedback = options.omitFeedback;\n this.omitStatus = options.omitStatus;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GOALS GET specific goal user goal, if not, grab public win
getGoal(goalId) { return fetch(`${config.API_ENDPOINT}/goals/${goalId}`, { headers: { 'authorization': `bearer ${TokenService.getAuthToken()}` }, }) .then(res => (!res.ok) ? res.json().then(e => Promise.reject(e)) : res.json() ) }
[ "function goal(goal_id) {\n yaCounter36635055.reachGoal(goal_id);\n }", "function getGoals() {\n sendCommand('get_goals');\n}", "getGoal() {\n return isValidGoal(this.goal) ? this.goal : DEFAULT_GOAL;\n }", "getNextGoal() {\n const { board } = this;\n const possibleGoals = board.goals.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomness Get one of the possible outcomes using points as dibs Outcome with 10 points is 10x more likely than an outcome with 1 point points is an array of integers, function returns the chosen index
function RandomByPoints(points) { var PossibilitiesCount = points.length; var MaxPoints = 0; for (var i = 0; i < PossibilitiesCount; i++) { MaxPoints += points[i]; } var RandomizedPoints = Math.floor(Math.random() * MaxPoints); for (var i = 0; i < PossibilitiesCount; i++) { if (RandomizedPoin...
[ "static randomChoice(p) \n {\n let rnd = p.reduce( (a, b) => a + b ) * Math.random();\n return p.findIndex( a => (rnd -= a) < 0 );\n }", "function chooseRandomIndex(array) {\n return Math.floor(Math.random() * array.length);\n}", "function randomizeIndex () {\n randomIndex = Math.floor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play sound effect of gun clicking
function playSFXGunClick (event) { sfxGunClick.currentTime = 0; $(sfxGunClick).each(function(){this.play(); $(this).animate({volume:1},1000)}); }
[ "function hitSound() {\n let audio = new Audio('https://assets.mixkit.co/sfx/download/mixkit-punching-boxing-gloves-hit-2103.wav');\n audio.play();\n }", "function soundClick () {\n clickSound.play();\n}", "function getMouseDown(e){\n mousePos ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }