query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Removes vertical seam. Recalculates pixels depending on removed pixel.
removeVerticalSeam(vseam) { this.imageData = this.context.createImageData(this.width - 1, this.height); for (var row = this.height - 1; row >= 0; row--) { var deletedCol = vseam[row]; // copy across pixels before seam col for (var col = 0; col < deletedCol; col ++) {...
[ "function pfield_erase_vborder_sprites() {\n\t\tif (visible_right_border <= visible_left_border)\n\t\t\treturn;\n\t\tvar pos = 0, len = 0;\n\t\tif (visible_left_border < native_ddf_left) {\n\t\t\tlen = res_shift_from_window(native_ddf_left - visible_left_border);\n\t\t\tpos = -len;\n\t\t}\n\t\tif (visible_right_bor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates label and inputs for each group, depending on the entered number of available groups
function GenerateDynamicInputs(element, groupElement) { var nGroups = $(groupElement).val(); var html_String = ""; for (var i=1;i<=nGroups;i++){ var total_sub = $(element).find('input[id=edit_total_sub_question_'+i+']').val(); if (total_sub == null) total_sub = 1; total_sub = parseInt(total_sub); html...
[ "function buildGroups() {\n if (gameData.targetArray[gameData.sequenceNum].groups.length <= 0) {\n return;\n }\n\n var groupHolderHTML = '<div id=\"groupHolder\"></div>';\n $('#questionHolder').append(groupHolderHTML);\n\n for (\n n = 0;\n n < gameData.targetArray[gameData.sequenceNum].groups.length;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A food item, with a current value and timer settings The lifecycle of a food is as follows: 0. Is invisible 1. Has initial count of value + (0 to 15) 2. Has visibility point of value + (0 to initial count) 3. Becomes visible when count reaches visibility 4. Starts descending when count reaches value 5. Disappears when ...
function Food(x, y) { this.x = x; this.y = y; this.value = Math.ceil(Math.random()*9); this.count = this.value + Math.floor(Math.random()*STILL_MAX); this.div = $("<div></div>"); this.div.css({ height: units(CELL*2), width: units(CELL), position: "absolute", }); placeDiv(this.div, x, y); this.div.text(...
[ "setHunger(foodDisplay) {\n let intNum = setInterval( () => {\n this.foodLevel -= 5;\n if (!this.didYouStarve()){\n foodDisplay(this.foodLevel);\n } else {\n foodDisplay(0);\n clearInterval(intNum);\n }\n }, 5000);\n }", "eat(food) {\n this.health += food.val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
partition(target) rearrange the nodes in the list so that all nodes with values less than the target value come first in the list, then all nodes with the target value, then all nodes with values greater than the target value if there are no nodes with values greater or less than the target value, or no nodes with the ...
partition(target) { var arr_less = [] var arr_greater = [] var arr_equ = [] var runner = this.head if (this.head == null && this.tail == null) { return 'empty'} while (runner != null) { if (runner.value == target){ arr_equ.push(run...
[ "partition(target) {\n var lowerHead = null;\n var lowerTail = null;\n var middleHead = null;\n var middleTail = null;\n var upperHead = null;\n var upperTail = null;\n\n var runner = this.head;\n\n while (runner != null) {\n var temp = runner;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: _fnStringToCss Purpose: Append a CSS unit (only if required) to a string Returns: 0 if match, 1 if length is different, 2 if no match Inputs: array:aArray1 first array array:aArray2 second array
function _fnStringToCss( s ) { if ( s === null ) { return "0px"; } if ( typeof s == 'number' ) { if ( s < 0 ) { return "0px"; } return s+"px"; } /* Check if the last character is not 0-9 */ var c = s.charCodeAt( s.length-1 ); if (c < 0x30 || c > 0x39) { ...
[ "function _fnStringToCss(s) {\n\t\t\tif (s === null) {\n\t\t\t\treturn \"0px\";\n\t\t\t}\n\n\t\t\tif (typeof s == 'number') {\n\t\t\t\tif (s < 0) {\n\t\t\t\t\treturn \"0px\";\n\t\t\t\t}\n\t\t\t\treturn s + \"px\";\n\t\t\t}\n\n\t\t\t/* Check if the last character is not 0-9 */\n\t\t\tvar c = s.charCodeAt(s.length - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================================================================== ==Constructor============================================================= ========================================================================== ========================================================================== ==Methods===========...
charPrint (c) { if (!c) { c = 'X'; } let i = this.width; while (i > 0) { console.log(c.repeat(this.width)); i--; } }
[ "charPrint (c) {\n if (c === undefined) {\n super.print();\n } else {\n const symbol = c;\n for (let line = 0; line < this.height; line++) {\n console.log(symbol.repeat(this.width));\n }\n }\n }", "charPrint (c) {\n if (!c) {\n this.print();\n } else {\n for (l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears all stored ninja elements
function clearAll () { ninja_config.variables = {}; ninja_config.rules = {}; ninja_config.build_statements = []; ninja_config.default_build_statements = []; ninja_config.phony_rules = {}; }
[ "clear() {\n for (const spot of this._spots) {\n this._game.dragAndDropManager.unconfigureSpot(spot);\n }\n this._spots = {};\n this._generateFunctions = {};\n }", "function clear() {\n blueprintDictionary.clear();\n hydratedBlueprints.clear();\n bpList = [];\n needsR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of titles name with the top ten titles field: imdb_score
function topTenTitles() { const newData = [...data]; newData.sort((a, b) => b.imdb_score - a.imdb_score); return newData.splice(0,9); }
[ "function getPopularity(movie) {\n return 10;\n}", "function printTopTen(array){\n var jsonData = JSON.parse(array);\n var topScores = [];\n\n for(var x in jsonData){\n\t\ttopScores.push(jsonData[x]);\n\t}\n\n//calls sort\n sort(topScores);\n\n if(topScores.length > 10){\n for(var i = 0; i < 10; i++){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add user name to DOM
function addUNameToDom(name) { const paraElement = document.createElement('p') paraElement.innerHTML = '<strong>From user: </strong>' + name return paraElement }
[ "function setUserName(name) {\n var userName = $(\".user-name\");\n userName.text(name);\n }", "function setUserName(user){\n userId = user.id;\n playerInfo.insertAdjacentHTML('beforeend',\n `\n <h3>Player: ${user.name}</h3>\n `)\n }", "function name(user) {\n Dom.span(function () {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles logic for moving the dragged card to it's new pile, as well as ensuring it's removed from it's original pile
moveItem(item) { var suit = item.suit; var value = item.value; var column; // Sets up local variables for the arrays for all the cards on the board var columns = [ this.state.col_1, this.state.col_2, this.state.col_3, this.state.co...
[ "function setCardMovable(card) {\n card.setAttribute(\"draggable\", \"true\");\n card.addEventListener(\"dragstart\", function(event) {\n event.stopImmediatePropagation()\n // Makes the correct card show when moving a card from the discard pile\n if(event.target.id === \"discard\") {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the closest global palette index we can find to the color c / Supports RRGGBBstyle, [r,g,b]style, or simply passing a global palette index.
findRGB(c){ if ((typeof c) == "number"){return c;} let rgb = []; if ((typeof c) == "string" && c.length == 7){ rgb = [parseInt(c.substr(1, 2), 16), parseInt(c.substr(3, 2), 16), parseInt(c.substr(5, 2), 16)]; } if (c instanceof Array){rgb = c;} if (!rgb.length){ console.log("Invalid ...
[ "findPalRGB(c){\n if ((typeof c) == \"number\"){return c;}\n let rgb = [];\n if ((typeof c) == \"string\" && c.length == 7){\n rgb = [parseInt(c.substr(1, 2), 16), parseInt(c.substr(3, 2), 16), parseInt(c.substr(5, 2), 16)];\n }\n if (c instanceof Array){rgb = c;}\n //Nothing to check against...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toggle hint list display
function displayHints() { hintBox.innerHTML = ''; if(hints == false){ const ulElem = document.createElement('ul'); hintBox.appendChild(ulElem); for(let i = 0; i < hintArray.length; i++){ const liElem = document.createElement('li'); liElem.textContent ...
[ "function toggleHint() {\n var x = document.getElementById(\"hint\");\n if (x.style.visibility === \"hidden\") {\n x.style.visibility = \"visible\";\n } else {\n x.style.visibility = \"hidden\";\n };\n}", "function toggleHint() {\n\n // read current values\n const hintStyle = document.getElementBy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set radius of circles drawn by drawCircle(e)
function setCircleRadius(newRadius, redrawing) { if(newRadius > 0) { circleRadius = newRadius; } if(!redrawing){ undo.push(new Array("circleradius", circleRadius)); } }
[ "function increaseRadius() {\n\t circles[circleSelectedNum].radius *=1.2;\n\t update();\n }", "function changeCircleRadius(circles, [ev, circ]) {\n const newRad = ev.currentTarget.value\n const newCircle = R.assoc('r', newRad, circ)\n const index = R.findIndex(R.propEq('id', circ.id), circles)\n return R.upda...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads content for accounts in the array
function loadContent() { var account = accounts.shift(); fields = ['account_id', 'avg_ctr', 'cat', 'channels', 'ckw', 'ctr', 'published', 'topics', 'url', 'updated_at', 'disabled'], sort = [['published', 'desc']]; var criteria = { "account_id": account }; if (account === undefined) { process.exit(1...
[ "loadAccounts() {\n let accounts = store.getData( this._accountsKey );\n if ( !Array.isArray( accounts ) || !accounts.length ) return;\n this.importAccounts( accounts, true );\n }", "function loadContent() {\n var account = accounts.shift();\n fields = ['account_id', 'avg_ctr', 'cat', 'channels', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Missing vowels (and doesn't look like acronym, and is ASCII so we can tell)
function missingVowels(str, normed) { const containsNonAscii = [...normed].some(c => c.charCodeAt() >= 128); const isAcronym = str === str.toUpperCase(); const isNth = /^\d+(?:st|nd|rd|th|)$/.test(str); if (containsNonAscii || isAcronym || isNth) { return false; } return !/[aeiouy]/i.tes...
[ "function removeVowels(str) {}", "function notStartWithVowel(str) {\r\n\t\treturn !((str[0]) === \"a\" || (str[0] === \"e\") || (str[0] === \"i\") ||\r\n\t\t\t(str[0] === \"o\") || (str[0] === \"u\"));\r\n\t}", "function noVowels (str){\n return str.replace (/[aeiou]/gi,\"\")\n}", "function absentVowel(x){...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the color associated with the given user (the color is client side, so its going to be different in every client).
function getUserColor(username) { var color = USERS_COLORS[username]; if (!color) { color = Utilities.generateRandomColor(); USERS_COLORS[username] = color; } return color; }
[ "function retrieveUserColor( userId ){\n\tvar userColor;\n\tKolabInReal.currentSquareMembers.forEach( function(element){\n\t\tconsole.log( element.kolabID, userId, element.color)\n\t\tif( element.kolabID == userId ){\n\t\t\tuserColor = element.color;\n\t\t}\n\t});\n\t\n\treturn userColor;\n}", "getUserColor(msg, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the window for searching a node for its data hostname > the hostname of the node to search
function nodeSearch(hostname){ $.getScript("static/js/spin.js", function(){ if(mode == 'night'){ var color = '#fff'; } else { color = '#000'; } if($('#nodeSearch_window').length != 0){ $('#nodeSearch_window').find('.tile-contents').empty(); } else { var new_tile = '<li...
[ "function searchNodes() {\r\n\t//get value from textbox\r\n\tvar input = document.getElementById(\"nodeNumber\").value;\r\n\t//get max # of nodes\r\n\tvar maxNodes = nodesX.length - 1;\r\n\t//if input is less than 0 or greater than maxNodes-1 then it is out of bounds\r\n\tif(input < 0 || input > maxNodes) {\r\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private methods for image display Finds anchors that belong to a gallery.
function _findGalleryItems(gallery) { // fetch or construct gallery identifier var id = gallery.attr('id'); id = id ? BOXPLUS + '-' + id : BOXPLUS; $('li', gallery).each(function () { $('a:first', this).attr('rel', id); }); return $('a[rel=' + id + ']', gallery); }
[ "function anchors(photos, options) {\n return $.map(photos.photo, function(photo) {\n var photo_anchor = $(anchor(image(photo, options.display_size), photo, options.link_to_size));\n photo_anchor.data(\"photo\", photo);\n return photo_anchor;\n });\n }", "function displayLinks() {\n $('[d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return true if player has empty houses
function checkEmptyHouses(player) { var playerhouseEmpty = false; switch (player) { case 1: playerhouseEmpty = (sum_array(houses.slice(0, 7)) === 0) ? true : false; break; case 2: playerhouseEmpty = (sum_array(houses.slice(7, 14)) === 0) ? true : false; break; } return playerhous...
[ "function checkEmpty() {\n\t\tif (blankSquares.length == 0) {\n\t\t\tgameWin();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "isGridFull() {\n if (this.player1.noOfMoves + this.player2.noOfMoves < this.maxNoOfMoves) {\n return false;\n }\n return true;\n }", "function isFu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the 'activateDivs' function. This function goes through and adds an event listener to every gameBoard cell. When clicked it runs the 'handleClickEvent' function then it runs the 'loadQuestionAndAnswers function passing through the even data. Then it sets the event target to be hidden, allowing the function to s...
function activateDivs() { divsArr.forEach(div => { div.addEventListener("click", event => { handleClickEvent(); loadQuestionAndAnswers(event); event.target.style.visibility = "hidden"; audio.play(); }); }); }
[ "function makeBoardInteractive() {\n for (var i = 0; i < boardSquares.length; i++) {\n boardSquares[i].addEventListener('click', playerTurn, false);\n }\n}", "function playerController(){\n\t\tvar count = 0;\n\t\tallboxes.map(x => {x.addEventListener('click', (e) => {\n\t\tvar box = document.getElementById(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets order books of basequote from the specified exchanges at the specified precision. discards any that fail.
async function getOrderBooks(base, quote, exchanges, precision) { const orderBookPromises = exchanges.map( (exchange) => exchange.getNormalizedOrderBook(base, quote, precision).catch( (err) => { // catch this error so one exchange failing doesnt cause problems })) const orderBooks = await Promise.all(orderBoo...
[ "function findQuoteInto(quote, book, reversedOrderBook) {\n const result = {\n total: 0,\n price: 0,\n currency: \"\",\n bestPrice: 0,\n lastPrice: 0\n };\n let orders;\n if (!reversedOrderBook) {\n orders = (quote.action === \"sell\") ? book.bids : book.asks;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates the given message given the `TranslationBundle` This is used for translating elements / blocks see `_translateAttributes` for attributes noop when called in extraction mode (returns [])
_translateMessage(el, message) { if (message && this._mode === _VisitorMode.Merge) { const nodes = this._translations.get(message); if (nodes) { return nodes; } this._reportError(el, `Translation unavailable for message id="${this._translations.dig...
[ "function serializeI18nMessageForLocalize(message) {\n const pieces = [];\n message.nodes.forEach(node => node.visit(serializerVisitor$2, pieces));\n return processMessagePieces(pieces);\n}", "function serializeI18nMessageForLocalize(message) {\n var pieces = [];\n message.nodes.forEach(function (n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isValidCharacters returns true if the string only contains characters '1' '9' and '.'
isValidCharacters(puzzleString) { const puzzleCharacterRegEx = /^[.1-9]+$/; return puzzleCharacterRegEx.test(puzzleString); }
[ "function isLegalCharacters(s)\r\n{\r\n\tvar str;\r\n\tstr = new String(s);\r\n\tvar len;\r\n\tlen = str.length;\r\n\tvar i;\r\n \r\n\tfor(i=0; i < len; ++i)\r\n\t{ //if(!((str.charAt(i) >= '0' && str.charAt(i) <= '9')))\r\n\t\tif(!((str.charAt(i) >= '!' && str.charAt(i) <= '~')))\r\n\t\t{ \r\n \t\tret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats a single prop with a prefix and indent.
function formatPropLines(prefix, indent, prop, value) { return formatLines(prefix, indent + ' ', formatProp(prop, value)); }
[ "function prop() {\n var prop = next();\n if (is('indent')) {\n next();\n while (!is('outdent')) {\n var tok = next();\n prop[2] += ' ' + tok[1].join(', ');\n }\n expect('outdent');\n }\n return prop;\n }", "prefixed(prop, prefix) {\n return prefix + prop\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear searchList so we dont have duplicates
function clearList(){ while(searchList.firstChild){ searchList.removeChild(searchList.firstChild); } }
[ "function clearSearchList() {\n\t\n\twhile (searchResults.length > 0) {\n\t\tsearchResults.pop();\n\t}\n}", "function clearList(){\r\n while(searchList.firstChild){\r\n searchList.removeChild(searchList.firstChild);\r\n }\r\n }", "function emptySearchResults()\n {\n searchL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of LocalGatewayRouteTableVpcAssociation. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LocalGatewayRouteTableVpcAssociation.__pulumiType; }
[ "function LocalGatewayRouteTableVpcAssociation() {\n _classCallCheck(this, LocalGatewayRouteTableVpcAssociation);\n\n LocalGatewayRouteTableVpcAssociation.initialize(this);\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in the maximum length that the timeline can be rendered in in pixels and the desired pixel spread. Teturns the sigma squared value for a gaussian function based on those values
function calculateSigmaSq(totalLen, spread) { var lengthSpread = totalLen/2; var sigmaSq = (lengthSpread * lengthSpread)/(-2 * Math.log(spread)); return sigmaSq; }
[ "function gaussian(x, center, height, std_dev) {\n let peak_xc = center || mouseX - width / 2;\n // let peak_xc = center || (map(mouseX-width/2, 0, width, 0, textWidth(msg))); // instead of textWidth(msg) can use bounds.w\n let curve_h = height || 600;\n let curve_sd = std_dev || 100;\n\n return curve_h * Math...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that selects all elements in a particular div (must be multi select box)
function selectAll(div) { var m = document.getElementById(div); for (var i = 0; i < m.options.length; i++) { m.options[i].selected = true; } }
[ "function selectAll(div) {\n var m = document.getElementById(div);\n for (var i = 0; i < m.options.length; i++) {\n m.options[i].selected = true;\n }\n}", "function SelectAll() {}", "function selectAllOnClick() {\n $('input').click(function () {\n $(this).select();\n });\n }", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize event helper, closes items then triggers recalculation of styles
_handleResizeH() { this._closeAll(); this._calculateStyles(); }
[ "function onWindowResize() {\n updateSizes();\n }", "handleResize() {\n if (this.isScrolling === true) {\n this.items.forEach((item, i) => {\n this.items[i].style.height = `${this.items[i].savedHeight}px`;\n });\n } else {\n this.items.forEach((item, i) => {\n this.items[i]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to display the uploaded image properties
function showProps() { document.getElementById("prop").style.display = "table"; document.getElementById("imgName").innerHTML = file.name; document.getElementById("mime").innerHTML = file.type; document.getElementById("dimensions").innerHTML = document.getElementById("img").naturalWi...
[ "function wifxAddImageInfo()\n{\n var wifx = WebImageFX.instances[0].editor;\n var name = \"uploadfilephoto\";\n wifxAddFormField(name + \"_height\", wifx.GetImageInformation(\"height\"), false);\n wifxAddFormField(name + \"_width\", wifx.GetImageInformation(\"width\"), false);\n}", "function loadImageDet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update numReplies for a parent post to this post
async updateParentPost () { const op = { $set: { numReplies: (this.parentPost.get('numReplies') || 0) + 1, modifiedAt: Date.now() } }; this.transforms.postUpdate = await new ModelSaver({ request: this.request, collection: this.data.posts, id: this.parentPost.id }).save(op); }
[ "async updateGrandParentPost () {\n\t\tif (!this.grandParentPost) { return; }\n\t\tconst op = { \n\t\t\t$set: {\n\t\t\t\tnumReplies: (this.grandParentPost.get('numReplies') || 0) + 1,\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t} \n\t\t};\n\t\tthis.transforms.grandParentPostUpdate = await new ModelSaver({\n\t\t\trequest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a damage multiplier based on the critical hit chance
function damageMultiplier(critChance, critMultiplier) { var roll = Math.random(); if (roll <= critChance) { return critMultiplier; } else { return 1; } }
[ "getCritMultiplier(critMult) {\n let critMultiplier = critMult\n\n // Chaotic Skyfire Diamond meta gem\n if (this.player.metaGemIds.includes(34220)) {\n critMultiplier *= 1.03\n }\n // Ruin\n if (this.type == 'destruction' && this.player.talents.ruin > 0) {\n // Ruin doubles the *bonus* ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show either the page or post settings based on whether user has chose to use pages/posts for the content
function updateSlideContentDisplay() { if ( $('#customize-control-slider_posts_or_pages').find('input:checked').val() == 'pages' ) { $('#customize-control-slider_recent_posts').addClass('hide'); $('#customize-control-slider_post_category').addClass('hide'); $('#customize-cont...
[ "function pageTemplateSettings() {\n\n // First show all fields, rows and sections\n $(everything).show();\n $(exampleImage).hide();\n\n // Update the current page template selection\n var pageTemplate = $(pageTemplatefield).find(\":selected\").text();\n console...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the test or if there is an AsynchronousTestHelper runs the next asynchronous method / private
function runTestOrAsync()/* : void*/ { if ( this.methodName == null || this.methodName == "" ) { flexunit.framework.Assert.fail( "No test method to run" ); } if ( this.asyncTestHelper$oHM3 != null ) { this.asyncTestHelper$oHM3....
[ "function asyncTest(testFunc, done) {\n testFunc(done);\n}", "runTests() {\n this.testCorrect()\n this.testComplete()\n }", "function async_test(func, name, properties) {\n numTests++;\n step = function(func) {\n func();\n if (!pass) {\n parent.TryItDisplay.fail();\n allDone = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Name: initChangeNickname Description: Binding Events to change nickname Author: JoonChul Kim
function initChangeNickname() { $('#txt_change_nickname').val(window.userData.nickname); $('#txt_change_nickname_back').click(function() { hidePopup(); }); // Try sign up when click "change" button or press "Enter" key. $('#txt_change_nickname_square').click(function() { tryChangeN...
[ "function setNickname(){\n // get nickname field content\n //var nickname = q( \"#nick_field\" ).value;\n var nickname = vm.currentUser.name;\n // if a nickname has been set ...\n if( nickname ){\n // initialize API client with application keys and nickname\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show form validation error message
function showFormValidationAlert() { formIsValid() ? null : alert('Please complete the order form and try again.') }
[ "function show_validation_message() {\n var desc = this.nextElementSibling;\n if(this.validity.valid) {\n\tdesc.textContent = desc.dataset.desc;\n\tdesc.dataset.color = '';\n } else {\n\tdesc.textContent = this.validationMessage;\n\tif(this.value === '')\n\t desc.textContent = printf(\n\t\t_('%1 cannot ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create pattern element in defs
pattern() { return this.defs().pattern(...arguments); }
[ "pattern(...args){return this.defs().pattern(...args)}", "function create() {\n\t\t// Create pattern\n\t\tpattern = ctx.createPattern(img, params.repeat);\n\t}", "function addPattern() {\n var patternContainers = [].slice.apply(getPatternContainers());\n patternContainers.forEach(function (conta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reemits a render event.
function onRender() { var args; var i; __debug_587( 'Received a render event. Re-emitting...' ); args = new Array( arguments.length+1 ); args[ 0 ] = 'render'; for ( i = 0; i < arguments.length; i++ ) { args[ i+1 ] = arguments[ i ]; } self.emit.apply( self, args ); }
[ "function onRender() {\n\t\tvar args;\n\t\tvar i;\n\t\t__debug_1990( 'Received a render event. Re-emitting...' );\n\t\targs = new Array( arguments.length+1 );\n\t\targs[ 0 ] = 'render';\n\t\tfor ( i = 0; i < arguments.length; i++ ) {\n\t\t\targs[ i+1 ] = arguments[ i ];\n\t\t}\n\t\tself.emit.apply( self, args );\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is used to limit someone holding down a hotkey and spamming the system with inputs.
function processingHotkey() { canAcceptNewInput = false; }
[ "function pingSpikeOnKey() {\r\n if (!GetVal(\"ping_spike\")) return;\r\n UI.SetValue(\"Misc\", \"GENERAL\", \"Extended backtracking\", UI.IsHotkeyActive(\"Script items\", \"Ping spike\"));\r\n}", "function powerUpKeyPressed(key){\n if (key === 'y') {\n shieldActivated();\n return true;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the information of the room which id is given in the url
async function updateRoom(req, res, next) { try { const room = await models.room.findById(req.params.roomId); room.capacity = req.body.capacity; room.photoPath = req.body.photoPath; room.purpose = req.body.purpose; room.restricted = req.body.restricted; await room.save(); res.send(room); ...
[ "function updateRoom() {\n const url = getRoute(\"/rooms/\" + roomNumber);\n\n var roomData = {\n roomNumber: parseInt(document.getElementById(\"roomNumberSelector\").value),\n roomTypeId: getRoomTypeId('room')\n }\n updateItem(url, roomData);\n}", "updateRoomInfo() {\n const state = store.getSta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CDATA section bracket state
[CDATA_SECTION_BRACKET_STATE](cp) { if (cp === $.RIGHT_SQUARE_BRACKET) { this.state = CDATA_SECTION_END_STATE; } else { this._emitChars(']'); this._reconsumeInState(CDATA_SECTION_STATE); } }
[ "_stateCdataSectionBracket(cp) {\n if (cp === unicode_js_1.CODE_POINTS.RIGHT_SQUARE_BRACKET) {\n this.state = State.CDATA_SECTION_END;\n }\n else {\n this._emitChars(']');\n this.state = State.CDATA_SECTION;\n this._stateCdataSection(cp);\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a random row containing y position and row number
function getRandomRow() { var rows = [[58,1],[140,2],[224,3]]; var row = Math.floor(Math.random()*3); //code snippet from: http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range return rows[row]; }
[ "function randomRow(){\n return (Math.floor(Math.random() * 4) + 1);\n}", "function generateRandomRowNumber() {\n let currentRow = Math.floor(Math.random() * 3) + 1;\n let currentRowTotalEnemies = dataLayer[totalEnemiesRowKeyPrefix + currentRow];\n\n while(currentRowTotalEnemies >= maxEnemiesPerRow) {\n cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function view_element show the element given as parameter (id) setting property 'display' to 'block'
function view_element(id){ // Gettting id element var el = document.getElementById(id); //el variable defintion el.style.visibility = "visible"; //set el's visibility attribute to visible }
[ "function show_element(id){\n // Gettting id element\n var el = document.getElementById(id); //el variable defintion\n el.style.display = \"block\"; //set el's display attribute to block\n}", "function showElement(elementId)\n{\n var element = document.getElementById(elementId);\n if (element) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
24. Count letters in string and return most common characters
function getWordsNums(str) { const lettersCount = {} str.split('').forEach(letter => { if (lettersCount[letter]) { lettersCount[letter] += 1 } else { lettersCount[letter] = 1 } }) const maxNum = Math.max.apply(null, Object.values(lettersCount)) let mostCommonLetters = []; for (let le...
[ "function mostFrequentLetter(string){\n\n}", "function mostFrequentLetter(string) {\n // P A R T 1\n let str = string.split(\"\");\n let charCount = {};\n\n str.forEach(char => {\n\t if (charCount[char] === undefined) {\n\t\t charCount[char] = 1;\n\t } else {\n\t\t charCount[char]++\n\t }\n });\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the list of teachers that are currently in the dataset and put them into a datalist that can be used to fill the teachername field.
function buildTeacherDataList() { let dataList = '<datalist id="Teachers">'; let dataListOptions = ''; let teacherList = databaseData.getTeachers(); for (let name of teacherList) { dataListOptions += "<option value='" + name + "'>"; } dataList += dataListOptions; dataList += '</datal...
[ "function buildTeacherDataList() {\n let dataList = '<datalist id=\"Teachers\">';\n let dataListOptions = '';\n let teacherList = database_data.getTeachers();\n for (let name of teacherList) {\n dataListOptions += \"<option value='\"+name+\"'>\";\n }\n dataList += dataListOptions;\n dataList += '</datalis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function to INSERT a new assignment
async function insertNewAssignment(new_assignment){ new_assignment = extractValidFields(new_assignment, AssignmentSchema); console.log(new_assignment) const [ result ] = await mysqlPool.query( 'INSERT INTO assignment SET ?', new_assignment ); return result.insertId; }
[ "function insertNewAssignment(Assignment) {\n return new Promise((resolve, reject) => {\n Assignment = extractValidFields(Assignment, AssignmentSchema);\n Assignment.id = null;\n mysqlPool.query(\n 'INSERT INTO assignments SET ?',\n Assignment,\n (err, result) => {\n if (err) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function called upon Save button of Address Popup is clicked
function fOMMoreAddress_onSaveClicked() { var elmId = _pageRef + "P"; var changes = $("#fomMaint_fomMoreAddress_"+elmId).hasChanges(true); if(changes == 'true' || changes == true) { parseNumbers(); var screen = $("#moreAddress_SCREEN_NAME_" + elmId).val(); var saveAction=''; var reloadPath=''...
[ "function continueSave() {\n notify(_L('Address successfully saved.'));\n $.customer_address.fireEvent('route', {\n page : 'addresses'\n });\n}", "function saveAddress(address, setDefault) {\n $(\"#modal-loading\").showModal();\n let promises = [];\n promises.push(APIUtils.edi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Most general function: Performs a kway merge on a collection of volumes
function merge(volumes, stencil, merge_func) { var result = new core.DynamicVolume() , iter = core.beginMulti(volumes, stencil) , coord = iter.coord , phases = new Int32Array(iter.ptrs.length) , distances = new Float64Array(iter.ptrs.length) , retval = [ 0, 1.0 ]; w...
[ "merge(things = this.pRequired(\"merge\"), nameToSave = this.pRequired(\"merge\")){\r\n\r\n if (!this.keysExist(things))\r\n throw \"merge: some or all objects with such keys not found \";\r\n\r\n console.log(\"Mergin' things\");\r\n let result = \"\";\r\n for (let i= 0; i< t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a basic car constructor, with a an input for color
function carConstructor(color){ this.color = color; }
[ "function Car(name, make, model, color) {\r\n this.name = name;\r\n this.make = make;\r\n this.model = model;\r\n this.color = color;\r\n}", "function ToyCar(color, price, name) {\n this.color = options.color;\n this.price = options.price;\n this.name = options.name;\n}", "function Coupe(color) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the last attempt. It'll be the highest number as long as it doesn't surpass the max number of attempts.
function getLastBeforeMax() { if (scorm.maxattempt != 0 && attempts.lastAttempt.number > scorm.maxattempt) { result.number = scorm.maxattempt; result.offline = attempts.offline.indexOf(scorm.maxattempt) > -1; } else { result.number = attempts.lastA...
[ "getLastError () {\n\t\tlet lastAttempt = this.attempts[this.attempts.length - 1];\n\n\t\treturn lastAttempt.error;\n\t}", "function maxRetries() {\n let tries = process.env.HALO5_429_RETRIES;\n if (isNaN(tries)) return 3;\n return +tries;\n}", "get maxRetries() {\n return parseInt(this.options.maxRetri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abre una ventana para guardar nuestro arte en un archivo pixelart.png
function guardarPixelArt() { html2canvas($("#grilla-pixeles"), { onrendered: function (canvas) { theCanvas = canvas; canvas.toBlob(function (blob) { saveAs(blob, "pixel-art.png"); }); } }); }
[ "function guardarPixelArt() {\n var arte = [];\n $grillaPixeles.children().each(function(){\n arte.push($(this).css('background-color'));\n })\n var nombre = $(\"#input-nombre-guardar\").val();\n if (!nombre) {\n nombre = \"pixel-art\"\n }\n var resultado = {\n arte: arte\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Question 5: When button 2 is clicked, change the color of all h2's to "green"
function Button202(){ $('h2').css('color','green'); }
[ "function changeGreen() {\n $('h2').css('color', 'green');\n }", "function question5(){\n var x = document.getElementsByTagName(\"h2\");\n var i;\n for (i = 0; i < x.length; i++) {\n x[i].style.color = \"green\";\n }\t\n\n}", "function onSecondButtonClick() {\n anotheritem.style.color = \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This finds the corner of each hex
getHexCornerCoord( center, i ) { // KEY pointy or flat // flat // let angleDeg = 60 * i // pointy let angleDeg = 60 * i + 30 let angleRad = Math.PI / 180 * angleDeg let x = center.x + this.state.hexSize * Math.cos( angleRad ) let y = center.y + this.sta...
[ "function hexGetCorners(layout, hex) //where they are on the screen.\n{\n var corners = [];\n var center = hex2Screen(layout, hex);\n var hexCorner = function(layout, corner) {\n var size = layout.size;\n var ori = layout.orientaion;\n var angle = 2.0 * Math.PI * (ori.start_angle + corner) / 6;\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PLAYLIST get current playlist index
getCurrentPlaylistIndex() { let that = this; if (that._playlist) return that._playlist.getIndexForId(that.getCurrentPlaylistId()); else return undefined; }
[ "getPlaylistItemWithIndex(index) {\n let that = this;\n if (that._playlist)\n return that._playlist.getItemWithIndex(id);\n else\n return undefined;\n }", "function findCurrentIndex(){\r\n\r\n for(var i = 0; i < current_song_list.length; ++i){\r\n current_song_index = -1;\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes ZIPString, a string of 5 or 9 digits; if 9 digits, inserts separator hyphen
function reformatZIPCode (ZIPString) { if (ZIPString.length == 5) return ZIPString; else return (reformat (ZIPString, "", 5, "-", 4)); }
[ "function reformatZIPCode (ZIPString)\n{ if (ZIPString.length == 5) return ZIPString;\n else return (reformat (ZIPString, \"\", 5, \"-\", 4));\n}", "function formatZipCode(znum){\n\tif(znum.length == 9){\n\t\treturn znum.substring(0,5) + \"-\" + znum.substring(5,znum.length);\n\t}\n\treturn znum;\n}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build an OData (V2) filter function to test whether a string is a substring of the other. Evaluates to boolean.
function substringOf(p0, p1) { return filterFunction('substringof', 'boolean', p0, p1); }
[ "function substringTest(string1, string2) {\n let testingString;\n let anotherString;\n \n if (string1.length >= string2.length) {\n testingString = string2.toLowerCase();\n anotherString = string1.toLowerCase();\n } else {\n testingString = string1.toLowerCase();\n anotherString = string2.toLowerC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate whether the before and after controls should be enabled or disabled. If the header is at the beginning of the list (scroll distance is equal to 0) then disable the before button. If the header is at the end of the list (scroll distance is equal to the maximum distance we can scroll), then disable the after but...
_checkScrollingControls() { if (this.disablePagination) { this._disableScrollAfter = this._disableScrollBefore = true; } else { // Check if the pagination arrows should be activated. this._disableScrollBefore = this.scrollDistance == 0; this._disab...
[ "checkScrollingControls() {\n if (this.disablePagination) {\n this.disableScrollAfter = this.disableScrollBefore = true;\n }\n else {\n // Check if the pagination arrows should be activated.\n this.disableScrollBefore = this.scrollDistance === 0;\n th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event handler for when the payment method selector is updated. Updates the section below based on which payment method is selected.
function updatePaymentMethod() { let paymentMethod = paymentSelector.value; if(paymentMethod === 'select method') { paymentMethod = 'credit-card'; document.querySelector('#payment option[value="credit card"]').selected = true; document.querySelector('#payment option[value="select met...
[ "function onPaymentMethodSelected() {\n if (pageLoad) {\n pageLoad = false;\n return;\n }\n var optionId = $(shopAnalytics.checkout.elements.paymentMethodSelected).attr('id');\n if (!optionId) {\n return;\n }\n registerCheckoutStepEvent(shop_analytics_checkout_steps.order, $('label[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reorders signatures to match pubKeys, fills undefined otherwise
function fixMSSignatures (transaction, vin, pubKeys, signatures, prevOutScript, hashType, skipPubKey) { // maintain a local copy of unmatched signatures var unmatched = signatures.slice() var cache = {} return pubKeys.map(function (pubKey) { // skip optionally provided pubKey if (skipPubKey && bu...
[ "mapSignatureKeys() {\n const allSigners = accountManager.accounts.map(a => a.publicKey)\n if (this.signatureSchema) {\n for (let s of this.signatureSchema.getAllPotentialSigners())\n if (!allSigners.includes(s)) {\n allSigners.push(s)\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function middleElement that takes an array as an argument and returns the middle element of that array. If the array has an even number of elements, the function should return "Oops, there's no middle..."
function middleElement(arr) { if (arr.length % 2 === 0) { return "Oops there's no middle..."; } else { var middleIndex = Math.floor(arr.length/2); return arr[middleIndex]; } }
[ "function middleElement(array){\n if(array.length % 2 !==0){\n return array[(array.length-1)/2] \n } else {\n return \"Oops , there's no middle\"\n }\n}", "function middleElement(array){\n return array[parseInt((array.length -1) / 2)];\n}", "function middle (array){\n if (array.leng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Code Example 5.8 See the Sheet method getDataRange() in action. Print the range address of the used range for a sheet to the log. Generates an error if the sheet name "english_premier_league" does not exist.
function getDataRange () { var ss = SpreadsheetApp.getActiveSpreadsheet(), sheetName = 'english_premier_league', sh = ss.getSheetByName(sheetName), dataRange = sh.getDataRange(); Logger.log(dataRange.getA1Notation()); }
[ "function getDataRange() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(),\n sheetName = 'english_premier_league',\n sh = ss.getSheetByName(sheetName),\n dataRange = sh.getDataRange();\n Logger.log(dataRange.getA1Notation());\n}", "function getDefaultRange() {\n try {\n var sheet ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge two or more reports into a single one.
static merge(reports) { const valid = reports.every((report) => report.valid); const merged = {}; reports.forEach((report) => { report.results.forEach((result) => { const key = result.filePath; if (key in merged) { merged[key].messa...
[ "static merge(reports) {\n const valid = reports.every((report) => report.valid);\n const merged = {};\n reports.forEach((report) => {\n report.results.forEach((result) => {\n const key = result.filePath;\n if (key in merged) {\n merge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the function given as _listenerfunction when an event of the type _eventtype occurs
static addEventListener(_eventtype, _listenerfunction) { var e = this.getEventTypeString(_eventtype); if (this.listener[e]) window.removeEventListener(e, this.listener[e]); this.listener[e] = function (_event) { _event.preventDefault(); _listenerfunction.call(...
[ "addListener(eventType, listenerFn){\n if(eventType == null){\n this.typeListenerMap[\"GLOBAL\"].push(listenerFn);\n }else{\n var eventTypeListeners = this.typeListenerMap[eventType.typeId];\n if(!eventTypeListeners){\n eventTypeListeners = this.typeListenerMap[eventType.type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var rattata = new Pokemon("Rattata", 40, 2); var datos ="vida: " + rattata.vida+"\n"+"\nataque: "+rattata.ataque; rattata.vida = rattata.vida 13; nombrePokemon.textContent = rattata.nombre; datosPokemon.textContent=datos; imgPokemon.src=rattata.imagen;
function getPokemon() { //console.log(pokemons[selectPokemon.value]); var p=pokemons[selectPokemon.value]; var poke = new Pokemon(p.nombre, p.vida, p.ataque,p.grito); var datos ="vida: " + poke.vida+"\n"+"\nataque: "+poke.ataque; poke.vida = poke.vida - 13; nombrePoke...
[ "function inicio()\n{\n\tvar rattata = new Pokemon(\"Rattata\", 40, 2);\n\trattata.vida = rattata.vida - 13;\n\t//nombrePokemon = document.getElementById(\"nombrePokemon\");\n\tnombrePokemon.textContent = rattata.nombre;\n\tdatosPokemon.textContent = rattata.vida;\n}", "function Pokemon(nombrep,tipop,vidap,ataque...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the API to retrieve user's information from the clicked user. In addition, this function modifies the active user in the user_list (removes the .active class from the old user and add it to the current user) TRIGGER: click on user_list li a
function handleGetUser(event) { if (DEBUG) { console.log ("Triggered handleGetUser"); } event.preventDefault(); $("#user_list li").removeClass("active"); // Make the user element 'active' visually $(this).parent().addClass("active"); prepareUserDataVisualization(); var url = $(this).attr("href")...
[ "function handleGetUser(event) {\n\tif (DEBUG) {\n\t\tconsole.log (\"Triggered handleGetUser\")\n\t}\n\t//TODO 2\n\t// This event is triggered by the a.user_link element. Hence, $(this)\n\t// is the <a> that the user has pressed. $(this).parent() is the li element\n\t// containing such anchor.\n\t// Use the method ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalidate the manifest cache.
function invalidateCache( repoDir ) { ManifestCache.del( repoDir ); CommitCache.del( repoDir ); }
[ "invalidate() {\n this.cache.clear();\n }", "_fetchManifest() {\n if (this.debug) {\n this.CACHE = {}\n return\n }\n\n const manifest_path = this.getManifestPath()\n\n process.on('SIGINT', this._deleteManifest)\n process.on('beforeExit', this._deleteManifest)\n\n if (fs.exist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if a particular path contains a clamav binary
async _is_clamav_binary(scanner) { const path = this.settings[scanner].path || null; if (!path) { if (this.settings.debug_mode) console.log(`${this.debug_label}: Could not determine path for clamav binary.`); return false; } const version_cmds = { cla...
[ "function hasBinary(binaryPath) {\n return fs.existsSync(binaryPath);\n}", "function CoreBinaryExists() {\n log.info('Checking if core binary exists: ' + GetCoreBinaryPath());\n try {\n fs.accessSync(GetCoreBinaryPath());\n log.info('Core binary exists');\n return true;\n } catch (e) {\n log.info(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the form and create the folder
save() { // Check if the form is valid if (!this.isValid()) { // TODO show an error message to user for insert a folder name // TODO mark the field as invalid return; } // Create the directory this.$store.dispatch('createDirectory', { name: this.folder, ...
[ "function saveDirectory(e) {\n e.preventDefault();\n // save a reference to the button\n var btn = this;\n // save a reference to the input\n var input = this.previousSibling.previousSibling;\n\n // set the attrs on the input\n input.setAttribute('name', input.value);\n input.setAttribute('id', input.value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check taskbar icon activity every second keep check on taskbar icons
function checkTaskbarIconActive() { taskbarIcons = document.querySelectorAll(".taskbar-icon"); taskbarIcons.forEach((icon) => { icon.addEventListener("click", () => { maximize_icon(icon.classList[0]); bringPanelToFront(icon); }); }); }
[ "function checkIcon() {\r\n\t\tsetTimeout(checkIconDelayed, 10);\r\n\t}", "function _iconIsRecording() {\n if ( currentConfig.isRecording !== undefined ) {\n if ( currentConfig.isRecording === true ) {\n chrome.browserAction.setIcon( { path: 'assets/img/icons/rec/' + current + '.png', tabId: curren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete messages from local storage when necessary
async deleteMessages() { try { await AsyncStorage.removeItem('messages'); this.setState({ messages: [], }); } catch (error) { console.log(error.message); } }
[ "function deleteMessage() {\n window.localStorage.removeItem('message');\n }", "async deleteMessages() {\n try {\n await AsyncStorage.removeItem('messages');\n this.setState({\n messages: []\n })\n } catch (error) {\n console.log(error.message);\n }\n }", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
flipCard(card_index) Draait kaart om van gegeven object carddiv. Als de kaart al is omgedraaid dan draaien we de kaart weer terug. Dit doen we met een CSSclass, genaamd flipped. Deze zorgt voor het draai effect. Door de tweede div te vullen met de juiste imgtag wordt de bijbehorende afbeelding zichtbaar. We vertellen
function flipCard(card_index) { if(speelveld[card_index].classList.contains('flipped')) { // Bevat de kaart al de css class flipped? /* Ja! Dan gaan de kaart weer terugdraaien door de css class flipped weer weg te halen */ speelveld[card_index].classList.remove('flipp...
[ "function flipCard(card) {\n //hide the card face initially so that it reveals itself when flipped, flip card with transition\n document.getElementById(card.code).childNodes[0].style.visibility = 'hidden';\n $('#' + card.code + ' img').transition({\n animation: 'horizontal flip',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method gets the CSRF token to use for the internal requests.
_getCSRFToken() { let that = this; return that._request('GET', that._getUrl('simplecsrf/token.json'), {}, that.localHeaders) .then(function (res) { console.log("CSRF",res.body); that.csrf = res.body.token; }); }
[ "csrfToken() {\n if (!this.isSafe() && !this.isCrossOrigin()) {\n return up.protocol.csrfToken();\n }\n }", "csrfToken() {\n if (!this.isSafe() && !this.isCrossOrigin()) {\n return up.protocol.csrfToken()\n }\n }", "function getCsrfToken() {\n var params_2 = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if we need to compute the display states of the cues. This could be the case if a cue's state has been changed since the last computation or if it has not been computed yet.
function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them.
[ "function shouldCompute(cues){for(var i=0;i<cues.length;i++){if(cues[i].hasBeenReset||!cues[i].displayState){return true;}}return false;}// We don't need to recompute the cues' display states. Just reuse them.", "function shouldCompute(cues) {\n for (var i = 0; i < cues.length; i++) {\n if (cues[i].ha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to pull the product url from the api data based on variant id
function getProductUrlForVariantId(id, apiData) { const currentItem = apiData.find(o => o.number == id); if (currentItem) { const url = currentItem.attributes.url; return url; } return ""; }
[ "function getImageUrlForVariantId(id, apiData) {\r\n const currentItem = apiData.find(o => o.number == id);\r\n let url;\r\n if (currentItem) {\r\n const imageWithCheckoutTag = currentItem.images.find(function (image) {\r\n return image.tags.includes(\"checkout\");\r\n });\r\n\r\n if (imageWithChec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called whenever a layoutnode is created/reused. Initializes the node with the `insertSpec` if it has been defined and enabled locking of the x/y translation so that the x/y position of the renderable is immediately updated when the user scrolls the view.
function _initLayoutNode(node, spec) { if (!spec && this.options.flowOptions.insertSpec) { node.setSpec(this.options.flowOptions.insertSpec); } }
[ "function _initLayoutNode(node, spec) {\n\t if (!spec && this.options.insertSpec) {\n\t node.setSpec(this.options.insertSpec);\n\t }\n\t }", "function _initLayoutNode(node, spec) {\n\t /*if (node.setOptions) {\n\t node.setOptions({\n\t spring: this.opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API test for 'GetServerCipher', Get cipher for SSL
function Test_GetServerCipher() { return __awaiter(this, void 0, void 0, function () { var out_rpc_str; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("Begin: Test_GetServerCipher"); return [4 /*yie...
[ "getCiphers() {\n return fetch(`${URL}/cipher`, {\n 'method': 'GET',\n 'headers': {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${tokenService.getToken()}`\n }\n })\n .then(res => {\n if (res....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify if user id in route params is same as logged in user
verifyUserIdParam(userId) { if (this._userService.loggedInUserId) { if (userId === this._userService.loggedInUserId) { return true; } else { this._router.navigate(['/Profile', this._userService.loggedInUserId]); return false; ...
[ "async checkUserParams(req, res, next) {\n let user = await User.findOne({ where: { userID: req.params.id } });\n if (user.userID === req.user.userID) {\n next();\n } else {\n res.status(401).json({ msg: \"Unauthorized User\" });\n }\n }", "function isSameUser(req, res, next) {\n if (req.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reformat the date string retrieved when grabbing campaign data It's necessary as Firefox doesn't work well with Date.parse when it's ''' instead of '/'
function reformatDate(dateString) { if (dateString != null) { // Using regex to look for all chars that are '-' and replace them with '/' dateString = dateString.replace(/\-/g, "/"); return dateString; } }
[ "function getDate() {\n var date = queryByOrpha(baseUrl, \"EN\", 558)\n .then((date) => {\n date = date.Date.split(\" \")[0].replaceAll(\"-\", \" \");\n// console.log(date);\n $(\"#date\").text(\"Data extraction: \" + date);\n });\n}", "function getFormattedDateString(dateString)\n{\n //variables t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all trace headers that are currently on the top scope.
function traceHeaders() { var scope = this.getScope(); if (scope) { var span = scope.getSpan(); if (span) { return { 'sentry-trace': span.toTraceparent(), }; } } return {}; }
[ "function traceHeaders() {\n\t const scope = this.getScope();\n\t if (scope) {\n\t const span = scope.getSpan();\n\t if (span) {\n\t return {\n\t 'sentry-trace': span.toTraceparent(),\n\t };\n\t }\n\t }\n\t return {};\n\t}", "function traceHeaders() {\n var scope = this.getScope();\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets all App model data / markup
resetApp() { this.dataOrg = []; this.dataState = []; this.filter.setData([]); this.results.render([]); this.assignFiltersControl([]); }
[ "reset() {\n for (let i = 0; i < this._models.length; ++i) {\n let model = this._models.data[i];\n model._viewID = -1;\n }\n }", "@action\n reset(data = []) {\n this.clearModels();\n this.setModels(data);\n }", "function resetAllContent() {\n $('#models').text('');\n $('#y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method for create quiz post
createQuiz(body) { this.setMethod('POST'); this.setBody(body); this.setAuth(); return this.getApiResult(`${Config.QUIZ_API}/new`); }
[ "function createQuiz() {\n var quizname = document.getElementById(\"quiz-name-field\").value;\n quiz = new Quiz(quizname);\n displayAddQuestionForm();\n}", "function createQuiz(req, res) {\n var quiz = Quiz.build(req.body.quiz);\n quiz.save()\n .success(function() {\n req.flash('success', 'Le quiz « ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check is the item exists in the list
function isListHasItem(list, item) { if (list.length === 0 || list.indexOf(item) === -1) { return false; } return true; }
[ "function contains(item, list, cb) {\n \n}", "isthereItem(item) {\r\n return this.items.indexOf(item) >= 0;\r\n }", "contains(item) {\n return this.items.indexOf(item) >= 0;\n }", "checkIfItemExists(item) {\n if (this.inventory.indexOf(item) === -1) {\n console.log(\"Thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::IoTEvents::DetectorModel.IotEvents` resource
function cfnDetectorModelIotEventsPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnDetectorModel_IotEventsPropertyValidator(properties).assertSuccess(); return { InputName: cdk.stringToCloudFormation(properties.inputName), Payload:...
[ "function cfnAlarmModelIotEventsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_IotEventsPropertyValidator(properties).assertSuccess();\n return {\n InputName: cdk.stringToCloudFormation(properties.inputName),\n Pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for channel without release get next (less risk) channel with a release
function getTrackingChannel(releasedChannels, track, risk, arch) { let tracking = null; // if there is no revision for this arch in given channel (track/risk) if ( !( releasedChannels[`${track}/${risk}`] && releasedChannels[`${track}/${risk}`][arch] ) ) { // find the next channel that ha...
[ "getFirstOpenChannel() {\n let tempCount = 0;\n\n if (this.myPublishClient > -1) {\n return this.myPublishClient;\n }\n\n for (var i = 0; i < this.numClients; i++) {\n tempCount = this.clients[i]._users.length;\n //console.log(\"### CHECKING CHANNEL \" + this.clients[i]._channelName + \",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle pile mouse out events.
mouseOutPileHandler () { fgmState.hoveredPile = undefined; if (fgmState.previousHoveredPile) { const zoomed = this.pilesZoomed[fgmState.previousHoveredPile.id]; fgmState.previousHoveredPile.elevateTo(zoomed ? Z_HIGHLIGHT : undefined); fgmState.previousHoveredPile.previewMatrix(); fgmSta...
[ "handleMouseOut(event) {\n this.searchCoordinatesForEvent(\"out\", event);\n }", "function on_mouse_leave() {}", "onMouseOut(e){}", "mouseOut () {\n if (this.screens[this.screenId].mouseOut) {\n this.screens[this.screenId].mouseOut(...arguments)\n }\n }", "function mouseoutOff() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select from table using given filters
async select(table, { filters = null, filterParams = [] } = {}) { try { let query = "SELECT * FROM " + table; if (filters) { query += " WHERE "; for (let filter of filters) { query += `${filter} AND `; } query = query.slice(0, query.length - 5); } qu...
[ "function filterTable() {\n \n // 8. Set the filtered data to the tableData.\n let filteredData = tableData;\n \n // 9. Loop through all of the filters and keep any data that\n // matches the filter values\n for ([key,value] of Object.entries(filters)) {\n filteredData = filteredData.filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets tripName of dragged card from event and deletes in Firebase and DOM
function deleteTrip(event) { event.preventDefault(); const tripId = event.dataTransfer.getData("text"); const tripName = $('#' + tripId).attr('data-tripname'); deleteTripFromFirebase(tripName); tripsSet.delete(tripName); $('#' + tripId).remove(); }
[ "function TaskCardDropped(event, ui)\r\n{\r\n\t// console.log(event, ui)\r\n\t/* console.log(\"dropped\");\r\n\tconsole.log(event);\r\n\tconsole.log(ui);\r\n\tconsole.log(this); */\r\n\r\n\r\n\tlet taskId = $(ui.draggable[0]).attr(\"task-id\");\r\n\tlet oTask = getTask(taskId);\r\n\r\n\t$(ui.draggable[0]).remove();...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether mappingB is after mappingA with respect to generated position.
function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generat...
[ "function generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n const lineA = mappingA.generatedLine;\n const lineB = mappingB.generatedLine;\n const columnA = mappingA.generatedColumn;\n const columnB = mappingB.generatedColumn;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize a port into a number, string or null.
function normalizePort(val) { if (val === undefined || val.length === 0) { return null; } const portNumber = parseInt(val, 10); if (isNaN(portNumber)) { // named pipe return [ 'pipe', val ]; } if (portNumber >= 0) { // port number return [ 'port', portN...
[ "function normalizePort(val) {\n const port = parseInt(val, 10);\n\n return port; // NaN or number returned;\n}", "function normalizePort(val) {\n var port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n if (port >= 0) {\n // port number\n return port;\n } else {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enumerablegrep(regex[, iterator = Prototype.K[, context]]) > Array Returns all the elements that match the filter. If an iterator is provided, it is used to produce the returned value for each selected element.
function grep(filter, iterator, context) { iterator = iterator || Prototype.K; var results = []; if (Object.isString(filter)) filter = new RegExp(RegExp.escape(filter)); this.each(function(value, index) { if (filter.match(value)) results.push(iterator.call(context, value, index)); ...
[ "function findAll(iterator, context) {\n var results = [];\n this.each(function(value, index) {\n if (iterator.call(context, value, index))\n results.push(value);\n });\n return results;\n }", "function grep(a, s) {\r\n var r = new Array();\r\n // Convert string into a regexp\r\n if (t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates Cookie string into a convenient map.
function getCookieAsMap() { var map = stringToMap(document.cookie, { separator: /;\s?/ }); if (typeof map.tmsso === 'string') { map.tmsso = stringToMap(map.tmsso, { separator: ':' }); } if (typeof map.engsso === 'string') { map.engsso = stringToMap(map.engsso, { separator: ':' }); } return map; }
[ "function parse(cookies) {\n if (typeof cookies !== 'string')\n throw new TypeError('Argument has to be a string');\n\n let cookieDict = {};\n\n cookies.split(';').forEach(function(cookie) {\n let parts = cookie.split('=');\n cookieDict[parts[0].trim()] = parts[1] || null;\n });\n\n return cookieDict;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a serializable BaggageEntryMetadata object from a string.
function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { diag.error("Cannot create baggage metadata from unknown type: " + typeof str); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, toString: function () { return str; ...
[ "function baggageEntryMetadataFromString(str) {\n if (typeof str !== 'string') {\n diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);\n str = '';\n }\n return {\n __TYPE__: symbol_1.baggageEntryMetadataSymbol,\n toString() {\n return str;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
now need to fetch store value from storage and set slider in its initial position from the last time we set it
async function init() { // re use value from last time it was set let { value } = browser.local.storage.get('value'); // if first time then value is set to 0 if (!value) { value = 0; } input.value = value; // once we get it from storage now adjust value setValue(value); }
[ "function setPosition () {\n var valuesContainer = $('.price-slider .values-wrapper'),\n containerOffset = $('.price-slider').offset().left,\n lowerOffset = $('.noUi-handle-lower').offset().left - containerOffset,\n upperOffset = $('.noUi-handle-upper').offset().left - contai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to fetch (ajax) XML file regarding rooms at the hotel
function showRooms() { var target = $("#room"); var source = "roomXML/hotelRooms.xml"; $.ajax({ type: "GET", url: source, cache: false, success: function (data) { parseRooms(data, target); } }); }
[ "function showRooms() {\n var target = $.find(\".seeRooms\")[0];\n var data = \"../xml/hotelRooms.xml\";\n $.ajax({\n type: \"GET\",\n url: data,\n cache: false,\n success: function(data) {\n parseRooms(data, target);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removing JSON from cache
function uncache(jsonFile) { searchCache(jsonFile, function (mod) { delete require.cache[mod.id]; }); Object.keys(module.constructor._pathCache).forEach(function (cacheKey) { if (cacheKey.indexOf(jsonFile) > 0) { delete module.constructor._pathCache[cacheKey]; } }); ...
[ "clearJSON(){\n this.putJSON(null);\n }", "function uncache(jsonFile) {\n searchCache(jsonFile, function(mod) {\n delete require.cache[mod.id];\n });\n\n Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {\n if (cacheKey.indexOf(jsonFile) > 0) {\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
terminateEventByIncident Parse value from xml node by first identifying 'name' element then locating next 'value' element
function terminateEventByIncident(incident_id) { try { // Get event by incident_id property var response = XMIO.get(REST_SERVICE_URL + "/events?status=ACTIVE&propertyName=incident_id%23en&propertyValue=" + incident_id); var events = JSON.parse(response.body); var total = parseInt(events.total); } ...
[ "function ParseIncident()\n{\n\tvar IncidentDoc\t= new ActiveXObject(\"microsoft.XMLDOM\");\n\t\n\ttry \n\t{\n\t\tIncidentDoc.load( g_szIncidentFile );\n\t\tif ( IncidentDoc.parseError.reason != \"\")\n\t\t{\n\t\t\talert( IncidentDoc.parseError.reason);\n\t\t}\n\t\t\n\t\t//\n\t\t// Fetch the Upload data\n\t\t//\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determine if special header was sent with the request that says to block emails
requestSaysToBlockEmails () { return ( ( this.request.api.config.email.suppressEmails && !this.request.request.headers['x-cs-test-email-sends'] ) || ( this.request.request.headers && this.request.request.headers['x-cs-block-email-sends'] ) ); }
[ "requestSaysToBlockEmails (options) {\n\t\tconst headers = (\n\t\t\toptions.request &&\n\t\t\toptions.request.request &&\n\t\t\toptions.request.request.headers\n\t\t);\n\t\treturn (\n\t\t\tthis.api.config.email.suppressEmails ||\n\t\t\t(headers && headers['x-cs-block-email-sends'])\n\t\t);\n\t}", "requestSaysToBl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
++++Method++++ Import a module with name or id
function _import(moduleName_Or_moduleId, context) { const tp = typeof moduleName_Or_moduleId; let elm; if(tp === NS.type.und) { throw ERROR("moduleNotDefined"); } else if(tp === NS.type.str) { return R(moduleName_Or_moduleId); } else if(tp === NS.type.num) { return R(modulesId[moduleName_Or_moduleId]);...
[ "import(moduleInstanceObject) {\n throw Error('Not implemented');\n }", "importModule(mod) {\n\t this.lib.checkCall(this.lib.exports.TVMModImport(this.handle, mod.handle));\n\t }", "importModule(mod) {\n this.lib.checkCall(this.lib.exports.TVMModImport(this.handle, mod.handle));\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a new tab to the online viewer and sends the local page's JSON results to the online viewer using postMessage.
sendJSONReport() { const VIEWER_ORIGIN = 'https://googlechrome.github.io'; const VIEWER_URL = `${VIEWER_ORIGIN}/lighthouse/viewer/`; // Chrome doesn't allow us to immediately postMessage to a popup right // after it's created. Normally, we could also listen for the popup window's // load event, how...
[ "function sendMessage(){\n window.open(\"MessageSendingPage.html\", \"_self\");\n}", "function openMyPage() {\n console.log(\"injecting\");\n browser.tabs.create({\n \"url\": \"/sony-tv.html\"\n });\n}", "sendMessage(message) {\r\n this.currentPanel.webview.postMessage(message);\r\n }", "sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a NN matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students. Example 1: Input: [[1,1,0], [1,1,0], [0,0,1]] Output:...
function findCircleNum(M) { // visited set const visited = new Set(); // friend circles count let circles = 0; // iterate thru matrix for (let i = 0; i < M.length; i++) { // check if this friend has been visited before if (!visited.has(i)) { // start dfs for this fr...
[ "function friendCircleNum(matrix) {\n let friendCircle = 0;\n let visited = new Array(matrix.length).fill(0);\n for (let i=0; i<matrix.length; i++) {\n if (visited[i] == 0) {\n friendCircle++;\n dfs(matrix, visited, i);\n }\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }