query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Draw the left arrow
function drawArrowLeft(xStart, yStart) { drawLine(xStart, yStart, xStart-20, yStart+30, context); drawLine(xStart-20, yStart+30, xStart, yStart+60, context); drawLine(xStart+20, yStart, xStart, yStart+30, context); drawLine(xStart, yStart+30, xStart+20, yStart+60, context); }
[ "displayLeft() {\n image(arrowImg[3], this.arrowLeftX, this.arrowLeftY, this.size, this.size)\n }", "function drawLeftTri () {\n\tvar tip = \"Previous Year\";\n\tdrawAnImage (0, svgHeight - arrowSize-barPadding, arrowSize, arrowSize, \"../Resources/arrows/LeftArrow.png\")\n\t\t.on('click', function(){\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a fallback item because we just got a miss. usually to avoid redirect loops
fallbackItemSlug() { if (this.manifest && this.activeItem) { if ( this.activeManifestIndex > 0 && this.manifest.items[this.activeManifestIndex - 1] ) { return this.manifest.items[this.activeManifestIndex - 1].slug; } else if ( this.activeManifestIndex < this.manifes...
[ "function doFallback() {\n\t\t\t\tif ( !Util.containsText( fallbackStr ) ) { return $element.empty() };\n\t\t\t\t$element.html( makeListItem( fallbackStr ) );\n\t\t\t}", "function maybeNot(item, action) {\n if(item) {\n return;\n }\n return action();\n}", "function maybe(item, action) {\n if(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 455 Given a simple math expression as a string, neatly format it as an equation.
function formatMath(expr) { return `${expr} = ${eval(expr.replace("x", "*"))}` }
[ "function evaluateExpression(equation, inputs) {\n //I'm pretty sure this removes all whitespace.\n equation = equation.replace(/\\s/g, \"\");\n //if equation is an input (like 't'), return the value for that input.\n if (equation in inputs) {\n return inputs[equation];\n }\n //make each va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asks user if another action is desired
function promptAnotherAction() { inquirer.prompt([ // Prompt user for yes or no { type: "confirm", message: "Would you like to perform another action?", name: "anotherAction", }, ]).then(function (inquirerResponse) { // If yes to prompt ...
[ "function afterAction() {\n console.log(\"\\n\");\n\n inquirer.prompt([\n {\n type: \"list\",\n message: \"Would you like to perform another action?\",\n choices: [\"Yes\", \"No\"],\n name: \"action\"\n }\n ]).then(function (response) {\n swi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will open the modal that will give the user a form for importing a public key.
function openImportPubKeyModal() { $uibModal.open({ templateUrl: '/components/profile/importPubKeyModal.html', backdrop: true, windowClass: 'modal', controller: 'ImportPubKeyModalController as modal' }).result.finally(function() { ...
[ "function importPubKey() {\n var newPubKey = new PubKeys(\n {raw_key: ctrl.raw_key, self_signature: ctrl.self_signature}\n );\n newPubKey.$save(\n function(newPubKey_) {\n raiseAlert('success', '', 'Public key saved successfully');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to restrict the bounds of the given preference:
function restrictBounds(value) { /*jshint validthis:true */ value = Number(value) || 0; if (value > this.max) { return this.max; } if (value < this.min) { return this.min; } return value; }
[ "function restrictToRange(val,min,max) {\r\n if (val < min) return min;\r\n if (val > max) return max;\r\n return val;\r\n }", "function bound (n, min, max) {\n return Math.min(max, Math.max(min, n))\n}", "function keepInRange(lower, upper, value) {\r\n if(value < lower){\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change the active point in carousel
_carouselPointActiver() { const i = Math.ceil(this.currentSlide / this.slideItems); this.activePoint = i; this.cdr.markForCheck(); }
[ "function setCurrentDotActive($dot) {\n $sliderDots.removeClass('active');\n $dot.addClass('slider-dot active');\n}", "function setActivePage() {\n\t\t\tvar $carouselPage = $pager.find('.carousel-page');\n\t\t\t$carouselPage.each(function () {\n\t\t\t\t$(this).removeClass('current-page');\n\t\t\t\tif ($(this).i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
===================================================== = Convert object to URI serialized key value string = =====================================================
function uriSerialize(obj, prefix) { var str = []; for(var p in obj) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push(typeof v == "object" ? uriSerialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } return str.join("&"); }
[ "function uriToJson(){\n URI.prototype.toJSON = function() {\n return this.toString();\n };\n}", "function urlEncodePair(key, value, str) {\n if (value instanceof Array) {\n value.forEach(function (item) {\n str.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(item...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new class stmts based on the given data.
function createClassStmt(config) { var parentArgs = config.parentArgs || []; var superCtorStmts = config.parent ? [SUPER_EXPR.callFn(parentArgs).toStmt()] : []; var builder = concatClassBuilderParts(Array.isArray(config.builders) ? config.builders : [config.builders]); var ctor = new ClassMe...
[ "enterClassInstanceCreationExpression(ctx) {\n\t}", "static create(data) {\n\n //Array?\n if (Array.isArray(data)) {\n return data\n .filter(item => !!item)\n .map(item => this.create(item));\n }\n\n //Already instance of LogAppRequest class?\n if (data instanceof LogAppRequest) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new TextureAssetTask object
function TextureAssetTask(/** * Defines the name of the task */name,/** * Defines the location of the file to load */url,/** * Defines if mipmap should not be generated (default is false) */noMipmap,/** * Defines if texture must be inverted on Y axis (defau...
[ "function CubeTextureAssetTask(/**\n * Defines the name of the task\n */name,/**\n * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n */url,/**\n * Defines the extensions to use to load files ([\"_px...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a function to accept head pointer and a value and check for occurance in the list
function listHas(head, value){ let result = false if (!head){ result = `The list is empty` } else { while (head){ if (head.val == value){ result = true break } head = head.next } } return result }
[ "contains(value){\n var runner = this.top;\n while(runner != null){\n if(runner.value == value){\n return true;\n }\n runner = runner.next;\n }\n return false;\n }", "deleteAtHead() {\n \n try {\n \n //check if there is a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alias of getQTIAncestor for assessmentSection.
function getQTISection(elem) { return getQTIAncestor(elem, "assessmentSection"); }
[ "get parent() {\n return tag.configure(ContentType(this, \"parent\"), \"ct.parent\");\n }", "function selectAncestor(elem, type) {\n type = type.toLowerCase();\n if (elem.parentNode === null) {\n console.log('No more parents');\n return undefined;\n }\n var tagName = elem.parentNod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fn for ticking simulation updates x && y position of each circle
function simTicked(){ let theCircles = d3.selectAll('.medal') //update x && y of each circle theCircles.attrs({ cx: d => d.x, cy: d => d.y }) }
[ "updateCircle() {\n const obj = this.newPos(); // Returns the random values as an object\n // Updates the circles css styling\n this.div.style.left = `${obj.posX}px`;\n this.div.style.bottom = `${obj.posY}px`;\n this.div.style.width = `${obj.radius}rem`;\n this.div.style.he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomly choose an action from actions, but don't go back to where the previous action (a) brought you from...
function chooseAction(actions, a) { var dir = Math.floor(Math.random()*actions.length); var nextA = actions[dir]; if (a=="UP" && nextA == "DOWN") { // remove "DOWN" and try again... actions.splice(dir,1); return chooseAction(actions, a); } else if (a=="DOWN" && nextA == "UP") { actions.splice(dir,1); retu...
[ "function getRandomAction(db){\n const allPossible = Felt.possibleActions(db);\n return randNth(allPossible);\n}", "function getRandomAction(db, allActions){\n let allPossible = possibleActions(db, allActions);\n return randNth(allPossible);\n}", "function battleRound(){\n chooseAction1();\n chooseAct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `TlsValidationContextAcmTrustProperty`
function CfnVirtualNode_TlsValidationContextAcmTrustPropertyValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); if (typeof properties !== 'object') { errors.collect(new cdk.ValidationResult('Expected an o...
[ "function CfnVirtualGateway_VirtualGatewayTlsValidationContextAcmTrustPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.Val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CREATED: Henry Karagory 03/12/2018 Description: Parsing function corresponding to the expr nonterminal symbol. Involved in mutual recursion with calculateTerm and calculateFactor functions. parameters: tokenQueue: A queue of tokens with expr as a prefix. trigMode: A string giving the interpretation of the argument to t...
function calculateExpressionRecursive(tokenQueue, trigMode){ var exprValue = calculateTerm(tokenQueue, trigMode); // If a string is returned then it is an error message, return the message. if(typeof exprValue == "string"){ return exprValue; } while(tokenQueue[0] == "+" || tokenQueue[0] ==...
[ "function calculateExpression(tokenQueue, trigMode=\"rad\"){\n var exprValue = calculateExpressionRecursive(tokenQueue, trigMode);\n if(tokenQueue.length != 0){\n return \"ERR: SYNTAX\";\n }\n\n return exprValue;\n}", "function calculateFactor(tokenQueue, trigMode) {\n console.log(tokenQueue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the weather icon for the forecasted divs depending on the weather status returned in the response
function determineIcon(weatherStatus, day) { if (weatherStatus == "Clear") { $(`#day${day}-icon`).addClass("fas fa-sun"); } else if (weatherStatus == "Thunderstorm") { $(`#day${day}-icon`).addClass("fas fa-bolt"); } else if (wea...
[ "function weatherIcon(weather) {\n const mainweather = weather.weather[0].main;\n const weather_icon = weather.weather[0].icon;\n let icon = \"\";\n\n switch (mainweather) {\n case \"Rain\":\n if (weather_icon === \"09d\") {\n icon += \"weather_icons/rainy-7.svg\";\n } else {\n icon +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Closes all the currently open drawers.
closeAllOpenDrawers() { var i = 0; var index = 0; while (i < this.closet_drawers_ids.length) { var drawer_front_face = this.group.getObjectById(this.closet_drawers_ids[5 * index + 1]); if (drawer_front_face.position.z > -50) { var drawer_base_face = this.group.getObjectById(this.closet_d...
[ "closeAll() {\n this.openDialogs.forEach(ref => ref.close());\n }", "closeAllWindows() {\n let windows = this.getInterestingWindows();\n for (let i = 0; i < windows.length; i++)\n windows[i].delete(global.get_current_time());\n }", "function closeAllInfoWindows() {\n\tfor (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Augments the original componentDidMount with instance tracking.
function proxiedComponentDidMount() { mountedInstances.push(this); if (typeof current.componentDidMount === 'function') { return current.componentDidMount.apply(this, arguments); } }
[ "render() {\n this.mounted = true\n this.logger('display')\n this.componentDidMount()\n }", "componentDidMount() {\n this._isMounted = true;\n this.loadRecommendedItems();\n }", "componentWillMount() {\n try {\n this.initApplication(function(err, context) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setting some defaults for each slider
function sliderDefaults() { $(".product-slider").each( function(index, value) { $(this).children().children(".slide-wrapper").children().children().first().addClass("active"); $(this).children().children(".lead").children().children(".left").addClass("disabled"); $(this).children().children(".slid...
[ "function initialSliderValues() {\n\t// set initial values for config\n\tupdateSliderValue('cannyConfigThreshold1Slider',\n\t\t\t'cannyConfigThreshold1Textbox');\n\tupdateSliderValue('cannyConfigThreshold2Slider',\n\t\t\t'cannyConfigThreshold2Textbox');\n\tupdateSliderValue('houghConfigRhoSlider', 'houghConfigRhoTe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to add the a beer to the counter
function addBeerCounter(val){ var qty = beer; var new_qty = parseInt(qty, 10) + val; if (new_qty < 0) { new_qty = 0; } beer = new_qty; return new_qty; }
[ "function addToHumanScore() {\n humanScore++\n $('#humanScore').text(humanScore)\n }", "function countSuitsBlazerWwiPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerWWI = instantObj.noOfSuitsBlazerWWI + 1;\n\t\t\tcountTotalBill();\n\t\t}", "function insertItemCounter () {\n let newh2 = document.createElement('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns pixel ratio of the current screen (used on retina displays).
function getPixelRatio() { var ratio = window.devicePixelRatio || 1; return ratio; }
[ "screenCoordToRatio(x, y) {\n x = x / this.canvas.width;\n y = y / this.canvas.height;\n return {x:x, y:y};\n }", "function getScreenWidth(percentage = 100) {\r\n return screenWidth * (percentage / 100);\r\n}", "function BAGetZoomRatio() {\n\tvar per = 1;\n\tif (BA.ua.isIE70) {\n\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checkFileReaderSyncSupport: Create a temporary worker and see if FileReaderSync exists
function checkFileReaderSyncSupport() { var worker = makeWorker(syncDetectionScript); if (worker) { worker.onmessage =function(e) { FileReaderSyncSupport = e.data; }; worker.postMessage({}); } }
[ "function checkForFileReaderSupport() {\n\tif (window.File && window.FileReader && window.FileList && window.Blob) {\n\t\tconsole.log(\"File API's supported\");\n\t\treturn true;\n\t} else {\n\t\t$('body').html(\n\t\t\t\"The Files APIs are not fully supported in this browser. Try using a newer browser\"\n\t\t);\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LINES DRAWN Add Line To Lines Drawn
addLineToLinesDrawn() { if (!Array.isArray(this._currentLineCoordinates)) throw Error('Line coordinates must be an array') this._linesDrawn.push(this._currentLineCoordinates) }
[ "addDeletedLineFromLinesErasedToLinesDrawn() {\n if (this.getLinesErased().length) {\n\n const lineCoordinates = this._deleteLastLineFromLinesErased()\n\n if (!Array.isArray(lineCoordinates)) throw Error('Line coordinates must be an array')\n\n this._linesDrawn.push(lineCoord...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the dice rolling
startRoll() { die.startRolling(); hideGameplayButtons(); }
[ "function rollDice(){\n var randomNum = getRandomInt(1,6);\n setDice(randomNum);\n // moveCoin(randomNum);\n }", "function rollDice() {\n $('.roll-dice').on('click', function() {\n roll(); \n }); \n}", "function randomizeDice(){\n diceRoll[0] = Math.floor( Math.random() * 6 )+1;\n diceR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
date validation for safari
function validateDateSafari(date) { let pattern = /([0-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/; if (!pattern.test(date)) { showMessageModal("Fehler bei der Eingabe", "Invalides Datum: Datum sollte im YYYY-MM-DD Format und valide sein!"); return false; } return true; }
[ "check_date(date){\n \n if(typeof(date) == 'undefined' || date == null)\n return false;\n \n return moment(date, 'YYYY-MM-DD').isValid();\n }", "function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
doubleClick to show dialog (edit res)
function doubleClick(e) { edit_reservation($(this)); }
[ "function handleDoubleClick(componentRec)\n{\n\treturn editCFC();\n}", "function jsDblClick() {\n if (!clicked) {\n clicked = true;\n return true;\n }\n else {\n return false;\n }\n }", "function editItemOnDblClick(event) {\n var input = $(this).find(\"input[type=t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the sum of age ratios (function above)
getSumOfAgeRatios() { let sum = 0; for (let ageGroup of this.ageGroups) { sum += this.getAgeRatio(ageGroup); } return sum; }
[ "function calculateage(yr, mon, day, unit, indecimal)\r\n{\r\n var one_day = 1000*60*60*24;\r\n var one_month = 1000*60*60*24*30;\r\n var one_year = 1000*60*60*24*30*12;\r\n\r\n var today = new Date();\r\n var pastdate = new Date(yr, mon-1, day);\r\n\r\n var countunit = unit;\r\n var decimals =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates duplicates for all meshes to be used as outlines, hidden by default
function createOutlines() { for (var i in scenes) { var c = scenes[i].children; for (var j in c) { if (c[j].type == "Mesh") { var outlineGeometry = c[j].geometry; var outlineMaterial = new THREE.MeshBasicMaterial( { color: 0x00FF00, side: THREE.BackSide, polygonOffset: true, polygonOffse...
[ "calculateMeshOutlines() {\n for (\n let vertexIndex = 0;\n vertexIndex < this.verticies.length;\n vertexIndex++\n ) {\n if (!this.checkedVerticies[vertexIndex]) {\n let newOutlineVertex = this.getConnectedOutlineVertex(vertexIndex);\n if (newOutlineVertex !== -1) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger the given range of options in response to user interaction. Should only be called in multiselection mode.
triggerRange(trigger, from, to, on) { var _a; if (this.disabled || (trigger && trigger.disabled)) { return; } this._lastTriggered = trigger; const isEqual = (_a = this.compareWith) !== null && _a !== void 0 ? _a : Object.is; const updateValues = [...this.optio...
[ "triggerOption(option) {\n if (option && !option.disabled) {\n this._lastTriggered = option;\n const changed = this.multiple\n ? this.selectionModel.toggle(option.value)\n : this.selectionModel.select(option.value);\n if (changed) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render subtree in target path
function renderSubtree(subtree, targetPath, level) { var i; //render documents for(i = 0; i < subtree.documents.length; i++) { var document = subtree.documents[i]; var documentName = getDocumentName(document); var documentPath = path.join(targetPath, documentName); renderDo...
[ "function fullpath(d, idx) {\r\n idx = idx || 0;\r\n curPath.push(d);\r\n return (\r\n d.parent ? fullpath(d.parent, curPath.length) : '') +\r\n '/<span class=\"nodepath'+(d.data.name === root.data.name ? ' highlight' : '')+\r\n '\" data-sel=\"'+ idx +'\" title=\"Set Root to '+ d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
processPollMini() / update all pollmini tags
function updatePollMini(pollURL) { if (!updateInProgress) { updateInProgress = true; rootDivs = document.getElementsByName("pollMini"); if (rootDivs.length == 0) { rootDivs = new Array; var div_attr; var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++...
[ "_updateAllowedTags() {\n // Update the list of auto-created tags.\n this.autoTags = this._calculateAutoAllowedTags(\n this.userTags,\n this.newFeatures,\n );\n\n // Remove any previous auto-created tag message.\n this.$allowedHTMLDescription.find('.editor-update-message').rem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if the left diagonal matches.
function leftDaigonalMatch(){ if(isEmptyRow("square0", "square4","square8")){ isEqual("#square0", "#square4", "#square8"); } }
[ "function is_to_the_left_of_blank(tile) {\n var isLeft = false;\n if (tile.row === blank.row - 1)\n {\n isLeft = true;\n }\n return isLeft;\n}", "function middleRowMatch(){\n\tif(isEmptyRow(\"square3\", \"square4\",\"square5\")){\n\t\tisEqual(\"#square3\", \"#square4\", \"#square5\");\n\t}\n}", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unwrap a value which might be behind a closure (for forward declaration reasons).
function maybeUnwrapFn(value) { if (value instanceof Function) { return value(); } else { return value; } }
[ "function unwrappingAccessor(accessor) {\n if (typeof accessor !== 'function') return accessor;\n return function (feature) {\n return accessor((0, _geojson.unwrapSourceFeature)(feature));\n };\n}", "function unwrap(elem) {\n if (elem) {\n if ( typeof XPCNativeWrapper === 'function' && typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
//////////////// Extra Functions ///////////////////////// ////////////////////////////////////////////////////////// Include the offset in de start and end angle to rotate the Chord diagram clockwise
function startAngle(d) { return d.startAngle + offset; }
[ "setCorrectRotation (raoad) {\r\n var pointBefore = this._lastRoad.children[0].children\r\n\r\n var SlopEndPosition2 = pointBefore[\r\n pointBefore.length - 1\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 1].position)\r\n var SlopEndPosition1 = pointBefore[\r\n pointBefore....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When new thread was created then push new route from route make an update in all component
threadCreated(thread) { const { history, dispatch } = this.props this.setState({thread_id: thread.id}) history.push(`/messages/?thread=${thread.id}`) this.props.threadCreated(thread); }
[ "refresh() {\n const temp = this.routeName;\n\n this.routeName = this.fullRouteName;\n this._super(...arguments);\n this.routeName = temp;\n }", "async [FmConfigActions_1.FmConfigAction.watchRouteChanges]({ dispatch, commit, rootState }, payload) {\n if (index_1.configuration.onRouteChange) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse ical feed, and send data off
function ParseiCalFeed(){ log.info('Parse ical file'); ical.fromURL(config.icalurl, {}, ParseiCalData); //ParseiCalData('',ical.parseFile('/home/jimshoe/dev/makerslocal/eventwitter/calendar.ics.test')); }
[ "function processCal(data,ical_url){\n let result = [];\n for (let k in data){\n let game;\n if (data.hasOwnProperty(k)) {\n let ev = data[k];\n if (ev.summary){\n game = processEvent(ev,ical_url);\n if (game){\n result.push(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers an icon by URL in the specified namespace.
addSvgIconInNamespace(namespace, iconName, url, options) { return this._addSvgIconConfig(namespace, iconName, new SvgIconConfig(url, null, options)); }
[ "static register(namespace, name, value) {\n this.getNamespace(namespace)[name] = () => value\n }", "_renderIcon () {\n let p = this._props,\n svg = document.createElementNS( this.NS, 'svg' ),\n content = `<use xlink:href=\"#${ p.prefix }${ p.shape }-icon-shape\" />`;\n svg.setAttribute(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks each predicate, and runs and removes them if they are true
check() { // For loop to check each predicate for (var i = 0; i < this.predicates.length; i++) { // Reference predicate for index var predicate = this.predicates[i]; // Check the check func of the predicate if (p...
[ "function remove(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> list<a> */ {\n return filter(xs, function(x /* 23638 */ ) {\n return !((pred(x)));\n });\n}", "function _remove(predicate, tree) {\n\tif (isEmpty(tree)) {\n\t\treturn tree;\n\t} else if (R.pipe(R.view(lenses.data), predicate)(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CircularStrip class. Used for the rim sides.
function CircularStrip(location, angle, scale, colour) { this.trs = mult(translate(location), mult(rotate(angle, [1, 0, 0]), scalem(scale))); this.colour = colour; }
[ "function drawMobiusStrip(ctx) {\n // using black stroke color and 1px line width\n ctx.strokeStyle = \"black\";\n ctx.lineWidth = 1;\n // draw a 2D mobius strip cartoon on the canvas\n // that is a 3D mapping representation of the shape\n ctx.beginPath();\n ctx.moveTo(0, 0);\n ctx.lineTo(0, 100);\n ctx.li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ascending Landen transform for real arguments
function ascending_transform(u, m) { var root_m = Math.sqrt(m); var mu = 4 * root_m / Math.pow(1 + root_m, 2); var root_mu1 = (1 - root_m) / (1 + root_m); var v = u / (1 + root_mu1); return { v: v, mu: mu, root_mu1: root_mu1 }; }
[ "reverse() {\n const compareOriginial = this.compare;\n this.compare = (a, b) => compareOriginial(b, a);\n }", "function normL1(x) {\n\treturn x.reduce(function (acc, curr) { \n\t\treturn acc + Math.abs(curr - uniform);\n\t}, 0);\n}", "function complex_ascending_transform(u, m) {\n var root_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
See graph_action.js for schema of data
handle_action(action, data) { switch (action) { case "graph/set_active": this.set_active(data.graph_id); break; case "graph/save": this.save(); break; case "graph/close": this.close(data.graph_id); break; case "graph/remove": ...
[ "function submit() {\n let graph = new Object();\n graph['vertices'] = digraph.vertices;\n graph['matrix'] = digraph.matrix;\n\n $.ajax({\n url: '/input/submit/',\n type: 'POST',\n data: JSON.stringify(graph),\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n async: false,\n success...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contacts the info service and displays pattern details
function patternInfo(pattern) { // Set spinner setSpinner(); // Update breadcrumbs var path = { step1 : { 'state' : 'inactive', 'title' : 'info demo', 'attributes' : { 'data-method' : 'load-service', 'data-service' : 'info' ...
[ "function _getInfo(content) {\n $(\"#hoverwarning\").css(\"display\", \"none\");\n\n contentInfoModel.isArtistInfoVisible(true);\n contentInfoModel.artistName(content.name);\n contentInfoModel.spotifyLink(content.external_urls.spotify);\n contentInfoModel.image(getSuitableImage(co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
readonly attribute AUTF8String mailboxType;
get mailboxType() { return this._mailboxType; }
[ "msg_type_str(id) {\n const text = Nano.EnumMsgtype[id];\n if (text) {\n return '<small>0x' + this.dec2hex(id) + ' - ' + text.toLowerCase() + '</small>';\n }\n else {\n return \"unknown\";\n }\n }", "get protocolType() {\n return this.getStringAtt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use eosjs rpc to get abi by account name
function getAbi(account){ try { return eos.getAbi(account).then(function(abi) { return abi; }); } catch (err) { let errorMessage = `Get Abi Controller Error: ${err.message}`; return errorMessage; } }
[ "function getContractABI(contractJSON) {\n return contractJSON[\"abi\"];\n}", "async _getVaultLabel(args, vaultAddress) {\n const vaultAbi = [{\"inputs\":[{\"internalType\":\"contract IStrategy\",\"name\":\"_strategy\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the post to the user's clipboard
copyToClipboard(e){ e.preventDefault(); var copyTextarea = document.getElementById('post'); copyTextarea.select(); try{ document.execCommand('copy'); console.log("Post copied succesfully."); } catch(err){ console.log("Unable to copy the...
[ "function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attaches an event listener function in a browser neutral fashion. elementId The ID of the element. eventType The type of event, such as "click", "mouseover". listener The event handler function.
function attachEventListener(elementId, eventType, listener) { var e = document.getElementById(elementId); if (e.addEventListener) { //Most modern browsers e.addEventListener(eventType, listener, false); } else { //Old IE e.attachEvent("on" + eventType, listener); } }
[ "function addEventListener(element, event, listener) {\n\t\tif (element.addEventListener) {\n\t\t\telement.addEventListener(event, listener, false);\n\t\t}\n\t\telse if (element.attachEvent) {\n\t\t\telement.attachEvent(\"on\" + event, listener);\n\t\t}\n\t}", "function addMapListener(element, eventType, callBack...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manages the browser's navigation URL. Returns methods and fields used to manipulate the browser's URL. url: The current URL in the browser's navigation bar. location: The current window.location. path: Information on the path part of the URL. components: Array of strings, which are the paths in the URL. first: String t...
function navigationUrl() { function sync() { var components = window.location.pathname.split("/").filter(function (i) { return i !== ""; }); var queryParams = window.location.search.substring(1).split("&").filter(function (i) { return i !== ""; }); var params = []; for (var i = 0; i ...
[ "function createBrowserHistory() {\n\t var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];\n\n\t !_ExecutionEnvironment.canUseDOM ? (undefined) !== 'production' ? _invariant2['default'](false, 'Browser history needs a DOM') : _invariant2['default'](false) : undefined;\n\n\t var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All action when current player is unselected
function unselectCurrentPlayer () { that.isSelected = false; this.unhighlightStates(); this.removeClass('selected'); }
[ "function playerButtonRemove(){\n buttons.forEach(selection => selection.removeEventListener('click', playerSelection));\n buttons.forEach(selection => selection.classList.remove(\"playerimg\"))\n\n //Rock.removeEventListener(\"click\", playerSelection);\n //Paper.removeEventListener(\"click\", playerSe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send the error in the development mode
function sendErrorDev(err, res) { res.status(err.statusCode).json({ status: err.status, message: err.message, stack: err.stack, error: err, }); }
[ "function developmentErrorHandler(err, req, res, next) {\n if (err !== null) {\n console.log(err);\n }\n res.status(err.status || 500);\n res.render('error', {\n message: err.message,\n error: err,\n status: err.status\n });\n }", "error() {\n const isAbsolute = this.options...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update warehouse by id
function updateWarehouse(id, data) { const updatedWarehouse = { id: id, name: data.name, address: data.address, city: data.city, country: data.country, contact: data.contact, }; console.log(id); const warehouseArray = warehouseList(); const warehouseIndex = warehouseArray.findIndex( ...
[ "updateItemsStock(id, stock) {\n return this.database\n .executeSql(\"UPDATE items SET stock = ? WHERE items_id = ?\", [stock, id])\n .then((_) => {\n this.loadItems();\n });\n }", "function update(id, property){\n return db('property').where('id', '=', id).up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We then do a loop which will go through the array arr, if the num is smaller than or equal to an element in the arr we break and return i which is the index the number would have been placed into
function getIndexToIns(arr, num) { arr.sort(function(a, b) { return a - b; }); for (var i = 0; i < arr.length; i++) { if (num <= arr[i]) { break; } } return i; }
[ "function getIndexToIns(arr, num) {\n var newArray = arr.concat([num]);\n newArray.sort((a,b) => a-b);\n return newArray.indexOf(num);\n}", "function missingNum(arr) {\n\tfor (let number=1; number<=10; number++) {\n\t\tif (! arr.includes(number)) return number;\n\t}\n}", "function search(arr, val) {\n\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove $words from $text
function removewords(text, words){ if(isUndefined(words)){words = wordstoignore;} text = text.toLowerCase().split(" "); for(var i=text.length-1; i>-1; i--){ if(words.indexOf(text[i]) > -1){ removeindex(text, i); } } text = removemultiples(text.join(" "), " ", " "); r...
[ "words(content) {\n //@TODO\n let content_array = content.split(/\\s+/);\n const normalized_content = content_array.map((w)=>normalize(w));\n const words = normalized_content.filter((w) => !this.noise_w_set.has(w)); \n return words;\n }", "function removeWord () {\n firstWord.remove();\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logout => Delete Token in setup Axios
function logout() { window.localStorage.removeItem("authToken"); delete axios.defaults.headers["Authorization"]; }
[ "function logout() {\n // clear the token\n AuthToken.setToken();\n }", "function postLogoutNoToken(){\n\treturn request(app)\n\t.post(\"/api/v1/auth/logout\")\t\t\t\n\t.send({})\n\t.set(\"x-access-token\", \"invalid token\")\n\t.then(function(res) {\n\t\texpect(res).to.have.status(40...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find number of all ClassDay objects in model
get numClassDays() { if(this.classDays && this.classDays.length) return this.classDays.length; return 0; }
[ "function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }", "function getCountedObjec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup the 'Add to Quotsy' context menu
function setupContextMenu(){ chrome.contextMenus.create({ "title": "Add to Quotsy", "contexts": ["selection"], "onclick": QuoteManager.addQuote }) }
[ "function AddCustomMenuItems(menu) {\r\n menu.AddItem(strHelp, 0, OnMenuClicked);\r\n}", "function deleteTripContextMenu() {\n confirmDeleteTrips();\n}", "function setAppMenu() {\n let menuTemplate = [\n {\n label: appName,\n role: 'window',\n submenu: [\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the update button to explain 4 icons need to be selected and disable it.
function saltReset() { saltUpdateButton.innerHTML = 'Choose 4 Icons'; saltUpdateButton.setAttribute('disabled', ''); }
[ "function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function sendDataStaff(checkedTrain, checkedEmployee, checkedDay, functionSelection, staffId) it is a function that sets all request parameters for sending to the servlet with url 'staff' and generates data in JSON format
function sendDataStaff(checkedTrain, checkedEmployee, checkedDay, functionSelection, staffId) { let xhr = new XMLHttpRequest(); let json; switch (functionSelection) { case 1: xhr.open('PUT', 'staff', true); json = JSON.stringify( { train_id : checkedTr...
[ "function sendDataTimetable(checkedTrain, checkedStation, checkedDay, inputArrivalTime, inputDepartureTime,\n functionSelection, timetableId) {\n let xhr = new XMLHttpRequest();\n let json;\n switch (functionSelection) {\n case 1: xhr.open('PUT', 'time_table', true);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method takes in the id number of the player you want to deal to and the number of cards (num) you want to deal to them, and it will deal the desired number of cards to that player
deal(id, num) { this.players.forEach(player => { if (player.id === id) { for (let i = 0; i < num; i++) { player.addCard(this.deck.deal()); } break; } }) }
[ "function dealCardsToPlayer(player, numberOfCards = 1) {\n // We want to keep track of how many cards are left to deal if the deck\n // needs to be shuffled.\n for (let cardsLeftToDeal = numberOfCards; cardsLeftToDeal >= 1; cardsLeftToDeal--) {\n const cardToDeal = rooms[player.roomCode].deck.drawPile.shift()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================================================= Option ============================================================================= MppOptions
function MppOptions() { throw new Error('This is a static class'); }
[ "get options() {\n if (typeof MI === 'undefined') {\n window.MI = { options: {} };\n }\n const { options } = MI;\n return options;\n }", "function Workman_Options() {\n this.initialize.apply(this, arguments);\n}", "options(params) {\n if(!params) {\n return {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update task in todoist
function task_update_todoist(task_name, project_id, todoist_api_token) { todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671' return todoist_add_tasks_ajax(todoist_api_token, { "content": task_name, "project_id": project_id }, 'item_update') }
[ "update(_task) {\n const { id, task, date, process } = _task\n let sql = `UPDATE tasks\n SET task = ?,\n date = ?,\n process = ?\n WHERE id = ?`;\n return this.dao.run(sql, [task, date, process, id])\n }", "taskUpdate(token, taskID, name, dueDate) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cleanOptions Remove options that will be processed interally from the data.
function cleanOptions(content, options) { var lines = content.match(/[^\r\n]+/g); var output = options; var setlist = [""]; var optionsets = {}; optionsets[""] = {}; var i; for (i=0; i<lines.length; i++) { var matches = lines[i].match(/^!!!verovio([^\s]*):\s*(.*)\s*$/); if (!matches) { continue...
[ "_mergeOptions(oldOptions, newOptions) {\n const origKeys = new Set(Object.keys(oldOptions))\n const mergedOptions = { ...oldOptions, ...newOptions }\n\n Object.keys(mergedOptions).forEach( (key) => {\n if (!origKeys.has(key)) {\n console.error(`Unexpected options para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize packed info tables see Gen2.Compactor for how the data is encoded
function h$initInfoTables ( depth // depth in the base chain , funcs // array with all entry functions , objects // array with all the global heap objects , lbls // array with non-haskell labels , infoMeta // packed ...
[ "function codec_setup_info(p) {\n p = p||{};\n \n // /* Vorbis supports only short and long blocks, but allows the\n // encoder to choose the sizes */\n\n // long blocksizes[2];\n\n // /* modes are the primary means of supporting on-the-fly different\n // blocksizes, different channel mappings (LR or M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attemps to retrieves the server session. If there is no session, redirects with HTTP 401 and an error message
function getSession(request, response) { var session = request.session; console.log("SESSION: ", session); if (!session.sfdcAuth) { response.status(401).send('No active session'); return null; } return session; }
[ "function ssoSession(req, res, next, config) {\n var ssoToken = 'ssoSessionId'; // name of sso session ID parameter\n\n // if we have a session, everything is fine\n console.log('check if session is there ...'); // FIXME debugging output\n // check if session is there\n if (req.session && req.session.username)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a type string corresponds to a module type. A custom module can be specified by picking a module type which is not included.
function isModuleType(type) { return ['chat', 'task', 'cal', 'poll'].includes(type); }
[ "function validateType(tstr){\n let retVal = Type.NOT_A_TYPE;\n if(tstr != Type.NOT_A_TYPE){\n for(const t in Type){\n // If a valid type (not NOT_A_TYPE) and symbol string matches given string:\n if(Type[t] && String(Type[t]).slice(7, -1) == tstr){\n retVal = Type[t];\n break;\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
groups items by year given array of items using _.groupBy() BUT returns in a more usable format where year = year and items = array of projects for that year
function groupItemsByYear(selectItems) { var grouped = _.groupBy(selectItems, 'year'); return _.map(grouped, function(items, key) { return { year: key, items: items }; }); }
[ "listYearly() {\n const tenYearBefore = dateService.getYearsBefore(10);\n return this.trafficRepository.getYearlyData(tenYearBefore)\n .then(data => {\n data = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(tenYearBefore.getFullYear(), 10);\n const val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assigns the students to a seat by row. In addition, this is currently used to evenly space out students 1 row and 1 seat apart from each other.
function assignSeatsByRow(seed, colOffset, rowOffset) { var leftStudents = [] // an array to hold the students who are left handed var rightStudents = [] // an array to hold the students who are right handed var tempList = students; var rightIndex = 0; // index containing how many students have been assigned in the...
[ "function seatsInTheater(nCols, nRows, col, row) {\n let blockedAcross = (nCols - col + 1)\n let blockedBehind = (nRows - row)\n return blockedAcross * blockedBehind\n}", "function randomOccupiedSeats() {\r\n for (i = 0; i < 6; i++) {\r\n let randomRow = Math.floor(Math.random() * (6 - 0 + 1)) + 0;\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page.
function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; /...
[ "function Datepick() {\r\n\tthis._uuid = new Date().getTime(); // Unique identifier seed\r\n\tthis._curInst = null; // The current instance in use\r\n\tthis._keyEvent = false; // If the last event was a key event\r\n\tthis._disabledInputs = []; // List of date picker inputs that have been disabled\r\n\tthis._datepi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The getAttachments function callback , this function calls the getAttachmentBody() and gets the downloadable link element, and appends to the iframe body of the email
function attachmentCallBack( filename, mimeType, attachment ) { var ifrm = $('#message-iframe-'+ message.id)[0].contentWindow.document; var link = getAttachmentBody( attachment, filename, mimeType ); $( link ).insertAfter( $( ifrm.body ) ); }
[ "readAttachment(){\n return new Promise((resolve, reject) => {\n\n //attachment url \n // GET https://graph.microsoft.com/v1.0/users/{userid}/messages/{msgid}/attachments/\n this.options.url=this.prop_recv.url+ this.prop_recv.accountId + '/messages/' + this.messageId + '/atta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves file tree from local storage
function getLocalStorage() { try { if (localStorage) { var store = localStorage.getItem('fileTree'); if (!!store) { fileTree = JSON.parse(store); my.init(); } } } catch (err) { //L...
[ "function retrievePaths(){\n\tif (typeof(Storage) !== \"undefined\"){\n\t\tvar paths = JSON.parse(localStorage.getItem(APP_PREFIX))\n\t\tfor (var i = 0; i<paths.length; i++){\n\t\t\tvar current = new Path(paths[i]);\n\t\t\tpathList.push(current);\n\t\t\tpathNames.push(current.title);\n\t\t}\n\t}else{\n\t\tconsole.l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds a node by text and type and then displays the children of the given node
function showNodeChildrenByText(nodeText, nodeType, index) { // figure logic in here to check if already expanded. Only perfom following if now already expanded if (typeof index == "undefined") { index = 0; } switch (nodeType) { case 'folder': return waitTillElementVisible(f...
[ "function showNodeChildrenByTextAndIndex(nodeText, nodeType, index) {\n // figure logic in here to check if already expanded. Only perfom following if now already expanded\n switch (nodeType) {\n case 'folder':\n return waitTillElementVisible(fileTree.expandCollapseFolderNode(nodeText)).then...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
interval sequence that steps generator through
function transitionSequence() { let interval = setInterval(() => { while (tranGen.done !== true) { tranGen.next() return } clearInterval(interval) }, 500) }
[ "function creerSequence(init,step){\n\tinit -= step;\n\n\treturn () => {\n\t\treturn init += step;\n\t}\n}", "getIntervalSteps (start, end, asIndex) {\n\t\tlet totalSteps = this.getTotalStepCount();\n\t\tlet ref = this.tzero;\n\t\tstart -= ref;\n\t\tstart /= (60 * 1000);\n\t\tstart = Math.ceil(start / this.getSte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a Plane for THREEx.HtmlMixer// //////////////////////////////////////////////////////////////////////////////// create the iframe element Creation des plans des pages web.
function addPageWeb(link, page_nb, out_of) { var url = link; var domElement = document.createElement('iframe') domElement.src = url domElement.style.border = 'none' // create the plane var mixerPlane = new THREEx.HtmlMixer.Plane(mixerContext, domElement) mixerPlane.object3d.scale.multiplyScalar(2) var parent...
[ "newPlotWidgetIframe(name, url) {\n var that = this;\n G.addWidget(1).then(w => {\n w.setName(name);\n\n w.$el.append(\"<iframe src='\" + url + \"' width='100%' height='100%s'/>\");\n that.widgets.push(w);\n w.showHistoryIcon(false);\n w.showHelpI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load list employee local from file json
function funcLoadAllEmployeesFromLocal(employees) { var doc = new XMLHttpRequest(); doc.onreadystatechange = function() { if (doc.readyState == XMLHttpRequest.HEADERS_RECEIVED) { } else if (doc.readyState == XMLHttpRequest.DONE) { var objectArray = JSON.parse(doc.responseText)...
[ "function LoadJson(){}", "static loadRoles() {\n let roleList = [];\n let dataFile = fs.readFileSync('./data/roles.json', 'utf8');\n if (dataFile === '') return roleList;\n\n let roleData = JSON.parse(dataFile);\n\n roleData.forEach((element) => {\n roleList.push(\n new Role(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Info about a transaction
getTransactionInfo(transaction) { return new Promise(async (resolve, reject) => { try { const res = await fetch(this.explorerUrl + "/api/tx/" + transaction); const data = await res.text(); resolve(data); }catch(err) { ...
[ "function getGoogleTransactionInfo() {\n return {\n countryCode: 'US',\n currencyCode: 'USD',\n totalPriceStatus: 'FINAL',\n // set to cart total\n totalPrice: '500.00'\n };\n}", "async txDetails (txid) {\n try {\n wlogger.silly('Entering slp.txDetails().')\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Post the display name change to the server.
function changeDisplayName(){ if ($('#displayName').val() !== '' ) { OC.msg.startSaving('#displaynameform .msg'); // Serialize the data var post = $( "#displaynameform" ).serialize(); // Ajax foo $.post( 'ajax/changedisplayname.php', post, function(data){ if( data...
[ "function setDisplayName(displayName){\n //Save display name into the storage\n localStorage.setItem('displayName',displayName);\n}", "function name_updater(){\n console.log(\"I entered her hihihi\");\n if(oldview_number != view_number){ //Cond...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the directory where the wiki pages are stored
function pageDir() { //global config; return (config.GENERAL.PAGES_DIRECTORY); }
[ "function getCurrentDirectory() {\r\n\treturn File.GetAbsolutePathName(\".\");\r\n}", "function wikiReadDir(path)\n{\n return eval( FILE.scandir(path) ); \n}", "getProjectsHtmlFolder(): string {\n let projectsPathHtml = join(this.projectFolder, 'html');\n if (!existsSync(projectsPathHtml)) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs each of the post walk plugins specified in the grunt config
function runPostWalkPlugins(options){ var cntxt = options.context || {}; mergeContexts(cntxt); }
[ "function runDuringWalkPlugins(filePath){\n\tvar contents;\n\t//Plugins will not process dot files\n\tif (util.getFileName(filePath).charAt(0) !== \".\") {\n\t\tif (p.extname(filePath) === '.json') {\n\t\t\t//Read the file contents so each plugin doesn't have to\n\t\t\tcontents = grunt.file.readJSON(filePath);\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handler for mouse scroll events Switches workspace by scrolling over the dock
_onScrollEvent(actor, event) { if (this._settings.get_boolean('disable-scroll') && this._autohideStatus && this._slider.slidex == 0 && // Need to check the slidex for partially showing dock (this._dockState == DockState.HIDDEN || this._dockState == DockState.HIDING)) ...
[ "function scrollViews(){\r\n var scroll = 2;\r\n $('#main_area, .ui_city_overview').bind('mousewheel', function(e){\r\n if($('.island_view').hasClass('checked')){\r\n scroll = 2;\r\n } else if($('.strategic_map').hasClass('checked')){\r\n scroll = 1;\r\n } else {\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select TWAIN Source (Scanner) and Acquire Image
function acquireImage() { var DWObject = gWebTwain.getInstance(); if (DWObject) { if (DWObject.SourceCount > 0) { var vDWTSource = document.getElementById("source"); if (vDWTSource) { if (vDWTSource) DWObject.SelectSourceByIndex(vDWTSource.sel...
[ "function source_onchange() {\n var DWObject = gWebTwain.getInstance();\n if (DWObject) {\n var vDWTSource = document.getElementById(\"source\");\n if (vDWTSource) {\n\n if (vDWTSource)\n DWObject.SelectSourceByIndex(vDWTSource.selectedIndex);\n else\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setting the customer Name
setCustomerName(name) { this.customerName = name; }
[ "getCustomerName() {\n return this.customerName;\n }", "function setClientNameUI(clientName) {\n var div = document.getElementById('client-name');\n div.innerHTML = 'Your client name: <strong>' + clientName +\n '</strong>';\n }", "function changeCustomer(v){\r\n\r\n\t\t//var x = document.getElemen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets whether trying to add the second number to the first is lossy (inexact). The first number is meant to be an accumulated result.
function isLossyToAdd(accum, num) { if (num === 0) { return false; } var lowBit = lowestBit(num); var added = accum + lowBit; if (added === accum) { return true; } if (added - lowBit !== accum) { return true; } return false; }
[ "function checkTwoGivenIntegers(int1, int2) {\n let sum = 50\n if ((sum === int1 + int2) || ((int1 === 50) || (int2 === 50))) {\n return true\n } else {\n return false\n }\n}", "function shouldPerformCalculation() {\n if ($.isNumeric(firstOperand) && $.isNumeric(secondOperand)) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether the update needs to happen to the page object (the page doesn't have any annotations or the /Annots object is just an array. Or if the /Annots is an indirect object and that is what needs to be updated. Calls the determineAnnotationStrings method to actually create the file update text.
async addAnnotation(annotation) { return new Promise(async (resolve, reject) => { try { logger.info(`${this.name}: adding annotation`) const currentByteLength = Buffer.byteLength(this.data) const page = this.pages[annotation.pageNumber] let newXrefTable = ['0 1', '0000000000 65...
[ "function saveAnnotationsInDoc() {\n var annotationsInCache = JSON.parse(CacheService.getPrivateCache().get('annotations'));\n var documentProperties = PropertiesService.getDocumentProperties();\n var annotationsInDoc = documentProperties.getProperty('ANNOTATIONS');\n var annotations_type = JSON.parse(documentP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
in_theater_mode Returns true if we're in Theater mode.
function in_theater_mode() { return (document.getElementById("player-theater-container") && document.getElementById("player-theater-container").childElementCount > 0 && !document.fullscreenElement) }
[ "function switchPlayerToTheaterMode() {\n\tif ($(\"div#page\").hasClass(\"watch-non-stage-mode\"))\n\t\t$(\"button.ytp-size-button, div.ytp-size-toggle-large\").click();\n}", "get shouldNightModeStart() {\n const { score, nightMode } = this;\n const { DISTANCE } = GameScene.CONFIG.NIGHTMODE;\n return sco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there's a discount in effect when we first render, immediately apply it
function applyInitialDiscount() { var dis = __defaultDiscount(); if (dis) { // do this after a timeout, because discountApply calls out into parent code, which expects // to have a fully-initialized CheckoutDiscount object at that point. We might be able to ...
[ "calcDiscount() {\n if (this.discount != 0 || this.discount != null) {\n this.discPrice = (1 - this.discount / 100) * this.totalPrice;\n }\n }", "applyDiscount(discount) {\n this.discount = discount;\n this.beveragePrice *= (1 - discount);\n }", "calDiscount(){\n this._discou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
utility function for UI pointing to learning path items
function learningItemsPath(learningPath) { if (learningPath && learningPath.Id) { return $location.path('/LearningPaths/' + learningPath.Id + '/Items'); } else { common.logger.logWarning('invalid item selected', learningPath, controllerId); return ''; } }
[ "function drawControl_path(header_ypos)\r\n{\r\n // draw the feedback panel with an appropriate sized gap\r\n header_ypos += (button_gap);\r\n \r\n // reset button\r\n control_button(\"Reset tree view\",header_ypos,\"viewReset_ns\",null,true);\r\n header_ypos += (button_gap+button_height);\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function selects the next sibling element which isn't a whitespace text node, nor a . It also returns the intervening whitespace.
function nextNonWhitespace(e) { const {nextSibling} = (e instanceof $ ? e[0] : e); if (nextSibling && ((nextSibling instanceof Text && !nextSibling.textContent.trim()) || (nextSibling.tagName || '').toLowerCase() === "br")) { const { whitespace, nextElem } = nextNonWhitespace(nextSibling); return { w...
[ "function next () {\r\n return this.siblings()[this.position() + 1]\r\n}", "function getNextSibling(node, tag){\n\tif (!tag) tag = node.nodeName;\n\ttag = tag.toUpperCase();\n\tvar cont = 20; // Limita o numero de itera��es para evitar sobrecarga no ie\n\twhile (node.nextSibling && node.nextSibling.nodeName && n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================================================= Guardar Items en el carrito Actualizar Disponible
actualizarDisponible(item:Object, cantidad:Number, remover:Boolean = false){ for (let productoLista of this.state.listaCarrito){ if (productoLista.id == item.id){ productoLista.cantidad = cantidad if(productoLista.cantidad == 0 || remover == true){ this.removerItem(item) } ...
[ "itemsChanged() {\n this._processItems();\n }", "completeAllItems() {\n this.items.forEach(item => {\n item.status = 'Completed';\n item.finishedAt = Date.now;\n });\n }", "function salvarItemEstoque() {\n if ($scope.novoItemEstoque.Id > 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implicitly check whether killService was called by checking that the service property was set to undefined.
function killServiceWasCalled() { return plugin.service === undefined; }
[ "serviceStopping(service) {\n\t\tconsole.log(\"MW serviceStopping is fired\", service.name);\n\t}", "isService() {\n\n return this.type == 'service';\n }", "verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new K(q.FAILED_PRECONDITION, \"The client has already been terminated.\");...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes sure the tab key will only focus elements within the current section/slide preventing this way from breaking the page. Based on "Modals and keyboard traps" from
function onTab(e){ var isShiftPressed = e.shiftKey; var activeElement = document.activeElement; var activeSection = $(SECTION_ACTIVE_SEL)[0]; var activeSlide = $(SLIDE_ACTIVE_SEL, activeSection)[0]; var focusableWrapper = activeSlide ? activeSlide : activeSect...
[ "function onTab(e){var isShiftPressed=e.shiftKey;var activeElement=document.activeElement;var focusableElements=getFocusables(getSlideOrSection($(SECTION_ACTIVE_SEL)[0]));function preventAndFocusFirst(e){preventDefault(e);return focusableElements[0]?focusableElements[0].focus():null;}//outside any section or slide?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CLUSTERSTATUS : Get cluster status
clusterstatus(params) { this.options.qs = Object.assign({ action: 'CLUSTERSTATUS', }, params); return this.request(this.options); }
[ "static get STATUS_RUNNING () {\n return 0;\n }", "get status() {\n this._status = getValue(`cmi.objectives.${this.index}.status`);\n return this._status;\n }", "function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(colu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decode t.cn to orginal url using Weibo API parse t.cn urls to complete urls Main function
function decode_sina_urls(urls,callback) { // console.log("go decode"); urls_api=[] for (var i = 0; i < urls.length; i++) { //limit api call to 20 results each if(urls_api.length == urls.length-1 || urls_api.length ==20) { call_sina_api_url(urls, function(long_urls){ callback(long_urls); }); urls_ap...
[ "parse(_stUrl) {\n Url.parse(_stUrl, true);\n }", "function substituteTwitterUrls(text, urls) {\n var restoredText = text;\n urls.forEach(function (urlObj) {\n log.debug(urlObj);\n log.debug('Substituting ' + urlObj.url + ' -> ' + urlObj.expanded_url);\n restored...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : checkDevicesToCreateLink AUTHOR : James Turingan DATE : December 5, 2013 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : create line in devices PARAMETERS : imgId
function checkDevicesToCreateLink(imgId,imgXpos2,imgYpos2){ var flag = dragtoTrash(imgId,imgXpos2,imgYpos2); if(flag == false){ return; } var obj; if(globalInfoType == "JSON"){ var devices = getDevicesNodeJSON(); }else{ var devices =devicesArr; } var allline =[]; for(var i = 0; i < de...
[ "function createDevice(src){\n\tvar devPath = \"Device_\" + deviceCtr;\n\tidsArray = [];\n\tidsArray = getalldevicepath(idsArray);\n\tif(idsArray.length == 0){\n\t\tcreateConfigName(); \n\t}\n\tvar str ='';\n\tif(idsArray.indexOf(devPath) == -1){\n\t\tvar imageObj = new Image();\n\t\tvar srcN = ($(src).attr('src')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Empty Shopping List With User Confirmation
function emptyShoppingList() { if (confirm('Are you sure you want to remove everything from your shopping list?')) { shoppingList = [] updateShoppingListDOM() } }
[ "function displayEmpty() {\n checkoutContainer.empty();\n var messageH2 = $(\"<h2>\");\n messageH2.css({ \"text-align\": \"center\", \"margin-top\": \"50px\" });\n messageH2.html(\"No purchases yet , navigate <a href='/view_products'>here</a> if you wish to purchase a product.\");\n checkou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class to build handlers for `triggers` on behaviors for views
function BehaviorTriggersBuilder(view, behaviors) { this._view = view; this._behaviors = behaviors; this._triggers = {}; }
[ "setupTriggers() {\n this.triggers.forEach((trigger) => {\n trigger.on('TRIGGERED', () => this.enrollIfTriggered());\n trigger.setup();\n });\n }", "_attachViewButtonHandlers(){\n\t\tvar self = this;\n\t\tthis.$viewButton.click(function(){\n\t\t\tself._viewButtonAction();\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Metod returns label for meter data
describeMeterData(meterData = false) { if (!meterData) return 'unknown'; const types = { '06': 'VolumeHeat', '16': 'VolumeCold' } let meterType = types.hasOwnProperty(meterData['deviceType']) ? types[meterData['deviceType']] : "unknown"; return `${meterData['label']} (${met...
[ "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adjust the height of carousel controls to height of images in this carousel
function carouselMakeoversControlsHeight() { // Get the height of first visible image const $carousel = $("#carousel-makeovers"); const carouselImgHeight = $carousel.find(".carousel-item.active") .filter(":visible").first().height(); $carousel.find(".carousel-control-prev, .carousel-control-next")...
[ "function reduce() {\n $(\".carousel-item\").css(\"height\", \"20vh\");\n }", "function setSlidesHeight() {\n let tallest = 0;\n\n $.each(self.find('.walkthrough__slide'), function () {\n tallest = $(this).height() > tallest ? $(this).height() : tallest;\n });\n\n $('.walkthrough__slide...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine two bounds into one, vertically stacking them, getting the maximum combined horizontal extent, and adding vertical padding in between.
function getStackedBounds(rect1, rect2) { var height = rect1.height + this.padding + rect2.height; var maxX = Math.max(rect1.x + rect1.width, rect2.x + rect2.width); var minX = Math.min(rect1.x, rect2.x); return new Rectangle(minX, 0, maxX - minX, height); }
[ "function unionBounds( a, b, target ) {\n\n\tlet aVal, bVal;\n\tfor ( let d = 0; d < 3; d ++ ) {\n\n\t\tconst d3 = d + 3;\n\n\t\t// set the minimum values\n\t\taVal = a[ d ];\n\t\tbVal = b[ d ];\n\t\ttarget[ d ] = aVal < bVal ? aVal : bVal;\n\n\t\t// set the max values\n\t\taVal = a[ d3 ];\n\t\tbVal = b[ d3 ];\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all of my news
static listAllOfMyNews() { return RestService.get('api/news'); }
[ "getNews() {\n\n this.dataBase.findByIndex(\"/news\",\n [\"_id\", \"title\", \"attachment\", \"seoDescription\", \"isMainNews\", \"createDate\", \"writerId\"], \"categoryId\", mvc.routeParams.id).then( data => {\n\n if (data) {\n this.listMainNews = da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for bookshelf return array of bookshelves found
function SearchForBookshelf(keyword, callback) { var bookshelfList = GetAllBookshelves(); var result = []; for (x of bookshelfList) { var str = x.id.toLowerCase(); if (str.indexOf(keyword.toLowerCase()) != -1) { result.push(x); } } return result; }
[ "findBookAndMergeShelf(allBooks, searchBook) {\n const propShelf = 'shelf';\n const userBook = allBooks.find(book => book.id === searchBook.id);\n searchBook[propShelf] = userBook ? userBook[propShelf] : 'none';\n }", "function getAllBooks() {\n return books;\n}", "function retrievedBooks (account, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }