query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
bin data into bins of x minutes, where x = binInterval
function binData(data, binInterval) { var binnedData = []; var binCounts = []; var minTime = null; var maxTime = null; for (var i=0; i<data.length; i++) { var dataType = data[i].activity_type; var skip = (i<data.length-1) && (dataType=='link') && (data[i+1].activity_type=='link_rating'); if (skip) contin...
[ "function timeBinIntoInteractions (data, numBins = 20, type = 'CPV') {\r\n\r\n var timeExtent = [0, d3.max(data, function (d) {\r\n return +d.date\r\n })]\r\n\r\n var elapsedTime = timeExtent[1] - timeExtent[0]\r\n var interval = elapsedTime / numBins\r\n\r\n var initBins = []\r\n for (var i = 1; i <= numB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when svg is ready
function init(svg){ svgReady = svg; goReady(); }
[ "function onSVGLoaded(data) {\n\t\ts.append(data);\n\t}", "function onSVGLoaded(data) {\n\n\n // Adiciona o svg dentro da tag <svg> com o id (nesse caso, #mapa) passado para o snap\n // Obs.: Realmente faz um append. Se existir dados, os novos dados serao acrescentados no final\n if(!init)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::IoTEvents::AlarmModel.AlarmCapabilities` resource
function cfnAlarmModelAlarmCapabilitiesPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnAlarmModel_AlarmCapabilitiesPropertyValidator(properties).assertSuccess(); return { AcknowledgeFlow: cfnAlarmModelAcknowledgeFlowPropertyToCloudFormati...
[ "renderAlarmRule() {\n return `ALARM(${this.alarmArn})`;\n }", "renderAlarmRule() {\n return `ALARM(\"${this.alarmArn}\")`;\n }", "function cfnApplicationAlarmMetricPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAppli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the minimum required answers for analysis have been collected.
function resultsReady() { /*console.log("resultsReady ", surveyStorage.allAnswers.length, ( surveyStorage.allAnswers.length >= MIN_RES));*/ return (surveyStorage.allAnswers.length < MIN_RES); }
[ "function outOfQuestionsCheck(){\n \tif(questionCounter === totalQuestions){\n \t\treturn true;\n \t}\n \telse{\n \t\treturn false;\n \t}\n }", "revealedAllAnswers() {\n return this.revealedAnswers.length >= this.orderedChoices.length;\n }", "checkResultsWeightsOk() {\n var total...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
factorial function which handles big integers
function factorial(n){ if (n ==1){ return 1; } return bigInt(n).multiply(factorial(n-1)); }
[ "function calculateFactorial( number ){\n\n}", "function calculateFactorial(n) {\n // TODO\n}", "function extraLongFactorials(n) {\n\n var bigInt = BigInt(n);\n var factorial = 1n;\n\n for (let i = 0n; i < bigInt ; i++) {\n factorial *= bigInt - i;\n }\n \n console.log(factorial.toStri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is carried out when the 'Sharpen Stone' button is clicked
function sharpenStone() { stoneBank -= 2; sharpStoneBank++; action(1,1,1); advanceTime(); updateDisp(); }
[ "function processSharpen(img, filename){\n let image = img.clone();\n image.convolute([\n\t[0, -1, 0],\n\t[-1, 5, -1],\n\t[0, -1, 0]\n ]);\n image.write(filename);\n console.log(getCurrentTime() + '> Sharpen image saved as <' + filename + '>.');\n}", "function sharpen(mix) {\n\t\n\tw = canvas.width;\n\th = c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
nextGame :: Game > Game
function nextGame(game) { var newGame = {}; enumerateObj(game, function nextGameEnumerator(cell, id) { var count = countActiveNeighbours(game, cell); var wasActive = isActive(cell); if (!(0 === count && !wasActive)) { var active = (wasActive === true &...
[ "getNextOpenGame() {\n return this.retrieve(this.openGames[this.openGames.length - 1]);\n }", "function newGame (){\n return new Game();\n}", "loadGame(game) { }", "function newGame () {\n const startGame = new Game();\n return startGame;\n}", "AddGame(game){\n this._curRound++;\n this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Carrega caption da label referente a imagem TRABALHO
function trabalho_caption(N_trabalho) { var caption = ''; switch (N_trabalho) { case 1: caption = "Capas para almofadas (1/10)"; break; case 2: caption = "Capas para livros e agendas (2/10)"; break; case 3: caption = "Panos d...
[ "function labelCaption(label0) /* (label : label) -> string */ {\n return label0.labelCaption;\n}", "function customizeCaption() {\n var captionText = \n \"Circle sizes represent rates of water withdrawals by county. \";\n if(waterUseViz.interactionMode === 'tap') {\n captionText = captionText +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The parent node that the range points into.
get parent() { return this.$from.node(this.depth); }
[ "get_parent_node(){\n return this.fc.get_fragment_by_id(this.parent_node[0]).get_node_by_id(this.parent_node[1])\n }", "parent() {\n return this._node(this.el.parent);\n }", "function getDeeperRangeParent(range) {\n if (!range) {\n return null;\n }\n\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return => 6 / 1.6 Write a function called greeting. Instead of giving it an object parameter, give it a destructured object as it's parameter. The properties of this object will be name and title. Return from this function a greeting sentence that should say "Hello, !". Title and name in this sentence should be replace...
function greeting({ name, title }) { return "Hello, " + title + " " + name + "!"; }
[ "function greeting( obj ) {\n //Code Here\n let {firstName, lastName, title} = obj\n // Do not edit the code below.\n return 'Hello, ' + title + ' ' + firstName + ' ' + lastName + '!';\n // Do not edit the code above.\n }", "function greeting( obj ) {\n let {title, firstName, lastName} = obj;\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the "results" panel that sits above the map this always shows either the Global tally of things, or a countryspecific count, or a count from a search term enterd in the "Free Search" input
function updateResultsPanel(data, country=CONFIG.default_title) { // update primary content $('div#country-results div#results-title h3').text(country); var totalrow = $('div#country-results div#total-count').empty(); var totaltext = data.length > 0 ? (data.length > 1 ? `Tracking ${data.length.toLocaleString()}...
[ "function updateSearchResultCount(count) {\n var resultString;\n //if no results were found, provide some ideas on improving the query to the end-user\n if (count === 0) {\n resultString = \"No results found. Try expanding the location radius, time frame, or just leaving the location and radius fields blank ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds new post to top of timeline.
function addPost(post) { var postElt = Mustache.render(postTmpl, post); console.log('generated HTML: %s', postElt); $('#index_list_posts').prepend(postElt); }
[ "addBlogPost(newPost) {\n let currentPosts = this.readData();\n currentPosts.unshift(newPost);\n this.storeBlogPost(currentPosts)\n }", "function addPost(data) {\n \n // Add username of the user who posted\n var $usernameDiv = $('<span class=\"postUsername\"/>')\n .text(data....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the debouncer to update examples list.
_computeExamples() { if (this._examplesDebouncer) { return; } this._examplesDebouncer = true; setTimeout(() => { this._examplesDebouncer = false; this.__computeExamples(this.examples, this.mediaType, this.rawOnly, this.typeName, this.payloadId, this.noAuto, this.renderReadOnly); })...
[ "function queueExamples() {\n if (debouncedTimer) {\n clearTimeout(debouncedTimer);\n }\n debouncedTimer = setTimeout(runExamples, 1);\n }", "function batchUIUpdates() {\n if (!debouncer) {\n debouncer = new bookmarks.Debouncer(\n () => bookmarks.Store.getInstance().endBa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display current weather conditions
function showWeatherConditions(response) { document.querySelector("#city").innerHTML = response.data.name; celsiusTemperature = response.data.main.temp; document.querySelector("#temperature").innerHTML = Math.round(celsiusTemperature); maxTemperature = response.data.main.temp_max; document.querySelector("...
[ "function currentConditions(cityName) {\n var queryURL = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&APPID=${APIKEY}&units=imperial`;\n $.ajax({\n \"url\": queryURL,\n \"method\": \"GET\",\n }).done(function (response) {\n displayCurrConditions...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a circle to represent the 'window' into the ball where we can see the die and response.
function draw_window(context){ // window context.beginPath(); context.arc(ball_visual.centre_x, ball_visual.centre_y, ball_visual.window_radius, 0, 2 * Math.PI, false); context.fillStyle = "#000000"; context.fill(); context.lineWidth = 1; context.strokeStyle = "#ffffff"; context.stroke()...
[ "function bigCircle() {\n\n\tcontext.beginPath();\n\tcontext.arc(windowCenterX,windowCenterY,circleRadius,0,2*Math.PI);\n\tcontext.stroke();\n}", "function player_circle() {\r\n window_context.beginPath();\r\n window_context.arc(px, py, radius, 0, Math.PI * 2);\r\n window_context.fillStyle = \"#0eede9\";\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects if the current device is an Android OSbased device and the browser is based on WebKit.
function DetectAndroidWebKit() { if (DetectAndroid() && DetectWebkit()) return true; else return false; }
[ "function DetectAndroidWebKit()\n{\n if (DetectAndroid() && DetectWebkit())\n return true;\n else\n return false;\n}", "function DetectAndroidWebKit()\n\t{\n \t\tif (DetectAndroid())\n \t{\n \tif (DetectWebkit())\n \treturn true;\n \telse\n \treturn false;\n \t\t}\n \t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds each business in the data to the searchresults div
function searchSuccess(data, textStatus, jqXHR) { //console.log(data); var businessDiv = $('<div id="businessDiv"></div>'); data.businesses.forEach(function(business){ var businessImage = $('<img class="businessImage" src="' + business.image_url + '" />') businessImage.attr('alt', 'No Picture Avai...
[ "function getSearchResults(search, divId) { // need to change this to use $.ajax for error handling\r\n var filePath = \"/beersearch/?q=\" + search;\r\n $.getJSON(filePath, function (json) {\r\n // clears previous search results\r\n $(\".beerSearchContainer\").empty();\r\n for (var elemen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render(show) save/delete note buttons for a new or existing note.
renderFormButtons() { //if the note.id exists, then we can either delete or edit that note if (this.props.note.id !== undefined) { return (<div> { /* Show the save button to edit note */} <button type="submit" className="btn btn-success float-right">Add Note</...
[ "function handleRenderSaveBtn() {\n if (!$(\".note-title\").val().trim() || !$(\".note-textarea\").val().trim()) {\n $(\".save-note\").hide();\n $(\".new-note\").show();\n } else {\n $(\".save-note\").show();\n $(\".new-note\").hide();\n }\n }", "function addNoteButton(note) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a sublanguage (returns a list of nodes).
function processSubLanguage() { var explicit = typeof top.subLanguage === 'string'; var subvalue; /* istanbul ignore if - support non-loaded sublanguages */ if (explicit && !languages[top.subLanguage]) { return addText(modeBuffer, []); } if (explicit) { subvalue = coreHighlight( ...
[ "function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string'\n var subvalue\n\n /* istanbul ignore if - support non-loaded sublanguages */\n if (explicit && !languages[top.subLanguage]) {\n return addText(modeBuffer, [])\n }\n\n if (explicit) {\n subvalue = coreH...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the calendar date of the start of the fiscal year
get startDate() { var tmp; if (this.fiscalMonth === 0) { // TODO test this case tmp = new Date(this.fiscalYear, this.fiscalMonth); } else { tmp = new Date(this.fiscalYear - 1, this.fiscalMonth); } return tmp; }
[ "function getFiscalYearStartDate(){\n\tvar fiscalDateFull = new Date();\n\tvar currentDate = new Date();\n\tvar fiscalYearDay = 1;\n\tvar fiscalYearMonth = 1;\n\tvar params = {\n\t\ttableName: 'afm_scmpref',\n\t\tfieldNames: toJSON(['afm_scmpref.fiscalyear_startday', 'afm_scmpref.fiscalyear_startmonth', 'afm_scmpre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clicking the rating table header will sort items by rating level in order.
function sortByRating(){ var sortColumn = 1; var tableData = document.getElementById("bookdata").getElementsByTagName('tbody').item(0); var rowData = tableData.getElementsByTagName('tr'); for(var i = 0; i < rowData.length - 1; i++){ ...
[ "function SortByRating() {\r\n sortedBy = \"Rating\";\r\n ResetTableHeaders();\r\n if (sortOrder == 1) {\r\n movies.sort(compareRatingDescending);\r\n document.getElementById(\"SortByRating\").innerText = \"Rating \\u2193\";\r\n } else {\r\n movies.sort(compareRatingAscending);\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
starts a session for the user if the given credentials are valid
async function startSession(user, pass) { let token = await post('./server/user/login.php', JSON.stringify({user: user, pass: pass})); if (token){ sessionStorage.setItem('token', token); return true; } return false; }
[ "function loginUser() {\n //Checks whether email and password were given\n if (!email || !password) {\n setError('Email and password must be given');\n }\n //Checks whether the user's email exists\n else if (!userExists()) {\n setError('This email is not assi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Chessboard Square. The properties of a square are its color, row and column. A square is initialized with a null piece on it.
function ChessSquare(color, row, column) { this.color = color; this.row = row; this.column = column; this.selected = false; // Initialize with a null piece: this.piece = null; }
[ "function Square (board, row, col) {\n this.board = board;\n this.row = row;\n this.col = col;\n}", "function WhiteBoardSquare(position, scale, color) {\n this.type = \"square\";\n this.position = position;\n this.scale = scale;\n this.color = color;\n}", "function createSquare() {\n new Squ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All `compiler` options should be applied for subprocesses
addCompilersForSubprocess(compilers) { this.compilers = compilers; }
[ "function Compilers() {\n\tvar kColiruBaseCommand = \"-std=c++1z -pthread -lboost_context -Wall main.cpp && ./a.out\";\n\tvar kColiruUrl = \"http://coliru.stacked-crooked.com/compile\";\n\t\n\tvar compilerParameters = {}\n\tcompilerParameters[\"clang\"] = {\"compilationCommand\" : \"clang++ \" + kColiruBaseCommand,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shuffle items changes the order of all of the colour divs on teh screen
shuffleItems() { this.items.sort(() => Math.random() - 0.5); this.items.forEach((item, index) => { item.div.style.order = index; }); }
[ "function generateColor() {\n var shuffleColor = shuffle(colorArr)\n for (var i = 0; i < shuffleColor.length; i++) {\n $colorPanel.append('<div class=\"box ' + shuffleColor[i] + '\"></div>')\n }\n }", "function shuffle(x) {\n var tarjetas = document.querySelectorAll('.tarjetas');\n\n for (i =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if "now" is within the range of times (start, end) even if "start" is after "end" and thus loops to the next day.
function inRange(start, end, now) { if (!start.def || !end.def) { return false; } let s = (start.hours * 60) + start.minutes; let e = (end.hours * 60) + end.minutes; let n = (now.getHours() * 60) + now.getMinutes(); if (s == e) { return false; } if (s < e) { // if it'...
[ "function time_range_contains({start, end, now}) {\n const moment_start = moment(start), moment_end = moment(end), moment_now = moment(now);\n if(moment_now.isAfter(moment_end) && moment_end.isBefore(moment_start)) {\n moment_end.add(1, 'day');\n } else if (moment_now.isBefore(moment_end) && moment_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a scene by its ID and save
deleteScene(sceneId) { this.scenes = this.scenes.filter((scene) => { return scene.id !== sceneId }) this.saveToFile() }
[ "function deleteSceneObject(id) {\n vm.project.scenes = LptHelper.deleteObjectFromArrayBy('_id', id, vm.project.scenes);\n\n angular.forEach(vm.groups, function(group) {\n if (!LptHelper.isEmpty(group.scenes)) {\n group.scenes = LptHelper.deleteObjectFromArrayBy('_id', id, gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the parent node of the new items. If the path is the same as `ide.davPrefix`, then we append to root
function getParentNodeFromPath(path) { var parentNode; if (path === ide.davPrefix) parentNode = trFiles.queryNode("folder[@root=1]"); else parentNode = trFiles.queryNode('//folder[@path=' + util.escapeXpathString(path) + ']'); return paren...
[ "get parentItem() {\n const parentItem = getParentItem(this.rootItem, this.dataPath, true) || null\n return parentItem !== this.item ? parentItem : null\n }", "get parent() {\n return new Path(this.parentPath);\n }", "parent() {\n return new Path(path_1.default.dirname(this.internalPath)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note: hydration is DOMspecific But we have to place it in core due to tight coupling with core splitting it out creates a ton of unnecessary complexity. Hydration also depends on some renderer internal logic which needs to be passed in via arguments.
function createHydrationFunctions(rendererInternals) { const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals; const hydrate = (vnode, container) => { if (( true) && !container.hasChildNodes()) { warn(`Attempting t...
[ "function createHydrationFunctions(rendererInternals){const{mt:mountComponent,p:patch,o:{patchProp,createText,nextSibling,parentNode,remove,insert,createComment}}=rendererInternals;const hydrate=(vnode,container)=>{if(!container.hasChildNodes()){warn$1(`Attempting to hydrate existing markup but container is empty. ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads a hexadecimal character and returns its positive integer value (015). '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns 1 if the provided character code was not a valid hexadecimal digit. HexDigit :: one of `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` `A` `B` `C` `D` `E...
function readHexDigit(code) { return code >= 0x0030 && code <= 0x0039 // 0-9 ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f ? code - 0x0057 : -1; }
[ "function readHexDigit(code) {\n return code >= 0x0030 && code <= 0x0039 // 0-9\n ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F\n ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f\n ? code - 0x0057 : -1;\n}", "readHexDigit() {\n let c = this.nextChar();\n if (c >= '0' && c <=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when the input field is populated we need to display askCommunity button
askQ(e) { if (e.target.value) { this.setState({ askCommunity: true}) } else{ this.setState({ askCommunity: false, showQuestions: false, showInfo: false, showReviews: false, showAsked: false}) } // console.log(e.target.value); }
[ "async enterText(){\n let value = await RandomUtils.generateRandomString();\n await this.stringField.enterText(value)\n this.inputValue = value;\n if (this.checkYourAnswersValue === null){\n this.checkYourAnswersValue = value;\n }\n this.label = await this._getLabel();\n }", "function init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
validate total measuret carton vs invoice
function validateTotalMeasurement() { try { var _total_measure_invoice = parseFloat($('.DSP_total_measure').text().replace(/,/g, '')); _total_measure_invoice = !isNaN(_total_measure_invoice) ? _total_measure_invoice : 0; var _total_measure_carton = parseFloat($('.DSP_total_measure_carton').text().replace...
[ "function validateCartonInvoice() {\n\ttry {\n\t\t// if (checkCarton()) {\n\t\t\tif (!validateTotalNetWeight()) {\n\t\t\t\tjMessage('C144', function(r) {\n\t\t\t\t\tif (r) {\n\t\t\t\t\t\tif (!validateTotalGrossWeight()) {\n\t\t\t\t\t\t\tjMessage('C145', function(k) {\n\t\t\t\t\t\t\t\tif (k) {\n\t\t\t\t\t\t\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIF Extract size from a binary GIF file TODO: GIF is not this simple
function getGifMetadata(binaryData) { const dataView = toDataView(binaryData); // Check first 4 bytes of the GIF signature ("GIF8"). const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638; if (!isGif) { return null; } // GIF is little endian. return { mimeType...
[ "function getGifSize(dataView) {\n // GIF is little endian.\n return {\n width: dataView.getUint16(6, LITTLE_ENDIAN),\n height: dataView.getUint16(8, LITTLE_ENDIAN)\n };\n}", "function getJpegSize(parser, sandbox) {\n parseJpegMarker(parser, function (code, length) {\n if (!code || length < 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode 16bit wave file as 8bit muLaw.
toMuLaw() { this.assure16Bit_(); /** @type {!Int16Array} */ let output = new Int16Array(this.data.samples.length / 2); unpackArrayTo(this.data.samples, this.dataType, output); this.fromScratch( this.fmt.numChannels, this.fmt.sampleRate, '8m', alawmulaw.mulaw.encode(o...
[ "toMuLaw() {\n this.assure16Bit_();\n let output = new Int16Array(this.data.samples.length / 2);\n unpackArrayTo(this.data.samples, this.dataType, output);\n this.fromScratch(\n this.fmt.numChannels,\n this.fmt.sampleRate,\n '8m',\n mulaw.encode(output),\n {container: this.corre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refilter allLinks into visibleLinks and reshow visibleLinks.
function filterLinks() { var filterValue = document.getElementById('filter').value; if (document.getElementById('regex').checked) { visibleLinks = allLinks.filter(function(link) { return link.match(filterValue); }); } else { var terms = filterValue.split(' '); visibleLinks = allLinks.filter(...
[ "toggleLinks() {\n if (this.showLinks) {\n this.hideLinks();\n } else {\n this.showAllLinks();\n }\n }", "showAllLinks() {\n for (let i = 0; i < this.constellationObjects.length; i++) {\n this.constellationObjects[i].showLinks();\n }\n this.showLinks = true;\n }", "hideLinks()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
write a function that will loop through a list of integers and print the index of each element after a three second delay
function fn(numbers) { for(var i = 0; i < numbers.length; i++) { (function(i) { setTimeout(function() { console.log(numbers[i]); }, 3000); })(i); } }
[ "function printArray(arr){\n var i;\n var j;\n for( i=0; i<arr.length; i++){\n j=i;\n // (function(inx){\n setTimeout(function(){\n console.log('index '+inx+':'+arr[inx]);\n },(i+1)*1000);\n // }(i))\n \n }\n console.log(i);\n}", "function printNumbersInterval() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove video FEC if available on the offer.
disableVideoFec () { this.constrainOfferToRemoveVideoFec = true; }
[ "function removeOldVideoProducers(){\n if(mediasouproom == null || mediasouproom == undefined || mediasouproom.producers.length < 0)\n return;\n let producers = mediasouproom.producers;\n Array.from(producers).forEach( (producer) => {\n if( producer.track.kind == 'video' ){\n produ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Middleware authentication using verginacl Function accepts action and resource params. Uses req.user.role to perform a check assigns quest role if no other roles exist
function isUserAllowed(action, resource) { return function(req, res, next) { // add quest role for non-logged in users. if (!req.user || !req.user.role) { req.user = { role: 'guest' }; } console.info(util.form...
[ "function roleCheck(role) {\n return function (req, res, next) {\n if ((req.body.role == role)) {\n next();\n } else {\n res.status(401).json({ message: \"you are unauthorized\" });\n }\n };\n}", "authMentor(req, res, next){\n if(req.userToken.role === ROLES.mentor || req.userToken.role ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method send details to Driver for ride Request
riderRequest(){ var jsonData = JSON.stringify( { source: this.state.currentLocation, destination: this.state.destinationLocation, deviceToken: this.state.deviceToken, sourceAddress:this.state.myLocationAddress, destinationAddress:this.state.destinationAddress, ...
[ "function updateRideRequest() {\n RideRequestService.update({id: vm.assignedRide.id}, vm.assignedRide).$promise.then(function (response) {\n console.log('Driver, saved riderequest:', response);\n }, function (error) {\n console.log('Driver, error saving ridereques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a modal prompt box (input box) and stores the resulting value in $[mapsettings].value
function mapPrompt(title, question, submit, allowCancel) { var content = '<form id = "modalQuestion" action = "#" method = "post"><h2>' + title + '</h2>' + '<p><label for = "question">' + question + '</label> <input id = "question" type = "text" name = "question" value = "" /><input type = "submit" name = "submit" v...
[ "function modalInput() {\n return 'Res želite izprazniti košarico?';\n}", "function onChooseModalSearchBox(){\n\tconst coords = this.getPlaces().shift().geometry.location;\n\tconst position = {lat: coords.lat(), lng: coords.lng()};\n\t// On place les données dans l'input hidden\n\t$(\"#coords-modal\").val(JSON...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Purpose: This is an helper function to perform BFS for individual Queue [queue for src as well as queue for dst] Params: matrix is the main grid storing info, queue is the datastructure storing locations to traverse which can be of either src or destination, parent refers to the Array of Object containing parent of e...
function bi_bfs(matrix, queue, visited, parent) { /* Getting the front element from the queue */ let rv = queue.shift(); /* extract the 'x' and 'y' coordinate of the popped element */ let x = parseInt(rv[0]), y = parseInt(rv[1]); /* Loop over each neighbour directions */ for (let i = 0; i < dirs.length; ...
[ "*shortestPath(src,dest) \r\n {\r\n //condition to check that input source or destination are invalid\r\n if(!this.isValid(src[0],src[1])||!this.isValid(dest[0],dest[1]))\r\n return [];\r\n\r\n //condition to check that input source or destination are obstacles\r\n if(this.isOb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Api to get all parcel by specific user
ParcelSpecificUsr (req, res) { const user_id = parseInt(req.params.userid, 10); let parcels = []; data.filter((parcel) => { if(parcel.createdBy === user_id){ parcels.push(parcel); return res.status(200).send({ success : 'True', message :...
[ "getAllParcelByUser() {\n const userId = this.getUserId();\n const apiKey = this.getApiKey();\n\n return HttpRequest.getWithHeader(`${endPoint}/users/${userId}/parcels/`, apiKey)\n .then(result => result);\n }", "async listParcels(req, res) {\n try {\n const { userId } = req.query\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update results from crossfilter.
updateResults() { if (this.reindexFlag_) { this.reindex(); } var results = []; if (this.timeModel_ && this.binMethod) { // make sure the source time model is filtered on the correct range if (this.source) { this.source.getFilteredFeatures(); } var tempFilters = {}...
[ "updateViewFilters() {\n this.viewFilters = this.filtersIterator(this.searchFilters, (filterName, anomalyIds) => {\n return [...this.getIntersection(this.selectedAnomalyIds, anomalyIds)];\n });\n }", "function updateData() {\n var data = self.data;\n\n self.filters.forEach(function(v, i)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that update the chart for given boundaries
function updateChart() { // What are the selected boundaries? extent = d3.event.selection // If no selection, back to initial coordinate. Otherwise, update X axis domain if (!extent) { if (!idleTimeout) return idleTimeout = set...
[ "function updateChart() {\n\n // What are the selected boundaries?\n extent = d3.event.selection\n\n // If no selection, back to initial coordinate. Otherwise, update X axis domain\n if(!extent){\n if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a lit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Effect Group on click
function add_effect_group(elem) { $(elem).siblings('.effectGroupControls').append($(elem).siblings('.effectGroupControls').find('div[name=effectgroup]:first').clone().show()); }
[ "function EffectBtnClicked(){\n\t _EffectListWidget.clear();\n for(i = 0; i < SpecialEffects.length; i++){\n _EffectListWidget.addItem(SpecialEffects[i]);\n }\n\t EffectProxy.visible = true;\n\t SceneProxy.visible = ! EffectProxy.visible;\n\t BackgroundProxy.visible = ! EffectProxy.visible;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if all items in an array are numbers
function numbers (a) { return low.isArray(a) && a.every(low.number) }
[ "function areAllNumbers(array) {\n return myOwnEvery(array, isANumber);\n}", "function isNumericArray(array) {\n let isal = true;\n for (const element of array) {\n if (!$.isNumeric(element)) {\n isal = false;\n }\n }\n return isal;\n }", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
since searchfield is custom field in worklist and is present in table toolbar, in this function we get the searchfield and store in oState. This searchfield will be used for setting and getting the searchtext when restoring the page state.
function fnFetchAndSaveWorklistSearchField() { var oSmartTable = oState.oSmartTable; var aTableToolbarContent = oSmartTable.getCustomToolbar().getContent(); for (var index in aTableToolbarContent) { if (aTableToolbarContent[index].getId().indexOf("SearchField") > -1) { oState.oWorklistData.oSearchFiel...
[ "static get searchField() {\n return new SearchField();\n }", "function getSearchObj(){\n return searchObj;\n }", "function getSearchObj(){\n return searchObj;\n }", "function get_search_query() {\n\t\t// returning the value of what was put into the search input b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alan is known for referring to the temperature of the apple turnover as 'Hotter than the sun!'. According to space.com the temperature of the sun's corona is 2,000,000 degrees C, but we will ignore the science for now. Your job is simple, if (x) squared is more than 1000, return 'It's hotter than the sun!!', else, retu...
function apple(x){ return (Math.pow(x,2) > 1000) ? 'It\'s hotter than the sun!!' : 'Help yourself to a honeycomb Yorkie for the glovebox.'; }
[ "function apple(x){\n \n return (Math.pow(Number(x), 2) > 1000 ? 'It\\'s hotter than the sun!!' : 'Help yourself to a honeycomb Yorkie for the glovebox.' ) \n }", "function apple(x){\n return ((x * x) >= 1000) ? `It's hotter than the sun!!` : `Help yourself to a honeycomb Yorkie for the glovebox.`;\n}", "get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alter trait in object/DOM
edit() { this.setNewTrait("name") this.setNewTrait("breed") this.setNewTrait("sex") return this }
[ "static implement(instance, trait) {\n // I would also like to reference classes (to cut down on the list of objects\n // we need to manage), but we can't do that either since jsii doesn't have the\n // concept of a class reference.\n instance[DEPENDABLE_SYMBOL] = trait;\n }", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create watchlist table row Args: watch_dso: WatchDso object date: A Date() to use on ALT/AZ calculations location: latitude and longitude to use on ALT/AZ calculations plot_canvas: canvas of visibilty plot delete_callback(watch_dso): Called when user clicks the delete button, gives watch_dso as argument save_callback(w...
function watchlist_create_row( watch_dso, date, location, plot_canvas, delete_callback, save_callback, goto_callback, plot_callback, style_change_callback, notes_change_callback ) { let tr = $("<tr>"); for (let col of watchlist_columns) { switch (col.name) { ...
[ "function catalog_create_row(\n dso,\n date,\n location,\n added,\n plot_canvas,\n add_callback,\n goto_callback,\n plot_callback\n) {\n let tr = $(\"<tr>\");\n for (let col of catalog_columns) {\n switch (col.name) {\n case \"id\":\n tr.append(create_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To reset update partner page
function resetUpdate(formId){ clearError(formId+" #partnerName"); clearError(formId+" #partnerDesc"); clearError(formId+" #partnerMdmId"); $("#feedBackTd").html(''); }
[ "function resetPage () {\r\n\t\t$(\"#vinText\").removeAttr(\"disabled\").val(\"\").focus();\r\n\t\ttoggleVinHint(true);\r\n\t\t$(\"#btnSubmit\").attr(\"disabled\",\"disabled\");\r\n\t\t$('#compCodeText').val(\"\").attr(\"disabled\",\"disabled\");\t\t//added by wujun\r\n\t\t$(\"#componentTable tbody\").text(\"\");\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
move function prepends/appends an image to start/end of slider:
function move($slider, image) { if (btn == "left") { $slider.prepend(image); } else { $slider.append(image); } }
[ "move(img) {\n img.x -= img.speed;\n\n // image(we get the source of image, x coordinate, y coordinate )\n image(img.src, img.x, 0);\n image(img.src, img.x + width, 0);\n if (img.x <= -width) {\n img.x = 0;\n }\n }", "function populateSlider() {\n movies.forEach((image) => {\n //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load css file (immediate callback)
function loadCSS() { // CSS file not loaded yet? => load CSS file if ( !resource ) jQuery( 'head' ).append( '<link rel="stylesheet" type="text/css" href="' + url + '">' ); // immediate perform success callback success(); }
[ "function loadCss() {\n $.post('/get-css', function (data) {\n var style = document.createElement('style');\n style.innerHTML = data;\n document.head.appendChild(style);\n });\n}", "loadCSS() {\n var fileRef = document.createElement(\"link\");\n fileRef.setAttribute(\"rel\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
During parsing, map & aliases contain CST nodes
resolveNodes() { const { map, _cstAliases } = this; Object.keys(map).forEach(a => { map[a] = map[a].resolved; }); _cstAliases.forEach(a => { a.source = a.source.resolved; }); delete this._cstAliases; }
[ "function ParseTreeTransformer() {}", "parse_map_d(tokens) {\n this.currentMaterial.mapDissolve = this.parseMap(tokens);\n }", "function convertMapping(\n/* eslint-enable complexity -- X */\npreTokens, cst, node, ctx, parent, doc) {\n var _a, _b;\n if (isPair(node)) {\n /* istanbul ignore...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
8. Create a function that adds a student like to all mentors in the array
function addStudentsLike(mentors) { mentors.forEach(mentor => mentor.addStudentLikes()) }
[ "function addStudentLikesToAll(mentors,likes){\n for(i = 0; i < mentors.length; i++){\n mentors[i].addstdlikes(likes);\n\n } \n}", "function addStudentLikesGlo(mentors){\n for (let index = 0; index < mentors.length; index++) {\n mentors[index].studentLikes += 1\n \n }\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get INSPECTION DETAILS Table
function getInspectionDetailsTable() { var result; result = { table: { widths: [100, '*', 25, '*', 40, '*'], body: [ [{ text: 'INSPECTION DETAILS', style: 'tableHeader', colSpan: 6, bo...
[ "function getInspectionDetailsTable() {\n var result;\n result = {\n table: {\n widths: [100, '*', 25, '*', 40, '*'],\n body: [\n [{\n text: 'INSPECTION DETAILS',\n style: 'tableHeader',\n colSpan: 6,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
actually creates the sell form
function createSellform(d,item,quant,descid,hash,itemimage,textdesc) { var form = document.createElement('form'); form.setAttribute('name','sellform'); form.setAttribute('action','managestore.php'); form.setAttribute('method','post'); form.setAttribute('style','display:inline;'); var input = doc...
[ "function createTrade() {\n if(vm.selectedSellSymbol && vm.selectedBuySymbol && vm.sellAmount > 0.0 && vm.rate){\n fixerservice.postTrade(vm.selectedSellSymbol, vm.sellAmount, vm.selectedBuySymbol, vm.rate)\n .then(postTradeSuccess);\n }else if(vm.sellAmount <= 0.0){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the percent of `values` that aren't null example: calcCompletedPercent([false, null, 3, 5]) > 75
function calcCompletedPercent(values) { return Math.floor(100 * values.reduce((total, v) => v == null ? total : total + 1, 0) / values.length); }
[ "function boolpercent(arr) {\n\tcount = 0;\n\tfor (i=0; i<arr.length; i++) {\n\t\tif (arr[i]) { count++; } \n\t}\n\treturn 100* count / arr.length;\n}", "countPercentage() {\n this.flatValues = this.coordinatesValues.reduce(function (\n accumulator,\n currentValue\n ) {\n return accumulator.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get matching queue number
function getClientsQueueNumber(clientID){ for (var i=0; i < clients.length; i++) { if (clients[i].cookie === clientID) { return clients[i].groupNumber; } } return 0; }
[ "function getQueuedNum() {\n let num = 0;\n for (const bookmark of bookmarkQueue) {\n if (bookmark[1]) {\n num++;\n }\n }\n return num;\n}", "function getPlaceInQueue(queue, id) {\n let result = 0;\n\n queue.forEach((order) => {\n if (order.id <= id) {\n result++;\n }\n });\n\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all indexes that are compatible with the given one(s)
function findCompatibles(indexSequences) { var str = ""; if(typeof indexSequences == "string") { indexSequences = [indexSequences]; } else { indexSequences = flattenArray(indexSequences); } for(var index in indexReference) { if(evaluateIndexes(indexSequences.concat(indexReference[index]))) { str += index ...
[ "ensureAllIndexes(force = false) {\n let key;\n const bIndices = this.binaryIndices;\n for (key in bIndices) {\n if (bIndices[key] !== undefined) {\n this.ensureIndex(key, force);\n }\n }\n }", "validateIndex() {\n // if (this.filter && !isEmp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`addPrefixes` adds the prefixes to the output stream
addPrefixes(prefixes, done) { var prefixIRIs = this._prefixIRIs, hasPrefixes = false; for (var prefix in prefixes) { var iri = prefixes[prefix]; if (typeof iri !== 'string') iri = iri.value; hasPrefixes = true; // Finish a possible pending quad if (this._subject !== null) { ...
[ "addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs)\n return done && done();\n\n // Write all new prefixes\n let hasPrefixes = false;\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'stri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST Github hook Accepts a webhook call from Github details a Git Push. Analyses the push and sets a status to indicate if the branch if belongs to has a fixup commit 'success' indicates no fixups 'failure' indicates branch contains a fixup
async function postHook (req, res, next) { try { const eventType = get(req, 'headers.x-github-event', 'n/a') if (eventType !== 'push') { log({ text: `Invalid event, ignoring: ${eventType}` }) return res.status(202).send('Invalid event, ignoring') } const pushData = req.body const { d...
[ "function handleGithubPush(req, res, state) {\n var db = assert(state.db);\n var github = assert(state.github);\n var trustedAuthors = assert(state.githubTrustedAuthors);\n var allowedRepos = assert(state.githubRepos);\n\n // Careful to avoid automatic test runs unless repo/author is\n // whitelis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the currently selected search engine
get selectedEngine() { // Open drop down which updates the list of search engines var state = this.enginesDropDownOpen; this.enginesDropDownOpen = true; var engine = this.getElement({type: "engine", subtype: "selected", value: "true"}); this._controller.waitForElement(engine, TIMEOUT); this....
[ "get currentEngine() {\n if (SearchService.currentEngine !== null) {\n return new SearchEngine(SearchService.currentEngine);\n }\n return null;\n }", "get defaultEngine() {\n if (SearchService.defaultEngine !== null) {\n return new SearchEngine(SearchService.defaultEngine);\n }\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draws an image and moves it according to the camera location for a parallax effect
function drawInParallax(buffer, img, x, y, parallax) { var par = parallax * 0.9; if (!parallaxFactor) par = 0; if (img.complete) { if (time - prevTime > 80) buffer.drawImage(img, 0, 0, img.width, img.height, Math.round(x + camera.x * par), Math.round(y + camera.y * par), img.width, img.height); else ...
[ "function drawInParallaxPlus(buffer, img, x, y, parallaxX, parallaxY) {\n\t\tvar parX = parallaxX * 0.9;\n\t\tvar parY = parallaxY * 0.9;\n\t\tif (!parallaxFactor) {\n\t\t\tparX = 0;\n\t\t\tparY = 0;\n\t\t}\n\t\tif (img.complete) {\n\t\t\tif (time - prevTime > 70)\n\t\t\t\tbuffer.drawImage(img, Math.round(x + camer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask the browser for the latitude and longitude First tries IPbased location, then geolocation (requires elevated permissions)
function getLocation() { if (navigator.geolocation) { requestGeoLocation(); } else { showStatus("Sorry, your browser is unsupported."); } }
[ "function getLocation() {\n navigator.geolocation.getCurrentPosition(blockPage, showError);\n}", "function getLocation() {\n window.navigator.geolocation.getCurrentPosition((location) => {\n userLat = location.coords.latitude;\n userLon = location.coords.longitude;\n checkParkCoord(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processAttempt Rellena las tablas intermedias y agrega los datos de las unidades.
function processData(unit) { if (!unit) { log("Warning processData: Parameter unit required"); return; } log("Processing unit: " + unit.id); var ud = unitsData[unit.id]; if (!ud) { return; // No data to process ...
[ "$_makeAttemptData() {\n const data = {\n attemptsAllowed: this.attemptsAllowed,\n attempts: this.attempts,\n correct: this.correct,\n completed: this.completed\n }\n this.attemptDataKeysLocal.forEach(k => data[k] = this[k])\n if (this.attemptDataKeys) {\n this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a hexjson grid with the layout and dimensions of the given hexjson
function getGridForHexJSON(hexjson) { // Create a new HexJSON object for the grid var grid = {}; grid.layout = hexjson.layout; grid.hexes = {}; // Get the hex objects from the hexjson as an array var hexes = []; Object.keys(hexjson.hexes).forEach(function (key) { hexes.push(hexjson.hexes[key]); });...
[ "function getGridForHexJSON (hexjson) {\n\t\t// Create a new HexJSON object for the grid\n\t\tvar grid = {};\n\t\tgrid.layout = hexjson.layout;\n\t\tgrid.hexes = {};\n\n\t\t// Get the hex objects from the hexjson as an array\n\t\tvar hexes = [];\n\n\t\tObject.keys(hexjson.hexes).forEach(function (key) {\n\t\t\thexe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to assert that provided names are valid. Copyright (c) 2015, Facebook, Inc. All rights reserved. This source code is licensed under the BSDstyle license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory...
function assertValidName(name) { (0, _invariant2.default)(NAME_RX.test(name), 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "' + name + '" does not.'); }
[ "function assertValidName(name) {\n (0, _invariant2.default)(NAME_RX.test(name), 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"' + name + '\" does not.');\n}", "function assertValidName(name) {\n (0, _jsutilsInvariant2['default'])(NAME_RX.test(name), 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"' + n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Devolve a diagonal esquerda da matriz num array unidimensional
function DiagonalEsquerda(tabuleiro){ var x = new Array(MAX); for(var i = 0; i < MAX; i++) { x[i]= tabuleiro[i][i]; } return x; }// fim da diagonalesquerda***************************************************************
[ "static diag(arr) {\n let dim = arr.length;\n let diag = NMatrix.zeros(dim);\n for(let i = 0; i < dim; i++) {\n diag.set(i, i, arr[i]);\n }\n return diag;\n }", "function diagonals(matrix){ \n let firstDignal = 0;\n let secDignal = 0; \n for(let i=0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
componentDidUpdate() checks the current location pathname against the previous if it doesn't match, recall the updatePictures again, based on the new pathname
componentDidUpdate(prevProps, prevState) { let regex = /^\// if(this.props.location.pathname !== prevProps.location.pathname) { let newSearchTerm = this.props.location.pathname.replace(regex,"") this.updatePictures(newSearchTerm); } }
[ "componentDidUpdate(prevProps) {\r\n if (this.props.location.key !== prevProps.location.key) {\r\n this.fetchPhotos(this.props.match.params.searchName);\r\n }\r\n }", "componentDidUpdate(prevProps) {\n\t\tconst { match, history, displayCurrentImage, images } = this.props;\n\t\tlet inde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
turns off keyboard shortcuts, used when the user is using the keyboard to edit or type in a class name
function turnOnShortcuts(){ if (_via_changing_class){ return; } _via_is_user_adding_attribute_name = false; _via_is_user_updating_attribute_value = false; _via_is_user_updating_attribute_name = false; }
[ "function unsetHotKeys() {\n hotkeys.del('esc');\n hotkeys.del('right');\n hotkeys.del('left');\n }", "function unsetHotKeys() {\n\t hotkeys.del('esc');\n\t hotkeys.del('right');\n\t hotkeys.del('left');\n\t }", "function _disable_keyboard_navigation() {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Editar uma proposta no historico de endosso
function editHistorico(){ submitForm($('#formHistorico').get(0), getContextApp()+'/proposta/editar.action', false); }
[ "function editVenueMeta(theId) {\n\tvar currentVenue = window.currentVenues[theId];\n\tvar startTime = convertTimeStringToHours($(\"#editVenue #timepickerStart\").val());\n\tvar endTime = convertTimeStringToHours($(\"#editVenue #timepickerEnd\").val());\n\tcurrentVenue.timeStart = $(\"#editVenue #timepickerStart\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decrease function will update state and udpate quantity to the localStorage
function decrease() { var holdCount2 = count - 1; if(holdCount2 >= 0){ setCount(holdCount2); var holdItem2 = props; window.localStorage.setItem(JSON.stringify(holdItem2), holdCount2); cartContext.setCartTotal(calTotal()); }else{ console.log("You can't order negative amount of p...
[ "function decrement() {\n setQuantity(+quantity - 1)\n }", "decrement(itemData) {\n if (itemData.quantity == 0) return;\n itemData.quantity -= 1\n this.props.setItemQuantity(itemData);\n }", "DecrementQuantity() {\n this.quantity--;\n this.UpdateQuantityLabel();\n this.UpdatePric...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to display the beer's information
function displayBeers() { // Get the div by ID and output the beer informations document.getElementById("beerName").innerHTML = "<br><strong>" + beerProducts[currentIndex].name + "</strong><br>"; document.getElementById("beerImage").src = beerProducts[currentIndex].image_url; }
[ "function displayBeers(contents, brewery_id, breweryClass){\n var info = JSON.parse(contents);\n if(info.data === undefined){\n $('.'+breweryClass+'-list').append('<li class=\"noBeers\">There were no beers found in the databased that are brewed by this brewery.</li>');\n }else{\n for(var j = 0; j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the name/subscript "px" to a number
function AddPx(num) { return String(num) + "px"; }
[ "function maybeAddPx (name, value) {\n return (typeof value === 'number' && !cssNumber[$.hyphenate(name)]) ? value + 'px' : value;\n }", "function makeStylePx(number){\n var tmpNumber = number.toString();\n var tmpEnding = \"px\";\n var tmpString = tmpNumber.concat(tmpEnding);\n return tmpString\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds members to the game array of associated patterns
function createGameToPatternRelations(){ Games.forEach(function(game){ game.LinkedPatterns = Patterns.filter(pattern => pattern.PatternsLinks.some(pLink => pLink.To == game.name)) }); }
[ "function addMatchesArray(farm){\n\tfor ( var animal in farm) {\n\t\tfarm[animal].matches = [];\n\t}\n}", "addPatternToMatch(key, i, p) {\n\t\tthis.matchList[key] =\n\t\t\t(this.matchList[key] !== undefined ? \n\t\t\t\t(this.matchList[key].patterns.push(p), this.matchList[key]) :\n\t\t\t\t{input: i, patterns: [p]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to swap position of elements in an array
function swap(array, posA, posB) { var temp = array[posA]; array[posA] = array[posB]; array[posB] = temp; }
[ "function swap(array, posA, posB) {\n var temp = array[posA]; \n array[posA] = array[posB]; \n array[posB] = temp; \n }", "function swap(arr, pos1, pos2)\n {\n\n var tempElement =0;\n tempElement=arr[pos1];\n arr[pos1] = arr[pos2];\n arr[pos2] = tempElement;\n\n }", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Below code shows on clicking View Details , we should see job description with Apply button
async clickJobViewDetails(jobTitle) { await this.driver.sleep(3000); const jobTitleElement = await this.driver.findElement(By.linkText(jobTitle)); const parentListElement = await jobTitleElement.findElement(By.xpath("./../../..")); return await parentListElement.findElement(By.xpath('//a[@class="button butt...
[ "editWorkAndEducation(){\n\t\tresources.workAndEducationTab().click();\n\t}", "function showDescriptionModal(job_id) {\n description = $('#'+job_id).find('.job_description').html();\n $('#description_modal .modal-message').val(description);\n $('#description_modal').addClass('is-active');\n}", "_handleButton...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the current document focus.
function clearDocumentFocus(){ setContextURL(baseURL + "clearDocumentFocus"); }
[ "defocus() {\n // Give the document focus\n window.focus();\n\n // Remove focus from any focused element\n if (document.activeElement) {\n document.activeElement.blur();\n }\n }", "function clearActiveDocument()\n {\n _activeDocument = null;\n }", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the frequency in hertz of a given piano key
function getFreq(key) { return Math.pow(2, (key-49)/12) * 440; }
[ "function getFreq(key) {\n return Math.pow(2, (key-49)/12) * 440;\n }", "static get _frequencies() {\n const map = { };\n let lix = 0;\n const octaves = [1, 2, 3, 4, 5, 6, 7];\n const letters = ['cn', 'c#', 'dn', 'd#', 'en', 'fn', 'f#', 'gn', 'g#', 'an', 'a#', 'bn'];\n\n const jus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return a response until the copy is complete.
copyFromURL(copySource, options) { const operationArguments = { copySource, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyFromURLOperationSpec); }
[ "copyFromURL(copySource, options) {\n return this.client.sendOperationRequest({ copySource, options }, copyFromURLOperationSpec);\n }", "copyTo(url, shouldOverWrite = true) {\n return spPost(this.clone(File, `copyTo(strnewurl='${escapeQueryStrValue(url)}',boverwrite=${shouldOverWrite})`));\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set to true to use cache False to disable
@bind setUseCache(value) { this.cache = value }
[ "static enableCache() {\n cacheEnabled = true;\n }", "static disableCache() {\n cacheEnabled = false;\n }", "cacheEnable() {\n this.cache = new Map();\n }", "setEnableCache(enableCache) {\n this.enableCache = enableCache;\n }", "get isFromCache() {\n return this._isFromCache;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search Spotify API for album tracks.
async function searchAlbumTracks (album) { const spotify = createSpotify() // Set comparison threshold. // @url https://www.npmjs.com/package/string-similarity const threshold = 0.75 const compare = (a, b) => similarity.compareTwoStrings(a, b) > threshold try { const query = `album:${album.album} ar...
[ "function searchSpotify() {\r\n\t\tSpotify.search(searchInput, 'album', $scope.options).then(function (data) {\r\n\t\t\tconsole.log(\"albums: \" + JSON.stringify(data));\r\n\t\t\t$scope.searchResults = data.albums.items;\r\n\t\t});\r\n\t}", "function searchSong(param) {\n spotify.search({ type: 'track', query: p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scroll automatically to filter in 3 transitionTime ms
scrollToFilter() { const targetPositionX = dom.filterContainer.offsetTop; setTimeout(() => { animatedScrollTo({ to: targetPositionX + 15, easing: easeInOutBack, duration: 3 * this.transitionTime, }); }, this.transitionTime); }
[ "function filterScroll() {\n\tvar thisFilter = $('.team-filter-scroll');\n\tvar thisFilterUl = thisFilter.find('ul');\n\tvar thW = 0;\n\t\n\tthisFilterUl.find('li').each(function(){\n\t\tthW+=$(this).outerWidth();\n\t});\n\tthisFilter.mousemove(function(e){\n\t\tvar blW = thisFilter.outerWidth();\n\t\tif(thW > blW)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
displays the keys from the Array as Buttons
function displayKeys(id){ var thekeys = $("#thekeys"); for (var i = 0; i < recipes[id].elements_key.length; i++){ var container = $('<p>').html( '<button type="button" id="_' + recipes[id].elements_key[i] + '" class="input-key btn btn-default btn-lg">' + getKeyDisplayFormat(recipes[id].elements_key[i]...
[ "function createButtons() {\n let html = '';\n for (const letter of alphabet) {\n html += `<button class=\"key\" id=\"${letter}\">${letter}</button>`;\n }\n document.getElementById('keyboard').innerHTML = html;\n }", "function displayKeyBoardButtonsValues(){\n // initi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store Coordinates (startLat, startLng, destLat, destLng)
async function setCoordinates(startLat, startLng, destLat, destLng) { try { await AsyncStorage.setItem("startLat", startLat); await AsyncStorage.setItem("startLng", startLng); await AsyncStorage.setItem("destLat", destLat); await AsyncStorage.setItem("destLng", destLng); dispatch({ ...
[ "setCordinates(lat1, lng1, lat2, lng2) {\n this.currCordinates = [{ //origin\n lat: this.convrtDegToRedian(lat1),\n lng: this.convrtDegToRedian(lng1)\n }, { //destination\n lat: this.convrtDegToRedian(lat2),\n lng: this.convrtDegToRedian(lng2)\n }];\n }", "setDestinationCoordinates(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates if the step element is an action and a dependent action
updateDependentActionStatus() { if (SharedElementHelpers.IsAction(this)) { this.isDependentAction = this.checkIfActionIsDependent(); this.analyticsManager.process(); this.notifyDependantActionStatusUpdate(this.isDependentAction); } }
[ "function checkForActions(xml_data, stepId, taskId){\n \n $(xml_data).find(\"step\").each(function() {\n if($(this).find(\"step-id\").text() == stepId){\n $(this).find(\"sub-step\").each(function() { \n if($(this).find(\"value\").text() == taskId){\n // when landing in here, I've go...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new ECHOTreeMap.
function ECHOTreeMap(instanceId, resourceType, refid, data) { if (refid == null) { refid = null; } if (data == null) { data = null; } ECHOTreeMap.__super__.constructor.call(this, instanceId, resourceType, refid); this._isSubtree = refid != null; if (data != null...
[ "function SHAMapTreeNode() { }", "function treeInit() {\n buildTreefromMap();\n }", "function buildMapper() {\n return new TreeMapperJustForLeaves(identity, identity, identity);\n}", "function createMap() {\n return new MapCtr();\n }", "function SearchableMap(tree, prefix) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shuffles the array of tetrominoes via FisherYates.
shuffleTetrominoes() { Utilities.shuffleArray(this.tetrominoArray) }
[ "function fisherYates(array, seed) {\n var _a;\n var length = array.length;\n // need to clone array or we'd be editing original as we goo\n var shuffled = array.slice();\n for (var i = (length - 1); i > 0; i -= 1) {\n var randomIndex = void 0;\n if (seed) {\n randomIndex = M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
new data into firstmeta
function newMeta(x) { var id = x.id; var ethnicity = x.ethnicity; var gender = x.gender; var age = x.age; var location = x.location; }
[ "set add_meta(v){\n this._meta = Object.assign(this._meta,v);\n this.backup_meta();\n }", "_appendSpecificMetaData(meta) {\n return meta;\n }", "function initializeFirstSongInPlaylistMetaData() {\n /*\n Iterates over all of the playlists setting the meta data for the\n first song.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save click upgrades to local storage
function saveClickUpgrades() { //save to local storage window.localStorage.setItem('player.clickInventory', JSON.stringify(player.clickInventory)); }
[ "function save () {\n svl.storage.set(\"tracker\", actions);\n }", "function saveButtons() {\n $(\".svBtn\").on(\"click\", function (e) {\n e.preventDefault();\n var hour = e.target.id.substring(4); //img-18\n var text = $(\"#text-\" + hour);\n localStorage.setItem(hour, text.val(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method for placing dots in a 2D rectangular space evenness: varies from 01 0 is purely random 1 uses a hybrid approach, first creating a sparse structure of random dots, then progressively filling in the spaces between dots (01) first creates an evenish structure of dots, then places additional dots using "dartthrowi...
function DotGrid(bounds, approxQueries, evenness) { var x0 = bounds.xmin; var y0 = bounds.ymin; var w = bounds.width(); var h = bounds.height(); var k = 0.5 * (evenness - 1) + 1; // k varies from 0.5 to 1 var approxCells = approxQueries * 0.9 * k; var cols = Math.round(Math.sqrt(approxCells...
[ "createDots(){\n var dotPositions = this.getDotPositions();\n var initialPosition;\n\n // Create the dots\n // 3% of the dots created are super dots\n dotPositions.forEach( dotPosition => {\n initialPosition = [dotPosition[\"colIx\"], dotPosition[\"rowIx\"]];\n this.dots.push(\n new ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the entire list of emoji's from Git
function getemojilist(callback) { _get('getemojilist', undefined, callback); }
[ "get emojis() {\n return List.from(Modules.EmojiUtils.getGuildEmoji(this.id), e => new Emoji(e));\n }", "function getEmojiCodepoints(data) {\n\treturn data.filter(d => d.property === 'Emoji').map(d => d.codepoint);\n}", "function findEmojiIcons() {\n var currentSection = targetSection;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Here we have the function named subtractUSD, it targets the event (which is the click to purchase the upgrade)
function subtractUSD(event) { // The variable elem is set to target the event var elem = event.target; //Here we declare that the variable 'dollar' is set to the .dataset value of the dollar let dollar = parseInt(elem.dataset.dollar); //Here we declare the varibable hash, which is attached to the elemen...
[ "function buyClickUpgrade(upgrade) {\n\tif (upgrade.price > totalFunds) {\n\t\talert(\"You cannot afford this upgrade\");\n\t}\n\telse {\n\t\ttotalFunds = Math.round(totalFunds - upgrade.price);\n\t\tperClick = perClick + upgrade.value;\n\t\tupgrade.num ++;\n\t\tupgrade.price = upgrade.price * upgrade.mult;\n\t\tdo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
INIT LOCAL INPUT BOX FUNCTIONS
function initLocalInputBoxes() { }
[ "function initLocalInputBoxes() {\n\n\t\t// COPY HOVER SETTINGS ON ELEMENT IF NEEDED\n\t\tRVS.DOC.on('copyhoversettings',function(e,a) {\n\t\t\tif (RVS.selLayers.length===0) return;\n\t\t\tif (a!==undefined && a===\"checkiffirst\" && RVS.L[RVS.selLayers[0]].hover.copied===true) return;\n\t\t\tfor (var li in RVS.sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the new champion to the datbase using the existing stats If stats are null, then generate values and update the authenticated user's champions by adding this new one
async function handleAdd(champion) { clearTimeout(resetCreateTimeout); try { if (user.info.champions.length < 3) { setCreateChamp({ ...createChamp, championAdded: true }); resetCreateStates(); ...
[ "setChampion(championID) {\n myChampion = champions[championID]\n }", "function updateChampion(champ) {\n currChampionName = champ.replace(\"+ \", \"\"); // set champ name\n // Get average\n var avgDataRow = avg_data.filter(function(d) { return d.champ == currChampionName; })[0];\n currAvg = +(avg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the real index of cluster in the variable: clusters.clusters
getClusterIndex ( clustersOrder, i ) { if ( this.params.type !== "gridbasedClientServer" ) { // considering all cells as clusters, where some cells are empty return clustersOrder[i]; } return i; }
[ "getClusterLength() {\n return this.clusterList.length;\n }", "get numberCacheClusters() {\n return this.getNumberAttribute('number_cache_clusters');\n }", "getTotalClusters() {\r\n return this.clusters_.length;\r\n }", "getTotalClusters() {\n return this.clusters_.length;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the last item of the Stack
get lastItem() { return stack[stack.length - 1]; }
[ "last() {\n return this.items[this.items.length - 1]\n }", "viewLastElement() {\n // Check If Stack Is Not Empty\n if (!this.isEmpty()) {\n return this.storage[this.storage.length - 1];\n }\n else {\n console.log('Stack is empty');\n }\n }", "pop() {\n const poppedItem =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to obtain fallback url in case a pdf is loaded
function getFallbackURL(url) { return (url.search(/\/pdf\//i) != -1) ? url.replace(/\/pdf\//i,"/abstract/") : null; }
[ "function getFallbackURL(url) {\n return (url.search(/\\/doi\\/pdf\\//i) != -1) ? url.replace(/\\/doi\\/pdf\\//i,\"/doi/abs/\") : null;\n }", "async function getExistingPdfUrl(raw_url) {\n // PDF as indicated by file extension\n const isPDFPattern = /\\.pdf$/;\n if (raw_url.match(isPDFPattern)) {\n log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Author : Kpotard date : 22/01/2019 openlayers 2 / GeoExt 1 / Ext3.4.1
function init() { map = new OpenLayers.Map("map-id"); // définition du fond de carte const wmsLayer = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0?", {layers: 'basic'}); // définition de la couche vecteur data let data = new OpenLayers.Layer.Vector("Da...
[ "function GeoHelper(){}", "function OL_map() {\r\n\r\n //New OS DataHub/Maps API code\r\n var apiKey = 'MQO2QVcsCR3qhKi8Xjw1TSUJbCmP5Zq3';\r\n var serviceUrl = 'https://api.os.uk/maps/raster/v1/zxy';\r\n\r\n // Setup the EPSG:27700 (British National Grid) projection.\r\n proj4.defs(\"EPSG:27700\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }