query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Pass in a path of a directory to walk and a regex to match against. The file(s) matching the patter will be deleted.
function walkAndUnlink(dirPath, regex){ var emitter = walkdir(dirPath) emitter.on('file',function(filename,stat){ if( regex.test(filename) ){ console.log("Removing old file: " + filename) fs.unlinkSync( path.resolve( dirPath, filename) ) } }) }
[ "function walkAndUnlink(dirPath, regex){\n \n var emitter = walkdir(dirPath)\n\n emitter.on('file',function(filename,stat){\n if( regex.test(filename) ){\n console.log(\"Removing old file: \" + filename)\n fs.unlinkSync( path.resolve( dirPath, filename) )\n }\n })\n \n}", "clean(directory) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO getNumberOfProfilesWithAssertedCompetencyAndParents adjust for multinode clusters
function getNumberOfProfilesWithAssertedCompetencyAndParents(compId) { var cpo = getProfilesWithAssertedCompetencyAndParents(compId); if (cpo) return Object.keys(cpo).length; else return 0; }
[ "function getProfilesWithAssertedCompetencyAndParents(compId) {\n var cpd = selectedFrameworksCompetencyData.competencyPacketDataMap[compId];\n if (!cpd) return [];\n else {\n var asArray = getAssertionsForCompetencyPacketDataInclusive(cpd);\n if (!asArray || asArray.length == 0) return [];\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CCUtility_crtCtrla(node, param, formId, userscript) node......: Current node which generates the event param.....: action used by the control to identify the event formId....: optional id of the form, if null the enclosing form is searched by the script userscript: optional jscript which must return true before the for...
function CCUtility_crtCtrla(node, param, formId, userscript) { var form = null; // if a user script was defined execute the script // To replace by CCUtility_executeUserScript if (null != userscript) { var rtc = true; var userfct = new Function(userscript); var obj = userfct(); if (typeof obj == 'boolean...
[ "function ccStaticASPCTLRequest(frmName,ctls, ctlName, ctlVal, eventSink, eventParam) {\r\n var frm = document.forms[frmName];\r\n var u = frm.action;\r\n if (u.indexOf('?') < 0) u += '?'; else u += '&';\r\n u += \"ASPCTLPartial=form.xml&ASPCTLControlList=\" + ctls.join(\",\");\r\n if (typeof(ctlName...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the angle from A to B, where each is an array [x,y]
function getAngle(A, B) { // move A to 0,0 // we could also push to A as our center let translated_x = B[0] - A[0]; let translated_y = B[1] - A[1]; return Math.atan2(translated_y, translated_x); }
[ "function getangle(x,y)\n{return Math.atan2(y,x);}", "static calculateAngle(a: Position, b: Position): number {\n return Math.atan2(b[1] - a[1], b[0] - a[0]);\n }", "function getAngleTo(x1, y1, x2, y2) {\n\treturn (Math.atan2(y2-y1,x2-x1));\n}", "angle (x, y) {\n\t\treturn Math.atan2(y, x);\n\t}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is responsible for gobbling an individual expression, e.g. `1`, `1+2`, `a+(b2)Math.sqrt(2)`
function _gobbleBinaryExpression(context) { var node, biop, prec, stack, biop_info, left, right, i, cur_biop; // First, try to get the leftmost thing // Then, check to see if there's a binary operator operating on that leftmost thing left = _gobbleToken(context); biop = _gobbleBinaryOp(co...
[ "function eval_expression(expression) {\n\tvar new_term;\n\tif (expression.indexOf(\"\\\\sqrt\") > -1) {\n\t\texpression = expression.replace(/\\\\sqrt\\{([ -~]+)\\}/g, \"($1)**0.5\");\n\t} else if (expression.indexOf(\"\\\\frac\") > -1) {\n\t\tvar occurences = getIndicesOf(\"\\\\frac\", expression).length;\n\t\tfo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to use the given socket as the WebSocket connection to the server.
function useWebSocket(socket) { socket.onopen = handleSocketOpen; socket.onclose = handleSocketClose; socket.onerror = handleSocketError; gSocket = socket; socket.onmessage = handleSocketMessage; }
[ "function connect() {\n if (ws) {\n throw new Error(\"A game socket is already open.\");\n }\n\n var WS = !!window.MozWebSocket ? MozWebSocket : WebSocket;\n ws = new WS(\"ws://\" + window.location.host + \"/connect\"); ws.onmessage = receiveEvent;\n ws.onclose = function(event) {\n ws = nu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the user's given name from the JWT payload.
function userGivenName(jwtPayload) { if (exports.mappingUserFields.givenName) { return jwt_1.readPropertyWithWarn(jwtPayload, exports.mappingUserFields.givenName.keyInJwt); } }
[ "function userName(jwtPayload) {\n return jwt_1.readPropertyWithWarn(jwtPayload, exports.mappingUserFields.userName.keyInJwt);\n}", "function userName(decodedToken) {\n return jwt_1.readPropertyWithWarn(decodedToken, exports.mappingUserFields.userName.keyInJwt);\n}", "function extractName(jwtToken){\n\tva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invoke the correct handler based on the given file extension. Parameter: fileInfo: Object File info, including `extension`, which is expected to be either 'json' or 'txt' Returns: A Promise
static fileWithInfo (fileInfo) { switch (fileInfo.extension) { case 'json': return MoveAnnotated.json(fileInfo) case 'txt': return MoveAnnotated.txt(fileInfo) default: throw new Error('unrecognized filetype') } }
[ "function fileHandler(file, request, response) {\n\tfor (var i = 0; i < fileActions.length; i++) {\n\t\tif (fileActions[i].method == request.method) {\n\t\t\tfileActions[i].handler(file, request, response);\n\t\t}\n\t}\n}", "async _handleFile(key, handler) {\n for (const extension of COMMON_LOCAL_FILE_EXTE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the location data for a given country and state
static lookupLocation(country, state) { return this.locationsForCountry(country) .find(x => x.state === state); }
[ "function fecthCoords(city, country, state) {\n let countryCode = getCountryCode(country);\n fetch(\n `http://api.openweathermap.org/geo/1.0/direct?q=${city},${state},${countryCode}&appid=${API_KEY}`\n )\n .then((response) => response.json())\n .then((data) => displayCoords(data));\n}", "function getd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To represent a hook primitive. A hook primitive is like a hook template, it allows a developer or a user to define hooks in different files and combine it in order to be injected by using a single script.
function HookPrimitive(config){ this.when = null; this.method_signature = null; this.isIntercept = false; this.isCustom = false; this.interceptBefore = null; this.interceptAfter = null; this.interceptReplace = null; this.onMatch = null; this.custom = false; this.variables = null;...
[ "function Hook() {\n _classCallCheck(this, Hook);\n\n Hook.initialize(this);\n }", "hook(hookName, callback, priorty = 0) {\n this._hooks[hookName] = this._hooks[hookName] || [];\n this._hooks[hookName].push({\n callback: callback,\n priorty: priorty\n });\n }", "constructor() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
REGEX / Updates all values in an array regex valid regular expression replace valid replacement expression, or plain string. Explained at Returns updated array on success, or undefined on error
function updateValues(arr, regex, replace) { if ( ! regex || regex.length < 1 || ! isRegexValid(regex) ) { error("Invalid regex: " + regex); return undefined; } else if (! replace ) { error("Undefined replace string"); return undefined; } else { var re = new RegExp(regex); var newArr = [...
[ "static _replacePatterns(input){\n patterns.forEach(([pattern, fixValue]) => {\n input = input.replace(pattern, fixValue)\n })\n return input\n }", "function replaceBulk(args) {\n\t\tvar solution = args.string;\n\t\tvar replaceArray = args.replacements;\n\t\tvar findArray = Object.keys(replaceArray...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Act API Returns an index of acts.
getActIndex() { return __awaiter(this, void 0, void 0, function* () { return yield this._handleApiCall(`${this.gameBaseUrlPath}/act`, 'Error fetching the act index.'); }); }
[ "function getIndex() {\n return internal.index;\n }", "async index({ params }) {\n return Attribute.findAttrs(params);\n }", "getID(index){\n return this.impacts[i].id;\n }", "function getActiveDocumentIndex(){\r\n var ref = new ActionReference();\r\n ref.putEnu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a new instance of ApolloClient Remember to clean up the store before setting a new client.
setClient(client) { if (this._client) { throw new Error('Client has been already defined'); } this._client = client; }
[ "setClient(client: ApolloClient) {\n this.apolloClient = client;\n }", "setClient(client) {\n this.client = client;\n }", "set client(client) {\n this._client = client\n }", "setApolloClientOptions(opt = {}) {\n this.apolloClientOptions = opt;\n }", "function initApolloClient(......
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Painting functions /! \fn void paintMatrix(matrix,canvasID, centered, matrixCoords, stretchX, stretchY) \param array matrix the matrix which should be painted \param string canvasID the id of the canvas which the matrix will be painted on \param bool centered specifies if the matrix should be centered on the canvas \pa...
function paintMatrix(matrix,canvasID, centered, matrixCoords,interPolate, visData) { //Set default start and stop coordinates in the matrix var xStart = 0; var yStart = 0; var xStop = matrix[0].length; var yStop = matrix.length; var stretchX = false; var stretchY = false; //If start and stop ...
[ "function paintMatrix() {\n\tvar x = arguments[0];\n\tvar m = x.m;\n\tvar rows = x.rows;\n\tvar cols = x.cols;\n\n\tvar o = {\n\t\tonCanvas: function() {\n\t\t\tvar id = arguments[0];\n\t\t\tvar can = document.getElementById(id);\n\t\t\tvar cx = can.getContext(\"2d\");\n\t\t\t\n\t\t\tvar dx = matrixPixelSize;\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns project type, specified by input string or null, if not project type parameter
function getProjectType (arg) { arg = arg.toLowerCase(); if (arg == "--phone"){ return "phone"; } else if (arg == "--store80"){ return "store80"; } else if (arg == "--store81" || arg == "--store"){ return "store"; } retu...
[ "function getProjectType(extension)\n{\n\tswitch (extension)\n\t{\n\t\tcase \".fdp\" : return getLocaleString(\"projectTypeFDP\");\n\t\tcase \".as2proj\" : return getLocaleString(\"projectTypeAS2\");\n\t\tcase \".as3proj\" : return getLocaleString(\"projectTypeAS3\");\n\t\tcase \".fdproj\" : return getLocaleString(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to add a vegetable on click
function addVegetable(id) { vegetable_text = document.getElementById('vegetable-input').value; // Create the new element, create text, add text vegetable_node = document.createElement('li'); vegetable_text_node = document.createTextNode(vegetable_text); vegetable_node.appendChild(vegetable...
[ "function addVegetables() {\n vegSubmit.addEventListener('click', function(e) {\n distributeVeg(1);\n distributeVeg(2);\n distributeVeg(3);\n distributeVeg(4);\n vegSubmitButton.innerHTML = 'Add more vegetables';\n e.preventDefault();\n });\n}", "_addPointBtn(){this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tokenise the chordpro line, returning pairs of [current, next] tokens so that there is some lookahead context
function tokenise (line) { // split line on chords, comments, hyphens, and spaces, keeping the delimiters const tokens = line.split(/(\[.+?\])|(\{.+?\})|( - |- | -)|( +)/g).filter(Boolean) const pairs = [] var current = null // counts used to determine if this line is chords, lyrics, or both var counts = {...
[ "function tokenize(text) {\n const lines = text.split(\"\\n\");\n const newText = [];\n for (const line of lines) {\n const newLine = [];\n let chordCount = 0;\n let tokenCount = 0;\n const tokens = line.split(/(\\s+|-|]|\\[)/g);\n let lastTokenWasString = false;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
and target avg value. check if array has pair which sum equal to target avg value
function averagePair(array, target) { // return false if array length less than 1 if (!array.length) { return false; } let i = 0; let j = array.length - 1; while(i < j) { let avg = (array[i] + array[j]) / 2; if (avg === target) { return true; ...
[ "function averagePair(arr, target) {\n if (arr.length === 0) return false;\n let p2 = arr.length - 1;\n for (let p1 = 0; p1 < arr.length; p1++) {\n let avg = (arr[p1] + arr[p2]) / 2;\n if (avg === target) {\n return true;\n } else if (avg > target) {\n p2--;\n p1--;\n } else {\n /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function clears the visibleStudents[] array containing a list of students to be displayed
function clearVisibleStudentArray() { visibleStudents = []; }
[ "function clearstudentItemLI () {\r\n for(let i = 0; i < totalStudents; i++) {\r\n studentItemLI[i].style.display = 'none';\r\n }\r\n}", "function hideAllStudents() {\n for (i = 0; i < students.length; i ++) {\n if (students[i]) {\n students[i].style.display = 'none';\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to highlight toc items when mouse over
function tocMouseOver(tocMouseOverElem) { tocMouseOverElem.classList.add("tocMouseOver"); }
[ "function highlightTocItem(node) {\n if (tocSupported) {\n // turn old off\n/*\n if (isIE) {\n \tvar lis = node.ownerDocument.getElementsByTagName(\"*\");\n for (var i = 0; i < lis.length; i++) {\n removeClass(lis.item(i), TOC_CLASS_ACTIVE);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To assign selected users from a role to a specific step. It will aslo replace/append previously added users. Arguments: 1) Role ID. 2) Step User's Id 3) Flag: true/false. If true is passed then user will be replaced else appended to previous selection Sample Call: SP_UserAssignment("mastercontrol.role.SP_AUD_LeadAudito...
function SP_UserAssignment(sourceRole, stepUsers, replace) { var sourceRole = $(document.getElementById(sourceRole)); var stepUsers = $(document.getElementById(stepUsers)); if (replace) { stepUsers.find('option').prop('selected',false); } sourceRole.find('option:selected').each(function() { opt = $(this); v...
[ "function assignRole(user){\n\tvar resolvedData = user;\n\n\tvar assignRoleModal = modalManager.openModal('assignRole', resolvedData);\n\n\t//after editing users\n\tassignRoleModal.result.then(function(results){\n\t\tactivate();\n\t})\n}", "function assignRolesToUsers(doc, oldDoc, accessAssignmentDefinition) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies formatting to the caret position
function applyCaretFormat() { var rng, caretContainer, textNode, offset, bookmark, container, text; rng = selection.getRng(true); offset = rng.startOffset; container = rng.startContainer; text = container.nodeValue; caretContainer = getParentCaretContainer(selection.getStart()); if (caretC...
[ "function applyCaretFormat() {\r\n\t\t\t\tvar rng, caretContainer, textNode, offset, bookmark, container, text;\r\n\r\n\t\t\t\trng = selection.getRng(true);\r\n\t\t\t\toffset = rng.startOffset;\r\n\t\t\t\tcontainer = rng.startContainer;\r\n\t\t\t\ttext = container.nodeValue;\r\n\r\n\t\t\t\tcaretContainer = getParen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the animation progress to a certain point (0..1)
progress(progress) { this.lottieAnimation.animationProgress = progress; }
[ "setProgress(progress) {\n const progressInFrames = this.durationToFrames(progress);\n this.animation.goToAndPlay(progressInFrames, true);\n }", "setProgress(value) { this._behavior('set progress', value); }", "function animateProgress() {\n var currValue = $(\"#progress\").val()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
attach a Chrome window to a specific tab window (after opening a saved window)
attachChromeWindow (tabWindow, chromeWindow) { // log.log('attachChromeWindow: ', tabWindow.toJS(), chromeWindow) // Was this Chrome window id previously associated with some other tab window? const oldTabWindow = this.windowIdMap.get(chromeWindow.id) // A store without oldTabWindow const rmStore ...
[ "function createWindow(){\n\tchrome.tabs.query({\n\t\t'active': true,\n\t\t'windowId': chrome.windows.WINDOW_ID_CURRENT\n\t},function(tabs){\n\t\turl = tabs[0].url;\n\t\tchrome.windows.create({url: url, incognito: true});\n\t});\n}", "function openChrome() {\r\n robot.moveMouseSmooth(59,704);\r\n setTimeout...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get input using Readline and Promises
function getInput(question){ //Return a Promise return new Promise(function(resolve, reject){ //Create the Readline Interface const reader = readline.createInterface({ input: process.stdin, output: process.stdout }); //Ask for input reader.question(question, (answer) => { resolve(answer); //We got...
[ "function readlineSync() {\r\n return new Promise((resolve, reject) => {\r\n process.stdin.resume();\r\n process.stdin.on('data', function (data) {\r\n process.stdin.pause(); // stops after one line reads\r\n resolve(data);\r\n });\r\n });...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reupdates graphics (i.e. size and colour of cells) by looking at the UI settings
function updateGraphics() { ui.cellColorAlive = $("input[name=colorAliveCellHexagon]").val(); ui.cellColorDead = $("input[name=colorDeadCellHexagon]").val(); ui.cellColorStroke = $("input[name=colorOutlineHexagon").val(); ui.draw(); }
[ "function updateGraphics() {\n ui.cellColorAlive = $(\"input[name=colorAliveCellSquare]\").val();\n ui.cellColorDead = $(\"input[name=colorDeadCellSquare]\").val();\n ui.cellColorStroke = $(\"input[name=colorOutlineSquare\").val(); \n ui.draw();\n }", "function updateGraphics...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description Delete elems by ids by calling ELEM.del for each id. If elems is not array, do nothing. Return always new empty array
_delElems(_elems) { if (this.isArray(_elems)) { _elems.forEach(_elemId => { ELEM.del(_elemId); }); } return []; }
[ "function removeElsByIdxs( a, idxs ) {\n var result = [];\n for ( var i=0; i<a.length; i++ ) {\n if ( indexInArray(i,idxs)==-1 ) {\n result.push(a[i]);\n }\n }\n return result;\n}", "function rmByID (arr, id) {\n\t\tvar len = arr.length;\n\t\twhile(len--) {\n\t\t\tif(arr[len]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select no rows in the grid
selectNone () { this.$refs.grid.gridOptions.api.deselectAll(); this.grid.hasSelectedRows = false; }
[ "function unselectAll() {\n loadedAgGrid.gridOptions.api.forEachNode(function (rowNode, index) {\n rowNode.setSelected(false);\n });\n}", "function datagrid_deselect_rows(table) {\n\tvar rows = table.fnGetNodes();\n\tfor (var i = 0; i < rows.length; i++) {\n\t\tvar row = rows[i];\n\t\tif (row)\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The GameObject module acts as an abstract object used to build objects for a game with abstract methods for updating and rendering the objects.
function GameObject() { // Module constants and variables var _this = this; _this.drawPriority = 0; _this.canDelete = false; /** * Abstract function that updates the GameObject. This function needs to * be overriden. * * @abstract * @functi...
[ "function GameObject(name, x, y, width, height) {\n this.tags = [name, \"gameObject\"];\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }", "function GameObject (Name, Position, Rotation, Camera, Type){\n this.name = Name;\n this.position = Position;\n this.rot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A schema is classified as a schema for a single property if: `type` is defined on the schema as a string. OR `default` is defined on the schema, as a reserved keyword. OR schema is empty.
function isSingleProperty (schema) { if ('type' in schema) { return typeof schema.type === 'string'; } return 'default' in schema; }
[ "function isSingleProperty (schema) {\n\t if ('type' in schema) {\n\t return typeof schema.type === 'string';\n\t }\n\t return 'default' in schema;\n\t}", "function getDefaultFromSchema(schema) {\n if (!schema || typeof schema.$ref === 'string') {\n var _schema$$ref;\n\n // get the schema from ajv\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filling the disks parameters list
initDisks(){ // portion to remove to each disk as we get closer to the smallest one // here, the smallest disk should be 1/3 of the width of the largest const decr = - 2 / 3 * this.diskWidth / this.props.nbDisks var listDisks = [] // defining the position of the disks fo...
[ "function initParams(){\n $scope.parametersList.loadListFromStorage();\n }", "function initDisks(n) {\r\n var peg = pegsState.pegs[0].coord;\r\n var colors = ['#aa1414', '#ce1414', '#f74545', '#f7a145', '#c5e56b', '#5bff0a', '#28ede9', '#84c5ff', '#2295f9', '#5f22f9'];\r\n var width = 20 * n;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert KM to Miles
function kmToMiles(km) { return km * 0.62137; }
[ "function toMiles(kilometers){\n return kilometers*0.6214;\n}", "function kiloToMiles(km) {\n console.log(km * 0.621371);\n}", "function kmToMile(km){\n\treturn (km*1.609344).toFixed(2);\n}", "function convertToKilometers(miles) {\n return miles * 1.60934\n}", "function kilometersToMiles(kilometers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initial confirm function Does resolve
function confirm(result) { garbageCollect(); resolve(result); }
[ "function runConfirm () {\n // Set up confirm message\n // Show conf msg, bind confirmed method,\n $this.text(settings.text).addClass(\"js--confirm__required\").unbind();\n console.log(\"Confirm barrier hit\");\n\n // If confirmed run completion method and reset but...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paints an array of cloud objects using a given style.
draw() { const { width, height, clouds, style } = this.props; /** * Pass the style string to the canvas context */ this.ctx.fillStyle = style.colour; /** * Clear the whole canvas. */ this.ctx.clearRect(0, 0, width, height); /** * For each cloud, draw a circle dependan...
[ "function drawClouds()\n{\n for(var i = 0; i < clouds.length; i++)\n { \n //cloud shadow\n fill(180);\n rect(clouds[i].x_pos - 2, clouds[i].y_pos + 1, 101, 29, 30);\n \n fill(255);\n //cloud base\n rect(clouds[i].x_pos, clouds[i].y_pos, 100, 28, 30);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the flags on the current node, setting all indices to the initial index, the directive count to 0, and adding the isComponent flag.
function initNodeFlags(tNode,index,numberOfDirectives){ngDevMode&&assertEqual(getFirstTemplatePass(),true,'expected firstTemplatePass to be true');var flags=tNode.flags;ngDevMode&&assertEqual(flags===0||flags===1/* isComponent */,true,'expected node flags to not be initialized');ngDevMode&&assertNotEqual(numberOfDirect...
[ "function initNodeFlags(tNode, index, numberOfDirectives) {\n // When the first directive is created on a node, save the index\n tNode.flags = 1 /* isComponent */ & tNode.flags, tNode.directiveStart = index, tNode.directiveEnd = index + numberOfDirectives, \n tNode.providerIndexes =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outro modo de delcarar Array sem o diamante private _negociacoes: Negociacao[] = [];
adiciona(negociacao) { this._negociacoes.push(negociacao); }
[ "get negociacoes() {\n\n return [].concat(this._negociacoes);\n }", "adiciona(negociacao) {\r\n this._negociacoes.push(negociacao);\r\n }", "adiciona(negociacao) {\n this._negociacoes.push(negociacao);\n }", "function negativos(array) {\n var newArray = [];\n for (var i = 0; i < ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates score card with score and par
function updateScorecard() { var i = strokesDisp.length - 1; if (hole != 10) { total = total + strokesDisp[i]; } sw = total - TOTAL_PAR[i]; // different colors if over or under par if (total > TOTAL_PAR[i]) { parScore.addColor('#228B22', 0); parScore.fontSize = 20 * HR; parScore.setText('+' + ...
[ "function updateScore(card, activePlayer) {\n activePlayer[\"score\"] += blackjackGame[\"cardsMap\"][card];\n }", "function updateScore() {\n score++;\n}", "UpdateScore(newScore){\n this.currentScore += newScore;\n }", "function updateScore() {\n score++;\n $('.score').text(scor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the duration (in seconds) of a number of framres running at a specified framerate
function timeGetNoteDuration(frameCount, framerate) { // multiply and devide by 100 to get around floating precision issues return ((frameCount * 100) * (1 / framerate)) / 100; }
[ "function timeGetNoteDuration(frameCount, framerate) {\r\n // multiply and divide by 100 to get around floating precision issues\r\n return ((frameCount * 100) * (1 / framerate)) / 100;\r\n}", "timePerFrame(framesPerSecond){\n return 1000.0/framesPerSecond;\n }", "getFramesNum() {\n const fps...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This renders a Board with 9 squares. Value is defined by the parameter for renderSquare in order to keep track of the squares.
render() { return ( <div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} ...
[ "function renderBoard(){\n\tfor(var i = 0; i < board.length; i++){ //rows\n\t\tfor(var j = 0; j < board[0].length; j++){\n\t\t\trenderSquare(i,j);\n\t\t}\n\t}\n}", "render() {\n return (\n <div>\n <div className=\"board-row\">\n {this.renderSquare(0)}\n {this.renderSquar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate each item in the menu.
populate() { //TODO Wait for the data to actually be available before populating. let menuWithFunctions = this.context.menu(); let evaluatedMenu = []; menuWithFunctions.forEach(function(e) { if (e) { let value = e[1](); evaluatedMenu.push({ title: e[0], value: v...
[ "static ExecuteMenuItem() {}", "function process_menu( menu ) {\n\n\t\t// if menu isn't an object return early\n\t\tif ( 'object' !== typeof( menu ) ) return;\n\n\t\t// process all items in the menu\n\t\tfor ($i=0;$i<menu.length;$i++) {\n\t\t\tprocess_item( menu[$i] );\n\t\t}\n\n\t\t// append the menutext to the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function will be called at set intervals to check the gesture state
function checkGesture() { // if a gesture is occuring, sample gesture parameter values if(gestureOccuring) { if (currGestureValue!=xValue){ currGestureValue=xValue; } if (currGestureValue<50){ currGestureValue=50; } if (currGestureValue>250){ currGestureValue=250; } v...
[ "function checkGesture()\n{\n // if a gesture is in fact occuring, we want to sample gesture values\n if(gestureOccuring)\n {\n if (currGestureValue!=rotationAngle){\n currGestureValue=rotationAngle;\n }\n if (currGestureValue<160){\n currGestureValue=160;\n }\n if(currGestureValue>205){...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a key for a DoubleMap type
function createKeyDoubleMap(registry, itemFn, args, [hasher1, hasher2]) { const { meta: { name, type } } = itemFn; // since we are passing an almost-unknown through, trust, but verify (0, _util.assert)(Array.isArray(args) && !(0, _util.isUndefined)(args[0]) && !(0, _util.isNull)(args[0]) && !...
[ "static mapType(keyType, valueType) {\n return TypeNames.parameterizedType(TypeNames.MAP, keyType, valueType);\n }", "function keyBuilder(type, params){\n return type + '.' + params[keyMap[type]];\n }", "makeMarker(keyValueMap,timestamp){timestamp=timestamp||new Date().getTim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide animation set for chosen marker
function hideAnimation(){ var l = self.restaurantList().length; for(var i=0;i<l;i++){ self.restaurantList()[i].marker.marker.setAnimation(null); } }
[ "function stopAnimation(){\r\n for(var i=0; i<self.markerArray().length; i++){\r\n self.markerArray()[i][1].setAnimation(null);\r\n\tself.markerArray()[i][1].setIcon(defaultIcon);\r\n }\r\n}", "function stopAnimation() {\n for (var i = 0; i < markers.length; i++) {\n markers[i].setAnimation(null);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify user that contents of field theField are invalid. String s describes expected contents of theField.value. Put select theField, pu focus in it, and return false.
function warnInvalid (theField, s) { theField.focus() theField.select() alert(s) return false }
[ "function warnInvalid(theField, s) {\r\n theField.focus()\r\n theField.select()\r\n alert(s)\r\n return false\r\n}", "function warnInvalid (theField, desField, s, f)\r\n{ if (f) theField.focus();\r\n if (theField.type == \"text\") {\r\n theField.select()\r\n }\r\n if (desField.length == 0) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns cpu usage as a percentage of total processing power (0100)
function getCpuUsage() { return cpu.getCpuUsage(); }
[ "async calculateCpuUsage() {\n this.__cpuUsage = await utils.getCpuUsage({ timeout: this.__cpuUsageInterval });\n }", "metricCpuUtilization(props) {\n return this.metric('CPUUtilization', props);\n }", "getCpuAvg() {\n const cpus = os.cpus();\n \n let totalIdle = 0;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create/Update Part Runs when a tracked field on the part add/edit screen is changed
static partCreateUpdateOnChange(control) { let controlName = control.getName(); let context = control.getPageProxy(); let controls = libCom.getControlDictionaryFromPage(context); switch (controlName) { case Constants.PartCategoryLstPkr: //Text item ...
[ "static partCreateUpdateOnChange(control) {\n let controlName = control.getName();\n let context = control.getPageProxy();\n let controls = libCom.getControlDictionaryFromPage(context);\n\n switch (controlName) {\n case Constants.PartCategoryLstPkr:\n //Text ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the timer for a product is done, this will send the id,current ticketcount and mincost to the backend, to see if a winner can be choosen, and which it will be. Afterwards it writes the winner into the product and updates its status, if no winner is chosen, it writes it in the product.
async function choose_winner(id, currentticket, mincost){ let response = await fetch("/choosewinner", { method: "POST", headers: { 'Content-Type': 'application/json' }, body: "prodid="+id+"&ticketsspent="+currentticket+"&mincost="+mincost }); if (response.status =...
[ "function checkQuantity() {\r\n console.log(\"Available: \" + res[chosenItemNo].stock_quantity);\r\n if (res[chosenItemNo].stock_quantity < getItem.chosenQ) {\r\n console.log(\"Insufficient supply\")\r\n\r\n } else {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates the httml containers with keywords using the json data received at initialisation
initQuestion(data) { this.jsonData = data; //Create keywords dynamicly and append them to wrapping container for (var d = 0; d < Object.keys(data).length; d++) { var newKeyword = document.createElement("span"); newKeyword.innerHTML = data[d].keyword; newKeywo...
[ "initQuestion(data) {\n\n this.jsonData = data;\n //Create keywords dynamicly and append them to wrapping container\n for (var d = 0; d < Object.keys(data).length; d++) {\n var newKeyword = document.createElement(\"div\");\n newKeyword.innerHTML = data[d].keyword;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: todoAddMultipleStoreInfo Parameter: Description: To add multiple storage information rows to database
function todoAddMultipleStoreInfo() { var storeInfoTable = document.getElementById('store-info-modify-table'); var data = []; /*Collect add rows and tranfer to an array*/ for (var i = storeInfoTable.rows.length - 1; i > 0; i--) { if (storeInfoTable.rows[i].cells[0].children[0].checked) { ...
[ "function addStore(store) {\n storesList.push(store);\n // set storeNumber to the new length of the list (array)\n store.storeNumber = storesList.length;\n}", "addStoreToList(garageOwnerId, storeInfo) {\n const promiseResult = GarageOwnerModel.addStoreToList({\n _id: garageOwnerId,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets all the inputs under the form parentItem as array
function getFormInputsAsArr(parentItem) { const standardInputs = resolveViewState(parentItem); const fileInputs = resolveFiles(parentItem); return standardInputs.concat(fileInputs); }
[ "getItems () {\n try {\n let ret = new Array();\n let chd = this.child();\n for (let cidx in chd) {\n if (true ===comutl.isinc(chd[cidx], \"FormItem\")) {\n ret.push(chd[cidx]);\n }\n }\n return (0 === ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::WAFv2::RuleGroup.LabelSummary` resource
function cfnRuleGroupLabelSummaryPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnRuleGroup_LabelSummaryPropertyValidator(properties).assertSuccess(); return { Name: cdk.stringToCloudFormation(properties.name), }; }
[ "function cfnRuleGroupLabelPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRuleGroup_LabelPropertyValidator(properties).assertSuccess();\n return {\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}", "function CfnRul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controller for rendering a single remote peer. Manages the peer model completely, including adding and removing from scene. Render the other peer in 6DOF. General pose updates (looking around) Entering transition Leaving transition Idle animation Walking animation Shrinking animation Growing animation Speaking animatio...
function PeerRenderer(scene, peerId) { this.state = State.NONE; this.color = this.getColorFromId_(peerId); // Create the peer itself. var peer = new THREE.Object3D(); peer.visible = false; // Create the legs for this peer. var leftLeg = this.createLeg_(); leftLeg.position.x = LEG_SEPARATION/2; var ...
[ "function PeerRenderer(scene) {\n this.state = State.NONE;\n\n // Create the peer itself.\n var peer = new THREE.Object3D();\n peer.visible = false;\n\n // Create the legs for this peer.\n var leftLeg = this.createLeg_();\n leftLeg.position.x = LEG_SEPARATION/2;\n var rightLeg = this.createLeg_();\n rightL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MODIFIED / To toggle between Enable/Disable state of fields. Arguments: 1) fieldList: array of field names to be disabled. 2) isDisable: true/false 3) Optional argument: ClassName to be applied or removed on targeted field var TargetFieldList = new Array('txtOtherSource'); Sample Call: SP_EnableDisableToggle(TargetFiel...
function SP_EnableDisableToggle(fieldList, isDisable) { var sClassName = "EditShadow"; if(arguments[2]) sClassName = arguments[2]; for(var i=0;i<fieldList.length;i++) { var fieldType = document.getElementById(fieldList[i]).type; var oField = document.getElementById(fieldList[i]); if(SP_Trim...
[ "function disableToggle(oField, bDisabled) {\n if (bDisabled) {\n oField.Disabled = true;\n oField.ForceSubmit = true;\n } else {\n oField.Disabled = false;\n }\n}", "function enableDisableByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
price should'nt be less than the base price
function CheckBasePrice(){ var base_price = document.getElementById("txt_item_baseprice").value; var price_variable = document.getElementById("txt_item_pricevariable").value; var price = document.getElementById('txt_item_price').value; if((eval(price) < eval(base_price)) && price_variable!=1){ ...
[ "function pricechecker() {\n //if user price range is less than the range of the restuarant, return false\n if (userpricerange < restlist.price) {\n return false;\n }\n }", "function surprisingPrices() {\r\n if (that.getTargetField() === null) {\r\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
first, second, and result. function to create a random member
function randomExpressionMember() { return Math.floor(Math.random() * 10 + 1); }
[ "function randomMember(arr)\n\t{\n\t\tvar arrl = arr.length\n\t\tif(arrl == 1)\n\t\t\treturn arr[0]\n\t\tvar idx = Math.round((Math.random() * arrl) - 0.5)\n\t\tif(idx >= arrl)\n\t\t\tidx = arrl - 1\n\t\treturn arr[idx]\n\t}", "function rando() {\n return Math.floor(Math.random() * (people.length));\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalidate all information derived from the given file and return the static symbols contained in the file.
invalidateFile(fileName) { this.metadataCache.delete(fileName); const symbols = this.symbolFromFile.get(fileName); if (!symbols) { return []; } this.symbolFromFile.delete(fileName); for (const symbol of symbols) { this.resolvedSymbols.delete(symbol...
[ "getStaticSymbol(declarationFile, name, members) {\n return this.staticSymbolCache.get(declarationFile, name, members);\n }", "invalidateFile(fileName) {\n this.metadataCache.delete(fileName);\n this.resolvedFilePaths.delete(fileName);\n const symbols = this.symbolFromFile.get(fileN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
passed as props to List takes a key as argument. when delete button is pressed, it finds the matched json and updates the deleted state
function deleteHandler(key) { for (let item of list) { if (item.key === key) { item.deleted = !item.deleted; } } setList([...list]); }
[ "delete(key) {\n\t\tthis.props.remove(key);\n\t}", "delete(key){\n this.props.delete(key);\n }", "_handleDeleteClick() {\n this.listOfMaterials.forEach((item, index) => {\n if (item?.id == this.currentlySelectedMaterial.id) {\n delete this.listOfMaterials[index]\n this.currentlyS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HELPER: reduce player health and colorize it based on the value
function h_reduceHealth() { health = health - healthDamage; // fit color (green -> orange -> red -> death) switch(health) { case 70: $('#health').css('color', 'orange'); break; case 30: $('#health').css('color', 'red'); break; case 0: var n = noty({text: 'You just died. RIP.'}); gameEnded()...
[ "changeColor() {\n if (this.health < 150 && this.health >= 100) {\n this.display(\"yellow\");\n }\n if (this.health < 100 && this.health >= 50) {\n this.display(\"orange\");\n }\n if (this.health < 50) {\n this.display(\"red\");\n }\n }", "function healthbarColor(max, health){\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the recaptcha in html page
function showRecaptcha(element) { //local public key: 6LduA_YSAAAAAHxKLuHMKx7ZelfvyQClzvavsj2B //Using the public key of site Recaptcha.create("6LdddPYSAAAAABXYEfL6a5-VGh1T1M4ewSNBwKa1", element, { theme : "red", callback : Recaptcha.focus_response_field }); }
[ "function _displayHtml() {\n _getHtml(settings.captchaEndpoint, styleName).done(function(captchaHtml) {\n //console.log(\"...\");\n //console.log(captchaHtml);\n //console.log(\"-------------\");\n captchaHtml = captchaHtml.replace(/href=\"/g, 'href=\"' + __captcha());\n capt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change scene states if the player's xposition is outside of the window!
function changeScene() { if (cx > windowWidth - 120) { scene += 1; } }
[ "checkVisibility(){\n if(switchScene.scene.isVisible('SecondLevel')){\n activeScene = 'SecondLevel';\n }\n if(switchScene.scene.isVisible('GameScene')){\n activeScene = 'GameScene';\n }\n }", "function checkPlayerChangedScene(currentScene) {\n // depending on ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add player to grid and controls Position = paramters for passing index where cat should appear, argument passed through when function called.
function addPlayer(position) { // Adds player to position in grid at index betwen [] cells[position].classList.add(playerClass) }
[ "function createPlayerGrid(){ //could pass in a variable in the brackets \n for (let i = 0; i < gridCellCount; i++){\n const cell = document.createElement('div') //creating the divs for the grid \n cell.textContent = i //creating text withing the grid with the value of its index\n //creating the p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a letter and finds all instances of appearance in the string and replaces them in the guess word.
function evaluateGuess(letter) { // Array to store positions of letters in string var positions = []; // Loop through word finding all instances of guessed letter and store in an array. for (var i = 0; i < currentWord.length; i++) { if (currentWord[i] === letter) { positions.push(i)...
[ "function evaluateGuess(letter) {\n \n // Array to store positions of letters in the string.\n var positions = [];\n\n // Loop through word and find all instances of guessed letter, \n // store the indicies in the \"positions\" array.\n for (var i = 0; i < randomAnimals[animalChoice].length; i++) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A noop: each date is its own bucket.
bucket(d) { return d; }
[ "_getBucket(date) {\n const bucketSize = this.eventInterval * 1000\n return Math.floor(date.getTime() / bucketSize)\n }", "bucket(items) {\n let buckets = {};\n items.forEach(item => {\n let date = new Date(item.create_date);\n let min = date.getUTCMinutes();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unsubscribe an event handler from a particular event.
_unsubscribe(eventType, eventHandler) { if (this.handlersMap[eventType] && eventHandler) { this.handlersMap[eventType].delete(eventHandler); } if (!eventHandler || this.handlersMap[eventType].size === 0) { delete this.handlersMap[eventType]; } if (O...
[ "unsubscribe (event, handler) {\n if(event in EventBus.instance.listeners) {\n let index = this.findHandler(event, handler);\n\n // We are going to find the handler and remove it from the array.\n if(index !== -1) {\n EventBus.instance.listeners[event].splice(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
25.4.1.2 PromiseReaction Records 25.4.1.3 CreateResolvingFunctions ( promise )
function CreateResolvingFunctions(promise) { var alreadyResolved = {'[[value]]': false}; var resolve = PromiseResolveFunction(); set_internal(resolve, '[[Promise]]', promise); set_internal(resolve, '[[AlreadyResolved]]', alreadyResolved); var reject = PromiseRejectFunction(); set_in...
[ "function CreateResolvingFunctions (promise) {\n var alreadyResolved = {'[[value]]': false}\n var resolve = PromiseResolveFunction()\n set_internal(resolve, '[[Promise]]', promise)\n set_internal(resolve, '[[AlreadyResolved]]', alreadyResolved)\n var reject = PromiseRejectFunction()\n set_internal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Required for mobile apps. Suspends drawing while map is zooming in/out. Insures map is in a steady state before we add a new graphic.
function synchronizeMap(){ map.on("zoom-start",function(){ console.log("Graphic drawing suspended"); map.graphics.suspend(); }) map.on("zoom-end",function(){ console.log("Graphic drawing resumed"); ...
[ "function updateMap() {\n //Anything else should be handled by pre and postdraw functions\n ms.draw();\n }", "drawOnNextTick() {\n _drawMapOnNextTick = true;\n }", "function update_map_canvas_check()\n{\n var time = new Date().getTime() - last_redraw_time;\n if (time > MAPVIEW_REFRESH_INTERVAL) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares two fields, returns true if they are identical, false otherwise
function isSameField(a, b) { if (a.length !== b.length) { return false; } for (let i = 0; i < b.length; ++i) { if (a[i] !== b[i]) { return false; } } return true; }
[ "isEqual(req, schema, one, two) {\n for (const field of schema) {\n const fieldType = self.fieldTypes[field.type];\n if (!fieldType.isEqual) {\n if ((!_.isEqual(one[field.name], two[field.name])) &&\n !((one[field.name] == null) && (two[field.name] == null))) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creating the dataPoint Class, where each dataPoint is a Nobel Prize winner with various parameters
function dataPoint(posX, posY, imgH, imgW, winnerObj) { this.posX = posX; this.posY = posY; this.imgH = imgH; this.imgW = imgW; this.winnerObj = winnerObj; // this.draw = function() { if (this.winnerObj.gender == "male") { tint(153, 255, 153); image(med...
[ "constructor(dimen, totpoint) {\n dimen = dimen === undefined ? 2 : dimen;\n\n this.dimen = dimen;\n this.totpoint = totpoint;\n this.points = [];\n\n if (dimen == 2) {\n this.r = 1 / Math.sqrt(totpoint);\n } else if (dimen == 3) {\n this.r = 1 / Math.cbrt(totpoint);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logic xor a register with accumulator
xorReg(register) { regA[0] ^= register[0]; regF[0] = regA[0] ? 0 : F_ZERO; return 4; }
[ "handle_XOR(operandA, operandB) {\n this.reg[operandA] ^= this.reg[operandB];\n }", "XOR_R(r1){\n this.register_A = r1 ^ this.register_A;\n this.zero_flag = this.register_A === 0;\n this.carry_flag = false;\n this.subtraction_flag = false;\n this.half_carry_flag = false;\n }"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new array of morph settings containing (i) an empty slot for each of the given frame''s morph settings and (ii) a slot containing a copy of each of the "extra" settings, that is, settings appearing in the given array of morph settings, but but not in the given frame''s morph settings.
makeMorphListWithExtras(A_FRAME, B_MORPHS) { var A_MORPHS, bextras, morphs; //---------------------- A_MORPHS = A_FRAME.getMorphs(); // Identify the extra B morphs, i.e. those for which there is // for which there is no entry in the A list. bextras = B_MORPHS.filter(function(bmph) { return (A_FRAME.getMorph(bmph.getNam...
[ "morphsWithAmbient(frame, ambientframe, scale) {\nvar AMB_AMT, AMB_MORPH, AMB_MORPHS, MORPH, MORPHS, M_4CC, amt, j, len, m, newmorph, newmorphs;\n//----------------\nMORPHS = frame.getMorphs();\nAMB_MORPHS = ambientframe.getMorphs();\n// Assume initially that we can just use the original morphs.\n// But if the ambi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Position functions return a Victor that is a position within the canvas
Center () { return new Victor(this.canvasWidth / 2, this.canvasHeight / 2); }
[ "get position() {\n const boundRect = this.canvas.getBoundingClientRect() || { left: 0, top: 0 };\n return new hamonengine.math.vector2(boundRect.left, boundRect.top);\n }", "function getPositionToCreateEntity() {\n \tvar direction = Quat.getFront(MyAvatar.orientation);\n \tvar ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
WHILE MESSAGES TO PLAY DO PLAYUP
function doPlayup() { if (keepGoing) { if (copyEv.length) { if (track[playtrack].midiMess[midEvent].data0<192 || track[playtrack].midiMess[midEvent].data0>207) {noteMessage = [track[playtrack].midiMess[midEvent].data0, track[playtrack].midiMess[midEvent].data1, track[playtrack].midiMess[midEvent].data2]; ...
[ "function messageLoop() {\n\tfor(i=0;i<repeating_times;i++) {\n\t\tsession.streamFile(file_path+'/'+voice_id+'/voice_'+voice_id+'.wav');\n\t console_log('notice', 'file played '+i+'\\n');\n\t}\n}", "function fadeInCtrlsMsg()\n {\n var loop = jQuery.runloop();\n loop.addKey('100%'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the last executed list
getLastList() { return new TotoAPI().fetch('/supermarket/pastLists?maxResults=1').then((response) => response.json()); }
[ "function load_last_opened_list()\r\n{\r\n\treturn Titanium.App.Properties.getString('last_opened_list', '1');\r\n}", "executingTaskList () {\n return _.orderBy(this.executingTaskQueue, ['lastExecutedTime'], ['asc'])\n }", "function last() {\n return promisedNames().then(res => res[res.length - 1])\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API test for 'GetCa', Get CA(Certificate Authority) setting from the hub
function Test_GetCa(key) { return __awaiter(this, void 0, void 0, function () { var in_rpc_hub_get_ca, out_rpc_hub_get_ca; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("Begin: Test_GetCa"); in_rpc...
[ "get caCertificate() {\n return this._caCertificate;\n }", "async function createCa() {\n try {\n return await mkcert.createCA({\n organization: 'Hello CA',\n countryCode: 'NP',\n state: 'Bagmati',\n locality: 'Kathmandu',\n validityDays: 365\n })\n } catch (e) {\n th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
12.4 nth triangular number
function triangular(n) { }
[ "function nthTriangular (n) { return n * (n + 1) / 2 }", "function triangular( n ) {\n if(isNaN(n) || n < 0) return 0;\n return (n+1)*n/2;\n}", "function triangular(n) {\n return (n > 0) ? (n * (n + 1) / 2) : 0;\n}", "function triangular( n ) {\n return (n > 0) ? ((n * n) + n) / 2 : 0;\n}", "function nt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reverse geocode a location and callback with zip5, address (formatted address), and location (lat, lng) properties
function reverseGeocode(location, callback) { var latlng = util.format("%s,%s", location.lat, location.lng) , query = qs.stringify({ latlng: latlng, sensor: false }) , reqtmpl = "http://maps.googleapis.com/maps/api/geocode/json?%s" , req = util.format(reqtmpl, query) , geo ; request(req, func...
[ "function reverseGeocode(coords) {\n var geocoder = new google.maps.Geocoder(),\n coordinates = new google.maps.LatLng(coords[0], coords[1]),\n setting = { 'latLng': coordinates };\n geocoder.geocode(setting, function (results, status) {\n if (status === 'OK') {\n var address =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update config based on canvas
updateConfig(canvas) { this.size = canvas.size; this.updateCache(); }
[ "updateConfig(canvas) {\n this.config.radius = Math.min(canvas.center.x * 2 / 3, canvas.center.y * 2 / 3);\n\n this.config.center = canvas.center;\n\n this.config.rawScale = this.config.radius / Math.min(canvas.width, canvas.height);\n\n this.refresh();\n }", "up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the next match from a given position
findNextMatch(string, startPosition, callback) { if (startPosition == null) { startPosition = 0; } if (typeof startPosition === 'function') { callback = startPosition; startPosition = 0; } try { const match = this.findNextMatchSync(...
[ "findNextMatch(string, startPosition, callback) {\r\n if (startPosition == null) {\r\n startPosition = 0;\r\n }\r\n if (typeof startPosition === 'function') {\r\n callback = startPosition;\r\n startPosition = 0;\r\n }\r\n try {\r\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get request to new controller method to retrieve project form and append to the DOM
function newProjectForm() { $.get("/projects/new", function(projectForm) { document.getElementById('js-new-project-form').innerHTML = projectForm; }).done(function() { listenerSaveProject(); }) }
[ "createProjectAJAX() {\n var project = {};\n project.nodeType = \"Project\";\n project.class = \"Project\";\n project.name = this.$.projectName.value;\n if (this.$.projectDescription.value) {\n project.description= this.$.projectDescription.value;\n }\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================ Useful operations =========================== / Function used to filter installed apps based on their category
function filterApps(selcat){ if(selcat == "All"){ $("#app-pane div").each(function(){ if($(this).is(":hidden")){ $(this).show("fast"); } }); } else{ $("#app-pane div").each(function(){ var str ...
[ "function filterApps() {\n\tlet { activeTags, searchText } = data;\n\t\n\n\tif (activeTags.length === 0 && searchText === \"\") {\n\t\tgoHome();\n\t} else {\n\t\tappd.search({ text: searchText, tags: activeTags }, (err, data) => {\n\t\t\tif (err) {\n\t\t\t\tLogger.system.error(`FDC3 App search failed!: ${err}`);\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renders the start page to app
function renderStartPage() { addView(startPage()); }
[ "function Main() {\n console.log(`%c App Started...`, \"font-weight: bold; font-size: 20px;\");\n \n insertHTML(\"/Views/partials/header.html\", \"header\");\n\n setPageContent(\"/Views/content/home.html\");\n\n insertHTML(\"/Views/partials/footer.html\", \"footer\");\n \n }", "function start(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end animation with audio
function endAnimation() { let endAnimationText = getEndAnimation(); endAnimationText.innerHTML = "Finished!"; endAnimationText.style.fontSize = "50px"; const finishedSound = audioFiles.finishedSound; if(audioOn && inhaleHold > 0) { finishedSound.load(); finishedSound.play(); } endEarlyDetails(); }
[ "function endGameAudio() {\n audioEnd.play();\n}", "function audioCompleted() {\n\tendPresentation();\n}", "function audioEnded()\n {\n stopAudioTimeout();\n\n _Playing.off();\n _Playing = null;\n playNextEntry();\n }", "endAnimation(){\n this.canc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An island of bodies connected with equations.
function Island() { /** * Current equations in this island. * @property equations * @type {Array} */ this.equations = []; /** ...
[ "function Island(){/**\n * Current equations in this island.\n * @property equations\n * @type {Array}\n */\nthis.equations=[],/**\n * Current bodies in this island.\n * @property bodies\n * @type {Array}\n */\nthis.bodies=[]}", "function Island(){/**\n * Current equations in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a class (word) from a list of classes (spaceseparated words).
function remClass(clist,cls) { return fold(function(v, acc) {if(v != cls) return acc + (acc == '' ? '' : ' ') + v; else return acc;},'',clist.split(' ')); }
[ "function RemoveClass(ele, classStr) {\r\n ele.className = ele.className.replaceAll(\" \" + classStr, \"\"); //function (replaceThis, withThis)\r\n // For words :\r\n // eg. <input class=\"word\" type=\"text\" value=\"Tucan\" />\r\n // <input class=\"word hide\" type=\"text\" value=\"Tucan\"\r\n}", "removeC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var rand3 = new RandIntArray3(); rand3.hello();
function RandIntArrayCppStyle(_data,_size) { var size, used, data = []; //new Array(); console.log("RandIntArray constructor"); size = _size; used = 0; data = _data; size = data.length; console.log('data: ' + String(data)); console.log('data.length: ' + String(data.length)); consol...
[ "static getRandomInt(){\r\n \r\n }", "function Random() {\n this.randomint = function(min,max) { \n if (max == undefined) { max = 0}\n return Math.floor(Math.random() * (max - min + 1)) + min; \n }\n this.sample = shuffle_sample\n this.shuffle = shuffle_sample\n\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check if user is logged out or not
isLoggedOut() { return !this.isLoggedIn(); }
[ "isLoggedOut() {\n return !this.isLoggedIn();\n }", "function isLoggedIn() {\n return !!user;\n }", "function logOut() {\n toDoUserOffline();\n sessionStorage.removeItem('currentUser');\n currentUser = {};\n checkAuthorization();\n }", "function log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
URL for this folder readonly attribute ACString folderURL;
get folderURL() { return true; }
[ "get folderURI() { return this._folderURI;}", "get folder() {\r\n return new Folder(this, \"folder\");\r\n }", "get folderId() { return this._folderId;}", "function getPublicUrl(folder, file) {\n // TODO: escape this\n return 'https://host.googledrive.com/host/' + folder.getId() + '/' + file.getNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transclude the materialTab items into the tabsHeaderItems container
function transcludeHeaderItems() { $transclude( function (content) { var header = findNode('.tabs-header-items', element); var parent = angular.element(element[0]); angular.forEach(content, function (node) { var intoHeader = isNodeType(node, 'material-tab') |...
[ "function transcludeHeaderItems() {\n $transclude(function (content) {\n var header = findNode('.tabs-header-items', element);\n var parent = angular.element(element[0]);\n\n angular.forEach(content, function (node) {\n var intoHeader = isNodeType(node, 'materi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles between Running and Stopped States
function ToggleStatus() { if (Consts.currStatus == Status.stopped || (Consts.currStatus == Status.init && Consts.stockTime == 0)) { incrementSecondMethod = setInterval(incrementSeconds, 10); Consts.currStatus = Status.running; $('#statusToggle').val('Pause'); } else if (Consts.currSt...
[ "function toggleRunning()\r\n{\r\n running = !running;\r\n console.log('Switched running to ', running);\r\n}", "toggleIsRunning() {\n this.setState({\n isRunning: !this.state.isRunning\n });\n }", "toggle() {\n this.pause.status ? this.start() : this.stop();\n }", "function changeRunnin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a request. If model is not null, it will pass it to the request as JSON. It will parse the response using the parser function provided, encapsulated in a promise. Uses default item parser.
buildRequestAndParseAsModel(url, requestType, model) { return this.buildRequestAndParseAsT(url, requestType, model, this.parser); }
[ "function parserRequestFactory(model){\n new parserRequest(model);\n}", "async request (url, type = 'json') {\n return await this.requester.single(this.baseUrl + url, {headers: this.buildHeaders(), type})\n }", "function fetchModel(url) {\n return axios.get(url)\n .then((response)=>{\n if(re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build and set result list for the day sum values. One list for: lastYear, currentYear, lastMonth, currentMonth, lastWeek, currentWeek
function buildAndSetResultListsGas(value){ var currentYear = moment().year(); var currentMonth = moment().month(); var currentMonthYear = moment().year(); var currentMonthDays = moment().daysInMonth(); var currentWeek = moment().isoWeek(); var currentWeekYear = moment().isoWeekYear(); var st...
[ "function buildAndSetResultListsPower(value){\t\r\n\t\tvar currentYear = moment().year();\r\n\t\t//var lastYear = moment().subtract(1, 'years').year();\t\r\n\r\n\t\tvar currentMonth = moment().month();\r\n\t\tvar currentMonthYear = moment().year();\r\n\t\tvar currentMonthDays = moment().daysInMonth();\r\n\t\t//var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the filter completely
function clearFilter() { filteredDimensions.forEach(function(v, i) { v.filterAll(); }); filteredDimensions = []; }
[ "clearFilter() {\n this.scope['filterName'] = null;\n this.setFilterFunction(null);\n // this.updateSize_(false);\n }", "clearFilter() {\n this._filter = undefined;\n }", "function clearFilter() {\n if (originalImage != null) {\n filteredImage = null;\n originalImage.drawTo(canvas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the RGB color with which a layer is tinted when it is being drawn.
getColorAt(layerID) { return this.compositeEffect.getLayerAt(layerID).color }
[ "get tint() {\n return this._tintColor.value;\n }", "get tintColor() {\n return this.style.fillColor;\n }", "function getLayerColor( targetLayer ){\n\tvar actionDescriptor = Stdlib.getLayerDescriptor(docRef, targetLayer)\n\treturn typeIDToStringID(actionDescriptor.getEnumerationValue(stringIDToTyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the currently executing script name, suitable for embedding in an error message.
function getScriptName() { var _require$main; // In Rhino, the current script name is available in require.main.id var scriptName = (_require$main = __webpack_require__.c[__webpack_require__.s]) === null || _require$main === void 0 ? void 0 : _require$main.id; return scriptName ? "'".concat(scriptName, "'") : "...
[ "function getScriptName() {\n return cc._RFpeek().script;\n}", "static getScriptName(trimExtension = true) {\n // Variables\n let error = new Error();\n let source;\n let lastStackFrameRegex = new RegExp(/.+\\/(.*?):\\d+(:\\d+)*$/);\n let currentStackFrameRegex = new RegExp(/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the HTML markup for the status. The status is referenced by name:
statusDivHtml(status) { 'use strict'; return `<div class="${$.otp.workflows.statusToClassName(status)}"></div>`; }
[ "function statusHTMLTemplate (newStatus) {\n return `<h3>Status</h3>\n <p>${newStatus}</p>`;\n}", "function displayStatus(status)\n{\n if (status == 1)\n return '<span class=\"statusSpan\" title=\"Active\"></span>';\n else\n return '<span class=\"statusSpan inactive\" title=\"Inacti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the stats of the hero and update them after clicking on one of the features
function displayStats(hero){ const stats = document.getElementById("stats"); const heroStats = `Name: ${hero.name} | Health: ${hero.health} | Weapon: ${hero.weapon.type} | Damage: ${hero.weapon.damage}`; stats.innerHTML = heroStats; console.log("it refreshed"); return hero }
[ "function update_hero(e) {\n let stat_div = document.getElementById('hero_stats');\n\n if (stat_div.childElementCount > 0) {\n stat_div.innerHTML = \"\";\n };\n\n // stat Nom\n let div_t_name = document.createElement('p');\n div_t_name.innerHTML = '</p><b>Nom</b>: ' + e.name + '<p>';\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the distance between two actors
function getDistance(a, b) { return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); }
[ "distance(actor) {\n let x1 = (this.x * TILE_SIZE) + this.renderOff.x;\n let y1 = (this.y * TILE_SIZE) + this.renderOff.y;\n let x2 = (actor.x * TILE_SIZE) + actor.renderOff.x;\n let y2 = (actor.y * TILE_SIZE) + actor.renderOff.y;\n // console.log(Math.sqrt(Math.pow(x2 - x1, 2) + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
callback function to set the value of storedTabs
function setStoredTabs(result) { if (result.storedTabs != null) { backConsole.log("Retrieved tabs from storage."); storedTabs = result.storedTabs; } else { backConsole.log("No tabs found in storage.") } }
[ "registeredTabs() {\n this.updateTabs()\n }", "function saveData(){\n chrome.storage.local.set({'tabDict': myTabDict}, function() {\n console.log('Value is set to ' + myTabDict);\n });\n}", "function setAllTabs(tabs) {\n localStorage.setItem(\"tabsInfo\", JSON.stringify(tabs));\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get project name in google console from current url
function locationProjectName () { return document.location.toString().match(/\project=(.+)$/)[1]; }
[ "function getProjectName() {\n\n //splitting the current url for getting the project name\n var path = $(location).attr('href');\n var splitted = path.split('/');\n return splitted[6];\n}", "function getProjectName() {\n\n //splitting the current url for getting the project name\n\n return $('#p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
created function to play and stop gif animation
function playGif() { var state = $(this).attr("data-state"); if (state == "still") { $(this).attr("src", $(this).data("animate")); $(this).attr("data-state", "animate"); } else { $(this).attr("src", $(this).data("still")); $(this).attr("data-state", "still"); } ...
[ "function startStopGif() {\n // The attr jQuery method allows us to get or set the value of any attribute on our HTML element\n var state = $(this).attr(\"data-state\");\n // If the clicked image's state is still, update its src attribute to what its data-animate value is.\n // T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }