query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Show dialog to edit an article
function showEditDialog(articleId, article) { var dialog = document.getElementById('edit-dialog'); dialog.setAttribute('data-article-id', articleId); var articleTitle = dialog.querySelector('#article-title'); articleTitle.value = article.title; var articleBody = dialog.querySelector('#article-body'); arti...
[ "function Edit (view, clb) {\n\n view.on('edit', function () {\n\n var editNode = document.createElement('div');\n editNode.setAttribute('x-context', 'edit');\n\n ContentElement(\n {\n el: editNode,\n id: view.getId(),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like maybe(), but the callback gets an additional first argument, owner, which may be used to take ownership of objects created by the callback. These will be disposed before each new call to the callback, and when the condition becomes false or the containing DOM gets disposed. maybeOwned(showEditor, (owner) => Editor...
function maybeOwned(boolValueObs, contentFunc) { return domComputedOwned(boolValueObs, (owner, value) => value ? contentFunc(owner, value) : null); }
[ "function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}", "function displayAddOwner(){\n getToken().then((token) => {\n var params = window.location.search + \"&idToken=\" + token;\n\n const displayRequest = new Request(\"/get-role\" + params, {method: \"GET\"});\n fetch(d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A convenience method for reducing by sum(value).
function reduceSum(value) { return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero); }
[ "function sumOfNumbers(arr) {\n function sum(total, num) {\n return total + num;\n }\n return arr.reduce(sum);\n}", "function sum(xs) /* (xs : list<int>) -> int */ {\n return foldl(xs, 0, function(x /* int */ , y /* int */ ) {\n return $std_core._int_add(x,y);\n });\n}", "function redu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the metadata from either a metadata.json or metadata.js file.
function getMetadata(dir) { const json = path.join(dir, 'metadata.json') const js = path.join(dir, 'metadata.js') let opts = {} if (exists(json)) { opts = metadata.sync(json) } else if (exists(js)) { const req = require(path.resolve(js)) // eslint-disable-line if (req !== Object(req)) { thr...
[ "function getMetadata(req, file, cb) {\n let md = _.pick(file,[\"originalname\"]);\n cb(null, md);\n}", "extractMetadata(content) {\n const metadata = {};\n const both = this.splitHeader(content);\n\n // if no content returned, then that means there was no header, and both.header is the content\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a rectangle expressed in SVG element coordinates to coordinates within specific [[Sprite]].
function svgRectToSprite(rect, sprite) { var p1 = svgPointToSprite(rect, sprite); var p2 = svgPointToSprite({ x: rect.x + rect.width, y: rect.y + rect.height }, sprite); return { x: p1.x, y: p1.y, width: p2.x - p1.x, height: p2.y - p1.y }; }
[ "createSvgRectElement(x,y,w,h){const rect=document.createElementNS(svgNs$1,'rect');rect.setAttribute('x',x.toString());rect.setAttribute('y',y.toString());rect.setAttribute('height',w.toString());rect.setAttribute('width',h.toString());rect.setAttribute('fill','#000000');return rect;}", "createSvgRectElement(x,y,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SaveReceipt to local storage
saveReceipt(receipt) { let receipts = this.storage.getItem('receipts') || {}; receipts[receipt.receiptId] = receipt; this.storage.setItem('receipts', receipts); }
[ "function saveCart() {\r\n //console.log(\"saveCart was called\");\r\n\r\n //localStorage.setItem(\"name\", value);\r\n //localStorage.setItem(\"shoppingCart\", cart);\r\n //NOTE local storage is best for strings and numbers\r\n //so going to convert cart into a usable string:\r\n localStorage.set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the state of the text editor at the given position.
getState(editor, position) { return { text: editor.model.value.text, lineHeight: editor.lineHeight, charWidth: editor.charWidth, line: position.line, column: position.column }; }
[ "getCursor(state, from = 0, to) {\n let st = state.doc ? state : EditorState.create({ doc: state })\n if (to == null) to = st.doc.length\n return this.regexp\n ? regexpCursor(this, st, from, to)\n : stringCursor(this, st, from, to)\n }", "function getWordOnPosition(pos)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper which sets the priority of a job.
function changePriority(job, priority) { job._setPriority(priority); }
[ "function setPriority (data, command) {\n if (_.includes(['DISMISS', 'RECALL'], command.type)) {\n command.priority = 3;\n } else if (_.includes(['CHARGE', 'PARRY', 'RETREAT', 'SHIFT'], command.type)) {\n command.priority = 2;\n } else if (command.type === 'SKILL') {\n command.priority = (ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private Functions Generate the enemies
generateEnemies() { // Run the spawn timer this.timer++; if (this.enemies.length == 0) { this.timer += 2; } else if (this.enemies.length == 1) { this.timer += 1; } if ( this.timer >= this.spawnDelay && this.enemies.length < MAX_ENEMIES.value ) { this.createEnem...
[ "function drawEnemies(){\r\n for (var _ = 0; _<4; _++){\r\n var x = Math.random()*(innerWidth-enemy_width);\r\n var y = -enemy_height; \r\n var width = enemy_width;\r\n var height = enemy_height;\r\n var speed = Math.random()*4.5;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
email sms twitter to all contacts
function bEmailSmsTwitterAllCon(senderId,broadCast_sender_email,broadCast_name,broadCast_sender_name,broadCast_message,broadCast_email_subject,x) { $('#takeOneAction').val('false'); var rEmail=1;var rTts=0;var rSms=1;var rTwitter=1; //checks of validations smsCntVal(senderId); generalValidations(broadCast_name,bro...
[ "function bEmailTwitterAllCon(broadCast_sender_email,broadCast_name,broadCast_sender_name,broadCast_message,broadCast_email_subject,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=1;var rTts=0;var rSms=0;var rTwitter=1;\n\t//checks of validations\n\tgeneralValidations(broadCast_name,broadCast_message);\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the colors of the array when an algortihm is suddenly stopped
function resetAfterSuddenIntervalStop(){ for(i = 0; i < barAmount; i++){ intsToSortArray[i].changeColor("#8083c9"); } updateCanvas(); }
[ "function color() {\n\tfor (var i = 0; i < num; i++) {\n\t\tcoloring.push(randomize());\n\t}\n}", "function resetBoard() {\n $tileArray.each(function (i, value) {\n var removeGreen = $($tileArray[i]).removeClass(\"green\");\n turnCounter = 0;\n greenTileCount = 0;\n });\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch the history for a particular channel
async history (channel) { const response = await this.pubnub.history( { channel: channel } ); if (!response || !(response.messages instanceof Array)) { throw 'no messages array'; } return response.messages.map(message => message.entry); }
[ "function pullChannelHistory(token, channel){\nslack.channels.history({token, channel},\n (err, data) => {\n if (err)\n console.log(err)\n else\n var messages = data.messages\n var grabAllText = messages.map((key)=> {\n return (key.text)\n })\n var obj = makeIntoObj(grabAllText)\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a promise which resolves whenever the document readystate is complete or immediately if it is called after page load complete.
function getDocumentReadyComplete() { var document = Api.getInstance().document; return new Promise(function (resolve) { if (document && document.readyState !== 'complete') { var handler_1 = function () { if (document.readyState === 'complete') { doc...
[ "function checkReadyState() {\n\t\t\t\tif (doc.readyState == 'complete') {\n\t\t\t\t\t// Clean-up\n\t\t\t\t\tdoc.detachEvent('onreadystatechange', checkReadyState);\n\t\t\t\t\twin.clearInterval(explorerTimer);\n\t\t\t\t\twin.clearInterval(readyStateTimer);\n\n\t\t\t\t\t// Process function stack\n\t\t\t\t\tprocess()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SECTION E: Helper Functions for Main Objects add/update initial dim variable names to a step object
function updateDimIndVarNames(sO, gO) { // If gO has more dims than sO has recorded, push initial names // and update sO.maxDims // for (var d = sO.dimNameExprs.length; d < gO.numDims; d++) { sO.dimNameExprs.push(getInitialDimNameExpr(d)); } }
[ "function initCurStep() {\r\n\r\n // First set the current step number (before we push below, since\r\n // curStepNum starts from 0\r\n //\r\n CurFuncObj.curStepNum = CurFuncObj.allSteps.length;\r\n //\r\n CurStepObj = new StepObj(); // create a new step\r\n CurFuncObj.allSteps.pus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the new quality returns a number
getNewQuality() { return this.item.quality + 1 * this.getUpdateRatio(); }
[ "updateQuality() {\n const newQuality = this.getNewQuality();\n if (newQuality > 50) return (this.item.quality = 50);\n if (newQuality < 0) return (this.item.quality = 0);\n this.item.quality = newQuality;\n }", "function backstagePassesQuality(currentQuality,days,qualityModifier) {\n\n currentQuali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds container for the chip items
_buildContainer() { this.chipsContainer = document.createElement('div'); this.chipsContainer.classList.add( ...this.config.chipsContainerClasses ); this.element.parentElement.prepend(this.chipsContainer); }
[ "_renderContentContainers() {\n // container of all suggestion elements\n this._suggestionContainer = document.createElement('div');\n this._suggestionContainer.classList.add(this.options.classNames.container);\n\n // child elements that will be populated by consumer\n this._header = document.createE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
making political affiliation have colors
colorizing_parties(party) { let affiliation = "gray"; if (party.includes("Democra")) { affiliation = "blue"; } else if (party.includes("Republ")) { affiliation = "red"; } else if (party.includes("Green")) { affiliation = "green"; } else if (party.includes("Libert")) { affilia...
[ "calculatePickingColors(attribute) {\n attribute.value = this.state.polygonTesselator.pickingColors();\n }", "getRatingColor(rating){\n //Colour mapping to percentage taken from: https://stackoverflow.com/a/17267684\n let a = rating / 100,\n b = (120 - 0) * a,\n c = b + 0;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an api response is accepted 0 valid, 1 invalid
function is_accepted(response) { if (response.token !== undefined) { return true; } if (response.success !== undefined && response.success == true) { return true; } return false; }
[ "function checkAPIReturn(response) {\n if (response.status === 201 ||\n response.status === 200 ||\n response.status === 204 ||\n response.status === 205\n ) {\n return response;\n }\n const error = new Error(response.statusText);\n error.response = response;\n throw error;\n}", "function valida...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A lightweight version of leave which is used with DI. This function only resets `previousOrParentTNode` and `LView` as those are the only properties used with DI (`enterDI()`). NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where as `leaveViewLight` has `LFrame`. This is so ...
function leaveViewLight() { const oldLFrame = instructionState.lFrame; instructionState.lFrame = oldLFrame.parent; oldLFrame.previousOrParentTNode = null; oldLFrame.lView = null; return oldLFrame; }
[ "function _revertToPreviousContext() {\n if(!this.previousContext) {\n return this;\n }\n return this.previousContext.clone();\n }", "leave(player) {\n this.restoreDefaultPlayerStatus(player);\n\n // To avoid abuse we'll kill the player if they had recently fought.\n const deci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalizes options by associating the scheme if user has selected a preset scheme
function normalizeOptions(options) { try { options.schemeDefinition = getSchemeDefinition(options); } catch (e) { console.error(e.message); throw e; // rethrow to stop process } }
[ "function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }", "function determineColorScheme() {\n setColorScheme(userPreferences.colorScheme);\n}", "function resetOptions() {\n\t\t\tif (supported('localStorage')) {\n\t\t\t\tlocalStorage.removeItem('ADI.options');\n\t\t\t}\n\t\t}", "function nor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps a function with additional behavior that does the following: 1. Checks if the result of the function call is in cache using the key 2. If result is in cache, returns that cached object. 3. If not in cache, execute apply on function with arguments and then store result in cache using the passed in key.
function wrap (key) { return function (func) { return function () { var data = cache.get(key); if (angular.isDefined(data)) { return data; } var result = func.apply...
[ "function cached(fn) {\n\t var cache = new Map();\n\t return function cachedFn() {\n\t var key = arguments.length <= 0 ? undefined : arguments[0];\n\t if (!cache.has(key)) cache.set(key, fn.apply(void 0, arguments));\n\t return cache.get(key);\n\t };\n\t }", "function cacheFn(fn) {\n var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the controller state diagnostics. Bit 0 indicates a chain length error, bit 1 indicates an inactivity timeout and bit 2 indicates a loopback test failure.
function YInputChain_get_chainDiags() { var res; // int; if (this._cacheExpiration <= YAPI.GetTickCount()) { if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) { return Y_CHAINDIAGS_INVALID; } } res = this._chainDiags;...
[ "function diagnosticCount(state) {\n let lint = state.field(lintState, false)\n return lint ? lint.diagnostics.size : 0\n }", "getHassState() {\n\t\tlet hass_state = super.getHassState();\n\t\tlet gate_state = this.status;\n\t\thass_state[ 'Uptime' ] = this.secondsToDTHHMMSS( this.getUpTime() );\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether a key exists in the store.
hasKey(key) { return this.store.hasOwnProperty(key); }
[ "function existsInDictionary(key){\n if(contents[key] == undefined)\n return false;\n return true;\n}", "function array_key_exists (key, search) {\n if(!search || (search.constructor !== Array && search.constructor !== Object)){\n return false;\n }\n return search[key] !== undefined;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : clearCanvasHistory AUTHOR :Clarice A. Salanda DATE : March 30, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : clear history PARAMETERS :
function clearCanvasHistory(){ window['variableHistory'+pageCanvas] = []; $("#historyDiv .ulDeco").html(""); $('#clearHistory').hide(); }
[ "clearHistory() {\n this.clear();\n }", "function clearHistory() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy)\n return;\n\n lastResult.copyIn(dummyResult);\n pastQueries.length = 0;\n currentQueryIndex = 0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the selected range and day span in the DateRangePicker.
getSelectedRange() { let range; if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(this.startValue) && !Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(this.endValue)) { range = (Math.round(Math.abs((this.removeTimeValueFromDate...
[ "function create_time_range_inputs(input_args) {\n //\n // defining static inputs\n var date_range_onclick = \"toggle_view_element_button('show_date_range','date_range','Hide Date Range','Show Date Ranage'); toggle_disabled('time-range,st-day,st-month,st-year,en-day,en-month,en-year');\";\n var st_img_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the nearest ref which the HEAD has a parent commit. Checks up to a limit of 100 previous shas.
function getParentBranchForHead(remote) { // Get the latest for the remote. fetchRemote(remote); let headCount = 0; while (headCount < 100) { // Attempt to get the ref on the remote for the sha. const branches = getBranchListForSha(`HEAD~${headCount}`, remote); const ref = getRefFromBranchList(bran...
[ "function getBestParent(point){\n\t\tlet currCost, neighbors = getNeighbors(point)\n\t\treturn neighbors.reduce((best, neighbor) => {\n\t\t\tcurrCost = NODES[neighbor].cost + getDistance(point, NODES[neighbor])\n\t\t\tif(!edgeCollision(point, NODES[neighbor]) && (best[1] === null || currCost < best[1])) best = [nei...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cancel the alarm and notificate user
function cancelAlarm() { chrome.alarms.clear(alarmName); chrome.browserAction.setBadgeText({ text: '' }); chrome.notifications.create('reminder', { type: 'basic', iconUrl: 'img/icon_128.png', title: 'Info:', message: 'Die Erinnerungen sind jetzt deaktiviert!' }, functio...
[ "function onDismissAlarm(event) {\n getAlarmService().dismissAlarm(event.target.item, event.target.alarm);\n}", "cancel(__preserveTimer) {\n if (this.nextSignal) clearTimeout(this.nextSignal);\n\n if (!this.overrideKickedIn) {\n clearTimeout(this.overrideTrigger);\n if (!__preserveTimer) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add platforms to the game
function addPlatforms() { platforms = game.add.physicsGroup(); platforms.create(600, 100, 'platform'); platforms.setAll('body.immovable', true); }
[ "function handlePlatforms() {\n\n for (var i = platforms.length - 1; i >= 0; i--) {\n\t\t// loop through platforms backward\n if (platforms[i].onScreen) {\n platforms[i].draw(player.loc.y);\n\t\t\tif (platforms[i] instanceof Doodler)\n\t\t\t\tplatforms[i].update(); // update Doodlers\n if (platforms[i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
' Name : handleUserResetPwdOnSuccess ' Return type : None ' Input Parameter(s) : jsonResponse ' Purpose : Show reset password Success Response ' History Header : Version Date Developer Name ' Added By : 1.0 15th March,2013 Karuna Mishra '
function handleUserResetPwdOnSuccess(user_reset_pwd_obj) { resetPswd = true; $("#LogingetPwd").hide(); $("#securityQuestionArea").hide(); $("#forcedPwd").hide(); $("#login_txt").val(user_auth_obj.userName);/* Getting user name from USER_AUTH response object and setting it to user name field*/ $("#p...
[ "_handleChangePasswordSuccess(response)\n {\n Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__USER_CHANGED_PASSWORD);\n }", "function sendResetPasswordRequest() {\n if (validateInputFieldOfResetArea()) {\n /* To show the progress bar */\n showProgressBar();\n\n $('#new_pwd'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This returns a component that redirects to '/' if not authenticated, but returns component otherwise
function __authReqWrapper(component) { return ( authToken ? component : () => <Redirect to="/" /> ); }
[ "function AuthRoute({ component: Component, ...rest }) {\n const { user } = useContext(AuthContext); //destructure user from AuthContext \n\n return (\n <Route\n {...rest}\n render={props =>\n user ? <Redirect to=\"/\"/> : <Component {...props}/> /*if user exists (logged in), redirect to home*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function appends the contentSection div with the PHP script for selecting the section to edit on the testimonials page
function showModifyTestimonials() { $('#statusMsg').append(""); $('#contentSection').load('scriptFiles/selectTestimonial.php'); }
[ "function showModifyAbout()\n{\n\t$('#statusMsg').append(\"\");\n\t$('#contentSection').load('scriptFiles/selectAbout.php');\n}", "function loadcontent(section, article) {\n $('#content').html(\"\");\n $('#content').load(pages[section][article][\"url\"], function() {\n renderLinks();\n prettyP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the gtag script element and namespaced data layer based on the codelabs primary GA4 ID.
initializeGa4_() { if (!this.ga4Id_) { return; } // First, set the GTAG data layer before pushing anything to it. window[CODELAB_DATA_LAYER] = window[CODELAB_DATA_LAYER] || []; const firstScriptElement = document.querySelector('script'); const gtagScriptElement = /** @type {!HTMLScriptEl...
[ "function init_() {\n /** @type {Object|undefined} */\n var goog = window['google'];\n\n /** @type {Object|undefined} */\n var gviz = goog && goog['visualization'];\n if (!gviz) {\n /** @type {string} */\n var src = JSAPI_URL + '?autoload=' + encodeURIComponent(JSON.stringify(JSAPI_MODULES)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a matrix multiplication with a FourMatrix
multiply(matrix) { if (matrix != null && matrix instanceof FourMatrix) { var ret = new FourMatrix(); ret._data[0][0] = this._data[0][0] * matrix._data[0][0] + this._data[0][1] * matrix._data[1][0] + this._data[0][2] * matrix._data[2][0] + this._data[0][3] * matrix._data[3][0]; ret._data[0][1] = this._dat...
[ "handleMultiplication() {\n const left = this.getSelectValue(\"multiply\", 1);\n const right = this.getSelectValue(\"multiply\", 2);\n const matrices = this.getMatrices(left, right);\n\n if (matrices !== null) {\n try {\n const product = matrices[0].matrixMultiplication(matric...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return true is d1 >= current date return false id d1 < current date d1 is string only
function getCompareNow( d1,d) { if (d1.length>10) d1 = changeToMM(d1) ; if (d.length>10) d = changeToMM(d) ; // Convert dash to slash d1 = dashToSlash(d1) ; d = dashToSlash(d) ; // Parse the string in DD/MM/YYYY format re = /(\d{1,2})\/(\d{1,2})\/(\d{4})/ var arr = re.exec( d1); //var d = get...
[ "function compareDate(string1, string2) {\n var year1 = string1.substr(0,4);\n var year2 = string2.substr(0,4);\n var month1 = string1.substr(5, 7);\n var month2 = string2.substr(5,7);\n var day1 = string1.substr(8,10);\n var day2 = string2.substr(8,10);\n if (parseInt(year1,10) > parseInt(year...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
displays error message upon uid mismatch
function uidMismatch() { alert("The unique id that you've provided doesn't match the id that have been assigned to your school. Please make sure that you have entered the valid unique id that has been provided to your school by our team."); }
[ "function initializeUserIfNeeded(uid) {\n}", "function _authError() {\n next('Invalid User ID / Password');\n }", "function handleGetUserMediaError (err) {\n util.trace(err)\n\n switch (err.name) {\n case 'NotFoundError':\n alert('Unable to open your call because no camera and/or microphone we...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the built in classes. The SessionWrapper class provides the following methods: getSession() returns a ScriptBasedSession getHttpMessage() returns an HttpMessage getParam(key) returns the parameter associated with the specified required or optional param name The ScriptBasedSession class provides the following methods: ...
function extractWebSession(sessionWrapper) { // You can add any objects to the session as required sessionWrapper.getSession().setValue("value1", "Example 1"); sessionWrapper.getSession().setValue("value2", "Example 2"); }
[ "get session() {\n return this.mSession;\n }", "function setSessionAttribute(name, value) {\n /* just to test callback */\n function test(doc) {\n// alert(\"Server returned: \" + doc.body.innerHTML);\n }\n sendServerMsg(\"/action/sessionAccess?action=setJavaScriptAttribute&name=\" + n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops recording audio from the radio.
function stopRecording() { fmRadio.stopRecording(); }
[ "function stopRecording() {\n isRecording = false;\n\n currentTrack = audioManager.createRecordedTrack(\n data.recorded,\n CHANNEL,\n DRUM_TAG\n );\n }", "function stopRecording() {\n isRecording = false;\n currentTrack = audioManager.createRecordedTrack(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
player logic this runs every time the player performs an action
function runPlayer(action) { let playerBullets = document.getElementById('player-bullets').innerHTML; // keep track of the player's action playerAction = action; // update bullets accordingly if (action === 'SHOOT' && playerBullets > 0) { document.getElementById('player-bullets').innerHTML...
[ "pursueDo() {\n // always try to face\n this.facePlayer();\n this.noAttack();\n // if not close enough to attack, also pursue\n if (!this.alivePlayerInRange(this.getParams().attackRange)) {\n this.moveForward();\n }\n }", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Terminate a thread. Remember to terminate every thread when you are done using it.
terminate(thread) { return thread[_symbols.$terminate](); }
[ "_terminate() {\n if (this._instance) {\n this._instance.close();\n this._instance = null;\n this._stopListeningForTermination();\n this._options.onStop(this);\n }\n\n process.exit();\n }", "function stop() {\n\tif (monitorThread) {\n\t\tclearInterval(monitorThread);\n\t\tmonitorThre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the next tutorial message, or hide it if it is the last one
function nextTutorialMessage() { tutorialInstructionIndex ++; if(tutorialInstructions[tutorialInstructionIndex+1]) { displayMessage( "Flip-a-Blox Tutorial", tutorialInstructions[tutorialInstructionIndex].message ); } else { callbackAfterMessage = function() {}; hideMessage(); playing_state = true; } }
[ "function showNext() {\n if (currentQuestion === TOTAL_QUESTIONS) {\n // Provide a function to call when the\n // fade animation is finished\n $(\"#scoreQuizButton\").fadeIn(scrollDown);\n } else {\n // Set up the next question\n currentQuestion++...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cast i32 to i1, if necessary
function castToI1(lctx) { if (currentTempType(lctx) === 'i1') { return ''; } const currentName = currentTempName(lctx); const castedName = nextTempName(lctx); const castBlock = TAB() + castedName + ' = icmp ne i32 ' + currentName + ', 0' + LF(); return castBlock; }
[ "function castToI32(lctx) {\n const currentType = currentTempType(lctx);\n if (currentType === 'i32') {\n return '';\n }\n\n if (currentType === 'i1') {\n const currentName = currentTempName(lctx);\n const castedName = nextTempName(lctx);\n const castBlock = TAB() + castedName + ' = zext i1 ' + curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array with all meeting days in it. Args: firstDay: first day of the month daysInMonth: Number of days in the month day: Is the first meeting day Wed or Sun?
function getAllMeetingDays(firstDay, daysInMonth, day) { let result = []; let span = 0; let span2 = 0; // Read in a config file...? // Get the span between the meeting days if (day === 0) // Sun span = 3; else if (day === 3) // Wed span = 4; else throw new Error('...
[ "function dates_within_this_month() {\n days = moment().daysInMonth();\n today = new Date()\n month = String(today.getMonth() + 1)\n year = String(today.getFullYear())\n date_string = year + \"-\" + month + \"-01\"\n start_time = moment(date_string)\n hours_list = []\n for (i = 0; i < days; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createHostDiv creates the JQuery element used for storing the hosts
function createHostDiv() { const hostDiv = $("<div>"); hostDiv.addClass("host_name"); return hostDiv; }
[ "async function createUI() {\n const infectedHosts = await getInfectedHosts();\n infectedHosts.forEach(async (host) => {\n const payloads = await getPayloads(host);\n\n const hostDiv = createHostDiv();\n const hostLink = createHostLink(host);\n\n hostDiv.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Purpose: Delete an plan Type: Manual function Precondition: Pass a document reference Postcondition: Delete an plan with the document id
function deletePlanPromise(document) { return database .collection(plans) .doc(document.id) .delete(); }
[ "deleteDoc(doc) {\n this.docs.delete(doc.getIdentifier());\n }", "async delete(req, doc, options = {}) {\n options = options || {};\n const m = self.getManager(doc.type);\n await m.emit('beforeDelete', req, doc, options);\n await self.deleteBody(req, doc, options);\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
countryes are show after 1 second
function showContries(){ setTimeout(function(){ let html = ''; countries.forEach(function(country){ html += `<li>${country}</li>`; }); document.getElementById('carrito').innerHTML = html; }, 1000); }
[ "function countryTimer() {\r\n countryElement.style.display = 'none';\r\n setTimeout(respondCountry, 1000);\r\n setTimeout(displayColour, 2000);\r\n}", "function displayCountries() {\n setTimeout(function() {\n let html = '';\n countries.forEach(function(country) {\n html += `<li>${...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the component instance whose view contains the DOM element. For example, if `` is used in the template of `` (i.e. a `ViewChild` of ``), calling `getOwningComponent` on `` would return ``.
function getOwningComponent(elementOrDir) { const context = loadLContext(elementOrDir, false); if (context === null) return null; let lView = context.lView; let parent; ngDevMode && assertLView(lView); while (lView[HOST] === null && (parent = getLViewParent(lView))) { // As long ...
[ "function _getValidComponent( node ) {\n\tif ( node && ( node._instance || node.constructor.name == 'ReactCompositeComponentWrapper' ) ) {\n\t\tnode = node._instance;\n\t}\n\tif ( node && IGNORED_COMPONENTS.indexOf( node.constructor.name ) >= 0 ) {\n\t\tnode = null;\n\t}\n\treturn node;\n}", "getTargetNode(props:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return's the nth even number
function nthEven(n) { return n*2-2; }
[ "function ifevenorzero(n){\n if (n == 0){\n return 1\n }\n\n else{\n if(n % 2 == 0 ){\n return 1;\n }\n else{\n return 0;\n }\n }\n}", "function oddsSmallerThan(n) {\n // Your code here\n\n return parseInt(n /2)\n\n}", "function isOdd(n) {if(!isNaN(n)){return n % 2 !== 0}}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send email report summary absent to Email for person
function sendEmailToPerson() { dataInit(); callSheetConfig(); var tmp = [] var today = new Date(); for (var i = 1; i < data1.length; i++){ for (var j=1; j < data.length; j++){ var slicesstring = data[j][4].slice(-7,-5); var stringYear = data[j][4].slice(-4); if(data1[i][2] == data[j][2] ...
[ "function notifyMember(site,personalMail,firstname,lastname,date){\n var body = \"Documents and information required for employee admission.\";\n var subject = \"Welcome to our company\";\n var options = {name:\"HR Team\",htmlBody:body,replyTo:\"hr@example.com\",from:\"hr@example.com\"};\n MailApp.sendEmail(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count of digits in the integer part of v. Used to find how many decimal digits to include in %g converions. Counts by comparing against known powers of ten, much faster than using v.toExponential(). 105m/s if <1000, else 48m/s
function countDigits( v, power ) { if (v < 1000) return v < 1 ? 0 : v < 10 ? 1 : v < 100 ? 2 : 3; var n = 0; while (_pow10[n + 6] <= v) n += 6; while (_pow10[n + 3] <= v) n += 3; while (_pow10[n] <= v) n += 1; return n; }
[ "function count_digits(i) /* (i : int) -> int */ {\n return _int_count_digits(i);\n}", "function numOfDigits(n) {\n return n.toString().\n replace(\".\", \"\").\n replace(\"-\", \"\").length\n}", "function INT(x) { return Math.floor(x) }", "static int48(v) { return n(v, -48); }", "static int64(v) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================================================================================ gameWin Function Opens the win game modal box Displays the time, star rating, and moves Can start a new game ======================================================================================================...
function gameWin( ) { //==Open You Win modal box================================================================================= modal.style.display = "block"; //==Display the final time, moves, and star rating========================================================= if( secondsTimer < 10 ) { fin...
[ "function gameWon() {\n $('#gameWon').modal('open');\n stopCountdown();\n stillChangeColor = true;\n changeBackgroundColor();\n gameState.wordsLeftToMatch = 10;\n}", "function endGameModal() {\n\tif (arguments[0] == \"youWon\") {\n\t\tdocument.getElementById(\"end-game-msg\").firstChild.innerHTML =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ends round, updates the progress bar.
endRound() { console.log(`Round ${this.round} completed.`) // update progress bar let point = this.round - 1; if (point >= 0) { // calc width for the bar let width = Math.round(100 / (totalRounds - 1) * point); progressBar.find('.active-line').animate({ width: ...
[ "function roundEnded() {\n\tif (roundCont == true) {\n\t\tclearInterval(interval);\n\t\ttargetDate = null;\n\t\troundCont = false;\n//\t\tdocument.myForm.round.disabled = false;\n\t\tupdateButtons();\n\t\tgetWords();\n\t}\n}", "function quitRound() {\n clearInterval(timer);\n endRound();\n}", "function progre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public function `iterable`. Returns true if `data` is an iterable, false otherwise.
function iterable (data) { if (typeof Symbol === 'undefined') { // Fall back to `arrayLike` predicate in pre-ES6 environments. return arrayLike(data); } return assigned(data) && isFunction(data[Symbol.iterator]); }
[ "function any( iterable )\n {\n var res = false;\n \n foreach(function (x)\n {\n if ( x )\n {\n res = true;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }", "function all( iterable )\n {\n var res = true;\n \n foreach(function (x)\n {\n if ( !x )...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tile showing average numbers of accidents / casualties per day Two functions below sum all accidents and divide them by number of days per year (365) in order to calculate daily average
function showAccidentsAvg(dataFor2017) { let dim = dataFor2017.dimension(dc.pluck("ref")); let totalAcc = dim.group().reduceSum(dc.pluck("number_of_accidents")); dc.numberDisplay("#accidents-average") .formatNumber(d3.format(",.0f")) .group(totalAcc) .valueAccessor(function(d) { ...
[ "function showAccidentsTotal(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"ref\"));\n let totalAcc = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n\n dc.numberDisplay(\"#accidents-total\")\n .formatNumber(d3.format(\".2s\"))\n .group(totalAcc);\n}", "function Stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the form for a given mode
setForm(form, mode) { this.forms.set(mode, form); }
[ "function setEditOrCreateMode(mode)\n {\n $(invoke_button).data(\"mode\", mode)\n \n if (mode == \"0\")\n $(\"#mainHeading\").text(\"Add an Author\")\n else\n $(\"#mainHeading\").text(\"Edit an Author\")\n }", "function setMod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Props should have the following values for the component to work properly: selectNames Array of strings for labelling each select selectOptions Array containing the component array for each select score The currently selected score value for each select See addScore.jsx for an example
constructor(props){ super(props); let formScore = props.score; // Initialize the score array when it's empty if (this.props.score.length === 0) { for (var i=0; i < this.props.selectOptions.length; i++) { formScore.push(this.props.selectOptions[i][0].props.value); } } this.sta...
[ "render() {\n\n let options = _.map(codes.counties, function(label, code) {\n return {\n value: code,\n label,\n };\n });\n\n return (\n <Select\n\n className=\"choropleth-select\"\n\n placeholder=\"Select a demographic variable\"\n options={options}\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prints the content of the deleteLeader div
function displayDeleteLeader(i) { var content = ""; content += "Careful! Are you sure you want to delete <strong>" + leaders[i].firstName + " " + leaders[i].lastName; content += "</strong> and all of their information?<br><br>"; content += "<button id='deleteLeaderYesButton' class='deleteButton' onC...
[ "function setMessageDeleted (message_id){\n\tconst delete_msg = `<p>---CHAT DELETED---</p>`\n\tdocument.getElementById(message_id).innerHTML = delete_msg;\n\n}", "function deletePlayer(e) {\n let playerid = e.target.parentElement.id.split('-')[1]\n console.log(`id is ${playerid}`);\n fetch(`http://localhost:30...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the corresponding codemirror textarea for any of 'code', 'header', and 'footer'
function getCodeMirrorTextArea(boxId) { return $('#' + boxId).parent().children('div').children().not('[class]').children()[0] }
[ "setupEditor() {\r\n this.fancyEditor = CodeMirror.fromTextArea(this.source.get(0), {\r\n mode: 'python',\r\n theme: this.theme,\r\n lineWrapping: true,\r\n lineNumbers: this.lineNumbers,\r\n tabSize: 2,\r\n autofocus: true,\r\n aut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect all the type declarations in the given path and add references to them for retreival later.
function collectTypes (path: NodePath): void { path.traverse({ InterfaceDeclaration (path: NodePath) { path.scope.setData(`typechecker:${path.node.id.name}`, path); }, TypeAlias (path: NodePath) { path.scope.setData(`typechecker:${path.node.id.name}`, path); }, ImportDe...
[ "function flushTypeQueue() {\n\t\t\t\tforEach(typeQueue, function (type) {\n\t\t\t\t\tif (UrlMatcher.prototype.$types[type.name]) {\n\t\t\t\t\t\tthrow new Error(\"A type named '\" + type.name + \"' has already been defined.\");\n\t\t\t\t\t}\n\t\t\t\t\tvar def = new Type(isInjectable(type.def) ? injector.invoke(type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes inventory levels, either adding to or subtracting from StockQuantity for the desired id
function changeInventory(id, currentQuantity, addOrSubtract){ var newQuantity = currentQuantity + addOrSubtract; var updateText = "UPDATE Products\ SET StockQuantity = ?\ WHERE id = ?"; connection.query(updateText, [newQuantity, id], function(error, results){ if(error){throw error}; }) }
[ "function change_product_quantity(product_id, qty)\n{\n\t//Save new quantity into the product in order_list \n\tif (product_id in order_list)\n\t{\n\t\torder_list[product_id].quantity = qty;\n\t\trecalculate_moqioq_flag(product_id);\n\t\t//Highlight the box - TBD\n\t}\n}", "function change_product_quantity(produc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
debug just trace out some text to the stats container:
function debug(text){ stats.setContent(stats.getContent()+"<br>"+text); }
[ "debug(entry) {\n this.write(entry, 'DEBUG');\n }", "function debug() {\n // Nothing to test, yay :D\n}", "debug() {\n this.registerNames.forEach(name => {\n console.log(`${name}: 0x${this.getRegister(name).toString(16).padStart(4, \"0\")}`);\n });\n console.log();\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a new Color3 converted from the current one to gamma space
toGammaSpace() { const convertedColor = new Color3(); this.toGammaSpaceToRef(convertedColor); return convertedColor; }
[ "toLinearSpace() {\n const convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n }", "function tonemap(r,g,b, gamma) {\n return new THREE.Color(clamp(Math.pow(r, 1.0 / gamma)),\n clamp(Math.pow(g, 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an `element` to `array`. If array already contains and item like this, it is removed before adding it again. Optionally `toIndex` can be specified to add element at specific index.
function move(array, element, toIndex) { // @todo this implementation must be the same as the List.moveValue method // @todo don't do anything if the desired index is the same as the current index var index = indexOf(array, element); // @todo remove all old values rather than only the first ? i...
[ "function addAnElementInGeneral(array, index, element) {\n array.splice(index, 0, element);\n return array;\n}", "add(element) {\n this._buffer.unshift(element);\n this._buffer = this._buffer.splice(0, this._size);\n }", "function addToEnd(array, item) {\n var index = array.indexOf(item);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
global image element so hiding img element works Sets the global background variable and then sets the image to hidden
function hideImage(img) { background = img; background.style.display = "none"; }
[ "function hideSmIm(){\r\ndocument.getElementById('smallImage').style.display = 'none';\r\n$(\"#savPicBlk\").hide();\r\n}", "function hideImagePopup(){\n\tdocument.getElementById('popupImage').style.visibility = \"hidden\";\n}", "function drawHidden(url) {\n\n \n\n v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isAcceptableFloat :: Number > Bool
function isAcceptableFloat(num) { const str = num.toString(); return str.indexOf('.') === str.length - 2; }
[ "function validate_float(checkprice){\n\nif(/^[+-]?\\d+(\\.\\d+)?$/.test(checkprice)){\n\nreturn true;\n\n}else{\n return false;\n}\n\n}", "function isValidUFloat(s) {\n return s.match(/^\\s*([0-9]+(\\.[0-9]*)?|\\.[0-9]+)\\s*$/)\n }", "function checkIfFinite(arg){\n return Number.isFinite(arg)\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in the current board state, the row and column of the germ placement, and the id of the current player Returns a list of grids that are infected by the germ placement
function infectedGrid(currentBoard, row, column, currentPlayer) { var opponent; if(currentPlayer == 1) { opponent = 2; } else { opponent = 1; } var infectedGridList = []; if(row > 0 && row < length - 1 && column > 0 && column < length - 1) { if(currentBoard[row+1][column] == opponent) { var infectedGr...
[ "showCellsId(G,ctx){\n\t\t\tconst cells = [...G.cells];\n\t\t\tfor (let i = 0; i < boardHeight; i++) {\n\t\t\t\tfor(let j=0;j<boardWidth;j++) {\n\t\t\t\t\tlet id = boardWidth * i + j;\n\t\t\t\t\tcells[id].setDisplay(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {...G,cells};\n\t\t}", "function get_valid_moves_list(board...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basicamente exporta los datos necesarios nada mas de este objeto para ser serializado
export(){ return this.iterarExport(this.objetos) }
[ "function exportAllCustomData() {\n let customDataObject = {\n cR: customRecipes,\n cI: customIngredients,\n sL: shoppingList,\n p: pantry,\n }\n download(\"menusmith.backup\", JSON.stringify(customDataObject));\n}", "export() {\n let { output, outputFrozen } = this.appStat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send delete answer action upwards
destroyAnswer(answer){ this.sendAction('destroyAnswer', answer); }
[ "deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }", "function deleteActionItem(id, type) {\n var livestock_id = String(localStorage.LivestockID)\n var startPointID = String(localStorage.startPointIDBelegung)\n ons.notification.confirm({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For some nodes, we want to include more props than for others
function getNodeProps(node, key, opts, renderer) { var props = { key: key }, undef; // `sourcePos` is true if the user wants source information (line/column info from markdown source) if (opts.sourcePos && node.sourcepos) { props['data-sourcepos'] = flattenPosition(node.sourcepos); } ...
[ "extractProps(node) {\n if (Element$1.isAncestor(node)) {\n var properties = _objectWithoutProperties(node, [\"children\"]);\n\n return properties;\n } else {\n var properties = _objectWithoutProperties(node, [\"text\"]);\n\n return properties;\n }\n }", "extend(...pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve Weekly usage data from Chrome storage and update data in the container through
async function retrieveWeeklyData() { prevWeek = []; for (i = 0; i < 7; i++) { prevWeek.push(dateString(getPreviousDays(i))); } weeklyTotalTimeData = await getWeeklyTotalTime(prevWeek); weeklyMostFrequentTimeData = await getWeeklyMostFrequentTime(); var left_container = document.ge...
[ "listWeekly() {\n const weekBefore = dateService.getWeekBefore();\n return this.trafficRepository.getWeeklyData(weekBefore)\n .then(data => {\n const mappedData = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(1, 7);\n const valuesToAdd = range.filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates a new highlight Layer and references it to the scene..
function HighlightLayer(name,scene,options){var _this=_super.call(this,name,scene)||this;_this.name=name;/** * Specifies whether or not the inner glow is ACTIVE in the layer. */_this.innerGlow=true;/** * Specifies whether or not the outer glow is ACTIVE in the layer. ...
[ "onLayerHighlight() {}", "function EffectLayer(/** The Friendly of the effect in the scene */name,scene){this._vertexBuffers={};this._maxSize=0;this._mainTextureDesiredSize={width:0,height:0};this._shouldRender=true;this._postProcesses=[];this._textures=[];this._emissiveTextureAndColor={texture:null,color:new BAB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the current caption
function _setCaption(caption) { /* jshint unused:false */ var container = _getElement(config.selectors.captions), content = document.createElement('span'); // Empty the container container.innerHTML = ''; // Default to empty if (_...
[ "function setupCaption() {\n $('.caption-detail', $detail).text(node.text);\n var capHelperText = '';\n if (node.hscs) {\n capHelperText = node.hscs + '次合绳';\n } else if (node.nzcs) {\n capHelperText = node.nzcs + '次捻制';\n } else i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an event listener to the current node. If an output exists on one of the node's directives, it also subscribes to the output and saves the subscription for later cleanup.
function listener(eventName, listenerFn, useCapture) { if (useCapture === void 0) { useCapture = false; } var viewData = getViewData(); var tNode = getPreviousOrParentTNode(); ngDevMode && assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */, 4 /* ElementContainer */); // add native e...
[ "function addListener(statePath, el) {\n var listeners = objectGet(treeListeners, statePath);\n if (listeners == false) {\n setWith(treeListeners, statePath, []);\n }\n listeners = objectGet(treeListeners, statePath);\n listeners.push(el);\n }", "function addEventL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Goes through the services and generate the corresponding provider file.
function generateProviderFiles() { for (let i = 0; i < services.length; i++) { generateProviderFile(services[i]); } }
[ "async function generate() {\n // get all of the files in this directory\n fs.readdirSync(__dirname)\n .filter((file) => {\n // filter include files with pattern *.json\n return (file.indexOf('.') !== 0) && (file.slice(-5) === '.json');\n })\n .forEach(async (file) => {\n // co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the domain hash for %%domain%%.
static hashDomain(domain) { const domainFields = []; for (const name in domain) { if (domain[name] == null) { continue; } const type = domainFieldTypes[name]; (0, index_js_4.assertArgument)(type, `invalid typed-data domain key: ${JSON.strin...
[ "function getWebCertFullHash(domain) {\n const hash = parent.webCertificateFullHashs[domain.id];\n if (hash != null) return hash;\n return parent.webCertificateFullHash;\n }", "function getDomainKey( domain ) {\n\treturn domain + '_block';\n}", "function resolveHost(domain)\r\n{\r\n v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If page is accessed from a specific itinerary, it will get the info from city and itinerary automatically, if not, it will get it from the dropdown menus. Below we check if props have been updated (so the function is only called when the props have been received) and if there is a city ID and an itinerary ID it sets th...
componentDidUpdate(prevProps) { if (prevProps.cities.cities !== this.props.cities.cities) { if (this.props.match.params.cityId) { const cities = this.props.cities.cities const city = cities.find(city => city.name === this.props.match.params.cityId) thi...
[ "function populateCityList() {\r\n var cityIds = new Object();\r\n cityIds[WME_ADD_UNKNOWN] = \"No City\";\r\n for (var cit in wazeModel.cities.objects) {\r\n var city = wazeModel.cities.get(cit);\r\n if (city && cityIds[city.id] == null && city.name != null && city.name.length > 0) {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function create a copy of $template element and appends it to $list element making it visible and removing ID it is used to add both the new channels to the list and the new messages
function addItem($list, $template) { // makes copy of template element var item = $template.clone(); // removes CSS class "hidden" item.removeClass('hidden'); // removes ID attribute item.removeAttr('id'); // adds el to the list $list.append(item); // and returns the reference to...
[ "function newMessage(template,message){\n if(template === 'partner'){\n partnerIsTyping();\n setTimeout(appendMessage, 1000)\n }\n else{\n appendMessage();\n }\n // generates message HTML from appropriate template, stored in DOM\n function appendMessage(){\n $('.chat-window-timeline .chat-partner-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find board, given short URL
function getBoardFromUrl(url) { var result = null; boardMap.forEach(function (brd) { if (brd.shortUrl === url) { result = brd; } }); return result; }
[ "function loadBoardByHash()\n{\n let hash = location.hash;\n let page = hash ? hash.slice(1) : 'home';\n\n loadBoard(page);\n}", "function searchByShortUrl(db, shortURL, cb) {\n let query = { \"shortURL\": shortURL };\n db.collection(\"urls\").findOne(query, cb);\n }", "function readURL(id, call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that executes Python script to change url to local server.
function url_server () { return spawn('python', ['./lib/python/change_url.py', 'serve'], {stdio: 'inherit'}) }
[ "function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}", "function readFileSyncReplacingUrl(fileName, req) {\n var port = app.get('port');\n var host = req.protocol + '://' + req.hostname + (port == 80 || port == 443 ? '' : ':'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4. We have a cost in the form "$120". That is: the dollar sign goes first, and then the number. Create a function extractCurrencyValue(str) that would extract the numeric value from such string and return it.
function extractCurrencyValue(s) { return +s.slice(1); }
[ "static amountPriceParser(amount) {\n //delete decimals\n let amountWithoutDecimals = parseInt(amount);\n let amountString = amountWithoutDecimals.toString();\n const regx = /(\\d+)(\\d{3})/;\n while (regx.test(amountString)) {\n amountString = amountString.replace(regx, `$1.$2`);\n }\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add fertilisers N rate and netRate.
function addFertilisers(fertilisersAdded, fertiliserData) { var fertiliserNames = fertiliserData.map(function(a) {return a.name;}); for (var i=0; i<fertilisersAdded.length; i++) { // matching fertiliserData row for (var j=0; j<fertiliserData.length; j++) { if (fertiliserData[j].nam...
[ "function testrate(){\n\t\tvar sum = rate[0]+rate[1]+rate[2]+rate[3];\n\t\tif(sum > 100){\n\t\t\talert(\"rate over more than 100%\");\n\t\t}else{\n\t\t\tif(sum <100){\n\t\t\t\talert(\"rate low than 100%\");\n\t\t\t}else{\n\t\t\t\tdrawcircle();\n\t\t\t\tdrawsmallcircle();\n\t\t\t\tdrawnote();\n\t\t\t\tfillvalue();\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We are given a list nums of integers representing a list compressed with runlength encoding. Consider each adjacent pair of elements [freq, val] = [nums[2i], nums[2i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right t...
decompressRunLengthEncodedList(numbers) { let arr = []; for (let i = 0; i < numbers.length; i += 2) { const frequency = numbers[i]; const val = numbers[+i + 1]; for (let j = 0; j < frequency; j++) { arr.push(val); } // ...
[ "function nextPermutation(nums) {\n //finding the first decreasing number from right\n let i = nums.length - 2;\n while (i >= 0 && nums[i] >= nums[i + 1]) {\n i--;\n }\n //if not found meaning the biggest #\n //otherwise, find the next bigger number from right\n if (i >= 0) {\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Organisation Registration Registration Settings
function orgRegistrationRegSettingsEndUserRegAction(payload) { const action = { type: ApiConstants.API_ORG_REGISTRATION_REG_SETTINGS_LOAD, payload: payload }; return action; }
[ "function startRegister() {\n\tif(request.httpParameterMap.MailExisted.value != null && request.httpParameterMap.MailExisted.value != 'true'){\n\t\tapp.getForm('profile').clear();\n\t}\n\n if (app.getForm('login.username').value() !== null) {\n app.getForm('profile.customer.email').object.value = app.getF...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the access token expiration date (useful for refresh logics)
function setExpiresAt() { if (!service.token) { return; } if (typeof (service.token.expired_in) !== 'undefined' && service.token.expired_in !== null) { var expires_at = new Date(); expires_at.setSeconds(expires_at.getSeconds() + parseIn...
[ "_setCacheExpiry() {\n const oThis = this;\n\n oThis.cacheExpiry = 86400; // 24 hours\n }", "setUserInactiveExpiresAt() {\n const value = new Date().getTime() + INACTIVE_OFFSET;\n\n if (Authenticator.getAccessToken() !== null) {\n localStorage.setItem(USER_INACTIVE_EXPIRES_AT, value);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
$MyTimer=0.3; //eseguo un ciclo ogni $MyTimer secondi timerID=''; / MyWindowF $opt['name']> Il nome della variabile che contiene l'oggetto finestra creato | valore [testo] $opt['title']> Il titolo della finestra | valore [testo] $opt['txt']> Il contenuto della finestra | valore [testo] $opt['isVisible']> Indica se a fi...
function MyWindow($opt){//name deve essere uguale al nome della variabile che contiene il nuovo oggetto this.opt=$opt; var test=$opt['name']; var _self=this; $zindex++; this.name=$opt['name']; this.chiudi= function(){ this.windows.innerHTML=""; return; }; this.hide= function(){ this.windows.style.visibili...
[ "timeProcess(itself=(cov_50nz68pmo.b[1][0]++,this)){cov_50nz68pmo.f[3]++;cov_50nz68pmo.s[7]++;// define begin cooldown\ninitTime=new Date().getTime();// function to send clockBar instant to setInterval\nfunction sendTosetInterval(){cov_50nz68pmo.f[4]++;cov_50nz68pmo.s[8]++;return itself;}// define time cooldown\nva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the petals based on the current page
function displayPetals() { const start = (currentPage - 1) }
[ "function showStrategyPage() {\n\n\t// Apply strategy styles\n\t$(\"body, header, .door\").addClass(\"strategy\");\n\n\t$(\".door span\").empty().append(\"1/3\");\n\t$(\"header h1\").append(\"<em> Strategy</em>\");\n\n\t$(\"div.strategy\").removeClass(\"hidden\");\n\t$text.fadeIn();\n\t$doorContainer.fadeIn();\n}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a string (self) starts with another one (phrase)
function startsWith(self, phrase) { return phrase.length && self.length && !self.indexOf(phrase); }
[ "function canMatchBegin(word1, word2) {\n \t\t\tif(word1[0] == \"*\" || word2[0] == \"*\") {\n \t\t\t\treturn true;\n \t\t\t}\n \t\t\tlet toCompare = Math.min(word1.indexOf(\"*\"), word2.indexOf(\"*\"));\n \t\t\treturn word1.slice(0, toCompare) == word2.slice(0, toCompare);\n \t\t}", "function isPrefix(word, pref...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
| Accumulate a result `z' from applying `f' to `z' and `xs[i]'. foldr :: (a > b > b) > b > [a] > b
function foldr(f, z, xs) { for (var i = 0; i < xs.length; i++) z = f(z, xs[i]) return z }
[ "function stream_for_each(fun, xs) {\n if (is_null(xs)) {\n return true;\n } else {\n fun(head(xs));\n return stream_for_each(fun, stream_tail(xs));\n }\n}", "function merge_in_place(lists, cmp_fn, dup_fn) {\n cmp_fn = cmp_fn || cmp\n\n if (!lists) return [];\n\n var reverse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to remove the seat selected in the details component
removeSeat(e) { // retrieve the index through the data attribute const { target } = e; const seatIndex = target.getAttribute('data-index'); // update the state removing the selected item const { seats: prevSeats } = this.state; const index = Number.parseInt(seatIndex, 10); const seats = [......
[ "removeSeat() {\n //recount the number of tickets\n if (this._seatType === \"regular\") {\n regularSeatCount--;\n regularTicketNum.innerHTML = regularSeatCount; //display reg ticket num\n Seat.calcTotalPrice(regularSeatCount, this._seatType);\n } else if (this._seatType === \"vip\") {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the post title to be editable. Handling done to add 'Updated' tag as per the screenshots, would be added only once even for multiple edits.
function editableTitle(){ var postTitle = document.getElementById('postTitle'); var titleText = postTitle.innerText; if(titleText.startsWith("UPDATED: ")) titleText = titleText.replace("UPDATED: ",""); postTitle.innerHTML = titleText; postTitle.contentEditable = "true"; postTitle.classList.add("edit...
[ "function updatedTitle(){\n var postTitle = document.getElementById('postTitle');\n var editedText = postTitle.innerText;\n postTitle.innerHTML = \"UPDATED: \"+editedText;\n postTitle.classList.remove(\"edit\");\n postTitle.contentEditable = \"false\";\n}", "function editablePost(){\n var postBody = documen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion progress for approve bulk onboard after create
function progressForApproveBulkOnboard(goApprove, bulkOnboardId) { if (goApprove === true) { // progess for approve if (bulkOnboardId) { return Onboarding.progressBulkOnboard(bulkOnboardId) .then(function() { ...
[ "@action\n statusChangeAction(field, value) {\n if (value == 'approved') {\n this.editEntry.set('create_entry', 1);\n }\n }", "approve () {\n this.resolve(true);\n let project = store.getters.project(this.project_id);\n new MocaMutationSet(\n 'update', 'project',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcion que comprueba si el campo es una fecha.
function comprobarFecha(campo){ //Comprueba que la fecha no este vacia y que no tenga espacios ya que el formato es mm/dd/aaaa if(!comprobarVacio(campo) && comprobarTextoSin(campo,campo.size)){ elementoValido(campo); return true; } //Si cumple las condiciones anteriores es un elemento invalido. else{ ...
[ "function ISDATE(value) {\n return value && Object.prototype.toString.call(value) == '[object Date]';\n}", "check_date(date){\n \n if(typeof(date) == 'undefined' || date == null)\n return false;\n \n return moment(date, 'YYYY-MM-DD').isValid();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=> 'Hi Chaka Khan!' QUESTION 3: Tax Caclulator Define a function taxCalculator that accepts the price of an item and a state. taxCalculator should return the aftertax cost of the item, assuming NY's tax is 4% and NJ's sales tax is 6.625%. taxCalculator(100, 'NY'); // => 104 taxCalculator(100, 'NJ'); // => 106.625 CODE ...
function taxCalculator(num1, state) { if (state == "NY") { num1 = 4 / 100 + 1; } else { num1 = 6.625 / 100 + 1; } sum = 100 * num1; return sum; }
[ "function taxCalculator(amount, taxrate){\n return amount + (amount * taxrate);\n}", "function exerciseTwo() {\n const price = 5.99;\n const quantity = prompt('How many items would you like to purchase?');\n const afterTax = price * quantity * 1.13;\n console.log(`The total cost of your purchase is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a routing control object, empty at first, popuplated after finding closest garda station
function showRouting() { route = L.Routing.control({ createMarker: function() { return null; } }).addTo(map); }
[ "function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO(sjmiles): a `slotInfo` contains an `id` and a device `context` (e.g. a dom node).
_findInnerSlotInfos() { return Array.from(this._dom.querySelectorAll("[slotid]")).map(s => { return { context: s, id: s.getAttribute('slotid') } }); }
[ "function DeviceSlot() {}", "function mySlotChange(eventData) {\n\t\t// $log.log(preDebugMsg + \"mySlotChange() \" + eventData.slotName + \" = \" + JSON.stringify(eventData.slotValue));\n\t\t// $log.log(preDebugMsg + \"mySlotChange() \" + eventData.slotName);\n\t\tswitch(eventData.slotName) {\n\t\t\tcase \"Select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an expected font size for the canvas size
function getFontSize(relativeSize) { return canvas.width * 0.001 * relativeSize; }
[ "function canvasSize({\n textStyle = 0,\n size = 300,\n primaryText = \"\",\n secondaryText = \"\",\n displaySize = false,\n }) {\n let scale = size / 300;\n let scaledWidth = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the slidedown animation to the modal
slideDown() { setTimeout(() => { // this.modalOnUI.style.removeProperty("top"); this.modalOnUI.style.removeProperty("opacity"); this.modalOnUI.style.setProperty("top", "5%"); this.modalOnUI.style.setProperty("opacity", "1"); }, 200); }
[ "slideUp() {\n this.modalOnUI.style.removeProperty(\"top\");\n this.modalOnUI.style.removeProperty(\"opacity\");\n this.modalOnUI.style.setProperty(\"top\", \"0%\");\n this.modalOnUI.style.setProperty(\"opacity\", \"0\");\n }", "function openModal() {\n var speed = 700;\n var easi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenient function to update the place result object
function updatePlaceResultObject(tobeupdated,update){ tobeupdated.geometry= update.geometry; tobeupdated.icon=update.icon; tobeupdated.name=update.name; tobeupdated.vicinity=update.vicinity; }
[ "updateResult() {\r\n }", "function updatePlaces(results, PlacesServiceStatus) {\n\t\t\t$scope.places = results;\n\t\t\t$scope.$apply();\n\t\t}", "function setResult(pointTotals, team, pts) {\n\tteamObj = pointTotals.find(object => object.name === team.name);\n\tif (teamObj === void 0)\n\t{\n\t\tteam.points = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swap the positions of the two players on a team
swapPosition(player1, player2, team) { this.animatePlayerSwap(player1, player2); [player1.pos, player2.pos] = [player2.pos, player1.pos]; if (team == nameWest) { [this.nw, this.sw] = [this.sw, this.nw]; } else { [this.ne, this.se] = [this.se, this.ne]; } ...
[ "switchPlayers(){\n if(this.currentPlayer == this.player1){\n this.currentPlayer = this.player2;\n }\n else this.currentPlayer = this.player1;\n }", "animatePlayerSwap(p1, p2) {\n var done = false;\n if (p1 != undefined) {\n swapping[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a string to spinal case. Spinal case is alllowercasewordsjoinedbydashes.
function spinalCase(str){ return str; }
[ "function toWeirdCase(string){\n return string.split(\" \")\n .map(word => word.split(\"\").map((word, ind) => ind%2 == 0 ? word.toUpperCase() : word).join(\"\"))\n . join(\" \")\n}", "function getCase(str) {\n\tconst a = [...new Set(str.match(/[a-z]/gi).map(x => x === x.toLowerCase() ? 1 : x =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an object with the i, j being in the middle of the local map
function getMiddleLocation() { return { i: HORIZONTALRADIUS, j: VERTICALRADIUS } }
[ "function get_city_dxy_to_index(dx, dy) \n{\n city_tile_map = {};\n city_tile_map[\" 00\"] = 0;\n city_tile_map[\" 10\"] = 1;\n city_tile_map[\" 01\"] = 2;\n city_tile_map[\" 0-1\"] = 3;\n city_tile_map[\" -10\"] = 4;\n city_tile_map[\" 11\"] = 5;\n city_tile_map[\" 1-1\"] = 6;\n city_tile_map[\" -11\"] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }