query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Attaches a text label to the specified root. Handles escape sequences.
function addTextLabel(root, node) { var domNode = root.append("text"); var lines = processEscapeSequences(node.label).split("\n"); for (var i = 0; i < lines.length; i++) { domNode.append("tspan") .attr("xml:space", "preserve") .attr("dy", "1em") .attr("x", "1") .text(lines[i]); } ...
[ "function addTextLabel(root, node) {\n\t var domNode = root.append(\"text\");\n\n\t var lines = processEscapeSequences(node.label).split(\"\\n\");\n\t for (var i = 0; i < lines.length; i++) {\n\t domNode.append(\"tspan\")\n\t .attr(\"xml:space\", \"preserve\")\n\t .attr(\"dy\", \"1em\")\n\t .at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates, or attempts to evaluate, a ArrayLiteralExpression
function evaluateArrayLiteralExpression({ node, environment, evaluate, typescript, statementTraversalStack }) { // Get the Array constructor from the realm - not that of the executing context. Otherwise, instanceof checks would fail const arrayCtor = getFromLexicalEnvironment(node, environment, "Array").literal...
[ "function ArrayLiteralExpression() {\n}", "visitLiteralArrayExpr(ast, ctx) {\n if (ast.entries.length === 0) {\n ctx.print(ast, '(');\n }\n const result = super.visitLiteralArrayExpr(ast, ctx);\n if (ast.entries.length === 0) {\n ctx.print(ast, ' as any[])');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add recipe //// Ingreedient recalculation Ingreedients
function recalculationIngreedient(){ var id = 0; $('.ingredient_block').each(function(){ $(this).attr('data-groupid', id); $(this).children('.ingredient_content').children('.form__group').children('.input-with-icon').attr('name', 'ingredient[' + id + '][]'); id++; }); }
[ "function createCulinaryRecipe ($name, $cuisine, $complexity, $ingredients, $time, $instruction) {\n recipe = {\n name: $name,\n typeOfCousine: $cuisine,\n complexity: $complexity,\n listOfIngredients: $ingredients,\n preparingTime: $time,\n preparingInstruction: $instru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the baseline alignment property of selected contents.
set baselineAlignment(value) { if (value === this.baselineAlignmentIn) { return; } this.baselineAlignmentIn = value; this.notifyPropertyChanged('baselineAlignment'); }
[ "setVAlign(align) {\n\t\tthis.ctx.textBaseline = align;\n\t}", "get baselineAlignment() {\n return this.baselineAlignmentIn;\n }", "alignText(alignment = \"left\", baseline = \"alphabetic\") {\n if (baseline == \"center\")\n baseline = \"middle\";\n if (baseline == \"baseline\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns 2D array that is the pseudoinverse of m1
function matrix_pseudoinverse(m1) { let m1_t = matrix_transpose(m1); return matrix_multiply(numeric.inv(matrix_multiply(m1_t,m1)), m1_t); }
[ "function matrix_pseudoinverse(m1) {\n\n var mat = [];\n var i,j;\n if (m1.length == m1[0].length){\n return numeric.inv(m1);\n }\n else{\n var m1_T = matrix_transpose(m1);\n if (m1.length > m1[0].length){\n return matrix_multiply(numeric.inv(matrix_multiply(m1_T,m1)),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You add this function, and change this context, it is passed the height of the rocket.
function drawLander(height) { // The y-coordinate goes from 0 to canvas.height, so need to reverse for // the rocket appearing to go down. var ycoord = gameCanvas.height - height; rocketSize = 5; // Rocket is a square, draw it. You should draw a nice rocket. gameContext.fillRect(gameCanvas.width/2, h-rocket...
[ "changeHeight() {\n\n // Decrease the value of y value by 100 and store in variable\n this.height = y_value - 70;\n\n // Set the y value of the pipe\n this.y = 0;\n\n }", "setHeight(newHeight) {this.height = newHeight;}", "changePoleHeight(height){\n\t\tthis.height = height;\n\t}", "setHeight(_he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new reverse string iterator; iterates up to one emoji or byte at a time.
function newReverseIterator(str) { let index = str.length - 1 const iter = () => { if (index === -1) { return EOF } const emoji = emojiTrie.atEnd(str.slice(0, index + 1)) if (!emoji) { const char = str[index] index-- return char } index -= emoji.emoji.length return emoji.emoji } return ite...
[ "function newIterator(str) {\n\tlet index = 0\n\tconst iter = () => {\n\t\tif (index === str.length) {\n\t\t\treturn EOF\n\t\t}\n\t\tconst emoji = emojiTrie.atStart(str.slice(index))\n\t\tif (!emoji) {\n\t\t\tconst char = str[index]\n\t\t\tindex++\n\t\t\treturn char\n\t\t}\n\t\tindex += emoji.emoji.length\n\t\tretu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds `item` into the `target` `Array` or `Set` when it is not already present.
function append(target, item) { if (Array.isArray(target)) { if (!target.includes(item)) { target.push(item); } } else { target.add(item); } return item; }
[ "function addOrRemove (targetArray, targetItem){\n \n //If the item provided isn't in the array provided\n if(targetArray.indexOf(targetItem) == -1){\n \n //Add it\n targetArray.push(targetItem);\n \n //Return the modified array\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the hidden computed routing field Logic: routing number = bankCode+branchCode
function pt4UpdateBankNumber() { var bankNumber = $('#pt4_bankCode').val(); var branchCode = $('#pt4_branchCode').val(); var routingNumber = bankNumber + branchCode; $('#pt4_routing').prop("disabled",false); $('#pt4_routing').val($.trim(routingNumber)); }
[ "function updateSnailHomeNumber() {\r\n //get values\r\n var som = getSlugOMeter();\r\n\r\n //calculate Snail Home Number\r\n var lneff = calculateSnailHomeNumber(som);\r\n\r\n //update corresponding id's output textfield\r\n setTextField(\"snailHomeNum_out\", lneff);\r\n}", "setRoutingKey(value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controlador para obtener los detalles de un post $routeParams nos da los parametros del navegador
function PostDetailCtrl($routeParams, Post, Comment, User) { this.post = {}; this.comments = {}; this.user = {}; var self = this; // referencia a la funcion // Como AJAX es asincrono, se hace una funcion de callback // para que al recuperar el post, recupere el usuario. // El Callback se ha...
[ "function getDetail() {\n Tasks.get({id: $routeParams.taskId}, function(data) {\n $scope.task = data;\n }); \n }", "function listPostulant(){\n\t\t/***\n\t\t\tRequète AJAX permettant de lister les postulants\n\t\t\tParamètres:\n\t\t\tSortie: \"auth\" => Variable permettant d'indiquer ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
push to income var
function addIncome(titleVal, typeVal, totalVal) { var data = createObject(titleVal, typeVal, totalVal); console.log(data); income.push(data); console.log(`"${titleVal.title}" has been added!`); }
[ "function addToIncome(){\n\t\tincomeStore = income;\n\t\tfor (var i = 0, row; row = tab.rows[i]; i++) {\n\t\t\t //iterate through rows\n\t\t\t //rows would be accessed using the \"row\" variable assigned in the for loop\n\t\t\t\n\t\t\t for (var j = 0, col; col = row.cells[j]; j++) {\n\t\t\t //iterate thro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send request checkout order to server
function requestCheckoutOrder() { // disable checkout button disableCheckoutButton(true); getListCupLength(); showListCup(); $.ajax({ type : "POST", contentType : "application/json", url : "order", data : JSON.stringify(listCup), dataType : 'json', timeout : 10000, beforeSend : function...
[ "function SendPrimeAndOrderInformation() {\n let checkOutUrl = API + \"/order/checkout\"\n SendPrimeAndOrderAjax(checkOutUrl);\n}", "finalizeOrder() {\n this.request(\n 'PUT',\n `${this.props.apiUrl}/orders/${this.props.order.id}/status?type=priced`,\n undefined,\n (response) => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear sheet but leave headers
clearSheet() { const { sheet } = this; const row = this.numHeaders + 1; const column = 1; const numRows = sheet.getLastRow() - row + 1; if (numRows < 1) { return; } const numColumns = this.fields.length; sheet.getRange(row, column, numRows, numColumns).clearContent(); }
[ "function clearSheet(sheet) {\n var lastRow = sheet.getLastRow();\n var lastColumn = sheet.getLastColumn();\n var range = sheet.getRange(2,1,lastRow,lastColumn);\n range.clear();\n}", "function ClearSheet(sheet)\n{\n sheet.clear({\n formatOnly: true,\n contentsOnly: true\n });\n sheet.cle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the given compilation job needs to be done.
function needsCompilation(job, cache) { for (const file of job.getResolvedFiles()) { const hasChanged = cache.hasFileChanged(file.absolutePath, file.contentHash, // we only check if the solcConfig is different for files that // emit artifacts job.emitsArtifacts(file) ? job.getSolcCo...
[ "canWorkJob(job) {\n return this.specialization().indexOf(job.type) !== -1;\n }", "function checkIfCanWork(job){\n var check = 0;\n for (i in jobs[job]['cost']){\n if (jobs[job]['cost'][i] <= currency[i]['amount']){\n check++;\n }\n }\n if (check == Object.keys(jobs[job]['cost']).length && jobs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Methods ///////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// Checks whether monowave closes the directional action or not
check(monowave) { // Directional Action Doesn't end until the next monowave retraces 100% of the current one // Check if monowave direction is the same as Directional Action Direction if (this.direction != monowave.direction) { // Different Direction, now check the strength of the change if (monowave.relati...
[ "function checkClosed() {\n\t\t\t if ((!win) || win.closed) {\n\t\t\t win = null;\n\t\t\t handleApproval();\n\t\t\t }\n\t\t\t }", "function checkForOutsideAction () {\n\tplayer.handle.isPaused(function (paused) {\n\t\tif (paused && player.state === player.STATES.PLAYING) {\n\t\t\tplayer.state = p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internally update active state.
setActiveState(active) { // If (cast) active value has changed: if (!!this._isActive !== active) { // Update to the new value. this._isActive = active; // Fire the appropriate activation event. if (active) { this.onActivate.emit(); ...
[ "update() {\r\n if (!this._active) {\r\n return;\r\n }\r\n this._updateState();\r\n }", "_updateActiveFlag() {\n // Calculate active flag.\n let newActive = this.isActive();\n if (this._active !== newActive) {\n if (newActive) {\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var with filename.extention /function to check if file validates by extention. Is not so secure as our checks in PHP, but is not necessary here. Nothing will be uploaded. Only the file will be presented as a preview for the user. Server has nothing to do with the preview. Extra validation is when someone publish his po...
function checkFileType() { var validFileType = false; var regexFileType = /(?:\.([^.]+))?$/; //whats my extention? var checkValidFileType = regexFileType.exec(fileName)[1]; var validFileTypes = ["jpeg", "png", "gif", "jpg"]; //which file types are valid? ...
[ "filevalidation() {\n var re = /(?:\\.([^.]+))?$/;\n var ext = re.exec(this.state.file.name)[1];\n if (ext === \"txt\") {\n return true;\n } else {\n return false;\n }\n }", "function validateFileBeforeUpload (file){\n // file type checking \n var validFormats = ['jpg','jpe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of integers A sorted in nondecreasing order, return an array of the squares of each number, also in sorted nondecreasing order. Example 1: Input: [4,1,0,3,10] Output: [0,1,9,16,100]
function squaresOfASortedArray(nums) { let length = nums.length, left = 0, right = length - 1, index = length - 1, result = new Array(nums.length).fill(0) while (left <= right) { const leftElement = nums[left] * nums[left] const rightElement = nums[right] * nums[right] if (leftElement > ...
[ "function sortedSquaredArray(array) {\n\tconst output = []\n\t// add negative integers to a new array\n\tconst negs = array.filter(int => int < 0)\n\t// iterate through original array, and push computed squares onto output array\n\t// if element is > current neg element, push neg element's square onto output array\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the TaskChart Refresher.
clearRefresher() { if (this.taskinterval) { clearInterval(this.taskinterval); this.taskinterval = null; } }
[ "function removeChart() {\n chart.destroy();\n }", "function removeChart() {\n monte_vis.chart.destroy();\n // reset chart sizing\n chart_container.style = \"\";\n }", "removeChart() {\n\t\tthis.chart.removeChart();\n\t}", "function removeChart() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the loading timeout is triggered.
onLoadingTimeout() { this.browserProxy_.timeout(); this.onErrorOccurred(); }
[ "startLoadingTimer_() {\n this.clearLoadingTimer_();\n this.loadingTimer_ = setTimeout(\n this.onLoadingTimeOut_.bind(this), MAX_GAIA_LOADING_TIME_SEC * 1000);\n }", "function setTimeoutLoader(){\n $timeout(function () {\n hideLoader();\n }, 30000);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `AuthProperty`
function CfnApi_AuthPropertyValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); errors.collect(cdk.propertyValidator('authorizers', cdk.validateObject)(properties.authorizers)); errors.collect(cdk.propertyVal...
[ "function CfnApi_AuthPropertyValidator(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" ] ] } }
appendNode > adds node to the end of the list
appendNode(data){ if(this.head === null){ this.head = new Node(data); } let currentNode = this.head; while(currentNode.next !== null){ currentNode = currentNode.next; } currentNode.next = new Node(data); }
[ "append(val) {\n const node = new Node(val, null);\n let current = this.head;\n while (current !== null) {\n if (current.next === null) {\n current.next = node;\n break;\n }\n current = current.next;\n }\n }", "append(val,node){\n let n = new Node(val);\n\n if(this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new colored log entry. Example: format('warn') => 21 Feb 11:24:47 warn: Returns String.
format(level) { const raw = new Date(); // 30 May 19:44:27 const d = raw.toDateString().replace(dateRe, '$2 $1'); const t = raw.toTimeString().replace(timeRe, ''); const date = `${d} ${t}`; // const red1 = /^\w{3},\s|\sGMT$/g; // const red2 = /(\w{3})\s\d{4}/; // const date = raw.toGMTSt...
[ "LogFormat() {}", "function createFormatter(format, useColor = false) {\n const { combine, colorize, printf } = winston.format;\n switch (format) {\n case SpawnerTypes_1.LogTimeFormat.Delta: {\n const custom = printf(({ deltaTime, level, message }) => {\n return `${deltaTime...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Width and Height of svg.js canvas Shape drawing function. Using the shape identifier and position within the 3shape structure, it generates a shape of the right fit. Absolute sizes are used here since this is a reference object. When reference image is used, it is scaled and adjusted using transformations.
function drawShape(shapeNumber, positionNumber, rotationDegrees){ var maxSize = 500; // Assuming width and height of the shape are the same, this is the size of the outer shape. var padding = 0; // Inner shapes are scaled down and hence need a padding from the left/top margins t...
[ "function shapey_createShape(options,shapeData)\n{\n\ttry\n\t{\n\t\t//if this shape doesn't have an id, or the id has already been used, assign a new one.\n\t\tif($('#'+shapeData.id).length > 0 || !shapeData.hasOwnProperty('id'))\n\t\t{\n\t\t\t//shapeData.id = shapeData.id + Math.floor((Math.random()*1000)+1)\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task Given a string s of lowercase letters ('a' 'z'), get the maximum distance between two same letters, and return this distance along with the letter that formed it. If there is more than one letter with the same maximum distance, return the one that appears in s first. Input/Output [input] string s A string of lower...
function distSameLetter(s){ var uniques = s.split('').filter((a, i) => s.indexOf(a) === i).join(''); var arr = ['', 0]; for(var i = 0; i < uniques.length; i++){ diff = s.lastIndexOf(uniques[i]) - s.indexOf(uniques[i]) + 1; if(diff > arr[1]){ arr = [uniques[i], diff]; } } return arr....
[ "function solve(s) {\n let abc = Array.from('abcdefghijklmnopqrstuvwxyz');\n s = s.replace(/[aeiou]/gi, ' ').split(' ');\n\n let result = s.map(el => el.split('').reduce((a, b) => a + abc.indexOf(b)+1, 0))\n\n return Math.max(...result)\n}", "function solve(s) {\n var letters = 'abcdefghijklmnopqrstu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If we have any union or interface types throw if no there is no resolveType or isTypeOf resolvers
function checkForResolveTypeResolver(schema, requireResolversForResolveType) { Object.keys(schema.getTypeMap()) .map(function (typeName) { return schema.getType(typeName); }) .forEach(function (type) { if (!(type instanceof graphql_1.GraphQLUnionType || type instanceof graphql_1....
[ "function checkForResolveTypeResolver(schema, requireResolversForResolveType) {\n var _a;\n utils.mapSchema(schema, (_a = {},\n _a[utils.MapperKind.ABSTRACT_TYPE] = function (type) {\n if (!type.resolveType) {\n var message = \"Type \\\"\" + type.name + \"\\\" is missing a \\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a user element and returns the user's data, null if not found, or false if allUsers array is empty.
function getUserData(userElement) { if (!allUsers.length) return false; for (var i = 0, len = allUsers.length; i < len; i++) { if (allUsers[i].userElement.html() === userElement.html()) { return allUsers[i].userData; } } return null; }
[ "function getUserObject(userElement) {\n\t\tif (!allUsers.length) return false;\n\n\t\tfor (var i = 0, len = allUsers.length; i < len; i++) {\n\t\t\tif (allUsers[i].userElement.html() === userElement.html()) {\n\t\t\t\treturn allUsers[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "function getUserData(userId) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a mutable ref for a `Path` object, which will stay in sync as new operations are applied to the editor.
pathRef(editor, path) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var { affinity = 'forward' } = options; var ref = { current: path, affinity, unref() { var { current } = ref; var pathRefs = Editor.pat...
[ "pathRef(editor, path) {\n var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};\n var {\n affinity = \"forward\"\n } = options;\n var ref2 = {\n current: path,\n affinity,\n unref() {\n var {\n current\n } = ref2;\n var path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isIsogram( "Dermatoglyphics" ) == true isIsogram( "aba" ) == false isIsogram( "moOse" ) == false // ignore letter case 1. convert to array added toLowerCase() on str to ignor case, remove to match case.
function isIsogram(str) { return !((/([a-zA-Z]).*?\1/).test(str.toLowerCase())); }
[ "function isIsogram(str){\n const arr = str.toLowerCase().split('')\n \n const usedLetters = [];\n \n for (let i = 0; i < arr.length; i++) {\n const letter = arr[i];\n if (usedLetters.indexOf(letter) == -1){\n usedLetters.push(letter)\n } else {\n return false\n }\n }\n return true;\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a trigger event handler for the given collision event state.
onTrigger(eventType, handler) { this.internal.on(eventType, handler); }
[ "onCollision(eventType, handler) {\n this.internal.on(eventType, handler);\n }", "createEventTrigger() {\n this.event1 = new EventTrigger({\n scene: this,\n x: 1200,\n y: 830,\n key: \"eventTrigger\",\n id: 1,\n });\n this.event1.setVisible(false);\n\n //Interact lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether the given list of modules contains an external module.
containsExternals(modules) { for (let index = 0, length = modules.length; index < length; index++) { if (modules[index].flags.isExternal) { return true; } } return false; }
[ "function containsExternals(modules) {\n for (var index = 0, length = modules.length; index < length; index++) {\n if (modules[index].isExternal)\n return true;\n }\n return false;\n }", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verifica se uma string representa uma hora
function isHour(value) { return /^\d+\:\d{2}$/.test(value); }
[ "function CheckTime(str){ \r\n\thora=str.value; \r\n\t\tif (hora=='') { \r\n\t\t\treturn; \r\n\t\t} \r\n\t\tif (hora.length>5) { \r\n\t\t\talert(\"Introdujo una cadena mayor a 5 caracteres\"); \r\n\t\t\treturn; \r\n\t\t} \r\n\t\tif (hora.length!=5) { \r\n\t\t\talert(\"Introducir HH:MM\"); \r\n\t\t\treturn; \r\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asynchronously create or revoke a share URL.
function generateShareUrl(){ //Grab a local ref to the webclient (save some typing) var webClient = pureweb.getFramework().getClient(); //If we don't have a share URL... if ((shareUrl === undefined) || (shareUrl === null)) { //Stop listening for disconnection events (as we expect the user to ba...
[ "function shareLinkCreationCallback(pid, deffered) {\n var urlForSharing = 'https://your-site.com/path?key=123';\n deffered.resolve(urlForSharing);\n }", "async function revokeShare(fileId, userAddress) {\n return await $.ajax({\n url: domain + \"/file/\" + e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that there are `pointerCount` active pointers, and that all have moved to `dir` direction.
function isMultiSwipe(dir, pointerCount) { const isSwipeDir = getIsSwipe(dir); const allGesturesDir = ActivePointers.every(isSwipeDir); return ActivePointers.length === pointerCount && allGesturesDir; }
[ "wallCheck(position,direction,distance)\n\t{\n\t\tlet currentPosition = position;\n\t\tfor(let x=0;x<distance;x++){\n\n\t\t\t\tswitch(direction){\n\t\t\t\t\tcase(0):\n\t\t\t\t\t\tif(this.props.G.cells[currentPosition].walls[0] === 0){\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentPosition = current...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The difference between this is confusing, but this actually signifies that we're appending a child element at some point AFTER parentInstance has been mounted (for instance, in response to an update which causes a new child to appear in the component tree.)
appendChild(parentInstance, child) { parentInstance.appendChild(child); }
[ "appendInitialChild(parentInstance, child) {\n parentInstance.appendChild(child);\n }", "mount(parent) {\n if (parent instanceof HTMLElement) {\n parent.appendChild(this.element);\n } else if (parent instanceof Component) {\n // parent.mountChild(this);\n parent.element.appendChild(this.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a form submission for uploading a new image to associate with the project.
function onAddNewImageFormSubmit() { let form = new FormData(this); form.append('action', 'addProjectImage'); api.post('/project-images.php', form, true) .then(res => { snackbar(res.message, 'success'); onUploadImageSuccess(res.content.id); }) .catch(err => {...
[ "function handleImageUpload(event) {\n // prevent standard form submit\n event.preventDefault();\n\n // clear existing prediction display\n clearElement(predictionElement);\n\n // if file selected and extension allowed\n if (imageInput.value && isAllowedExtension(imageInput...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when done reading the file display total number of items and quit redis connection
function handleEnd() { console.log('---Done reading file---'); client.scard(textName, function(err, res) { console.log("number of sets:", res); // will be true if successfull }); // client.llen(listName+"set", function(err, len){ // var totalItems = len // console.log("---Total Number...
[ "function handleEnd() {\n\tconsole.log('---Done reading file---');\n\t\n\t// client.llen(listName+\"set\", function(err, len){\n\t// \tvar totalItems = len\n\t// \tconsole.log(\"---Total Number of Items:\", totalItems, \"---\");\n\t// });\n\n\t// client.lindex(listName, 1, function (err, data) {console.log(data)})\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set (or add/remove) slot value.
set(name, value) { if (value === undefined) { this.remove(name); } else { if (this.slots) { for (let n = 0; n < this.slots.length; n += 2) { if (this.slots[n] === name) { this.slots[n + 1] = value; return; } } } this.add(name, v...
[ "set(name, value) {\n if (this.slots) {\n for (let n = 0; n < this.slots.length; n += 2) {\n if (this.slots[n] === name) {\n this.slots[n + 1] = value;\n return;\n }\n }\n }\n add(name, value);\n }", "set_value(n, value) {\n this.slots[n * 2 + 1] = value;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decide if a bead can be slide and what direction to slide it
function decideSlideBead(beadSpot){ let x; spot = beadChecker("left", "left"); if (beadSpot === spot && canClick){ moveBead("right"); } else { spot= beadChecker("right", "right"); if (beadSpot === spot && canClick){ moveBead("left"); } } }
[ "get canTurnToRight() {\n return this.wrap || this.currentIndex < this.childSlides.length - 1;\n }", "function directionalArrow(conditional){\r\n if(conditional) {\r\n numberOfSlide++;\r\n } else {\r\n numberOfSlide--;\r\n }\r\n hideSlide();\r\n}", "function canSlideSwipe(){\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For paginated scrolling, simply scroll the card one item in the given direction and let css scroll snaping handle the specific alignment.
function scrollToNextPage() { card_scroller.scrollBy(card_item_size, 0); }
[ "function getAmountToScrollToCenterNextCard(direction) {\n var centeredLocation = parentContainer.height() / 2 ;\n var scrollDifference = 0;\n\n if (direction < 0) {\n $.each(cardDatas, function(i, cardData) {\n var height = getCardHeightPx(cardData.card);\n var totalCardSpace = height +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revoke the Ship It on the review. This will first confirm that the user does want to revoke the Ship It. If they confirm, the Ship It will be removed via an API call.
async _revokeShipIt() { this._$boxStatus.addClass('revoking-ship-it'); const confirmation = RB.ReviewRequestPage.ReviewEntryView.strings.revokeShipItConfirm; if (!confirm(confirmation)) { this._clearRevokingShipIt(); return; } const review =...
[ "function revokeReceipt(receiptID) {\n if (cookie != null) {\n var str = PROXY_CONTEXT_PATH + \"/portal/gadgets/consent_management/revoke_receipt.jag\";\n\n $.ajax({\n type: \"POST\",\n url: str,\n data: {cookie: cookie, user: userName, id: receiptID}\n\n })\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toggleCell: To handle showing the circle with actual color
function toggleCell(selector) { $(selector).css('background', selector.attr('data-circle-color')); }
[ "function toggleCell(e) {\n\tthis.toggleBackground();\n}", "toggleCell(value) {\n if (this.convCell !== undefined) {\n this.convCell.visible = value;\n }\n if (this.primCell !== undefined) {\n this.primCell.visible = value;\n }\n }", "color( clicked, cell ) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read the doc back out from the database. we don't store the _id or _rev because we already have _doc_id_rev.
function decodeDoc(doc) { if (!doc) { return doc; } var idx = doc._doc_id_rev.lastIndexOf(':'); doc._id = doc._doc_id_rev.substring(0, idx - 1); doc._rev = doc._doc_id_rev.substring(idx + 1); delete doc._doc_id_rev; return doc; }
[ "function decodeDoc(doc) {\n\t if (!doc) {\n\t return doc;\n\t }\n\t var idx = doc._doc_id_rev.lastIndexOf(':');\n\t doc._id = doc._doc_id_rev.substring(0, idx - 1);\n\t doc._rev = doc._doc_id_rev.substring(idx + 1);\n\t delete doc._doc_id_rev;\n\t return doc;\n\t}", "function decodeDoc(doc) {\n if (!d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates the character selection row with all characters.
function moveAllToSelect() { for (var index in characters) { var character = characters[index]; var characterColumn = createCharacterColumn(character, 3); $("#selectRow").append(characterColumn); } }
[ "function recreateCharSelection()\n{\n\t// Remove all realms - recreate from scratch\n\t$('#charSelectFormb').html(\"\");\n\t\n\tfor(var i = 1; i <= numRealms; i++) {\n\t\taddRealmAuto(i);\n\t}\n\t\n}", "blankCharArray() {\n // In each row, the modified field reports whether the line needs to be\n /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send highscores from database to client
function sendHighScores(req,res){ }
[ "async function recordHighScore() {\n await fetch('/scores', {\n method: 'POST',\n headers: { authorization: idToken, 'Content-Type': 'application/json' },\n body: JSON.stringify({ score: CURRENT_SCORE }),\n });\n }", "function sendHighScore(hits) {\n socket.em...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sends headlines for the news
function sendNewsHeadlines(sender_psid){ NewsDataUtils.getNewsHeadlines().then(headlines => { let tiles = headlines.map((headline) => { return { "title": headline.title, "image_url":headline.imageURL, "buttons":[ { "type":"web_url", "url": headline.u...
[ "function getNewsAsBody() {\n const url = 'http://newsapi.org/v2/top-headlines?' +\n `category=${userCategory}&` +\n 'country=us&' +\n `apiKey=${apiKey}`;\n fetch(url)\n .then(response => response.json())\n .then(recieveNews)\n console.log(\"-> Body has got the news !\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify listeners that a comment's issue status changed. This will trigger the ``issueStatusUpdated`` event. Args: comment (RB.BaseComment): The comment instance that changed. rsp (object): The API response object from saving the comment. oldIssueStatus (string): The old issue status.
_notifyIssueStatusChanged(comment, rsp, oldIssueStatus) { const CommentTypes = RB.CommentIssueManager.CommentTypes; let rspComment; let commentType; if (rsp.diff_comment) { rspComment = rsp.diff_comment; commentType = CommentTypes.DIFF; } else if (rsp.gen...
[ "_onIssueStatusUpdated(comment, oldIssueStatus, timestamp, commentType) {\n const options = this.options;\n\n if (comment.id === options.commentID &&\n commentType === options.commentType) {\n this._showStatus(comment.get('issueStatus'));\n }\n }", "_onIssueStatusChan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the associate Producer is paused.
get producerPaused() { return __classPrivateFieldGet(this, _producerPaused); }
[ "isPaused() {\n return this._isPaused;\n }", "isPaused() {\n const listeners = this.listeners;\n for (const listener of listeners) {\n if (listener.isPaused)\n return true;\n }\n return false;\n }", "function isPaused()\n{\n return paused;\n}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renderBook Function renders a new book card in the DOM
function renderBook(book) { // Create book card and internal elements in the DOM const bookListItem = document.createElement("div"); bookListItem.classList.add("book-card"); const bookTitle = document.createElement("h2"); const bookAuthor = document.createElement("h3"); const bookPages = document.createEle...
[ "function renderBook(book) {\n // Grab book box where books are displayed\n let bookBox = document.querySelector('.bookBox')\n let bookCard = makeBookCard(book)\n bookBox.appendChild(bookCard)\n}", "function renderBook(book) {\n // Create the div with a class of card that will contain the information of this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a valid key from a string
generateKey(str) { return utils.slug(String(str), this.separator); }
[ "function firebaseSafeKey (str) {\n if (!str || (typeof str !== 'string' && typeof str !== 'number')) return false;\n\n return ('' + str).replace(/ |\\/|\\\\|\\.|\\$|\\&|\\[|\\]|\\*|\\#|\\\"|\\'|\\`|\\,|\\{|\\}/g, '_').replace(/_{2,}/g, '_');\n}", "function make_key() {\n return Math.random().toStrin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save current tab as a source.
function saveAsSource(tab, profileId, sourceUrl) { chrome.tabs.sendMessage(tab.id, { action: 'getLinks' }, getLinksCB); idb.updateProfileScrapeDate({ sourceUrl, }); }
[ "function ViewSourceSavePage() {\n internalSave(\n gBrowser.currentURI.spec.replace(/^view-source:/i, \"\"),\n null,\n null,\n null,\n null,\n null,\n \"SaveLinkTitle\",\n null,\n null,\n gBrowser.contentDocument,\n null,\n gBrowser.webNavigation.QueryInterface(Ci.nsIWebPageDesc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Updates an existing ActivityLogAlertResource's tags. To update other fields use the CreateOrUpdate method.
async function patchAnActivityLogAlert() { const subscriptionId = "187f412d-1758-44d9-b052-169e2564721d"; const resourceGroupName = "Default-ActivityLogAlerts"; const activityLogAlertName = "SampleActivityLogAlert"; const activityLogAlertPatch = { enabled: false, tags: { key1: "value1", key2: "value2" }...
[ "async function updateFlowLogTags() {\n const credential = new DefaultAzureCredential();\n const client = createNetworkManagementClient(credential);\n const subscriptionId = \"\";\n const resourceGroupName = \"rg1\";\n const networkWatcherName = \"nw\";\n const flowLogName = \"fl\";\n const options = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Input(s): eventObj event object taken from the events array within the flashTeamsJSON object Output(s): an object that contains all info necessary to render an 'editable' popover
function editablePopoverObj(eventObj) { var totalMinutes = eventObj["duration"]; var groupNum = eventObj["id"]; var title = eventObj["title"]; var startHr = eventObj["startHr"]; var startMin = eventObj["startMin"]; var notes = eventObj["notes"]; var inputs = eventObj["inputs"]; if(!input...
[ "function readOnlyPopoverObj(ev) {\n var groupNum = ev.id;\n var hrs = Math.floor(ev.duration/60);\n var mins = ev.duration % 60;\n\n var content = '<b>Event Start:</b><br>'\n + ev.startHr + ':'\n + ev.startMin.toFixed(0) + '<br>'\n +'<b>Total Runtime: </b><br>' \n + hrs + ' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables a mutation operator
function disableOperator(ID) { //Disable all operators if(!ID){ var success = operator.disableAll(); if (success) console.log("All mutation operators disabled."); else console.log("Error"); }else{ //Disable operator ID var success = operator.disable(ID); if (success) consol...
[ "function setNoOp(op) {\n delete op.op;\n delete op.create;\n delete op.del;\n}", "function setNoOp(op) {\ndelete op.op;\ndelete op.create;\ndelete op.del;\n}", "function removeOperators(){\n let copyOperators = operators.slice();\n copyOperators.pop();\n setOperator(copyOperators);\n }", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As indexes are shifted by 1 when starting from the right, clamping has to go down to 1 to accommodate the full range of the sliced array.
function clampStartIndexFromRight(startIndex, len) { return min(len, max(-1, startIndex)); }
[ "function filterRange1(arr,min,max) {\n for(ind=0; ind <= (max-min); ind++) {\n arr[ind] = arr[min+ind]\n }\n arr.length = (max-min+1)\n return arr\n}", "function clampStartIndexFromRight(startIndex, len) {\n return min(len, max(-1, startIndex));\n }", "shift(arr) {\n let res = arr.sli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all arguments as an object from current page
function getCurrentPageArgs() { var oRet; var arrPages; var oCurrentPage; var oOptions; // ... oRet = null; // // get stack array of current pages // arrPages = getCurrentPages(); if ( wlib.isArray( arrPages ) && arrPages.length > 0 ) { // // get the object of current page // oCurrentPage = arrPag...
[ "get args()\n {\n return new helpers.args(this.url); \n }", "function getViewargs() {\n\t\tconsole.log(\"getViewargs(): search string is: \" + window.location.search);\n\t\tvar argstr = decodeURIComponent(window.location.search.substring(\"?args=\".length));\n\t\tvar args = JSON.parse(argstr);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
received single encrypted message with only our part left
receiveEncrypted(ourEncryptedMessage) { const otherPublicKey = this.state.users.filter( function(user) { return user._id === ourEncryptedMessage.originalSender; })[0].publicKey; const decryptedMessageText = this.decrypt(ourEncryptedMessage.text, otherPublicKey); const newMessage = { ...our...
[ "function decrypt(enc_msg) {\n if (client_dh_secret) {\n let encryted_aes_msg = enc_msg.slice(3, enc_msg.byteLength);\n App.webSocketSend(\"(client) Received ciphertext:\" + encryted_aes_msg.toString());\n try {\n let decrypted_aes_msg = Buffer.from(aesWrapper.decrypt(client_dh_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Word Object from line
function Word(line, idx){ var word = {}; // ignore '\t' before '@' var at = line.indexOf('@'); word.index = idx; word.key = line.substring(0, at - 1); word.descriptions = ''; var last = at; var current = line.indexOf('\\n', last); while(current > -1) { word.descriptions += HTMLFormat...
[ "function create (hljsLine) {\n return new Line(hljsLine)\n}", "function WordIndex(word, lineNum, line) {\n this.word = word;\n this.lineNums = [lineNum];\n this.lines = [line];\n}", "function getLineWords(line) {\n\n\t// Compress spaces\n\tvar line = this.text.replace(/\\s+/g, ' ');\n\t\n\tvar cuts = line....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if decimal_set1 is superset of decimal_set2
function is_a_superset(decimal_set1, decimal_set2) { var rc = find_subset_relationship(decimal_set1, decimal_set2); if (rc == 2) { return true; } return false; }
[ "function is_a_subset(decimal_set1, decimal_set2) {\n var rc = find_subset_relationship(decimal_set1, decimal_set2);\n if (rc == 1) {\n\treturn true;\n }\n return false;\n}", "function find_subset_relationship(decimal_set1, decimal_set2) {\n if ((decimal_set1 & decimal_set2) == decimal_set1) {\n\tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
64bit unsigned addition Sets v[a,a+1] += v[b,b+1] v should be a Uint32Array
function ADD64AA (v, a, b) { const o0 = v[a] + v[b] let o1 = v[a + 1] + v[b + 1] if (o0 >= 0x100000000) { o1++ } v[a] = o0 v[a + 1] = o1 }
[ "function ADD64AA(v, a, b) {\n var o0 = v[a] + v[b];\n var o1 = v[a + 1] + v[b + 1];\n\n if (o0 >= 0x100000000) {\n o1++;\n }\n\n v[a] = o0;\n v[a + 1] = o1;\n} // 64-bit unsigned addition", "function ADD64AA (v, a, b) {\n var o0 = v[a] + v[b]\n var o1 = v[a + 1] + v[b + 1]\n if (o0 >= 0x100000000) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add income to ui and array
function addIncome(){ var name = document.querySelector('.add-name'); var value = document.querySelector('.add-value'); // check validity if(name.checkValidity() && value.checkValidity()){ // update ui var name = document.querySelector('.add-name').value; ...
[ "function addExpenseToTotal()\n {\n //creating an object of expenseItem\n const expenseItem={} ;\n\n //read input value from inputAmount\n const textAmount = element1.value ;\n\n //read Description from inputDescEl\n const textDesc = inputDesc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
___ __ _____ _____ ____ _____ _____ || \/ | ||== ||_// (( ___ ||== ||_// || | ||___ || \\ \\_|| ||___ || \\ / arrFrom data From with same fields order arrTo data To numIdColTo number of volumns of user with Ids Note! We need user column with Id because user data and source data in this step are merged by fields order =...
function merge2dArrays(arrFrom, arrTo, numIdColTo, fieldTypes, columns) { // get the row of IDs from var idsFrom = {}; for (var i = 0, l = arrFrom.length; i < l; i++) { idsFrom[arrFrom[i][numIdColTo - 1]] = i; } var result = []; // loop arrTo row by row var id = -1; var row = []; va...
[ "function dataInput_getVarFieldsJson() {\n var dataJSON = '[';\n var jsonToSent = [];\n var spread = getSpreadJS();\n var writeNan = getWriteNan();\n var firstRowIdx = dataInput_firstRowIndex();\n var fieldsNum = $('#inputs-fields').children().length;\n for (var i = 0; i < fieldsNum; i++) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EditEntry funciton will remove the entry from the list area, add the entry back to the input area, and update the total values again
function editEntry(entry){ // making entry the variable that represents the entry id which includes amount, name,type let ENTRY = ENTRY_LIST[entry.id]; // if the entry type is an input, we are going to update the item name and cost in the input section if (ENTRY.type == "inputs"){ itemTitle.valu...
[ "function deleteEntry(entry){\n ENTRY_LIST.splice(entry.id, 1);\n// after we call the deleteEntry funciton we need to update the Total values again\n updateUI();\n }", "function clearEntry() {\n display = entry = 0;\n newEntry = true;\n }", "function reSetEditEntryDlg() {\r\n\tDWRUtil.setV...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pass in props for what color it's supposed to change type: "background","backgroundring","progresscolor","textcolor"
changeColor(colors){ const type = this.props.navigation.getParam('type', 'background'); switch(type){ case "background": this.props.changeBackground(colors); break; case "backgroundringcolor": this.props.changeBackgroundRi...
[ "renderColor() {\r\n if ((this.state.extType) === 'Normal') {\r\n return 'green';\r\n } else if ((this.state.extType) === 'Terminated') {\r\n return 'orange';\r\n } else if ((this.state.extType) === 'Absconding') {\r\n return 'red';\r\n } else {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by AgtypeParserNullValue.
enterNullValue(ctx) { }
[ "_nullTerminal() {\n if (this._token === null || this._token.type !== 'null')\n throw new ConditionError(this._errorString('null'));\n\n this._addNode();\n this._advance();\n }", "function EO_AST() {\n\tthis.root = null;\n\t\n\treturn this;\n}", "function parse() {\n parseTree = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a song to the queue
function addToQueue(msg, song) { if (!queues[msg.guild.id]) { queues[msg.guild.id] = {"songs": [], "queuemessageid": null}; } queues[msg.guild.id].songs.push(song); msg.channel.sendMessage(getQueueMessage(msg)) .catch(e => { console.log(e); }); if (queues[msg.guild.id].songs.length == 1) { playNextIn...
[ "addsongtoqueue(songLink){\n this.queue.push(songLink)\n }", "AddToQueue(song, msg) {\n if(this.queue.length < 1) {\n this.queue.push(song);\n this.Play(msg);\n }\n else {\n msg.channel.send(\"`\" + song.name + \"` **added to queue.**\");\n this.queue.push(song);\n }\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
called every bundle of ticks > input the 'iteration' ie the current bundle of ticks ie the 'day' > adds normal wear and wear and tear > add information to shipHistory
updateShip(iteration){ //----[ adds normal wear and tear ]----// if (this.inFlight && (this.tick % this.integrity) == 0){ this.parts["engine"] -= 1; this.parts["shields"] -= 1; if (this.parts["shields"] <= 0){ this.parts["hull"] -= 1; } this.parts["thrusters"] -= 1; t...
[ "function increaseTickAndAnimate () {\n // Reset data for new tick\n frontarcRoute = []\n backarcRoute = []\n currentdrones = []\n\n // Set position at new tick\n droneInfoFeat.forEach((drone) => {\n setPosition(drone.properties)\n })\n\n // Update data for travelled route\n map.getS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
name : fnRemoveFabric description : remove fabric item author : minyeong kim
function fnRemoveFabric(e) { //remove option item e.parentNode.remove(); }
[ "function Remove_click(guid){\r\n\tvar guidIndexHash = getGuidIndexHash();\r\n\timageUploader1.UploadFileRemove(guidIndexHash[guid]);\r\n}", "function fnAddFabric(){\n var fabricList = document.getElementsByClassName('fabric-list')[0];\n var fabricItem = '<div class=\"fabric-item\">' +\n ' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new MailgunUpdateAllOf.
constructor() { MailgunUpdateAllOf.initialize(this); }
[ "function PullrequestAllOf() {\n _classCallCheck(this, PullrequestAllOf);\n\n PullrequestAllOf.initialize(this);\n }", "function MailgunUpdate() {\n _classCallCheck(this, MailgunUpdate);\n\n _IntegrationUpdateBase[\"default\"].initialize(this);\n\n _MailgunUpdateAllOf[\"default\"].initialize(this)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates new Game object from given seed (defaults to empty grid)
constructor(seed = [ [ 0 ] ]) { this.width = seed[0].length; this.height = seed.length; this.origin = { x: 0, y: 0 }; this.cells = { 0: {} }; // add all live cells to Game for (let y = 0; y < seed.length; y++) { for (let x = 0; x < seed[y].length; x++) { if (!seed[y][x]) continue;...
[ "static initBoard({cells: seedCells, width: boardWidth, height: boardHeight, center_seed: centerSeed = 1}){\n\n // create a blank board first\n let board = Board.createBlankBoard(boardWidth, boardHeight);\n\n // assume the seed is orthogonal\n const seedWidth = seedCells.length;\n const seedHeight = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function called netSalary with Salary as the parameter has been defined
function netSalary(salary) { let netSalary = salary - deductions(5000000); console.log(netSalary); }
[ "function SalaryLogic() {}", "function SalaryCost() {\n let expensesAmount = SalaryExpenses();\n let insuranceAmount = InsuranceExpenses();\n let contributionsAmount = ContributionsExpenses();\n //optellen van de kosten = expense + insurance + contributions\n return expensesAmount + insuranceAmount...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resume the parsing from where it stopped. If the parser has been stopped by a call to endScript(), this function reset its states so it can resume properly
resume() { if(this._endScript) { this._resetStates(); } else { this._wait = false; } this._next(); }
[ "resume() {\n this.parser.resume();\n }", "function resumeLexicalEnvironment() {\n ts.Debug.assert(state > 0 /* Uninitialized */, \"Cannot modify the lexical environment during initialization.\");\n ts.Debug.assert(state < 2 /* Completed */, \"Cannot modify the lexical environmen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
props and class manipulation
get props() { return this._props }
[ "static get props () {\n return assign({}, super.props, this[$ctorProps]);\n }", "static get props () {\n return assign({}, super.props, this[ctorProps]);\n }", "constructor(props) { //Le pasamos el array de los props sin descomponer\n super(props); //Hademos lo mismo aquí\n //Esto nos per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[boolean] isOnMainlineLayer([SVGElement] obj) Recursive function to determine if SVGElement is on the mainline layer. Searches parents until either the mainline track layer object is found or the svg document itself is found.
function isOnMainlineLayer(obj) { var mainlineTrackLayer = svgDocument.getElementById("mainlineTrackLayer"); if((mainlineTrackLayer != null) && (obj == mainlineTrackLayer)) return true; if((obj == svgDocument) || (obj == null)) return false; return isOnMainlineLayer(obj.parentNode); }
[ "function isMainLayer(_layer){\n\tfor each(var _frame in filterKeyFrames(_layer.frames)){\n\t\tif(isMainFrame(_frame)){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function isMainlineTurnout(obj)\n{\n\treturn isOnMainlineLayer(obj);\n}", "get isTopLayer()\n {\n return this.parent.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map orderlines to orderlineitems with fields by id
function mapOrderlinesToItemsWithFields(orderlines) { return orderlines.reduce((oliMap, orderline) => { orderline.orderlineitems.forEach(({ orderlinefields, ...orderlineitem }) => { // Add orderlineitem to the map oliMap[String(orderlineitem.id)] = { ...orderlineitem, item: orderline.item, orderlin...
[ "function createLineitem(orderId) {\n\tvar data = JSON.stringify({product_number:1, order_number: orderId, qty_ordered: 1});\n\tmakeCall(\"POST\", \"OneCustomer.Orders.Lineitems/\", data, null, true, function(response) {\n\t\trefreshAfterUpdate(response);\n\t});\n}", "createLineItems(lineItems) {\n let lLi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ordena os vetores sempre nessa ordem v1 < v2 < v3
function orderVertices(v1, v2, v3){ if(v1.y > v2.y){ var tmp = v2; v2 = v1; v1 = tmp; } if(v2.y > v3.y){ var tmp = v2; v2 = v3; v3 = tmp; } if(v1.y > v2.y){ var tmp = v2; v2 = v1; v1 = tmp; } return [v1, v2, v3]; }
[ "function orderVertices(v1, v2, v3){\n\tif(v1.y > v2.y){\n\t\tvar tmp = v2;\n\t\tv2 = v1;\n\t\tv1 = tmp;\n\t}\n\t\n\tif(v2.y > v3.y){\n\t\tvar tmp = v2;\n\t\tv2 = v3;\n\t\tv3 = tmp;\n\t}\n\t\n\tif(v1.y > v2.y){\n\t\tvar tmp = v2;\n\t\tv2 = v3;\n\t\tv3 = tmp;\n\t}\n\t\n\treturn [v1, v2, v3];\n}", "function compare...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push a search term into the observable stream.
search(term) { this.searchTerms.next(term); }
[ "search(term) {\n this.searchTerms.next(term);\n }", "function handleSearchTerm (term) {\n setTerm(term);\n }", "function toSearch(){\n\tvar query = document.getElementById('text').value;\n\tsocket.emit('toSearch', { q: query });\n}", "function emitSearch(event){ if (event.which == 13) {addSearc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do not rename the GameMode function As this is necessary for the game engine to load
function GameMode() { this.start = function() { // Called when the game starts } this.tick = function() { // Called every frame update } }
[ "function setGameMode(mode){\n gameMode = mode;\n game = newGame();\n displayAll();\n}", "function game_setGameMode(mode)\n{\n switch (mode)\n {\n case GAME_MODE_ENUM.PLAY_MODE:\n {\n if (DEBUG_MODE) console.log(\"Play mode\");\n gamecore.mode = GAME_MODE_ENUM.PL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
steps the entity using position, velocity, acceleration and drag
step() { // TODO figure out formula to apply drag this.vel = this.vel.add(this.acc).mult(1 - this.drag); this.pos = this.pos.add(this.vel); }
[ "move() {\n this.acceleration = this.directions[this.energy]; // get acceleration Vector from directions\n\n this.velocity\n .add(this.acceleration)\n .normalize() // make velocity vector a unit vector to preserve direction given by acceleration\n .multiply(this.speed); // direction of ve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a team pool from local storage
function loadTeamPool(e){ var val = $(e.target).find("option:selected").val(); var data = window.localStorage.getItem(val); $(".team-import").val(data); $(".team-import").trigger("change"); }
[ "function load_teams(){ //Load the Teams list to the teams object\n\tvar teams = require(\"./prof_walnut/teams.json\");\n}", "async loadPlayersData() {\n let allPlayers = await getNFLData();\n let myTeam = loadPlayers(\"myTeam\");\n let teamIds = {};\n myTeam.forEach(p => (teamIds[p.id] = true));\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pick a random word from the dictionary.
function pickword(dictionary) { return dictionary[Math.floor(Math.random() * (dictionary.length - 1))]; }
[ "function getRandomWord () {\n var rand = Math.floor(Math.random() * Object.keys(dict).length);\n return Object.keys(dict)[rand];\n}", "function getRandomWord() {\n const index = Math.floor(Math.random() * dictionary.length);\n return dictionary[index];\n}", "function pickWord() {\n var randomInt = M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads endpoint data, specifically what endpoints are available and what clusters are defined within those endpoints.
async function loadEndpoints() { let result = []; const { db, sessionId } = this.global; const endpoints = await queryEndpoint.selectAllEndpoints(db, sessionId); // Selection is one by one since existing API does not seem to provide // linkage between cluster and what endpoint it belongs to. // // TODO...
[ "discoverEndpoints() {\n // Get all endpoints folders\n const path = this.settings.endpointsPath;\n const endpoints = this.getPaths(path);\n this.info(`* Discovering Endpoints...(${endpoints.length} founds)`);\n\n endpoints.forEach(endpoint => {\n this.configureEndpoint(path, endpoint);\n });...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test, generate crosssection widths for a single crosssection
function testSingleCrossSection() { var f = ee.Feature(crossSections.filterBounds(geometry.buffer(200)).first()) var images = getImages(f.geometry()) print('Number of images covering cross-section: ', images.size()) f = etimateWidthForImages(images)(f) print(f) var t = ee.List(f.get('times')) var...
[ "function generateWidthForCatchment(c, index, crossSections) {\n var bounds = c.geometry()\n \n crossSections = crossSections.filterBounds(bounds)\n\n crossSections.size().evaluate(function(size) {\n print(index)\n \n if(!size) {\n print('<no cross-sections detected>')\n return\n }\n \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check colorspace of a single file
function checkFile(path, done){ //console.log('CHECKING: ' + path) im.identify(['-format', '%[colorspace]', path], function(err, clr){ if(err){ console.error(err) done(path) } done(path, clr) }) }
[ "function checkColorSpace(files){\n\n\tlet progress = 0\n\n\tprocess.on('uncaughtException', function(err){\n\t\tconsole.log('CANNOT READ: ' + files[progress])\n\t\tfound(files[progress])\n\t})\n\n\tfunction found(file, color){\n\n\t\tif(color == colorSpace){\n\t\t\tconsole.log(file.replace(path, ''))\n\t\t}\n\t\tp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register extension and also can batch add
function registerExtension(name, extension, options) { var params = name; if (!isObject(name)) { params = {}; params[name] = { extension: extension, options: options }; } each(params, function (v, name) { if (v) { var _extension = v.extension, _options = v.options; ...
[ "addExtension(extension) {\n extension.extend(this);\n }", "function registerExtension(ext, register, originalHandler) {\n const old = require.extensions[ext] || originalHandler; // tslint:disable-line\n require.extensions[ext] = function (m, filename) {\n if (register.ignored(filename))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
view prihvati model (listu podataka) i ubaci u template i vrati gotov view
view(model){ //kreiraj listu napravljenih templejta u koji su ugurani podaci const airports = model.airports.reduce((html, airport) => html + chooseAirportItem(airport), ''); const flightsHTML = model.flights.reduce((html, flight) => html + `<li>${flightsTemplate(flight)}</li>`, ''); return ...
[ "render (model) {\n return this._indexTemplate (model);\n }", "getView() {}", "function listPeopleView(targetid, people) {\n\n apply_template(targetid,\"people-list-template\", {'people': people});\n\n}", "function loadPostIt() {\n //appel de la fonction get de l'objet, necessitant une fonction de t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalidate cache of domain names for all languages if header cachecontrol:nocache is present
function invalidate_domain_cache_maybe() { if (acre.request.headers['cache-control'] && acre.request.headers['cache-control'].indexOf('no-cache') !== -1) { var keys = []; i18n.LANGS.forEach(function(lang){ keys.push("domains:"+lang.key); }); acre.cache.request.removeAll(keys); return ...
[ "static mustRevalidate() { return new CacheControl('must-revalidate'); }", "function invalidateCaches() {\n javaConfigCache = {};\n locationCache = {};\n}", "function removeCacheHeadersForVarnish() {\n headers.removeAllHeaders(\"Age\")\n headers.removeAllHeaders(\"Via\")\n headers.removeAllHeaders(\"Ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function called on each layer; sets style, popup, and event listeners
function handleLayer(layer) { // Calculate fill color using attribute // TODO: change to MURC attribute var fillColor = getColor(layer.feature.properties.MURC_Class); // Set the style of each layer layer.setStyle({ fillColor: fillColor, fillOpacity: .7, color: '#5...
[ "function clickLayer() {\r\n // Outline and open popup on click\r\n this.openPopup();\r\n this.bringToFront();\r\n this.setStyle({\r\n weight: 2,\r\n opacity: 1\r\n });\r\n}", "function initializeLayers() {\n\n showElement(setupDetailsWrapper);\n setId(rightSideWrapper, 'customi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of the specified list option.
_getOptionIndex(option) { return this.options.toArray().indexOf(option); }
[ "_getOptionIndex(option) {\n return this.options.reduce((result, current, index) => {\n if (result !== undefined) {\n return result;\n }\n return option === current ? index : undefined;\n }, undefined);\n }", "getOptionIndex(option) {\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force the blocker to hide, even when the show counter is larger than zero.
forceHide() { this.__count = 0; this.hide(); }
[ "function\nHideBlocker\n()\n{\n var blocker;\n\n blocker = document.getElementById(\"MainBlocker\");\n blocker.style.visibility = \"hidden\";\n}", "function hideBlocker(index) {\n const blocker = document.querySelector(\"#blockerLayer\");\n blocker.className = \"hidden a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The RecorderPanel is responsible for the UI of the tool.
function RecorderPanel(win, toolbox) { this.controller = new RecorderController(toolbox); this.win = win; this.doc = this.win.document; this.toolbox = toolbox; this.toggle = this.toggle.bind(this); this.onRecord = this.onRecord.bind(this); this.search = this.search.bind(this); this.initUI(); }
[ "function RecorderController(toolbox) {\n this.mm = toolbox.target.tab.linkedBrowser.messageManager;\n this.mm.loadFrameScript(FRAME_SCRIPT_URL, false);\n\n this.onRecord = this.onRecord.bind(this);\n this.mm.addMessageListener(\"PageRecorder:OnChange\", this.onRecord);\n\n this.sessions = [];\n}", "record_(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run email validator function, set checkmark state for email address if it passes
function checkEmail() { if (validateEmail(this.value) === true) { setAccepted('email-validated'); } else { setUnaccepted('email-validated'); } }
[ "function email_check() {\n email_warn(email_validate());\n final_validate();\n}", "function emailCheck(e) {\n\n\t\t// If email format returned false prevent submission\n\t\tif(!emailFormatCheck()) {\n\t\t\te.preventDefault();\n\n\t\t\t// Apply required field indicator\n\t\t\t$(\"label[for='mail']\").text(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions create a function which sends query and gets new image from unsplash.com
async function newImage(query) { let url = `https://api.unsplash.com/search/photos?query=${query}&per_page=20&orientation=landscape&client_id=${ACCESS_KEY}`; const result = await fetch(url); if(!result.ok) { throw new Error(`status: ${result.status}`); } return await result.json(); }
[ "function query_random_image_from_unsplash(){\n read_dom();\n\n fetch('https://api.unsplash.com/photos/random/?client_id=632c1d73955fbf286b85e73d858e8f82a583655b90426b2d914810912474a180&w=1920&h=1080')\n .then((response) => response.json())\n .then(function(response_json){\n inject_image_into_backgroun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add 6 more rows
add6Row() { //loop through (6 times)*(rowCount) //give ids based on row }
[ "function addRow(){\n\t\tvar gridRowId = jQuery(\"#htmlTable\").getDataIDs().length;\n\t\tfor(var i = 1; i <= 10 - gridRowId ; i++){\n\t\t\tjQuery(\"#htmlTable\").jqGrid(\"addRowData\", gridRowId+i, datarow);\n\t\t}\n\t}", "appendRows() {\n const newRows = [];\n for (let i = this.rows.length; i < this.store...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the weight of a tower with name name If a tower is carrying anything, add what it's carrying to its weight
function calcWeight(towerArray,name) { var tower = getTower(towerArray,name); //If tower is on top, just return its weight if (tower.carrying == null) { return getWeight(towerArray,name); } //return tower's weight plus the weight of the towers its carrying else { var weight = getWeight(towerArray,name); to...
[ "function getWeight(towerArray, name) {\n\tvar result = getTower(towerArray,name);\n\tif (result !== null) {\n\t\treturn result.weight;\n\t}\n\telse return 0;\n}", "function getWeight(name) {\r\n return [...name].map(v => /[a-z]/i.test(v) ? v.toUpperCase() == v ? v.charCodeAt() + 32 : v.charCodeAt() - 32 : 0)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This test verifies IME related stuff for guest. Briefly: 1) We load a guest, the guest gets initial focus and sends message back to the embedder. 2) In InputMethodTestHelper's step 1, we receive some text via cpp, the text is InputTest123, we verify we've seen the change in the guest. 3) In InputMethodTestHelper's step...
function testInputMethod() { var webview = document.createElement('webview'); g_webview = webview; document.body.appendChild(webview); var onChannelEstablished = function(webview) {}; if (!g_inputMethodTestHelper) { g_inputMethodTestHelper = new InputMethodTestHelper(); } embedder.waitForResponseFr...
[ "function testImeMacSafari3() {\n simulateMacSafari3();\n mh.fireEvent('focus', '');\n assertFalse('IME should not be triggered', mh.waitingForIme_);\n\n // ime_on\n\n // a\n mh.fireKeyEvents(goog.events.KeyCodes.WIN_IME, true, false, false);\n mh.fireKeyEvents(goog.events.KeyCodes.A, false, false, true);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for opening a note in the text editor
function openNote($item, notebook){ if($item.closest('.note-item').attr('data-notebook')){ notebook = $item.closest('.note-item').attr('data-notebook'); } let noteContent = getContent(notebook, $item.attr('data-id')); $('.notes-list-container .note-it...
[ "async function newNote() {\n console.log(\"\\nnewNote:\")\n\n var sel = Editor.selectedText\n // console.log(\"\\tCurrent cursor position: \" + sel.start + \" for \" + sel.length + \" chars\")\n // selectedText = (sel.length > 0) ? Editor.content.slice(sel.start, sel.start + sel.length) : \"\" // NB: There's a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
General Utility helpers return a random element from a collection
function getRandomElementFrom(collection) { var itemNumber = Math.floor(Math.random() * collection.length); return collection[itemNumber]; }
[ "randomItemOf(collection) {\n if (!assert.isDefined(collection, \"spellCore.randomItemOf(collection)\")) return undefined\n const key = spellCore._randomKeyOf(collection)\n if (key === undefined) return undefined\n return spellCore.getItemOf(collection, key)\n }", "function rand_element(list){ return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
saveCredentials(string setupPass) Takes given password, generates salt and hash
function saveCredentials(setupPass) { var salt = ""; for (var i=0;i<32;i++) { salt += os.randomChar(); // TODO: Figure out why the hell randomChars(int length) isnt working } var hash = os.hash(setupPass + salt) + ""; os.storage.login.put({"id":"passwordSalt","value":salt}); os.storage.login.put({"id":"passwor...
[ "generateSaltedHash(password, salt) {}", "function saltAndHashPassword(password) {\n const salt = generateRandomString(8);\n return generateHash(password, salt);\n}", "function createHashPwd(pass,callback)\n{\n\tvar salt=crypto.randomBytes(128).toString('base64');\n\tcrypto.pbkdf2(pass, salt , 100, 512, funct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note, this function can be called with two input types: 1. Object with a bunch of data; this data will be merged with the json data of contract being cloned. 2. network id; this will clone the contract and set a specific network id upon cloning.
clone(json) { json = json || {}; const temp = function TruffleContract() { this.constructor = temp; return Contract.apply(this, arguments); }; temp.prototype = Object.create(this.prototype); let network_id; // If we have a network id passed if (typeof json !== "object") { ...
[ "clone(json) {\n json = json || {};\n\n const temp = function TruffleContract() {\n this.constructor = temp;\n return Contract.apply(this, arguments);\n };\n\n temp.prototype = Object.create(this.prototype);\n\n let network_id;\n\n // If we have a network id passed\n if (typeof json !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }