query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
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'); articleBody.textContent = article.body; var permissionRadioElementId = '#permission-' + article.permission; var permissionRadioElement = dialog.querySelector(permissionRadioElementId); permissionRadioElement.setAttribute('checked', 'checked'); permissionRadioElement.parentElement.classList.add('is-checked'); var saveArticleButton = dialog.querySelector('.save-article'); articleTitle.addEventListener('keyup', () => { toggleArticleButton(saveArticleButton, articleTitle, articleBody); }); articleTitle.addEventListener('change', () => { toggleArticleButton(saveArticleButton, articleTitle, articleBody); }); articleBody.addEventListener('keyup', () => { toggleArticleButton(saveArticleButton, articleTitle, articleBody); }); articleBody.addEventListener('change', () => { toggleArticleButton(saveArticleButton, articleTitle, articleBody); }); dialog.showModal(); }
[ "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 storage: view.storage,\n templates: view.templates\n },\n function () {\n dialog(editNode).overlay().show();\n }\n );\n\n });\n\n clb();\n}", "function openEditor() {\n let card = cards.get(editId)\n $(\".card-editor-container\").removeClass(\"invisible\")\n $(\"#card-text-input\").val(card.text)\n $(\"#card-text-input\").focus()\n\n // Reattach the card that should be edited\n card.node.appendTo($(\".card-editor-card-display\"))\n }", "function editNote() {\n vm.isEditingNote = true;\n }", "function getEditAuthorForm(req, res) {\n Author.findById(req.params.authorsIdForEditForm, function(err, authorToEditFromDb) {\n res.render('authorsViews/edit', {\n authorToEditReferenceForEJS: authorToEditFromDb,\n title: `Edit ${authorToEditFromDb.name}`\n })\n })\n}", "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 goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}", "function editNote(){\n\t\n\tvar moment = require('alloy/moment');\n\t\n\tvar note= myNotes.get(idNote);\n\tnote.set({\n\t\t\"noteTitle\": $.noteTitle.value,\n\t\t\"noteDescription\": $.noteDescription.value,\n\t\t\"date\": moment().format()\n\t}).save();\n\t\n\tvar toast = Ti.UI.createNotification({\n\t\t \t\t\t \tmessage:\"Note has been succesfully saved\",\n\t\t \t\t\tduration: Ti.UI.NOTIFICATION_DURATION_SHORT\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\ttoast.show();\n\tAlloy.Collections.note.fetch();\n\t\n $.detailnote.close();\n\t\t\n}", "listenLoadEditForm() {\n editor.clearMenus();\n const slugs = h.getAfterHash(this.href),\n post = model.getPostBySlugs(slugs);\n\n editor.currentPost = post;\n editor.currentPostType = post.type;\n\n if (editor.currentPostType !== 'settings') {\n view.currentPost = post;\n view.update();\n } else {\n event.preventDefault();\n }\n\n editor.showEditPanel();\n }", "fillEditForm() {\n let post = editor.currentPost,\n editTitle = document.getElementById('editTitle'),\n postTitle = h.getPostTitle(),\n titleField = h.getEditorTitleField();\n\n // Update the title and content fields\n editTitle.value = post.title;\n editContent.value = post.content;\n\n // Initialize the wysiwyg editor\n wysiwyg = wysiwygEditor(document.getElementById('editContent'));\n\n // Add listeners to update the view on field changes\n if (post.type !== 'settings') {\n // Actions if not editing a setting\n titleField.addEventListener('input', function () {\n editor.currentPost.title = this.value;\n view.updateTitle(this.value);\n }, false);\n wysiwyg.onUpdate(function () {\n view.updateContent(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {\n // Live update controls for settings\n if (post.slug === 'site-name') {\n wysiwyg.onUpdate(function () {\n view.updateSiteName(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else if (post.slug == 'site-description') {\n wysiwyg.onUpdate(function () {\n view.updateSiteDescription(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {}\n }\n }", "function displayEditPost(post){\r\n\t\t\t$(\"form#edit-form input#title\").val(post.title);\r\n\t\t\t$(\"form#edit-form textarea#content\").val(post.body);\r\n\t\t}", "function handleEdit(event,ele){\n event.preventDefault();\n setEditing(true);\n setCurrentBlog(ele);\n\n }", "author_update_get(req, res, next) {\n Author.findById(req.params.id,\n function (err, author) {\n if (err) { return next(err); }\n\n res.render(\"author_form\", {\n title: \"Edit Author\",\n author,\n });\n });\n }", "function handleShowEditableIdeaForm() {\n $('body').on(\"click\", \".js-show-edit-idea-form-btn\", (event) => {\n const ideaID = $(event.currentTarget).data('id');\n const success = response => {\n displayEditableIdeaForm(response, ('.js-content'), false);\n }\n\n getIdeaDetails({\n jwToken: user,\n ideaID,\n onSuccess: success\n });\n });\n}", "function onEntryAction(evt) {\n if ($(this).hasClass(\"edit\")) {\n zdPage.navigate(\"edit/existing/\" + $(this).data(\"entry-id\"));\n //window.open(\"/\" + zdPage.getLang() + \"/edit/existing/\" + $(this).data(\"entry-id\"));\n }\n }", "function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}", "function showEditor(post){\n\t\t\n\t\t$('#newpostBtn').hide();\n\t\t$('#editpostBtn').hide();\n\t\t$('#savepostBtn').show();\n\t\t$('#deletepostBtn').hide();\n\t\t$('#backBtn').show();\n\t\t\n\t\t$('#editordiv').show();\n\t\t$('#postdiv').hide();\n\t\t$('#postlistdiv').hide();\n\t\t\n\t\t//if we edit an existing post we fill in the form\n\t\tif(post!=null){\n\t\t\t$('#edittitle').val(post.title);\n\t\t\t$('#edittext').val(post.text);\n\t\t\t$('#postid').val(post.id);\n\t\t//if we create a new post we empty the fields\t\n\t\t}else{\n\t\t\t$('#edittitle').val('');\n\t\t\t$('#edittext').val('');\n\t\t\t$('#postid').val('');\n\t\t}\n\t\t\n\t}", "showEditableAnswer(e){\n e.preventDefault();\n document.getElementById('editAnswerContent').style.display = \"inherit\";\n document.getElementById('answerContent').style.display = \"none\";\n document.getElementById('clickEdit').style.display = \"none\";\n document.getElementById('submitAnswer').style.display = \"initial\";\n document.getElementById('cancelAnswer').style.display = \"initial\";\n }", "function commentEdit(id) {\n var comment = jQuery('#comment-' + id);\n var content = comment.find('.comment-text');\n\n comment.find('.comment-edit').hide();\n\n var form = jQuery(template('template-comment-edit', {\n id: id,\n content: content.text()\n }))\n .find('.comment-edit-abort')\n .click(function(e) {\n e.preventDefault();\n comment.find('.comment-edit').show();\n jQuery(this).parents('form').replaceWith(content);\n })\n .end();\n\n content.replaceWith(form);\n}", "function editWord() {\r\n var entry = idLookUp(parseInt(this.getAttribute('data-id'), 10));\r\n\r\n //set data key for modal\r\n document.querySelector(\"#edit-confirm\").setAttribute('data-id', entry.Id);\r\n\r\n //edit row\r\n var row = document.querySelector(\"#row_\" + entry.Id);\r\n\r\n //set default text in input fields to word values\r\n document.querySelector(\"#edit-text\").innerHTML = \"Edit the word \" + row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"word-edit\")[0].value = row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"pronunciation-edit\")[0].value = row.childNodes[1].innerHTML;\r\n document.getElementsByName(\"part-of-speech-edit\")[0].value = row.childNodes[2].innerHTML;\r\n document.getElementsByName(\"definition-edit\")[0].value = row.childNodes[3].innerHTML;\r\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.create(owner).renderSomething());
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(displayRequest).then(response => response.json()).then((role) => {\n var elem = document.getElementById(\"ownerForm\");\n if (role === \"owner\"){\n elem.style.display = \"inline-block\";\n }\n });\n });\n}", "function isRouteOwner(req, res, next) {\n if (!req.params.user) {\n next(new Error('Invalid route: missing user parameter.'));\n } else if (req.params.user != req.user.username) {\n next(new Error('Is not owner'));\n } else {\n req.isOwner=true;\n next(null);\n }\n}", "function getCodeOrDiffEditor(editor) {\n if (editor) {\n var control = editor.getControl();\n if (control) {\n if (Object(__WEBPACK_IMPORTED_MODULE_1__editorBrowser_js__[\"d\" /* isCodeEditor */])(control)) {\n return {\n codeEditor: control,\n diffEditor: null\n };\n }\n if (Object(__WEBPACK_IMPORTED_MODULE_1__editorBrowser_js__[\"e\" /* isDiffEditor */])(control)) {\n return {\n codeEditor: null,\n diffEditor: control\n };\n }\n }\n }\n return {\n codeEditor: null,\n diffEditor: null\n };\n}", "isEditor(value) {\n if (!isPlainObject(value)) return false;\n var cachedIsEditor = IS_EDITOR_CACHE.get(value);\n\n if (cachedIsEditor !== undefined) {\n return cachedIsEditor;\n }\n\n var isEditor = typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && typeof value.deleteForward === 'function' && typeof value.deleteFragment === 'function' && typeof value.insertBreak === 'function' && typeof value.insertFragment === 'function' && typeof value.insertNode === 'function' && typeof value.insertText === 'function' && typeof value.isInline === 'function' && typeof value.isVoid === 'function' && typeof value.normalizeNode === 'function' && typeof value.onChange === 'function' && typeof value.removeMark === 'function' && (value.marks === null || isPlainObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && Node$1.isNodeList(value.children) && Operation.isOperationList(value.operations);\n IS_EDITOR_CACHE.set(value, isEditor);\n return isEditor;\n }", "function ensureOwner(req, res, next) {\n\tvar scoreId = req.params.scoreId;\n\tvar userId = req.user.id;\n\tif (!scoreId && !userId) {\n\t\tdebug('ensureOwner Invalid[' + scoreId + '] or userId[' + userId + ']');\n\t\treturn res.status(500).send('Invalid user or score');\n\t}\n\t\n\tdaoScore.getById(scoreId, function(err, score) {\n\t\tif (err) {\n\t\t\tdebug('ensureOwner error: ' + err);\n\t\t\treturn res.status(500).send('error');\n\t\t}\n\t\t\n\t\tif (!score) {\n \t\tdebug('invalid score');\n\t\t\treturn res.status(500).send('invalid score');\n\t\t}\n\t\t\n\t\tif (!score || score.owner !== userId) {\n\t\t\tdebug('invalid owner score[' + score.owner + ' logged user[' + userId + ']');\n\t\t\treturn res.status(500).send('invalid owner');\n\t\t}\n\t\t\n\t\tnext(null);\n\t});\n}", "async function checkOwner(presentationid, userid) {\n let queryIfOwner = `SELECT * FROM public.presentations t\n WHERE id = '${presentationid}' and user_id = '${userid}'`;\n let isOwner = await db.select(queryIfOwner);\n if (isOwner) {\n return true;\n } else {\n return false;\n }\n}", "function maybe(item, action) {\n if(!item) {\n return;\n }\n return action(item);\n}", "function pessimistic_create_owner(attempt, username, cb) {\n\tvar options = {\n\t\tpeer_urls: [helper.getPeersUrl(0)],\n\t\targs: {\n\t\t\tmarble_owner: username,\n\t\t\towners_company: process.env.marble_company\n\t\t}\n\t};\n\tmarbles_lib.register_owner(options, function (e) {\n\n\t\t// --- Does the user exist yet? --- //\n\t\tif (e && e.parsed && e.parsed.indexOf('owner already exists') >= 0) {\n\t\t\tconsole.log('');\n\t\t\tlogger.debug('finally the user exists, this is a good thing, moving on\\n\\n');\n\t\t\tcb(null);\n\t\t}\n\t\telse {\n\n\t\t\t// -- Try again -- //\n\t\t\tif (attempt < 4) {\n\t\t\t\tsetTimeout(function () {\t\t\t\t\t\t\t\t//delay for peer catch up\n\t\t\t\t\tlogger.debug('owner existance is not yet confirmed, trying again', attempt, username, Date.now());\n\t\t\t\t\treturn pessimistic_create_owner(++attempt, username, cb);\n\t\t\t\t}, helper.getBlockDelay() + 1000 * attempt);\n\t\t\t}\n\n\t\t\t// -- Give Up -- //\n\t\t\telse {\n\t\t\t\tlogger.debug('giving up on creating the user', attempt, username, Date.now());\n\t\t\t\tif (cb) return cb(e);\n\t\t\t\telse return;\n\t\t\t}\n\t\t}\n\t});\n}", "function maybeNot(item, action) {\n if(item) {\n return;\n }\n return action();\n}", "isInDOM() {\n return document.querySelector(\"#iovon-hybrid-modal\") !== null;\n }", "function maybe_6(b) /* (b : bool) -> maybe<()> */ {\n return (b) ? Just(_unit_) : Nothing;\n}", "function AsVisualHelper(/*DependencyObject*/ element, visualOut/*out Visual visual*/) \r\n { \r\n /*Visual*/ elementAsVisual = element instanceof EnsureVisual2() ? element : null;\r\n\r\n if (elementAsVisual != null)\r\n {\r\n \tvisualOut.visual = elementAsVisual;\r\n return true;\r\n } \r\n\r\n\r\n visualOut.visual = null;\r\n return false;\r\n }", "function maybeModifier (predicate) {\n var modifiedPredicate = function () {\n if (!assigned(arguments[0])) {\n return true;\n }\n\n return predicate.apply(null, arguments);\n };\n\n // Hackishly indicate that this is a maybe.xxx predicate.\n // Without this flag, the alternative would be to iterate\n // through the maybe predicates or use indexOf to check,\n // which would be time-consuming.\n modifiedPredicate._isMaybefied = true;\n\n return modifiedPredicate;\n }", "'entries.isOwner' (entryId) {\n console.log('see if user can access this entry');\n\n // If no user is logged in, throw an error\n if (!Meteor.user()) {\n console.log(\"No user is logged in!\");\n return false;\n }\n \n // Locate the entry\n let entry = JournalEntryCollection.findOne({_id: entryId});\n\n // If no entry exists, the logged in user can't access it\n if (!entry) {\n console.log(`entry with ID ${entryId} wasn't found`);\n return false;\n }\n\n console.log(`Entry found: ${entry._id}, ${entry.text}`);\n\n // If the entry's owner is not the logged in user, they\n // can't access it\n if (entry.ownerId != Meteor.userId()) {\n console.log(`This entry belongs to ${entry.ownerId} but the logged in user is ${Meteor.userId()}`);\n return false;\n }\n\n // The entry exists and the logged in user is the owner,\n // so they can access it\n return true;\n }", "waitFor_horseProfile_Overview_OwnerContent() {\n this.horseProfile_Overview_OwnerContent.waitForExist();\n }", "function EnsureVisual(/*DependencyObject*/ element, /*bool*/ allowNull)\r\n {\r\n if (element == null) \r\n {\r\n if (!allowNull) \r\n { \r\n throw new ArgumentNullException(\"element\");\r\n } \r\n\r\n return;\r\n }\r\n\r\n //\r\n if (!(element instanceof EnsureVisual2())) \r\n { \r\n throw new ArgumentException(SR.Get(SRID.Visual_NotAVisual));\r\n } \r\n\r\n// element.VerifyAccess();\r\n }", "function editorsLoaded() {\n return editorsLoaded;\n}", "getOwner() {\n this.logger.debug(GuildService.name, this.getOwner.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getOwner.name, \"Getting owner and exiting.\");\n return this.guild.owner.user;\n }", "GetCompatibleWithEditor() {}" ]
{ "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 reduce(arreglo, inicial) {\r\n let suma=0;\r\n for (let i = 0; i < arreglo.length; i++) {\r\n \r\n suma = suma + parseInt(arreglo[i]);\r\n \r\n }\r\n return suma + (inicial || 0 );\r\n}", "function runningSum(nums) {\n const result = []\n \n nums.reduce((acc, curr) => {\n result.push(acc + curr)\n return acc + curr\n }, 0)\n \n return result;\n}", "function summ(a) {\n\treturn function(b) {\n\t\tif(!b) {\n\t\t\treturn a;\n\t\t}\n\t\telse {\n\t\t\treturn summ(a+b);\n\t\t}\n\t}\n}", "function plusOneSum(arr) { \n var sum = arr.length;\n for (var index = 0; index < arr.length; index++) {\n sum += arr[index];\n } \n return sum;\n }", "function sumSet(set) {\n var i, n = 0;\n\n for (i = 0; i < set.length; i++) {\n n += +set[i];\n }\n\n return n;\n }", "function sumOf() {\n sum = newDieValues.reduce(function (a, b) {\n return a + b.info.value;\n }, 0);\n alert(\"Sum of dice equals: \" + sum);\n console.log(newDieValues);\n}", "function sumArgs() {\r\n return [].reduce.call(arguments, function(a, b) {\r\n return a + b;\r\n });\r\n}", "function arraySum(arr){\n\n // code goes here\n // similar to flatten, handle all levels of depth\n // use reduce to flatten the array and add integers to the startValue \n // if the curr value is an array, use recursion to run the function on the array again\n // if the value is a number, then add that to the total sum, else add 0\n // 0 is for any other value that is not a number\n return arr.reduce(function(sum, isNested){\n \n sum += (Array.isArray(isNested)) ? arraySum(isNested) : (typeof isNested === \"number\") ? isNested : 0;\n return sum;\n \n },0);\n\n}", "function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n sum=sum+array[index];\n index++;\n return add();\n }\n return add();\n}", "function sumOfSums(numberArray) {\n return numberArray.map(function (number, idx) {\n return numberArray.slice(0, idx + 1).reduce(function (sum, digit) {\n return sum + digit;\n });\n }).reduce(function (sum, partialSum) {\n return sum + partialSum;\n });\n}", "function func(accumulator, currentValue, currentIndex, sourceArray) {\n return accumulator + currentValue;\n}", "function mapReduce(f, a, seed) {\n\t\n\tfor (var i=0;i<a.length;i++){\n\t\tif (typeof a[i] != \"string\"){\n\t\t\ta[i] = a[i].toString()\n\t\t}\n\t\ta[i]=f(a[i]);\n\n\t}\n\tfor (var i=1;i<a.length;i++){\n\t\tif (typeof seed != \"undefined\"){\n\t\t\tfor (i=0;i<a.length;i++){\n\t\t\t\tseed = seed + f(a[i]);\n\t\t\t}\n\t\treturn seed;\n\t\t}\n\t\telse {\n\t\t\tif (typeof a[i] == \"string\"){\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\ta[i] = a[i].toString();\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t}\n\treturn a[0];\n\n}", "function sum(object) {\n let valArray = Object.values(object);\n let total = 0;\n valArray.forEach(function (item) {\n if (typeof (item) === 'number') {\n total = total + item;\n }\n });\n return total;\n}", "function summation(x){\n\tif(x % 1 !== 0) {return \"Invalid Value\";}\n\t\n\tvar total = 0;\n\twhile(x > 0){\n\t\ttotal += x;\n\t\tx -= 1;\n\t}\n\t\n\treturn total;\n}", "function reductions(source, xf, initial) {\n var reduction = initial;\n\n return accumulatable(function accumulateReductions(next, initial) {\n // Define a `next` function for accumulation.\n function nextReduction(accumulated, item) {\n reduction = xf(reduction, item);\n\n return item === end ?\n next(accumulated, end) :\n // If item is not `end`, pass accumulated value to next along with\n // reduction created by `xf`.\n next(accumulated, reduction);\n }\n\n accumulate(source, nextReduction, initial);\n });\n}", "computeSummation(num){\n if (num >= 1) return ( (num * (num + 1)) / 2);\n else return 0;\n }", "function sumAllFollowersFromTheUK(accumulator, currentValue) {\n // Write your code here\n}", "function combineOperations(startVal,arrOfFuncs){\n\n //////////solution 1\n // return arrOfFuncs.reduce((acc,func)=> {\n // return func(acc)\n // },startVal)\n\n ///////////solution 2\n // let output = startVal\n // arrOfFuncs.forEach(element=>{\n // output = element(output)\n // })\n // return output\n}" ]
{ "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)) { throw new Error('metadata.js needs to expose an object') } opts = req } return opts }
[ "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 (!both.content) {\n if (!both.header) {\n return { metadata, rawContent: content };\n }\n return { metadata, rawContent: both.header };\n }\n\n // New line characters => to handle all operating systems.\n const lines = both.header.split(/\\r?\\n/);\n\n // Loop that add to metadata the current content of the fields of the header\n // Like the format:\n // id:\n // title:\n // original_id:\n for (let i = 0; i < lines.length - 1; ++i) {\n const keyvalue = lines[i].split(\":\");\n const key = keyvalue[0].trim();\n let value = keyvalue\n .slice(1)\n .join(\":\")\n .trim();\n try {\n value = JSON.parse(value);\n } catch (err) {\n // Ignore the error as it means it's not a JSON value.\n }\n metadata[key] = value;\n }\n return { metadata, rawContent: both.content };\n }", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('metadata_metadata', 'get', kparams);\n\t}", "get manifest(){\n if(fs.existsSync(path.join(this.root, 'package.json'))){\n return JSON.parse(fs.readFileSync(path.join(this.root, 'package.json')))\n }\n }", "function getGeneratorMeta(rootDir, defaultName, defaultDescription) {\n let name = defaultName;\n let description = defaultDescription;\n if (rootDir && rootDir !== 'unknown') {\n try {\n const metapath = findup('package.json', { cwd: rootDir });\n const meta = JSON.parse(fs.readFileSync(metapath, 'utf8'));\n description = meta.description || description;\n name = meta.name || name;\n }\n catch (error) {\n if (error.message === 'not found') {\n logger.debug('no package.json found for generator');\n }\n else {\n logger.debug('unable to read/parse package.json for generator', {\n generator: defaultName,\n err: error.message,\n });\n }\n }\n }\n return { name, description };\n}", "function getID3Meta(song, coverPath) {\n\t\treturn {\n\t\t\ttitle: song.title,\n\t\t\tartist: song.artist,\n\t\t\talbum: song.album,\n\t\t\tcomposer: song.composer,\n\t\t\timage: coverPath\n\t\t}\n\t}", "function getVideoMetaData(opts, callback) {\n debug('fn: getVideoMetaData');\n var videoId;\n\n if (typeof opts === 'string') {\n videoId = opts;\n }\n\n if (_typeof(opts) === 'object') {\n videoId = opts.videoId;\n }\n\n var _opts$hl = opts.hl,\n hl = _opts$hl === void 0 ? 'en' : _opts$hl,\n _opts$gl = opts.gl,\n gl = _opts$gl === void 0 ? 'US' : _opts$gl;\n var uri = \"https://www.youtube.com/watch?hl=\".concat(hl, \"&gl=\").concat(gl, \"&v=\").concat(videoId);\n\n var params = _url.parse(uri);\n\n params.headers = {\n 'user-agent': _userAgent,\n 'accept': 'text/html',\n 'accept-encoding': 'gzip',\n 'accept-language': \"\".concat(hl, \"-\").concat(gl)\n };\n params.headers['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15';\n\n _dasu.req(params, function (err, res, body) {\n if (err) {\n callback(err);\n } else {\n if (res.status !== 200) {\n return callback('http status: ' + res.status);\n }\n\n if (_debugging) {\n var fs = require('fs');\n\n var path = require('path');\n\n fs.writeFileSync('dasu.response', res.responseText, 'utf8');\n }\n\n try {\n _parseVideoInitialData(body, callback);\n } catch (err) {\n callback(err);\n }\n }\n });\n}", "function getEntryMetadata(entryId, done) {\n\tdbEntry.getEntry(entryId, function(err, entry) {\n\t\tif (err) {\n\t\t\treturn done(err);\n\t\t}\n\n\t\t//got the core challenge info, now construct the meta data\n\t\tvar metadata = {\n\t\t\tfbAppId: dynamicConfig.facebookClientId,\n\t\t\tpublisherName : config.branding.siteName,\n\t\t\timageURL : dynamicConfig.nodeHostname + config.url.entryImages + entry.id + \".\" + mime.extension(entry.imageType),\n\t\t\tpageTitle : \"Caption Entry: \" + entry.caption + \" | \" + config.branding.siteName,\n\t\t\tpageURL : dynamicConfig.nodeHostname + config.url.entry + entry.id,\n\t\t\tpageDescription : \"Posted by \" + entry.postedByUser.displayName + \". Like this entry? Check out more such entries, and challenge yourself to post one of your own! It takes just a few minutes, and it's free :)\",\n\t\t\timageType : entry.imageType,\n\t\t\tauthorName : entry.postedByUser.displayName\n\t\t};\n\n\t\tvar output = {\n\t\t\tentry: entry,\n\t\t\tmetadata: metadata\n\t\t};\n\n\t\treturn done(null, output);\n\t});\n}", "function getClientMetadata() {\n // check if in session storage already\n var metadata = JSON.parse(sessionStorage.getItem(exports.STORAGE_KEY) || '{}');\n // if not retrieve and store in session storage\n if (!metadata.sessionId) {\n metadata = {\n sessionId: uuid_1.createUUID(),\n browser: {\n mobile: /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),\n userAgent: navigator.userAgent,\n resolution: screen.width + \"x\" + screen.height + \"x\" + screen.colorDepth\n }\n };\n sessionStorage.setItem(exports.STORAGE_KEY, JSON.stringify(metadata));\n }\n return metadata;\n}", "function getChallengeMetadata(challengeId, done) {\n\tdbChallenge.getChallenge(challengeId, function(err, challenge) {\n\t\tif (err) {\n\t\t\treturn done(err);\n\t\t}\n\n\t\t//got the core challenge info, now construct the meta data\n\t\tvar metadata = {\n\t\t\tfbAppId: dynamicConfig.facebookClientId,\n\t\t\tpublisherName : config.branding.siteName,\n\t\t\timageURL : dynamicConfig.nodeHostname + config.url.challengeImages + challenge.id + \".\" + mime.extension(challenge.imageType),\n\t\t\tpageTitle : \"Challenge: \" + challenge.caption + \" | \" + config.branding.siteName,\n\t\t\tpageURL : dynamicConfig.nodeHostname + config.url.challenge + challenge.id,\n\t\t\tpageDescription : \"Posted by \" + challenge.postedByUser.displayName + \". Up for the challenge? Check out the challenge and post your entry now, it's free and takes just a few minutes! Also, check out the awesome entries posted by others :)\",\n\t\t\timageType : challenge.imageType,\n\t\t\tauthorName : challenge.postedByUser.displayName\n\t\t};\n\n\t\tvar output = {\n\t\t\tchallenge: challenge,\n\t\t\tmetadata: metadata\n\t\t};\n\n\t\treturn done(null, output);\n\t});\n}", "function getMetaData(linkHeader) {\n\n if(!linkHeader) return null;\n\n var metadata = {\n first_page: 1,\n last_page: null,\n next_page: null,\n prev_page: null\n };\n\n var linkArr = linkHeader.split(',');\n\n _.each(linkArr, function (link) {\n var start_pos = link.indexOf('<') + 1;\n var end_pos = link.indexOf('>',start_pos);\n var url = link.substring(start_pos,end_pos)\n var page = Number(getParam(url, 'page'));\n\n if (link.indexOf('rel=\"last\"') !== -1) {\n metadata.last_page = page;\n } else if (link.indexOf('rel=\"first\"') !== -1) {\n metadata.first_page = page;\n } else if (link.indexOf('rel=\"next\"') !== -1) {\n metadata.next_page = page;\n } else if (link.indexOf('rel=\"prev\"') !== -1) {\n metadata.prev_page = page;\n }\n });\n\n return metadata;\n\n}", "function readManifest() {\n if (manifestExists()){\n var manifestString = fs.readFileSync(testManifestPath, 'utf8');\n var manifestJSON = JSON.parse(manifestString);\n return manifestJSON;\n }\n\n return {};\n}", "function tlds() {\n // reading as file will make sure that we read new file upon package renewal\n try {\n return JSON.parse(fs.readFileSync(json_path,'utf8'))\n }catch(err) {}\n return false\n}", "function getPlaylistMetaData(opts, callback) {\n debug('fn: getPlaylistMetaData');\n var listId;\n\n if (typeof opts === 'string') {\n listId = opts;\n }\n\n if (_typeof(opts) === 'object') {\n listId = opts.listId || opts.playlistId;\n }\n\n var _opts$hl2 = opts.hl,\n hl = _opts$hl2 === void 0 ? 'en' : _opts$hl2,\n _opts$gl2 = opts.gl,\n gl = _opts$gl2 === void 0 ? 'US' : _opts$gl2;\n var uri = \"https://www.youtube.com/playlist?hl=\".concat(hl, \"&gl=\").concat(gl, \"&list=\").concat(listId);\n\n var params = _url.parse(uri);\n\n params.headers = {\n 'user-agent': _userAgent,\n 'accept': 'text/html',\n 'accept-encoding': 'gzip',\n 'accept-language': \"\".concat(hl, \"-\").concat(gl)\n };\n\n _dasu.req(params, function (err, res, body) {\n if (err) {\n callback(err);\n } else {\n if (res.status !== 200) {\n return callback('http status: ' + res.status);\n }\n\n if (_debugging) {\n var fs = require('fs');\n\n var path = require('path');\n\n fs.writeFileSync('dasu.response', res.responseText, 'utf8');\n }\n\n try {\n _parsePlaylistInitialData(body, callback);\n } catch (err) {\n callback(err);\n }\n }\n });\n}", "function getUserMetadata(userId, done) {\n\tdbUser.getUser(userId, function(err, user) {\n\t\tif (err) {\n\t\t\treturn done(err);\n\t\t}\n\n\t\t//got the core challenge info, now construct the meta data\n\t\tvar metadata = {\n\t\t\tfbAppId: dynamicConfig.facebookClientId,\n\t\t\tpublisherName : config.branding.siteName,\n\t\t\timageURL : dynamicConfig.nodeHostname + user.image,\n\t\t\tpageTitle : \"User: \" + user.displayName + \" | \" + config.branding.siteName,\n\t\t\tpageURL : dynamicConfig.nodeHostname + config.url.user + user.id,\n\t\t\tpageDescription : \"Captionify User Profile for \" + user.displayName,\n\t\t\timageType : serverUtils.getMimeTypeForImage(user.image),\n\t\t\tauthorName : config.branding.siteName\n\t\t};\n\n\t\tvar output = {\n\t\t\tuserInfo: user,\n\t\t\tmetadata: metadata\n\t\t};\n\n\t\treturn done(null, output);\n\t});\n}", "function package_info() {\n try {\n var pkg = require('../../package.json');\n return pkg;\n }\n catch (err) {\n return {\n name: 'aws-crt-nodejs',\n version: 'UNKNOWN'\n };\n }\n}", "function getMetadata(sampleId) {\n d3.json(\"samples.json\").then((data) => {\n console.log(data)\n\n var metadata = data.metadata;\n //console.log(metadata)\n var metadataArray = metadata.filter(metadataObject => metadataObject.id == sampleId);\n //console.log(metadataArray)\n var metadataResult = metadataArray[0]\n //console.log(metadataResult)\n \n // Update the Demographic Info panel data reflected on the screen with the selected \"Test Subject ID No\"\n var demoInfo = d3.select(\"#sample-metadata\");\n demoInfo.html(\"\");\n Object.entries(metadataResult).forEach(([key, value]) => {\n demoInfo.append(\"h6\").text(`${key}: ${value}`);\n });\n\n // BONUS: Wash Frequency Gauge Chart\n var washFrequency = metadataResult.wfreq;\n \n var gaugeData = [\n {\n type: \"indicator\",\n mode: \"gauge+number\",\n value: washFrequency,\n title: { text: \"Wash Frequency\", font: { size: 24 } },\n gauge: {\n axis:\n { range: [0, 9], tickcolor: \"darkblue\" },\n \n bar: { color: \"teal\" },\n bgcolor: \"white\",\n borderwidth: 2,\n bordercolor: \"lightgray\",\n steps: [\n { range: [0, 9], color: \"beige\", label: \"0-1\" }\n ],\n }\n }\n ];\n \n var gaugeLayout = {\n width: 500,\n height: 400,\n margin: { t: 100, \n r: 30, \n l: 30, \n b: 30 },\n paper_bgcolor: \"white\",\n font: { color: \"teal\", family: \"Arial\" }\n };\n \n Plotly.newPlot('gauge', gaugeData, gaugeLayout);\n //Plotly.newPlot('gauge', gaugeData, gaugeLayout);\n });\n }", "function jsonObjFromFile(fn) {\n var jsonObj = [];\n try {\n var data = fs.readFileSync(fn, 'utf-8');\n if (data) {\n jsonObj = JSON.parse(data);\n } else {\n console.log(basicFile + \": no data\");\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n console.log('File not found:' + fn);\n } else {\n throw err;\n }\n }\n return jsonObj;\n}", "function getTenantScriptMetadata(axios$$1, identifier, tenantToken, scriptId) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts/' + scriptId);\n }" ]
{ "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,w,h){const el=document.createElementNS(BrowserCodeSvgWriter.SVG_NS,'rect');el.setAttributeNS(svgNs,'x',x.toString());el.setAttributeNS(svgNs,'y',y.toString());el.setAttributeNS(svgNs,'height',w.toString());el.setAttributeNS(svgNs,'width',h.toString());el.setAttributeNS(svgNs,'fill','#000000');return el;}", "function setRectAttr(rectEl, x, y, width, height) {\n rectEl.each(function () {\n $(this).attr({\n x: roundTo(x,2),\n y: roundTo(y,2),\n width: roundTo(width,2),\n height: roundTo(height,2),\n });\n });\n }", "static childBounds(svgElement) {\n var result \n svgElement.childNodes.forEach(ea => {\n var r = ea.getBoundingClientRect() \n var b = rect(r.x, r.y, r.width, r.height)\n result = (result || b).union(b)\n })\n return result\n }", "function Rectangulo(x, y, ancho, alto)\n{\n\n this.x = x;\n this.y = y;\n this.ancho = ancho;\n this.alto = alto;\n\n}", "static getHitbox(child) {\r\n if (isser_1.isDisplayObjectContainer(child)) {\r\n const hitboxes = child.getChildren().map(child => this.getHitbox(child));\r\n const allX = [];\r\n const allY = [];\r\n hitboxes.forEach((box) => {\r\n allX.push(box.topLeft.x, box.topRight.x, box.bottomLeft.x, box.bottomRight.x);\r\n allY.push(box.topLeft.y, box.topRight.y, box.bottomLeft.y, box.bottomRight.y);\r\n });\r\n const left = Math.min(...allX);\r\n const right = Math.max(...allX);\r\n const top = Math.min(...allY);\r\n const bottom = Math.max(...allY);\r\n const result = {\r\n topLeft: { x: left, y: top },\r\n topRight: { x: right, y: top },\r\n bottomLeft: { x: left, y: bottom },\r\n bottomRight: { x: right, y: bottom }\r\n };\r\n return result;\r\n }\r\n else {\r\n const matrix = child.worldMatrix;\r\n const topLeft = this.transformPoint(0, 0, matrix);\r\n const topRight = this.transformPoint(child.width, 0, matrix);\r\n const bottomLeft = this.transformPoint(0, child.height, matrix);\r\n const bottomRight = this.transformPoint(child.width, child.height, matrix);\r\n const result = {\r\n topLeft: topLeft,\r\n topRight: topRight,\r\n bottomLeft: bottomLeft,\r\n bottomRight: bottomRight\r\n };\r\n return result;\r\n }\r\n }", "function rect( x,y,w,h, color){\n\t\n var x = x;\n var y = y;\n var w = w;\n var h = h;\n var color = color;\n\n \t//defaults\n if(x == undefined) x = 0;\n if(y == undefined) y = 0;\n if(w == undefined) w = 100;\n if(h == undefined) h = 100;\n if(color == undefined) color = \"lightgrey\";\t\n\n\trectElem = document.createElement(\"div\");\n\t// rectElem.id = id;\n\n rectElem.innerHTML = \"\";\n rectElem.style.backgroundColor = color;\n rectElem.style.position =\"absolute\";\n rectElem.style.left = x + \"px\";\n rectElem.style.width = w + \"px\";\n rectElem.style.top = y + \"px\";\n rectElem.style.height = h + \"px\";\n \n //temp\n // rectElem.style.border = \"1px solid blue\";\n\n return rectElem;\n\n}", "function positionRect(rect, cx, cy, width, height) {\n rect.transition().attr({\n x: cx - width / 2,\n y: cy - height / 2,\n width: width,\n height: height\n });\n }", "function RectangleExtended(pos, id, angle, news) {\n var w = 20;\n var h = 20;\n this.fabricRect = new fabric.Rect({\n left: Math.round(pos.x - w/2),\n top: Math.round(pos.y - h/2),\n width: w,\n height: h,\n angle: angle,\n fill: '#e0e0e0',\n opacity: 0.8,\n strokeWidth: 1,\n stroke: '#004d40',\n selectable: true,\n hasControls: false,\n hasBorders: false,\n lockMovementX: true,\n lockMovementY: true\n });\n this.news=news;\n this.id = id;\n}", "function rounded_rect(x, y, w, h, r, tl, tr, bl, br) {\n\t\t\t var retval;\n\t\t\t retval = \"M\" + (x + r) + \",\" + y;\n\t\t\t retval += \"h\" + (w - 2*r);\n\t\t\t if (tr) { retval += \"a\" + r + \",\" + r + \" 0 0 1 \" + r + \",\" + r; }\n\t\t\t else { retval += \"h\" + r; retval += \"v\" + r; }\n\t\t\t retval += \"v\" + (h - 2*r);\n\t\t\t if (br) { retval += \"a\" + r + \",\" + r + \" 0 0 1 \" + -r + \",\" + r; }\n\t\t\t else { retval += \"v\" + r; retval += \"h\" + -r; }\n\t\t\t retval += \"h\" + (2*r - w);\n\t\t\t if (bl) { retval += \"a\" + r + \",\" + r + \" 0 0 1 \" + -r + \",\" + -r; }\n\t\t\t else { retval += \"h\" + -r; retval += \"v\" + -r; }\n\t\t\t retval += \"v\" + (2*r - h);\n\t\t\t if (tl) { retval += \"a\" + r + \",\" + r + \" 0 0 1 \" + r + \",\" + -r; }\n\t\t\t else { retval += \"v\" + -r; retval += \"h\" + r; }\n\t\t\t retval += \"z\";\n\t\t\t return retval;\n\t\t\t}", "createSprite() {\n this.sprite = new PIXI.Sprite(PIXI.loader.resources[this.category].textures[this.spriteName]);\n if(this.isOnFloor) {\n this.sprite.position.set(this.x, this.y);\n }\n this.sprite.width = this.sprite.height = this.spriteSize;\n this.floor.itemSprites.addChild(this.sprite);\n\n // would be nice to consolidate to a function. currently not working\n // this._textStyle = new PIXI.TextStyle({\n // fill: '#fff',\n // fontSize: 17\n // });\n // this.itemNameSprite = new PIXI.Text(this.spriteName, this._textStyle);\n // /* eslint-disable-next-line no-extra-parens */\n // this.itemNameSpriteOffset = (this.sprite.width / 2) - (this.itemNameSprite.width / 2);\n // this.itemNameSprite.position.set(\n // this.sprite.position.x + this.itemNameSpriteOffset,\n // this.sprite.position.y - 15\n // );\n // this.floor.itemSprites.addChild(this.itemNameSprite);\n }", "getIndex (rect){\n\n var index = -1\n //\n const verticalMidPoint = this.bounds.x + this.bounds.width / 2\n const horizontalMidPoint = this.bounds.y + this.bounds.height / 2\n // object can completely fit within the top quadrants\n const topQuadrant = rect.y < horizontalMidPoint && rect.y + rect.height < horizontalMidPoint\n // object can completely fit within the bottom quadrants\n const bottomQuadrant = rect.y > horizontalMidPoint\n\n // object can completely fit within the left quadrant\n if (rect.x < verticalMidPoint && rect.x + rect.width < verticalMidPoint) {\n\n if (topQuadrant) {\n index = 1\n } else if (bottomQuadrant) {\n index = 2\n }\n\n }\n // object can completely fit within the right quadrant\n else if (rect.x > verticalMidPoint) {\n\n if (topQuadrant) {\n index = 0\n } else if (bottomQuadrant) {\n index = 3\n }\n\n }\n\n return index\n\n }", "function Sprite( params ) {\n this.game = params.game;\n var r = this.game.getSprite( params.imageid );\n if( !r ) {\n console.log( \"Sprite id :\" + params.id + \" references invalid image\");\n return;\n }\n\n // body width/heihgt can be different thatn physical dimensiosn due to margin\n this.margins = {top:r.sprite.top/SCALE,\n left:r.sprite.left/SCALE,\n right:r.sprite.right/SCALE,\n bottom:r.sprite.bottom/SCALE};\n\n params.width = r.sprite.w/SCALE - this.margins.left - this.margins.right;\n params.height = r.sprite.h/SCALE - this.margins.top - this.margins.bottom;\n params.x += this.margins.left;\n params.y += this.margins.top;\n RectangleEntity.call(this, params);\n this.imageid = params.imageid;\n this.bodyless = params.bodyless;\n}", "project(x, y) {\n var width = this.width;\n var height = this.height;\n var vpRadius = Math.sqrt(width*width + height*height) / 2;\n var scale = this.scene.view.r / vpRadius;\n var vLeft = this.scene.view.x - width * scale / 2;\n var vTop = this.scene.view.y + height * scale / 2;\n return {\n a: vLeft + x * scale,\n b: vTop - y * scale\n };\n }", "static getBounds(rectangle, matrix, out = null) {\n if (!out) out = new Rectangle()\n\n let minX = Number.MAX_VALUE,\n maxX = -Number.MAX_VALUE\n let minY = Number.MAX_VALUE,\n maxY = -Number.MAX_VALUE\n const positions = RectangleUtil.getPositions(\n rectangle,\n RectangleUtil.sPositions\n )\n\n for (let i = 0; i < 4; ++i) {\n MatrixUtil.transformCoords(\n matrix,\n positions[i].x,\n positions[i].y,\n RectangleUtil.sPoint\n )\n\n if (minX > RectangleUtil.sPoint.x) minX = RectangleUtil.sPoint.x\n if (maxX < RectangleUtil.sPoint.x) maxX = RectangleUtil.sPoint.x\n if (minY > RectangleUtil.sPoint.y) minY = RectangleUtil.sPoint.y\n if (maxY < RectangleUtil.sPoint.y) maxY = RectangleUtil.sPoint.y\n }\n\n out.setTo(minX, minY, maxX - minX, maxY - minY)\n return out\n }", "path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }", "function convertCoordinates (ele)\r\n\t{\r\n\t\tvar gps = coordinates (ele); //gets the coordinates of the puzzle piece\r\n\r\n\t\tvar l = parseInt (gps[0], 10); //left value: x coordinate\r\n\t\tvar t = parseInt (gps[1], 10); //top value: y coordinate\r\n\r\n\t\tl = l/100;\r\n\t\tt = t/100;\r\n\r\n\t\treturn l + \" \" + t;\r\n\t}", "function Terrain_Square(x,y,w,h,type,which_sprite_array,name_of_sprite_sheet){\n\n\tthis.x = x * w;\n\tthis.y = y * h; \n\tthis.w = w;\n\tthis.h = h;\n\n\t//console.log(\"1which_sprite_array is: \" + which_sprite_array);\n\t\n\t//so that these 4 values dont need to be calculated over and over again. \n\tthis.ulc_x = this.x;\n\tthis.urc_x = this.x + this.w;\n\tthis.ulc_y = this.y;\n\tthis.llc_y = this.y + this.h;\n\n\tthis.contains_mouse = false;\n\tthis.color = \"black\";//random default. not associated with any type currently. \n\n\tif(type == 0){\n\t\tthis.color = \"yellow\";\n\t}\n\telse if(type == 1){\n\t\tthis.color = \"red\";\n\t}\n\n\t\n\tthis.type = type; //can it be walked on.\n\tthis.sprite_sheet = document.getElementById(name_of_sprite_sheet);\n\tthis.ssi = new SSI();\n\tthis.ssi.set_x_y_w_h_dw_and_dh(which_sprite_array[0],\n\t\t\t\t\t\t\t\t which_sprite_array[1],\n\t\t\t\t\t\t\t\t which_sprite_array[2],\n\t\t\t\t\t\t\t\t which_sprite_array[3],\n\t\t\t\t\t\t\t\t this.w,\n\t\t\t\t\t\t\t\t this.h\n\t\t\t\t\t\t\t\t );\n\n}", "function drawRects() {\n\n var rectangles = svg.append('g')\n .selectAll(\"rect\")\n .data(taskArray)\n .enter();\n\n\n var innerRects = rectangles.append(\"rect\")\n .attr(\"height\", barHeight)\n .attr(\"stroke\", \"none\");\n\n var mobileLabelRect = rectangles.append(\"rect\")\n .attr(\"y\", function (d, i) {\n return i * gap - 15 + topPadding;\n })\n .attr(\"opacity\", '0.3')\n .attr(\"height\", 15)\n .attr(\"stroke\", 'none')\n .attr(\"class\", \"mobile-label-rect\");\n\n var rectText = rectangles.append(\"text\")\n .attr(\"y\", function (d, i) {\n return i * gap - 4 + topPadding;\n })\n .attr(\"font-size\", 11)\n .attr(\"class\", \"rect-text\")\n .attr(\"text-height\", barHeight)\n .attr(\"font-style\", \"italic\")\n .attr(\"fill\", \"#000000\");\n\n }", "function toCoordinate(id_num) {\n // Math doesnn't work properly for last cell\n if (id_num === \"256\") {\n return [15, 15];\n }\n else {\n id_num = parseInt(id_num);\n var x = Math.floor((id_num-1)/16);\n var y = id_num-(16*x);\n return [x, y-1];\n }\n}" ]
{ "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.setItem(\"shoppingCart\", JSON.stringify(cart));\r\n }", "function saveDeliveryAddress(delivery_address){\n var cart_data = JSON.parse(localStorage.getItem('cart_data'));\n var delivery_method = document.getElementById(\"shippingMethodInput\").value;\n\n cart_data[\"delivery_address\"] = delivery_address;\n cart_data[\"delivery_method\"] = delivery_method;\n\n localStorage.setItem('cart_data', JSON.stringify(cart_data));\n\n console.log(\"Update delivery address and method to cart_data\");\n console.log(cart_data);\n}", "@action\n async save() {\n await this.rdfaCommunicator.persist();\n this.owner.lookup(SAVE_RESET_KEY).handleClose(this.args.info, null);\n }", "function updateLocalStorage() {\n\tlocalStorage.setItem('transactions', JSON.stringify(transactions));\n}", "save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }", "function setAmount() {\n localStorage.setItem(\"amount\", JSON.stringify(amount)); //updates the cart\n }", "function saveCartToLocalStorage() {\n localStorage.setItem('cart', JSON.stringify(Product.allProductsInCart));\n}", "function descSave() {\n localStorage.setItem(\"dailyDesc\", JSON.stringify(dailyDesc));\n}", "function saveLib(){\n chrome.storage.local.set({'library': raw_notes}, function(){\n console.log(\"Library successfully saved.\");\n });\n}", "getReceiptById(receiptId) {\n console.log(\"getting by \", receiptId);\n let receipts = this.storage.getItem('receipts') || {};\n return receipts[receiptId];\n }", "saveArt(){\n this.name = prompt('Enter File Name', this.name);\n if(this.name)\n {\n localStorage.setItem(`art_${this.name}`, JSON.stringify(app.art));\n }\n }", "static persist() {\n let questionsJson = JSON.stringify(questions);\n fs.writeFileSync(storagePath, questionsJson, 'utf-8');\n }", "function saveData() {\n if (hasLocalStorage)\n {\n localStorage.setItem(SAVE_LOCATION, JSON.stringify(books));\n }\n}", "function save(){\n EWD.sockets.sendMessage({\n type: \"saveLabOrder\",\n params: {\n id: \"1\",\n comment: document.getElementById(\"comment\").value,\n selectedTest: document.getElementById(\"testList\").value,\n collectionType: document.getElementById(\"collectionType\").value ,\n howOften: document.getElementById(\"howOften\").value,\n collectionDate: document.getElementById(\"collectionDate\").value,\n collectionSample: document.getElementById(\"collectionSample\").value,\n specimen: document.getElementById(\"specimen\").value,\n urgency: document.getElementById(\"urgency\").value,\n notifyProviders: document.getElementById(\"selectProvHidden\").value, \n howLong: document.getElementById(\"howLong\").value,\n sender: 'ELOM',\n date: new Date().toUTCString() \n }\n });\n }", "function storeAccountDetails(accountObj){\n\tlocalStorage.konyAccountDetails = JSON.stringify(accountObj); //storing the corresponding account details in localstorage\n\twindow.location.href = \"accountDetails.html\"; //redirecting to details page\n}", "function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}", "function runLocalStorage() {\n\t\n\tlet htmlModal = '';\n\thtmlModal = '<div id=\"modalLocalStorage\" class=\"modal fade\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"modalLocalStorageTitle\">';\n\thtmlModal += '<div class=\"modal-dialog\" role=\"document\">';\n\thtmlModal += '<div class=\"modal-content\">';\n\thtmlModal += '<div class=\"modal-header\">';\n\thtmlModal += '<h5 class=\"modal-title\" id=\"modalLocalStorageTitle\">' + langVallydette.recoverTitle + '</h5>';\n\thtmlModal += '<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"' + langVallydette.close + '\"></button>';\n\thtmlModal += '</div>';\n\thtmlModal += '<div class=\"modal-body\" id=\"modalLocalStorageForm\">';\n\thtmlModal += '</div>';\n\thtmlModal += '<div class=\"modal-footer\">';\n\thtmlModal += '<button type=\"button\" id=\"localStorageCancelBtn\" class=\"btn btn-secondary\" data-dismiss=\"modal\">' + langVallydette.cancel + '</button>';\n\thtmlModal += '<button type=\"button\" id=\"localStorageSaveBtn\" data-dismiss=\"modal\" class=\"btn btn-primary\">' + langVallydette.recoverAction + '</button>';\n\thtmlModal += '<button type=\"button\" id=\"localStorageDeleteBtn\" class=\"btn btn-danger\">' + langVallydette.deleteAction + '</button>'\n\thtmlModal += '</div></div></div></div>';\n\t\n\tlet elModal = document.getElementById('modal');\n\telModal.innerHTML = htmlModal;\n\tcreateFormLocalStorage();\n\n\tvar localStorageSaveBtn = document.getElementById(\"localStorageSaveBtn\");\n\tlocalStorageSaveBtn.addEventListener('click', function () {\n\t\tvalueSelect = document.querySelector('input[name=\"auditRadioRestore\"]:checked').value;\n\t\tgetLocalStorage(valueSelect);\n\t});\n\n\tvar localStorageDeleteBtn = document.getElementById(\"localStorageDeleteBtn\");\n\tlocalStorageDeleteBtn.addEventListener('click', function () {\n\t\tvalueSelect = document.querySelector('input[name=\"auditRadioRestore\"]:checked').value;\n\t\tlet selectChecklist = window.localStorage.getItem(valueSelect);\n\t\tselectChecklist = JSON.parse(selectChecklist);\n\t\tlet HtmlDivDelete ='';\n\t\tHtmlDivDelete += '<p>'+ langVallydette.deleteAsk +' '+ selectChecklist.checklist.name +' ?</p>';\n\t\tHtmlDivDelete += '<button type=\"button\" id=\"localStorageDeleteYesBtn\" class=\"btn btn-primary\">' + langVallydette.yes + '</button>';\n\t\tHtmlDivDelete += '<button type=\"button\" id=\"localStorageDeleteNoBtn\" class=\"btn btn-danger ml-2\">' + langVallydette.no + '</button>'\n\t\tlet elDivDelete = document.getElementById('localStorageValidDelete');\n\t\telDivDelete.innerHTML = HtmlDivDelete;\n\t\telDivDelete.focus();\n\n\t\tvar localStorageDeleteYesBtn = document.getElementById(\"localStorageDeleteYesBtn\");\n\t\tlocalStorageDeleteYesBtn.addEventListener('click', function () {\n\t\t\tvalueSelect = document.querySelector('input[name=\"auditRadioRestore\"]:checked').value;\n\t\t\twindow.localStorage.removeItem(valueSelect);\n\t\t\tcreateFormLocalStorage();\n\t\t\tif(Object.keys(getAllStorage()).length === 0){\n\t\t\t\tdocument.getElementById(\"localStorageCancelBtn\").click();\n\t\t\t\tdocument.getElementById('btnExcelExport').focus();\n\t\t\t\tlet btnLocalStorage = document.getElementById(\"btnLocalStorage\");\n\t\t\t\tbtnLocalStorage.disabled=true;\n\t\t\t\tbtnLocalStorage.classList.add(\"disabled\");\n\t\t\t}\n\t\t\telse{\n\t\t\t\tdocument.getElementById(document.querySelector('input[name=\"auditRadioRestore\"]:checked').id).focus();\n\t\t\t}\t\n\t\t});\n\n\t\tvar localStorageDeleteNoBtn = document.getElementById(\"localStorageDeleteNoBtn\");\n\t\tlocalStorageDeleteNoBtn.addEventListener('click', function () {\n\t\t\tcreateFormLocalStorage();\n\t\t\tdocument.getElementById(document.querySelector('input[name=\"auditRadioRestore\"]:checked').id).focus();\n\t\t});\n\t});\n\n\t\n\n}", "function saveNotificationService(notificationService, filename) {\n console.log();\n notificationService.save(filename);\n}", "addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }" ]
{ "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) {\n\tvar editableDiv = document.getElementById(\"inputTextarea\");\n\tvar curPos = getCaretPositionInDiv(editableDiv);\n\tsetCaretPositionInDiv(editableDiv, pos);\n\tvar word = getCurrentWord();\n\tsetCaretPositionInDiv(editableDiv, curPos);\n\treturn word;\n}", "buildHighlightPosition (position, linenum, text) {\n var remainingCharacters = position;\n let lines = text.split(\"\\n\");\n\n // Iterate until we get to the position of the character we need, and then build\n // a relative vscode.Position.\n for (var i = 0; i < lines.length; i++) {\n let charactersInLine = lines[i].length + 1; // +1 for the newline.\n\n if (remainingCharacters - charactersInLine < 0) {\n return new vscode.Position(linenum - 1, remainingCharacters);\n }\n\n remainingCharacters = remainingCharacters - charactersInLine;\n }\n\n // If we get here, there's probaly a buffer mismatch.\n return undefined;\n }", "function _getRange() {\n\t\t// sel: a selection object representing the range of text selected by the user\n\t\tvar sel = win.getSelection();\n\t\t// Return a range object representing the current selection or false\n\t\treturn (sel.rangeCount) ? sel.getRangeAt(0) : false;\n\t}", "getChar(pos) {\n return this.document.getText(new vscode.Range(pos, pos.translate(0, 1)));\n }", "getPrev(pos) {\n if (pos.character === 0 && pos.line === 0)\n throw new Error(\"Attempt to get position before (0,0)!\");\n return this.document.positionAt(this.document.offsetAt(pos) - 1);\n }", "getSelectionEntity(editorState) {\n let entity;\n const selection = editorState.getSelection();\n let start = selection.getStartOffset();\n let end = selection.getEndOffset();\n if (start === end && start === 0) {\n end = 1;\n } else if (start === end) {\n start -= 1;\n }\n const block = this.getSelectedBlock(editorState);\n\n for (let i = start; i < end; i += 1) {\n const currentEntity = block.getEntityAt(i);\n if (!currentEntity) {\n entity = undefined;\n break;\n }\n if (i === start) {\n entity = currentEntity;\n } else if (entity !== currentEntity) {\n entity = undefined;\n break;\n }\n }\n return entity;\n }", "*positions(editor) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n at = editor.selection,\n unit = 'offset',\n reverse: reverse$1 = false\n } = options;\n\n if (!at) {\n return;\n }\n\n var range = Editor.range(editor, at);\n var [start, end] = Range.edges(range);\n var first = reverse$1 ? end : start;\n var string = '';\n var available = 0;\n var offset = 0;\n var distance = null;\n var isNewBlock = false;\n\n var advance = () => {\n if (distance == null) {\n if (unit === 'character') {\n distance = getCharacterDistance(string);\n } else if (unit === 'word') {\n distance = getWordDistance(string);\n } else if (unit === 'line' || unit === 'block') {\n distance = string.length;\n } else {\n distance = 1;\n }\n\n string = string.slice(distance);\n } // Add or substract the offset.\n\n\n offset = reverse$1 ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.\n\n available = available - distance; // If the available had room to spare, reset the distance so that it will\n // advance again next time. Otherwise, set it to the overflow amount.\n\n distance = available >= 0 ? null : 0 - available;\n };\n\n for (var [node, path] of Editor.nodes(editor, {\n at,\n reverse: reverse$1\n })) {\n if (Element.isElement(node)) {\n // Void nodes are a special case, since we don't want to iterate over\n // their content. We instead always just yield their first point.\n if (editor.isVoid(node)) {\n yield Editor.start(editor, path);\n continue;\n }\n\n if (editor.isInline(node)) {\n continue;\n }\n\n if (Editor.hasInlines(editor, node)) {\n var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);\n var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);\n var text = Editor.string(editor, {\n anchor: s,\n focus: e\n });\n string = reverse$1 ? esrever.reverse(text) : text;\n isNewBlock = true;\n }\n }\n\n if (Text.isText(node)) {\n var isFirst = Path.equals(path, first.path);\n available = node.text.length;\n offset = reverse$1 ? available : 0;\n\n if (isFirst) {\n available = reverse$1 ? first.offset : available - first.offset;\n offset = first.offset;\n }\n\n if (isFirst || isNewBlock || unit === 'offset') {\n yield {\n path,\n offset\n };\n }\n\n while (true) {\n // If there's no more string, continue to the next block.\n if (string === '') {\n break;\n } else {\n advance();\n } // If the available space hasn't overflow, we have another point to\n // yield in the current text node.\n\n\n if (available >= 0) {\n yield {\n path,\n offset\n };\n } else {\n break;\n }\n }\n\n isNewBlock = false;\n }\n }\n }", "position(line, column) {\n return new vscode.Position(line, column);\n }", "visualLineAt(pos, editorTop = 0) {\n return this.viewState.lineAt(pos, editorTop);\n }", "textDirectionAt(pos) {\n let perLine = this.state.facet(perLineTextDirection)\n if (!perLine || pos < this.viewport.from || pos > this.viewport.to)\n return this.textDirection\n this.readMeasured()\n return this.docView.textDirectionAt(pos)\n }", "function setCaretPosition(position) {\n\tdocument.getElementById(\"content-editor\").setSelectionRange(position, position);\n\tdocument.getElementById(\"content-editor\").focus();\n}", "function getLastPosition()\n {\n var newSize;\n\n // get last known ui position\n if ( typeof lastState.position !== \"undefined\" )\n {\n newPosition = {\n left: lastState.position.left,\n top: lastState.position.top\n }\n }\n\n // if no previous position, use defaults\n else\n {\n var lastSize = getLastSize();\n newPosition = {\n left: $window.width() - lastSize.uiWidth,\n top: $window.height() - lastSize.uiHeight\n }\n }\n\n return newPosition;\n }", "get currentLine() {\n return this.lines[ this.cursor.y ].textContent;\n }", "function getStateExpr(index) {\n\t\treturn Calc.getState().expressions.list[index];\n\t}", "get visibleEditors() {\n return vscode.window.visibleTextEditors;\n }", "get onDidChangeActiveTextEditor() {\n return vscode.window.onDidChangeActiveTextEditor;\n }", "function peek() {\n return tokens[position];\n }", "marks(editor) {\n var {\n marks,\n selection\n } = editor;\n\n if (!selection) {\n return null;\n }\n\n if (marks) {\n return marks;\n }\n\n if (Range.isExpanded(selection)) {\n var [match] = Editor.nodes(editor, {\n match: Text.isText\n });\n\n if (match) {\n var [_node] = match;\n\n var _rest = _objectWithoutProperties(_node, [\"text\"]);\n\n return _rest;\n } else {\n return {};\n }\n }\n\n var {\n anchor\n } = selection;\n var {\n path\n } = anchor;\n var [node] = Editor.leaf(editor, path);\n\n if (anchor.offset === 0) {\n var prev = Editor.previous(editor, {\n at: path,\n match: Text.isText\n });\n var block = Editor.above(editor, {\n match: n => Editor.isBlock(editor, n)\n });\n\n if (prev && block) {\n var [prevNode, prevPath] = prev;\n var [, blockPath] = block;\n\n if (Path.isAncestor(blockPath, prevPath)) {\n node = prevNode;\n }\n }\n }\n\n var rest = _objectWithoutProperties(node, [\"text\"]);\n\n return rest;\n }", "_getCaretPosition(field) {\n\t\t// Initialize\n\t\tlet caretPos = 0;\n\n\t\t// IE Support\n\t\tif (document.selection) {\n\t\t\t// Set focus on the element\n\t\t\tfield.focus();\n\n\t\t\t// To get cursor position, get empty selection range\n\t\t\tconst selection = document.selection.createRange();\n\n\t\t\t// Move selection start to 0 position\n\t\t\tselection.moveStart(\"character\", -field.value.length);\n\n\t\t\t// The caret position is selection length\n\t\t\tcaretPos = selection.text.length;\n\t\t} else if (field.selectionStart || field.selectionStart === \"0\") { // Firefox support\n\t\t\tcaretPos = field.selectionDirection === \"backward\" ? field.selectionStart : field.selectionEnd;\n\t\t}\n\n\t\treturn caretPos;\n\t}" ]
{ "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 = (new Skill().findSkill(command.name, data) || {}).priority || 0;\n } else if (command.type === 'SPELL') {\n command.priority = (new Spell().findSpell(command.name, data) || {}).priority || 0;\n } else {\n command.priority = 0;\n }\n }", "function ServerBehavior_setPriority(priorityNumber)\n{\n if (priorityNumber > 0 && priorityNumber <= 10)\n {\n this.priority = priorityNumber;\n }\n}", "function initPodsPriority() {\n var podsPriority = lodash.get(ctrl.version, 'spec.priorityClassName', '');\n\n if (lodash.isEmpty(podsPriority)) {\n var defaultPodsPriority = lodash.get(ConfigService, 'nuclio.defaultFunctionConfig.attributes.spec.priorityClassName', '');\n\n ctrl.selectedPodsPriority = lodash.isEmpty(defaultPodsPriority) ?\n lodash.find(ctrl.podsPriorityOptions, ['id', 'igz-workload-medium']) : defaultPodsPriority\n\n lodash.set(ctrl.version, 'spec.priorityClassName', ctrl.selectedPodsPriority.id);\n } else {\n ctrl.selectedPodsPriority = lodash.find(ctrl.podsPriorityOptions, ['id', podsPriority]);\n }\n }", "function projectPriorities(priorityTitle, jobsList) {\n this.priority = priorityTitle;\n this.jobs = jobsList;\n}", "updateJob( req, res, next ){\n\t\tlet safeParams = lodash.pick( req.params, [\n\t\t\t'name',\n\t\t\t'description',\n\t\t\t'enabled',\n\t\t\t'cron',\n\t\t\t'environment_vars',\n\t\t\t'meta',\n\t\t\t'priority',\n\t\t\t'ttl',\n\t\t\t'attempts'\n\t\t])\n\t\tlodash.each( safeParams, ( value, param ) => req.job.set( param, value ) )\n\t\treq.job.save(( err ) => {\n\t\t\tif(err) return next( err )\n\t\t\tres.send( req.job )\t\n\t\t\tthis._events.emit( 'jobUpdated', req.job )\n\t\t})\n\t}", "function change(priority){\n if (priority == \"high\"){\n document.getElementById(\"priority\").selectedIndex = 0;\n }\n else if (priority =='medium'){\n document.getElementById(\"priority\").selectedIndex = 1; \n }\n else {\n document.getElementById(\"priority\").selectedIndex = 2; \n }\n}", "setJobStability({ JobID, JobVersion = 0, Stable = false }, callback) {\n return this.request.postAsync({\n body: {\n JobID,\n JobVersion,\n Stable,\n },\n uri: esc`job/${JobID}/stable`,\n })\n .bind(this)\n .asCallback(callback);\n }", "function Priority() {\n _classCallCheck(this, Priority);\n\n Priority.initialize(this);\n }", "addPriorityWorker(){\r\n if(this.priorityWorkerPool.length<10) {\r\n console.log(MODULE_NAME + ': adding priority worker');\r\n let worker = new FatusPriorityWorker(this);\r\n this.initWorker(worker);\r\n worker.setStackProtection(3);\r\n this.priorityWorkerPool.push(worker);\r\n worker.run();\r\n }\r\n }", "updateJob({\n JobID, Job, EnforceIndex = false, JobModifyIndex = 0, PolicyOverride = false,\n }, callback) {\n return this.request.postAsync({\n body: {\n Job,\n EnforceIndex,\n JobModifyIndex,\n PolicyOverride,\n },\n uri: esc`job/${JobID}`,\n })\n .bind(this)\n .asCallback(callback);\n }", "function scheduleHighPlatformJob() {\n mimicSchedulePump(function () {\n scheduleNormalPlatformJob();\n priorityOfPlatformJob = MSApp.NORMAL;\n\n assertHigh();\n count++;\n }, MSApp.HIGH);\n }", "setJob(job) {\n this.setState({'job': job});\n }", "function set_str_rulePriority(str_rule, str_prio){\n var cf = document.forms[0];\n var ruleArr = str_rule.split(\"\\x02\");\n ruleArr[_prio] = str_prio;\n ruleArr.push(ruleArr[_name]);\n ruleArr[_name] = cf.name.value;\n return (parts_arrayToString(ruleArr));\n}", "get priority()\n\t{\n\t\t//dump(\"get priority: title:\"+this.title+\", value:\"+this._calEvent.priority);\n\t\treturn this._calEvent.priority;\n\t}", "waitForJob(job, targetStatus = 3) {\n return this.waitFor(job, (job) => job.status === targetStatus)\n }", "standardizeJob (name,payload) {\n\n let jobQueue = {\n name,\n attempts : 0,\n payload\n };\n\n return jobQueue;\n\n }", "function ServerBehavior_getPriority()\n{\n return this.priority;\n}", "function krnSetScheduler(newScheduler)\n{\n if(_Scheduler.processEnqueued)\n {\n _StdIn.putText(\"Please wait for executing processes to complete!\");\n }\n else if(_Scheduler.name === newScheduler)\n {\n _StdIn.putText(\"Scheduler is already in use!\");\n }\n else if(newScheduler === \"fcfs\")\n {\n _Scheduler = new FCFS();\n _StdIn.putText(\"New Scheduler is \" + _Scheduler.name);\n }\n else if(newScheduler === \"rr\")\n {\n _Scheduler = new RoundRobin();\n _StdIn.putText(\"New Scheduler is \" + _Scheduler.name);\n }\n else if(newScheduler === \"priority\")\n {\n _Scheduler = new Priority();\n _StdIn.putText(\"New Scheduler is \" + _Scheduler.name);\n }\n else\n {\n _StdIn.putText(\"Scheduler \"+ newScheduler+ \" not found, supported schedulers include: [fcfs,rr,priority]\")\n }\n}", "setStudentPriority(value) {\n this.setState({studentPriorityValue: value});\n }", "function sortTask() {\n var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"priority_queue\");\n //var sheet = SpreadsheetApp.getActiveSheet();//.setName('Settings');\n var col_num=sheet.getDataRange().getNumColumns();\n var row_num=sheet.getDataRange().getNumRows();\n var priority_relevant_cols=sheet.getRange(1,1,row_num,3).getValues();\n var calculated_priority=[];\n var currentTime=new Date();\n for(i=0;i<row_num;i++){//reading all tasks and caculate the priority for sorting\n var priority=priority_relevant_cols[i][0];\n var assigningTime=new Date(priority_relevant_cols[i][1]);\n var requestingTime=new Date(priority_relevant_cols[i][2]);\n calculated_priority.push([]);\n \n var difference= Math.floor((currentTime-assigningTime)/1000/3600/24/10);//every 10 days' delay equals one priority level up\n if(i==0) calculated_priority[i].push(\"cal_pri\");\n else if(currentTime-requestingTime>=-1) calculated_priority[i].push(1000000);\n else calculated_priority[i].push(priority+ difference);\n\n }\n sheet.getRange(1, col_num+1, row_num, 1).setValues(calculated_priority);\n sheet.setFrozenRows(1);\n sheet.getRange(1, 1, row_num, col_num+1).sort({column:col_num+1,ascending: false});\n sheet.deleteColumn(col_num+1);\n}" ]
{ "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.createEnemy(this.x, this.y); this.resetTimer(); } }
[ "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;\r\n var __enemy = new Enemy(x, y, width, height, speed);\r\n _enemies.push(__enemy); \r\n }\r\n }", "createInitialEnemies() {\n this.enemies = [];\n this.checkEnemyCreation(1000);\n for (let i = 0; i < this.level.numEnemyRows - 1; ++i) this.checkEnemyCreation(2);\n }", "setupEnemies() {\n if (!this.enemies) {\n this.enemies = [];\n }\n while (this.enemies.filter(e => !!e).length < MAX_ENEMIES) {\n this.addEnemy();\n }\n }", "function addMoreEnemies(){\n let enemyPosition = Math.random() * 184 + 50;\n enemyLocation.push(enemyPosition);\n enemy = new Enemy(0, enemyPosition, Math.random() * 256);\n allEnemies.push(enemy);\n}", "function createArrayOfEnemies() {\n let arrayOfEnemies = [];\n const SPACING = 4; // the spacing between each enemy in each row\n // Iterate through each stone row\n for (let i=1; i<4; i++) {\n // Determine a random speed for the enemies in each row based on\n // the current level (player index being played)\n const LOWER_SPEED_LIMIT = 50 + currentPlayerIndex*25;\n const UPPER_SPEED_LIMIT = 75 + currentPlayerIndex*25;\n const SPEED = getRandomInteger(LOWER_SPEED_LIMIT, UPPER_SPEED_LIMIT);\n // Alternate direction for each row\n const DIRECTION = i%2;\n // Create 8 enemies within each row.\n for (let j=-3; j<4; j++) {\n // Determine the column in which the enemy will initialize.\n // This is determined according to index of the enemy in the\n // current row, the set spacing provided for the row, and\n // a random increment in spacing so that the enemies don't\n // march with a uniform spacing. Some enemies will initialize\n // before the visibile portion of the row begins, within the\n // visible portion of the row, and after the visible portion\n // of the row ends.\n const START_X_COL = j*SPACING + getRandomInteger(0, 2);\n // Create and add an enemy to the arrayOfEnemies\n arrayOfEnemies.push(new Enemy(i, DIRECTION, START_X_COL, SPEED));\n }\n }\n return arrayOfEnemies;\n}", "checkEnemyCreation(dt) {\n if (Math.random() < dt * this.level.enemyFrequency * this.level.stoneRows) {\n // only create enemies in stone rows\n const row = Math.floor(Math.random() * this.level.stoneRows + this.level.waterRows);\n const speed = Math.floor(Math.random() * (this.level.enemyMaxSpeed - this.level.enemyMinSpeed) + this.level.enemyMinSpeed);\n // place enemies at either the left or right edge of screen\n // and set their movement to travel to the other side\n if (Math.random() < 0.5) {\n this.enemies.push(new Enemy({x: -this.level.tileWidth, y: row * this.level.tileHeight}, {x: speed, y: 0}));\n } else {\n this.enemies.push(new Enemy({x: this.level.widthPixels() + this.level.tileWidth, y: row * this.level.tileHeight},\n {x: -speed, y: 0}));\n }\n }\n }", "spawnOne(i){\n\n // pick which enemy to spawn:\n // shooting enemies appear starting at difficulty level 2,\n // and are more likely to appear at difficulty level 3\n\n let choice='fighter'\n if(levelData.difficulty>1){\n if(levelData.difficulty>2&&Math.random()>0.3) choice='shooter';\n else if(Math.random()>0.6) choice='shooter';\n }\n\n if(i==undefined) i=0;\n enemies.push(new Enemy(\n this.x - 50 + randInt(50) + i*50,\n this.y-80,\n choice\n ));\n }", "spawnEnemy() {\n // Pick a random x coordinate without set bounds\n // x will be between 25 and 425\n const x = (Math.random() * 360) + 40;\n\n // Casting X as a whole number to be used to pick a random enemy design\n let num = Math.round(x)\n\n // Creates the actual enemy object at the given position\n this.createEnemy(x, 0, num);\n\n // Set the spawn timer and time between spawns\n this.lastSpawned = this.now();\n\n if (this.score % 5 == 0)\n {\n this.spawnTime *= 0.95;\n }\n\n // Puts a hard limit on how small spawn time can get\n if (this.spawnTime < this.minSpawnTime) {\n this.spawnTime = this.minSpawnTime;\n }\n }", "function weaponHit(e, m, ei, mi) {\n\n if(m.x <= (e.x + e.w) && (m.x + m.w) >= e.x && m.y <= (e.y + e.h) && (m.y + m.h) >= e.y) {\n enemyArray.splice(ei,1)\n weaponArray.splice(mi,1)\n new enemyExplosion(\"./sfx/enemyExplosion.wav\")\n score += 100\n\n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 3) + 1\n let dx = (Math.random() - 0.5) * 20;\n let dy = (Math.random() - 0.5) * 20;\n let color = colorArray[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n \n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 1) + 1\n let dx = (Math.random() - 0.5) * 30;\n let dy = (Math.random() - 0.5) * 30;\n let color = colorArray2[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n }\n}", "function newEnemy() {\n if (allEnemies.length < maxEnemy) {\n var enemy = new Enemy(randomCol(), enemyY, randomSpeed(), enemyWidth, enemyHeight, getChar());\n allEnemies.push(enemy);\n }\n}", "function generateNewEnemy() {\n enemyHP = Math.floor(Math.random() * (10 - 5 + 1) + 5);\n $(\"#enemy-info\").css(\"visibility\", \"visible\");\n $(\"#enemy-hp\").html(\"HP: \" + enemyHP);\n }", "function generateAgents(numHum, propZomb,x,y){\r\n\t//if(gameState){\r\n\t\tfor (var i = 0; i < numHum; i++){\r\n\t\t\tconst human = new Agents('Human',2,traitSelector(),'Blue',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(human);\r\n\t\t}\r\n\t\tfor (var j = 0; j < (numHum*propZomb); j++){\r\n\t\t\tconst zombie = new Agents('Zombie',1,traitSelector(),'Red',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(zombie);\r\n\t\t}\r\n\t//}\r\n}", "function generateZerg() {\n if (frames % 70 === 0) {\n enemies.push(new Zerg())\n }\n }", "function spawnEnemy() {\n // If there are still enemies left in this combat phase. \n if (remainingEnemies > 0) {\n // Spawn a regular enemy. \n enemies.push(new component(80, 80, \"images/placeholder/enemy.gif\", \n 480, 190, \"combat\", enemySpeedX,enemyMaxHP));\n remainingEnemies --; \n // Otherwise, if a boss hasn't been spawned yet... \n } else if (bossChar == null) {\n // IF this is the last boss in the level...\n if (remainingBosses == 1) {\n // Spawn the last boss in this level. \n bossChar = new component(80, 80, \"images/placeholder/final.gif\", \n 480, 190, \"boss\", enemySpeedX); \n } else {\n // Otherwise, spawn a miniboss. \n bossChar = new component(80, 80, \"images/placeholder/potato.gif\", \n 480, 190, \"boss\", enemySpeedX); \n } \n remainingBosses--; \n }\n}", "function random_enemy() {\n var y,\n speed,\n size = null; //reset\n y = getRndInteger(50, game.canvas.height);\n speed = getRndInteger(1, 5);\n size = randomSize();\n\n function randomSize() {\n var rndSize = getRndInteger(1, 100);\n if (rndSize <= 10) {\n return 1;\n } else if (rndSize > 10 && rndSize <= 50) {\n return 2;\n } else if (rndSize > 50 && rndSize <= 90) {\n return 3;\n } else if (rndSize > 90 && rndSize <= 98) {\n return 4;\n } else if (rndSize > 98) {\n return 5;\n } else {\n return 3;\n }\n }\n\n var newEnemy = new Enemy(y, size, speed);\n newEnemy.setSizeProps();\n return newEnemy;\n}", "distributeEnemy(){\n this.x = -200; \n this.y = y_axis[Math.floor(Math.random() * y_axis.length)];\n this.speed = speedEnemy[Math.floor(Math.random() * y_axis.length)];\n }", "function drawenemy() {\n var canvas = document.getElementById('myCanvas');\n var context = canvas.getContext('2d');\n context.fillStyle=\"green\";\n context.textAlign = 'center';\n context.font = \"20px monospace\";\n \n for(var i = 0; i < enemy.length; i++) {\n // context.fillText(enemy[i][6]-enemy[i][7],enemy[i][0],enemy[i][1]-enemysize*5);\n context.lineWidth = 1;\n context.save();\n // enemyx= enemyx+1;\n enemy[i][0]=enemy[i][0]+enemy[i][3];\n if( enemy[i][0]>canvas.width){\n enemy[i][0]=1;\n }\n enemy[i][7]=enemy[i][7]+1;\n // context.translate(enemyx,enemyy);\n if(enemy[i][7]>enemy[i][6]){\n enemy[i][7]=0;\n enemy[i][5]=\"red\";\n rndx = (Math.round(Math.random() * canvas.width));\n randangle = (Math.round(Math.random() * 5)+1);\n superenemyspeed = (Math.round(Math.random() * 8)+1);\n superenemies.push([enemy[i][0], enemy[i][1], randangle, superenemyspeed, superenemyspeed, \"red\", minePoints*2]);\n }\n if(enemy[i][7]>0 && enemy[i][7]<enemy[i][6]) {\n enemy[i][5]=\"green\";\n }\n context.strokeStyle = enemy[i][5];\n context.translate(enemy[i][0],enemy[i][1]);\n context.beginPath();\n context.strokeRect(-enemysize, -enemysize, enemysize*2, enemysize*2); \n context.arc(0, 0, enemysize*3, 0, Math.PI * 2, true);\n context.closePath();\n context.stroke();\n context.rotate(enemyrotatedeg * Math.PI / 180);\n// context.translate(0, 0);\n for (var b = 0; b < 2; b++) {\n // context.translate(0, 0);\n context.rotate(45*Math.PI/180)\n context.strokeRect(-enemysize*2.5, -enemysize*2.5, enemysize*5, enemysize*5);\n \n }\n context.restore();\n }\n}", "function basicEnemy(x, y, angle, speed){\n var newEnemy = new enemy(x, y, angle, speed);\n newEnemy.maxHealth = 10;\n newEnemy.health = 10;\n newEnemy.score = 10;\n\tnewEnemy.name = \"Alien Invader\";\n\tnewEnemy.weight = 50; // inflicts 50 damage if player crashes into it\n\tnewEnemy.height = 30;\n\t\n\t// color: blue color by default, adjust by setColor function\n\tnewEnemy.color = \"#0000FF\";\n\t\n\t// setColor function: to customize the color of this enemy:\n\t// PARAMETER: a color string (e.g. \"#FF0000\")\n\tnewEnemy.setColor = function(newColor){\n\t\tthis.color = newColor;\n\t}\n\n // balance: this variable is used to animate the enemy (see draw function)\n newEnemy.balance = -10;\n newEnemy.dBalance = (30/FPS); // change in balance per frame based on FPS\n\n\t// add a weapon to this enemy that shoots a single bullet at a random interval\n newEnemy.addWeapon(new enemyWeapon(Math.ceil(20 + getRandNum(30))))\n .onShootEvent = function(enemy){\n var bul1 = BulletFactory.enemyBullet(14, 0, \n enemy.getAngle(), \n 6, 10);\n rotatePoint(bul1, enemy.getAngle());\n translatePoint(bul1,enemy.getX(), enemy.getY());\n\n enemy.enemySys.addBullet(bul1);\n }\n\t\n\t// add a triangular collision object to this enemy\n newEnemy.addCollision(new standardCollision(25))\n .addObject(new cTriangle({x:15,y:0},{x:-10,y:10},{x:-10,y:-10}));\n \n\t// OVERRIDE\n\t// function called by enemy abstract class when enemy falls off screen:\n\t//\tThis function resets the enemy position to the top of the screen at a\n\t//\trandom X position.\n newEnemy.onOutOfScreen = function(){\n this.y = -30;\n this.x = getRandNum(areaWidth - 60) + 30;\n this.setSpeed(getRandNum(3) + 1);\n\t\tthis.normalSpeed = this.speed;\n }\n\n\t// OVERRIDE\n // Draw function called each frame to draw this enemy onto the canvas.\n\t//\tThis draws the enemies specific appearance and animations\n newEnemy.draw = function(ctx){\n // update enemy animation (using balance variable)\n if(this.balance>=10)\n this.balance=-10;\n else // update balance based on dBalance (change value)\n this.balance += this.dBalance;\n \n\t\t// save context (start new drawing stack)\n ctx.save();\n\t\t// move context to enemy's x and y position\n ctx.translate(this.getX(), this.getY());\n // rotate context\n ctx.rotate(this.angle);\n\t\t// set stroke (lines) to BLUE color\n ctx.strokeStyle = this.color;\n \n\t\t// start drawing enemy\n ctx.beginPath();\n ctx.moveTo(-13, -this.balance);\n ctx.lineTo(15, 0);\n ctx.closePath();\n ctx.stroke();\n \n ctx.fillStyle = \"#FFFAF0\";\n ctx.beginPath();\n ctx.moveTo(-10, 0);\n ctx.lineTo(15, 0);\n ctx.lineTo(-10, -10);//?\n ctx.closePath();\n ctx.fill();\n ctx.stroke();\n \n ctx.fillStyle = \"#CFAF8F\";\n ctx.beginPath();\n ctx.moveTo(-10, 0);\n ctx.lineTo(15, 0);\n ctx.lineTo(-10, 10);\n ctx.closePath();\n ctx.fill();\n ctx.stroke();\n \n ctx.beginPath();\n ctx.moveTo(-13, this.balance);\n ctx.lineTo(15, 0);\n ctx.closePath();\n \n ctx.stroke();\n \n //--------Collision circle-------\n /*\n ctx.strokeStyle = \"#FF00FF\";\n ctx.beginPath();\n ctx.arc(0, 0, 40,0,Math.PI*2,true);\n ctx.closePath();\n ctx.stroke();\n */\n //-------------------------------\n \n\t\t// restore the context draw stack (finish drawing this enemy)\n ctx.restore();\n }\n \n\t// when enemy dies, create a blue round explosion\n newEnemy.deathEffect = function(){\n this.enemySys.addEffect(this.enemySys.effectSys.basicBlueExplosion(this.getX(), this.getY()));\n }\n \n\t// when enemy is hit by a bullet, create a spark on the side that the bullet hit\n newEnemy.hitEffect = function(x, y){\n\t\t// create an angle\n var angle;\n\t\t// if bullet hit from the right, shift angle to the right side\n if(x > this.x)\n angle = Math.PI/3;\n\t\t// if bullet hit from the left, shift angle to the left side\n else if(x < this.x)\n angle = (2*Math.PI)/3;\n\t\t// otherwise, it hit in the middle so create the effect directed down\n else\n angle = (3*Math.PI)/2;\n\t\t// push the effect into the enemySys effect system\n this.enemySys.addEffect(this.enemySys.effectSys.basicSpark(x, y, angle));\n }\n\t\n\t// when enemy is burned by a laser, create a circular spart on the location of impact\n\tnewEnemy.burnEffect = function(x, y){\n\t\tthis.enemySys.addEffect(this.enemySys.effectSys.basicBurnEffect(x, y));\n\t}\n return newEnemy;\n}", "function generateEnergies()\r\n{\r\n var position = 0;\r\n\r\n for (var i = 0; i < numOfEnergies; i++)\r\n {\r\n\r\n //add platform to array with dimensions\r\n energies[i] = new Energy(Math.random()*(width-energyRadius),position);\r\n\r\n //if platform is below screen add it to the top of the screen.... (I think lol)\r\n if (position < height - energyRadius)\r\n {\r\n position += ~~(height / numOfEnergies);\r\n }\r\n }\r\n}" ]
{ "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,broadCast_message); var isvalid = emailCntVal(broadCast_sender_email,broadCast_sender_name); console.log("voice and email and sms twitter to all contacts"); //checks for validations var res = calculateRecipients(rEmail,rTts,rSms,rTwitter); var Valueofcheckboxtwtvo=res[3]; var Valueofcheckboxmob=res[1]; Valueofcheckbox=res[0]; recipientVal(res[4]); broadCast_message = broadCast_message.split('"').join(''); broadCast_message = broadCast_message.split('\n').join(''); //setting JSON datasinfo = '{"senderName":"'+senderId+'","message":"'+broadCast_message+'","emailSubject":"'+broadCast_email_subject+'","broadcastName":"'+broadCast_name+'",'+Valueofcheckbox+','+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}'; if(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&broadCast_sender_name!=''&&broadCast_sender_email!=''&&res[4]!=0&&isvalid&&senderId!='') { console.log('sending'); $("#main").css({"opacity": "0.3"}); broadcastFunc(datasinfo,x); } }
[ "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\tvar isvalid = emailCntVal(broadCast_sender_email,broadCast_sender_name);\n\tconsole.log(\"email twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tValueofcheckbox=res[0];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+broadCast_sender_email+'\",\"message\":\"'+broadCast_message+'\",\"emailSubject\":\"'+broadCast_email_subject+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckbox+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&broadCast_sender_name!=''&&broadCast_sender_email!=''&&res[4]!=0&&isvalid)\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}", "function bSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=0;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}", "function bTtsSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,lCode,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=1;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"voice and email and sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmobvo=res[2];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\tlCode=$('#ldId').val();\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",\"audio\": \"null\",'+Valueofcheckboxmob+','+Valueofcheckboxmobvo+','+Valueofcheckboxtwtvo+'},\"language\": \"'+lCode+'\"}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t\t$('#ldId').val(\"nl-nl\").attr(\"selected\", \"selected\");\n\t\t}\n}", "function getTwitterTweets(screen_name) {\n socket.emit('user_tweets', { screen_name: screen_name });\n }", "function tweetEvent(tweet) {\n\n // Who is this in reply to?\n var reply_to = tweet.in_reply_to_screen_name;\n // Who sent the tweet?\n var name = tweet.user.screen_name;\n // What is the text?\n var txt = tweet.text;\n // If we want the conversation thread\n var id = tweet.id_str;\n\n // Ok, if this was in reply to me\n // Tweets by me show up here too\n if (reply_to === 'InatorBot') {\n\n // Get rid of the @ mention\n txt = txt.replace(/@InatorBot/g,'');\n\n //reply back to the sender\n var replyText = '@'+name + ' thx for doing the twit at me XD';\n\n // Post that tweet\n T.post('statuses/update', { status: replyText, in_reply_to_status_id: id}, tweeted);\n\n // Make sure it worked!\n function tweeted(err, reply) {\n if (err) {\n console.log(err.message);\n } else {\n console.log('Tweeted: ' + reply.text);\n }\n }\n }\n}", "function emailSend(results) { // results is returned from getResults()\r\n for (let i = 0; i < results.length; i++) {\r\n let userInfo = results[i];\r\n\r\n // Send email to tutor about appointment\r\n let tutorEmailMsg1 = 'Hello, ' + userInfo[6] + '! ';\r\n let tutorEmailMsg2 = userInfo[0] + ' wants to be tutored by you in ' + userInfo[5] + '. ';\r\n let tutorEmailMsg3 = userInfo[0] + ' is in grade ' + userInfo[2] + ' and goes to ' + userInfo[1] + '. ';\r\n let tutorEmailMsg4 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let tutorEmailMsg5 = 'Here is some information they added about their appointment: ' + userInfo[7] + '.';\r\n let tutorEmailSubject = 'Your Tutoring Appointment!';\r\n let tutorEmailMessage = tutorEmailMsg1 + tutorEmailMsg2 + tutorEmailMsg3 + tutorEmailMsg4 + tutorEmailMsg5;\r\n MailApp.sendEmail(userInfo[8], tutorEmailSubject, tutorEmailMessage);\r\n\r\n // Send email to student about appointment\r\n let studentEmailMsg1 = 'Hello, ' + userInfo[0] + '! ';\r\n let studentEmailMsg2 = 'You are going to be tutored by ' + userInfo[6] + '! ';\r\n let studentEmailMsg3 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let studentEmailMsg4 = 'Here is the information you added about your appointment: ' + userInfo[7] + '.';\r\n let studentEmailSubject = 'Your Tutoring Appointment!';\r\n let studentEmailMessage = studentEmailMsg1 + studentEmailMsg2 + studentEmailMsg3 + studentEmailMsg4;\r\n MailApp.sendEmail(userInfo[4], studentEmailSubject, studentEmailMessage);\r\n }\r\n}", "function mentions(tweet) {\n var string = tweet.split(\" \");\n var hash = [];\n for (var i = 0; i < string.length; i++) {\n if (string[i].startsWith(\"@\")) {\n hash.push(string[i]);\n }\n }\n return hash;\n}", "sendEmailList (e, template) {\n var subscribers = this.getSubscribers(); //list of subscriber objects\n subscribers.forEach((subscriber) => {this.sendEmail(e, template, subscriber)});\n console.log('Emails sent')\n }", "function sendContacts () {\n\t\t\tUser.getContacts(socket.handshake.user.username, function (contacts) {\n\t\t\t\tsocket.emit('contacts', contacts);\n\t\t\t});\n\t\t}", "function sendemail(){\t\n\t\n\t\t// make ajax request to post data to server; get the promise object for this API\n\t\tvar request = WmsPost.newAjaxRequest('/wms/x-services/email/producer', formToJSON());\n\t\n\t\t// register a function to get called when the data is resolved\n\t\trequest.done(function(data,status,xhr){\n\t\t\t//console.log(\"Email sent successfully!\");\n\t\t\tlocation.href = \"emailthankyou.html\";\n\t\t});\n\n\t\t// register the failure function\n\t\trequest.fail(function(xhr,status,error){\n\t\t\t//console.error(\"The following error occured: \"+ status, error);\n\t\t\talert(\"Problem occured while sending email: \" + error);\n\t\t});\n\n\t}", "async function mySendMail( ticker ){\n const result = await transporter.sendMail({\n from: '\"fred <small>👻 </small>\" <knows@amail.com>',\n to: 'homegreen18@gmail.com',\n replyTo: '\"my ghost email shadow who nobody\" <knows@amail.com>',\n subject: 'doing stuff sayiong people coffe',\n html: ticker\n });\n }", "function getMessages(phoneNumber, twilioNumber) {\n $(\"#messages\").html(\"\");\n $.getJSON(\"/api/admin/get_messages\", {\"phone_number\": phoneNumber, \"twilio_number\": twilioNumber}, \n function(messages) {\n for (i in messages) {\n var message = messages[i];\n messageDiv = makeElement(\"message\");\n messageDiv.find(\".to\").text(message.outbound == 0 ? \"Me: \" : \"Them: \");\n messageDiv.find(\".body\").text(message.body);\n $(\"#messages\").append(messageDiv);\n }\n });\n}", "function _sendEmail() {\n\t\t\t}", "function main() {\n \n \t//Step 1: Add Email\n\tvar recipient = \"peterstavrop@gmail.com\";\n \n \t//Step 2: Change Subject Line\n\tvar subject = \"Add Subject Line Here\";\n \n\tvar body = AdWordsApp.currentAccount().getName() + \" Paid Search Email \\n\";\n \n \t//Step 3: Add Text to Email Body\n \tbody = body + \"Add Text Here\";\n\n\tMailApp.sendEmail(recipient, subject, body);\n\t\n}", "sendPhoneVerifyCodeViaSMS(phone, action, callback) {\n callback = ensureCallback(callback);\n Meteor.call(prefix + 'sendPhoneVerifyCodeViaSMS', {phone, action}, callback);\n }", "function processTweet(data) {\n\t\treturn [[ \"receiving transmission\" ], [\n\t\t\"type : tweet\",\n\t\t\"handle : \"+data.user.screen_name,\n\t\t\"name : \"+data.user.name,\n\t\t\"location : \"+data.user.location,\n\t\t\"message : \"+data.text,\n\t\t/* \"profile : \"+data.user.description, */\n\t\t\"date : \"+data.created_at.substr(0,20),\n\t\t]];\n\t}", "function showSMSDialog() {\n var SMS = require('ti.sms');\n \n var SMSDialog = SMS.createSMSDialog({\n barColor: \"black\",\n toRecipients: [\"1234567890\", \"0987654321\"],\n subject: \"What's up?\",\n messageBody: \"Titanium rocks! 🔥\"\n });\n \n if (!SMS.canSendText()) {\n Ti.API.error(\"Device cannot send SMS!\");\n return;\n }\n \n if (!SMS.canSendSubject()) {\n Ti.API.error(\"Device cannot send subject!\");\n return;\n }\n \n if (!SMS.canSendAttachments()) {\n Ti.API.error(\"Device cannot send attachments!\");\n return;\n } else {\n SMSDialog.addAttachments([Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory(), \"KS_nav_ui.png\").read()])\n }\n\n SMSDialog.addEventListener('complete', function(e) {\n if (e.success) {\n alert('SMS sent!');\n } else {\n switch (e.result) {\n case SMS.CANCELLED:\n alert('User cancelled SMS!');\n break;\n case SMS.FAILED:\n default:\n alert(e.error);\n }\n }\n });\n\n SMSDialog.open({\n animated: true\n });\n}", "function addImsEmail(l) {\r\n\tvar email = getURLParam(\"e12\");\r\n \tif(email!=\"\") l.href += \"&e12=\" + email;\r\n}", "'mobileRecoverPasswordEmail'(email) {\n Email.send({\n to: email,\n from: \"kupongoteam@kupongo.com\",\n subject: \"Password recovery\",\n html: /*link this to mobile Reset.js page */ \"Link to reset page\",\n });\n }" ]
{ "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 }", "function recolorHexGrid() {\n for (let hex of hexArray) {\n hex.randomizeColors();\n }\n}", "function clearColor(){\n for (var i = 0; i < squares.length; i++) {\n squares[i].bgColor = 'white';\n }\n}", "function colorAlgorithm(){\n\tvar temp = new Array();\n\t\n\tvar tag2 = document.getElementById('gloss').value;\n\tglossiness = tag2;\n\t\n\tvar lightVector = new Vector3([500, 500, 500]);\n\tlightVector.normalize();\n\tvar lightVector2 = new Vector3([0,500,0]);\n\tlightVector2.normalize();\n\t\tfor (var j = 3; j < normies.length; j+=6){\n\t\t\tvar nVector = new Vector3([normies[j],normies[j+1],normies[j+2]]);\n\t\t\tnVector.normalize();\n\t\t\tvar reflect = calcR(nVector,lightVector); //two times dot times normal minus lightdirection\n\t\t\tvar dot = (\n\t\t\t\tnormies[j] * lightVector.elements[0] +\n\t\t\t\tnormies[j+1] * lightVector.elements[1] +\n\t\t\t\tnormies[j+2] * lightVector.elements[2]\n\t\t\t\t);\n\t\t\t\tdot = dot/256; //////color hack\n\n\t\t\tif (pointLight&&lightDir.checked){\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\t\t\n\t\t\t} else if (pointLight&&!lightDir.checked){\n\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\n\t\t\t} else if (lightDir.checked){\n\t\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse for (var k = 0; k < 20; k++) temp.push(0.5,0.5,0.5);\n\t\t}\n\t return temp;\n}", "function flashRandomColorsArray(array, i, speed) {\n timedFlashes(array, i, speed)\n}", "function flushLEDs()\r\n{\r\n\t// changedCount contains number of lights changed\r\n var changedCount = 0;\r\n\r\n // count the number of LEDs that are going to be changed by comparing pendingLEDs to activeLEDs array\r\n for(var i=0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i]) changedCount++;\r\n }\r\n\r\n // exit function if there are none to be changed\r\n if (changedCount == 0) return;\r\n\r\n //uncommenting this displays a count of the number of LEDs to be changed\r\n // //println(\"Repaint: \" + changedCount + \" LEDs\");\r\n\r\n for(var i = 0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i])\r\n { \r\n activeLEDs[i] = pendingLEDs[i];\r\n\r\n var colour = activeLEDs[i];\r\n\r\n if (i < 16) // Main Grid\r\n {\r\n var column = i & 0x7;\r\n var row = i >> 3;\r\n\r\n if (colour >=200 && colour < 328)//flashing colour numeration. need to substract 200 to get the appropriate final color\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x92, 96 + row*16 + column, colour-200);\r\n }\r\n else\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + row*16 + column, colour);\r\n }\r\n }\r\n\r\n else if (i>=64 && i < 66) // Right buttons\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + 8 + (i - 64) * 16, colour);\r\n }\r\n }\r\n }\r\n}", "function resetMarkerColor(array){\n\n for (var i = 0; i< array.length; i++) {\n\n var markerIconAttr = array[i].getIcon();\n\n markerIconAttr.fillColor = '#fdd835';\n array[i].setIcon(markerIconAttr);\n\n }\n\n\n}", "function resetArray(){\n const newArray = [];\n //populate the new away array\n for(let i = 0; i < arraySize; i++){\n newArray.push(randomIntFromInterval(10,500));\n }\n setArray(newArray);\n }", "function clearScreenDithered() {\r\n //\r\n // set all the attribute values\r\n const attr = makeAttribute(my.ink, my.paper, false)\r\n displayColours.fill(attr)\r\n //\r\n // fill the display with an odd pixel pattern\r\n displayPixels.fill(0b01010101)\r\n //\r\n // fill every other line with an even pixel pattern;\r\n // it is necessary to do this even/odd alternation otherwise\r\n // the pixels will align into lines instead of a checkerboard\r\n for (let i = 0; i < (XMAX * YMAX); i += COLUMNS * 2)\r\n displayPixels.fill(0b10101010, i, i + COLUMNS)\r\n}", "ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }", "function resetColours() {\n\tvar circles = document.getElementsByClassName('round-button-circle_1');\n\tfor (var i = 0; i < circles.length; i++) {\n\t\tcircles[i].style.background='#5AB9EA';\n\t}\n}", "function resetDraw() {\n\tfor (var i=0; i<=currentTournament.numberMatches*2;i++) { \n\t\t\t$(\"#p\" + i).css(\"color\", \"#000\");\n\t\t}\n\t}", "function randomizeColors() {\n for (let i = ORIGINAL_COLORS.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = ORIGINAL_COLORS[i];\n ORIGINAL_COLORS[i] = ORIGINAL_COLORS[j];\n ORIGINAL_COLORS[j] = temp;\n }\n}", "function resetLasers() {\n\t\tfor (var j = 0; j < NUM_COLS; j++) {\n\t\t\tinvaderLasers[j].alive = false;\n\t\t}\n\t\tlaserCount = 0;\n\t}", "function wrongGuess() {\n state.colors.forEach(color => {\n color.style.opacity = 0.8;\n setTimeout(() => {\n color.style.opacity = 0.4;\n }, 500);\n });\n}", "restart(){\n this._seed = []\n this._inGame = []\n this._numbersPuzzle = []\n this._sizePuzzle = 0\n this._count = 0\n this._movements = 0\n this._time = 0\n clearInterval(this._intervalTime)\n }", "function setallcolorfunction(){\r\n\t\t\tfinalcolor = allcolorfunction;\r\n\t\t}", "function reset() {\n Caman(\"#canvas\", img, function () {\n this.revert();\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 sendToWatson(obj)\n })\n}", "function getHistory() {\n var db = getDatabase();\n var respath=\"\";\n db.transaction(function(tx) {\n var rs = tx.executeSql('SELECT * FROM history ORDER BY history.uid DESC;');\n for (var i = 0; i < rs.rows.length; i++) {\n historyModel.append({\"url\" : rs.rows.item(i).url});\n }\n })\n}", "getHistory () {\n return this._historyStore.list();\n }", "async getAccountChannel(){\n await fetch('/rest/accountchannels/accountid/' + this.currentAccount.id )\n .then( loggedInAccountChannels => loggedInAccountChannels.json() )\n .then( loggedInAccountChannels => this.loggedInAccountChannels = loggedInAccountChannels );\n }", "getHistory () {\n return this.game.history({ verbose: true })\n }", "function get_history(filename, callback)\n{\n simpleGit.log([ filename ], function(err, data) {\n if(err) {\n console.error(err);\n callback();\n }\n\n var filter_data = data.all.map(function(elem) {\n return {\n date : elem.date,\n message : elem.message,\n author_email : elem.author_email\n }\n });\n\n callback(filter_data);\n });\n}", "getHistory(){\n\t\treturn this.history;\n\t}", "static async getAssetHistory(ctx, assetKey) {\n\t\t//Return iterator of asset history for the key provided\n\t\treturn await ctx.stub.getHistoryForKey(assetKey);\n\t}", "function getHistory() {\n const historyCmd = `appcenter codepush deployment history -a DigiServe/adroit-${os} ${environment} --output=\"json\"`;\n\n console.log(chalk.cyan(historyCmd));\n\n exec(historyCmd, (error, stdout, stderr) => {\n try {\n if (error) {\n throw error;\n }\n const history = JSON.parse(stdout);\n // eslint-disable-next-line prefer-destructuring\n const latestCodePushVersion = history[history.length - 1][0];\n const tagName = `code-push-${os}-${environment}-${latestCodePushVersion}`;\n const message = `Code Push release (${os}/${environment})`;\n util.gitTag(tagName, message);\n } catch (err) {\n console.log(\n chalk.red(\n 'Failed to fetch latest Code Push version. Please manually call the git tag command to tag this commit with the Code Push release version just created.'\n )\n );\n console.log(chalk.red(err));\n if (stderr) {\n console.log(chalk.red(stderr));\n }\n process.exit(EXIT_CODE.HISTORY_FAILED);\n }\n });\n}", "function getCalcs() {\n Calc.find({}, null, { sort: { _id: -1 } }, (err, calculations) => {\n if (err) {\n console.log('Error Getting Calcs')\n }\n else {\n calcHistory = [];\n calculations.forEach((calc) => {\n calcHistory.push(calc.calc);\n })\n calcHistory = [...calcHistory.slice(0, 10)];\n io.emit('updateHistory', calcHistory);\n }\n })\n}", "function get_channel(id){\n return guild.channels.cache.get(id);\n}", "function process_history(issue, history, cb) {\n const dbKey = feed.id + ':history:' + history.id;\n\n db.get(dbKey, (err, created) => {\n if (err && err.notFound) created = cutoff;\n else if (err) return cb(err);\n\n if (history.created > created) {\n db.put(dbKey, history.created, (err) => {\n if (err) return cb(err);\n log.info('Issue history %s#%s', issue.key, history.id);\n cb(null, history.author);\n });\n } else {\n log.debug('Skipping history %s#%s (%s < %s)', issue.key, history.id, history.created, created);\n cb();\n }\n });\n }", "historicalOrderbook(symbol_id, time_start, time_end, limit, limit_levels) {\n const params = this._getParamString({\n time_start: time_start,\n time_end: time_end,\n limit: limit,\n limit_levels: limit_levels\n });\n return this._request(`/v1/orderbooks/${symbol_id}/history${params}`)\n }", "function getAll() {\n\t'use strict';\n\tds.historics.get(function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic queries: ' + JSON.stringify(response));\n\t\t\tcheckStatus();\n\t\t}\n\t});\n}", "function loadMoreHistory() {\n if ($historyList.is(\":visible\")) {\n if (($tableContainer.prop(\"scrollHeight\") - $tableContainer.scrollTop()) === $tableContainer.height()) {\n if ($historyList.attr(\"x-finished\") === \"true\") {\n return;\n }\n return Svn.getCurrentBranchName().then(function (branchName) {\n var p,\n file = $historyList.data(\"file-relative\"),\n skipCount = $tableContainer.find(\"tr.history-commit\").length;\n if (file) {\n p = Svn.getFileHistory(file, branchName, skipCount);\n } else {\n p = Svn.getHistory(branchName, skipCount);\n }\n return p.then(function (commits) {\n if (commits.length === 0) {\n $historyList.attr(\"x-finished\", \"true\");\n return;\n }\n\n commits = addAdditionalCommitInfo(commits);\n commitCache = commitCache.concat(commits);\n\n var templateData = {\n commits: commits,\n usePicture: avatarType === \"PICTURE\",\n useIdenticon: avatarType === \"IDENTICON\",\n useBwAvatar: avatarType === \"AVATAR_BW\",\n useColoredAvatar: avatarType === \"AVATAR_COLOR\",\n Strings: Strings\n };\n var commitsHtml = Mustache.render(gitPanelHistoryCommitsTemplate, templateData);\n $historyList.children(\"tbody\").append(commitsHtml);\n })\n .catch(function (err) {\n ErrorHandler.showError(err, \"Failed to load more history rows\");\n });\n })\n .catch(function (err) {\n ErrorHandler.showError(err, \"Failed to get current branch name\");\n });\n }\n }\n }", "createChannelListForGuild(guild){\n console.log(guild)\n this.setState((state, props) => ({\n guildChannels: guild.channels.cache\n }), ()=>console.log(this.state.guildChannels))\n }", "function getBacklog(room, callback) {\r\n var keys = getRedisKeys(room);\r\n var ret = {};\r\n\r\n // First, get the event backlog\r\n redis.lrange(keys.events, 0, 999, function(err, events) {\r\n ret.events = (events || []).map(function(jsonEvent) {\r\n return JSON.parse(jsonEvent);\r\n });\r\n\r\n ret.stats = {};\r\n\r\n // Get the number of events that happened today\r\n redis.get(keys.todayCount, function(err, todayCount) {\r\n ret.stats.today = parseInt(todayCount) || 0;\r\n\r\n // Get the number of events that happened this week\r\n redis.get(keys.weekCount, function(err, weekCount) {\r\n ret.stats.week = parseInt(weekCount) || 0;\r\n\r\n // We got everything, return the backlog and statistics\r\n callback(null, ret);\r\n });\r\n });\r\n });\r\n}", "async doSaveCacheHistory() {\n\t\tlet theUnsaved = this.historyCache.getUnSaved();\n\t\tif (!$.isEmptyObject(theUnsaved)) { await this.doAddToDB('searching', 'history', Object.values(theUnsaved)); }\n\t}", "function update_history_crid(crid) {\n $('#search_prompt').html(\"This programme is a repeat. Searching for activities with the same CRID.\");\n\n if (typeof snapshot_time == \"undefined\") {\n var url = '/tvdiary/history_json.jim?crid=' + encodeURIComponent(crid);\n } else {\n var url = '/tvdiary/json/history_' + encodeURIComponent(crid) + '.json?nocache=' + today_start;\n }\n update_history(url, true);\n }" ]
{ "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') { document.removeEventListener('readystatechange', handler_1); resolve(); } }; document.addEventListener('readystatechange', handler_1); } else { resolve(); } }); }
[ "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();\n\t\t\t\t}\n\t\t\t}", "waitForDOMContentLoaded() {\n const callback = () => {\n this.isReady = true;\n this.runMethodsThatWaits();\n this.frame.contentWindow.document.removeEventListener(\n \"DOMContentLoaded\",\n callback\n );\n };\n this.frame.contentWindow.document.addEventListener(\n \"DOMContentLoaded\",\n callback\n );\n }", "function _onFinishedLoadingDOM() {\n var request = new XMLHttpRequest();\n request.open(\"GET\", exports.url);\n request.onload = function onLoad() {\n if ((request.status >= 200 && request.status < 300) ||\n request.status === 304 || request.status === 0) {\n _mapDocumentToSource(request.response);\n _load.resolve();\n } else {\n var msg = \"Received status \" + request.status + \" from XMLHttpRequest while attempting to load source file at \" + exports.url;\n _load.reject(msg, { message: msg });\n }\n };\n request.onerror = function onError() {\n var msg = \"Could not load source file at \" + exports.url;\n _load.reject(msg, { message: msg });\n };\n request.send(null);\n }", "function readyStateChangePoll() {\n\t\t\tif( asyncRequest.req.readyState == 4 ) {\n\t\t\t\tprocessResponse();\n\t\t\t}\n\t\t}", "function idbReady() {\n const isSafari = /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers through this mess.\n if (!isSafari)\n return Promise.resolve();\n let intervalId;\n return new Promise((resolve) => {\n const tryIdb = () => indexedDB.databases().finally(resolve);\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(() => clearInterval(intervalId));\n}", "function promiseDOMMutation() {\n return new Promise((resolve, reject) => {\n const observer = new MutationObserver((mutations) => {\n observer.disconnect();\n resolve();\n });\n const thebody = document.getElementById('mainbody');\n observer.observe(\n thebody,\n { attributes: true, childList: true, characterData: true, subtree: true });\n });\n}", "function waitReady() {\n ready = getStore().getState().blocksSaveDataGet.contextListReady.hasAll();\n if (!ready) {\n window.setTimeout(waitReady, 50);\n return false;\n }\n resolve(true);\n return true;\n }", "function load() {\n page.open(url, function() {\n var test_passed = page.evaluate(evaluatePage, first_load, cache);\n\n if (test_passed) {\n console.log('pass');\n // phantom.exit();\n }\n else {\n console.log('fail');\n setTimeout(load, REFRESH_DELAY);\n }\n });\n}", "_ensure_future() {\n let ptrobj = _getPtr(this);\n let resolveHandle;\n let rejectHandle;\n let promise = new Promise((resolve, reject) => {\n resolveHandle = resolve;\n rejectHandle = reject;\n });\n let resolve_handle_id = Module.hiwire.new_value(resolveHandle);\n let reject_handle_id = Module.hiwire.new_value(rejectHandle);\n let errcode;\n try {\n errcode = Module.__pyproxy_ensure_future(\n ptrobj,\n resolve_handle_id,\n reject_handle_id\n );\n } catch (e) {\n Module.fatal_error(e);\n } finally {\n Module.hiwire.decref(reject_handle_id);\n Module.hiwire.decref(resolve_handle_id);\n }\n if (errcode === -1) {\n Module._pythonexc2js();\n }\n return promise;\n }", "get readyState() {\r\n return this._ws ? this._ws.readyState : ReconnectingWebSocket.CONNECTING;\r\n }", "function waitForNextFrame() {\r\n return new Promise(resolve => setTimeout(resolve, 5));\r\n}", "function waitForTransitionEnd(element) {\r\n return new Promise((resolve) => {\r\n const duration = getTransitionDuration(element);\r\n const timeout = 250; // Minimum transition duration of 350ms\r\n const transitionEndHandler = () => {\r\n element.removeEventListener(\"transitionend\", transitionEndHandler);\r\n resolve(true);\r\n clearTimeout(timeoutTimer);\r\n };\r\n\r\n element.addEventListener(\"transitionend\", transitionEndHandler);\r\n var timeoutTimer = setTimeout(function () {\r\n resolve(false);\r\n }, timeout);\r\n });\r\n}", "function checkWindow() {\n alert(\"Page has loaded successfully.\");\n}", "function isFileReady ( state ) {\n\t\treturn ( !state || state === 'loaded' || state === 'complete' || state === 'uninitialized' );\n\t}", "_awaitStateChange(reg) {\n\t\treg.installing.addEventListener('statechange', (event) => {\n\t\t\tswitch (event.target.state) {\n\t\t\t\tcase 'installed':\n\t\t\t\t\tif (navigator.serviceWorker.controller) {\n\t\t\t\t\t\t// At this point, the old content will have been purged and the fresh content will\n\t\t\t\t\t\t// have been added to the cache.\n\t\t\t\t\t\t// It's the perfect time to display a \"New content is available; please refresh.\"\n\t\t\t\t\t\t// message in the page's interface.\n\t\t\t\t\t\tthis._waiting(reg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// At this point, everything has been precached.\n\t\t\t\t\t\t// It's the perfect time to display a \"Content is cached for offline use.\" message.\n\t\t\t\t\t\tthis._log('New serviceworker is controlling page. Content is now available offline!');\n\t\t\t\t\t\tthis.trigger('activated');\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'redundant':\n\t\t\t\t\tthis._log('The installing service worker became redundant.');\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}", "async _readStorageIfNecessary() {\n if (this._storageReadyPromise === null) {\n // This is the first time the storage has been requested. Initiate a read.\n this._storageReadyPromise = this._readStorage();\n }\n\n // Wait for the pending read to complete.\n await this._storageReadyPromise;\n }", "function asynchronity() {\n //setTimeout is used, which is an asynchronous function.\n let result = new Promise((resolve, reject) => {\n setTimeout(() => resolve('I am complete!'), 1000);\n });\n\n /*Because of setTimeout, result isn't evaluated yet. Because of JavaScript's\n asynchronity, result is still logged. */\n console.log(result); //Logs Promise { <pending> }\n\n /*JavaScript contains many asynchronous functions, such as setInterval,\n requestAnimationFrame, XMLHttpRequest, WebSocket, Worker, some APIs, and more. */\n}", "appLoad(type, callback) {\n const _self = this;\n\n switch (type) {\n case 'loading':\n if (_self.doc.readyState === 'loading') {\n callback();\n }\n\n break;\n case 'dom':\n _self.doc.onreadystatechange = function () {\n if (_self.doc.readyState === 'complete') {\n callback();\n }\n };\n\n break;\n case 'full':\n _self.window.onload = function (e) {\n callback(e);\n };\n\n break;\n default:\n callback();\n }\n }", "function checkStatus() {\n return new Promise((resolve, reject) => {\n getStatusFromCache()\n .then(function(data) {\n resolve(data);\n })\n .catch(function(err) {\n resolve(scrapeStatus());\n });\n });\n}", "function WaitScriptLoad() {}" ]
{ "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.push(CurStepObj); // and push it\r\n}", "function editIndNameExprs(dim) {\r\n\r\n var sO = CurStepObj;\r\n\r\n // STEP\r\n // Redraw code window without any focused box or any active\r\n // expression/space. This is important for the user so that the user\r\n // knows expression boxes are not where the input goes. \r\n // We redraw with editDimNames true, so that dim names become editable\r\n //\r\n sO.focusBoxId = CodeBoxId.INVALID;\r\n sO.focusBoxExpr = null;\r\n //\r\n sO.activeParentPath = null;\r\n sO.activeChildPos = INVID;\r\n sO.isSpaceActive = false;\r\n sO.activeParentExpr = null;\r\n //\r\n sO.editDimNames = true;\r\n drawCodeWindow(sO);\r\n\r\n // STEP: After redrawing code window with editable dim names\r\n // disable editable flag and set focus on the dim name the\r\n // user clicked on \r\n //\r\n sO.editDimNames = false;\r\n var name = \"IndName\" + dim;\r\n var sp1 = document.getElementById(name);\r\n //\r\n sp1.focus();\r\n //\r\n // disable our keyboard processing\r\n //\r\n sO.keyboardEnabled = false;\r\n\r\n}", "addTvar(i) {\n this.sim.variables['T'+(i || ++this.sim.tVarCount)] = '';\n }", "function getIndNames4Step(sO) {\r\n\r\n var inames = \"\";\r\n\r\n for (var d=0; d < sO.dimNameExprs.length; d++) { // for all dimensions\r\n\r\n\tvar cl = \" class='indexName' \"; // class name for index\r\n\r\n //var onC = \" onclick=\\\"addIndNameExpr(\" + d + \")\\\" \";\r\n //var onC = \" onclick=\\\"indVarClicked(\" + d + \")\\\" \";\r\n\r\n var onC = \" onmousedown=\\\"indVarMouseDown(\" + d + \")\\\" \" +\r\n \" onmouseup=\\\"indVarMouseUp(\" + d + \")\\\" \";\r\n\r\n cl += \" style='cursor:pointer' \";\r\n\r\n // if the user double clicked on the index names, make the index\r\n // names editable\r\n //\r\n if (sO.editDimNames) {\r\n var args = \"this, \" + d;\r\n //onC=\" oninput=\\\"updateIndexEdit(\" + args + \")\\\" contenteditable \";\r\n onC = \" onblur=\\\"updateIndexEdit(\" + args +\r\n \")\\\" contenteditable \";\r\n onC += \"id='IndName\" + d + \"' \";\r\n onC += \" onblur='doneIndexEdit()' \";\r\n }\r\n\r\n var dname = sO.dimNameExprs[d].str;\r\n var span = \"<span \" + cl + onC + \">\" + dname + \"</span>\";\r\n var sep = (d > 0) ? \",\" : \"\";\r\n inames += sep + span;\r\n }\r\n\r\n var ret = \"\";\r\n\r\n // if there are index variables (i.e., not all grids are scalar)\r\n //\r\n if (sO.dimNameExprs.length) {\r\n ret = \"<span style='font-size:10px'>Index Variables : </span>\" +\r\n \" <span class='indexNames'>[\" + inames + \"]</span>\";\r\n }\r\n\r\n return ret;\r\n}", "function addDim() {\r\n\r\n var gO = NewGridObj; // currently configured grid\r\n\r\n var newdim = gO.numDims;\r\n gO.numDims++;\r\n if (gO.numDims == 2) gO.multiCol = true; //MPI: bug fix general\r\n gO.dimTitles[newdim] = new Array();\r\n gO.dimComments[newdim] = new Array();\r\n\r\n for (var t = 0; t < DefNumTabsInDim; t++) {\r\n //gO.dimTitles[newdim].push( \"d\" + (newdim+1) + DefDimTitleRoot + t);\r\n if (newdim > 1) //MPI: bug fix\r\n\t gO.dimTitles[newdim].push(getTabName(newdim, t));\r\n\telse //MPI: bug, this can only be newdim = 1\r\n\t gO.dimTitles[newdim].push(DefTitleRoots[ColDimId] + t);\r\n\t \r\n gO.dimComments[newdim].push(null);\r\n }\r\n\r\n gO.dimHasTitles[newdim] = true; // VERIFY -- do we need titles by default\r\n gO.dimHasIndices[newdim] = false; // VERIFY -- do we need indices by default\r\n\r\n gO.dimIsExtended[newdim] = false; //MPI:\r\n\r\n gO.dimShowSize[newdim] = DefNumTabsInDim;\r\n gO.dimActSize[newdim] = DefNumTabsInDim;\r\n gO.dimDynSize[newdim] = null;\r\n gO.dimShowStart[newdim] = 0;\r\n\r\n gO.dimSelectTabs[newdim] = 0; // select first tab by default\r\n\r\n reDrawConfig(); // redraw with updates\r\n}", "initiateVariableName() {\n this.variableName = this.variableName || `val_${this.compiler.referenceVariableCounter++}`;\n }", "function cloneStepObj(s) {\r\n\r\n // All out/src grids in this step. \r\n // NOTE: When we are cloning, we are doing a deep cloning by cloning\r\n // the gridObjs as well. This is necessary because some properties\r\n // like row/col indices are private to a step.\r\n //\r\n this.allGridIds = new Array();\r\n this.allIndObjs = new Array();\r\n\r\n for (var i = 0; i < s.allGridIds.length; i++) {\r\n var gId = s.allGridIds[i];\r\n this.allGridIds.push(gId);\r\n\r\n // TODO: We don't need to clone indices later. Remove this.\r\n this.allIndObjs.push(s.allIndObjs[i]);\r\n }\r\n\r\n this.boxExprs = s.boxExprs.slice(0);\r\n this.boxAttribs = s.boxAttribs.slice(0);\r\n\r\n // VERIFY: should we clone dim names? \r\n //\r\n this.dimNameExprs = s.dimNameExprs.slice(0);\r\n\r\n // VERIFY: Since we are cloning an existing grid, the output grid cannot\r\n // be a new one\r\n //\r\n this.isOutGridNew = false;\r\n //\r\n this.title = s.title;\r\n\r\n\r\n this.focusBoxId = s.focusBoxId;\r\n this.focusBoxExpr = s.focusBoxExpr;\r\n //\r\n this.focusHtmlObj = s.focusHtmlObj;\r\n\r\n // VERIFY: We may not need to copy all active properties but rather\r\n // reset them to initial values, when a step obj is cloned\r\n //\r\n this.activeParentPath = s.activeParentPath;\r\n this.activeChildPos = s.activeChildPos;\r\n this.activeParentExpr = s.activeParentExpr;\r\n this.isSpaceActive = s.isSpaceActive;\r\n\r\n // when the user is entering a number with the keyboard, the digits\r\n // entered so far are kept here\r\n //\r\n this.numberExpr = null;\r\n this.editDimNames = s.editDimNames;\r\n\r\n // Comments are stored in the following\r\n // \r\n this.indexComment = s.indexComment;\r\n this.ifComment = s.ifComment;\r\n this.formulaComment = s.formulaComment;\r\n this.stepComment = s.stepComment;\r\n\r\n // Parallelism of the step, indicated by the parallelism meter\r\n //\r\n this.parallelism = s.parallelism;\r\n\r\n this.stageInStep = s.stageInStep;\r\n\r\n /* \r\n this.configStarted = s.configStarted;\r\n this.configDone = s.configDone; // out configuration done\r\n this.gridSelectDone = s.gridSelectDone; // all grids have been selected\r\n */\r\n\r\n // whether we are displaying data in grids\r\n //\r\n //this.showData = ShowDataState.None; \r\n\r\n this.maxDataVal = MININT; // maximum data value\r\n this.isHeader = s.isHeader; // is this a function header\r\n\r\n this.keyboardEnabled = s.keyboardEnabled;\r\n this.potOCLstep = s.potOCLstep;\r\n this.showOptions = s.showOptions;\r\n\r\n // Method to add a source grid\r\n //\r\n this.addGridId = s.addGridId;\r\n}", "function updateStepObj(sO) {\r\n\r\n // Put any updates necessary here\r\n\r\n\r\n}", "setupSteps() {\n // Functions for setting up the DOM for each step. Order is important\n this.steps = [() => this.fileUploadStep(), () => this.requiredInfoStep(), () => this.resultsStep()];\n // Setup current step\n this.steps[this.currentStep]();\n }", "function addFactorSliderData(rootPanelId, handleId, trackId, sampleSpanId, indicatorId, initialValue, minValue, maxValue, increment, inputElement) {\n// alert('adding factor for ' + handleId + ', ' + trackId + ', ' + initialValue + ', ' + maxValue + ', ' + increment + ', ' + inputElement);\n var newSliderData = {\n rootPanelId: rootPanelId,\n handleId: handleId,\n trackId: trackId,\n sampleSpanId: sampleSpanId,\n indicatorId: indicatorId,\n initialValue: initialValue,\n minValue: minValue,\n maxValue: maxValue,\n increment: increment,\n inputElement: inputElement\n };\n \n factorSliderData[numFactorSliders] = newSliderData;\n numFactorSliders++;\n}", "function addIndNameExpr(dim) {\r\n\r\n var sO = CurStepObj;\r\n var fO = CurFuncObj;\r\n\r\n if (sO.focusBoxId == CodeBoxId.Range) { // append a new range\r\n \r\n\t// We are appending a whole new range variable\r\n\t// -- i.e., new range for dim with default output grid \r\n\t//\r\n\tvar gO = fO.allGrids[sO.allGridIds[0]];\r\n\tvar rangeExpr = newRangeExpr(sO, dim, gO); \r\n\taddGenExpr(rangeExpr); // add to range box\r\n\r\n } else {\r\n\r\n var iexpr = sO.dimNameExprs[dim];\r\n addGenExpr(iexpr);\r\n }\r\n}", "function addInitals(first, last){\n console.log ('Your Initals:', (first + last));\n}", "function Steps (dataSteps){ \n // this.$el = \"\"; // this will hold the stepsContainer html element\n // this.dots.$el = '';\n // this.titles.$el = '';\n // this.descriptions.$el = '';\n this.data = dataSteps;\n this.dotsArr = [];\n this.titlesArr = [];\n\n this.init = function (){ \n this.dotsInit (this.data.dots , \".stepsDotsContainer--js\"); // create a steps object , append into the html tag.\n this.titlesInit (this.data.titles, \".stepsTitlesContainer--js\"); // create a titles object , append into the html tag.\n // steps.descriptions.init (stepsDescriptionsData, \".stepsDescriptionsContainer\"); // create a titles object , append into the html tag.ta\n // setStepsDefaults (this.data); \n }\n\n this.dotsInit = function (dataStepsDots , stepsDotsHtmlEL){ //when creating a new Steps object we need to define the html element to connect it to \n // for loop, create the steps according to dataStepsDots\n var output = '';\n for (var i in dataStepsDots){\n var stepDot = new StepDot();\n stepDot.init (dataStepsDots[i] , i);\n output += stepDot.snippet; //adds to output var (a holder var) the html element of this new step\n this.dotsArr.push(stepDot);\n };\n // the birth of the stepsDots into the UI\n $(stepsDotsHtmlEL).append(output);\n\n // after the elements are appended, set the $el for each dot\n for (var i in dataStepsDots){\n this.dotsArr[i].$el = $('#stepDot-' + i) \n }\n }\n\n // ** Titles ------------------------------------------------------------------------------------\n this.titlesInit = function (dataStepsTitles , stepsTitlesHtmlEL){ //when creating a new Titles object we need to define the html element to connect it to \n // for loop, create the steps according to dataSteps\n var output = '';\n for (var i in dataStepsTitles){\n var stepTitle = new StepTitle();\n stepTitle.init (dataStepsTitles[i] , i);\n output += stepTitle.snippet; //adds to output var (a holder var) the html element of this new step\n this.titlesArr.push(stepTitle);\n };\n // append the steps into $el. this will actually place the steps object (which include each of the step object inside it) into the ui. \n this.$el = $(stepsTitlesHtmlEL).append(output);\n \n // after the elements are appended, set the $el for each titles\n for (var i in dataStepsTitles){\n this.titlesArr[i].$el = $('#stepTitle-' + i) \n }\n\n this.removeAllTitles();\n this.titlesArr[0].showTitle()\n }\n // define init descriptions\n // set defaults\n\n // Steps FUNCTIONS -------------------------------------\n // \n\n this.setSelectedStep = function (index){\n this.removeAllSelectedDots();\n this.dotsArr[index].setSelected(); \n this.removeAllTitles();\n this.titlesArr[index].showTitle();\n // this.descriptionsArr[index].setDescription();\n }\n\n this.removeAllSelectedDots = function (){\n for (var i in this.dotsArr) {\n this.dotsArr[i].removeSelected()\n }\n }\n this.pauseAllDots = function () {\n for (var i in this.dotsArr) {\n this.dotsArr[i].setPause()\n }\n }\n this.removeAllTitles = function (){\n for (i in this.titlesArr){\n this.titlesArr[i].displayNone();\n }\n }\n this.next = function (currentStepIndex){\n if(currentStepIndex !== this.dotsArr.length){\n setSelectedStep(currentStepIndex+1)\n }\n };\n\n this.prev = function (currentStepIndex){\n if(currentStepIndex !== 0){\n setSelectedStep(currentStepIndex-1)\n }\n };\n \n this.toggleDotIcon = function (index) {\n switch(true){\n case (this.dotsArr[index].$el.find(\".stepDot__icon\").hasClass(\"stepDot__icon--pause\")) :\n this.pauseAllDots();\n break; \n case (this.dotsArr[index].$el.find(\".stepDot__icon\").hasClass(\"stepDot__icon--play\")) :\n this.pauseAllDots(); \n this.dotsArr[index].togglePlayPause();\n }\n }\n\n // function setSelectedStep (index){\n // selectDot (index)\n // showTitle (index);\n // }\n \n\n\n // function setStepsDefaults (dataSteps){\n // this.removeAllTitles();\n // dataSteps.titlesArr[0].showTitle() ;\n // }\n\n function selectDot (index) {\n for (var i in this.dotsArr){\n $('#stepDot-' + i).addClass('displayNone') \n }\n $('#stepDot-' + index).removeClass('displayNone') \n }\n\n\n\n \n\n}", "function initCodeOfStep(sO) {\r\n\r\n var fO = CurFuncObj;\r\n\r\n // if we have alredy intialized code of the setp, nothing to do.\r\n //\r\n if (sO.boxExprs.length)\r\n return;\r\n\r\n var gId = sO.allGridIds[0];\r\n var gO = fO.allGrids[gId]; // gO = output grid object\r\n\r\n var ind = \"\";\r\n var numind = 0;\r\n\r\n // 3 bins are used for range/mask/formula. Push null expressions for those\r\n //\r\n sO.boxExprs.push(null); // index (grid obj index editing)\r\n sO.boxExprs.push(null); // range\r\n sO.boxExprs.push(null); // mask\r\n sO.boxExprs.push(null); // formula\r\n\r\n sO.boxAttribs.push(new BoxAttribs(0, CodeBoxId.Index)); // index editing \r\n sO.boxAttribs.push(new BoxAttribs(0, CodeBoxId.Range)); // range\r\n sO.boxAttribs.push(new BoxAttribs(1, CodeBoxId.Mask)); // mask\r\n sO.boxAttribs.push(new BoxAttribs(2, CodeBoxId.Formula)); \r\n\r\n\r\n // Foreach root expression. We add this for ALL grids -- even for \r\n // scalars. If the index expressions are not added, the keyword\r\n // \"foreach\" is not displayed.\r\n //\r\n sO.boxExprs[CodeBoxId.Range] =\r\n new ExprObj(false, ExprType.Foreach, \"foreach\");\r\n\r\n if (gO.numDims > 0) { // if output gO is not a simple scalar\r\n\r\n\r\n\r\n // Create the main 'foreach' root expression \r\n //\t\r\n // Create shortcut name \r\n //\r\n var rangeExpr = sO.boxExprs[CodeBoxId.Range];\r\n\r\n for (var d = 0; d < gO.numDims; d++) {\r\n\r\n if (!gO.dimHasTitles[d]) {\r\n\r\n // create a new sub expression (range) for each range\r\n // -- i.e., new range for dim with default output grid \r\n //\r\n var gO = fO.allGrids[sO.allGridIds[0]];\r\n var rangeChild = newRangeExpr(sO, d, gO);\r\n //\r\n // add it to the rangeExpr of the step\r\n //\r\n rangeExpr.addSubExpr(rangeChild);\r\n }\r\n }\r\n }\r\n\r\n // STEP:\r\n // (1) Create default 'if' statement. A standalone if is displayed only if\r\n // the mask box has focs\r\n // (2) Create the default expression statement for a formula\r\n //\r\n sO.boxExprs[CodeBoxId.Mask] = new ExprObj(false, ExprType.If, \"if\");\r\n sO.boxExprs[CodeBoxId.Formula] = new ExprObj(false, ExprType.ExprStmt,\r\n \"\");\r\n\r\n setFocusToDefaultBox();\r\n\r\n}", "function increaseStepCount() {\n lx.stepCount++;\n }", "function allocDataArraysOfStep(fO, sO) {\r\n\r\n // create/init arrays for all grids in a step\r\n //\r\n for (var id = 0; id < sO.allGridIds.length; id++) {\r\n\r\n var gId = sO.allGridIds[id];\r\n var gO = fO.allGrids[gId];\r\n\r\n //alert(\"alloc for grid: \" + gO.caption);\r\n\r\n // create arrays only if we haven't done so before for this grid AND\r\n // this grid is not an input arg OR scalar grid\r\n // NOTE: For a scalar grid, we always need to create an array of 1\r\n // element to show the data value. Even when a scalar grid is\r\n // an incoming arg, we have to explicitly write its data array\r\n // in order to show the value of the incoming arg. \r\n //\r\n // NOTE: If a grid refers to a global grid, we must not create\r\n // data arrays for them (it's a grid reference)\r\n //\r\n if (((gO.inArgNum < 0) && (gO.globalRefId < 0)) ||\r\n (!gO.numDims && !gO.isGridRef)) {\r\n\r\n\t if (!gO.data) { // if we haven't allocated before\r\n\t\tcreateArrays(gO); // create arrays\r\n\t\t// alert(\"Data alloced for \" + gO.caption);\r\n\t }\r\n\t else if (gO.numDims > 0) {\r\n\t\tclearData(gO.numDims-1, gO.data, undefined); // clear data\r\n\t\tlogMsg(\"clearing: \" + gO.caption);\r\n\t } else {\r\n\t\tlogMsg(\"No data alloc/clear for : \" + gO.caption);\r\n\t }\r\n\t} else {\r\n\t logMsg(\"Skipping data alloc/clear entirely for : \" + gO.caption);\r\n\t}\r\n }\r\n}", "function drawProgStructHead() {\r\n\r\n var pO = CurProgObj;\r\n var fO = CurFuncObj;\r\n var sO = CurStepObj;\r\n\r\n var com_opt = \"style='float:left' \";\r\n var com_id = getCommentHtmlId(CommentType.StepTitle, 0);\r\n var comment = getCommentStr('div', com_id, com_opt, sO.stepComment);\r\n\r\n // STEP: Span that is placed on the left\r\n //\r\n var curmod = getModuleSelectStr(); // CurModObj.name;\r\n var str = \"<span class='progStructHead'>\" +\r\n \" <span title='Current Module'>\" + curmod + \"</span> ::\";\r\n\r\n var curfunc = getFuncSelectStr();\r\n str += \" <span title='Current Function'>\" + curfunc + \"</span> :: \";\r\n\r\n //\t+ \" <span title='Current Function'>main()</span> :: \";\r\n\r\n // Step selection drop down box\r\n //\r\n str += \"<span> \" + getStepSelectStr() + \"</span>\";\r\n //\r\n // Get step advance arrow buttons\r\n //\r\n str += \"<span> \" + getStepArrowStr() + \"</span>\";\r\n\r\n str += \"<span> &nbsp </span> <span> &nbsp </span> \";\r\n\r\n // Display the step title. If sO.title is empty (null), we use a\r\n // default title. \r\n //\r\n var titletxt = sO.title;\r\n if (!titletxt) {\r\n titletxt = (sO.isHeader) ? DefHeaderTitle : DefStepTitle;\r\n }\r\n //\r\n // TODO: A text area causes a larger vertical space on Firefox. \r\n //\r\n var onc = \" onchange='recordStepTitle(this)' \";\r\n var title = \"<textarea rows='1' cols='30' class='stepTitle' \" +\r\n \" height=16px maxlength=40\" +\r\n\r\n \"id='StepTitle' \" + onc + \">\" + titletxt + \"</textarea>\";\r\n\r\n //title = \"<span class='stepTitleSpan' contenteditable>Title</span>\";\r\n\r\n\r\n // Comment for this step\r\n // NOTE: Changing this order causes Firefox to draw incorrectly\r\n //\r\n str += \"</span>\" + title + comment;\r\n\r\n\r\n // STEP: Start a new span that floats on to the right of the page\r\n //\r\n str += \"<span style='float:right'>\"; // place on the right\r\n var onc = \"\";\r\n\r\n // show parallelism meter only if configuration is done AND showing data\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) && pO.showData) {\r\n\r\n str += getParallelismMeterStr();\r\n\r\n } // if config done AND showing data\r\n\r\n\r\n // We can create a new step if config is done OR if we are in a header\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) || sO.isHeader) {\r\n\r\n onc = \" onclick='newNextStep(\" + fO.curStepNum + \")' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Insert New Step' \" + onc +\r\n \">\";\r\n }\r\n\r\n // We can duplicate a step only after completing it.\r\n // Note: We cannot duplicate the function header step\r\n //\r\n if ((sO.stageInStep >= StageInStep.ConfigDone) && !sO.isHeader) {\r\n onc = \" onclick='duplicateStep()' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Duplicate Step' \" + onc + \">\";\r\n }\r\n\r\n // We can cancel/delete a step only after starting to configure it\r\n // We can *never* cancel a header step\r\n //\r\n if ((sO.stageInStep >= StageInStep.New) && !sO.isHeader) {\r\n onc = \" onclick='deleteStep()' \";\r\n onc += \" class='headbut' \";\r\n str += \"<input type='button' value='Delete Step' \" + onc + \">\";\r\n }\r\n\r\n str += getMenuHeadStr();\r\n\r\n str += \"</span><BR>\"; // floating right span\r\n str += \"<HR>\"; // horizontal divider\r\n\r\n // Information Window\r\n //\r\n str += \"<span id='infoWin'></span>\";\r\n\r\n var head1 = document.getElementById('progHead');\r\n head1.innerHTML = str;\r\n\r\n // updateInfoWin(\"Sample Message\");\r\n}", "function changeStep(ind) {\r\n\r\n var sO = CurStepObj;\r\n var fO = CurFuncObj;\r\n\r\n // If we are going to a next step while we are just going through \r\n // new output grid selection menu, abandon current step\r\n //\r\n if (sO.stageInStep < StageInStep.ConfigStarted) {\r\n\r\n CurFuncObj.curStepNum = ind;\r\n drawStep(CurFuncObj.allSteps[ind]);\r\n return;\r\n }\r\n\r\n // STEP : Actually change the step\r\n //\r\n if (ind < CurFuncObj.allSteps.length) {\r\n\r\n\t// Remove any highlighted expression and grid highlight from the \r\n\t// current step because we are going to change this step. Not doing\r\n\t// so will keep highlights in grid (even in other steps)\r\n\t//\r\n\tremoveExprAndGridHighlight();\r\n\t//\r\n CurFuncObj.curStepNum = ind;\r\n drawStep(CurFuncObj.allSteps[ind]);\r\n\r\n } else {\r\n alert(\"Step does not exist\");\r\n }\r\n\r\n}", "function fillStepDefaults(oneCaseStep) {\n\n\t\tif (! oneCaseStep['step']){\n\t\t\toneCaseStep['step'] = { \"@ExecType\": \"Yes\", \n\t\t\t\t\t\"Rule\": { \"@Condition\": \"\", \"@Condvalue\": \"\", \"@Else\": \"next\", \"@Elsevalue\": \"\" }\n\t\t\t\t}; \n\t\t}\n\t\tif (!oneCaseStep['step']['Rule']) {\n\t\t\t\toneCaseStep['step']['Rule'] = { \"Rule\": { \"@Condition\": \"\", \"@Condvalue\": \"\", \"@Else\": \"next\", \"@Elsevalue\": \"\" } };\n\t\t}\n\t\tif (! oneCaseStep['onError']) {\n\t\t\toneCaseStep['onError'] = { \"@action\": \"next\", \"@value\": \"\" };\n\t\t}\n\t\tif (! oneCaseStep['runmode']) {\n\t\t\toneCaseStep['runmode'] = { \"@type\": \"next\", \"@value\": \"\" };\n\t\t}\n\t\tif (! oneCaseStep['retry']) {\n\t\t\toneCaseStep['retry'] = { \"@type\": \"next\", \"@Condition\": \"\", \"@Condvalue\": \"\", \"@count\": \"\" , \"@interval\": \"\"};\n\t\t}\n\t\tif (! oneCaseStep['Arguments']) {\n\t\t\toneCaseStep['Arguments'] = { 'argument': [] }\n\t\t}\n\t\tif (! oneCaseStep['InputDataFile']) {\n\t\t\toneCaseStep['InputDataFile'] = \"\";\n\t\t}\n\n}" ]
{ "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 currentQuality += qualityModifier\n\n if (days < 10) {\n currentQuality += qualityModifier\n }\n if (days < 5) {\n currentQuality += qualityModifier\n }\n if (days < 1) {\n currentQuality = 0\n }\n\n return currentQuality\n}", "speedUp() {\n if(this.score > 30) {\n return 1.8;\n }\n if(this.score > 20) {\n return 1.7;\n }\n if(this.score > 15) {\n return 1.5;\n }\n else if(this.score > 12) {\n return 1.4;\n }\n else if(this.score > 10) {\n return 1.3;\n }\n else if(this.score > 8) {\n return 1.2;\n }\n else if(this.score > 5) {\n return 1.1;\n }\n return 1;\n }", "function weather(quality) {\n if(quality >= 8 && quality < 10) {\n return 'great';\n }\n else if(quality >= 6 && quality < 8) {\n return 'good';\n }\n else if(quality >= 3 && quality < 6) {\n return 'okay';\n }\n else {\n return 'not so great';\n }\n}", "getAverageQuality(save) {\n let total = 0;\n let count = 0;\n for (let x in save.modifiers) {\n let mod = save.modifiers[x]\n total += mod.quality\n count++;\n }\n return total/count;\n }", "function rawMultiplier(componentCount){\r\n if(this.componentCount >= 6){\r\n return .3;\r\n }\r\n else{ \r\n return 0.225;\r\n }\r\n \r\n}", "function efficiency(snr) {\n return Math.log2(1.0 + Math.pow(10,snr/10));\n }", "function updateVideoQuality(value) {\n var item = new Array;\n\n //! Update Video Quality\n item.modified = new Date();\n item.id = 1\n item.quality = value;\n Storage.updateVideoQuality(item);\n strVideoQuality = value;\n}", "function rActive (fm10ros) {\n return 3.34 * fm10ros\n}", "function calculateFitFactor(chromosome,getBest){\n\t\t\n\t\tvar chi=0;\n\t\tvar chiTmp=0;\n\t\tvar refTotal=0;\n\t\tfor(var x in this.refferencePoints){\n\t\t\tif (chromosome==undefined){\n\t\t\t console.log(\"nope\");\n\t\t\t}\n\t\t\tvar k=this.getResultForChromosome(chromosome, this.refferencePoints[x][0]);\n\t\t\tvar ref=this.refferencePoints[x][1];\n\t\t\t//\n\t\t\t//chiTmp=x*x*Math.pow(ref-k,2);\n\t\t\tchiTmp=Math.abs(ref-k,2)*Math.abs(ref-k,2);\n\t\t\tchi+=chiTmp;\n\t\t\trefTotal+=ref;\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t//chi = Math.sqrt(chi);\n\t\t//chi=chi/refTotal;\n\t\tvar fitFactor=(100+10000000000000000*Math.exp(-chi*0.0000000001))/10000000000000000;\n\t\t\n\t\tif (this.bestInPopulation.fit<fitFactor && typeof getBest!='undefined'){\n\t\t\tthis.bestInPopulation={\n\t\t\t\t\"fit\":fitFactor,\n\t\t\t\t\"chromosome\":chromosome\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\t\n\t\t//,this.getResultForChromosome(chromosome, x));\n\t\t//console.log(fitFactor);\n\t\treturn fitFactor;\n\t}", "get speedVariation() {}", "function totalQualityPointsPerRow(gpaOrLetGrade, credits) {\n var result = credits * gpaOrLetGrade || 0; //defaults to zero if NaN\n return result.toFixed(2);\n }", "function increaseCostofSubsequentMultiplierPurchase(){\r\n widgetMaker.multiplierCost = widgetMaker.multiplierCost * 1.1;\r\n }", "function calculaArrecadacao(qtdHomens, qtdMulheres){\n return qtdHomens*20 + qtdMulheres*17;\n}", "getCompressionRatio(){\n return ( this.compressedSize*this.compressedSize/\n (this.width*this.height) ) ;\n }", "function getAnchoBandaMinimoQPSK(Fb) {\n B=Fb/2\n return B;\n}", "get sensitivity() {\n return (0, _Conversions.gainToDb)(1 / this._inputBoost.gain.value);\n }", "function selectQuality(q) {\t\r\n\t\t\tvar p = 0;\r\n\t\t\tvar f = false;\r\n\t\t\tvar pref = YT_EMBED_QUALTIY.split(\",\");\r\n\t\t\tfor(px in pref) {\r\n\t\t\t\tif(pref[px] == \"1080p\")\r\n\t\t\t\t\tpref[px] = \"hd1080\";\r\n\t\t\t\telse if(pref[px] == \"720p\")\r\n\t\t\t\t\tpref[px] = \"hd720\"\r\n\t\t\t\telse if(pref[px] == \"480p\")\r\n\t\t\t\t\tpref[px] = \"large\"\r\n\t\t\t\telse if(pref[px] == \"360p\")\r\n\t\t\t\t\tpref[px] = \"medium\"\t\r\n\t\t\t}\r\n\t\t\tvar find = function() {\r\n\t\t\t\tfor(j in q) {\r\n\t\t\t\t\tif(q[j] == pref[p]) {\r\n\t\t\t\t\t\tf = true;\r\n\t\t\t\t\t\tp = j;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tfor(c = 0; c < pref.length; c++) {\r\n\t\t\t\tfind();\r\n\t\t\t\tif(f == true) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tp++;\r\n\t\t\t};\r\n\t\t\treturn q[p];\r\n\t\t}", "function powerOfTheFire (fliActive) {\n return fliActive / 129\n}" ]
{ "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.createElement('h4');\n this._header.classList.add(this.options.classNames.header);\n this._setHeader(this.state.header);\n this._suggestionContainer.appendChild(this._header);\n\n this._listContainer = document.createElement('ul');\n this._listContainer.setAttribute('role', 'listbox');\n this._listContainer.classList.add(this.options.classNames.list);\n this._suggestionContainer.appendChild(this._listContainer);\n\n // put the suggestions adjacent to the input element\n // firefox does not support insertAdjacentElement\n if (HTMLElement.prototype.insertAdjacentElement) {\n this._input.insertAdjacentElement('afterend', this._suggestionContainer);\n } else {\n this._input.parentNode.insertBefore(\n this._suggestionContainer,\n this._input.nextSibling,\n );\n }\n }", "create() {\n this.children = [];\n this.container = document.createElement(\"div\");\n for (var i = 0; i < this.data.length; i++) {\n this.children.push(interfaceUnit(this.data[i], this.container));\n }\n return this.container;\n }", "function buildWeatherDiv(){\n let selectedCity = buildHTML(\"div\", \"col-12 col-lg-8 selected-city\");\n currentWeatherEl.appendChild(selectedCity);\n let card = buildHTML(\"div\", \"card\");\n selectedCity.appendChild(card);\n let cardBody = buildHTML(\"div\", \"card-body d-flex flex-column justify-content-center\");\n card.appendChild(cardBody);\n\n cardBody.appendChild(buildHTML(\"h2\", \"card-title\", `${requestedWeatherData.cityName}`));\n\n let currentDateRaw = new Date(requestedWeatherData.dailyForecast[0].dt*1000);\n let currentDate = currentDateRaw.toLocaleDateString(\"en\");\n cardBody.appendChild(buildHTML(\"h5\", \"current-date\", `${currentDate}`));\n\n let weatherIcon = `https://openweathermap.org/img/wn/${requestedWeatherData.dailyForecast[0].weather[0].icon}@2x.png`\n let weatherIconEl = buildHTML(\"img\", \"col-1 weather-img\");\n weatherIconEl.setAttribute(\"src\", weatherIcon);\n cardBody.appendChild(weatherIconEl);\n\n cardBody.appendChild(buildHTML(\"p\", \"temperature\", `Temperature: ${requestedWeatherData.currentTemp}`));\n cardBody.appendChild(buildHTML(\"p\", \"humidity\", `Humidity: ${requestedWeatherData.currentHumidity}`));\n cardBody.appendChild(buildHTML(\"p\", \"windspeed\", `Wind Speed: ${requestedWeatherData.currentWind}`));\n\n let uvIndex = requestedWeatherData.currentUVI <= 3 ? \"UVindex-low p-2\" : requestedWeatherData.currentUVI <= 7 ? \"UVindex-med p-2\" : \"UVindex-high p-2\";\n cardBody.appendChild(buildHTML(\"p\", uvIndex, `UV Index: ${requestedWeatherData.currentUVI}`));\n}", "create() {\n this.children = { };\n this.container = document.createElement(\"div\");\n for (var key in this.data) {\n this.children[key] = interfaceUnit(this.data[key], this.container);\n }\n return this.container;\n }", "function makeCards() {\n //clear previous search results\n cardWrapperDiv.innerHTML = ``;\n for (let i = 0; i < recipeList.length; i++) {\n let newCard = document.createElement(`div`);\n newCard.classList.add(`card`);\n newCard.setAttribute(`data-id`, [i]);\n newCard.setAttribute(`style`, `background-image: url(${recipeList[i].image}); background-position: center;`);\n\n newCard.innerHTML = `\n <div >\n <span class=\"card-title\">${recipeList[i].label}</span>\n </div> \n `;\n cardWrapperDiv.append(newCard);\n\n }\n\n }", "function createChip(cell) {\n newCell = document.createElement('div')\n newCell.classList = 'chip'\n cell.setAttribute(\"data-player\", `${currentPlayer}`);\n newCell.style.backgroundColor = chipColour();\n cell.appendChild(newCell);\n cell.setAttribute(\"data-clicked\", true);\n}", "function buildMenuContainer() {\n var l_html = '<div id=\"action_container\" class=\"file-action-menu shadow hideme\">' +\n '<ul>' +\n '<li class=\"menu-tile\">Paste options</li>' +\n '<li><a href=\"#\"><span><img src=\"images/paste16.gif\" alt=\"\">Paste</span></a></li>' +\n '<li><a href=\"#\"><span>Paste special...</span></a></li>' +\n '<li class=\"separator\"><a href=\"#\"><span><img src=\"images/link16.gif\" alt=\"\">Paste link</span></a></li>' +\n '</ul>' +\n '</div>';\n\n jQuery('body').append(l_html);\n }", "renderMenuCategories() {\n\n const secondary = this.props.secondary;\n const font = this.props.font;\n\n return this.state.categories.map((item) =>\n <Col key={item} sm={6} className=\"p-3\" style={{'minWidth':'225px'}}>\n <Card className=\"text-center\" >\n <div onClick={() => this.changeCategory(item) }> \n <Card.Header style ={{'fontFamily' :font, 'backgroundColor': secondary, 'textAlign' : 'center', 'fontWeight': 'bold'}}>{item}</Card.Header>\n <Card.Body>\n <img src={this.state.imageUrls[item]} alt = \"category\" style = {{ 'maxHeight': '250px'}} className=\"img-fluid rounded \"></img>\n {this.loadingImage(item)}\n </Card.Body> \n </div>\n </Card>\n </Col> \n );\n }", "function createChips() {\n chipXCenterOne = -0.5;\n chipYCenterOne = 0.5;\n\n chipXCenterFive = 0.5;\n chipYCenterFive = 0.5;\n\n chipXCenterTen = -0.5;\n chipYCenterTen = -0.5;\n\n chipXCenterTwoFive = 0.5;\n chipYCenterTwoFive = -0.5;\n\n // Generic Circle\n var p = vec2(0.0, 0.0);\n chipVertices = [p];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n chipVertices.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n chipVertices.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n // Generic Rectangle for chips\n markerVertices = [\n vec2(-1.5, 0.25),\n vec2(-1.5, -0.25),\n vec2(0, 0.25),\n\n vec2(0, 0.25),\n vec2(0, -0.25),\n vec2(-1.5, -0.25),\n ];\n\n chipVertices.push(...markerVertices);\n\n // Make Bet Area from 2 rectangles and 1 part of a circle\n // Wide Area One\n betAreaWideVertices = [\n vec2(-0.15, 0.0),\n vec2(-0.15, 1.4),\n vec2(0.15, 0),\n\n vec2(0.15, 0),\n vec2(0.15, 1.4),\n vec2(-0.15, 1.4),\n ];\n chipVertices.push(...betAreaWideVertices);\n\n // Tall Area One\n betAreaTallVertices = [\n vec2(-0.1, 0.0),\n vec2(-0.1, 1.45),\n vec2(0.1, 0),\n\n vec2(0.1, 0),\n vec2(0.1, 1.45),\n vec2(-0.1, 1.45),\n ];\n\n chipVertices.push(...betAreaTallVertices);\n\n // Corner\n var k = vec2(0.0, 0.0);\n var cornerVerts = [k];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n cornerVerts.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n cornerVerts.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n chipVertices.push(...cornerVerts);\n\n // Set Colors\n // 1 - white/blue\n chipOnePrimary = vec3(1.0, 1.0, 1.0);\n chipOneSecondary = vec3(20 / 255, 20 / 255, 175 / 255);\n\n // 5 - red/white\n chipFivePrimary = vec3(180 / 255, 10 / 255, 10 / 255);\n chipFiveSecondary = vec3(1.0, 1.0, 1.0);\n\n // 10 - blue/white\n chipTenPrimary = vec3(50 / 255, 50 / 255, 200 / 255);\n chipTenSecondary = vec3(1.0, 1.0, 1.0);\n\n // 25 - black/white\n chipTwoFivePrimary = vec3(0.0, 0.0, 0.0);\n chipTwoFiveSecondary = vec3(1.0, 1.0, 1.0);\n}", "function createStoreItem(storeItemList) {\n // console.log(\"Inside createStoreItem: \", storeItemList)\n\n storeItemListEl.innerHTML = \"\"\n\n for(let i = 0; i < storeItemList.length; i++) {\n const storeItem = storeItemList[i]\n // console.log(storeItem)\n const storeItemListItemEl = document.createElement(\"li\");\n \n const storeItemDivEl = document.createElement(\"div\");\n storeItemDivEl.className = \"store--item-icon\";\n // console.log(\"Inside storreItemDivEl: \", storeItemDivEl)\n // I'm not sure about the below - img , it makes sense to me to include it\n const storeItemImgEl = document.createElement(\"img\");\n // src?\n storeItemImgEl.src = `assets/icons/${storeItem.id}.svg`;\n storeItemImgEl.alt = storeItem.name\n\n const storeItemButtonEl = document.createElement(\"button\")\n // console.log(storeItemButtonEl)\n storeItemButtonEl.innerHTML = \"Add to Cart\"\n\n storeItemListEl.append(storeItemListItemEl)\n storeItemListItemEl.append(storeItemDivEl)\n storeItemDivEl.append(storeItemImgEl)\n storeItemListItemEl.append(storeItemButtonEl)\n \n }\n\n}", "build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}", "_populateCardsGrid(){\n\t\tconst cardsFragment = document.createDocumentFragment();\n\t\tthis._cardsDeck.forEach((card) => {cardsFragment.appendChild(card);});\n\t\t//console.log(this._cardsDeck);\n\t\t//cardsFragment.appendChild(this._cardsDeck[0]);\n\t\t//cardsFragment.appendChild(this._cardsDeck[1]);\n\t\tthis._cardsGrid.appendChild(cardsFragment);\n\t}", "function renderItem() {\n var code = ui.selected[0];\n $item.empty();\n if (code) {\n $item.append(\n ui.view == 'grid'\n ? Ox.TreeList({\n data: Ox.getCountryByCode(code),\n scrollbarVisible: true,\n width: itemSize\n })\n : Ox.Element('<img>')\n .addClass('flag')\n .attr({src: Ox.getFlagByCountryCode(code, 256)})\n );\n }\n }", "function buildCommonCardElements(hSize, theDate, fontColor, iconSize, iconType, temp) {\n let dateEl = document.createElement(hSize);\n dateEl.classList.add(\"card-subtitle\", fontColor);\n let dayMonth = moment(theDate*1000).format('dddd MMMM');\n let dateString = moment(theDate*1000).format('DD');\n dateEl.innerHTML = dayMonth + \"&nbsp;\" + dateString;\n weatherCardBodyEl.appendChild(dateEl);\n let weatherIconEl = document.createElement(\"i\");\n weatherIconEl.classList.add(\"weather-icon\", iconSize, fontColor, \"wi\", \"wi-owm-\"+iconType);\n weatherCardBodyEl.appendChild(weatherIconEl);\n let tempEl = document.createElement(\"h3\");\n tempEl.classList.add(\"card-subtitle\", \"mb-2\", fontColor); \n tempEl.textContent = Math.round(temp) + tempScale;\n weatherCardBodyEl.appendChild(tempEl);\n}", "function createContainer(){\n let container = document.createElement('div');\n container.classList.add('cart-item', 'd-flex', 'justify-content-between', 'text-capitalize' ,'my-3');\n container.innerHTML = `<img src=\"img-cart/doughnut-2.jpeg\" class=\"img-fluid rounded-circle\" id=\"item-img\" alt=\"\">\n <div class=\"cart-item-text\">\n\n <p id=\"cart-item-title\" class=\"font-weight-bold mb-0\">cart item</p>\n <span>$</span>\n <span id=\"cart-item-price\" class=\"cart-item-price\" class=\"mb-0\">10.99</span>\n </div>\n <a href=\"#\" id='cart-item-remove' class=\"cart-item-remove\">\n <i class=\"fas fa-trash\"></i>\n </a>`;\n return container;\n }", "function buildTags()\n {\n TagAPI.get().done((results) => {\n let $modal = $('#tags-modal'),\n id = $(this).attr('data-id'),\n tags = $(results[id]),\n tagCloud = [];\n\n if (tags.length > 0)\n {\n tags.each(function (index, tag) {\n tagCloud.push(\n '<div class=\"tag-entry\">',\n '<strong>' + tag.label + '</strong>',\n '<button type=\"button\" class=\"tag-remove\" data-id=\"' + tag.id + '\"><span class=\"glyphicon glyphicon-trash\"></span></a>',\n '</div>'\n );\n });\n\n $modal.find('#tags-list').html(tagCloud.join(\"\\n\"));\n }\n\n $modal.find('#item-tags').val('');\n $modal.find('#item-id').val(id);\n $modal.modal('show');\n });\n }", "buildCarousel() {\n // Subclasses may override.\n }", "function initializeCards() {\n cardsContainer.empty();\n var cardsToAdd = [];\n for (var i = 0; i < folUpCards.length; i++) {\n cardsToAdd.push(createNewCard(folUpCards[i]));\n }\n cardsContainer.append(cardsToAdd);\n }", "function createCategoriesSlider() {\n let startPoint = document.querySelector(\".dashboard__categories__slider\");\n\n categories.forEach((cat, i) => {\n let sliderItem = document.createElement(\"div\");\n sliderItem.className = \"categories__slider__item\";\n sliderItem.classList.add(`${cat.classes}`);\n sliderItem.onclick = function () {\n filterCategories(cat, sliderItem, i);\n };\n let SliderItemImg = document.createElement(\"img\"); //create the icon element\n SliderItemImg.src = cat.icon;\n SliderItemImg.alt = `${cat.classes}`;\n let sliderItemSpan = document.createElement(\"span\"); //create the text element\n sliderItemSpan.innerHTML = `${cat.category}`;\n startPoint.appendChild(sliderItem);\n sliderItem.appendChild(SliderItemImg);\n sliderItem.appendChild(sliderItemSpan);\n });\n}", "artifactBlockList() {\n return this.state.artifacts.map((currArtifact, i) => {\n return <ArtifactBlock artifactData={currArtifact} key={i} />;\n });\n }" ]
{ "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")) { affiliation = "yellow"; } return affiliation; }
[ "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 return 'hsl('+c+', 100%, 50%)';\n }", "function activityColor(a) {\n if(a.special) {\n return \"#000000\";\n } else if(a.mission_index == null) {\n return \"#FFFFFF\";\n } else {\n return loadedStory.missions[a.mission_index].color;\n }\n}", "function colorize(actorNode) {\r\n\tvar candidate = actorNode.text();\r\n\tif (candidate != \"\") {\r\n\t\tif (isSpecial(candidate)) { //your special list\r\n\t\t\t$(actorNode).css('color', 'rgb(' + specialColor.r + ',' + specialColor.g +','+ specialColor.b +')');\r\n\t\t} else if (isFriend(candidate)) { //your friends\r\n\t\t\t$(actorNode).css('color', 'rgb(' + friendsColor.r + ',' + friendsColor.g +','+ friendsColor.b +')');\r\n\t\t} else if (isLikedPage(candidate)) { //pages you like\r\n\t\t\t$(actorNode).css('color', 'rgb(' + likesColor.r + ',' + likesColor.g +','+ likesColor.b +')');\t\t\t\r\n\t\t} else if (isSelf(candidate)) { //you\r\n\t\t\t$(actorNode).css('color', 'rgb(' + selfColor.r + ',' + selfColor.g +','+ selfColor.b +')');\r\n\t\t} else { //no connection\r\n\t\t\t$(actorNode).css('color', 'rgb(' + noneColor.r + ',' + noneColor.g +','+ noneColor.b +')');\r\n\t\t}\r\n\t\t$(actorNode).css('color', 'rgb(' + noneColor.r + ',' + noneColor.g +','+ noneColor.b +')');\t\t\r\n\t}\r\n}", "function colorPlates(feature){\n return{\n color: \"#FFA500\",\n fillOpacity: 0.05\n };\n}", "_makeColorScheme(category_info) {\n // If at least one element has an explicit itemRgb, assume the entire dataset has colors. BED intervals require rgb triplets,so assume that colors will always be \"r,g,b\" format.\n const has_explicit_colors = category_info.find((item) => item[2]);\n if (has_explicit_colors) {\n return category_info.map((item) => to_rgb({}, item[2]));\n }\n\n // Use a set of color schemes for common 15, 18, or 25 state models, as specified from:\n // https://egg2.wustl.edu/roadmap/web_portal/chr_state_learning.html\n // These are actually reversed so that dim colors come first, on the premise that usually these are the\n // most common states\n const n_categories = category_info.length;\n if (n_categories <= 15) {\n return ['rgb(212,212,212)', 'rgb(192,192,192)', 'rgb(128,128,128)', 'rgb(189,183,107)', 'rgb(233,150,122)', 'rgb(205,92,92)', 'rgb(138,145,208)', 'rgb(102,205,170)', 'rgb(255,255,0)', 'rgb(194,225,5)', 'rgb(0,100,0)', 'rgb(0,128,0)', 'rgb(50,205,50)', 'rgb(255,69,0)', 'rgb(255,0,0)'];\n } else if (n_categories <= 18) {\n return ['rgb(212,212,212)', 'rgb(192,192,192)', 'rgb(128,128,128)', 'rgb(189,183,107)', 'rgb(205,92,92)', 'rgb(138,145,208)', 'rgb(102,205,170)', 'rgb(255,255,0)', 'rgb(255,195,77)', 'rgb(255,195,77)', 'rgb(194,225,5)', 'rgb(194,225,5)', 'rgb(0,100,0)', 'rgb(0,128,0)', 'rgb(255,69,0)', 'rgb(255,69,0)', 'rgb(255,69,0)', 'rgb(255,0,0)'];\n } else {\n // If there are more than 25 categories, the interval layer will fall back to the 'null value' option\n return ['rgb(212,212,212)', 'rgb(128,128,128)', 'rgb(112,48,160)', 'rgb(230,184,183)', 'rgb(138,145,208)', 'rgb(102,205,170)', 'rgb(255,255,102)', 'rgb(255,255,0)', 'rgb(255,255,0)', 'rgb(255,255,0)', 'rgb(255,195,77)', 'rgb(255,195,77)', 'rgb(255,195,77)', 'rgb(194,225,5)', 'rgb(194,225,5)', 'rgb(194,225,5)', 'rgb(194,225,5)', 'rgb(0,150,0)', 'rgb(0,128,0)', 'rgb(0,128,0)', 'rgb(0,128,0)', 'rgb(255,69,0)', 'rgb(255,69,0)', 'rgb(255,69,0)', 'rgb(255,0,0)'];\n }\n }", "function setColour() {\r\n vertices.selectAll(\"circle\")\r\n .style(\"fill\", function (v) {\r\n\r\n // If not connected to any other vertex, set colour to grey\r\n if (!v.degree)\r\n return customColours[2];\r\n\r\n // If general graph, set colour to red\r\n if (selectedAlgorithm == 3)\r\n return customColours[1];\r\n\r\n // If left-hand vertex, set colour to red and if right-hand vertex, set colour to blue\r\n if (v.parity)\r\n return customColours[v.parity % 2];\r\n\r\n // If non-bipartite graph, use one of the standard colours\r\n else\r\n return standardColours(v.id);\r\n\r\n });\r\n}", "static Purple() {\n return new Color3(0.5, 0, 0.5);\n }", "function ColorType()\n{\t\t\t\t\n}", "function colorSituation(d,i){ \n if(mod.IsProvince && mod.IsCity==false){\n return provinceColor(d,i);\n }else if(mod.IsProvince==false && mod.IsCity){\n if(i<34 && d.properties.id != 82 && d.properties.id != 81 && d.properties.id != 31 &&\n d.properties.id != 31 && d.properties.id != 12 && d.properties.id != 11){\n return \"lightgray\"\n }else if(d.properties.id>500 || d.properties.id == 82 || d.properties.id == 81 || d.properties.id == 31 ||\n d.properties.id == 31 || d.properties.id == 12 || d.properties.id == 11){\n return cityColor(d,i); \n }\n }\n }", "static Purple() {\n return new Color4(0.5, 0, 0.5, 1);\n }", "function applyBasicColor() {\n var type;\n basicColorMenu.forEach(function (element) {\n for (i = 0; i < currentColorData.length; i++) {\n if (element.id === currentColorData[i].id) {\n type = element.type;\n element.elements.forEach(function (element) {\n setClassColor(element, currentColorData[i].color, type);\n });\n }\n }\n });\n showClassOnHover();\n}", "function circleColor() {\n red = restrict(red + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n green = restrict(green + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n blue = restrict(blue + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n fill(red, green, blue);\n}", "function jointColor(typeOfJoint) {\n var color;\n switch (typeOfJoint) {\n case 'boundary':\n color = [255, 255, 0];\n break;\n }\n return color;\n}", "setColorQuiescent(){\n\t this.color = colorQuie;\t \n }", "function setColor(population) {\n\tvar population_num = parseInt(population);\n\n\tif (population_num > 150000) {\n\t\treturn '#005824';\n\t} else if (population_num > 125000) {\n\t\treturn '#238b45';\n\t} else if (population_num > 100000) {\n\t\treturn '#41ae76';\n\t} else if (population_num > 75000) {\n\t\treturn '#66c2a4';\n\t} else if (population_num > 50000) {\n\t\treturn '#99d8c9';\n\t} else if (population_num > 25000) {\n\t\treturn '#ccece6';\n\t} else {\n\t\treturn '#edf8fb';\n\t}\n}", "function color() {\n\tfor (var i = 0; i < num; i++) {\n\t\tcoloring.push(randomize());\n\t}\n}", "function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}", "static Teal() {\n return new Color3(0, 1.0, 1.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 validateResponse ( packet ) {\n\tlet result = false;\n\n\t//0 0 129 128 0 1 0\n\tif (packet.length > 7 &&\n\t\tpacket[2] === 129 &&\n\t\tpacket[3] === 128 &&\n\t\tpacket[4] === 0 &&\n\t\tpacket[5] === 1 &&\n\t\tpacket[6] === 0 &&\n\t\tpacket[7] > 0\n\t) {\n\t\tresult = true;\n\t}\n\n\treturn result;\n}", "validateResponse (data) {\n\t\tAssert.deepEqual(data, {}, 'request should return empty response');\n\t}", "function API_Endpoint_Ok(url){\n // ignore the query string, it will be handled by the targeted controller\n let queryStringMarkerPos = url.indexOf('?');\n if (queryStringMarkerPos > -1)\n url = url.substr(0, queryStringMarkerPos);\n // by convention api endpoint start with /api/...\n if (url.indexOf('/api/') > -1) {\n // extract url componants, array from req.url.split(\"/\") should \n // look like ['','api','{resource name}','{id}]'\n let urlParts = url.split(\"/\");\n // do we have a resource name?\n if (urlParts.length > 2) {\n // by convention controller name -> NameController\n controllerName = capitalizeFirstLetter(urlParts[2]) + 'Controller';\n // do we have an id?\n if (urlParts.length > 3){\n if (urlParts[3] !== '') {\n id = parseInt(urlParts[3]);\n if (isNaN(id)) { \n response.badRequest();\n // bad id\n return false;\n } else\n // we have a valid id\n return true;\n\n } else\n // it is ok to have no id\n return true;\n } else\n // it is ok to have no id\n return true;\n }\n }\n // bad API endpoint\n return false;\n }", "function successfulCallbackResponse (response) {\n var statusCode = response.statusCode\n return statusCode >= 200 && statusCode < 300\n}", "function validateSpeechFailAPNFResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"App package not found\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}", "function validateSpeechFailUPResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0002\", \"messageId\");\n equal(se[\"text\"], \"Undefined Parameter\", \"text\");\n equal(se[\"variables\"], \"%1\", \"variables\");\n }\n }\n}", "function validateNumbers() {\n return auctions_id == [0-9]*$ ? axios.post('https://silent-auction-69.herokuapp.com/api/items', auction)\n .then(res => {\n console.log('res:', res)\n })\n .catch(err => {\n console.log('error:', err)\n }) : cogoToast.error('')\n }", "function responseValid(response, data) {\n\tmessage = new Response();\n\tmessage.status = \"valid\";\n\tmessage.data = data;\n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/plain\"});\n\tresponse.write(JSON.stringify(message));\n\tresponse.end();\n}", "function validateSpeechFailACNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Audio coding not specified\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}", "function validateSpeechFailBNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Bitrate not supported\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}", "validateTravisResponse(response) {\n\t\tconst thisPageBuilds = response.data.builds;\n\t\treturn Array.isArray(thisPageBuilds) && thisPageBuilds.length > 0;\n\t}", "function checkAllBidsResponseReceived(){\n\t\tvar available = true;\n\n\t\tutils._each(bidResponseReceivedCount, function(count, bidderCode){\n\t\t\tvar expectedCount = getExpectedBidsCount(bidderCode);\n\n\t\t\t// expectedCount should be set in the adapter, or it will be set\n\t\t\t// after we call adapter.callBids()\n\t\t\tif ((typeof expectedCount === objectType_undefined) || (count < expectedCount)) {\n\t\t\t\tavailable = false;\n\t\t\t}\n\t\t});\n\n\t\treturn available;\n\t}", "function validateSpeechFailTMSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Too Much Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}", "validate() {\n this.verifTitle();\n this.verifDescription();\n this.verifNote();\n this.verifImg();\n console.log(this.errors);\n console.log(this.test);\n if (this.test !== 0) {\n return false;\n }\n return true;\n }", "function handle_API_responses(requestMessage, requestName, request) {\n\t\tswitch(requestMessage){\n\n\t\t\tcase 'weather':\n\t\t\t\tweatherRequestPass = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 'forecast':\n\t\t\t\tforecastRequestPass = true;\n\t\t\t\tbreak;\n\n\t\t\tcase 'error':\n\t\t\t\tconsole.log(\"*** API REQUEST ERROR ***\");\n\t\t\t\tconsole.log(`status and response for the ${requestName} API Request ...`);\n\t\t\t\tconsole.log(request.status);\n\t\t\t\tconsole.log(request.response);\n\n\t\t\t\t// Calls function to display on screen feedback\n\t\t\t\thandleVisualFeedback('fail');\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// IF both API Requests are Sucessful navigate to next section of program\n\t\tif (weatherRequestPass == true && forecastRequestPass == true){\n\t\t\tconsole.log(\"Both API Requests Succesfull !\");\n\t\t\t// Changing button text feedback (back to normal)\n\t\t\thandleVisualFeedback('pass');\n\n\t\t\t//Calling functions to manage/handle the sucesfull API Response data\n\t\t\tmanageWeatherData(weatherDataResponse);\n\t\t\tmanageForecastData(forecastDataResponse);\n\t\t}\n\t}", "static checkParamsValidity (channel) {\n const { clientId, clientSecret, serviceId } = channel\n channel.phoneNumber = channel.phoneNumber.split(' ').join('')\n\n if (!clientId) { throw new BadRequestError('Parameter is missing: Client Id') }\n if (!clientSecret) { throw new BadRequestError('Parameter is missing: Client Secret') }\n if (!serviceId) { throw new BadRequestError('Parameter is missing: Service Id') }\n if (!channel.phoneNumber) { throw new BadRequestError('Parameter is missing: Phone Number') }\n\n return true\n }", "validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }", "function validateSpeechFailNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"No Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}" ]
{ "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 that `leaveViewLight` can be used in `leaveView`.
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 decision = this.limits_().canLeaveDeathmatchZone(player);\n if (!decision.isApproved()) {\n player.sendMessage(Message.DEATH_MATCH_LEAVE_KILLED, decision);\n \n // Manually trigger a death event, because their death should count.\n this.onPlayerDeath({\n playerid: player.id,\n killerid: Player.kInvalidId,\n reason: 0,\n });\n }\n\n if (player.syncedData.lagCompensationMode !== 2) {\n player.syncedData.lagCompensationMode = 2; // this will respawn the |player|\n } else {\n player.respawn();\n }\n\n this.showStats(player);\n }", "leave(...args) {\n const [handId, leaverAddr] = args;\n // make leave receipt\n // size: 32bytes receipt\n const payload = Buffer.alloc(32);\n // <1 bytes 0x00 space for v>\n payload.writeInt8(0, 0);\n // <7 bytes targetAddr>\n payload.write(this.targetAddr.replace('0x', '').substring(26, 40), 1, 'hex');\n // <4 bytes handId>\n payload.writeUInt32BE(handId, 8);\n // <20 bytes signerAddr>\n payload.write(leaverAddr.replace('0x', ''), 12, 'hex');\n return new Signer(args, [payload], Type.LEAVE);\n }", "_unbindLayoutAnimationEndEvent() {\n const menu = this.getMenu()\n\n if (this._transitionCallbackTimeout) {\n clearTimeout(this._transitionCallbackTimeout)\n this._transitionCallbackTimeout = null\n }\n\n if (menu && this._transitionCallback) {\n TRANS_EVENTS.forEach(e => {\n menu.removeEventListener(e, this._transitionCallback, false)\n })\n }\n\n if (this._transitionCallback) {\n this._transitionCallback = null\n }\n }", "restoreThreadState() {\n if (!this._active || !this.tree || !this.view.dbView.viewFolder) {\n return;\n }\n\n if (\n this.view._threadExpandAll &&\n !(this.view.dbView.viewFlags & Ci.nsMsgViewFlagsType.kExpandAll)\n ) {\n this.view.dbView.doCommand(Ci.nsMsgViewCommandType.expandAll);\n }\n if (\n !this.view._threadExpandAll &&\n this.view.dbView.viewFlags & Ci.nsMsgViewFlagsType.kExpandAll\n ) {\n this.view.dbView.doCommand(Ci.nsMsgViewCommandType.collapseAll);\n }\n }", "_removeSelectedElement() {\n // check if a node is selected\n if (this._currentManipulationTarget) {\n // delete all direct and indirect children\n let deleteNodeIds = [this._currentManipulationTarget.id];\n\n let affectedNodes = [...this._currentManipulationTarget.querySelectorAll('.model-node')];\n affectedNodes.forEach(item => deleteNodeIds.push(item.id));\n\n // remove affected nodes\n deleteNodeIds.forEach(item => {\n this._syncedModelNodes.delete(item);\n this.direwolfSpace.sharedStates.delete(item);\n\n // delete nodes from HTML binding\n let htmlBindings = this.globalState.get('htmlBindings');\n htmlBindings.delete(item);\n });\n\n // remove edges\n let deleteEdgeIds = [];\n Object.keys(this._modelEdges).forEach(key => {\n let modelEdge = this._modelEdges[key];\n if ((deleteNodeIds.indexOf(modelEdge.origin) > -1) || (deleteNodeIds.indexOf(modelEdge.target) > -1)) {\n deleteEdgeIds.push(this._syncedModelEdges.get(key).id);\n }\n });\n\n // remove affected edges\n deleteEdgeIds.forEach(item => {\n this._syncedModelEdges.delete(item);\n this.direwolfSpace.sharedStates.delete(item);\n });\n }\n\n // check if an edge is selected\n if (this._lastSelectedModelElement) {\n this._syncedModelEdges.delete(this._lastSelectedModelElement.element.node.id);\n this.direwolfSpace.sharedStates.delete(this._lastSelectedModelElement.element.node.id);\n }\n }", "previous() {\n let tmp = this.currentNode.previous();\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.currentNode.clearChildren();\n //this.currentNode.children.forEach((child) => child.clearChildren());\n console.log(\" ================ PREV ================ \");\n this.ptree();\n }\n return tmp;\n }", "function _mouseLeave(e) {\r\n mouse.posX = 0;\r\n mouse.posY = 0;\r\n for (var button in _state) {\r\n _state[button] = false;\r\n }\r\n }", "function backToLoseMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"loseScreen\");\n} // backToLoseMenu", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "onLeavingFolder() {\n FolderDisplayListenerManager._fireListeners(\"onLeavingFolder\", [this]);\n\n // Keep the msgWindow's openFolder up-to-date; it powers nsMessenger's\n // concept of history so that it can bring you back to the actual folder\n // you were looking at, rather than just the underlying folder.\n if (this._active) {\n msgWindow.openFolder = null;\n }\n }", "function mouseleave(e) {\n lastMousePos = {}\n coords.show()\n }", "detach() {\n this.surface = null;\n this.dom = null;\n }", "function renderGameLost(ctx) {\n resultHeader.innerText = \"You Lost!\";\n gameBtn.innerText = SMILEY_FROWN;\n clearInterval(timer);\n revealEntireGrid(ctx);\n canvas.removeEventListener(\"click\", gridClickListener);\n}", "turnOff() {\n\t\tthis.lightMap.makeDarkness();\n\t}", "function PrisonLeaveCell() {\n\tif (!PrisonSubBehindBars) {\n\t\tPrisonSubIsPresent = false;\n\t\tPrisonSubSelfCuffed = false;\n\t}\n\tif (MaidQuartersCurrentRescue == \"Prison\") MaidQuartersCurrentRescueCompleted = true;\n\tCommonSetScreen(\"Room\", \"MainHall\");\n}", "detach() {\n const parentNode = this._container.parentNode;\n\n if (parentNode) {\n parentNode.removeChild(this._container);\n\n this._eventBus.fire('propertiesPanel.detach');\n }\n }", "function unmount(event) {\n const idx = event.target.parentNode.parentNode.parentNode.id; //grabs id which is designed to correspond to rendererArr idx\n const newRendererArray = [...rendererArray]; //clone rendererArray and change the rendererArray to be false at idx to force the corresponding mealcard not to be rendered\n newRendererArray[idx] = false;\n // const newLayout = [...this.state.layout];\n // for (let i = idx; i < newLayout.length; i++) {\n // newLayout[i].x -= 2;\n // }\n //above does not work, trying to shift every card over upon unmounting left card... oh well :)\n //i think its because gridlayout is not rerendering because it is not diffing so the diff algo doesnt pick it up\n // console.log(newLayout);\n setRendererArray(newRendererArray);\n v;\n }", "static exitAllMenus() {\n ActionManager.instance.menuStack_ = [];\n ActionManager.instance.actionNode_ = null;\n ActionManager.instance.menuManager_.close();\n if (SwitchAccess.mode === Mode.POINT_SCAN) {\n Navigator.byPoint.start();\n } else {\n Navigator.byPoint.stop();\n }\n }", "function backToMain() {\n clearInterval(timer);\n $(\"game-view\").classList.add(\"hidden\");\n $(\"menu-view\").classList.remove(\"hidden\");\n }" ]
{ "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 normalizeOptions(options) {\n options = options || {};\n return {\n concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages),\n format: options.format === undefined ? isomorphic_node_1.format\n : (typeof options.format === \"function\" ? options.format : false),\n };\n}", "function loadOptionsFromStorage() {\n chrome.storage.sync.get([\n 'yiiShortcut',\n 'yiiDocsVersion',\n 'laravelShortcut',\n 'laravelDocsVersion'\n ], function (props) {\n var data = Object.assign({}, defaultOptions, props || {});\n\n yiiShortcutSelect.value = data.yiiShortcut;\n laravelShortcutSelect.value = data.laravelShortcut;\n laravelDocsVersionSelect.value = data.laravelDocsVersion;\n });\n }", "function getSchemeDefinition(options) {\n let definedSchemesNames = Object.keys(definedSchemes);\n // verify that its not custom and preset\n if (options.scheme !== \"custom\" && definedSchemesNames.indexOf(options.scheme) !== -1)\n return definedSchemes[options.scheme];\n // Throw error if scheme is not defined\n else if (options.scheme !== \"custom\" && definedSchemesNames.indexOf(options.scheme) === -1) {\n throw new Error(`Scheme ${options.scheme} is not defined.`);\n }\n else if (options.scheme === \"custom\" && (!options.schemeDefinition || options.schemeDefinition.trim() === \"\")) {\n throw new Error(`Custom scheme has no definition. Scheme Definition must be specified in options`);\n }\n else if (!options.schemeDefinition || options.schemeDefinition.trim() === \"\") {\n throw new Error(`Custom scheme has no definition. Scheme Definition must be specified in options`);\n }\n else {\n return options.schemeDefinition;\n }\n}", "function filterSchemes(scheme){\n\n $(\"#search-status .option-status\").removeClass(\"active\");\n $(\"#no-matches\").hide();\n\n if (scheme != \"\"){\n var slug = strings.toSlugCase(scheme);\n $(\".scheme\").hide();\n $(\".ministry\").hide();\n\n if ($(\".\" + slug).length != 0){\n $(\".\" + slug).show();\n $(\".\" + slug).closest(\".ministry\").show();\n } else {\n $(\"#no-matches\").show();\n }\n\n } else {\n $(\".scheme\").show();\n $(\".ministry\").show();\n }\n\n}", "function cleanOptions(content, options) {\n\t\tvar lines = content.match(/[^\\r\\n]+/g);\n\t\tvar output = options;\n\t\tvar setlist = [\"\"];\n\t\tvar optionsets = {};\n\t\toptionsets[\"\"] = {};\n\t\tvar i;\n\n\t\tfor (i=0; i<lines.length; i++) {\n\t\t\tvar matches = lines[i].match(/^!!!verovio([^\\s]*):\\s*(.*)\\s*$/);\n\t\t\tif (!matches) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (matches[1] == \"-parameter-group\") {\n\t\t\t\tsetlist.push(matches[2]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar mm = matches[2].match(/^\\s*([^\\s]+)\\s+(.*)\\s*$/);\n\t\t\tif (!mm) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar m = matches[1].match(/^-([^\\s]+)\\s*$/);\n\t\t\tvar set = \"\";\n\t\t\tif (m) {\n\t\t\t\tset = m[1];\n\t\t\t}\n\t\t\tif (typeof optionsets[set] === 'undefined') {\n\t\t\t\toptionsets[set] = {};\n\t\t\t}\n\t\t\toptionsets[set][mm[1]] = mm[2];\n\t\t}\n\n\t\tfor (i=0; i<setlist.length; i++) {\n\t\t\tif (!optionsets[setlist[i]]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar keys = Object.keys(optionsets[setlist[i]]);\n\t\t\tvar j;\n\t\t\tvar key;\n\t\t\tfor (j=0; j<keys.length; j++) {\n\t\t\t\tif (typeof output[keys[j]] !== 'undefined') {\n\t\t\t\t\tdelete output[keys[j]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn output;\n\t}", "function updateThemeField() {\n\tvar linkTypeValue = settings.linkType;\n\tvar themePref, themeDef;\n\t\n\t//Get the correct theme preference and default.\n\tif (linkTypeValue == REMOTE) {\n\t\tthemePref = REMOTE_THEME;\n\t\tthemeDef = jQMThemeSource;\n\t} else {\n\t\tvar libPath = getTrueConfigurationPath() + assetDir;\n\t\tthemeDef = libPath + localThemeCSS;\n\t\tthemePref = PREF_CSS_FILE;\n\t}\n\t\n\t//Pre-populate select menu with CSS files.\n\tvar cssOpts = dw.getPreferenceString(PREF_SECTION, themePref, themeDef);\n\tsettings.themeInput.value = cssOpts;\n}", "function createPresetOfCurrent() {\r\n\tvar name = $(\".menuContentGlobal\").find(\"input\").val();\r\n\tvar preset = [];\r\n\tvar isPresetAllowed = true;\r\n\r\n\tif(!name) {\r\n\t\tconsole.log(\"Preset not Allowed: Missing Name\");\r\n\t\tisPresetAllowed = false;\r\n\t}\r\n\tif(activeGraphs.length < 1) {\r\n\t\tconsole.log(\"Preset not Allowed: No Graph\");\r\n\t\tisPresetAllowed = false;\r\n\t}\r\n\r\n\tfor(var i = 0; i < activeGraphs.length; i++) {\r\n\t\tvar graph = {};\r\n\t\tgraph.graphs = activeGraphs[i].graphs;\r\n\t\tgraph.time = activeGraphs[i].time;\r\n\t\tgraph.interpolation = activeGraphs[i].interpolation;\r\n\t\tgraph.keepUpdated = activeGraphs[i].keepUpdated;\r\n\t\tpreset.push(graph);\r\n\r\n\t\tif(activeGraphs[i].graphs.length < 1) {\r\n\t\t\tconsole.log(\"Preset not Allowed: No Station\");\r\n\t\t\tisPresetAllowed = false;\r\n\t\t}\r\n\r\n\t\tif(!activeGraphs[i].time.end && !activeGraphs[i].keepUpdated) {\r\n\t\t\tconsole.log(\"Preset not Allowed: End or Till-Now missing\");\r\n\t\t\tisPresetAllowed = false;\r\n\t\t}\r\n\t\tif(!activeGraphs[i].time.start && !activeGraphs[i].time.span) {\r\n\t\t\tconsole.log(\"Preset not Allowed: Start or Span missing\");\r\n\t\t\tisPresetAllowed = false;\r\n\t\t}\r\n\t}\r\n\tvar preset_json = JSON.stringify(preset);\r\n\r\n\tif(isPresetAllowed) {\r\n\t\t$.ajax({\r\n\t\t\turl:\"../php/savePreset.php\",\r\n\t\t\ttype:\"POST\",\r\n\t\t\tdata: {name: name, preset: preset_json},\r\n\t\t\tsuccess:function(success){\r\n\t\t\t\tconsole.log(success);\r\n\t\t\t\tif(success == \"success\") {\r\n\t\t\t\t\tconsole.log(\"Preset was created!\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\tconsole.log(\"Error while creating!\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tloadAllPresets(function(json_presets){\r\n\t\t\t\t\t//Delete current presets\r\n\t\t\t\t\tallPresets = [];\r\n\t\t\t\t\t$(\".menuContentGlobal\").find(\"Option\").remove();\r\n\r\n\t\t\t\t\tvar json_presets_decoded = JSON.parse(json_presets);\r\n\t\t\t\t\tconsole.log(json_presets_decoded);\r\n\r\n\t\t\t\t\tfor(var i = 0; i < json_presets_decoded.length; i++) {\r\n\t\t\t\t\t\tvar preset_object = {};\r\n\r\n\t\t\t\t\t\tpreset_object.name = json_presets_decoded[i].Name;\r\n\t\t\t\t\t\tpreset_object.data = JSON.parse(json_presets_decoded[i].Data);\r\n\r\n\t\t\t\t\t\tif(preset_object.data[0].time.start) {\r\n\t\t\t\t\t\t\tpreset_object.data[0].time.start = new Date(preset_object.data[0].time.start);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(preset_object.data[0].time.end) {\r\n\t\t\t\t\t\t\tpreset_object.data[0].time.end = new Date(preset_object.data[0].time.end);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tallPresets.push(preset_object);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvar options = \"\";\r\n\t\t\t\t\tfor(var i = 0; i < allPresets.length; i++) {\r\n\t\t\t\t\t\toptions += '<option value=\"'+allPresets[i].name+'\">'+allPresets[i].name+'</optioin>';\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t$(\".menuContentGlobal\").find(\"Select\").append(options);\r\n\r\n\t\t\t\t});\r\n\t\t\t},\r\n\t\t});\r\n\t}\r\n}", "mergeSetOptionDefualtOption(option) {\r\n let options = (option && _.isObject(option)) ? _.pick(option, _.keys(this.defaultOptions)) : {};\r\n\r\n options = _.extend(this.defaultOptions, options);\r\n\r\n return this.checkCorrectValueFallback(options);\r\n }", "function _sanitizeOption(options, defaults, property, predicate) {\n // set the property to the default value if the predicate returned false\n if (!predicate(options[property])) {\n options[property] = defaults[property];\n }\n }", "function initOptions(optConfig, optSet = undefined, preInit = undefined) {\n let value;\n\n if (optSet === undefined) {\n optSet = { };\n }\n\n for (let opt in optConfig) {\n const __OPTCONFIG = optConfig[opt];\n const __PREINIT = getValue(__OPTCONFIG.PreInit, false);\n\n if ((preInit === undefined) || (__PREINIT === preInit)) {\n const __CONFIG = getSharedConfig(__OPTCONFIG);\n const __ALTACTION = getValue(__CONFIG.AltAction, __CONFIG.Action);\n // Gab es vorher einen Aufruf, der einen Stub-Eintrag erzeugt hat? Wurde ggfs. bereits geaendert...\n const __USESTUB = ((preInit === false) && __PREINIT);\n const __LOADED = (__USESTUB ? optSet[opt].Loaded : false);\n const __VALUE = (__USESTUB ? optSet[opt].Value : initOptValue(__CONFIG));\n\n optSet[opt] = {\n 'Config' : __CONFIG,\n 'Loaded' : __LOADED,\n 'Value' : __VALUE,\n 'SetValue' : __CONFIG.SetValue,\n 'Action' : initOptAction(__CONFIG.Action, opt, optSet),\n 'AltAction' : initOptAction(__ALTACTION, opt, optSet)\n };\n } else if (preInit) { // erstmal nur Stub\n optSet[opt] = {\n 'Config' : __OPTCONFIG,\n 'Loaded' : false,\n 'Value' : initOptValue(__OPTCONFIG)\n };\n }\n }\n\n return optSet;\n}", "processAudienceFilters(values) {\n const oldTerms = this.props.filters[c.TYPE_AUDIENCE] || [];\n const newTerms = values[c.TYPE_AUDIENCE] || [];\n const tree = this.props.audienceOptions;\n\n let selected = newTerms;\n\n // Return if audiences are the same.\n if (oldTerms.length === newTerms.length) {\n return values;\n }\n\n // Which audience changed?\n const altered = xor(oldTerms, newTerms).pop();\n // Was audience added or removed?\n const op = oldTerms.length < newTerms.length ? 'add' : 'remove';\n // Does audience have children?\n const top = tree.filter(t => t.key === altered).pop();\n // If this is a parent apply same operation to children\n if (top) {\n const related = top.children.map(child => child.key);\n selected = op === 'add'\n ? uniq([].concat(newTerms, related))\n : difference(newTerms, related);\n }\n // If this is a child apply same operation to the parent based on all children\n else {\n // Find parent\n const related = tree.filter(\n node => node.children.filter(child => child.key === altered).length > 0\n ).pop();\n\n // If removing a child\n if (op === 'remove') {\n // Remove the parent\n selected = difference(newTerms, [related.key]);\n }\n // If adding a child and all children are selected\n else if (difference(related.children.map(child => child.key), newTerms).length === 0) {\n // Add the parent\n selected = uniq([].concat(newTerms, related.key));\n }\n }\n\n return {\n ...values,\n [c.TYPE_AUDIENCE]: selected,\n };\n }", "function handle_options(optionsArray) {\n var programName = [];\n var currentItem = optionsArray.shift();\n var defaults = amberc.createDefaultConfiguration();\n\n while (currentItem != null) {\n switch (currentItem) {\n case '-C':\n defaults.configFile = optionsArray.shift();\n break;\n case '-p':\n optionsArray.shift.split(',').forEach(function (pairString) {\n var mapping = pairString.split(':');\n defaults.paths[mapping[0]] = mapping[1];\n });\n break;\n case '-l':\n defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));\n break;\n case '-g':\n defaults.jsGlobals.push.apply(defaults.jsGlobals, optionsArray.shift().split(','));\n break;\n case '-n':\n defaults.amdNamespace = optionsArray.shift();\n break;\n case '-D':\n defaults.outputDir = optionsArray.shift();\n break;\n case '-d':\n amber_dir = path.normalize(optionsArray.shift());\n break;\n case '-v':\n defaults.verbose = true;\n break;\n case '-h':\n case '--help':\n case '?':\n case '-?':\n print_usage_and_exit();\n break;\n default:\n defaults.stFiles.push(currentItem);\n break;\n }\n currentItem = optionsArray.shift();\n }\n\n if (1 < programName.length) {\n throw new Error('More than one name for ProgramName given: ' + programName);\n } else {\n defaults.program = programName[0];\n }\n return defaults;\n}", "function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}", "function save() {\n\tvar schemaRaw = document.getElementById('copy-agent-schema').value;\n var schema = JSON.parse(schemaRaw);\n\n // callback on after sync.set\n function onComplete() {\n var err = chrome.runtime.lastError;\n var status = document.getElementById('status');\n\n status.textContent = err || 'Options saved.';\n delete chrome.runtime.lastError;\n\n setTimeout(function() {\n status.textContent = '';\n }, 2000);\n }\n\n chrome.storage.sync.set({'copy-agent-schema': schema}, onComplete);\n}", "function applyPatch(patch) {\n let params = Object.keys(patch);\n params.forEach(i => {\n if (i === \"osc\") {\n $(`#synthWrap :input:radio[name=${i}][id=${patch[i]}]`).prop('checked', true);\n } else if (i === \"detune\") {\n $(`#synthWrap :input:radio[name=${i}][value=${patch[i]}]`).prop('checked', true);\n } else {\n $(`#synthWrap :input#${i}`).val(patch[i]);\n }\n });\n $(\"#synthWrap\").trigger(\"change\");\n $(\"#synthVol\").trigger(\"change\");\n}", "function customSelectsAdjust() {\n $('.sel').each(function () {\n let value = ($(this).find('.sel__opt-val').length > 0) // if .sel__opt-val exists\n ? $(this).find('.sel__opt-val').first().text()\n : $(this).find('.sel__opt').first().text();\n $(this).find('.sel__rslt').text(value);\n \n $(this).width($(this).find('.sel__opts').width());\n })\n }" ]
{ "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(this, arguments); cache.put(key, result); return result; }; }; }
[ "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 cache = {};\n return function(arg) {\n if (cache[arg]) {\n return cache[arg];\n } else {\n cache[arg] = fn(arg);\n return cache[arg];\n }\n };\n}", "function byCache(key, fn) {\n\n\t// the timestamp key\n\tvar timestamp_key = key + '.timestamp';\n\n\t// get by the key\n\tchrome.storage.local.get([ key, timestamp_key ], function(result) {\n\n\t\t// did we find anything\n\t\tif(result) {\n\n\t\t\t// current time\n\t\t\tvar current_timestamp = new Date().getTime();\n\n\t\t\t// check the timestamp\n\t\t\tif( result[timestamp_key] &&\n\t\t\t\t( current_timestamp - result[timestamp_key] ) <= 1000 * 60 * CONSTANTS.CACHE ) {\n\n\t\t\t\t// output our item ..\n\t\t\t\tfn( JSON.parse(result[key]) )\n\n\t\t\t} else {\n\n\t\t\t\t// remove it\n\t\t\t\tchrome.storage.local.remove([ key, timestamp_key ], function() {\n\n\t\t\t\t\t// signal done and that nothing was found from cache ...\n\t\t\t\t\tfn(null);\n\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t} else fn(null);\n\n\t});\n\n}", "function redisCache(prefix, func) {\n return function cacheFuncWrapper() {\n var args = Array.prototype.slice.call(arguments);\n var keyComponents = [prefix].concat(args);\n var key = formatRedisKey.apply(this, keyComponents);\n\n return redis.get(key)\n .then(function(cachedValue) {\n if (cachedValue) {\n // Fail safe cache parsing.\n // If cached value is somehow broken, calculate the value\n // again.\n var obj = null;\n try {\n obj = JSON.parse(cachedValue);\n } catch (err) {\n logger.error('Error when parsing redis cached value:');\n logger.error('key: ' + key);\n logger.error('value: ' + cachedValue);\n logger.error(err);\n }\n\n if (obj) {\n return obj;\n }\n }\n\n logger.info('Calculating redis cache, key: ' + key);\n // Pass arguments passed to `cacheFuncWrapper`\n return func.apply(this, args)\n .then(function(calculatedValue) {\n redis\n .multi()\n .set(key, JSON.stringify(calculatedValue))\n .expire(key, EXPIRE_SECONDS)\n .exec()\n .catch(function(err) {\n logger.error('Error when saving to redis');\n logger.error('key: ' + key);\n logger.error(err);\n throw err;\n });\n\n return calculatedValue;\n })\n .catch(function(err) {\n throw err;\n });\n });\n };\n}", "function setCache(key, value, fn) {\n\n\t// the timestamp key\n\tvar timestamp_key = key + '.timestamp';\n\n\t// params to set\n\tvar params = {};\n\n\t// add in\n\tparams[key] = JSON.stringify(value);\n\tparams[timestamp_key] = new Date().getTime();\n\n\t// get by the key\n\tchrome.storage.local.set(params, function(){\n\n\t\t// signal that we are done\n\t\tfn(null);\n\n\t});\n\n}", "function LocalCache( fn, initCalls, timeout ) {\n\n var cachedFunction = function() {\n return cachedFunction.this( this || cachedFunction._this ).apply( argumentsToArray( arguments ) )\n }\n\n cachedFunction.__proto__ = LocalCache.prototype;\n\n cachedFunction.fn = fn;\n cachedFunction.calls = initCalls || {};\n cachedFunction.timeout = timeout || -1;\n cachedFunction._this = null;\n cachedFunction.forceNext = false;\n\n return cachedFunction;\n\n}", "function cacheLyrics(func) {\n const cachedData = {};\n return (...args) => {\n return new Promise((resolve, reject) => {\n const key = args[0].getAttribute('id');\n if (!(key in cachedData)) {\n func(...args).then((response) => {\n cachedData[key] = response;\n resolve(cachedData[key]);\n });\n } else {\n resolve(cachedData[key]);\n }\n });\n };\n}", "function Cache$( configOrFunction, declConfig ) {\n\n var cache = null;\n\n if ( configOrFunction === undefined ) configOrFunction = {};\n\n if ( typeof configOrFunction === 'function' ) {\n\n // declarative syntax\n var timeout = declConfig ? declConfig.timeout : undefined;\n return LocalCache( configOrFunction, {}, timeout );\n\n } else {\n\n // anonymous syntax\n cache = function( fn ) {\n\n // if we have an existing cache for this function, we'll use it in the\n // LocalCache that we create. Otherwise we'll initialize a new cache.\n var initCalls = getFnCalls( cache, fn );\n if ( initCalls === null ) {\n\n cache._calls[hashFnDef( fn )] = {};\n initCalls = getFnCalls( cache, fn );\n\n }\n\n // if we have a timeout we'll set it, otherwise -1\n var timeout = -1;\n if ( cache.timeout !== undefined ) {\n timeout = cache.timeout;\n }\n\n // create a new LocalCache\n return LocalCache( fn, initCalls, timeout );\n\n }\n\n // set some properties of the cache function\n cache._fn = null;\n cache._calls = {};\n cache.timeout = configOrFunction.timeout;\n\n }\n\n // last resort error checking\n if ( cache === null )\n throw new Error( \"an unknown error caused cache initialization to return null\" );\n\n return cache;\n\n}", "addToCache(key, value) {\n assert.isString(key)\n this._cache[key] = value\n }", "function cachedFetch(cacheKeySelector, fetchFn) {\n return this.scan((cache, item) => {\n const cacheKey = cacheKeySelector(item);\n if (cache.has(cacheKey)) {\n return cache;\n }\n\n return cache.set(cacheKey, fetchFn(cacheKey));\n }, new Map())\n .flatMap(cache => Promise.all(\n cache\n .entrySeq()\n // dematerialize map\n .map(([key, promise]) => promise.then(value => [key, value]))\n )\n // and materialize again\n .then(reduce((acc, [key, value]) => acc.set(key, value), new Map()))\n )\n .map(cache => cache.filter(complement(isNull)));\n}", "function addMethod(key) {\n Cacher.prototype[key] = function () {\n return this.query(key, Array.prototype.slice.call(arguments));\n };\n}", "function wrap (fn) {\n return function () { return fn.apply(this, arguments) }\n}", "function load(req, res, next, key) {\n Cache.get(key)\n .then((cache) => {\n req.cache = cache;\n return next();\n })\n .catch(e => next(e));\n}", "setCache (state, args) {\n state.cache[args.property].args = args\n }", "runPluginFunc(key, args) {\n let retval = {};\n Object.entries(this.plugins).forEach(entry => {\n if (key in entry[1].functions) {\n const val = entry[1].functions[key](this, ...args);\n if (val) {\n retval[entry[0]] = val;\n }\n }\n });\n return retval;\n }", "function createCache() {\n var keys = [];\n\n function cache(key, value) {\n // Use (key + \" \")\n if (keys.push(key + \" \") > Expr.cacheLength) {\n // Only keep the most recent entries.\n delete cache[keys.shift()];\n }\n return (cache[key + \" \"] = value);\n }\n return cache;\n }", "async enforce(...rvals) {\n if (!this.enableCache) {\n return super.enforce(...rvals);\n }\n let key = '';\n const cache = CachedEnforcer.canCache(...rvals);\n if (cache) {\n key = CachedEnforcer.getCacheKey(...rvals);\n const res = this.getCache(key);\n if (res !== undefined) {\n return res;\n }\n }\n const res = await super.enforce(...rvals);\n if (cache) {\n this.setCache(key, res);\n }\n return res;\n }", "function getFnCalls( cache, fn ) {\n\n var fnHash = hashFnDef( fn );\n return cache._calls[fnHash] || null;\n\n}", "visitResult_cache_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "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; return res; }
[ "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\thass_state[ 'Last Connected' ] = gate_state.lastOpened;\n\t\thass_state[ 'Last Message' ] = gate_state.lastMessage;\n\t\thass_state[ 'Last Error' ] = gate_state.lastError;\n\t\thass_state[ 'Connections' ] = gate_state.sessionCount || 0;\n\t\thass_state[ 'Total Messages' ] = gate_state.messageCount || 0;\n\t\thass_state[ 'Dispatched Messages' ] = this.dl.dispatchCount;\n\t\thass_state[ 'Commands' ] = gate_state.commandCount || 0;\n\t\thass_state[ 'Confirmations' ] = gate_state.confirmCount || 0;\n\t\thass_state[ 'Errors' ] = gate_state.errorCount || 0;\n\t\treturn hass_state;\n\t}", "function diagnostic() {\n return Object.keys(tape)\n .map(key => tape[key] === 1 ? 1 : 0)\n .reduce((acc, v) => acc + v, 0);\n}", "function setDiagnostics(state, diagnostics) {\n return {\n effects: setDiagnosticsEffect.of(diagnostics),\n reconfigure: maybeEnableLint(state)\n };\n}", "isInErrorState_(state) {\n return state == TermsOfServiceScreenState.ERROR;\n }", "function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(columnify(env));\n console.log(\" \"); \n }\n \n var ret = model.checkStatus();\n if(ret === false){\n console.log(\"You currently do not have any timers running\");\n }else{\n console.log(columnify(ret));\n }\n }", "getGeneralSystemStatus() {\n const journey = this.props.spec.journey;\n if (journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC\n && journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n if (journey.steps.SUBPROCESS_LISTEN\n && journey.steps.SUBPROCESS_LISTEN.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n return 'preparation-error';\n }", "function listErrors() {\n\treturn Object.keys(errorCodeMap);\n}", "getChangeFlags() {\n var _this$internalState2;\n\n return (_this$internalState2 = this.internalState) === null || _this$internalState2 === void 0 ? void 0 : _this$internalState2.changeFlags;\n }", "get_wlanState() {\n return this.liveFunc._wlanState;\n }", "_systemStatus() {\n\t\tlet systemStatus = SystemStatuses.ok;\n\t\tlet alertCount = 0;\n\t\tthis.activeAlerts.forEach((a) => {\n\t\t\tif (a.status !== SystemStatuses.ok) {\n\t\t\t\talertCount += 1;\n\t\t\t\tif (this._statusIsWorseThan(a.status, systemStatus)) {\n\t\t\t\t\tsystemStatus = a.status;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tstatus: systemStatus,\n\t\t\tmessage: systemStatus !== SystemStatuses.ok ? `${alertCount} alerts outstanding` : null,\n\t\t};\n\t}", "validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }", "async function checkMintControllerState(mintController, customState) {\n await checkControllerState(mintController, customState);\n await checkState(\n mintController,\n customState,\n mintControllerEmptyState,\n getActualMintControllerState,\n Accounts,\n true\n );\n}", "function getHardwareConfigDetails() {\n \n let CONTROL_STATUS = {\n 0 : \"ACTIVE STATUS\",\n 1 : \"REAL TIME UPDATE STATUS\",\n 2 : \"FUNCTION HANDLING STATUS\",\n 3 : \"DEVICE FREEZ\",\n 4 : \"DEVICE RISK\",\n 5 : \"ONE TIME OPERATION\",\n 6 : \"DEVICE RESTART\",\n 7 : \"FIREBASE UPDATE\",\n 8 : \"UPDATE DOUT STATUS ON DB\",\n 9 : \"UPDATE DOUTPIN\",\n 10 : \"UPDATE STATUS\",\n 11 : \"DEEP SLEEP STATUS\"\n }\n\n return CONTROL_STATUS\n\n}", "get isError() {\n return (this.flags & 4) /* NodeFlag.Error */ > 0\n }", "function getStateLabel(){\n\t\t/*jshint validthis:true */\n\t\tif (! this.state){\n\t\t\treturn \"off\";\n\t\t}\n\n\t\tvar position = (_dec2bin(this.state).length - 1).toString(),\n\t\t\tlabels = _.invert(this.conditions);\n\n\t\treturn labels[position];\n\t}", "isErrorState() {\r\n const gl = this.gl;\r\n return gl === null || gl.getError() !== gl.NO_ERROR;\r\n }", "function getConnTrackValues(cb)\n{\n\tvar stderr = '';\n\n\tvar assured = 0;\n\tvar total = 0;\n\tvar unreplied = 0;\n\n\tvar state = {};\n\tSTATES.forEach(function(s) { state[s] = 0; });\n\n\tvar conntrack = _child.spawn('conntrack', ['-L']);\n\tconntrack.stderr.on('data', function (data) { stderr += data.toString(); });\n\tconntrack.stdout.on('data', function (data)\n\t{\n\t\t// parse the output\n\t\tvar lines = data.toString().split('\\n');\n\t\tlines.forEach(function(line)\n\t\t{\n\t\t\tvar match = line.match(/^(tcp|udp)\\s+(\\d+)\\s+(\\d+)\\s+(\\w+)/);\n\t\t\tif (!match)\n\t\t\t\treturn;\n\n\t\t\tif (match[1] === 'tcp' && STATES.indexOf(match[3]) !== -1)\n\t\t\t\tstate[match[3]]++;\n\n\t\t\tif (match[1] === 'udp')\n\t\t\t\tstate.UDP++;\n\n\t\t\tif (line.match(/ASSURED/))\n\t\t\t\tassured++;\n\n\t\t\tif (line.match(/UNREPLIED/))\n\t\t\t\tunreplied++;\n\n\t\t\ttotal++;\n\t\t});\n\t});\n\tconntrack.on('error', function(err)\n\t{\n\t\treturn cb(CONNTRACK_NOT_INSTALLED);\n\t});\n\tconntrack.on('close', function (code)\n\t{\n\t\tif (stderr && !stderr.match(/flow entries have been shown/))\n\t\t\treturn cb(stderr);\n\n\t\tif (code !== 0)\n\t\t\treturn cb('conntrack exited with code ' + code);\n\n\t\treturn cb && cb(null, {\n\t\t\tassured: assured,\n\t\t\tunreplied: unreplied,\n\t\t\ttotal: total,\n\t\t\tstate: state\n\t\t});\n\t});\n}", "getStatus(){ \n // return a clone of the current state garantees it can be \n // stored by the user without being altered when new input events happen\n return {...VIRTUAL_BUTTONS_STATE}; \n // ...eventually deep clone ... unnecessary rignt now ( no nested objects )\n // return JSON.parse( JSON.serialize( VIRTUAL_BUTTONS_STATE ) ); \n }" ]
{ "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;\n}", "function bagHasKey(bag, key) {\n try {\n bag.getProperty(key);\n return true;\n }\n catch (e) {\n return false;\n }\n}", "function checkIfDataExistsLocalStorage(key) {\n let data = localStorage.getItem(key);\n if (data) {\n if (data !== null && data !== \"undefined\" && data !== \"\") {\n return true;\n }\n }\n else {\n return false;\n }\n}", "checkForKey (futureLocation) {\n const isKeyType = this.board.getCell(futureLocation).getType()\n if (isKeyType === 'key') {\n this.keyGained = true\n return true\n } else {\n return false\n }\n }", "has(key) {\n return (this.links.find((ref) => (ref.rel === key)) != null);\n }", "exists() {\n return null !== this._document;\n }", "has(offset) {\n var keys = Array.isArray(offset) ? offset : dotpath(offset);\n if (!keys.length) {\n return;\n }\n\n var name = keys.shift();\n if (keys.length) {\n var value = this._data[name];\n return value && typeof value.has === 'function' ? value.has(keys) : false;\n }\n return this._data[name] !== undefined;\n }", "hasCache(identifier) {\n validation_1.CacheValidation.validateIdentifier(identifier);\n return this._resources.has(identifier);\n }", "Exists() {\n return this.transaction != null;\n }", "function get(key) {\n console.log('Searching for: ' + key);\n storeObject.table.forEach(function(item) {\n if (item['key'] === key) {\n console.log(item['value']);\n } \n });\n }", "function hasStoredToken() {\n //const vault = await this.getVault();\n return authVault.hasStoredToken();\n }", "function objectExists(type, id) {\n\tif (!metaData.hasOwnProperty(type)) return false;\n\t\n\tfor (var obj of metaData[type]) {\n\t\tif (obj && obj.hasOwnProperty(\"id\") && obj.id === id) return true;\n\t}\n\t\n\treturn false;\n}", "function DDLightbarMenu_QuitKeysIncludes(pKey)\n{\n\treturn (this.additionalQuitKeys.indexOf(pKey) > -1);\n}", "function DDLightbarMenu_SelectItemKeysIncludes(pKey)\n{\n\treturn (this.additionalSelectItemKeys.indexOf(pKey) > -1);\n}", "async existsInDB() {\n let result = {\n dataValues: null\n };\n try {\n const tmpResult = await db.appModel.findOne({\n where: {\n appId: this.appId\n }\n });\n\n if (tmpResult) {\n result = tmpResult;\n this.setApp(result.dataValues);\n return true;\n }\n } catch (err) {\n new ErrorInfo({\n appId: this.appId,\n message: err.message,\n func: this.existsInDB.name,\n file: constants.SRC_FILES_NAMES.APP\n }).addToDB();\n }\n return false;\n }", "async includes (key, value) {\r\n\t\tconst obj = await this.model.findOne({ name: key });\r\n\t\tif (obj) {\r\n\t\t\treturn obj.value.includes(value);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "exists() {\n return this.element ? true : false;\n }", "onPropertyHas(room, property, identifier) {\n return room.hasOwnProperty(property);\n }", "async exists() {\n return $(this.rootElement).isExisting();\n }" ]
{ "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;\n\n saveStateToStorage(); // save current history\n }", "clearHistory() {\n ConfirmUI.launchConfirm(/** @type {osx.window.ConfirmOptions} */ ({\n confirm: this.clearHistoryInternal_.bind(this),\n prompt: 'Are you sure you want to clear the application history? This action cannot be undone.',\n yesText: 'Clear',\n yesIcon: 'fa fa-trash-o',\n yesButtonClass: 'btn-danger',\n windowOptions: {\n 'label': 'Clear History',\n 'icon': 'fa fa-trash-o',\n 'x': 'center',\n 'y': 'center',\n 'width': '325',\n 'height': 'auto',\n 'modal': 'true',\n 'headerClass': 'bg-danger u-bg-danger-text'\n }\n }));\n }", "function clear_data_canvas(){\n data_ctx.clearRect(0,0,110,80)\n}", "function addDrawHistory() {\n restoreArray.push(ctx.getImageData(0, 0, canvas.width, canvas.height))\n index+=1; \n}", "updateHistory(board) {\n /* add current board to history and increment history index\n *** if historyIndex is less than historyLength-1, it \n means that a move has been played after the user has \n used the jump backwards button. Therefore, all elements in history after\n where historyIndex currently is should be erased *** \n */\n const historyIndex = this.state.historyIndex;\n const historyLength = this.state.history.length;\n let history = this.state.history;\n if (historyIndex < historyLength - 1) {\n history = this.state.history.splice(0, historyIndex + 1);\n }\n\n return history.concat([{ board: board }]);\n }", "function clearCanvas() {\n elements.gridCanvas.innerHTML = '';\n }", "function clearConsole() {\n // reset drawing title\n abEamTcController.setDrawingPanelTitle(getMessage('noFlSelected'));\n // clear drawing content\n abEamTcController.clearDrawing();\n // clear asset details\n abEamTcController.clearAssetDetailRestriction(true);\n}", "function resetCanvas() {\n\tcxt.fillStyle = localStorage.fillColor;\n\tcxt.fillRect(0, 0, canvas.width, canvas.height);\n}", "function clearHighlightCanvas() {\n\tvar highlightCanvas = document.getElementById('highlight-points')\n\tvar highlightCtx = highlightCanvas.getContext('2d')\n\thighlightCtx.clearRect(0, 0, highlightCanvas.offsetWidth, highlightCanvas.offsetHeight)\n}", "function clearCanvas() {\n context.clearRect(0, 0, canvas.width, canvas.height);\n pointCount = 0;\n drawImage();\n }", "function clearCC() {\n\t$('#'+shell.caption.textEl).empty();\t\n}", "function initClearButton() {\n $('#canvas-clear').on('click', function (e) {\n // clear canvas\n cls();\n // clear corresponding kg tags\n clearKgTags();\n clearKgHistories(roomIdDb);\n });\n}", "function clean(canvas) {\r\n\tvar canvas = canvas[0];\r\n\tvar context = canvas.getContext('2d');\r\n\tcontext.clearRect(0, 0, canvas.width, canvas.height);\r\n}", "function clearGrid() {\n const mainDiv = document.getElementById('canvas');\n mainDiv.innerHTML = '';\n}", "function clearScreen(event) {\n pageTitleEl.textContent = '';\n instructionEl.textContent = '';\n startButtonEl.textContent = '';\n quizStarter();\n}", "clearAllObject() {\r\n this.m_drawToolList.length = 0;\r\n this.clearTechToolMousePos();\r\n }", "flushHistory() {\n const currDate = new Date();\n for (let i = 0; i < this.history.length; i += 1) {\n const diff = (currDate - new Date(this.history[i].date));\n if (diff / (1000 * 3600 * 24 * 365) > 1) {\n this.history.splice(i, 1);\n }\n }\n localStorage.setItem('statsHistory', JSON.stringify(this.history));\n }", "function delete_prev_grid() {\n var table = document.getElementById(\"pixel_canvas\");\n var rowCount = table.rows.length;\n while (table.rows.length > 0) {\n table.deleteRow(0);\n }\n }" ]
{ "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(this.startValue).getTime() - this.removeTimeValueFromDate(this.endValue).getTime()) / (1000 * 60 * 60 * 24))) + 1); this.disabledDateRender(); if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(this.disabledDayCnt)) { range = range - this.disabledDayCnt; this.disabledDayCnt = null; } } else { range = 0; } return { startDate: this.startValue, endDate: this.endValue, daySpan: range }; }
[ "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_onclick = \"create_calander('calander','0','st-day','st-month','st-year'); show_hide('calander');\";\n var end_img_onclick = \"create_calander('calander','0','en-day','en-month','en-year'); show_hide('calander');\";\n //\n // initializing variable inputs\n var time_range_onchange = '';\n var day_onkeyup = '';\n var month_onchange = '';\n var year_onchange = '';\n //\n // creating date objects for time range inputs\n var today = new Date();\n var first = new Date(today.getFullYear(),today.getMonth(),1);\n var curr_wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()))];\n curr_wk[1] = new Date(curr_wk[0].getFullYear(),curr_wk[0].getMonth(),(curr_wk[0].getDate()+6))\n var last_2wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-7)),curr_wk[1]];\n var last_4wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-21)),curr_wk[1]];\n var curr_mth = [new Date(first.getFullYear(),first.getMonth(),(first.getDate()-first.getDay()))];\n curr_mth[1] = new Date(first.getFullYear(),first.getMonth()+1,1);\n curr_mth[1] = new Date(curr_mth[1].getFullYear(),curr_mth[1].getMonth(),(curr_mth[1].getDate()+(6-curr_mth[1].getDay())));\n var curr_pp = new Date(CONSTANTS.FIRST_BUSINESS_DAY[0],+CONSTANTS.FIRST_BUSINESS_DAY[1]-1,CONSTANTS.FIRST_BUSINESS_DAY[2]);\n var test_date = curr_pp;\n curr_pp = [curr_pp]\n for (var w = 0; w < 60; w+=2) {\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()+14));\n curr_pp[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-1));\n if (test_date > today) {break;}\n curr_pp = [test_date];\n }\n var prev_pp = [new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-14))];\n prev_pp[1] = new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-1));\n curr_wk = curr_wk[0].yyyymmdd()+ '|' +curr_wk[1].yyyymmdd();\n last_2wk = last_2wk[0].yyyymmdd()+'|' +last_2wk[1].yyyymmdd();\n last_4wk = last_4wk[0].yyyymmdd()+'|' +last_4wk[1].yyyymmdd();\n curr_mth = curr_mth[0].yyyymmdd()+'|' +curr_mth[1].yyyymmdd();\n curr_pp = curr_pp[0].yyyymmdd()+ '|' +curr_pp[1].yyyymmdd();\n prev_pp = prev_pp[0].yyyymmdd()+ '|' +prev_pp[1].yyyymmdd();\n //\n // processing input args\n if (!!(input_args.time_range_onchange)) {time_range_onchange = input_args.time_range_onchange;}\n if (!!(input_args.day_onkeyup)) {day_onkeyup = input_args.day_onkeyup;}\n if (!!(input_args.month_onchange)) {month_onchange = input_args.month_onchange;}\n if (!!(input_args.year_onchange)) {year_onchange = input_args.year_onchange;}\n if (!!(input_args.add_date_range_onclick)) {date_range_onclick += input_args.add_date_range_onclick;}\n if (!!(input_args.add_st_img_onclick)) {st_img_onclick += input_args.st_img_onclick;}\n if (!!(input_args.add_end_img_onclick)) {end_img_onclick += input_args.add_end_img_onclick;}\n //\n // creating output fields\n var output = ''+\n '<label class=\"label\">Time Range:</label>'+\n '<select id=\"time-range\" class=\"dropbox-input\" name=\"time-range\" onchange=\"'+time_range_onchange+'\">'+\n '<option value=\"'+curr_wk+'\">Current Week</option>'+\n '<option value=\"'+curr_pp+'\">Current Pay Period</option>'+\n '<option value=\"'+prev_pp+'\">Previous Pay Period</option>'+\n '<option value=\"'+last_2wk+'\">Last 2 Weeks</option>'+\n '<option value=\"'+last_4wk+'\">Last 4 Weeks</option>'+\n '<option value=\"'+curr_mth+'\">Current Month</option>'+\n '</select>'+\n '&nbsp;&nbsp;'+\n '<button id=\"show_date_range\" type=\"button\" name=\"show_date_range\" onclick=\"'+date_range_onclick+'\">Show Date Range</button>'+\n '<div id=\"date_range\" class=\"hidden-elm\" name=\"date_range\">'+\n '<span id=\"calander\" class=\"cal-span hidden-elm\"></span>'+\n '<label class=\"label-4em\">From:</label>'+\n '<input id=\"st-day\" class=\"text-input-xsmall\" type=\"text\" name=\"st-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n '&nbsp;'+\n '<select id=\"st-month\" class=\"dropbox-input\" name=\"st-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id=\"1\" value=\"01\">January</option>'+\n '<option id=\"2\" value=\"02\">February</option>'+\n '<option id=\"3\" value=\"03\">March</option>'+\n '<option id=\"4\" value=\"04\">April</option>'+\n '<option id=\"5\" value=\"05\">May</option>'+\n '<option id=\"6\" value=\"06\">June</option>'+\n '<option id=\"7\" value=\"07\">July</option>'+\n '<option id=\"8\" value=\"08\">August</option>'+\n '<option id=\"9\" value=\"09\">September</option>'+\n '<option id=\"10\" value=\"10\">October</option>'+\n '<option id=\"11\" value=\"11\">November</option>'+\n '<option id=\"12\" value=\"12\">December</option>'+\n '</select>'+\n '&nbsp;'+\n '<select id=\"st-year\" class=\"dropbox-input\" name=\"st-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n '&nbsp;&nbsp;&nbsp;&nbsp;'+\n '<a onclick=\"'+st_img_onclick+'\"><image id=\"cal_st_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '<br>'+\n '<label class=\"label-4em\">To:</label>'+\n '<input id=\"en-day\" class=\"text-input-xsmall\" type=\"text\" name=\"en-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n '&nbsp;'+\n '<select id=\"en-month\" class=\"dropbox-input\" name=\"en-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id =\"1\" value=\"01\">January</option>'+\n '<option id =\"2\" value=\"02\">February</option>'+\n '<option id =\"3\" value=\"03\">March</option>'+\n '<option id =\"4\" value=\"04\">April</option>'+\n '<option id =\"5\" value=\"05\">May</option>'+\n '<option id =\"6\" value=\"06\">June</option>'+\n '<option id =\"7\" value=\"07\">July</option>'+\n '<option id =\"8\" value=\"08\">August</option>'+\n '<option id =\"9\" value=\"09\">September</option>'+\n '<option id =\"10\" value=\"10\">October</option>'+\n '<option id =\"11\" value=\"11\">November</option>'+\n '<option id =\"12\" value=\"12\">December</option>'+\n '</select>'+\n '&nbsp;'+\n '<select id=\"en-year\" class=\"dropbox-input\" name=\"en-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n '&nbsp;&nbsp;&nbsp;&nbsp;'+\n '<a onclick=\"'+end_img_onclick+'\"><image id=\"cal_en_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '';\n //\n document.getElementById(input_args.output_id).innerHTML = output;\n //\n populate_year_dropboxes('st-year');\n populate_year_dropboxes('en-year');\n}", "function _getRange() {\n\t\t// sel: a selection object representing the range of text selected by the user\n\t\tvar sel = win.getSelection();\n\t\t// Return a range object representing the current selection or false\n\t\treturn (sel.rangeCount) ? sel.getRangeAt(0) : false;\n\t}", "function getRegionBounds(def) {\n var _getHistRange = getHistRange(def);\n\n var _getHistRange2 = _slicedToArray(_getHistRange, 2);\n\n var minRange = _getHistRange2[0];\n var maxRange = _getHistRange2[1];\n\n return [minRange].concat(def.dividers.map(function (div) {\n return div.value;\n }), maxRange);\n }", "function _getSegments() {\n switch ($scope.options.timeScope) {\n case 'day':\n return _getHours();\n case 'range':\n return _getDaysForRange();\n case 'month':\n return _getDaysForMonth();\n case 'week':\n default:\n return _getWeekDays();\n }\n }", "function datePickerHook() {\n $('.select-options li').each(function () {\n $(this).on('click', function () {\n let startMonth = document.getElementById('date-range--start-month')\n .value\n let startYear = document.getElementById('date-range--start-year').value\n let endMonth = document.getElementById('date-range--end-month').value\n let endYear = document.getElementById('date-range--end-year').value\n const facetDate = document.getElementsByClassName(\n 'facetwp-facet-publish_date'\n )[0]\n\n facetDate.querySelectorAll('.fs-option').forEach(function (el) {\n const startDate = new Date(startYear, startMonth, 1)\n const endDate = new Date(endYear, endMonth, 1)\n const elDate = new Date(\n el.getAttribute('data-value').slice(0, 4),\n el.getAttribute('data-value').slice(4, 6) - 1,\n 1\n )\n if (elDate >= startDate && elDate <= endDate) {\n el.click()\n }\n })\n })\n })\n }", "function ServerBehavior_getWrapSelectionOffsets()\n{\n var retVal = null;\n\n var dom = dw.getDocumentDOM();\n\n // get the start and end offsets\n var partList = this.getParticipants();\n\n var start = -1;\n var end = -1;\n for (var i=0; i < partList.length; i++)\n {\n var nodeSegment = partList[i].getNodeSegment();\n var weight = partList[i].getWeight();\n\n if (weight == \"wrapSelection\")\n {\n // record the start and end\n var nodeOffset = dwscripts.getNodeOffsets(nodeSegment.node);\n var newStart = nodeOffset[0] + nodeSegment.matchRangeMin;\n var newEnd = nodeOffset[0] + nodeSegment.matchRangeMax;\n if (newStart < start || start == -1)\n {\n start = newStart;\n }\n if (newEnd > end)\n {\n end = newEnd;\n }\n }\n else if (weight == \"beforeSelection\")\n {\n var nodeOffset = dwscripts.getNodeOffsets(nodeSegment.node);\n var newStart = nodeOffset[0] + nodeSegment.matchRangeMin;\n if (newStart < start || start == -1)\n {\n start = newStart;\n }\n }\n else if (weight == \"afterSelection\")\n {\n var nodeOffset = dwscripts.getNodeOffsets(nodeSegment.node);\n var newEnd = nodeOffset[0] + nodeSegment.matchRangeMax;\n if (newEnd > end)\n {\n end = newEnd;\n }\n }\n }\n\n if (start != -1 && end != -1)\n {\n retVal = new Array(start,end);\n }\n\n return retVal;\n}", "getDayRanges() {\n let params = '?part=day-ranges&time_zone='\n + Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n return fetch(`${config.API_ENDPOINT}/projects${params}`, {\n headers: {\n 'authorization': `bearer ${TokenService.getAuthToken()}`,\n }\n })\n .then(res =>\n (!res.ok)\n ? res.json().then(e => Promise.reject(e))\n : res.json()\n )\n }", "createRangeBySelectedCells() {\n const sq = this.wwe.getEditor();\n const range = sq.getSelection().cloneRange();\n const selectedCells = this.getSelectedCells();\n const [firstSelectedCell] = selectedCells;\n const lastSelectedCell = selectedCells[selectedCells.length - 1];\n\n if (selectedCells.length && this.wwe.isInTable(range)) {\n range.setStart(firstSelectedCell, 0);\n range.setEnd(lastSelectedCell, lastSelectedCell.childNodes.length);\n sq.setSelection(range);\n }\n }", "function getDateRange(start, end){\n\n\tvar done = false\n\tconst bg = chrome.extension.getBackgroundPage()\n\n\tvar xhr = new XMLHttpRequest()\n\txhr.open(\"POST\", \"http://localhost:3000/requestData\")\n\txhr.setRequestHeader(\"Content-Type\", \"application/json\")\n\n\txhr.send(JSON.stringify({\"id\":bg.id, \"startDate\":start, \"endDate\":end}))\n\txhr.onreadystatechange = function() {\n\t\tif (!done) {\n\t\t\tlet returnData = xhr.responseText.trim()\n\t\t\tif (returnData === \"\") return\n\t\t\tsiteDataTextrange = '{' + \"\\\"key_val\\\":\" + xhr.responseText + '}'\n\n\t\t\tconsole.log(siteDataTextrange)\n\t\t\tsiteDatarange = JSON.parse(siteDataTextrange)[\"key_val\"]\n\n\t\t\tdateRangeData = siteDatarange\n\n\t\t\tdone = true\n\t\t}\n\t}\n}", "function getCombinedDateRange() {\n var datasets = ocean.variables[ocean.variable].plots[ocean.plottype][ocean.period];\n var minDate = Number.MAX_VALUE;\n var maxDate = Number.MIN_VALUE;\n\n $.each(datasets, function(i, datasetid) {\n var range = getDateRange(datasetid, ocean.variable, ocean.period);\n\n if (!range)\n return; /* continue */\n\n /* 726: ww3 hourly data is available until July 2014 whereas monthly data is available until 2009*/\n if (datasetid == \"ww3\" && ocean.period == \"hourly\" && ocean.plottype == \"map\"){\n range.max = new Date(2016, 0, 31);\n }\n\n minDate = Math.min(minDate, range.min);\n maxDate = Math.max(maxDate, range.max);\n });\n\n return { min: new Date(minDate), max: new Date(maxDate) };\n}", "function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }", "GetDates() {\n let today = new Date();\n let nextDate = today.setDate(today.getDate() + 30);\n let dates = this.getDatesBetween(new Date(), nextDate);\n let datesOptions = {};\n dates.forEach((date) => {\n datesOptions[date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()] = getTextDate(date);\n });\n return datesOptions;\n }", "function minMaxSet() {\n min = parseInt(minRange.value);\n max = parseInt(maxRange.value);\n}", "function getRangeObject(selectionObject)\n{\n if (selectionObject.getRangeAt)\n return selectionObject.getRangeAt(0);\n else\n { // Safari 1.3\n let range = document.createRange();\n range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);\n range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);\n return range;\n }\n}", "function getSelectionCoordinates() \n{\n var selection = SlidesApp.getActivePresentation().getSelection();\n switch (selection.getSelectionType()) \n {\n case SlidesApp.SelectionType.PAGE_ELEMENT:\n {\n // only interested if selection is containing page elements\n var elements = selection.getPageElementRange();\n var top = 1000000;\n var left = 1000000;\n if (elements) \n {\n // find the left-most, top-most coordinate of selected elements\n var pageElements = elements.getPageElements();\n for (var i = 0; i < pageElements.length; i++) \n {\n var element = pageElements[i];\n var elementTop = element.getTop();\n var elementLeft = element.getLeft();\n if (top > elementTop)\n top = elementTop;\n if (left > elementLeft)\n left = elementLeft;\n }\n return [left, top];\n }\n }\n }\n return [0, 0];\n}", "getReportRange(date1,date2){\n let d1= new Date(date1);\n let d2 = new Date(date2);\n let days = (d2.getTime() - d1.getTime()) / (1000*60*60*24)\n let goal = this.gCals() * days;\n let eaten = this.getFoodRange(date1,date2).calories;\n let burned = this.getActivitiesRange(date1,date2).caloriesBurned;\n let calRemaining = goal - eaten + burned;\n return {eaten: eaten, burned: burned, goal: goal, \n remaining: calRemaining};\n }", "splitDateRange(begin, end, step) {\n const beginDate = moment(begin);\n const endDate = moment(end);\n if (!beginDate.isValid() || !endDate.isValid() || beginDate.isAfter(endDate)) {\n throw new Error('invalid date range');\n }\n\n const format = 'YYYY-MM-DD';\n const ranges = [];\n while (!beginDate.isAfter(endDate)) {\n const beginDateString = beginDate.format(format);\n beginDate.add(step - 1, 'days');\n const minDate = moment.min(beginDate, endDate);\n const endDateString = minDate.format(format);\n ranges.push([beginDateString, endDateString]);\n beginDate.add(1, 'days');\n }\n return ranges;\n }", "formattedSelectedPeriod() {\n return createSelector(slice, (state) => {\n if (\n state.selectedPeriod === PeriodEnum.CUSTOM &&\n state.fromDate &&\n state.toDate\n ) {\n const fromDateFormatted = lightFormat(state.fromDate, \"dd/MM/yy\");\n const toDateFormatted = lightFormat(state.toDate, \"dd/MM/yy\");\n return `${fromDateFormatted} - ${toDateFormatted}`;\n }\n\n return getPeriodLabel(state.selectedPeriod);\n });\n }", "range(start, end) {\n return new vscode.Range(start, end);\n }" ]
{ "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(branches, remote); // If the ref exists, get the sha and latest sha for the remote ref. if (ref) { const sha = getShaFromRef(`HEAD~${headCount}`); const latestSha = getShaFromRef(`${remote}/${ref}`); return {ref, sha, latestSha, remote}; } headCount++; } return {ref: '', latestSha: '', sha, remote}; }
[ "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 = [neighbor, currCost]\n\t\t\treturn best\n\t\t}, [0, null])\n\t}", "function getRefsAndShasForChange() {\n let base, target;\n if (process.env['CI']) {\n base = getRefAndShas(process.env['CI_GIT_BASE_REVISION'], process.env['CI_REPO_OWNER']);\n target = getRefAndShas(process.env['CI_GIT_REVISION'], process.env['CI_PR_USERNAME']);\n } else {\n const originSha = getShaFromRef(`HEAD`);\n target = getRefAndShas(originSha, 'origin');\n base = getParentBranchForHead('upstream');\n }\n const commonAncestorSha = getCommonAncestorSha(base.sha, target.sha);\n return {\n base,\n target,\n commonAncestorSha,\n };\n}", "parentHashes(str) {\n if (Objects.type(str) === 'commit') {\n return str.split('\\n')\n .filter(line => line.match(/^parent/))\n .map(line => line.split(' ')[1]);\n }\n }", "function whoIsTheParent(tree, target) {\n let parentValue = tree['value'];\n let children = tree['children'];\n for(let child of children){\n if(child['value']===target){\n return parentValue\n }else {\n if(child['children'].length!==0){\n if(whoIsTheParent(child,target)!==undefined) return whoIsTheParent(child,target)\n }\n }\n }\n return undefined;\n}", "findFsParents () {\n for (const path of this.linkTargets) {\n const node = this.cache.get(path)\n if (!node.parent && !node.fsParent) {\n for (let p = dirname(path); p;) {\n if (this.cache.has(p)) {\n node.fsParent = this.cache.get(p)\n p = null\n } else {\n // walk up the tree until p === dirname(p)\n const pp = dirname(p)\n if (pp === p)\n p = null\n else\n p = pp\n }\n }\n }\n }\n }", "ancestors(commitHash) {\n const parents = Objects.parentHashes(Objects.read(commitHash));\n return Util.flatten(parents.concat(parents.map(Objects.ancestors)));\n }", "function findParent(mod) {\n return mod.parent ? findParent(mod.parent) : mod;\n}", "function findNextParentHeading(cell, notebook) {\n let index = findIndex(notebook.widgets, (possibleCell, index) => {\n return cell.model.id === possibleCell.model.id;\n });\n if (index === -1) {\n return -1;\n }\n let childHeaderInfo = getHeadingInfo(cell);\n for (index = index + 1; index < notebook.widgets.length; index++) {\n let hInfo = getHeadingInfo(notebook.widgets[index]);\n if (hInfo.isHeading &&\n hInfo.headingLevel <= childHeaderInfo.headingLevel) {\n return index;\n }\n }\n // else no parent header found. return the index of the last cell\n return notebook.widgets.length;\n }", "function getParentOfRange(editor) {\r\n\tvar r = getRange(editor);\r\n\tif ($.browser.msie) return r.parentElement()\r\n\treturn r.commonAncestorContainer\r\n }", "async function getLeftMostLeaf(leafCheckArray) { //LeafCheckArray must be a since array - in this case it is\n\n let mostRecentLeaf = {}\n let leafURL = '';\n\n //First time you come upon an empty next is your leftmost leaf\n for (annot in leafCheckArray) {\n \tif (leafCheckArray[annot].__rerum.history.next.length == 0) {\n \t\tmostRecentLeaf = leafCheckArray[annot];\n \t\tbreak;\n \t}\n\n }\n\n return mostRecentLeaf;\n}", "function extUtils_getOffsetsAfterClimbingTree(theObj,currOffs)\n{\n var currObj = theObj;\n var objParent, parentOffs;\n var climbTree = true;\n\n // Note - don't walk all the way up to the document node. It has no offsets.\n while ( climbTree && currObj.parentNode\n && currObj.parentNode.nodeType != Node.DOCUMENT_NODE\n )\n {\n objParent = currObj.parentNode;\n parentOffs = dwscripts.getNodeOffsets(objParent);\n if ( (parentOffs[0] < currOffs[0] && parentOffs[1] < currOffs[1]) ||\n (parentOffs[0] > currOffs[0] && parentOffs[1] > currOffs[1]) )\n {\n currObj = objParent;\n }\n else\n {\n climbTree = false;\n }\n }\n return ( dwscripts.getNodeOffsets(currObj) );\n}", "function getParentPageState() {\n return sp.result(spNavService.getParentItem(), 'data');\n }", "_getStartRefLineNumber(referenceNumber: number): ?number {\n const refRef = PassageMarkdown.START_REF_PREFIX + referenceNumber;\n const ref = this.refs[refRef];\n if (!ref) {\n return null;\n }\n\n const $ref = $(ReactDOM.findDOMNode(ref));\n // We really care about the first text after the ref, not the\n // ref element itself:\n let $refText = $ref.next();\n if ($refText.length === 0) {\n // But if there are no elements after the ref, just\n // use the ref itself.\n $refText = $ref;\n }\n const vPos = $refText.offset().top;\n\n return (\n this.state.startLineNumbersAfter +\n 1 +\n this._convertPosToLineNumber(vPos)\n );\n }", "get parent() {\n return new Path(this.parentPath);\n }", "function getBranch(payload) {\n\n if ( payload.ref ) {\n // ref example: \"refs/tags/simple-tag\", this will get the last string\n return payload.ref.split(\"/\")[2];\n } else {\n return payload.pull_request.head.ref;\n }\n\n}", "parent() {\n var selection = this.selected.anchorNode;\n // prevent '#text' node as element\n if (selection && selection.nodeType == 3) selection = selection.parentElement;\n\n return selection ? selection : null;\n }", "function getParents (collection, result, callback) {\n if (!collection._parent) return callback(null, result)\n m.Collection.findById(collection._parent, function (err, parentCollection) {\n if (err) console.log(err)\n result.push(parentCollection)\n if (!parentCollection._parent) return callback(null, result)\n return getParents(parentCollection, result, callback)\n })\n}", "parent(root, path) {\n var parentPath = Path.parent(path);\n var p = Node$1.get(root, parentPath);\n\n if (Text.isText(p)) {\n throw new Error(\"Cannot get the parent of path [\".concat(path, \"] because it does not exist in the root.\"));\n }\n\n return p;\n }", "function pruneAndRecenter(min_prob) {\n\tvar path = [];\n\tvar current = global.stableTree.root;\n\tvar next;\n\n\twhile (true) {\n\n\t\t// keep track of current child branch we're searching\n\t\tif (current.child_index != undefined) {\n\t\t\tcurrent.child_index++;\n\t\t} else {\n\t\t\tcurrent.child_index = 0;\n\t\t}\n\n\t\t// recenter when first encountering a terminal node\n\t\tif (current.child_index == 0 && (current.probability > 0 || current.children.length == 0)) {\n\t\t\tcurrent.probability -= min_prob;\t// recenter probability\n\t\t}\n\n\t\t// get next child\n\t\tif (current.child_index < current.children.length) {\n\t\t\tnext = current.children[current.child_index];\n\t\t} else {\n\t\t\tnext = undefined;\n\t\t\tdelete current.child_index;\n\t\t}\n\n\t\tif (next) {\n\t\t\t// move to child\n\t\t\tpath.push(current);\n\t\t\tcurrent = next;\n\t\t} else if (path.length > 0) {\n\t\t\t// if dead leaf node\n\t\t\tif (current.probability <= 0 && current.children.length == 0) {\n\t\t\t\twhile (true) {\n\t\t\t\t\t// backtrack to last terminal node or last node with > 1 children\n\t\t\t\t\tcurrent = path.pop();\n\t\t\t\t\tif (current.probability != 0 || current.children.length > 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// remove child (and thus, dead branch)\n\t\t\t\tcurrent.children.splice(current.child_index, 1);\n\t\t\t\tcurrent.child_index--;\n\t\t\t} else {\n\t\t\t\t// if normal leaf node, backtrack\n\t\t\t\tcurrent = path.pop();\n\t\t\t}\n\t\t} else {\n\t\t\t// if no next child and path empty, break (back at root)\n\t\t\tbreak;\n\t\t}\n\t}\n\t// debug\n\tconsole.log(\"Finished pruning / recentering\");\n}" ]
{ "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!' }, function(notificationId) {}); document.getElementById('delayInMinutes').value = ''; }
[ "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 if (this.signalHandler) this.signalHandler(this.totalSignalCount-1);\n TaskTimer.__forget__(this);\n }\n }\n }", "function cancelAction(email, ref, type) { \n\tvar message = prompt(\"Cancel Ride: Put the reason as to why the ride was cancelled in the text field below; it will be sent to the user. A reason is not required.\", \"\");\n\tif (message != null) {\n\t\tvar user = ref.child(email);\n\t\tuser.once(\"value\", function(snapshot) {\n\t\t\tvar ts = snapshot.val().timestamp\n\t\t\tuser.update({\"endTime\" : \"Cancelled by Dispatcher\", \"message\" : message});\n\t\t\tvar cancelled = firebase.database().ref().child(\"CANCELLED RIDES\");\n\t\t\tcancelled.child(email + \"_\" + ts).set({ \n\t\t\t\temail: snapshot.val().email,\n\t\t\t\tend: snapshot.val().end,\n\t\t\t\tendTime: \"Cancelled by Dispatcher\",\n\t\t\t\teta: snapshot.val().eta,\n\t\t\t\tmessage: message,\n\t\t\t\tnumRiders: snapshot.val().numRiders,\n\t\t\t\tstart: snapshot.val().start,\n\t\t\t\ttime: snapshot.val().time,\n\t\t\t\ttimestamp: ts,\n\t\t\t\twaitTime: snapshot.val().waitTime,\n\t\t\t\tvehicle: snapshot.val().vehicle,\n\t\t\t});\n\t\t\tuser.remove();\n\t\t});\n\t} //else do not cancel\n}", "function stopUpdateAlarm(){\n\tconsole.log(\"[ALARMS] Getting feed update alarm\");\n\tchrome.alarms.clear(\"updateAlarm\");\n\tlistAlarms();\n}", "static recordCancelEvent_() {\n chrome.metricsPrivate.recordUserAction(MetricsUtils.CANCEL_SPEECH_METRIC);\n }", "cancel(time) {\n time = (0, _Defaults.defaultArg)(time, -Infinity);\n const ticks = this.toTicks(time);\n\n this._state.forEachFrom(ticks, event => {\n this.context.transport.clear(event.id);\n });\n\n this._state.cancel(ticks);\n\n return this;\n }", "function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }", "cancel() {\n console.log('Canceling the transaction')\n return this.replace({\n from: this.manager.address,\n to: this.manager.address,\n value: 0,\n })\n }", "cancel () {\n this.close();\n this._reject(new Error('User closed dialog.'));\n }", "function snooze() {\r\n stopAlarm();\r\n alarmTimer = setTimeout(initAlarm, 300000); // 5 * 60 * 1000 = 5 Minutes\r\n}", "function confirmForCancelAppt(patientId, clinicId, doctorId, these) {\n\n $(\"#apptCancelCnfmPopup\").addClass(\"dailog-show\");\n $(\".cancelapp\").off().on('click', function () {\n var retVal = this.id;\n $(\"#apptCancelCnfmPopup\").removeClass(\"dailog-show\");\n if (retVal === \"Yes\") {\n var date = $(these).parent().closest('td').attr('id');\n cancelScheduledAppt(doctorId, clinicId, patientId, date);\n }\n });\n}", "cancel(invitation) {\n axios.delete(`/settings/invitations/${invitation.id}`)\n .then(() => {\n this.$parent.$emit('updateInvitations');\n });\n }", "function cancelChallenge() {\n challengesService.getActiveChallengeByCompetitionByPlayer(vm.competitionId, vm.currentUserPlayer._id).then(function (challenge) {\n if (challenge.data) {\n // Allow the challenger to cancel the challenge\n if (challenge.data.challenger._id === vm.currentUserPlayer._id) {\n challengesService.cancelPyramidChallenge(challenge.data).then(function () {\n vm.hasActiveChallenge = false;\n });\n }\n }\n });\n }", "cancelAutoClose() {\n var button = this.getJQueryObject().find(\".timeout\");\n\n if(this.timeout != null) {\n button.hide();\n clearInterval(this.timeout);\n }\n }", "function cancel() {\n\t\t//i've pressed cancel so don't save changes and tell all clients its open\n\t\t$(document).on('click', '.word-cancel', function () {\n\t\t\tvar id = $(this).data('link_id');\n\t\t\tsocket.emit('cancelword', id);\n\n\t\t\tuiObj.alertsOpen();\n\t\t});\n\n\t\t//response to cancelling the edit\n\t\tsocket.on('cancelword', function (word) {\n\t\t\tvar wordC = $('[data-_id-word=\"' + word._id + '\"]');\n\t\t\tmenu.call(this, word, word.active, wordC, true);\n\t\t\tvar editor = tinymce.get(word._id);\n\t\t\teditor.getBody().setAttribute('contenteditable',false);\n\t\t\teditor.getBody().style.backgroundColor = \"rgba(0,0,0,0.5)\";\n\t\t\tif (word.data === undefined) {\n\t\t\t\teditor.setContent('');\n\t\t\t} else {\n\t\t\t\teditor.setContent(word.data);\n\t\t\t}\n\t\t\tuiObj.removeEdits(wordC);\n\t\t\tuiObj.alertsClose();\n\t\t});\n\t}", "function mentorCancelMeetingRequest() {\n return confirm(\"Are you sure you want to cancel your meeting request with this mentee?. No record at this stage will be kept.\");\n}", "function createAlarm() {\n\n // default delay of 60 seconds\n var userDelay = 60;\n\n if (userInput() != '') {\n userDelay = parseInt(userInput());\n }\n\n var alarmInfo = {\n delayInMinutes: userDelay,\n periodInMinutes: userDelay\n }\n\n chrome.alarms.create(alarmName, alarmInfo);\n chrome.notifications.create('reminder', {\n type: 'basic',\n iconUrl: 'img/icon_128.png',\n title: 'Info:',\n message: 'Die Erinnerungen sind jetzt aktiviert!'\n }, function(notificationId) {});\n }", "function cancelled() {\n fire(\"refresh-cancelled\");\n finish();\n }", "cancel() {\n let parser = this._parser;\n if (parser) {\n this._parser = null;\n // This will call back to onUpdateCheckError with a CANCELLED error\n parser.cancel();\n }\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].collidesWith(player)) {\n player.jump();\n if (platforms[i] instanceof Doodler) {\n\t\t\t\t\t// it's not a platform, but a doodler!\n points += 100;\n platforms.splice(i, 1); // remove from array\n }\n }\n } else {\n\n /* no longer on-screen, delete previous platforms */\n platforms.splice(i, 1);\n\t\t\t/* push new platform */\n var x = noise(player.maxA, frameCount) * width;\n var y = player.maxA + height;\n if (random() < 0.9) {\n\t\t\t\t// 90% chance of being a regular platform\n platforms.push(new Platform(x, y));\n } else {\n if (random() > 0.5) {\n\t\t\t\t\t// 5% chance of being a doodler\n\t\t\t\t\tplatforms.push(new Doodler(x, y, true));\n\t\t\t\t}\n\t\t\t\t// 5% chance of not regenerating\n }\n }\n }\n}", "function createplat(){\n platforms.push(\n {\n x: 0,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 100,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 300,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 550,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 700,\n y: 250,\n width: 270,\n height: 15\n }\n );\n\n }", "function platform_init() {\r\n\tplatform.push(new Platform(0, 400, 400, 0, 0));\r\n\t\tvar plat_num = 0;\r\n\t\tvar plat_y = 400;\r\n\t\tvar plat_x = Math.floor(Math.random()*300);\r\n\t\twhile (plat_num < 10) {\r\n\t\t\tvar next_plat_y = Math.floor(Math.random()*35) + 50;\r\n\t\t\tplat_y -= next_plat_y;\r\n horiz = Math.min(canvas.width - (plat_x + 200), Math.min(plat_x, Math.random() * 300));\r\n if (horiz < 5) {\r\n horiz = 0;\r\n }\r\n\t\t\tplatform.push(new Platform(plat_x, plat_y, 100, horiz, 0));\r\n\t\t\tvar next_plat_x = Math.floor(Math.random()*150);\r\n\t\t\tif(plat_num % 2 === 1)\r\n\t\t\t\tnext_plat_x += 150;\r\n\t\t\tplat_x = next_plat_x;\r\n\t\t\tif (plat_x > 300 || plat_x < 0)\r\n\t\t\t\tplat_x = Math.floor(Math.random()*200) + Math.floor(Math.random()*100);\r\n\t\t\tplat_num++;\r\n\t\t}\r\n}", "function init(game) {\n let createPlatform = platform.create;\n\n ////////////////////////////////////////////////////////////////////////\n // ALL YOUR CODE GOES BELOW HERE ///////////////////////////////////////\n \n /*\n * ground : here, we create a floor. Given the width of of the platform \n * asset, giving it a scaleX and scaleY of 2 will stretch it across the \n * bottom of the game.\n */\n createPlatform(0, game.world.height - 32, 3, 2); // DO NOT DELETE\n\n // example:\n createPlatform(100, 210, 0.6);\n createPlatform(100, 230, 0.6);\n createPlatform(100, 250, 0.6);\n createPlatform(100, 270, 0.6);\n createPlatform(100, 290, 0.6);\n createPlatform(100, 310, 0.6);\n createPlatform(100, 330, 0.6);\n createPlatform(100, 350, 0.6);\n createPlatform(100, 370, 0.6);\n createPlatform(100, 390, 0.6);\n createPlatform(100, 410, 0.6);\n createPlatform(100, 430, 0.6);\n createPlatform(100, 460, 0.6);\n createPlatform(100, 490, 0.6);\n createPlatform(100, 520, 0.6);\n createPlatform(100, 540, 0.6);\n createPlatform(100, 570, 0.9);\n createPlatform(100, 600, 0.6);\n createPlatform(100, 630, 0.6);\n createPlatform(100, 660, 0.6);\n\n createPlatform(300, 210, 0.6);\n createPlatform(300, 230, 0.6);\n createPlatform(300, 250, 0.6);\n createPlatform(300, 270, 0.6);\n createPlatform(300, 290, 0.6);\n createPlatform(300, 310, 0.6);\n createPlatform(300, 330, 0.6);\n createPlatform(300, 350, 0.6);\n createPlatform(300, 370, 0.6);\n createPlatform(300, 390, 0.6);\n createPlatform(300, 410, 0.6);\n createPlatform(300, 430, 0.6);\n createPlatform(300, 460, 0.6);\n createPlatform(300, 490, 0.6);\n createPlatform(300, 520, 0.6);\n createPlatform(300, 540, 0.6);\n createPlatform(300, 570, 0.9);\n createPlatform(300, 600, 0.6);\n createPlatform(300, 630, 0.6);\n createPlatform(300, 660, 0.6);\n\n createPlatform(500, 210, 0.6);\n createPlatform(500, 230, 0.6);\n createPlatform(500, 250, 0.6);\n createPlatform(500, 270, 0.6);\n createPlatform(500, 290, 0.6);\n createPlatform(500, 310, 0.6);\n createPlatform(500, 330, 0.6);\n createPlatform(500, 350, 0.6);\n createPlatform(500, 370, 0.6);\n createPlatform(500, 390, 0.6);\n createPlatform(500, 410, 0.6);\n createPlatform(500, 430, 0.6);\n createPlatform(500, 460, 0.6);\n createPlatform(500, 490, 0.6);\n createPlatform(500, 520, 0.6);\n createPlatform(500, 540, 0.6);\n createPlatform(500, 570, 0.9);\n createPlatform(500, 600, 0.6);\n createPlatform(500, 630, 0.6);\n createPlatform(500, 660, 0.6);\n\n createPlatform(700, 210, 0.6);\n createPlatform(700, 230, 0.6);\n createPlatform(700, 250, 0.6);\n createPlatform(700, 270, 0.6);\n createPlatform(700, 290, 0.6);\n createPlatform(700, 310, 0.6);\n createPlatform(700, 330, 0.6);\n createPlatform(700, 350, 0.6);\n createPlatform(700, 370, 0.6);\n createPlatform(700, 390, 0.6);\n createPlatform(700, 410, 0.6);\n createPlatform(700, 430, 0.6);\n createPlatform(700, 460, 0.6);\n createPlatform(700, 490, 0.6);\n createPlatform(700, 520, 0.6);\n createPlatform(700, 540, 0.6);\n createPlatform(700, 570, 0.9);\n createPlatform(700, 600, 0.6);\n createPlatform(700, 630, 0.6);\n createPlatform(700, 660, 0.6);\n // ALL YOUR CODe GOES ABOVE HERE ///////////////////////////////////////\n ///////////////////////////////////////////////////////////////////////\n }", "function renderplat(){\n for(var i=0; i<platforms.length;i++){\n ctx.fillStyle = platforms[i].color;\n ctx.fillRect(platforms[i].x, platforms[i].y, platforms[i].width, platforms[i].height);\n }\n}", "function renderplat(){\n ctx.fillStyle = \"#8C158E\";\n platforms.forEach((platform) => {\n ctx.fillRect(platform.x, platform.y, platform.width, platform.height);\n })\n}", "function refreshPlatforms(platforms) {\n if(platforms === undefined) return;\n deleteDirSync(\"platforms\");\n\n if(platforms.indexOf(\"a\") !== -1)\n runShell(\"npx ionic cordova platform add android\");\n\n if(platforms.indexOf(\"i\") !== -1)\n if (OS.platform() === \"darwin\") runShell(\"npx ionic cordova platform add ios\");\n else consoleOut(`(set_brand.js) did not add ios-platform on the operating system \"${OS.platform()}\"`);\n}", "function addPlayer() \n{\n\tgbox.addObject({\n\t\tid: 'player_id',\t\t\t// Reference ID\n\t\tgroup: 'player',\t\t\t// Rendering group player belongs to\n\t\ttileset: 'player_tiles',\t// Image set for sprite animation\n\t\t\t\n\t\t// Set collision box for player\n\t\t// TODO: Test, may not need this for toys.platformer.\n\t\t// toys.topview object's default colh value is bottom half of tile,\n\t\t// so character can overlap map features.\n\t\tcolh: gbox.getTiles('player_tiles').tileh,\n\t\t\n\t\t// Run once upon creation, initialize player object\n\t\tinitialize: function() {\n\t\t\t// Initialize the player as a platformer object\n\t\t\t// to access helper methods\n\t\t\ttoys.platformer.initialize(this, {});\n\t\t\t\n\t\t\t// Set default player position\n\t\t\t// TODO: Make default location a constant point\n\t\t\tthis.x = 20;\n\t\t\tthis.y = 20;\n\t\t},\n\t\t\n\t\t// Step function performed during each cycle (*before* rendering)\n\t\tfirst: function() {\n\t\t\t// \"Keys\" methods apply acceleration based on direction pressed.\n\t\t\ttoys.platformer.horizontalKeys(this, { left: 'left', right: 'right' });\n\t\t\t\n\t\t\t// Apply friction to acceleration to prevent crazy physics\n\t\t\ttoys.platformer.handleAccellerations(this);\n\t\t\t\n\t\t\t// Apply forces through physics engine\n\t\t\ttoys.platformer.applyGravity(this);\n\t\t\t\n\t\t\t/*\n\t\t\t * Collision detection\n\t\t\t * Tolerance value creates more organic collision box.\n\t\t\t * TODO: Only check for vertical collision if this.y has changed.\n\t\t\t */\n\t\t\ttoys.platformer.verticalTileCollision(this, map, 'map');\n\t\t\t//toys.platformer.horizontalTileCollision(this, map, 'map', 1);\n\t\t},\n\t\t\n\t\t// Draw the player tile with updated position/properties\n\t\tblit: function() {\n\t\t\tvar blitData = {\n\t\t\t\t\ttileset: this.tileset,\n\t\t\t\t\ttile:\t 0, //this.frame,\n\t\t\t\t\tdx:\t\t this.x,\n\t\t\t\t\tdy:\t\t this.y,\n\t\t\t\t\tfliph:\t this.fliph,\n\t\t\t\t\tflipv:\t this.flipv,\n\t\t\t\t\tcamera:\t this.camera,\n\t\t\t\t\talpha:\t 1.0\n\t\t\t};\n\t\t\tgbox.blitTile(gbox.getBufferContext(), blitData);\n\t\t}\n\t});\n}", "function update() {\n // ================================\n // ==== Update all game clocks ====\n // ================================\n update_timer();\n\n // ==============================\n // ==== Check for collisions ====\n // ==============================\n\tgame.physics.arcade.collide(clams, platforms);\n game.physics.arcade.collide(jellyfishes, platforms);\n game.physics.arcade.collide(patties, platforms);\n game.physics.arcade.collide(player,\n\t\tpatties,\n\t\tcollect_patty,\n\t\tnull,\n\t\tthis);\n game.physics.arcade.overlap(player,\n\t\tjellyfishes,\n\t\thit_jellyfish,\n\t\tnull,\n\t\tthis);\n\tgame.physics.arcade.overlap(player,\n\t\tclams,\n\t\thit_clam,\n\t\tnull,\n\t\tthis);\n game.physics.arcade.overlap(player,\n sharks,\n hit_shark,\n null,\n this);\n\tgame.physics.arcade.overlap(player,\n\t\tbubble_shields,\n\t\thit_shield,\n\t\tnull,\n\t\tthis);\n\t\t\n\t\t\n // ===============================\n // ==== Add & delete entities ====\n // ===============================\n\n if (game.time.time % 4 === 0) {\n var entities = Object.keys(ENTITY_VALUE_MAP);\n for (var i = 0; i < entities.length; i++) {\n set_spawn_rate(entities[i]);\n }\n }\n\n var jelly_rate = fuzz_number(ENTITY_VALUE_MAP['jellyfish'].SPAWN_RATE);\n if (game.time.time % jelly_rate === 0 && altitude > 0) {\n add_grouped('jellyfish');\n }\n\n var patty_rate = fuzz_number(ENTITY_VALUE_MAP['patty'].SPAWN_RATE);\n if (game.time.time % patty_rate === 0 && altitude > 0) {\n \tadd_patty_group();\n }\n\n var shark_rate = fuzz_number(ENTITY_VALUE_MAP['shark'].SPAWN_RATE);\n if (game.time.time % shark_rate === 0 && altitude > 0) {\n add_shark();\n add_clam();\n }\n\n\tvar shield_rate = fuzz_number(ENTITY_VALUE_MAP['shield'].SPAWN_RATE);\n\tif (game.time.time % shield_rate === 0 && altitude > 0) {\n\t\tadd_bubble_shield();\n }\n\n var squid_rate = fuzz_number(ENTITY_VALUE_MAP['squid'].SPAWN_RATE);\n if (altitude % squid_rate === 0 && altitude > 999) {\n add_squid(50 + Math.floor(Math.random() * 650), 600);\n }\n\n var bubble_rate = fuzz_number(ENTITY_VALUE_MAP['bubble'].SPAWN_RATE);\n // bubbles are background objects, no dynamic changing spawn rate\n // (10 + Math.floor(Math.random() * 65))\n if (game.time.time % bubble_rate === 0 && altitude > 0) {\n add_grouped('bubble');\n }\n\n if (DEBUG && game.time.time % 16 === 0) {\n console.log('patty rate ' + ENTITY_VALUE_MAP['patty'].SPAWN_RATE +\n ' ' + patty_rate);\n }\n\n // ==================\n // ===== Physics ====\n // ==================\n\n update_physics();\n\n // ====================\n // ==== Controller ====\n // ====================\n\n var walking = altitude === 0;\n var falling = (speed <= 0 && altitude > 0);\n var swimming = (speed > 0 && altitude > 0); \n\n if (swimming) {\n player.animations.play('swimming');\n } else if (walking) {\n player.animations.play('walking');\n } else if (falling) {\n player.animations.play('falling');\n } else {\n player.animations.stop();\n }\n\n if (cursors.left.isDown) {\n player.body.velocity.x = -PATRICK_VELOCITY_X;\n if (facing_right) {\n facing_right = false; \n player.scale.x *= -1;\n }\n } else if (cursors.right.isDown) {\n player.body.velocity.x = PATRICK_VELOCITY_X;\n if (!facing_right) {\n facing_right = true; \n player.scale.x *= -1;\n }\n } else if (walking) {\n // stand still, no horiz movement, but only if walking!\n player.animations.stop();\n player.frame = 14;\n }\n\n // ===========================\n // ==== Text and counters ====\n // ===========================\n if (game.time.time % 4 === 0) {\n altitude_as_string = numberWithCommas(altitude);\n altitude_text.text = 'Altitude: ' + altitude_as_string;\n\n var energy_percent = Math.floor(\n (energy / ENERGY_CAP) * 100).toString() + \"%\";\n energy_text.text = energy_percent;\n\n if (DEBUG) {\n console.log(\n '<DEBUG>: Speed: ' + speed.toString() +\n ', Energy: ' + energy.toString() + \n ', Altitude: ' + altitude.toString());\n console.log(energy_percent);\n }\n }\n\n energy_bar.width = (energy / ENERGY_CAP) * 212;\n}", "function MovePlatform(game, gameplay, x, y, key, firstY, secondY, gravityDir, sound){\n\tPhaser.Sprite.call(this, game, x, y, key);\n\tgame.add.existing(this); // Adds to display list\n\tthis.zOrder = layerMovePlatform; // Sets z layer for depth sorting\n\tthis.gameplay = gameplay; // Obtains reference to the gameplay state\n\tthis.gameplay.group.add(this); // Adds into group for layer sorting\n\n\t//this.scale.setTo(0.22, 0.11); // Scales the sprite\n\n\tthis.isMoving = false; // Boolean for if the platform is moving\n\n\tthis.lockNoise = game.add.audio(sound); // Adds in the sounds for when the platform is locked\n\n\t// Enable physics\n\tgame.physics.p2.enable(this, debugCollisionsObjects); // Enables physics\n\tthis.body.fixedRotation = true; // Cloud cannot rotate\n\tthis.body.damping = 0.5;\n\tthis.body.dynamic = true; // Makes it dynamic so can be collided with player\n\n\tif(gravityDir === \"down\"){ // If the gravity is down\n\t\tthis.gravDirMultiplier = 1;\n\t}\n\telse if(gravityDir === \"up\"){ // If the gravity is up\n\t\tthis.body.data.gravityScale = -1;\n\t\tthis.gravDirMultiplier = -1;\n\t}\n\telse{\n\t\tconsole.log(\"Invalid gravity direction\"); // In case I make a typo\n\t}\n\n\t// Detects which y coordinate in the movement range is first\n\t// And sets the references accordingly\n\tvar yMult = -this.gravDirMultiplier; //Must multiply by -1 for math to work out\n\tvar minY = yMult*Phaser.Math.min(yMult * firstY, yMult * secondY);\n\tvar maxY = yMult*Phaser.Math.max(yMult * firstY, yMult * secondY);\n\n\tvar minHeight = minY + (this.gravDirMultiplier*this.height); // height of the min limiter platform\n\tthis.min = new MovePlatformLimiter(game, x, minHeight, key); // Creates the limiter body that will be below the platform\n\n\tthis.max = new MovePlatformLimiter(game, x, maxY, key); // Creates the limiter body that will be above the platform\n\n\tthis.leftLimit = new MovePlatformLimiter(game, x-this.width, y, key); // Creates the limiter body that will be to the left of the platform\n\n\tthis.rightLimit = new MovePlatformLimiter(game, x+this.width, y, key); // Creates the limiter body that will be to the right of the platform\n\n\t// Create references to the gameplay collision groups\n\tvar cloudCG = this.gameplay.cloudCollisionGroup;\n\tvar limiterCG = this.gameplay.limiterCollisionGroup;\n\tvar playerCG = this.gameplay.playerCollisionGroup;\n\tvar surrogateCG = this.gameplay.surrogateCollisionGroup;\n\tvar objectCG = this.gameplay.objectCollisionGroup\n\n\t// Sets the collision groups per body\n\tthis.body.setCollisionGroup(cloudCG);\n this.body.collides([limiterCG, playerCG, surrogateCG, objectCG]);\n\n this.min.body.setCollisionGroup(limiterCG);\n this.min.body.collides([cloudCG]);\n\n this.max.body.setCollisionGroup(limiterCG);\n this.max.body.collides([cloudCG]);\n\n this.leftLimit.body.setCollisionGroup(limiterCG);\n this.leftLimit.body.collides([cloudCG]);\n\n this.rightLimit.body.setCollisionGroup(limiterCG);\n this.rightLimit.body.collides([cloudCG]);\n\n //this.body.moveUp(-this.gravDirMultiplier*150);\n}", "function addWorldObjects() {\n //Number of rendered objects\n let numObjects = 60;\n let gap = 6.28 / 60;\n for (let i = 0; i < numObjects; i++) {\n let rnd = Math.random();\n if (rnd <= 0.25) {\n addObject(false, i * gap, true);\n } else if (rnd > 0.25 && rnd <= 0.50) {\n addObject(false, i * gap, false);\n } else {\n addObject(true, i * gap, true);\n addObject(true, i * gap, false);\n }\n\n }\n }", "initPlayers() {\n\n for( var i = 0; i < this.gameConfig.numPlayers; i++ ) {\n this.gameConfig.players.push({\n name : '',\n imgPath : 'img/ninja-odd.png',\n killed : false,\n nameToKill: '',\n word : ''\n })\n }\n\n this.saveGameConfig();\n }", "setup() {\n for (const layer in this.layerRegistry) {\n this.layers.set(`${layerRegistry[layer]}Layer`, this.game.add.group());\n this.game.world.bringToTop(this.layers.get(`${layerRegistry[layer]}Layer`));\n }\n }", "setColliders() {\n this.physics.add.collider(this.player, this.platforms);\n this.physics.add.collider(this.stars, this.platforms);\n this.physics.add.collider(this.bombs, this.platforms);\n this.physics.add.collider(this.player, this.bombs, this.endGame, null, this);\n this.physics.add.overlap(this.player, this.stars, this.collectStar, null, this);\n }", "function applybox(context, phys, platformLevel, platformRadius)\n{\n\tvar objectradius = 135*0.4;\n\tvar restitution = 0.8;\n\t\n\t// bounce on platform\n\tonPlatform = (Math.pow(phys.x - phys.x0, 2) < platformRadius*platformRadius) && (phys.y <= platformLevel+50) ;\n\t\n\tif (phys.y>platformLevel && onPlatform)\n\t\tphys.vy = phys.v0;\n\t\n\t// bounce on all borders of the canvas\n\tif (phys.x < objectradius && phys.vx < 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\n\tif (phys.x > context.canvas.width - objectradius && phys.vx > 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\t\n\tif (phys.y > context.canvas.height - objectradius && phys.vy > 0)\n\t{\n\t\tphys.vx = phys.vx * restitution;\n\t\tphys.vy = -phys.vy * restitution;\n\t}\n\t\n\t// if falling off the platform, add rotation\n\tvar v = Math.sqrt(phys.vx*phys.vx + phys.vy*phys.vy);\n\tvar vr = v/500;\n\tif (!onPlatform)\n\t{\n\t\tif (phys.x > phys.x0)\n\t\t\tphys.vr = vr;\n\t\telse\n\t\t\tphys.vr = -vr;\n\t}\n\t\n\treturn onPlatform;\n}", "function deletePlatform(){\r\n var platforms = svgdoc.getElementById(\"platforms\");\r\n \r\n for (var i = 0; i < platforms.childNodes.length; i++) {\r\n var platform = platforms.childNodes.item(i);\r\n\r\n if(platform.getAttribute(\"delete\") == \"true\") {\r\n platforms.removeChild(platform);\r\n }\r\n }\r\n}", "function addShapes() {\n scene.add(camera);\n scene.add(ambientLight);\n}", "createInteractionZones() {\n this.r3a1_graphics = this.add.graphics({fillStyle: {color: 0xFFFFFF, alpha: 0.0}});\n //this.graphicsTest = this.add.graphics({fillStyle: {color: 0x4F4F4F, alpha: 1.0}});\n //TOP ZONES\n //xpos ypos x y\n this.r3a1_increaseAssets = new Phaser.Geom.Rectangle(425,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseAssets);\n\n this.r3a1_decreaseAssets = new Phaser.Geom.Rectangle(425,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseAssets);\n\n this.r3a1_increaseLiabilities = new Phaser.Geom.Rectangle(525,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseLiabilities);\n\n this.r3a1_decreaseLiabilities = new Phaser.Geom.Rectangle(525,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseLiabilities);\n\n this.r3a1_increaseStock = new Phaser.Geom.Rectangle(625,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseStock);\n\n this.r3a1_decreaseStock = new Phaser.Geom.Rectangle(625,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseStock);\n\n this.r3a1_increaseRevenue = new Phaser.Geom.Rectangle(725,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseRevenue);\n\n this.r3a1_decreaseRevenue = new Phaser.Geom.Rectangle(725,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseRevenue);\n\n this.r3a1_increaseExpenses = new Phaser.Geom.Rectangle(825,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseExpenses);\n\n this.r3a1_decreaseExpenses = new Phaser.Geom.Rectangle(825,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseExpenses);\n\n this.r3a1_increaseDividend = new Phaser.Geom.Rectangle(925,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseDividend);\n\n this.r3a1_decreaseDividend = new Phaser.Geom.Rectangle(925,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseDividend);\n\n //this.r3a1_holeInteract = new Phaser.Geom.Rectangle(1300, 400, 100, 100);\n //this.r3a1_graphics.fillRectShape(this.r3a1_holeInteract);\n\n this.r3a1_exitDoor_zone = new Phaser.Geom.Rectangle(113,320,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_exitDoor_zone);\n }", "SetPlatformData() {}" ]
{ "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*/ $("#password_txt").val($('#re_new_pwd').val()); showGeneralSuccessMsg(messages['login.resetPwdMsg']); }
[ "_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').removeClass(\"error_red_border\");\n $('#re_new_pwd').removeClass(\"error_red_border\");\n /* Used for Disable the button and coming from utility.js */\n disableButton(\"reset_pwd\");\n \n var request = {};\n request.userId = user_auth_obj.userId;\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n request.newPassword = $('#re_new_pwd').val();\n \n var call_user_reset_pwd = new user_reset_pwd(request);\n call_user_reset_pwd.call();\n }\n}", "function passwordResetFormHandler(templateName, continueURL) {\n var resetPasswordToken, passwordemail;\n\n app.getForm('profile').handleAction({\n cancel: function () {\n app.getView({\n ContinueURL: continueURL\n }).render(templateName);\n },\n send: function () {\n var Customer, resettingCustomer, Email;\n Customer = app.getModel('Customer');\n Email = app.getModel('Email');\n var requestForm = Form.get('requestpassword').object.email.htmlValue;\n resettingCustomer = Customer.retrieveCustomerByLogin(requestForm);\n\n if (!empty(resettingCustomer)) {\n resetPasswordToken = resettingCustomer.generatePasswordResetToken();\n\n passwordemail = Email.get('mail/headerresetpasswordemail', resettingCustomer.object.profile.email);\n passwordemail.setFrom('noreply@rapalausa.com');\n passwordemail.setSubject(Resource.msg('email.resetpassword', 'email', null));\n passwordemail.send({\n ResetPasswordToken: resetPasswordToken,\n Customer: resettingCustomer.object.profile.customer\n });\n \n app.getView({\n ErrorCode: null,\n ShowContinue: true,\n ContinueURL: continueURL\n }).render('account/password/requestpasswordreset_confirm');\n } else {\n\n //for security reasons the same message will be shown for a valid reset password request as for a invalid one\n\t app.getView({\n\t ErrorCode: 'notfounderror',\n\t ShowContinue: true,\n\t ContinueURL: continueURL\n\t }).render('account/password/requestpasswordresetdialog');\n }\n },\n error: function () {\n app.getView({\n ErrorCode: 'formnotvalid',\n ContinueURL: continueURL\n }).render(templateName);\n }\n });\n}", "function passwordReset() {\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetForm')\n }).render('account/password/requestpasswordreset');\n}", "function showPWReset(myId) {\r\n if (myId === null || myId < 1) { \r\n return false; \r\n } else {\r\n var myURL = \"PasswordResetForm.php?U=\" + myId;\r\n processAjax (myURL, \"logInMsg\");\r\n setBlockVis(\"logInMsg\", \"block\");\r\n return true;\r\n }\r\n}", "function editPWResponse(request,pw){\n\tvar body = JSON.parse(request.responseText);\n\t//299 is code for incorrect password\n\tif (request.status === 299){\n\t\tif (verboseDebugging){\n\t\t\tconsole.log(\"Password incorrect.\");\n\t\t}\n\t\tvar repromptPassword = \"Password incorrect \" + body.message;\n\t\tvar initCoords = {};\n\t\tinitCoords.xcoord = body.xcoord;\n\t\tinitCoords.ycoord = body.ycoord;\n\t\tinitCoords.pw = pw;\n\t\t//\n\t\tdisplayMessage(repromptPassword,editPWSubmit,removePrompt,true,false,false,pw,initCoords);\n\t}\n\t//else password is confirmed. Note that 242 is success because tile is being edited.\n\telse if (request.status === 224){\n\t\tif (verboseDebugging){\n\t\t\tconsole.log(\"Password correct. Moving to edit.\");\n\t\t}\n\t\tpasswordReprompt = false;\n\t\teditPasswordApproved(body.xcoord,body.ycoord,pw);\n\t}\n}", "function setNewPasswordForm() {\n\n app.getForm('profile').handleAction({\n cancel: function () {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n return;\n },\n send: function () {\n var Customer;\n var Email;\n var passwordChangedMail;\n var resettingCustomer;\n var success;\n\n Customer = app.getModel('Customer');\n Email = app.getModel('Email');\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (!resettingCustomer) {\n response.redirect(URLUtils.https('Account-PasswordReset'));\n }\n\n if (app.getForm('resetpassword.password').value() !== app.getForm('resetpassword.passwordconfirm').value()) {\n app.getForm('resetpassword.passwordconfirm').invalidate();\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n } else {\n\n success = resettingCustomer.resetPasswordByToken(request.httpParameterMap.Token.getStringValue(), app.getForm('resetpassword.password').value());\n if (!success) {\n app.getView({\n ErrorCode: 'formnotvalid',\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n } else {\n passwordChangedMail = Email.get('mail/passwordchangedemail', resettingCustomer.object.profile.email);\n passwordChangedMail.setFrom('noreply@rapalausa.com');\n passwordChangedMail.setSubject(Resource.msg('email.resetpassword', 'email', null));\n passwordChangedMail.send({\n Customer: resettingCustomer.object\n });\n\n app.getView().render('account/password/setnewpassword_confirm');\n }\n }\n }\n });\n}", "function setNewPassword() {\n var Customer, resettingCustomer;\n Customer = app.getModel('Customer');\n\n app.getForm('resetpassword').clear();\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (empty(resettingCustomer)) {\n \tresponse.redirect(URLUtils.https('Login-Show', 'TokenExpired', 'TokenError'));\n } else {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n }\n}", "forgotPassword(req, res) {\n const we = req.we,\n email = req.body.email;\n\n res.locals.emailSend = false;\n res.locals.messages = [];\n res.locals.user = req.body.user;\n\n if (req.method !== 'POST') return res.ok();\n\n if (!res.locals.user) res.locals.user = {};\n res.locals.formAction = '/auth/forgot-password';\n\n if (!email) {\n return res.badRequest('auth.forgot-password.field.email.required');\n }\n\n we.db.models.user\n .findOne({ where: { email: email }})\n .then( (user)=> {\n if (!user) {\n return res.badRequest('auth.forgot-password.user.not-found', {\n email\n });\n }\n\n if (user.blocked) {\n we.log.warn('auth.user.blocked.on.forgotPassword', {\n id: user.id\n });\n return res.badRequest('auth.forgot-password.user.not-found', {\n id: user.id\n });\n }\n\n we.db.models.authtoken\n .create({\n userId: user.id, tokenType: 'resetPassword'\n })\n .nodeify( (err, token)=> {\n if (err) return res.queryError(err);\n\n if (we.plugins['we-plugin-email']) {\n const options = {\n to: user.email\n };\n\n user = user.toJSON();\n\n if (!user.displayName) {\n user.displayName = user.username;\n }\n\n const templateVariables = {\n userId: user.id,\n name: user.username,\n displayName: (user.displayName || user.fullName),\n siteName: we.config.appName,\n siteUrl: we.config.hostname,\n resetPasswordUrl: token.getResetUrl(),\n token: token.token\n };\n\n if (we.systemSettings) {\n if (we.systemSettings.siteName) {\n templateVariables.siteName = we.systemSettings.siteName;\n }\n }\n\n we.email\n .sendEmail('AuthResetPasswordEmail', options, templateVariables, (err , emailResp)=> {\n if (err) {\n we.log.error('Error on send email AuthResetPasswordEmail', {\n err, emailResp\n });\n return res.serverError();\n }\n we.log.verbose('AuthResetPasswordEmail: Email resp:', {\n emailResp\n });\n });\n\n res.locals.emailSend = true\n }\n\n res.addMessage('success', 'auth.forgot-password.email.send');\n res.ok();\n });\n })\n .catch(res.queryError)\n }", "function confirmPasswordChangeAction(req, res, next) {\n\n Promise.resolve(passwordChangeVerifyTokenController.verifyPasswordChangeToken(req, res, next))\n .then(function (dataObj) {\n if (dataObj) {\n //if the confirmation status is 200, password change action is verified successfully and redirect the user to the password change page\n //if the confirmation status is 410 i.e token expired, redirect the user to the token expired page\n //if the confirmation status is 404 i.e token not found, redirect the user to the page not found page\n // var redirectUrl = \"\";\n // if (req.app.get(\"env\") == \"production\")\n // redirectUrl = \"/admin/login\";\n // else\n // redirectUrl = \"/login\";\n\n switch (dataObj.status.toString()) {\n case HTTPStatus.OK.toString():\n res.json({\n status: true,\n userId: dataObj.data,\n accessToken: req.params.accessToken\n });\n // res.render('pages/password-reset', {\n // userId: dataObj.data,\n // accessToken: req.params.passwordChangeToken,\n // redirectUrl: redirectUrl,\n // layout: \"plain-layout\"\n // });\n break;\n case HTTPStatus.NOT_FOUND.toString():\n res.json({\n status: false,\n message: \"Token not found!!!\"\n });\n break;\n case HTTPStatus.GONE.toString():\n res.json({\n status: false,\n message: \"The link has already expired!\"\n });\n break;\n\n }\n } else {\n res.redirect('/404');\n }\n })\n .catch(function (err) {\n return next(err);\n });\n }", "async function resendToken(req, res, next) {\n const { email, phone, password } = req.body;\n const resetUrl = `${req.protocol}://${req.get(\n \"host\"\n )}/api/systemUsers/resetPassword/`;\n const user = new SystemUser();\n await user.setPassword(password);\n const sent = await createAndSendToken({\n type: \"password\",\n email,\n phone,\n Model: SystemUser,\n tokenLength: 16,\n sendBy: \"mail\",\n resetUrl,\n extraData: user.password\n });\n if (sent) {\n return res.status(200).json({\n message: `A verification email has been sent .`\n });\n }\n return res.status(400).json({\n message: \"there is no user with this info\"\n });\n}", "function passwordResetDialog() {\n // @FIXME reimplement using dialogify\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetDialogForm')\n }).render('account/password/requestpasswordresetdialog');\n}", "async handleGeneratePasswordResetCode (req, res) {\n const self = this;\n const userId = req.decoded.userId\n const password = req.body.password;\n\n let baseUser;\n let code;\n let email;\n\n try {\n baseUser = await self.models.BaseUser.findOne({ where: { user_id: userId }});\n email = baseUser.user_email;\n\n try {\n // Verify that the password is correct.\n await self.models.BaseUser.prototype.checkPassword(email, password)\n }\n\n catch (err) {\n return res.status(400).json({ message: 'Password doesnt match.' })\n }\n\n self.Crypto.randomBytes(20, (err, buf) => {\n if (err) return res.status(500).json({err: err.toString() })\n code = buf.toString('hex');\n self.Redis.addPasswordResetCode(email, code);\n return res.status(200).json({ code: code });\n })\n }\n\n catch (err) {\n console.log(err);\n return res.status(500).json({\n message: 'Could not generate a password reset code'\n })\n }\n }", "function update_success_response_function(response)\n {\n show_notification(\"msg_holder\", \"success\", \"Success:\", \"Admin updated successfully\");\n fade_out_loader_and_fade_in_form(\"loader\", \"updateform\"); \n }", "function forgotPassword(myUserName) {\r\n if (myUserName) { \r\n var myURL = \"PasswordHintEmailer.php?U=\" + myUserName;\r\n processAjax (myURL, \"logIn\");\r\n setBlockVis(\"logIn\", \"block\");\r\n return true;\r\n } else {\r\n alert(\"Please enter your E-mail address and click the link again.\");\r\n return false; \r\n }\r\n}", "function getSellerPassSuccess(responseText){\n /*\n EDIT HERE!\n */\n}", "function postUpdatePassword(req, res) {\r\n\tif (req.session.uid) {\r\n\t\tvar query = \"UPDATE Users SET password=? WHERE uid=?\";\r\n\t\tdatabase.query(req, res, query, [req.body.password, req.session.uid], ajaxSimplePostCbFcn);\r\n\t}\r\n}", "function add_admin_success_response_function(response)\n {\n show_notification(\"msg_holder\", \"success\", \"Success:\", \"Admin added successfully\");\n fade_out_loader_and_fade_in_form(\"loader\", \"form\"); \n $('#form')[0].reset();\n }", "function PasswordResetConfirmController($scope, $location, $auth, $stateParams, RestFul) {\n $scope.resetpassConfirmForm = function() {\n if ($scope.resetpass_confirm_form.$valid) {\n $scope.resetpassLoading = true;\n RestFul.error(\n {\n 'action': 'Auth:AccountRetrieveConfirm',\n 'params': {\n 'identity': $stateParams.identity,\n 'password': $scope.resetpassPassword,\n }\n },\n function(response) {\n if (!response) { return; };\n if (response.hasOwnProperty('message')) {\n $scope.resetpassSuccess = true;\n } else if (response.hasOwnProperty('warning')) {\n if (response.inner_code === 101) {\n $scope.resetpassError = \"凭证已过期, 请重新发送验证邮件.\";\n } else if (response.inner_code === 102) {\n $scope.resetpassError = \"不是有效的凭证, 请重新发送验证邮件.\";\n }\n }\n $scope.resetpassLoading = false;\n }\n )\n } else {\n $scope.resetpass_confirm_form.submitted = true;\n }\n }\n}" ]
{ "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*/\n }\n />\n );\n}", "redirectToLogin () {\n window.location.assign('/login')\n }", "loginWithRedirect () {\n return this.oidcClient.signinRedirect()\n }", "function ProtectedClient() {\n const [user, setUser] = useState(null);\n const router = useRouter();\n useEffect(() => {\n Auth.currentAuthenticatedUser()\n .then((user) => setUser(user))\n // if there is no authenticated user, redirect to profile page\n .catch(() => router.push(\"/profile\"));\n }, []);\n if (!user) return null;\n return <h1>Hello {user.username} from client route!</h1>;\n}", "renderLoginView(req, res) {\n if (req.session.loggedIn) return res.redirect('/');\n res.render('pages/login.ejs', { loginUrl: AuthServices.getOauthUrl() });\n }", "componentDidUpdate() {\n if (!this.props.user.is_authenticated)\n this.props.history.push(\"/login\");\n }", "function isNOTLoggedIn(req, res, next) {\n if (!req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "requireAuth(req, res, next) {\n if (!req.session.userId) {\n return res.redirect('/signin');\n }\n next();\n }", "function prevent(req, res, next) {\n if(!req.isAuthenticated()){\n return next();\n }\n console.log(\"Athenticated user\");\n res.redirect(\"/userDashboard\");\n}", "render(){\n\n if(this.state.isLoggedIn){\n return(\n <Router>\n <div>\n <Navigation isLoggedIn={this.state.isLoggedIn} isAuthenicated={this.isAuthenicated.bind(this)}/>\n <Switch>\n <Route exact path=\"/\" component={Home} />\n\n <Route exact path=\"/home\" component={Home} />\n\n <Route exact path=\"/about\" component={About} />\n\n <Route exact path=\"/account\" component={Account} isLoggedIn={this.state.isLoggedIn} />\n\n <Route exact path=\"/search\" component={Search} />\n\n <Route component={NoMatch} />\n\n </Switch>\n </div>\n </Router>\n )\n }\n else {\n return(\n <Router>\n <div>\n <Navigation isLoggedIn={this.state.isLoggedIn} isAuthenicated={this.isAuthenicated.bind(this)}/>\n <Switch>\n <Route exact path=\"/\" component={Home} />\n\n <Route exact path=\"/home\" component={Home} />\n\n <Route exact path=\"/about\" component={About} />\n\n <Route exact path=\"/search\" component={Search} />\n\n <Route exact path=\"/account\" component={Home} />\n\n <Route component={NoMatch} />\n\n </Switch>\n </div>\n </Router>\n )\n }\n }", "getRedirectForEmptyInterval() {\n const routeInterval = this.intervalRouteParam;\n if (routeInterval === '_' && this.relevantLoaded) {\n const interval = this.cgpStore.relevantInterval.interval;\n return <Redirect to={getPageUrl(interval)} />;\n }\n return null;\n }", "function redirect() {\r\n if (document.location.pathname.endsWith(\"/admin/index.html\")) {\r\n document.body.innerHTML = '<h2 class=\"w3-center\">Login Required</h2><p class=\"w3-center\">If not redirected, please click <a href=\"' +\r\n cognitoURL + document.location.href.split(\"?\")[0] + '\">here</a> to go to the login page</p>'\r\n window.location.href = cognitoURL + document.location.href.split(\"#\")[0];\r\n }\r\n else {\r\n window.location.href = document.location.origin + \"/admin/index.html\";\r\n }\r\n}", "async handleRedirectCallback () {\n this.loading = true\n try {\n this.user = await this.oidcClient.signinRedirectCallback()\n this.isAuthenticated = true\n } catch (e) {\n this.isAuthenticated = false\n this.error = e\n } finally {\n this.loading = false\n }\n }", "function redirectAfterLogin() {\n\n var identity = getAuthenticatedIdentity();\n\n if (!identity) {\n spAppError.add('Attempted redirect after signed in');\n\n } else {\n\n if (redirectState && redirectState.toParams.tenant.toLowerCase() === identity.tenant.toLowerCase()) {\n $state.go(redirectState.toState.name, redirectState.toParams);\n } else {\n $state.go('home', { tenant: identity.tenant });\n }\n\n }\n }", "renderContent() {\n switch (this.props.authUser) {\n // when the login status is still pending return nothing\n case null:\n return null;\n // when the user is not logged in, show them a link to login\n case false:\n return <MenuLoggedOut />;\n // when the user is logged in, show them a link to logout\n default:\n return <MenuLoggedIn />;\n }\n }", "function isLoggedOut (req, res, next) {\n if (req.isUnauthenticated()) {\n return next()\n }\n\n res.redirect('/')\n}", "rerouteIfPossible() {\n if (Meteor.user() && Meteor.user().username == this.username)\n Router.go(\"myprofileHead\");\n }", "initializeMiddleware() {\n if (this.hasInitialized) throw new Error('authenticated view middleware already initialized');\n this.hasInitialized = true;\n\n const {\n htmlDirectory,\n htmlFilename,\n } = this.configuration;\n\n const trshcmpctrClientRouter = express.Router();\n\n trshcmpctrClientRouter.get('/', [\n handleRenderAuthenticated.bind(null, htmlDirectory, htmlFilename),\n // Redirect to login if not authenticated\n handleRedirect.bind(null, '/login')\n ]);\n\n // Serve application static assets\n trshcmpctrClientRouter.use(express.static(htmlDirectory));\n trshcmpctrClientRouter.use(handleError);\n\n this.router = trshcmpctrClientRouter;\n }", "function isLoggedIn(request, response, next) {\n if(request.isAuthenticated()) {\n console.log('user is authenticated');\n next();\n } else {\n console.log('not authenticated');\n response.redirect('/');\n }\n }" ]
{ "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 prettyPrint();\n });\n crumbs(section, article);\n $('a.dropdown-toggle').each(function() {\n if ($(this).text() == section) {\n $(this).parent().addClass(\"active\");\n } else {\n $(this).parent().removeClass(\"active\");\n }\n });\n}", "function addSection(id)\n{\n current_template_index=0;\n\n var sectionID = \"section-\"+current_section_index;\n\n showSidebarBrowser();\n $(\".browser-menu-item\").each(function(){\n $(this).prop(\"disabled\", false);\n });\n $(\".sidebar-browser\").attr(\"id\", sectionID);\n $(\".sidebar-browser\").data(\"template-index\", current_template_index);\n\n //html for sidebar section input\n var sectionHtml =\n '<div class=\"sidebar-item sidebar-section\"'+\n 'id=\"'+sectionID+'\">' +\n getSidebarButtonHtml(sectionID) +\n\n '<button class=\"sidebar-btn glyphicon glyphicon-remove remove-section-btn\"'+ //remove section btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '<span id=\"sidebar-title-section-'+ current_section_index +'\">Section Name</span>'+\n '<button class=\"sidebar-btn fa fa-toggle-on toggle-linebreak\"'+ //toggle line break btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '</div>';\n\n current_section_index+=1;\n\n\n $(\".section-list\").append(sectionHtml);\n\n var sectionHtml = '<div class=\"section\" id=\"'+sectionID+'-html\"></div>';\n $(\"#section-container\").append(sectionHtml);\n}", "function addnewsection() {\n sectionNumber ++;\n\n //=======> Create Anther section\n let addSection = document.createElement('section');\n addSection.innerHTML = `\n <section id=\"section${sectionNumber}\" class=\"your-active-class\">\n <div class=\"landing__container\">\n <h2 id=\"se_${sectionNumber}\">Section ${sectionNumber}</h2>\n <p id=\"getActive_${sectionNumber}\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>\n </div>\n </section>`;\n mainSection.appendChild(addSection);\n\n //=======> Create Anther item in navbar\n let addli = document.createElement('li');\n addli.innerHTML = `<li ><a id=\"li_${sectionNumber}\" onclick=\"scroll_to('section${sectionNumber}')\">Section ${sectionNumber}</a></li>`;\n mynavbar.appendChild(addli);\n}", "function showModifyMemberBenefits()\n{\n\t$('#statusMsg').append(\"\");\n\t$('#contentSection').load('scriptFiles/selectMemberBenefits.php');\n}", "function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}", "function addPersonalData() {\r\n var sel = \"#personaldata .section-content\";\r\n $(sel).append(\"<div class='sub-section'></div>\");\r\n sel = sel + \" .sub-section:last\";\r\n \r\n var firstName = $(this).find(\"firstName\").text();\r\n var lastName = $(this).find(\"lastName\").text();\r\n addField(sel, \"Full name:\", firstName + \" \" + lastName);\r\n \r\n var address = $(this).find(\"address\").text();\r\n addField(sel, \"Address:\", address);\r\n \r\n var mobile = $(this).find(\"mobile\").text();\r\n addField(sel, \"Mobile:\", mobile);\r\n \r\n var landline = $(this).find(\"landline\").text();\r\n addField(sel, \"Landline:\", landline);\r\n \r\n var email = $(this).find(\"email\").text();\r\n addField(sel, \"E-Mail:\", email);\r\n \r\n var dob = $.format.date($(this).find(\"dateOfBirth\").text(), \"dd.MM.yyyy\");\r\n addField(sel, \"Date of birth\", dob);\r\n}", "appendToCurrent(toAppend) {\n this.currentSectionContent += toAppend +\"\\n\";\n }", "function addQuizForm() {\n $('main').find('fieldset').html(loadQuizQuestion)}", "function ready_content() {\n app.param.generate.addClass('ready');\n $('.generate-container .thumb').html('<i class=\"fa fa-check fa-2x\" aria-hidden=\"true\"></i>');\n (!app.param.checkbox.prop('checked') ? media = 'Movie' : media = '<br>TV Show');\n $('.generate-container .header').html('See Random ' + media + ' <i class=\"fa fa-angle-right\" aria-hidden=\"true\"></i>');\n\n app.param.generate.on('click', function() {\n if ($(this).hasClass('ready')) {\n show_content();\n $('.container').addClass('active');\n app.param.generate.hide();\n $('.switch-container').hide();\n }\n });\n }", "function changeLecturerContent(event, tab){\n document.getElementById('profile').style.display = 'none';\n if (tab == \"Profile\") {\n //TODO: Pass the current user to the function\n editUserInfo(\"lecturerContent\");\n\n } else if(tab == \"Student\"){\n \n } else if(tab == \"Evaluation\"){\n \n } else if(tab == \"Message\"){\n \n } else if(tab == \"References\"){\n\t\t\n\t\tdocument.getElementById('lecturerContent').innerHTML=template_references(); \n\t\n } else if(tab == \"Editing\"){\n \n } else if(tab == \"New\"){\n \n }\n}", "function createSelectedCashOptionSubsection(jsonType) {\n\t$(\"#optionsListContainer\").hide();\n\t$(\"#cashInfoTxt\").hide();\n\t$(\"#helpCash\").hide();\n\tjsonType = jsonType.trim();\n\tif (jsonTypeConstant.PRECASH == jsonType) {\n\t\t$(\"#cashPaymentOptionBox1\").show();\n\t\t$(\"#cashPaymentOptionBox1 #cashSelectedFundingSourceImage\")\n\t\t\t\t.attr(\"src\", formatMessage(messages[\"checkout.image_fundingSource_URL\"], getImageNameByJsonType(jsonType)));\n\t\tclearFieldsOnBack('pinSectionPreCash', 'amountOfCashEvolve', 'blueBoxCnt1');\n\t\t$(\"#pinOfCashEvolve1\").val(messages[\"checkout.Precash.FirstBox\"]);\n\t} else if (jsonTypeConstant.BLACKHAWK === jsonType) {\n\t\t$(\"#cashPaymentOptionBox2\").show();\n\t\t$(\"#cashPaymentOptionBox2 #cashSelectedFundingSourceImage\")\n\t\t\t\t.attr(\"src\", formatMessage(messages[\"checkout.image_fundingSource_URL\"], getImageNameByJsonType(jsonType)));\n\t\tclearFieldsOnBack('pinSectionBlackhawk', 'amountOfCashReloadit', 'blueBoxCnt2');\n\t} else if (jsonTypeConstant.INCOMM == jsonType) {\n\t\t$(\"#cashPaymentOptionBox3\").show();\n\t\t$(\"#cashPaymentOptionBox3 #cashSelectedFundingSourceImage\")\n\t\t\t\t.attr(\"src\", formatMessage(messages[\"checkout.image_fundingSource_URL\"], getImageNameByJsonType(jsonType)));\n\t\tclearFieldsOnBack('pinSectionVanilla', 'amountOfCashVanilla', 'blueBoxCnt3');\n\t}\n\t$(\"#newSelectOption\").hide();\n\t$(\"#opsList\").hide();\n\t$(\"#optionsListContainer\").hide();\n\t$(\"#historyFundingSources\").hide();\n\t$(\"#cashSummaryTotalArea\").hide();\n\trunTimerEnableSaveButton();\n}", "function renderSections(){\n\tlet searchURL = `/sections/?campus=${$('.campuses option:selected').val().toLowerCase()}`;\n\tsearchURL = searchURL+`&subject=${$('.subject option:selected').val().toLowerCase()}`;\n\tsearchURL = searchURL+`&coursenumber=${$('.coursenumber option:selected').text()}`;\n\t$.get(searchURL, function(data){\n\t\t$('.search-result-list').empty();\n\t\tdata.sections.map((sec) => {\n\t\t\tconst singleData = sec;\n\t\t\tappendDataToList(singleData, '.search-result-list')\n\t\t\tremoveListFromSearchResult();\n\t\t\tsortList('.search-result-list');\n\t\t})\n\t});\n}", "function loadEditForm(button){\n// path = location.pathname.replace(/products\\/[\\S]+/,'contents/edit_dispatch/'+$('#ContentEditDispatchForm').attr('content_id'));\n var id = $(button).attr('content_id');\n var path = $('#ContentEditDispatchForm').attr('action') + '/' + id;\n// alert(path);\n button.html('Cancel');\n $('.formContent'+id).html('<p>Loading...</p>');\n $('.formContent'+id).append().load(path,\n {collection:$('.related').attr('collection').match(/[\\d]+/),slug:button.attr('slug')},\n function(){\n toggleFieldsets();\n// enableSubmit();\n });\n// toggleFieldsets();\n }", "function sectionOn() { }", "function generateStartPage() {\n $('.js-main').html(\n `<section id=\"start\">\n <div class=\"page\">\n <p>\n Identify as many creatures by their descriptions as you can!\n </p>\n <div id=\"start-button\">\n <button id=\"js-start\">Begin Quiz</button>\n </div>\n </div>\n </section>`)\n //console.log('generateStartPage ran')\n}", "function setSectionHeader(header) {\r\n\tdocument.getElementById('section-header').innerHTML = header;\r\n}", "function loadSpendingEditPage (data) {\n mainView.router.loadContent(\n '<!-- Top Navbar-->\\n' + \n '<div class=\"navbar\">\\n' + \n ' <div class=\"navbar-inner\">\\n' + \n ' <div class=\"left\"><a href=\"#\" class=\"back link\"> <i class=\"icon icon-back\"></i><span>Back</span></a></div>\\n' + \n ' <div class=\"center sliding\">Edit Spending</div>\\n' + \n ' <div class=\"right\">\\n' + \n ' <a href=\"#\" class=\"link icon-only open-panel\"> <i class=\"icon icon-bars\"></i></a>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n '</div>\\n' + \n '<div class=\"pages\">\\n' + \n ' <!-- Page, data-page contains page name-->\\n' + \n ' <div data-page=\"spendingAdd\" class=\"page\">\\n' + \n ' <!-- Scrollable page content-->\\n' + \n ' <div class=\"page-content\">\\n' + \n ' <div class=\"content-block\">\\n' + \n ' <div class=\"list-block\">\\n' + \n ' <ul>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Spending date\" readonly id=\"spending_date\" value=\"'+data.spending_date+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Name\" id=\"name\" value=\"'+data.name+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Brand\" id=\"brand\" value=\"'+data.brand+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Where do you buy?\" id=\"location\" value=\"'+data.location+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Description\" id=\"descr\" value=\"'+data.descr+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"tel\" placeholder=\"How much?\" onkeypress=\"return isNumberKey(event);\" onkeyup=\"this.value=numberWithCommas(this.value);\" id=\"spent\" value=\"'+data.spent+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' </ul>\\n' + \n ' </div>\\n' + \n ' <div class=\"row\">\\n' + \n ' <div class=\"col-50\">\\n' + \n ' <a href=\"#\" class=\"button button-big button-fill color-gray\" style=\"background-color:red;\" onclick=\"spendingDel('+data.id+');\">Delete</a>\\n' + \n ' </div>\\n' + \n ' <div class=\"col-50\">\\n' + \n ' <a href=\"#\" class=\"button button-big button-fill color-gray\" style=\"background-color:grey;\" onclick=\"spendingEdit('+data.id+');\">Edit</a>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n '</div>\\n'\n );\n return;\n}", "#updateControlsContent() {\n var additionalControlsID = '#'+this.serverKey+'_additionalControls';\n var queuedCommands = '#'+this.serverKey+'_queuedCommands';\n var unqueuedCommands = '#'+this.serverKey+'_unqueuedCommands';\n\n var fill = '<li style=\"display: none;\">Additional Controls</li>'+$(queuedCommands).html()+$(unqueuedCommands).html();\n \n $(additionalControlsID).html(fill);\n }" ]
{ "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 {!HTMLScriptElement} */ ( document.createElement('script')); gtagScriptElement.async = true; // Key for the formatted params below: // 'id': the stream id for the GA4 analytics property. The gtag script // element must only be created once, and only the ID of the primary // stream is appended when creating the src for that element. // Additional streams are initialized via the function call // `window[GTAG]('config', ga4Id...` // 'l': the namespaced dataLayer used to separate codelabs related GA4 // data from other data layers that may exist on a site or page. safeScriptEl.setSrc( gtagScriptElement, TrustedResourceUrl.formatWithParams( Const.from('//www.googletagmanager.com/gtag/js'), {}, {'id': this.ga4Id_, 'l': CODELAB_DATA_LAYER})); firstScriptElement.parentNode.insertBefore( gtagScriptElement, firstScriptElement); window[GTAG] = function() { window[CODELAB_DATA_LAYER].push(arguments); }; window[GTAG]('js', new Date(Date.now())); // Set send_page_view to false. We send pageviews manually. window[GTAG]('config', this.ga4Id_, {send_page_view: false}); }
[ "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));\n\n (function load(src, listen) {\n /** @type {Node|Element} */\n var head = document.getElementsByTagName('HEAD')[0];\n\n /** @type {Node|Element} */\n var script = document.createElement('SCRIPT');\n script.type = 'text/javascript';\n script.src = src;\n\n if(listen) {\n script.onload = function() {\n load(JSAPI_VIS_URL + google.visualization.Version + '/' + google.visualization.JSHash + '/format+en,default,' + JSAPI_MODULES.modules[0].packages.toString() + '.I.js', false);\n }\n }\n\n head.appendChild(script);\n })(src, true);\n }\n }", "setTrackingID() {\n dataLayer.push({ ga_tracking_id: window.fatherlyDataLayer.ga_tracking_id });\n ga('create', window.fatherlyDataLayer.ga_tracking_id, 'auto');\n }", "function initAdData () {\r\n\tvar config = {\r\n\t\t\t\"dfpTemplateType\" \t\t: \"headerOnly\",\r\n\t\t\t\"dfpSecondLevelAdUnit\"\t: '/news',\r\n\t\t\t\"lazyAdStartPosition\"\t: 0,\r\n\t\t\t\"keywords\"\t\t\t\t: 'animal-house',\r\n\t\t\t\"tag\"\t\t\t\t\t: \"animal-house\"\r\n\t},\r\n\tads;\r\n\t//strip trailing comma\r\n\tconfig.keywords = config.keywords.replace(/(^\\s*,)|(,\\s*$)/g, '');\r\n\t//External Scripts File\r\n\tif (typeof __gh__externalApp != \"undefined\") {\r\n\t\tconfig \t\t= __gh__externalApp.config.ads;\r\n\t}\r\n\t//Exit function if ads were not set up - __gh__externalApp.config\r\n\tif (!config) { return; }\r\n\t//Set up global variables\r\n __gh__coreData.globalVariables.ads \t\t\t\t\t= __gh__coreData.globalVariables.ads || {};\r\n\t__gh__coreData.globalVariables.ads.dfpTemplateType \t= config.dfpTemplateType;\r\n\t__gh__coreData.globalVariables.ads.dfpSecondLevel \t= config.dfpSecondLevelAdUnit;\r\n\t__gh__coreData.globalVariables.ads.keywords \t\t= config.keywords;\r\n\t__gh__coreData.globalVariables.ads.lazyStart \t\t= config.lazyAdStartPosition;\r\n\tif (config.dfpTemplateType == \"search\") {\r\n\t\t__gh__webApp.ads.search.init();\r\n\t}\r\n\tif (config.dfpSecondLevelAdUnit == \"/contests\") {\r\n\t\t__gh__coreData.globalVariables.ads.dfpSecondLevel = urlCleanUp(__gh__coreData.globalVariables.ads.dfpSecondLevel);\r\n\t}\r\n\tif (config.tag == \"eedition\") {\r\n\t\tfooterOnlySlots.base.keyvalues.platform = 'eEdition';\r\n\t}\r\n\tfunction urlCleanUp(url) {\r\n\t //var url = 'subdomain.domain.com/file.php?id=1',\r\n\t\tvar a \t\t= document.createElement('a');\r\n\t \t\ta.href \t= url;\r\n\t\treturn a.pathname + a.search;\r\n\t}\r\n}", "function setNamespace() {\n var namespace = _scriptTag.getAttribute('data-namespace');\n if (namespace) {\n if (constants.NAMESPACE_REGEX_VALIDATION.test(namespace)) {\n _config.namespace = namespace;\n } else {\n throw new Error(Errors.INVALID_NAMESPACE);\n }\n } else {\n _config.namespace = constants.DEFAULT_NAMESPACE;\n }\n}", "function createGlobalScript(axios$$1, identifier, request) {\n return restAuthPost(axios$$1, 'instance/microservice/' + identifier + '/scripting/scripts/' + identifier, request);\n }", "function init() {\r\n myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v2.0');\r\n scope = 'https://www.google.com/analytics/feeds';\r\n var button = document.getElementById('authButton');\r\n \r\n // Add a click handler to the Authentication button.\r\n button.onclick = function() {\r\n // Test if the user is not authenticated.\r\n if (!google.accounts.user.checkLogin(scope)) {\r\n // Authenticate the user.\r\n google.accounts.user.login(scope);\r\n } else {\r\n // Log the user out.\r\n google.accounts.user.logout();\r\n getStatus();\r\n }\r\n }\r\n getStatus();\r\n }", "function onDomReady () {\n console.log('DOM loaded');\n\n // assuming the initAddLiveLogging and initDevicesSelects\n // are exposed via ADLT namespace.\n // (check shared-assets/scripts.js)\n ADLT.initAddLiveLogging();\n ADLT.initDevicesSelects();\n // Initializes the AddLive SDK.\n initializeAddLive();\n }", "init(){\n\t\tif( this.packagename ){\n\t\t\tthis.componentname = this.packagename.replace(/[\\/\\.]/g,'_'); // id should not have dot\n\t\t}else{\n\t\t\tthis.componentname = this.constructor.name;\n\t\t}\n\t\tthis.componentId = this.componentname + '_' + this.component_serial;\n\t\tComponentStack.set(this.componentId,this);\n\t\t\n\t\tthis.view.id = this.componentId;\n\t}", "function init() {\n\n // reset any previous data\n displayReset();\n\n // read in samples from JSON file\n d3.json(\"data/samples.json\").then((data => {\n\n\n // ********** Dropdown Menu ************// \n\n // Iterate over each name in the names array to populate dropdowns with IDs\n data.names.forEach((name => {\n var option = idSelect.append(\"option\");\n option.text(name);\n })); //end of forEach loop\n\n // get the first ID from the list as a default value for chart\n var initId = idSelect.property(\"value\")\n\n // plot charts with initial ID\n displayCharts(initId);\n\n }));\n }", "function initAnalytics() {\n\tvar gaID = \"UA-32832674-1\"\t\t//capital tours account\n\twindow.plugins.analytics.start(gaID);\n\tanalytics = window.plugins.analytics;\n\t\n\tinitPagetracker();\n}", "function exoclick_videoslide_load() {\r\n var ga = document.createElement('script'); \r\n ga.type = 'text/javascript'; \r\n ga.src = 'https://a.exdynsrv.com/video-slider.js';\r\n ga.onload(exoclick_videoslide_init);\r\n var s = document.getElementsByTagName('body')[0]; \r\n s.insertBefore(ga, s.firstChild);\r\n}", "function initGameArea() {\n\t\tgameArea = document.createElement('div');\n\t\tgameArea.setAttribute(\"id\", domContainerID);\n\t}", "addGoogleAnalytics () {\n (function (i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r;\n i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments);\n }, i[r].l = 1 * new Date();\n a = s.createElement(o),\n m = s.getElementsByTagName(o)[0];\n a.async = 1;\n a.src = g;\n m.parentNode.insertBefore(a, m);\n })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');\n ga('create', `${this.opts.trackingCode}`, 'auto');\n }", "function loadDSDK() {\n var channelId = bidReq.params.video.channel_id;\n adLoader.loadScript('//js.spotx.tv/directsdk/v1/' + channelId + '.js', initDSDK, true);\n }", "function onVPAIDLoad()\n { \n lkqdVPAID.subscribe(function() { lkqdVPAID.startAd(); }, 'AdLoaded');\n }", "function init() {\n\t\tid = utilities.UUID('toastify');\n\t\tvar root = document.querySelector(settings.root);\n\t\tvar toastifyEl = document.createElement('div');\n\t\t// Sets attributes and classes of toastify element.\n\t\ttoastifyEl.setAttribute('id', id);\n\t\ttoastifyEl.classList.add('toastify');\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.horizontal);\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.vertical);\n\t\troot.appendChild(toastifyEl);\n\t}", "function init() {\n loadName();\n}", "function startYandexSdk() {\n (function(d) {\n var t = d.getElementsByTagName('script')[0];\n var s = d.createElement('script');\n s.src = 'https://yandex.ru/games/sdk/v2';\n s.async = true;\n t.parentNode.insertBefore(s, t);\n s.onload = initSDK;\n })(document);\n}", "init() {\n var taxid, i, svgClass;\n\n var ideo = this;\n\n var t0 = new Date().getTime();\n\n var bandsArray = [],\n numBandDataResponses = 0,\n resolution = this.config.resolution,\n accession;\n\n var promise = new Promise(function(resolve) {\n ideo.getTaxids(resolve);\n });\n\n promise.then(function(taxids) {\n taxid = taxids[0];\n ideo.config.taxid = taxid;\n ideo.config.taxids = taxids;\n\n var assemblies,\n bandFileName;\n\n var bandDataFileNames = {\n 9606: '',\n 10090: ''\n };\n\n for (i = 0; i < taxids.length; i++) {\n taxid = String(taxids[i]);\n\n if (!ideo.config.assembly) {\n ideo.config.assembly = 'default';\n }\n assemblies = ideo.organisms[taxid].assemblies;\n accession = assemblies[ideo.config.assembly];\n\n bandFileName = [];\n bandFileName.push(\n Ideogram.slugify(ideo.organisms[taxid].scientificName)\n );\n if (accession !== assemblies.default) {\n bandFileName.push(accession);\n }\n if (\n taxid === '9606' &&\n (accession !== assemblies.default || resolution !== 850)\n ) {\n bandFileName.push(resolution);\n }\n bandFileName = bandFileName.join('-') + '.js';\n\n if (taxid === '9606' || taxid === '10090') {\n bandDataFileNames[taxid] = bandFileName;\n }\n\n if (typeof chrBands === 'undefined' && taxid in bandDataFileNames) {\n d3.request(ideo.config.dataDir + bandDataFileNames[taxid])\n .on('beforesend', function(data) {\n // Ensures correct taxid is processed in response callback; using\n // simply 'taxid' variable gives the last *requested* taxid, which\n // fails when dealing with multiple taxa.\n data.taxid = taxid;\n })\n .get(function(error, data) {\n eval(data.response);\n\n ideo.bandData[data.taxid] = chrBands;\n numBandDataResponses += 1;\n\n if (numBandDataResponses === taxids.length) {\n bandsArray = ideo.processBandData();\n writeContainer();\n }\n });\n } else {\n if (typeof chrBands !== 'undefined') {\n // If bands already available,\n // e.g. via <script> tag in initial page load\n ideo.bandData[taxid] = chrBands;\n }\n bandsArray = ideo.processBandData();\n writeContainer();\n }\n }\n });\n\n function writeContainer() {\n\n if (ideo.config.annotationsPath) {\n ideo.fetchAnnots(ideo.config.annotationsPath);\n }\n\n // If ploidy description is a string, then convert it to the canonical\n // array format. String ploidyDesc is used when depicting e.g. parental\n // origin each member of chromosome pair in a human genome.\n // See ploidy_basic.html for usage example.\n if (\n 'ploidyDesc' in ideo.config &&\n typeof ideo.config.ploidyDesc === 'string'\n ) {\n var tmp = [];\n for (var i = 0; i < ideo.numChromosomes; i++) {\n tmp.push(ideo.config.ploidyDesc);\n }\n ideo.config.ploidyDesc = tmp;\n }\n // Organism ploidy description\n ideo._ploidy = new Ploidy(ideo.config);\n\n // Chromosome's layout\n ideo._layout = Layout.getInstance(ideo.config, ideo);\n\n svgClass = '';\n if (ideo.config.showChromosomeLabels) {\n if (ideo.config.orientation === 'horizontal') {\n svgClass += 'labeledLeft ';\n } else {\n svgClass += 'labeled ';\n }\n }\n\n if (\n ideo.config.annotationsLayout &&\n ideo.config.annotationsLayout === 'overlay'\n ) {\n svgClass += 'faint';\n }\n\n var gradients = ideo.getBandColorGradients();\n var svgWidth = ideo._layout.getWidth(taxid);\n var svgHeight = ideo._layout.getHeight(taxid);\n\n d3.select(ideo.config.container)\n .append('div')\n .append('svg')\n .attr('id', '_ideogram')\n .attr('class', svgClass)\n .attr('width', svgWidth)\n .attr('height', svgHeight)\n .html(gradients);\n\n finishInit();\n }\n\n function finishInit() {\n try {\n var t0A = new Date().getTime();\n\n var i;\n\n ideo.initDrawChromosomes(bandsArray);\n\n // Waits for potentially large annotation dataset\n // to be received by the client, then triggers annotation processing\n if (ideo.config.annotationsPath) {\n function pa() {\n if (typeof ideo.timeout !== 'undefined') {\n window.clearTimeout(ideo.timeout);\n }\n\n ideo.annots = ideo.processAnnotData(ideo.rawAnnots);\n ideo.drawProcessedAnnots(ideo.annots);\n\n if (typeof crossfilter !== 'undefined' && ideo.initCrossFilter) {\n ideo.initCrossFilter();\n }\n }\n\n if (ideo.rawAnnots) {\n pa();\n } else {\n (function checkAnnotData() {\n ideo.timeout = setTimeout(function() {\n if (!ideo.rawAnnots) {\n checkAnnotData();\n } else {\n pa();\n }\n },\n 50\n );\n })();\n }\n }\n\n if (ideo.config.showBandLabels === true) {\n var bandsToShow = ideo.bandsToShow.join(',');\n\n // d3.selectAll resolves to querySelectorAll (QSA).\n // QSA takes a surprisingly long time to complete,\n // and scales with the number of selectors.\n // Most bands are hidden, so we can optimize by\n // Hiding all bands, then QSA'ing and displaying the\n // relatively few bands that are shown.\n var t0C = new Date().getTime();\n d3.selectAll(ideo.selector + ' .bandLabel, .bandLabelStalk')\n .style('display', 'none');\n d3.selectAll(bandsToShow).style('display', '');\n var t1C = new Date().getTime();\n if (ideo.debug) {\n console.log('Time in showing bands: ' + (t1C - t0C) + ' ms');\n }\n\n if (ideo.config.orientation === 'vertical') {\n var chrID;\n for (i = 0; i < ideo.chromosomesArray.length; i++) {\n chrID = '#' + ideo.chromosomesArray[i].id;\n ideo.rotateChromosomeLabels(d3.select(chrID), i);\n }\n }\n }\n\n if (ideo.config.showChromosomeLabels === true) {\n ideo.drawChromosomeLabels(ideo.chromosomes);\n }\n\n if (ideo.config.brush === true) {\n ideo.createBrush();\n }\n\n if (ideo.config.annotations) {\n ideo.drawAnnots(ideo.config.annotations);\n }\n\n var t1A = new Date().getTime();\n if (ideo.debug) {\n console.log('Time in drawChromosome: ' + (t1A - t0A) + ' ms');\n }\n\n var t1 = new Date().getTime();\n if (ideo.debug) {\n console.log('Time constructing ideogram: ' + (t1 - t0) + ' ms');\n }\n\n if (ideo.onLoadCallback) {\n ideo.onLoadCallback();\n }\n\n if (!('rotatable' in ideo.config && ideo.config.rotatable === false)) {\n d3.selectAll(ideo.selector + ' .chromosome').on('click', function() {\n ideo.rotateAndToggleDisplay(this);\n });\n } else {\n d3.selectAll(ideo.selector + ' .chromosome')\n .style('cursor', 'default');\n }\n } catch (e) {\n // console.log(e);\n throw e;\n }\n }\n }" ]
{ "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._data[0][0] * matrix._data[0][1] + this._data[0][1] * matrix._data[1][1] + this._data[0][2] * matrix._data[2][1] + this._data[0][3] * matrix._data[3][1]; ret._data[0][2] = this._data[0][0] * matrix._data[0][2] + this._data[0][1] * matrix._data[1][2] + this._data[0][2] * matrix._data[2][2] + this._data[0][3] * matrix._data[3][2]; ret._data[0][3] = this._data[0][0] * matrix._data[0][3] + this._data[0][1] * matrix._data[1][3] + this._data[0][2] * matrix._data[2][3] + this._data[0][3] * matrix._data[3][3]; ret._data[1][0] = this._data[1][0] * matrix._data[0][0] + this._data[1][1] * matrix._data[1][0] + this._data[1][2] * matrix._data[2][0] + this._data[1][3] * matrix._data[3][0]; ret._data[1][1] = this._data[1][0] * matrix._data[0][1] + this._data[1][1] * matrix._data[1][1] + this._data[1][2] * matrix._data[2][1] + this._data[1][3] * matrix._data[3][1]; ret._data[1][2] = this._data[1][0] * matrix._data[0][2] + this._data[1][1] * matrix._data[1][2] + this._data[1][2] * matrix._data[2][2] + this._data[1][3] * matrix._data[3][2]; ret._data[1][3] = this._data[1][0] * matrix._data[0][3] + this._data[1][1] * matrix._data[1][3] + this._data[1][2] * matrix._data[2][3] + this._data[1][3] * matrix._data[3][3]; ret._data[2][0] = this._data[2][0] * matrix._data[0][0] + this._data[2][1] * matrix._data[1][0] + this._data[2][2] * matrix._data[2][0] + this._data[2][3] * matrix._data[3][0]; ret._data[2][1] = this._data[2][0] * matrix._data[0][1] + this._data[2][1] * matrix._data[1][1] + this._data[2][2] * matrix._data[2][1] + this._data[2][3] * matrix._data[3][1]; ret._data[2][2] = this._data[2][0] * matrix._data[0][2] + this._data[2][1] * matrix._data[1][2] + this._data[2][2] * matrix._data[2][2] + this._data[2][3] * matrix._data[3][2]; ret._data[2][3] = this._data[2][0] * matrix._data[0][3] + this._data[2][1] * matrix._data[1][3] + this._data[2][2] * matrix._data[2][3] + this._data[2][3] * matrix._data[3][3]; ret._data[3][0] = this._data[3][0] * matrix._data[0][0] + this._data[3][1] * matrix._data[1][0] + this._data[3][2] * matrix._data[2][0] + this._data[3][3] * matrix._data[3][0]; ret._data[3][1] = this._data[3][0] * matrix._data[0][1] + this._data[3][1] * matrix._data[1][1] + this._data[3][2] * matrix._data[2][1] + this._data[3][3] * matrix._data[3][1]; ret._data[3][2] = this._data[3][0] * matrix._data[0][2] + this._data[3][1] * matrix._data[1][2] + this._data[3][2] * matrix._data[2][2] + this._data[3][3] * matrix._data[3][2]; ret._data[3][3] = this._data[3][0] * matrix._data[0][3] + this._data[3][1] * matrix._data[1][3] + this._data[3][2] * matrix._data[2][3] + this._data[3][3] * matrix._data[3][3]; return ret; } else return null; }
[ "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(matrices[1]);\n this.displayResults(matrices[0], \"x\", matrices[1], \"=\", product);\n } catch (error) {\n alert(\"The rows of the first matrix must match the columns of the second matrix.\");\n }\n }\n }", "add(matrix)\n\t{\n\t\tif (matrix != null && matrix instanceof FourMatrix)\n\t\t{\n\t\t\tvar ret = new FourMatrix();\n\n\t\t\tret._data[0][0] = this._data[0][0] + matrix._data[0][0];\n\t\t\tret._data[0][1] = this._data[0][1] + matrix._data[0][1];\n\t\t\tret._data[0][2] = this._data[0][2] + matrix._data[0][2];\n\t\t\tret._data[0][3] = this._data[0][3] + matrix._data[0][3];\n\n\t\t\tret._data[1][0] = this._data[1][0] + matrix._data[1][0];\n\t\t\tret._data[1][1] = this._data[1][1] + matrix._data[1][1];\n\t\t\tret._data[1][2] = this._data[1][2] + matrix._data[1][2];\n\t\t\tret._data[1][3] = this._data[1][3] + matrix._data[1][3];\n\n\t\t\tret._data[2][0] = this._data[2][0] + matrix._data[2][0];\n\t\t\tret._data[2][1] = this._data[2][1] + matrix._data[2][1];\n\t\t\tret._data[2][2] = this._data[2][2] + matrix._data[2][2];\n\t\t\tret._data[2][3] = this._data[2][3] + matrix._data[2][3];\n\n\t\t\tret._data[3][0] = this._data[3][0] + matrix._data[3][0];\n\t\t\tret._data[3][1] = this._data[3][1] + matrix._data[3][1];\n\t\t\tret._data[3][2] = this._data[3][2] + matrix._data[3][2];\n\t\t\tret._data[3][3] = this._data[3][3] + matrix._data[3][3];\n\t\t\treturn ret;\n\t\t}\n\t\telse\n\t\t\treturn null;\n\t}", "testMultiplyingMatricesIdentity() {\r\n console.info('test Matrix2.multiplyMatrices() by identity matrix')\r\n const firstMatrixElements = [\r\n 1, 2,\r\n 3, 4,\r\n ]\r\n const identityMatrixElements = [\r\n 1, 0,\r\n 0, 1,\r\n ]\r\n const expectedMatrixElements = [\r\n 1, 2,\r\n 3, 4,\r\n ]\r\n const matrix = new Matrix2(firstMatrixElements)\r\n matrix.multiplyMatrices(identityMatrixElements)\r\n const actualMatrixElements = matrix.elements\r\n this.assertIdentical(actualMatrixElements, expectedMatrixElements)\r\n }", "function vectorMultiplyMatrix(a, B) {\n\t//var A_x = 1;\n\tvar A_y = a.length;\n\tvar B_x = B.length;\n\tvar B_y = B[0].length;\n\t\n\tif (B_x != A_y) {\n\t\talert(\"Matrix inner dimensions must agree\");\n\t\treturn;\n\t}\n\t\t\n\tvar v = new Array(B_y);\n\tfor (var j = 0; j < B_y; j++) {\n\t\tv[j] = 0;\n\t}\n\t\t\n\tfor (var i = 0; i < A_y; i++) {\n\t\tvar Browi = B[i];\n\t\tfor (var j = 0; j < B_y; j++) {\n\t\t\tv[j] += a[i] * Browi[j];\n\t\t}\n\t}\n\treturn v;\n}", "function matrix_mult(x, A_inv, b) {\n x[0] = A_inv[0][0] * b[0] + A_inv[0][1] * b[1];\n x[1] = A_inv[1][0] * b[0] + A_inv[1][1] * b[1];\n}", "function multiplyMatrixByVector(m, v) {\r\n result = new Array(m.length);\r\n for (let i = 0; i < m.length; i++) {\r\n result[i] = 0;\r\n for (let j = 0; j < v.length; j++) {\r\n result[i] += m[i][j] * v[j];\r\n }\r\n }\r\n return result;\r\n}", "multv(v) {\n // check column must match vector's row count\n if (this.n !== v.m) {\n console.error('matrix column must match vector\\'s row count')\n return undefined\n }\n // check if v is a vector\n if (v.n !== 1) {\n console.error(v, 'is not a vector')\n return undefined\n }\n const C = []\n let rn = []\n for (let i=1; i<=this.m; i++) {\n let n = 0\n for (let j=1; j<=this.n; j++) {\n n += this.at(i,j)*v.at(j,1)\n }\n C.push([n])\n }\n return new Matrix(C)\n }", "function vmm( x , y )\n {\n\n let i = undefined ;\n let j = undefined ;\n\n for( i = 0; i < x.nv; ++i )\n \n for( j = 0; j < y.nv; ++j )\n\n this.v[ this.idx( i , j ) ] = ( x.v[ i ] * y.v[ j ] ) ;\n\n return ;\n\n }", "function calculateProduct(matrixK, matrixJ){\n var matrix = new Array();\n var dotProduct = 0;\n\n for(var i = 0; i < matrixK.length; i++){\n matrix[i] = [];\n for(var k = 0; k < matrixJ[0].length;k++){\n for(var j = 0; j < matrixK[0].length; j++){\n dotProduct += matrixK[i][j] * matrixJ[j][k];\n }\n matrix[i][k] = dotProduct;\n dotProduct = 0;\n }\n }\n\n return matrix;\n\n}", "function pushMVMatrix() {\n \tvar mvMatrixCopy = mat4.create();\n \tmat4.set(mvMatrix, mvMatrixCopy);\n \tmvMatrixStack.push(mvMatrixCopy);\n }", "function sparseMatrixMultiplyVector(B,a) {\n\t\n\tvar k = a.length; \n\tvar m = B.length;\n\tvar n = B[0].length; // n=m\n\t\n\tif (k != m) {\n\t\talert(\"Inner dimensions must match!\");\n\t\treturn;\n\t}\n\n\tvar t = new Array(m);\n\tfor (var j = 0; j < m; j++) {\n\t\tt[j] = 0;\n\t}\n\n\tfor (var i = 0; i < m; i++) {\n\t\t//get array of locations\n\t\tvar d = _indexes(B[i]);\n\n\t\tvar temp = 0;\n\t\t\n\t\tfor(var k = 0; k < d.length; k++) {\n\t\t\tt[i] += a[d[k]];\n\t\t}\n\t\t//t[i]+=temp;\n\t}\n\n\treturn t;\n}", "multiply(otherVector) {\n return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);\n }", "static identity(){\n return new matrix4([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]);\n }", "addToValuesFromArrayMatrixProduct(\n copyTo, // array being modified\n copyFromArray, // array: values are copied from for processing\n copyFromMatrix, // matrix: values are copied from for processing\n copyCountDim0, // = copyFromMatrix dimension 0 limit AND <= copyFromArray.length\n copyCountDim1 // = copyFromMatrix dimension 1 limit AND <= copyTo.length\n ) {\n for (var j = 0; j < copyCountDim1; ++j)\n for (var i = 0; i < copyCountDim0; ++i)\n copyTo[j] += copyFromArray[i] * copyFromMatrix[i][j]\n }", "function multiFourAndReturn(n1,n2,n3,n4){\n return n1*n2*n3*n4\n}", "function create_matrix(index, global_mode,global_rotation,shapes_tx,shapes_ty,shapes_rotation,shapes_scale){\n var mvMatrix = mat4.create(); // this is the matrix for transforming each shape before draw\n //set into an identity matrix (after create you don't know if there's junk in it)\n // set identity - fresh matrix\n mat4.identity(mvMatrix); \n if(global_mode[index]){\n for(var j = 0; j < global_rotation[index].length; j++){\n mat4.rotate(mvMatrix,degToRad(global_rotation[index][j]),[0,0,1]);\n } \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = global_scale;\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale);\n }\n var trans = [0,0,0];\n trans[0] = shapes_tx[index]; \n trans[1] = shapes_ty[index];\n trans[2] = 0.0;\n //translate is multiplied to the right side of the mvMatrix \n mvMatrix = mat4.translate(mvMatrix, trans); // move from origin to mouse click\n //2d x-y in 3d x-z rotate around z\n // only accept radian, not degree. so we use degToRad\n mvMatrix = mat4.rotate(mvMatrix, degToRad(shapes_rotation[index]), [0, 0, 1]); // rotate if any \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = shapes_scale[index];\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale); // scale if any \n //var mvMatrix1 = mat4.inverse(mvMatrix);\n //mvMatrix = mat4.multiply(mvMatrix1,mvMatrix);\n return mvMatrix;\n}", "function applyTransformation ( ctm , buffer ) {\n\tvar result = [];\n\tvar temp;\n\tfor (var i = 0; i < buffer.length; ++i)\n\t{\n\t\ttemp = vec4( buffer[i][0], buffer[i][1], buffer[i][2], buffer[i][3] );\n\t\tresult.push( matMultVec( ctm, temp ) );\n\t}\n\treturn result;\n}", "multiplyToArray(other, result, offset) {\n const m = this._m;\n const otherM = other.m;\n // tslint:disable:one-variable-per-declaration\n const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];\n const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];\n const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];\n const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];\n const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];\n const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];\n const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];\n const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];\n // tslint:enable:one-variable-per-declaration\n result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;\n result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;\n result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;\n result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;\n result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;\n result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;\n result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;\n result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;\n result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;\n result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;\n result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;\n result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;\n result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;\n result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;\n result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;\n result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;\n return this;\n }", "function transformMatrix_(s, t) {\n return [t[0] * s[0] + t[1] * s[2],\n t[0] * s[1] + t[1] * s[3],\n s[0] * t[2] + s[2] * t[3],\n s[1] * t[2] + t[3] * s[3],\n s[0] * t[4] + s[4] + s[2] * t[5],\n s[1] * t[4] + s[3] * t[5] + s[5]];\n}" ]
{ "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 = getCurrentDate(); var arr2 = re.exec( d); //alert('getCompareNow'); var dt = new Date( parseInt(arr[3]), parseInt(arr[2], 10) - 1, parseInt(arr[1], 10)); var dn = new Date( parseInt(arr2[3]), parseInt(arr2[2], 10) - 1, parseInt(arr2[1], 10)); return dt >= dn; }
[ "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(year2, 10)) {\n return true;\n }\n else if (parseInt(month1, 10) > parseInt(month2, 10) && parseInt(year1, 10) == parseInt(year2, 10)) {\n return true;\n }\n else if (parseInt(day1, 10) > parseInt(day2, 10) && parseInt(month1, 10) == parseInt(month2, 10) && parseInt(year1, 10) == parseInt(year2, 10)) {\n return true;\n }\n else {\n return false;\n }\n}", "function validDates() {\n if (checkIn.val() != '' && checkOut.val() != '') {\n inDate = new Date(checkIn.val())\n outDate = new Date(checkOut.val())\n if (inDate < outDate) {\n return true\n }\n }\n return false\n }", "function isPresentOrFuture(date) {\n var now = new Date();\n date = new Date(Date.parse(date));\n if (date.getFullYear() > now.getFullYear()) return true;\n if (date.getFullYear() < now.getFullYear()) return false;\n\n if (date.getMonth() > now.getMonth()) return true;\n if (date.getMonth() < now.getMonth()) return false;\n\n if (date.getDate() >= now.getDate()) return true;\n if (date.getDate() < now.getDate()) return false;\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 }", "function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){\n console.log(enteredCode + ' ' + correctCode + ' ' + currentDate + ' ' + expirationDate)\n console.log(enteredCode.length);\n if(enteredCode.toString().length < 3 || enteredCode.toString() != correctCode.toString() || enteredCode == '') {\n return false;\n }\n var dateNow = new Date(currentDate);\n var dateCoupon = new Date(expirationDate);\n if (dateNow > dateCoupon) {\n return false;\n }\n\n return true;\n\n}", "function isDateEqual(a, b) {\n return (\n a instanceof Date &&\n b instanceof Date &&\n a.getFullYear() === b.getFullYear() &&\n a.getMonth() === b.getMonth() &&\n a.getDate() === b.getDate()\n );\n}", "function sameDate(date1, date2) {\n return (date1.getDate() === date2.getDate()\n && date1.getMonth() === date2.getMonth()\n && date1.getFullYear() === date2.getFullYear()\n );\n}", "function validateDateForGapScan(date){\t\n\tvar valid = true;\n\tvar oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds\n\tvar todayDateArray = getTodayDate().split(\"/\");\n\tvar selDateArray = date.split(\"/\");\n\tvar selDate = new Date(selDateArray[2],selDateArray[1]-1,selDateArray[0]);\n\tvar todayDate = new Date(todayDateArray[2],todayDateArray[1]-1,todayDateArray[0]);\n\n\tvar diffDays = Math.round(Math.abs((todayDate.getTime() - selDate.getTime())/(oneDay)));\n\t\n\tif(selDate > todayDate){\n\t\tvalid = false;\n\t\t$.fn.showCustomMsg(['Entered date is greater than today\\'s date.'],error,'GapScan Report');\n\t}else if(diffDays > 6){\n\t\tvalid = false;\n\t\t$.fn.showCustomMsg(['This report is limited to last 7 days. Please choose a valid date.'],error,'GapScan Report');\n\t}\n\treturn valid;\n\t\n}", "function compareTwoDates ( value1 , value2 )\n\t{\n\t var date1, date2;\n\t var month1, month2;\n\t var year1, year2;\n\t year1 = value1.substring (0, value1.indexOf (\"-\"));\n\t month1 = value1.substring (value1.indexOf (\"-\")+1, value1.lastIndexOf (\"-\"));\n\t date1 = value1.substring (value1.lastIndexOf (\"-\")+1, value1.length);\n\t year2 = value2.substring (0, value2.indexOf (\"-\"));\n\t month2 = value2.substring (value2.indexOf (\"-\")+1, value2.lastIndexOf (\"-\"));\n\t date2 = value2.substring (value2.lastIndexOf (\"-\")+1, value2.length);\n\t \tdate1 = parseInt(date1, 10);\n\t \tmonth1= parseInt(month1, 10);\n\t \tyear1= parseInt(year1, 10);\n\t \tdate2 = parseInt(date2, 10);\n\t \tmonth2= parseInt(month2, 10);\n\t \tyear2= parseInt(year2, 10);\n\t \t\n\t if (year1 > year2) return 1;\n\t else if (year1 < year2) return -1;\n\t else if (month1 > month2) return 1;\n\t else if (month1 < month2) return -1;\n\t else if (date1 > date2) return 1;\n\t else if (date1 < date2) return -1;\n\t else return 0;\n\t}", "function isDateACHSafe(dateFieldIdName)\n{\n\tvar dateOne = Date.parse(nextSafeACHDueDate);\n\t\n\tvar dateValue = document.getElementById(dateFieldIdName);\n\n\tif(!dateOne || !dateValue) return false;\n\t\n\tvar dateTwo = Date.parse(dateValue.value);\n\t\n\tvar diff = dateTwo - dateOne;\n\tvar days = Math.floor(diff / ( 1000 * 60 * 60 * 24));\n\n\tif(days >= 0)\n\t{\n\t\treturn true\n\t}\n\n\treturn false;\n}", "function filterByDate(flights) {\n var today = new Date();\n if (vm.formData.date == null || vm.formData.date == '') {\n return flights.GateID == vm.filterByGateId;\n } else {\n var arrivalDate = moment(new Date(flights.ArrivalTime),'MM/DD/YYYY').format('MM/DD/YYYY');\n var compareDate = moment(new Date(vm.formData.date),'MM/DD/YYYY').format('MM/DD/YYYY');\n return flights.GateID == vm.filterByGateId && arrivalDate == compareDate;\n }\n }", "function checkIfNatural(dateString){\n\t\t\tvar valid = new Date(dateString).getTime() > 0; \n\t\t\treturn valid; \n\t\t}", "function IsEarlier(less, more)\n{\n\tif (less.getFullYear() > more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\tif (less.getMonth() > more.getMonth() && less.getFullYear() == more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\tif (less.getDate() > more.getDate() && less.getMonth() == more.getMonth() && less.getFullYear() == more.getFullYear())\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}", "function compareDates(date1, date2) {\n if (sameDate(date1, date2)) {\n return 0;\n }\n\n return date1 < date2 ? -1 : 1;\n}", "function isAfter(date, ref_date){\n\tvar date_year = parseInt(date.substring(0, 4));\n\tvar date_month = parseInt(date.substring(5, 7));\n\tvar ref_date_year = parseInt(ref_date.substring(0, 4));\n\tvar ref_date_month = parseInt(ref_date.substring(5, 7));\n\t\n\tif(date_year > ref_date_year){\n\t\treturn true;\n\t}\n\tif(date_year == ref_date_year){\n\t\treturn date_month > ref_date_month;\n\t}\n\treturn false;\n}", "function areDatesDifferent(ts0, ts1) {\n\t\tvar d0 = new Date(ts0 - dateBoundaryOffsetMs);\n\t\tvar d1 = new Date(ts1 - dateBoundaryOffsetMs);\n\t\treturn d0.getFullYear() != d1.getFullYear() || d0.getMonth() != d1.getMonth() || d0.getDate() != d1.getDate();\n\t}", "function CashPostDateIsDateChanged(pCurrPostDateArr)\n{\n for (var i = 0; i < globArrPostDateData.length; i++) {\n\n if (globArrPostDateData[i].date !== pCurrPostDateArr[i].date) {\n var olddate = parseDate(globArrPostDateData[i].date);\n var newDate = parseDate(pCurrPostDateArr[i].date);\n if (!isNaN(newDate) && (newDate > olddate)) {\n return i;\n }\n }\n }\n return -1;\n}", "function ISDATE(value) {\n return value && Object.prototype.toString.call(value) == '[object Date]';\n}", "function filterDate(aliens) {\n return aliens.datetime == $dateInput.value.trim().toLowerCase();\n}" ]
{ "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 were found.')\n break\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break\n default:\n alert('Error opening your camera and/or microphone: ' + err.message)\n break\n }\n}", "function pwUpdateError(){\n\tdisplayMessage(\"There was an error updating the password. The previous\\npassword will still be used to access the tile edit feature\\nand any edits you have made have been saved. Try to reset\\nthe password for this tile again later\", removePrompt(),\n\t\t\t\t\tremovePrompt(),false,false);\n}", "function error(id) {\n var item = itemDictionary()[id];\n if (item && item.inputValue && item.inputValue.error) {\n return item.inputValue.error();\n }\n }", "get uid()\n\t{\n\t\treturn this._uid;\n\t}", "function validateId(user_id, callback){\n\tvar sel_q = \"SELECT id, user_name, xp_sent, xp_received, send_count, receive_count, last_activity FROM spg_users WHERE id = \" + user_id;\n\tc.query(sel_q, function(err, rows, fields) {\n\t\tr_val = {is_valid:false,user_obj:{}};\n\t\tif (!err) {\n\t\t\tif (rows.length == 1) {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") exists on DB\");\n\t\t\t\tr_val.is_valid = true;\n\t\t\t\tr_val.user_obj = rows[0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") does not exist on DB\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"Error selecting [\" + user_id + \"]\");\n\t\t\tconsole.log(\"Err: \" + err );\n\t\t}\n\n\t\tcallback(r_val);\n\t});\n}", "function errorGetOtherProfile(error){\n removeLoading();\n document.getElementById(\"showProfileMsg\").innerHTML = error.message;\n document.getElementById(\"showProfileMsg\").className = \"errors\"; \n}", "function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }", "function setupUGID(uid, gid) {\n if (uid) {\n if (!gid) {\n gid = uid;\n }\n\n try {\n process.setgid(gid);\n util.log('changed gid to ' + gid);\n process.setuid(uid);\n util.log('changed uid to ' + uid);\n } catch (e) {\n util.log('Failed to set uid/gid to ' + [uid, gid].join('/') +\n ' Error: ' + e.message);\n }\n }\n}", "function check_user_pers(err,row,data,response){\n if(err === null && row != undefined){\n if(row.persistentLogin === data.per){\n validSignUp(response,err,data.usr);\n }\n else{\n submitionError(9,response);\n }\n }\n else{\n submitionError(1,response);\n }\n}", "function errorRRRV(){\n\tvar RRRV1 = document.getElementById('TRV_RRRV1_id').value\n\tvar RRRV2 = document.getElementById('TRV_RRRV2_id').value\n\t\n\tif (RRRV1 != 0 && RRRV2 ==0){\n\t\treturn true\n\t}\n\tif (RRRV2 == 0 && RRRV1 == 0){\n\t\treturn true\n\t} \n\telse \n\t\treturn false\n}", "function isnotsu() {\nif(msguser !== superuserid ) {\nconst plaintext = \"<:warn_3:498277726604754946> Sorry, you don't have permissions to use this!\"\nconst embed = new RichEmbed() \n//.setTitle('Title') \n.setColor(0xCC0000) \n.setDescription('only ' + superuser + ' may use this command')\n//.setAuthor(\"Header\")\n.setFooter(\"@\" + msgauthor)\n//.addField(\"Field\");\nmessage.channel.send(plaintext, embed);\n\n\t/*\nreturn message.reply(\"Sorry, you don't have permissions to use this!\")\n*/\nreturn true\n}\nelse\nreturn false;\n}", "function defaultDataError(error) {\n// console.log(error+\" error \"+JSON.stringify(error))\n var errorNumber = parseFloat(error.error_code);\n if (schneider.util.inArray(errorNumber, [21327, 21334, 21335, 21336])) {\n self._deferFailedRequests(obj);\n } else if (schneider.util.inArray(errorNumber, [21305, 21332, 21333])) {\n self.logout();\n } else if (errorNumber == 20006 && error.error.indexOf(\"@\") == -1) {\n self.logout();\n }\n schneider.util.unmask();\n }", "function CreatePatientMessage(val)\n{\t\n\tif(val == 0)\n\t{\n\t\t$('#Create_Patient_Main_Error').html(\"Patient alreday exist\");\n\t\t$(\"#Create_Patient_Main_Success\").hide();\n\t\t$('#Create_Patient_Main_Error').show();\n\t//\t$(\"#Create_User_user_name_error\").show();\n\t//\tdocument.getElementById('Create_User_user_name_error').innerHTML=\"Username already exists\";\n\t}\n\telse if(val == 1)\n\t{\n\t\t $('#Create_Patient_Main_Success').html(\"New patient has been created\");\n\t\t$(\"#Create_Patient_Main_Success\").show();\n\t\t$('#Create_Patient_Main_Error').hide();\n\t//\tdocument.getElementById('Create_User_error_message').innerHTML=\"User Created Successfully\";\t\t\n\t}\n}", "function checkMMR(message, userID){\n sql.get(\"SELECT * FROM accounts WHERE userID='\"+userID+\"'\").then(row=>{\n if(row){\n message.author.send(\"MMR: \" + row.mmr);\n }\n else{\n message.channel.send(\"No MMR found\");\n }\n }).catch(console.error);\n}", "function validateUUID(arg) {\n if (!arg) {\n console.error('Error: missing UUID');\n process.exit(1);\n }\n if (!UUID_REGEX.test(arg)) {\n console.error('Error: invalid UUID \"%s\"', arg);\n process.exit(1);\n }\n return arg;\n}", "function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}", "function checkError(errorCode) {\n switch(errorCode) {\n case 0:\n return 'Geen watertoevoer';\n case 1:\n return 'Temperatuur te laag';\n case 2:\n return 'Koffiebonen op';\n case 3:\n return 'Afvalbak vol';\n case 4:\n return 'Geen druk';\n default:\n return 'Onbekende foutcode';\n }\n}" ]
{ "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: setValue(key, value) the key must be a string but the value can be any object getValue(key) Extract the script web session information from the Http Message and store in the ScriptBasedSession
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=\" + name + \"&value=\" + value, test);\n _getSession()[name] = value;\n}", "function getSession(request, response) {\n\tvar session = request.session;\n\tconsole.log(\"SESSION: \", session);\n\tif (!session.sfdcAuth) {\n\t\tresponse.status(401).send('No active session');\n\t\treturn null;\n\t}\n\treturn session;\n}", "get sessData() {\n return this._sessData || {};\n }", "function getSessionTimeoutFor(session) {\n if (!(session._id in sessionTimeouts)) {\n sessionTimeouts[session._id] = new SessionTimeout(session._id, [], [])\n }\n return sessionTimeouts[session._id]\n}", "function getSession(text) {\n\n return text.substring(text.search('Session ID:')).split('\\n', 1)[0];\n\n }", "function newSession() {\n\n // Get a session from the API.\n sessionPromise = SessionDataService.create().then(\n function (session) {\n\n // Replace currently stored session.\n replace(sessionObject, session);\n\n return sessionObject;\n });\n\n return sessionPromise;\n }", "function getSession(ctx) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!matchPath(ctx)) {\n return;\n }\n if (storeStatus === PENDING) {\n // store is disconnect and pending;\n yield waitStore;\n }\n else if (storeStatus === UNAVAILABLE) {\n // store is unavailable\n throw new Error(\"session store is unavailable\");\n }\n if (!ctx.sessionId) {\n ctx.sessionId = sessionIdStore.get(ctx);\n }\n let session;\n let isNew = false;\n if (!ctx.sessionId) {\n // session id not exist, generate a new one\n session = generateSession();\n ctx.sessionId = genSid(ctx, 24);\n // now the ctx.cookies.get(key) is null\n isNew = true;\n }\n else {\n try {\n // get session %j with key %s\", session, this.sessionId\n session = yield store.get(ctx.sessionId);\n }\n catch (err) {\n if (err.code === \"ENOENT\") {\n console.warn(\"get session error, code = ENOENT\");\n }\n else {\n console.warn(\"get session error: \", err.message);\n errorHandler(err, \"get\", ctx);\n }\n }\n }\n // make sure the session is still valid\n if (!session || !valid(ctx, session)) {\n // session is empty or invalid\n session = generateSession();\n ctx.sessionId = genSid(ctx, 24);\n // now the ctx.cookies.get(key) is null\n sessionIdStore.reset(ctx);\n isNew = true;\n }\n // get the originHash\n const originalHash = !isNew && hash(session);\n return {\n originalHash,\n session,\n isNew,\n };\n });\n }", "function storeToSession(key, value) {\n if (sessionStorage) {\n sessionStorage[key] = value;\n }\n else {\n throw Error(\"Session storage not supported\");\n }\n}", "static async find(id) {\n let sessionData = await db.get(`session:${id}`)\n return new Session(sessionData);\n }", "function retrieveFromSession(key) {\n if (sessionStorage) {\n if (sessionStorage[key]) {\n return sessionStorage[key];\n }\n return null;\n }\n else {\n throw Error(\"Session storage not supported\");\n }\n}", "function injectSearchSession(Component) {\n return /** @class */ (function (_super) {\n tslib_1.__extends(WrapperComponent, _super);\n function WrapperComponent() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.searchSessionId = null;\n return _this;\n }\n WrapperComponent.prototype.render = function () {\n var _this = this;\n return (React.createElement(SearchSessionContext.Consumer, null, function (_a) {\n var searchSessionId = _a.searchSessionId;\n if (!_this.searchSessionId) {\n _this.searchSessionId = searchSessionId || v4_1.default();\n }\n return (React.createElement(Component, tslib_1.__assign({}, _this.props, { searchSessionId: _this.searchSessionId })));\n }));\n };\n return WrapperComponent;\n }(React.Component));\n}", "resolveSession() {\n console.debug('session.resolveSession');\n // Request session data\n // TODO: no reject handling\n return this.get('server').sessionRPC().then((data) => {\n console.debug(\"RESOLVE SESSION REQ\");\n console.debug('data: ' + JSON.stringify(data));\n let isSessionValid = (data.sessionValid === true);\n this.set('sessionValid', isSessionValid);\n let promise;\n if (isSessionValid) {\n promise = this.onResolveSessionValid(data);\n } else {\n promise = this.onResolveSessionInvalid();\n }\n const resolveFunction = this.get('sessionInitResolve');\n // the resoleFunction can be undefined/null only if we (re)open WebSocket\n // only, without reinitializing session\n if (resolveFunction) {\n resolveFunction();\n }\n\n this.setProperties({\n sessionInitResolve: null,\n sessionInitReject: null,\n sessionRestoreResolve: null,\n sessionRestoreReject: null\n });\n\n return promise;\n });\n }", "function refreshSession() {\n\n // Use session promise to ensure we have a session object.\n return sessionPromise.then(\n function (session) {\n\n // Return promise from data service.\n return SessionDataService.get(session.Guid).then(\n function (sessionUpdate) {\n\n replace(sessionObject, sessionUpdate);\n\n return sessionObject;\n });\n });\n }", "function ssget(k) {\n k = _tokey(k);\n let v = JSON.parse(sessionStorage.getItem(k));\n return v;\n}", "renewSession() {\n // implement in concrete authenticator\n }", "function startSessionTracking() {\n if (typeof WINDOW.document === 'undefined') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}", "function initializeSessionTimers(warningInterval, timeoutInterval) {\n sessionWarningTimer = new KradTimer(showSessionTimeoutWarning, warningInterval);\n sessionTimeoutTimer = new KradTimer(showSessionTimeout, timeoutInterval);\n\n broadcastSessionUpdate();\n\n window.addEventListener(\"storage\", checkForSessionUpdate);\n}", "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) {\n console.log(' --> YES, session there!'); // FIXME debugging output\n next();\n return;\n }\n\n // no session there => SSO process kicks in ...\n\n // check if we got an SSO token\n console.log('check for SSO token ...'); // FIXME debugging output\n if (req.query[ssoToken]) {\n console.log(' --> YES, got SSO token: ' + req.query[ssoToken]); // FIXME debugging output\n\n // fetch user info\n console.log(' --> fetching user info ...'); // FIXME debugging output\n request(config.identityProvider.getIdUrl.replace('${SSO_TOKEN}', req.query[ssoToken]), function(err, response, data) {\n console.log(' --> response from id.json: ' + JSON.stringify(data)); // FIXME debugging output\n if (!err && response.statusCode == 200) {\n console.log(' --> GOT user info: ' + JSON.stringify(data)); // FIXME debugging output\n data = JSON.parse(data);\n req.session.username = 'USER' + data.username;\n } else {\n console.log(' --> ERROR at fetching user info (status code: ' + response.statusCode + ') with SSO token ' + req.query[ssoToken]); // FIXME debugging output\n }\n\n next();\n return;\n });\n\n } else {\n // no SSO token and no session => ask SSO identity provider for identity\n console.log('no SSO token => redirect to SSO auth ...'); // FIXME debugging output\n res.redirect(config.identityProvider.authUrl.replace('${TARGET}', encodeURIComponent(config.appTarget)));\n }\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 data.recorded,\n CHANNEL,\n PARALLELOGRAM_TAG\n );\n }", "recordingStopped() {\n if (this.stopAfterRecording) {\n this.stopBuffering();\n }\n }", "function stopAudio() {\n for (var key in audioSrcList) {\n if (audioSrcList.hasOwnProperty(key)) {\n audioSrcList[key][0].pause();\n audioSrcList[key][0].currentTime = 0;\n }\n }\n}", "stop() {\n\n this.isPlaying = false; // set the 'playing' boolean to false\n\n // stop all tracks (basically only the currently playing track needs to be stopped, but for safety all are stopped)\n for (let i in this.allTracks) {\n this.allTracks[i].stop();\n }\n\n this.playing = 0; // reset to the beginning (next time it starts from the beginning)\n }", "stop() {\n this.queueLock = true;\n this.queue = [];\n this.audioPlayer.stop(true);\n }", "function stopMusic() {\n music_audio.play();\n}", "function stop_other_audio_tracks()\n {\n for (var i = 1; i <= 3; i++)\n if (i != audio_player && audio_stream [i])\n audio_stream [i].stop();\n }", "async disable () {\n // Disconnect everything\n this.mic.disconnect()\n this.scriptNode.disconnect()\n\n // Stop all media stream tracks and remove them\n this.media.getAudioTracks().forEach(\n (element) => {\n element.stop()\n this.media.removeTrack(element)\n }\n )\n\n // Close the context and remove it\n await this.context.close()\n this.context = null\n\n this.stats.teardown() // hide stats page\n this.isActive = false\n console.log('Audio Detection Disabled')\n }", "function restartRecording() {\n \n // https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/state\n //console.log('recorder ' + recorder.state )\n\n // need otherwise I get on Chrome the error:\n // Failed to execute 'stop' on 'MediaRecorder': The MediaRecorder's state is 'inactive'.\n if (recorder.state != 'inactive')\n recorder.stop()\n\n audioPlay = false\n recorder.start()\n \n}", "stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }", "stop() {\n return (0, _tslib.__awaiter)(this, void 0, void 0, function* () {\n (0, _Debug.assert)(this.state !== \"stopped\", \"Recorder is not started\");\n const dataPromise = new Promise(done => {\n const handleData = e => {\n this._recorder.removeEventListener(\"dataavailable\", handleData, false);\n\n done(e.data);\n };\n\n this._recorder.addEventListener(\"dataavailable\", handleData, false);\n });\n\n this._recorder.stop();\n\n return yield dataPromise;\n });\n }", "function stopGoogle() {\n googleListen = false;\n clearTimeout(googleKiller);\n silenceIndex = 0;\n recognizeStream.end();\n}", "function stop(alias) {\n var soundInstance = getSoundByAlias(alias);\n soundInstance.stopSound();\n }", "function stop() {\n\t/**\n\t * optional, e.g. for analysis:\n\t * post the String created along the lines (\"measure\", not in this file) to the server, and save as .csv file\n\t */\n\t/**if (measure != \"#Measurement, Acceleration X, Acceleration Y, Acceleration Z, Rotation Alpha, Rotation Beta, Rotation Gamma, Orientation Alpha, Orientation Beta, Orientation Gamma \\r\\n\") {\n $.ajax(\n {\n type: \"POST\",\n url: \"/sensordata\",\n dataType: \"String\",\n data: {\n sensData: measure\n },\n statusCode: {\n 200: function () {\n alert(\"Measurement saved successfully!\");\n },\n 400: function () {\n alert(\"Saving did not work.\")\n }\n }\n }\n );\n }*/\n\t//remove listeners, thus ending measurements\n\twindow.removeEventListener('devicemotion', deviceMotionHandler, false);\n\twindow.removeEventListener('deviceorientation', deviceOrientationHandler, false);\n}", "function powerOff() {\n setVisible(powerOffButton, false);\n setVisible(powerOnButton, true);\n if (fmRadio.isPlaying()) {\n fmRadio.stop();\n }\n saveCurrentStation();\n saveVolume();\n }", "function stopCall() {\n // quit the current conference room\n bc.quitRoom(room);\n}", "function endVideo() {\n var video = document.getElementById('video');\n var audio = document.getElementById('audio');\n audio.parentNode.removeChild(audio);\n video.parentNode.removeChild(video);\n}", "endSeek() {\r\n if (this.isSeeking && this.wasPlaying === true)\r\n this.play();\r\n this.wasPlaying = false;\r\n this.isSeeking = false;\r\n }", "function endSound() {\n winSound.play();\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 = parseInt(playerBullets) - 1; } if (action === 'RELOAD') { document.getElementById('player-bullets').innerHTML = parseInt(playerBullets) + 1; } // run the computer runComputer(); }
[ "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 }", "function playStuff() {\r\n\t\tgsapAnimation(this);\r\n\t\tuserClicks.push(\"#\"+this.id);\r\n\t\tcheckCorrectness();\r\n\t}", "returnActionCards() {\n \n let action = {};\n \n action['action1']\t= { \n \tname : \"Accidental Colonization\" ,\n \ttype : \"instant\" ,\n \ttext : \"Gain control of one planet not controlled by any player\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action2']\t= { \n \tname : \"Hydrocannon Cooling\" ,\n \ttype : \"instant\" ,\n \ttext : \"Ship gets -2 on combat rolls next round\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action3']\t= { \n \tname : \"Agile Thrusters\" ,\n \ttype : \"instant\" ,\n \ttext : \"Attached ship may cancel up to 2 hits by PDS or Ion Cannons\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action4']\t= { \n \tname : \"Diaspora Conflict\" ,\n \ttype : \"instant\" ,\n \ttext : \"Exhaust a planet card held by another player. Gain trade goods equal to resource value.\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action5']\t= { \n \tname : \"Consortium Research\" ,\n \ttype : \"instant\" ,\n \ttext : \"Cancel 1 yellow technology prerequisite\" ,\n \tinteractive : 0 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action6']\t= { \n \tname : \"Independent Thinker\" ,\n \ttype : \"instant\" ,\n \ttext : \"Cancel 1 blue technology prerequisite\" ,\n \tinteractive : 0 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action7']\t= { \n \tname : \"Military-Industrial Complex\" ,\n \ttype : \"instant\" ,\n \ttext : \"Cancel 1 red technology prerequisite\" ,\n \tinteractive : 0 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action8']\t= { \n \tname : \"Innovative Cluster\" ,\n \ttype : \"instant\" ,\n \ttext : \"Cancel 1 green technology prerequisite\" ,\n \tinteractive : 0 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action9']\t= { \n \tname : \"Aggressive Upgrade\" ,\n \ttype : \"instant\" ,\n \ttext : \"Replace 1 of your Destroyers with a Dreadnaught\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n action['action10']\t= { \n \tname : \"Lost Mission\" ,\n \ttype : \"instant\" ,\n \ttext : \"Place 1 Destroyer in a system with no existing ships\" ,\n \tinteractive : 1 ,\n \timg : \"/imperium/img/action_card_template.png\" ,\n onPlay : function(imperium_self, player, mycallback) {\nconsole.log(\"THE ACTION CARD: \" + this.name + \" is being played!\");\n mycallback(1);\n },\n };\n \n return action;\n \n }", "onPlayed () {\n UIManager.setStatusCast(UIManager.status.READY);\n UIManager.showSplashScreen();\n\n this.isCompleted = true;\n if (this.endedCallback !== null) {\n this.endedCallback();\n }\n\n this.notifySenders.apply(this, arguments);\n\n logger.info(LOG_PREFIX, 'Played');\n }", "collect(type, condition, player) {\n while (condition) {\n setInterval(() => {\n if (type === 'timber') {\n player.timber += this.interactSpeed;\n } else {\n player.wheat += this.interactSpeed;\n }\n }, 1000);\n }\n }", "function characterMover(){\n    var tempLocale = locations[currentLvl];\n    var msg = tempLocale.name + \":\" + \"\\n\" + tempLocale.desc;\n\n btnEnable();\n   scoreCount(tempLocale);\n    updateDisplay (msg + \"\\n\" + \"Your score is: \" + score);\n}", "playAction(name) {\n this.action(actions[name])\n }", "switchUser() {\n this.currentPlayer = this.currentPlayer == 1 ? 0 : 1;\n this.io.to(this.id).emit('g-startTurn', this.players[this.currentPlayer]);\n }", "function playerAttack(light, medium, heavy, magic)\n {\n if (light)\n {\n $(\"#attackLight\").click(function()\n {\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getLightWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getLightWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getLightDmgTotal()*doubleDamage*doubleLight*critical)));\n });\n }\n if (medium)\n {\n $(\"#attackMedium\").click(function()\n {\n mediumAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getMediumWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getMediumWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getMediumDmgTotal()*doubleDamage*doubleMedium*critical)));\n });\n }\n if (heavy)\n {\n $(\"#attackHeavy\").click(function()\n {\n heavyAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getHeavyWpn()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getHeavyWpn()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getHeavyDmgTotal()*doubleDamage*doubleHeavy*critical)));\n });\n }\n if (magic)\n {\n $(\"#attackMagic\").click(function()\n {\n magicAttack = false;\n if (player.getPower() === null)\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getMagic()+\"</div>\");\n else\n actionsArray.push(\"<div class='playerAction characterAction'>\"+player.getName()+\" attacks with \"+player.getPower()+\" \"+player.getMagic()+\"</div>\");\n // send damage to enemyDefend\n // normal damage multiplied by special rounds plus powerup\n enemyDefend((player.getPowerDmg()+(player.getMagicDmgTotal()*doubleDamage*critical)));\n });\n }\n }", "setUpStartingPlayerClick(event) {\n const { changeCurrentPlayer, setCurrentPlayer, opponentChoice } = this.player\n const icon = event.target\n const bottomIcons = Array.from(document.querySelectorAll(\".bottom-container__iconcont\"))\n this.removeSetTimeOuts()\n this.startGame()\n changeH4Text(\"Let\\'s see who is better\", \"25px\")\n if (icon.classList.contains(\"1\")) {\n setCurrentPlayer(\"O\")\n bottomIcons[1].style.color = \"#7cb0d4\"\n bottomIcons[0].style.color = \"black\"\n // Player 2 should start this time:\n if (this.gameType === \"humancomputer\") {\n // First we let the computer randomly choose a grid to speed up the game:\n this.takeTurn(opponentChoice(this.board.origBoard), this.player.currentPlayer)\n // Then it's the other player's turn:\n changeCurrentPlayer()\n }\n } else if (icon.classList.contains(\"0\")) {\n setCurrentPlayer(\"X\")\n bottomIcons[0].style.color = \"#7cb0d4\"\n bottomIcons[1].style.color = \"black\"\n }\n // Should run this regardless of which icon is clicked (currentPlayer will change anyway)\n if (this.gameType === \"computercomputer\") {\n // First the computer chooses a random grid, then it's the opponent's turn with the minimax algorithm.\n changeH4Text(\"Let\\'s see who is the better A.I...\", \"20px\")\n this.takeTurn(opponentChoice(this.board.origBoard), this.player.currentPlayer)\n changeCurrentPlayer()\n this.opponentsTurn(this.player.currentPlayer, 900)\n }\n }", "setup() {\n this.player.setup();\n }", "function readyToPlay() {\n\t\talert(\"Player X goes first\");\n\t\tfor (var i = 0; i < 9; i ++){\n\t\tself.gameObj.gameBoard[i].piece = \" \";\n\t\t}\t\n\t}", "function gameStart() {\n let random = Math.random();\n if (random > 0.5) {\n playerTurn = true;\n playerMessage.text('Your Turn');\n } else {\n playerTurn = false;\n loader.show();\n computerAction();\n }\n}", "function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}", "function useAction(slot:int){\r\n\tclickAudio.Play();\r\n\tGameStateScript.setClicked(slot);\r\n}", "function battleRound(){\n chooseAction1();\n chooseAction2();\n}", "function replayGame() {\n resetGame();\n togglePopup();\n }", "function actionOnClick ()\n{\n if (buttonAllowed) {\n // If both player cards were removed by clicking on them draw new cards\n if (playerCards.total == 0) {\n drawAndMoveCard(playerCards, 0);\n buttonAllowed = false;\n return;\n }\n for (let childIndex = playerCards.total - 1; childIndex >= 0; childIndex--) {\n let card = playerCards.children[childIndex];\n let tween = game.add.tween(card).to({ x : -300 }, 250, Phaser.Easing.Linear.None, true);\n tween.onComplete.add(function () { playerCards.remove(card); card.destroy(); }, this);\n }\n // Draw a new card after 300 milliseconds (shortly after moving the cards out of the scene)\n game.time.events.add(300, () => { drawAndMoveCard(playerCards, 0); }, this);\n buttonAllowed = false;\n }\n}", "_update() {\n console.log(\"UPDATE:\" + this.currentTurn);\n // on vérifie toujours en premier lieu l'état de validité\n if (!this.isValid()) {\n this._terminate();\n } else {\n\n switch (this.state) {\n case GameStates.Starting: {\n this._starting();\n }\n break;\n\n case GameStates.NextPlayer: {\n this._nextPlayer();\n }\n break;\n\n case GameStates.Picking: {\n this._picking();\n }\n break;\n\n case GameStates.Drawing: {\n this._drawing();\n }\n break;\n\n case GameStates.Ended: {\n this._ended();\n }\n break;\n\n case GameStates.Terminating: {\n this._terminate();\n }\n break;\n }\n\n }\n this.sendState();\n }" ]
{ "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\tmonitorThread = null;\n\t} else {\n\t\tconsole.err(\"ERR: Attempted to halt monitor thread but no instance existed.\")\n\t}\n}", "_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }", "stop() {\n if (!this.stopped) {\n for (let timeout of this.timeouts) {\n clearTimeout(timeout);\n }\n clearTimeout(this.mainLoopTimeout);\n this.stopped = true;\n }\n }", "function doTerminate()\n{ \n if (! initialized) return \"true\";\n \n var api = getAPIHandle();\n if (api == null)\n {\n message(\"Unable to locate the LMS's API Implementation.\\nTerminate was not successful.\");\n return \"false\";\n }\n else\n {\n // switch Terminate/LMSFinish method based on SCORM version\n if (versionIsSCORM2004 == true)\n {\n var result = api.Terminate(\"\");\n }\n else\n {\n var result = api.LMSFinish(\"\");\n } \n \n if (result.toString() != \"true\")\n {\n var err = ErrorHandler();\n message(\"Terminate failed with error code: \" + err.code);\n }\n }\n \n initialized = false;\n window.close();\n return result.toString();\n}", "async function terminateInstance(instanceId) {\n console.log('Terminating instance', instanceId);\n\n await ec2.terminateInstances({\n InstanceIds: [\n instanceId\n ]\n }).promise();\n\n console.log('Instance was terminated')\n}", "dispose () {\n\n for ( let taskWorker of this.workers.instances ) {\n\n taskWorker.terminate();\n\n }\n\n }", "function stepTerminateInstances(fill, callback) {\n if (fill.name === 'AWS') {\n ec2.terminate();\n } else {\n throw new Error('Unable to terminate instances of type [' + fill.name + ']: Unknown type!');\n }\n callback();\n}", "_stopListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.removeListener(eventName, this._terminate);\n });\n }", "stopExecution() {\n this.worker_.postMessage({'command': JobCommand.STOP});\n }", "clearInterval() {\n if (this.handle === undefined) {\n throw new Error('The interval must be running for it to be stoppped');\n }\n cancelAnimationFrame(this.handle);\n //clearInterval(this.handle)\n this.handle = undefined;\n }", "stop() {\n dbg.log0('Stopping hosted_agents');\n this._started = false;\n //stop all running agents\n _.each(this._started_agents, (agent, node_name) => this._stop_agent(node_name));\n }", "stop() {\n\n this._outterJobMap.values().forEach(job => {\n this.cancelJob(job);\n });\n\n this.info(\"JobService Stopped\")\n }", "function stopCountdown() {\n clearInterval(nIntervId);\n}", "function end_trial() {\n\n // kill any remaining setTimeout handlers\n jsPsych.pluginAPI.clearAllTimeouts();\n\n // gather the data to store for the trial\n var trial_data = {\n stimulus: trial.stimulus,\n rt: performance.now() - starttime\n };\n\n // clear the display\n display_element.innerHTML = '';\n\n // move on to the next trial\n jsPsych.finishTrial(trial_data);\n }", "close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }", "function teardownSession(data, callback) {\n\tlog(\"Terminating firefox (PID: \" + data.firefox_proc.pid + \")\");\n\tlog(\"Terminating VNC\");\n\tasync.waterfall([function(cb) {\n\t\tdata.firefox_proc.on('exit', function (code, signal) {\n\t\t\tcb(null); // TODO: when would an error happen?\n\t\t});\n\t\tdata.firefox_proc.kill('SIGINT');\n\t}, function(cb) {\n\t\tkillVNCserver(10, cb);\n\t}], function(err) {\n\t\tcallback(err);\n\t});\n}", "function stop() {\n testTransport.removeListener(\"close\", find);\n testTransport.close();\n }", "abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }", "function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}" ]
{ "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++;\n // Provide a function to call when the\n // slide animation is finished\n $(\"#q\" + currentQuestion).slideToggle(scrollDown);\n }\n }", "function startTutorial() {\n\t// May or may not be necessary\n\tgameType = 'tutorial';\n\tstartGame();\n\ttutorialInstructionIndex = -1;\n\tcallbackAfterMessage = nextTutorialMessage;\n\tnextTutorialMessage();\n}", "function onboardingFollowSubjectNextStepButton() {\n $(\"#onboarding-follow-subjects-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-subjects-modal\").remove();\n showOnboardingFollowInstitutionsStep(); // show the next step\n }", "function nextQuestion(){\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n if (q !== questions.length - 1){\n q++;\n showNextQA();\n } else {\n finalScore();\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n }\n}", "function onboardingFollowCoursesNextStepButton() {\n $(\"#onboarding-follow-courses-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-courses-modal\").remove();\n showOnboardingProfileStep(); // show the next step\n }", "function displayWaitingText() {\n var index = 0;\n var waitingMessages = [ 'Creating Your Station...',\n 'This Could Take Up To 30 secs...',\n 'So... uh....',\n 'Nice weather, huh?...',\n \" (fingers tapping...) \"];\n\n showNextMessage();\n \n function showNextMessage() {\n $scope.submitButtonInfo.text = waitingMessages[index];\n \n // iterate\n index++;\n if (index >= waitingMessages.length) {\n index = 0;\n }\n \n // set next message change\n submitButtonTextChangeTimeout = $timeout(function () {\n showNextMessage();\n }, 5000);\n }\n }", "function onboardingFollowInstitutionsNextStepButton() {\n $(\"#onboarding-follow-institutions-modal\").modal(\"hide\"); // hide the modal\n $(\"#onboarding-follow-institutions-modal\").remove();\n showOnboardingFollowCoursesStep(); // show the next step\n }", "function next(next_view_id, current_view_id) {\n //Hiding the current view\n $(current_view_id).hide();\n //Making the next view appear with a animation\n $(next_view_id).slideDown();\n}", "function nextWord(){\n currentWord = currentList.pop();\n $('#front').text(currentWord.nativeWord);\n setTimeout(function(){\n $('#back').text(currentWord.foreignWord);\n }, 500);\n $('#next-question').hide();\n $('#quiz-answer').show();\n $('.flashcard').toggleClass('flipped');\n}", "function showHintPage(hintPage, nextPage) {\n\n try\n {\n // show hint page\n $.mobile.changePage('#' + hintPage, {transition: \"flip\"});\n\n\n if (nextPage !== 'null') {\n // then show next page \n setTimeout(function () {\n $.mobile.changePage('#' + nextPage, {transition: \"none\"});\n }, 3000);\n }\n }\n\n catch (error) {\n console.log(\"An error has been occured! \" + error);\n }\n}", "function introResponse() {\n var commands = {\n \"What is it like being an AI\": function() {\n beingAnAI();\n },\n \"Are you a human\": function() {\n humanQuestion();\n },\n \"I don't want to be here\": function() {\n doNotWant();\n }\n };\n\n // can only say the phrases as they appear on screen and can only say one phrase\n annyang.start({\n autoRestart: false,\n continuous: false\n });\n // show the commands and let player say one when function is triggered\n annyang.addCommands(commands);\n $('#intro').show();\n}", "function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}", "function showFirstQuizQuestion(){\r\n\r\n\t// we want to remove the initial heading of lets play the quiz and make the screen blank for the \r\n\t//other HTML elements to start appearing and also the button\r\n\t$(\"#topheading\").hide();\r\n\t$(\"#proceed\").hide();\r\n\r\n}", "function nextButton() {\n $('#next').click(function() {\n // increment current question number\n questionNumber++;\n //check if we are out of questions\n if (questionNumber<QUIZ.length) {\n //remove old question\n $('.question-page').empty();\n $('.question-result').empty();\n buildCurrentQuestion();\n askQuestion();\n } else {\n finalResults();\n }\n });\n}", "function nextQuestion() {\n // clear out divs (image and win/loss/outoftime)\n console.log(questionIndex + \"entering\");\n\n questionIndex++;\n clearDivs();\n console.log(questionIndex + \"after\");\n asking();\n }", "function onLearnMoreClick(){\n $('#learnmoretext').slideDown();\n $('.learnmore').hide();\n }", "function showNextTail() {\n if (tailHistory.length == 0) {\n $(\"#no_tiles_msg\").hide();\n }\n if (tails.length > 0 || currentTailIdx < tailHistory.length - 1) {\n currentTailIdx += 1;\n if (currentTailIdx == tailHistory.length) { \n var newTail = popRandomTail();\n tailHistory.push(newTail);\n addTailToHistoryList(newTail);\n }\n showCurrTail();\n }\n}", "function setNextQuestion() {}", "function nextClicked() {\n if (currentFeed && currentItemIndex < currentFeed.items.size - 1) {\n currentItemIndex++;\n displayCurrentItem();\n }\n }" ]
{ "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 ' + currentName + ' to i32 ;cast i1 to i32' + LF();\n return castBlock; \n }\n\n /*\n if (currentType === 'i8*') {\n const castedName = nextTempName(lctx);\n const castBlock = TAB() + castedName + ' = or i32 255, 255 ;-- dummy value for casting i8* to i32 --' + LF();\n return castBlock;\n }\n */\n\n println('-- ERROR: unknown type in castToI32() ---');\n printObj(currentType);\n abort();\n}", "function toAInt(v) {\n\tif (!(v instanceof AInt))\n\t\treturn new AInt(v);\n\treturn v;\n}", "static int8(v) { return n(v, -8); }", "static uint32(v) { return n(v, 32); }", "get i32() { return new Int32Array(module.memory.buffer, this.ptr, this.len); }", "function INT(x) { return Math.floor(x) }", "function doubleInt (integer) {\n \n return (integer << 1)\n}", "static int64(v) { return n(v, -64); }", "static bytes1(v) { return b(v, 1); }", "static int48(v) { return n(v, -48); }", "static int24(v) { return n(v, -24); }", "static int208(v) { return n(v, -208); }", "static int128(v) { return n(v, -128); }", "static int88(v) { return n(v, -88); }", "function encode_int(v) {\n if (!(v instanceof BigInteger) ||\n v.compareTo(BigInteger.ZERO) < 0 ||\n v.compareTo(LARGEST_NUM_PLUS_ONE) >= 0) {\n throw new Error(\"BigInteger invalid or out of range\");\n }\n return intToBigEndian(v);\n }", "static int256(v) { return n(v, -256); }", "function changeBoolToInt(e){\n if(e===true){\n return 1\n } else {\n return 0\n }\n}", "static bytes32(v) { return b(v, 32); }", "function convertOneIndexToZeroIndex(indexToConvert) {\r\n return indexToConvert - 1;\r\n}", "static int176(v) { return n(v, -176); }" ]
{ "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('getAllMeetingDays() - Invalid Input: Not Wed or Sun') span2 = 7 - span; let counter = firstDay; result.push(counter); while (counter <= daysInMonth) { counter += span; if (counter > daysInMonth) break; result.push(counter); counter += span2; if (counter > days) break; result.push(counter); } return result; }
[ "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; i++) {\n next_time = start_time.clone()\n next_time.add(i, 'day')\n hours_list.push(next_time)\n\n }\n return hours_list\n}", "populateDaysInMonth() {\n var daysInMonth = [];\n //first day of this.state.monthNumber\n var date = new Date(this.state.year, this.state.monthNumber);\n while (date.getMonth() === this.state.monthNumber) {\n daysInMonth.push(new Date(date));\n //Increment to next day\n date.setDate(date.getDate() + 1)\n }\n return daysInMonth\n }", "function setupMonths(){\n for(var i = 0; i < months.length; i++){\n for(var x = months[i].firstDay; x < months[i].lastDay + months[i].firstDay; x++){\n months[i].days.push({cell: {}, todos: [], events:[]});\n }\n }\n}", "function getDaysInMonth()\n{\n var daysArray = new Array(12);\n \n for (var i = 1; i <= 12; i++)\n {\n daysArray[i] = 31;\n\tif (i==4 || i==6 || i==9 || i==11)\n {\n daysArray[i] = 30;\n }\n\tif (i==2)\n {\n daysArray[i] = 29;\n }\n }\n return daysArray;\n}", "function getCourseEventDays(meetings) {\n let meet = meetings.split(' ')[0];\n let days = [];\n for (let i = 0; i < daysOfWeek.length; i++) {\n if (meet.includes(daysOfWeek[i])) {\n days.push(translateDaysForIcs[daysOfWeek[i]]);\n }\n }\n return days;\n }", "function buildWeek(date, month, viewedMonth){\n var days = [];\n for (var i = 0; i < 7; i++) {\n days.push({\n name: date.format(\"dd\").substring(0, 2),\n number: date.date(),\n isCurrentMonth: date.month() === month.month(),\n isViewedMonth: date.month() === viewedMonth.month(),\n isToday: date.isSame(new Date(), \"day\"),\n date: moment(date, \"MM-DD-YYYY\"),\n transactions: applyTransactions(date),\n endOfDay: Math.round((calculateEndOfDay(date, viewedMonth) + 0.00001) * 100) / 100\n });\n\n if (date._d.toString() == moment().endOf('month').startOf('day')._d.toString() && date.month() == viewedMonth.month()){\n console.log('last day of the current month', days[days.length -1]);\n applyNextTotal(days[days.length -1])\n }\n\n date = date.clone();\n date.add(1, \"d\");\n }\n return days;\n }", "function getUpcomingDays(data, firstDay) {\r\n\t\tvar dates = data.map(function(e) { return dateFormat(e.date.month + \"/\" + e.date.day + \"/\" + e.date.year) });\r\n\t\tvar index = dates.indexOf(firstDay);\r\n\t\treturn data.slice(index, index+3);\r\n\t}", "function getByNowMonth(interviewees) {\n return interviewees[(new Date()\n .getMonth()) % interviewees.length]\n}", "function make_weekday() {\n today = new Date();\n new_array = [];\n loop_counter = 0;\n\n // gets all weekdays for the coming week in the order they appear\n while (loop_counter < 7) {\n new_day = new Date(today);\n new_day.setDate(new_day.getDate() + loop_counter);\n name_of_day = new_day.getDay();\n if (name_of_day == 0) name_of_day = 'SUN';\n if (name_of_day == 1) name_of_day = 'MON';\n if (name_of_day == 2) name_of_day = 'TUE';\n if (name_of_day == 3) name_of_day = 'WED';\n if (name_of_day == 4) name_of_day = 'THU';\n if (name_of_day == 5) name_of_day = 'FRI';\n if (name_of_day == 6) name_of_day = 'SAT';\n new_array.push(name_of_day);\n loop_counter++;\n }\n // returns an array of weekdays\n return new_array;\n}", "function buildTodayArray(events) {\n // Create Todays Date\n let today = new Date()\n let tomorrow = new Date\n tomorrow.setDate(tomorrow.getDate() + 1)\n console.log(tomorrow)\n let tomorrowDate = tomorrow.toISOString().split('T', 1)[0]\n console.log(tomorrowDate)\n let dayDate = today.toISOString().split('T', 1)[0]\n // events.forEach(console.log(events.startdate))\n\n //Find all objects in JSON with same date as today\n let todayArray = events.filter(function (e) { return e.startdate === dayDate })\n return todayArray;\n }", "function createDaysOfWeek() {\n\tconst daysOfWeek = [];\n\n\tconst startWeek = DateTime.local().startOf('week');\n\n\tfor (let i = 0; i < 7; i += 1) {\n\t\tdaysOfWeek.push({\n\t\t\tdate: startWeek.plus({ days: i }).toFormat('dd-MM-yyyy'),\n\t\t\tisActive: false,\n\t\t\tisCompleted: false,\n\t\t});\n\t}\n\n\treturn daysOfWeek;\n}", "function splitintoSeperateDays(array) {\n try {\n const temp = array.map(item => item['StartDate']);\n // unique days;\n const unique = [...new Set(temp)];\n const final = [];\n unique.forEach(item =>\n final.push(array.filter(obj => obj['StartDate'] === item)),\n );\n return final;\n } catch (err) {\n winston.error(err);\n }\n}", "function buildMonth(start, month){\n var done = false, date = start.clone(), monthIndex = date.month(), count = 0;\n monthArray = [];\n $scope.month = moment().month(start.month() +1).format('MMMM');\n var viewedMonth = moment().month(start.month() +1);\n $scope.viewedMonth = viewedMonth.month();\n while (!done) {\n monthArray.push({ days: buildWeek(date.clone(), month, viewedMonth) });\n date.add(1, \"w\");\n done = count++ > 2 && monthIndex !== date.month();\n monthIndex = date.month();\n }\n var filterForBadWeek = [];\n filterForBadWeek = _.filter(monthArray[0].days, {'number': 1 })\n\n if (filterForBadWeek.length == 0){\n monthArray.shift();\n }\n $scope.monthArray = monthArray;\n\n console.log('Currently viewed month Array', $scope.monthArray);\n\n }", "function DateTimeDayMonth() { }", "function getMonthlyHolidays() {\n calendarificURL = \"https://calendarific.com/api/v2/holidays?&api_key=\" + cAPIkey + \"&country=\" + countries[country].abbr + \"&year=2021&type=national,local,religious\";\n var trueMonths = [];\n $.ajax({\n url: calendarificURL,\n method: \"GET\"\n }).then(function (calendarResponse) {\n for (var m = 1; m < 13; m++) {\n for (var i = 0; i < calendarResponse.response.holidays.length; i++) {\n if (calendarResponse.response.holidays[i].date.datetime.month === m) {\n var index = m - 1;\n trueMonths.push((Object.keys(months)[index]));\n break;\n }\n }\n }\n var message1 = $(\"<p>\").text(\"There are no holidays in \" + country + \" in \" + month + \" in our database.\")\n var message2 = $(\"<p>\").text(country + \" has holidays in \" + trueMonths.join(\", \") + \".\")\n $(\"#messageDiv\").append(message1).append(message2);\n })\n}", "function setCalendarDayFills(weeksIntoFuture){\n\t\n\tvar daysInAdvance = weeksIntoFuture * 7;\n\t\n\tvar theDay = today.getDay();\n\t//theDay = 0; //Just for testing\n\t\n\t//Shift the days over so Monday is 0 instead of Sunday\n\ttheDay -= 1;\n\tif(theDay == -1){theDay = 6;}\n\t\n\t//Variables for fill\n\tvar fillMO = fillTU = fillWE = fillTH = fillFR = fillSA = fillSU = 0;\n\t\n\t//Variables for day numbers\n\tvar numMO = numTU = numWE = numTH = numFR = numSA = numSU = 0;\n\t\n\t//Set day fills and day numbers\n\tif(weeksIntoFuture == 0){\n\t\tfor(i=theDay;i<7;i++){\n\t\t\tif(dateSpan[i]){\n\t\t\t\tif(i == 0){\n\t\t\t\t\tfillMO = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 1){\n\t\t\t\t\tfillTU = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumTU = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 2){\n\t\t\t\t\tfillWE = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumWE = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 3){\n\t\t\t\t\tfillTH = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumTH = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 4){\n\t\t\t\t\tfillFR = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumFR = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 5){\n\t\t\t\t\tfillSA = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 432000000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumFR = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumSA = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 6){\n\t\t\t\t\tfillSU = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 518400000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 432000000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumFR = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumSA = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumSU = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//Gray out the past days\n\t\tswitch(theDay){\n\t\t\tcase 1: grayOutDays('mo'); break;\n\t\t\tcase 2: grayOutDays('mo','tu'); break;\n\t\t\tcase 3: grayOutDays('mo','tu','we'); break;\n\t\t\tcase 4: grayOutDays('mo','tu','we','th'); break;\n\t\t\tcase 5: grayOutDays('mo','tu','we','th','fr'); break;\n\t\t\tcase 6: grayOutDays('mo','tu','we','th','fr','sa'); break;\n\t\t\n\t\t}\n\t\t\n\t}else{\n\t\t//Recolor grayed out days\n\t\trecolorGrayDays();\n\t\t\t\n\t\t//Set day fills\n\t\tif((dateSpan[daysInAdvance-theDay]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillMO = (dateSpan[daysInAdvance-theDay].fill / dateSpan[daysInAdvance-theDay].capacity * 100);\n\t\t}else{fillMO = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+1]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillTU = (dateSpan[(daysInAdvance-theDay)+1].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillTU = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+2]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillWE = (dateSpan[(daysInAdvance-theDay)+2].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillWE = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+3]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillTH = (dateSpan[(daysInAdvance-theDay)+3].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillTH = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+4]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillFR = (dateSpan[(daysInAdvance-theDay)+4].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillFR = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+5]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillSA = (dateSpan[(daysInAdvance-theDay)+5].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillSA = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+6]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillSU = (dateSpan[(daysInAdvance-theDay)+6].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillSU = 0;}\n\t\t\n\t\t//Set day numbers\n\t\tnumMO = new Date(dateSpan[daysInAdvance-theDay].date).getDate();\n\t\tnumTU = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 86400000).getDate();\n\t\tnumWE = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 172800000).getDate();\n\t\tnumTH = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 259200000).getDate();\n\t\tnumFR = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 345600000).getDate();\n\t\tnumSA = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 432000000).getDate();\n\t\tnumSU = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 518400000).getDate();\n\t\t\n\t}\n\t\n\t//Use the results to animate the day fill divs\n\t$(\"#calendarDayFill-mo\").animate({height: fillMO + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-tu\").animate({height: fillTU + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-we\").animate({height: fillWE + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-th\").animate({height: fillTH + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-fr\").animate({height: fillFR + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-sa\").animate({height: fillSA + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-su\").animate({height: fillSU + \"%\"}, 1000, \"easeOutElastic\");\n\t\n\t//...and set the day numbers\n\t$(\"#calendarDayNumber-mo\")[0].innerHTML = numMO;\n\t$(\"#calendarDayNumber-tu\")[0].innerHTML = numTU;\n\t$(\"#calendarDayNumber-we\")[0].innerHTML = numWE;\n\t$(\"#calendarDayNumber-th\")[0].innerHTML = numTH;\n\t$(\"#calendarDayNumber-fr\")[0].innerHTML = numFR;\n\t$(\"#calendarDayNumber-sa\")[0].innerHTML = numSA;\n\t$(\"#calendarDayNumber-su\")[0].innerHTML = numSU;\n}", "function getMDays ( d ) {\n \tvar dateArr = [];\n \tvar date = d.toJSON().split(\"T\")[0].split(\"-\");\n \tvar dateStr;\n \tvar days = new Date(d.getUTCFullYear(),d.getUTCMonth()+1,0).getDate();\n \tfor(var i=1;i<days+1;i++) {\n \t\tvar t = i;\n \t\tif(i<10) {t = \"0\" + i;}\n \t\tdate[2] = t;\n \t\tdateStr = date.join('');\n \t\tdateArr.push({date: dateStr});\n \t}\n \treturn dateArr;\n }", "getFoodMonth(){\n let temp = [];\n let total = 0;\n let today= new Date();\n for(var i = 0; i< this.foodLog.length; i++){\n let then = this.foodLog[i].date;\n if(then.getFullYear() == today.getFullYear() && then.getMonth() == today.getMonth()){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }", "function days_this_month() {\n r = new Date()\n return daysInMonth(r.getMonth() + 1, r.getYear())\n}" ]
{ "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.append(hostLink);\n $(\"#infected_hosts\").append(hostDiv);\n\n payloads.forEach(async (payloadObject) => {\n const userPayloadsDiv = createUserPayloadsDiv();\n const userPayloadsLink = createUserPayloadsLink(payloadObject);\n\n userPayloadsDiv.append(userPayloadsLink);\n\n const payload = await getPayload(host, payloadObject['payload_id']);\n\n const payloadDataDiv = $(\"<pre class=\\\"payload\\\"></pre>\");\n payloadDataDiv.append(payload);\n const containerDiv = $(\"<div class=\\\"container\\\"></div>\");\n containerDiv.css(\"display\", \"none\");\n containerDiv.append(userPayloadsDiv);\n containerDiv.append(payloadDataDiv);\n hostDiv.append(containerDiv);\n });\n });\n }", "function defineHostOwnership(elementNode, hostNode, id) {\n if ( hostNode && hostNode !== elementNode ) {\n if ( !hostNode.id ) {\n hostNode.id = 'host_' + id\n }\n _.aria(elementNode, 'owns', hostNode.id)\n }\n}", "function createDeleteDiv(){\n // Create parent div for delete button\n deleteDiv = document.createElement(\"div\");\n deleteDiv.setAttribute(\"class\", \"delete-div\");\n // Add delete button in case user wishes to delete this item later.\n deleteButton = document.createElement(\"div\");\n deleteButton.setAttribute(\"class\", \"delete-button\");\n deleteText = document.createElement(\"p\");\n deleteText.setAttribute(\"class\", \"delete-text\");\n deleteText.innerHTML = \"Remove\";\n deleteButton.appendChild(deleteText);\n deleteDiv.appendChild(deleteButton);\n return deleteDiv\n }", "function dayContainer() {\n var div = document.createElement(\"div\");\n div.style.border = \"2px solid black\";\n div.style.color = \"white\";\n div.style.padding = \"4px\";\n div.href = \"/calendar/day\";\n days.push(div);\n return div;\n}", "function createServer(parentElement) {\n var serverBlock = document.getElementById('details_server');\n var newServerBlock = serverBlock.cloneNode(true);\n parentElement.appendChild(newServerBlock);\n}", "function create_canvas_div() {\n var mydiv = document.createElement(\"div\")\n mydiv.className += \" figure_div \"\n $('#figure_results').append(mydiv)\n return mydiv\n}", "function spawn() {\n\t$.ajax({\n\t\ttype: \"POST\",\n\t\turl: \"/spawn\",\n\t\tsuccess: function (data, result, jqXHR) {\n\t\t\tspawnDivData(data);\n\t\t}\n\t})\n}", "function createTaskDiv(task) {\r\n\r\n let taskDiv = $('<div/>', { class: 'task flex', id: task.taskid }) // contains the entire div for the task\r\n\r\n // create the SVGs by using the status of the tasks\r\n let taskDescriptionSpan = createTaskDescription(task.description);\r\n let checkmarkSVG = createCheckMarkSVG();\r\n let helpSVG = createHelpSVG(task.help, task.status);\r\n\r\n // add all the elements\r\n taskDiv.append(taskDescriptionSpan, checkmarkSVG, helpSVG);\r\n\r\n return taskDiv;\r\n}", "createContainer() {\n const existingContainer = document.querySelector('#bitski-dialog-container');\n if (existingContainer) {\n return existingContainer;\n }\n const container = document.createElement('div');\n container.id = 'bitski-dialog-container';\n document.body.appendChild(container);\n return container;\n }", "function createTitleElement(detailsDiv, url, title){\n\tvar controlDiv = $('<div id=\"titleLinkDiv\"></div>').appendTo(detailsDiv);\n\tvar fixedURL = \"'\" + url + \"'\";\n\t$('<button class=\"controlButtons titleLnk\" onclick=\"location.href=' + fixedURL + '\" alt=\"Play\">' + title + '</button>').appendTo(controlDiv);\n}", "function attachOnDOM(){\n\tdocument.getElementsByTagName('body')[0].appendChild(getComponent())\n}", "function createControlElement(detailsDiv, title, waveformURL, previewURL){\n\tvar controlDiv = $('<div id=\"controlDiv\"></div>').appendTo(detailsDiv);\n\t//create play stop and fav buttons and append to controlDiv\n\t$('<button class=\"controlButtons playIco\" onclick=\"playAudio(0)\" alt=\"Play\"><i class=\"fas fa-play\"></i></button>').appendTo(controlDiv);\n\t$('<button class=\"controlButtons stopIco\" onclick=\"stopAudio(0)\" alt=\"Stop\"><i class=\"fas fa-stop\"></i></button>').appendTo(controlDiv);\n\t$('<button class=\"controlButtons favIco\" onclick=\"favAudio()\" alt=\"Fav\"><i class=\"fas fa-star\"></i></button>').appendTo(controlDiv);\n\t//store variables in session - for use in favourite\n\tsessionStorage.setItem(\"title\", title);\n\tsessionStorage.setItem(\"image\", waveformURL);\n\tsessionStorage.setItem(\"sound\", previewURL);\n}", "function Host(props) {\n return __assign({ Type: 'AWS::EC2::Host' }, props);\n }", "function cargarDiv(origen, destino)\r\n{\r\n\t$.ajax(\r\n\t{\r\n\t\turl : origen,\r\n\t\tsuccess : function(data)\r\n\t\t{\r\n\t\t\t$('#' + destino).html(data);\r\n\t\t}\r\n\t});\r\n}", "function createH2Element(id, value, div) {\n let h2 = document.createElement('h2');\n h2.id = id;\n h2.append(value);\n \n //Append to div\n let divWrap = document.getElementById(div);\n divWrap.append(h2);\n}", "createEl(tag = 'div', props = {}, attrs = {}) {\n\t\tprops = assign({\n\t\t\tclassName: 'ntk-dialog'\n\t\t}, props);\n\t\t\n\t\tconst el = super.createEl(tag, props, attrs);\n\t\t\n\t\treturn el;\n\t}", "create() {\n this.children = { };\n this.container = document.createElement(\"div\");\n for (var key in this.data) {\n this.children[key] = interfaceUnit(this.data[key], this.container);\n }\n return this.container;\n }", "createHTMLElement(parent){\n let htmlElement=document.createElement(this.htmlTagName);\n this.parent=parent;\n this.parent.appendChild(htmlElement);\n this.htmlElementId=getUniqueId(parent,this.htmlTagName);\n htmlElement.id=this.htmlElementId;\n this.applyStyleToElement();\n widgets[this.htmlElementId]=this;\n }", "function createTutorialDiv (parent, id, templateId){\n // Create div element\n const tutorialDiv = document.createElement('div');\n // Assign id and class to div\n tutorialDiv.id = id;\n tutorialDiv.classList.add(\"help\");\n // Style div based on template\n const jqTemplate = $(\"#\" + templateId);\n const pos = jqTemplate.position();\n tutorialDiv.style.left = pos.left + \"px\";\n tutorialDiv.style.top = pos.top + \"px\";\n tutorialDiv.style.marginTop = jqTemplate.css('marginTop');\n tutorialDiv.style.height = jqTemplate.outerHeight() + \"px\";\n tutorialDiv.style.width = jqTemplate.outerWidth() + \"px\";\n tutorialDiv.tabIndex = 0;\n // Change the explanatory text showing when focus is changed\n tutorialDiv.onfocus = function(){\n setHelpClass(id + \"Text\");\n }\n\n // Add div to parent\n parent.appendChild(tutorialDiv);\n}" ]
{ "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 await m.emit('afterDelete', req, doc, options);\n }", "static async deleteOne(doc) {\n try {\n const modelName = this.name.toLowerCase();\n return db\n .collection(modelName)\n .doc(doc[\".key\"])\n .remove();\n } catch (error) {\n console.log(\"Error occured while performing operation\", error);\n }\n }", "async function deletePlanValidation(planId, userId) {\n\n try {\n\n await planConstraint(planId);\n await lockedConstraint(planId);\n await deleteConstraint(planId, userId);\n return \"valid\";\n\n } catch (err) {\n if (err.name === \"ConstraintViolation\") {\n return err;\n } else {\n throw err;\n }\n }\n\n}", "deleteRecord() {}", "function deleteYearSem(req , res , conn)\n{\n var body=req.body;\n body._id = ObjectId(body._id);\n conn.collection(\"yearsem\").deleteOne( {_id: body._id}, function( err, result ){\n if( err )\n {\n res.statusCode = 500;\n res.json({\"result\":err.message});\n }\n else\n {\n res.json({\"result\":\"deleted \" + result.deletedCount+ \" record \"});\n }\n } );\n \n}", "remove({ Meteor }, { _id }) {\n Meteor.call(\n 'documents.remove',\n {\n _id,\n }, (error) => {\n if (error) {\n Bert.alert(error.reason, 'danger');\n } else {\n Bert.alert('Document removed!', 'success');\n }\n },\n );\n }", "deleteRecord(store, type, record) {\n this.logToConsole(OP_DELETE_RECORD, [store, type, record]);\n let id = Ember.get(record, 'id');\n return this.asyncRequest(OP_DELETE_RECORD, type.modelName, id);\n }", "async function deleteDept(deptId) {\n //validates number of arguments\n if (arguments.length != 1) {\n throw new Error(\"Wrong number of arguments\");\n }\n //validates arguments type\n if (!deptId || typeof (deptId) != \"string\" || deptId.length == 0) {\n throw \"Invalid Department ID\";\n }\n let deletedDept = await getDeptById(deptId);\n const deptCollection = await dept();\n const removedDept = await deptCollection.removeOne({ _id: ObjectId(deptId) });\n\n if (!removedDept || removedDept.deletedCount == 0) {\n throw \"Could not remove Department\";\n }\n return deletedDept;\n}", "async delete() {\n await this.pouchdb.destroy();\n await this.database.removeCollectionDoc(this.dataMigrator.name, this.schema);\n }", "delete ({ commit, getters }, { processId, portId, id }) {\n return new Promise( (resolve, reject) => {\n // Try to send data on the server.\n apiPortData.delete( processId, portId, id ).then(response => {\n // console.log(\"PortData Store, 'delete' action, API response:\")\n // console.log(response)\n\n // Update port in the Store\n commit('delete', { id, parentId: processId })\n\n resolve(response)\n }).catch(error => {\n reject(error)\n })\n })\n }", "static deleteAction(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('document_documents', 'delete', kparams);\n\t}", "function deleteGrant(id) {\n return db(\"grants\").where({ id }).del();\n}", "function deleteCustomerType(axios$$1, customerTypeToken, force) {\n var query = '';\n if (force) {\n query += '?force=true';\n }\n return restAuthDelete(axios$$1, 'customertypes/' + customerTypeToken + query);\n }", "function realestateobject_delete(req, res, next) {\n console.log('Real estate object delete');\n\n RealEstateObjects.findByIdAndDelete(req.params.id)\n .then(realestateobject => {\n res.send(`realestateobject ${realestateobject} deleted!`);\n })\n .catch(error => next(error));\n}", "static async apiDeletePostit(req, res, next) {\n try {\n const postitId = req.query.id;\n console.log(postitId);\n const postitDelRes = await PostitsDAO.deletePostit(postitId);\n res.json({ status: \"Postit deleted successfully !\" });\n } catch (e) {\n res.status(500).json({ error: e.message });\n }\n }", "function delete_type(type_id, user_id, dry_run, force) {\n return type_info(type_id, user_id)\n .then(function(info) {\n if (dry_run) {\n return [info, null];\n }\n if (!force && (info.instance_count ||\n info.expected_by.permitted.length ||\n info.expected_by.not_permitted.length)) {\n throw deferred.rejected(JSON.stringify(info));\n }\n var q = {\n guid: info.guid,\n type: {id: \"/type/type\", connect: \"delete\"},\n \"/type/type/domain\": {id: info.domain.id, connect: \"delete\"},\n \"/dataworld/gardening_task/async_delete\": {value:true, connect:\"update\"}\n };\n if (info.key.length) {\n q.key = [{namespace:k.namespace, value:k.value, connect: \"delete\"} for each (k in info.key)];\n }\n if (info.expected_by.permitted.length) {\n q[\"/type/type/expected_by\"] = [{id: eb.id, connect: \"delete\"} for each (eb in info.expected_by.permitted)];\n }\n return freebase.mqlwrite(q)\n .then(function(env) {\n return env.result;\n })\n .then(function(result) {\n // cleanup result\n result.domain = result[\"/type/type/domain\"];\n result.expected_by = result[\"/type/type/expected_by\"];\n return [info, result];\n });\n });\n}", "async destroy ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n await tarefa.delete();\n }", "function deleteOne(req, res) {\n const id = req.params.applicantId;\n ApplicantModel.findByIdAndDelete(id, (err, applicant) => {\n if (err) throw err;\n if (applicant) {\n res.send({ success: true, message: 'successfully removed' });\n } else {\n res.send({ success: false, message: 'applicant does not exist' });\n }\n });\n}" ]
{ "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>${country}</li>`;\n });\n document.body.innerHTML = html;\n }, 1000 );\n}", "function showcity() {\n let CS = document.getElementById(\"coutriesSelect\");\n let selectedCountry = CS.options[CS.selectedIndex].innerHTML;\n let selectedIdCountry = CS.value;\n\n //in case to prevent double-click:\n if (selectedIdCountry == last_click) {\n return;\n }\n //set the last_click to prevent double-click on the save country...\n last_click = selectedIdCountry;\n\n get_data_countries(selectedIdCountry);\n }", "function showInfoCountry(result) {\n // On rend le tableau visible\n var table = document.getElementById(\"tableInfo\");\n table.style.display = \"initial\";\n \n // On met en titre du tableau le nom du Country\n var country = document.getElementById(\"title\");\n country.innerHTML = result.name;\n \n // On affiche les infos\n showInfo(result);\n}", "function update_city_options(country_name)\r\n\t{\r\n\t\t$('#billing-city').html(city_list_cache[country_name]);\r\n\t}", "function displayCountries(country) {\n document.getElementById(\"countryList\").innerHTML +=\n \"<option>\" + country + \"</option>\";\n }", "function countryChange() {\n country = document.getElementById(countryName + \"-select\").value;\n updateData();\n }", "function showcountries() {\r\nlet finland = new Destination(\"Finland\", \"Europe\", 5.5);\r\nlet southAfrica = new Destination(\"South Africa\", \"Africa\",55 );\r\nlet thailand = new Destination(\"Thailand\", \"Asia\", 68);\r\n let allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\n\r\ndocument.getElementById('country1').innerHTML = (finland.toString());\r\ndocument.getElementById('country2').innerHTML = (southAfrica.toString());\r\ndocument.getElementById('country3').innerHTML = (thailand.toString());\r\n\r\n}", "function getGoalsByCountry(){\n\t\tvar country = hashValue;\n\t\tcountry = country.charAt(0).toUpperCase() + country.substring(1);\n\t\tshotsPerCountry = _.where(data, {TEAM: country});\n\t\t$('h1#title').html('All of '+ country + '\\'s goals and shots at the 2014 World Cup mapped: click on the dots for more info')\n\t\t_.each(shotsPerCountry, populateGoals);\n\t}", "function searchForCountry() {\n header.innerHTML = country;\n fetchData(country);\n}", "function casesByCountry (){\n\n let today = dateToday();\n let endPoint = 'https://api.covid19tracking.narrativa.com/api/' \n let queryCountriesUrl = endPoint + today; \n let URL = {\n url: queryCountriesUrl,\n method: \"GET\" \n } \n\n // making request to pull all Covid data by countries\n $.ajax(URL).then(function(response){\n countriesData(response.dates[today].countries); \n });\n}", "function toggleCountries() {\n if (!countriesExpanded) {\n // open animation\n gsap.to('.country-options-wrapper', { duration: 0.5, height: 'auto' });\n gsap.to('.icon-countries-open-close', {\n rotation: 180,\n duration: 0.7,\n });\n if (analysisExpanded) toggleAnalysis();\n } else {\n // close animation\n gsap.to('.country-options-wrapper', { duration: 0.5, height: 0 });\n gsap.to('.icon-countries-open-close', {\n rotation: 0,\n duration: 0.7,\n });\n }\n setAnalysisExpanded(false);\n setCountriesExpanded(!countriesExpanded);\n }", "function showInitialCities() {\n Object.keys(INITIALCITIES).forEach(function(cityName) {\n displayTeleportCity(cityName);\n });\n }", "getCountries() {\r\n let domeinCountry = { name: \"\", times: 0 };\r\n let users = this.users;\r\n let topCountry = [];\r\n let countries = [];\r\n for (let i in users) {\r\n countries.push(this.users[i].country);\r\n }\r\n let refiendCountries = new Set(countries);\r\n countries = [...refiendCountries];\r\n countries.forEach(country => {\r\n topCountry.push({ name: country, times: 0 });\r\n });\r\n for (let x in topCountry) {\r\n users.map(user => {\r\n if (user.country === topCountry[x].name) {\r\n topCountry[x].times++;\r\n }\r\n });\r\n }\r\n for (let x in topCountry) {\r\n if (domeinCountry === undefined) {\r\n domeinCountry = {\r\n name: topCountry[x].name,\r\n times: topCountry[x].times\r\n };\r\n } else if (topCountry[x].times > domeinCountry.times) {\r\n domeinCountry = {\r\n name: topCountry[x].name,\r\n times: topCountry[x].times\r\n };\r\n }\r\n }\r\n return domeinCountry;\r\n }", "function getCountryFromApi(country) {\n if (country === \"faroe islands\") {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n throw new Error(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n }\n\n const url = `https://agile-oasis-81673.herokuapp.com/api/country/${country}`;\n\n request(url)\n .then((rawCountryData) => {\n let translateRes, geoCodeRes, timeZone1Res, timeZone2Res;\n\n let countryData = findCountry(rawCountryData, country);\n\n $(\"html\").removeClass(\"first-background\");\n $(\"html\").addClass(\"second-background\");\n\n const googleTranslatePromise = googleTranslateApi(countryData).then(\n (res) => {\n translateRes = res;\n }\n );\n\n const geoCodingPromise = geoCodeCapitalApi(countryData)\n .then((res) => {\n geoCodeRes = res;\n return timeZoneApi1(geoCodeRes);\n })\n .then((res) => {\n timeZone1Res = res;\n return timeZoneApi2(timeZone1Res);\n })\n .then((res) => {\n timeZone2Res = res;\n });\n\n Promise.all([googleTranslatePromise, geoCodingPromise]).then(() => {\n $(\"body\").addClass(\"centered\");\n let countryCapital = countryData.capital;\n let countryName = countryData.name;\n displayTimeResults(\n timeZone2Res,\n countryCapital,\n countryName,\n translateRes\n );\n restartButton();\n $(\"header\").addClass(\"hidden\");\n $(\"footer\").addClass(\"hidden\");\n });\n })\n .catch((err) => {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list! \" +\n err.message +\n \".\"\n );\n });\n}", "function getCountryNames(){\n for(let i = 0; i < country_info[\"ref_country_codes\"].length; i++){\n let country = country_info[\"ref_country_codes\"][i][\"country\"];\n countryNames.push(country);\n countryCodes[country] = country_info[\"ref_country_codes\"][i][\"alpha2\"];\n }\n}", "function showCountriesSelect(e) {\n select.innerHTML = '';\n if (e.currentTarget.value === 'Asia') {\n asia.map((val, i) => select.innerHTML += `<option value=\"${i}\">${val.name}</option>`)\n }\n else if (e.currentTarget.value === 'Europe') {\n europe.map((val, i) => select.innerHTML += `<option value=\"${i}\">${val.name}</option>`)\n }\n else if (e.currentTarget.value === 'Africa') {\n africa.map((val, i) => select.innerHTML += `<option value=\"${i}\">${val.name}</option>`)\n }\n else if (e.currentTarget.value === 'Americas') {\n americas.map((val, i) => select.innerHTML += `<option value=\"${i}\">${val.name}</option>`)\n }\n else {\n worldCorona.map((val, i) => select.innerHTML += `<option value=\"${i}\">${val.name}</option>`)\n }\n}", "function chooseCountry() {\n let firstDropdown = document.getElementById(\"countries\")\n let countryIndex;\n let countryName;\n firstDropdown.addEventListener(\"change\", function() {\n countryName = this.value\n let countries = covidData.countries\n for (let i = 0; i < countries.length; i++) {\n let country = countries[i]\n if (country === countryName) {\n countryIndex = i\n }\n }\n if (chart) {\n chart.destroy()\n }\n createBarGraph(countryIndex)\n displayTextData(countryName, countryIndex)\n })\n}", "async function callCountryData() {\n\n const response = await fetch('land.json')\n const countryData = await response.json()\n countryDropDownMenu(countryData);\n}" ]
{ "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 as lView[HOST] is null we know we are part of sub-template such as `*ngIf` lView = parent; } return lView[FLAGS] & 512 /* IsRoot */ ? null : lView[CONTEXT]; }
[ "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: PropsT) {\n const { children, targetRef, targetSelector } = props\n if (children) {\n return ReactDOM.findDOMNode(this._target)\n }\n if (targetRef) {\n return ReactDOM.findDOMNode(targetRef)\n }\n if (targetSelector) {\n return document.querySelector(targetSelector)\n }\n return null\n }", "elementFromNode(node) {\n let part = this.nodes2parts[node.uuid];\n // one of many hacks to handle circular constructs, this returns the ID for the initial block\n // which we assume is the circular block itself when given the id for the end cap.\n if (part === Layout.backboneEndCapId) {\n invariant(this.constructViewer.isCircularConstruct() && this.rootLayout, 'this should only occur in the root layout');\n return this.construct.components[0];\n }\n if (!part) {\n const nestedKeys = Object.keys(this.nestedLayouts);\n for (let i = 0; i < nestedKeys.length && !part; i += 1) {\n part = this.nestedLayouts[nestedKeys[i]].elementFromNode(node);\n }\n }\n return part;\n }", "getItem(component){\n while (component && component.$parent){\n if (component.isDraggable && component.dndModel){\n return component\n }else{\n component = component.$parent\n }\n }\n return null\n }", "getComponentType() {\n return utilities_1.getComponentInstanceTypeFromComponentName(this.constructor.getComponentName());\n }", "getPlayerComponent(uid) {\n const agoraPlayer = this.selectComponent(`#rtc-player-${uid}`);\n return agoraPlayer;\n }", "getContainer(component){\n if (!this.dataObject){\n return null\n }\n while (component && component.$parent){\n if (component.isNestable && component.dndModel && component.dndZone == this && !this.isSubset(component.dndModel,this.dataObject)){\n return component\n }else{\n component = component.$parent\n }\n }\n return null\n }", "getCardViewer(){\n for(const component of this.components){\n if(component instanceof CardViewer){\n return component;\n }\n }\n return false;\n }", "getElement(el) {\n return document.getElementsByClassName(el)[0];\n }", "function get_elem(target) {\n return document.querySelector(target);\n }", "getCurrentlySelectedComponent() {\n return simulationArea.lastSelected;\n }", "get element() {\n if (Screen.cache_.element === undefined) {\n Screen.cache_.element = document.getElementById(\"screen\");\n }\n return Screen.cache_.element;\n }", "getHoveredComponent() {\r\n let me = this;\r\n let hoveredComp = null;\r\n if (me.mousePos !== null && me.hoveredConn === null) {\r\n me.moduleController.activeModule.components.forEach((component) => {\r\n let mousePosReal = me.getRealCoords(me.mousePos);\r\n if (component.bounds.contains(mousePosReal.x, mousePosReal.y)) {\r\n hoveredComp = component;\r\n return false;\r\n }\r\n });\r\n }\r\n return hoveredComp;\r\n }", "function getComponentModel(params) {\n var componentInfo = params.componentName ? AppPlayer.Views.componentInfos[params.componentName] : null, bindingProperties = [], componentViewModel = AppPlayer.propertyVisitor(params.viewModel, function (context) {\n var value = context.value, propName = context.name, isEvent = false, result = value, fn;\n if (componentInfo && componentInfo.events) {\n isEvent = componentInfo.events.some(function (eventName) { return eventName === propName; });\n }\n if (isEvent) {\n fn = params.functions[value];\n var runContext = $.extend({}, params.runContext);\n result = function (e) {\n var event = e ? e.jQueryEvent : null;\n if (event && event.stopPropagation && params.componentName !== \"command\") {\n event.stopPropagation();\n }\n // TODO Pletnev Choose itemData or data depending on event and object\n if (e && (e.itemData || e.data)) {\n runContext.$data = e.itemData || e.data;\n }\n else {\n runContext.$data = params.runContext.$data;\n }\n return fn(runContext);\n };\n }\n else {\n if (typeof value === \"string\") {\n var val = value;\n if (val.indexOf(\"'\") === 0 && val.lastIndexOf(\"'\") === val.length - 1) {\n val = val.substr(1, val.length - 2);\n }\n result = AppPlayer.wrapModelReference(val, params.runContext, params.callerInfo);\n if (result !== val) {\n bindingProperties.push(context.path ? context.path + \".\" + propName : propName);\n }\n }\n }\n return result;\n });\n if (componentInfo && componentInfo.componentViewModel) {\n componentViewModel = componentInfo.componentViewModel(componentViewModel);\n }\n if (bindingProperties.length > 0) {\n componentViewModel[\"_bindingProperties\"] = bindingProperties;\n }\n return componentViewModel;\n }", "function getEl(id) {\n return document.getElementById(id) || document.getElementsByClassName(id)[0] || document.getElementsByTagName(id)[0] || null;\n}", "function getDivFromPiece(gamePiece) {\n let gpDiv = document.getElementById(`${gamePiece.row}:${gamePiece.col}`);\n return gpDiv;\n}", "function tocGetParent(element) {\n\tif(!element) {\n\t console.error('element to get parent of is null');\n\t return null;\n\t}\n\n\tconst elemParent = element.parentNode;\n\n\tif (!elemParent) {\n\t return null;\n\t}\n\n\tif (elemParent.tagName === 'UL') {\n\t return elemParent;\n\t} else {\n\t return tocGetParent(elemParent);\n\t}\n }", "function getElement(el) {\r\n if (typeof jQuery === 'function' && el instanceof jQuery) {\r\n return el[0];\r\n }\r\n return el;\r\n}", "getDropParent(mouseComponent) {\n if (!mouseComponent) return undefined;\n\n const { dragComponents } = this.state;\n let parent = mouseComponent;\n while (parent) {\n if (parent.canDrop(dragComponents)) return parent;\n parent = this.getElement(parent._parent);\n }\n }", "get icalComponent()\n\t{\n\t\t//dump(\"get icalComponent: title:\"+this.title+\", value:\"+this._calEvent.icalComponent);\n\t\treturn this._calEvent.icalComponent;\n\t}" ]
{ "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}}", "function evenDes() {\n\tfor (let i = 98; i >= 0; i--) {\n\t\tif (i % 2 === 0){\n\t\t\tconsole.log(i);\n\t\t}\n\t}\n}", "function numberIndexEven(array){\r\n \r\n return map(array,function(value, index){\r\n if((typeof(value)==='number')&& (index%2===0)){\r\n return value*2;\r\n }else{ return value}\r\n })\r\n}", "function summationEven(num){\n let n = 0;\n for(var i = 1; i<= num; i++){\n\n if(i % 2 == 0){\n n += i \n }\n }\n console.log(n) \n}", "function is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\n}", "function evenNumbers(numbers) {\n return numbers % 2 == 0;\n\n}", "function getEven1000() {\n var sum = 0;\n for (var i = 1; i <= 1000; i++) {\n if (i % 2 === 0) {\n sum += i;\n }\n }\n return sum;\n}", "function printOdds(n) { \n if(n%2 != 0)\n console.log(n)\n if(n == 0) return;\n\n printOdds(n-1)\n}", "function firstEvenNumbersSum(n) {\n if (n === 1) return 2;\n let nthEven = 2 * n;\n return nthEven + firstEvenNumbersSum(n - 1);\n}", "function randomNegativeEvenNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomNumber;\n }\n\n return randomNegativeEvenNumber();\n}", "function evenDigitsOnly(n) {\n const digits = n.toString().split(\"\");\n // console.log(digits);\n\n return digits.every((dig) => parseInt(dig) % 2 === 0);\n}", "function how_many_even(arr){\n count = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 0){\n count ++;\n }\n }\n return count;\n}", "function isEvenHackReactor(num) {\n if (num % 2 === 0){\n return true;\n } else if (num % 3 === 0) {\n return false;\n }\n}", "function how_many_even(arr){\n var count = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 0){\n count++;\n }\n }\n return count;\n}", "function nth(arr,num) {\n//Check to see if array is not too short \n if(arr.length <= 2){\n //If array is too short, return null \n return null; \n }\n //If array is long enough, return value of the proposed index\n return arr[arr.length-num]\n}", "function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}", "function isaNumberEven(array){\n\t\n}", "function oddOrEven(){\n for (let i = 0; i <= 20; i++) {\n if (i % 2 === 0) {\n console.log(i + ' is even');\n } else {\n console.log(i + ' is odd');\n }\n }\n}" ]
{ "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] && (today.getMonth()+1) == slicesstring && today.getFullYear() == stringYear){ tmp.push([data[0][3] + ": " + data[j][3] + "\t" + data[0][4] + ": " + data[j][4] + "\t" + data[0][5] + ": " + data[j][5] + '\n']); } } if (tmp.length === 0){ var emailAddress = data1[i][2] var message = dataconfig[1][1] + '\n' + 'No day off' var subject = dataconfig[1][0]; MailApp.sendEmail(emailAddress, subject, message) tmp =[]; } else{ var emailAddress = data1[i][2] var message = dataconfig[1][1] + '\n' + tmp var subject = dataconfig[1][0]; MailApp.sendEmail(emailAddress, subject, message) tmp =[]; } } }
[ "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(personalMail,subject,body,options);\n }", "function _daily_report_(ListName,Destination)\n{\n var listId = _list_by_name_(ListName);\n if (!listId) {\n Logger.log(\"No such list\");\n return;\n }\n var now = new Date();\n var lookBack2 = (now.getDay() == 1) ? -4 : -2;\n var later = _days_away_(1);\n var before = _days_away_(-1);\n var before2 = _days_away_(lookBack2);\n var i, n, c, t, tasks, items;\n var message = {\n to: Destination,\n subject: \"Daily Task Status: \"+ListName,\n name: \"Happy Tasks Robot\",\n htmlBody: \"<div STYLE=\\\"background-color:#88ffff;\\\"><table>\\n\",\n body: \"Task report for \"+now+\":\\n\"\n };\n //Logger.log(before.toISOString());\n // past week\n tasks = Tasks.Tasks.list(listId, {'showCompleted':true, 'dueMin':before.toISOString(), 'dueMax': now.toISOString()});\n items = tasks.getItems();\n message = _add_to_message_(message,items,\"Today's Scheduled Tasks\");\n tasks = Tasks.Tasks.list(listId, {'showCompleted':true, 'dueMin':before2.toISOString(), 'dueMax': before.toISOString()});\n items = tasks.getItems();\n message = _add_to_message_(message,items,\"Yesterday's Schedule\");\n message['htmlBody'] += _footer_text_();\n message['htmlBody'] += \"</table>\\n\";\n message['htmlBody'] += \"</div>\";\n //\n MailApp.sendEmail(message);\n Logger.log('Sent email:\\n'+message['body']);\n Logger.log('Sent email:\\n'+message['htmlBody']);\n}", "function sendApprovalResults(row, approval) {\n \n var approvedOrRejected = (approval.approveExpenseReport == \"Yes\") ? \"approved\" : \"rejected\";\n \n var mailsubject = \"mailto:teeyonglim@hotmail.com?subject=Expense%20Report%20ID%20\" + row.rowNumber;\n //original code had a strange way of specifying the approver. Approval email is actually used to pre-fill the approval form.\n //I changed it to use the requester email. So, iinstead of approval.emailAdress, I changed it to row.deaconEmailAddress.\n \n var message = \"<HTML><BODY>\"\n + \"<P>\" + row.department + \" deacon has \" + approvedOrRejected + \" your check/expense reimbursement request .\"\n + \"<P>Amount: $\" + row.amount\n + \"<P>Description: \" + row.descriptionOfItem\n + \"<P>Report Id: \" + row.rowNumber\n + \"<P>Deacon's comment: \" + (approval.comments || \"\")\n // + '<P>If your request is approved, please submit the receipt to our Treasurer <a href=\"'+mailsubject +'\">here</a>'\n + \"<P>\" + \"<br/>\"\n + \"</HTML></BODY>\";\n MailApp.sendEmail(row.emailAddress, \"GCCSD Check/Expense Approval Results\", \"\", {htmlBody: message});\n if (approval.approveExpenseReport == \"Yes\") {\n row.state = STATE_APPROVED;\n } else {\n row.state = STATE_DENIED;\n }\n}", "function reporting(area){\n var date = moment().startOf('week').toDate().toString().substring(0, 15);\n\n var district = Districts.findOne({ _id: area.district });\n var districtLeader = Areas.findOne({ _id: district.leader });\n var dlNumber = districtLeader.phone + \"@txt.att.net\";\n\n var progress = {};\n for (key in indicators){\n progress[key] = 0;\n }\n\n Kis.find({ areaId: area._id, date: date }).forEach(function(ki) {\n for (key in indicators){\n progress[key] += ki[key];\n }\n });\n\n //send area's numbers to district leader\n var subject = \"Weekly Actuals For \" + area.name;\n\n var message = \"\";\n for (key in progress){\n message = message + key + \":\" + progress[key] + \" \"\n }\n\n email(dlNumber, \"CFM OPPS <assistants@cfmopps.com>\", subject, message);\n}", "function emailSend(results) { // results is returned from getResults()\r\n for (let i = 0; i < results.length; i++) {\r\n let userInfo = results[i];\r\n\r\n // Send email to tutor about appointment\r\n let tutorEmailMsg1 = 'Hello, ' + userInfo[6] + '! ';\r\n let tutorEmailMsg2 = userInfo[0] + ' wants to be tutored by you in ' + userInfo[5] + '. ';\r\n let tutorEmailMsg3 = userInfo[0] + ' is in grade ' + userInfo[2] + ' and goes to ' + userInfo[1] + '. ';\r\n let tutorEmailMsg4 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let tutorEmailMsg5 = 'Here is some information they added about their appointment: ' + userInfo[7] + '.';\r\n let tutorEmailSubject = 'Your Tutoring Appointment!';\r\n let tutorEmailMessage = tutorEmailMsg1 + tutorEmailMsg2 + tutorEmailMsg3 + tutorEmailMsg4 + tutorEmailMsg5;\r\n MailApp.sendEmail(userInfo[8], tutorEmailSubject, tutorEmailMessage);\r\n\r\n // Send email to student about appointment\r\n let studentEmailMsg1 = 'Hello, ' + userInfo[0] + '! ';\r\n let studentEmailMsg2 = 'You are going to be tutored by ' + userInfo[6] + '! ';\r\n let studentEmailMsg3 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let studentEmailMsg4 = 'Here is the information you added about your appointment: ' + userInfo[7] + '.';\r\n let studentEmailSubject = 'Your Tutoring Appointment!';\r\n let studentEmailMessage = studentEmailMsg1 + studentEmailMsg2 + studentEmailMsg3 + studentEmailMsg4;\r\n MailApp.sendEmail(userInfo[4], studentEmailSubject, studentEmailMessage);\r\n }\r\n}", "function sendEmail(listingInfo) {\n var footer = '<hr>' +\n var imageDiv = listingInfo.ImageUrl ? '<img src=\"' + listingInfo.ImageUrl + '\" alt=\"' + listingInfo.Title + '\" width=\"128\">' :\n '';\n var emailTemplate = listingInfo.Description + '<br>' +\n listingInfo.Location + '<br>' +\n listingInfo.Date + '<br>' +\n '<br>' +\n imageDiv +\n '<br><hr><br>' +\n 'Email: <a href=\"mailto:' + listingInfo.ID + '@posts.freecycle.org?subject=' + listingInfo.Title + ' posted to Freecycle\" target=\"_blank\">Reply by email</a><br>' +\n 'Url: <a href=\"' + listingInfo.PostUrl + '\" target=\"_blank\">Link</a>' +\n '<hr>' +\n footer;\n var subject = '[' + contextValues.sheetName + '] ' + listingInfo.Title + ' (' + listingInfo.Location + ')';\n\n\n // Get information from TotalSavings tab\n var email = MailApp.sendEmail({\n to: myEmail,\n subject: subject,\n htmlBody: emailTemplate,\n });\n}", "function sendemail(){\t\n\t\n\t\t// make ajax request to post data to server; get the promise object for this API\n\t\tvar request = WmsPost.newAjaxRequest('/wms/x-services/email/producer', formToJSON());\n\t\n\t\t// register a function to get called when the data is resolved\n\t\trequest.done(function(data,status,xhr){\n\t\t\t//console.log(\"Email sent successfully!\");\n\t\t\tlocation.href = \"emailthankyou.html\";\n\t\t});\n\n\t\t// register the failure function\n\t\trequest.fail(function(xhr,status,error){\n\t\t\t//console.error(\"The following error occured: \"+ status, error);\n\t\t\talert(\"Problem occured while sending email: \" + error);\n\t\t});\n\n\t}", "function _sendEmail() {\n\t\t\t}", "function onReportOrApprovalSubmit() {\n // This is the Expense Report Spreadsheet\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheets()[0];\n\n var currentTimeStamp = new Date();\n \n // Also open the Approvals Spreadsheet\n var approvalsSpreadsheet = SpreadsheetApp.openById(APPROVALS_SPREADSHEET_ID);\n var approvalsSheet = approvalsSpreadsheet.getSheets()[0];\n\n // Fetch all the data from the Expense Report Spreadsheet\n // getRowsData was reused from Reading Spreadsheet Data using JavaScript Objects tutorial\n var data = getRowsData(sheet);\n\n // Fetch all the data from the Approvals Spreadsheet\n var approvalsData = getRowsData(approvalsSheet);\n\n // For every expense report\n for (var i = 0; i < data.length; ++i) {\n var row = data[i];\n \n row.rowNumber = i + 2;\n if (!row.state) {\n // This is a new Expense Report.\n // Email the deacon to request his approval.\n // Lookup deacon email address based on department selected.\n row.deaconEmailAddress = lookupDeaconEmail(row);\n sendReportToManager(row);\n // Update the state of the report to avoid email sending multiple emails\n // to managers about the same report.\n sheet.getRange(row.rowNumber, COLUMN_STATE).setValue(row.state);\n //update the deaconEmailAddress cell with lookup email. Essentially overriding the value the user entered.\n sheet.getRange(row.rowNumber, COLUMN_DEACONEMAIL).setValue(row.deaconEmailAddress);\n } else if (row.state == STATE_MANAGER_EMAIL) {\n // This expense report has already been submitted to a manager for approval.\n // Check if the manager has accepted or rejected the report in the Approval Spreadsheet.\n for (var j = 0; j < approvalsData.length; ++j) {\n var approval = approvalsData[j];\n if (row.rowNumber != approval.expenseReportId) {\n continue;\n }\n // Email the member to notify him/her of the Deacon's decision about the Check or Expense Reimbursement Request.\n sendApprovalResults(row, approval);\n sendApprovalResultsTreasurer(row, approval);\n \n // Update the state of the report to APPROVED or DENIED\n sheet.getRange(row.rowNumber, COLUMN_STATE).setValue(row.state);\n break;\n }\n \n \n // Check to see how long the state has remained in STATE_MANAGER_EMAIL\n // After 3 days, the manager will be sent the approval request reminder \n \n if (elapseTimeInDays(row)>2){\n // reset the time stamp so that manager won't be receiving constant stream of approval reminders.\n // Remember that reminders will not stop until approval is given or denied.\n // obviously, we can make it simple and just use a counter to keep state of reminders as REMINDER_ONE; REMINDER_TWO and so on.\n sheet.getRange(row.rowNumber, COLUMN_TIMESTAMP).setValue(currentTimeStamp);\n \n sendReportToManagerReminder(row); //remind manager to approve\n \n }\n }\n }\n}", "function selfEvalEmail(email, displayName, employee_email) {\n const mailOptions = {\n from: `${APP_NAME} <noreply@firebase.com>`,\n to: email\n };\n\n // The user subscribed to the newsletter.\n mailOptions.subject = `Autoevaluación de ${employee}`;\n mailOptions.text = `Hola ${displayName || ''}, ${employee} envió su autoevaluación del período .\n Puedes revisar esta y todas las otras en https://evaluacion-personal.firebaseapp.com.\n - ${APP_NAME}`;\n return mailTransport.sendMail(mailOptions).then(() => {\n console.log('New notice email sent to:', email);\n });\n}", "function sendEmailToHR(){\n var sheet = SpreadsheetApp.getActiveSpreadsheet();\n callSheetConfig();\n var emailAddress = datainit[1][2];\n var message = dataconfig[1][1] + \"\\n\" + sheet.getUrl() \n var subject = dataconfig[1][0];\n MailApp.sendEmail(emailAddress, subject, message);\n}", "function findUsersAndSend(maxDeliveries) {\n console.log('Starting incident and health notification process.');\n const usersInterested = UserProfiles.find({ 'notification_preferences.max_per_day': maxDeliveries }).fetch();\n console.log(' Users requesting notification:', _.map(usersInterested, user => user.username));\n const startTime = (maxDeliveries === 'once a day') ?\n Moment().subtract(1, 'day').format('LLLL') :\n Moment().subtract(1, 'hour').format('LLLL');\n\n // Now loop through all users desiring notifications, and compose and send the email(s).\n _.forEach(usersInterested, user => {\n const notifications = Notifications.find({ username: user.username, delivered: false }).fetch();\n const incidentReport = Incidents.getIncidentReport(startTime.valueOf());\n // only sends out an email if user has undelivered notifications\n console.log('User, Notifications, Incidents: ', user.username, notifications.length, incidentReport.totalIncidents);\n if ((notifications.length > 0) || (incidentReport.totalIncidents > 0)) {\n const contactEmails = UserProfiles.getContactEmails(user._id);\n const services = extractServicesFromNotifications(notifications);\n const downTotal = notifications.length;\n const incidentTotal = incidentReport.totalIncidents;\n const classifications = incidentReport.classifications;\n const locations = incidentReport.locations;\n sendEmail(contactEmails, startTime, services, downTotal, incidentTotal, classifications, locations);\n Notifications.updateDeliveredStatus(notifications);\n }\n });\n}", "function paid_teams_notification ()\n{\n\tvar arrayLength = L_paid_teams.length;\n\tif (arrayLength==0)\n\t{\n\t\tL_email_html += \"<b>No teams updated in database paid</b><br><br>\";\n\t}\n\t\n\t// else output the paid teams info\n\telse\n\t{\n\t\tfor (var i=0; i< arrayLength; i++) \n\t\t{\n\t\t\t// get team code\n\t\t\tvar team_code = L_paid_teams[i]; \n\t\n\t\t\t// find the team in the database \n\t\t\tvar found = 0;\n\t\t\tfor (var iteam=0; iteam<G_team_database.length; iteam++)\n\t\t\t{\n\t\t\t\tif (G_team_database[iteam][\"Team_Code\"]==team_code)\n\t\t\t\t{\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t} \n\t\t\t}\n\t\t\tif (found==0) \n\t\t\t{\n\t\t\t\talert (\"Bad error .. new_team_notification - team not found in database\");\n\t\t\t\tXreturn();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar team_index = iteam;\n\t\n\t\t\tL_email_html += \"<b>\" + \"Team \" + team_code + \" updated in database as paid\" + \"</b><br><br>\";\n\t\t\tL_email_html += \" Team Name: \" + G_team_database[team_index][\"Team_Name\"] + \"<br>\";\n\t\t\tL_email_html += \" Ordered By Name: \" + G_team_database[team_index][\"Ordered_By\"] + \"<br>\";\n\t\t\tL_email_html += \" Email: \" + G_team_database[team_index][\"Email\"] + \"<br>\";\n\t\t\tL_email_html += \" Address: \" + G_team_database[team_index][\"Address\"] + \"<br>\";\n\t\t\tL_email_html += \" Mobile Phone: \" + G_team_database[team_index][\"Tel_Mobile\"] + \"<br>\";\n\t\t\tL_email_html += \" Landline Phone: \" + G_team_database[team_index][\"Tel_Landline\"] + \"<br><br>\";\n\t\t}\n\t}\n}", "function main() {\n \n \t//Step 1: Add Email\n\tvar recipient = \"peterstavrop@gmail.com\";\n \n \t//Step 2: Change Subject Line\n\tvar subject = \"Add Subject Line Here\";\n \n\tvar body = AdWordsApp.currentAccount().getName() + \" Paid Search Email \\n\";\n \n \t//Step 3: Add Text to Email Body\n \tbody = body + \"Add Text Here\";\n\n\tMailApp.sendEmail(recipient, subject, body);\n\t\n}", "function sendEmail() {\n const mailOption = {\n to: toEmail,\n from: fromEmail,\n subject: `Change detected in ${urlToCheck}`,\n html: `Change detected in <a href=\"${urlToCheck}\"> ${urlToCheck} </a> `,\n };\n transporter.sendMail(mailOption, function (error, info) {\n if (error) {\n console.log(error);\n } else {\n console.log('Email sent: ' + info.response);\n }\n });\n}", "function assignDisplayNextEmail() {\n const actionItemsCountElement =\n document.getElementById('assign-suspected-action-items');\n const subjectLineElement = document.getElementById('assign-subject');\n\n actionItemsCountElement.innerText = actionableEmails.length;\n if (actionableEmails.length === 0) {\n subjectLineElement.innerText = '';\n disableAssignAcceptRejectButtons();\n return;\n }\n\n subjectLineElement.innerText =\n `(From: ${actionableEmails[0].sender}, ` +\n `Priority: ${actionableEmails[0].priority}) ` +\n `${actionableEmails[0].subject}`;\n}", "function new_teams_notification ()\n{\n\tvar arrayLength = L_new_teams.length;\n\tif (arrayLength==0)\n\t{\n\t\tL_email_html += \"<b>No new teams added to database</b><br><br>\";\n\t}\n\t\n\t// else output the new teams info\n\telse\n\t{\n\t\tfor (var i=0; i<arrayLength; i++) \n\t\t{\n\t\t\t// get team code\n\t\t\tvar team_code = L_new_teams[i];\t \n\t \n\t\t\t// find the team in the database \n\t\t\tvar found = 0;\n\t\t\tfor (var iteam=0; iteam<G_team_database.length; iteam++)\n\t\t\t{\n\t\t\t\tif (G_team_database[iteam][\"Team_Code\"]==team_code)\n\t\t\t\t{\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t} \n\t\t\t}\n\t\t\tif (found==0) \n\t\t\t{\n\t\t\t\talert (\"Bad error .. new_team_notification - team not found in database\");\n\t\t\t\tXreturn();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar team_index = iteam;\n\t\n\t\t\tif (G_team_database[team_index][\"Payment_Status\"]==\"Paid\") \n\t\t\t{\n\t\t\t\tL_email_html = L_email_html + \"<b>\" + \"New Team \" + team_code + \" added to database as Paid\" + \"</b><br><br>\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tL_email_html = L_email_html + \"<b>\" + \"New Team \" + team_code + \" added to database as Unpaid\" + \"</b><br><br>\";\n\t\t\t}\n\t\t\tL_email_html += \" Team Name: \" + G_team_database[team_index][\"Team_Name\"] + \"<br>\";\n\t\t\tL_email_html += \" Ordered By Name: \" + G_team_database[team_index][\"Ordered_By\"] + \"<br>\";\n\t\t\tL_email_html += \" Email: \" + G_team_database[team_index][\"Email\"] + \"<br>\";\n\t\t\tL_email_html += \" Address: \" + G_team_database[team_index][\"Address\"] + \"<br>\";\n\t\t\tL_email_html += \" Mobile Phone: \" + G_team_database[team_index][\"Tel_Mobile\"] + \"<br>\";\n\t\t\tL_email_html += \" Landline Phone: \" + G_team_database[team_index][\"Tel_Landline\"] + \"<br><br>\"\n\t\t}\n\t}\n}", "function send_day_3_emails(){\n\n //console.log(\"Inside the day3 function\");\n\n PA.find({\"createdate\":{\"$gte\":day3Date,\"$lt\":day2Date}}, function(err, user) {\n\n\tconsole.log(\"Sending day3 emails\");\n\n\n if (err){\n console.log(\"Cannot find the users\");\n }else{\n\n console.log(\"Number of Users\", user.length);\n\n for (i=0; i<user.length; i++){\n\n //set up email content for day3 users\n const data = {\n from: 'Curovate <info@curovate.com>',\n to: 'taikunzhang581@gmail.com',\n subject: user[i].firstname + \", take advantage of Curovate’s ACL recovery tools! Watch video guided exercises, measure your knee extension, and track your progress during your ACL recovery\",\n template: 'day3email',\n \"o:tracking\": 'yes',\n \"o:tag\" : ['Day3emailA'],\n };\n mg.messages().send(data, function (error, body) {\n //console.log(body);\n });\n }\n }\n });\n}", "function send_day_7_emails(){\n\n // console.log(\"Inside the day7 function\");\n\n PA.find({\"createdate\":{\"$gte\":day7Date,\"$lt\":day6Date}}, function(err, user) {\n\n\tconsole.log(\"Sending day7 emails\");\n\n\n if (err){\n console.log(\"Cannot find the users\");\n }else{\n\n console.log(\"Number of Users\", user.length);\n\n for (i=0; i<user.length; i++){\n\n //set up email content for day7 users\n const data = {\n from: 'Curovate <info@curovate.com>',\n to: 'taikunzhang581@gmail.com',\n subject: user[i].firstname + \", join the Curovate family and complete your 6 month ACL recovery journey!\",\n template: 'day7email',\n \"o:tracking\": 'yes',\n \"o:tag\" : ['Day7emailA'],\n };\n mg.messages().send(data, function (error, body) {\n //console.log(body);\n });\n }\n }\n });\n}" ]
{ "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) { return n(v, -64); }", "function largest_length(num)\n {\n count = 0;\n while(num > 0)\n {\n num = Math.floor(num/10);\n count++;\n }\n return count;\n }", "function expandIntegral(num) {\n return [...String(num)].reverse()\n .map((elem, index) => elem * 10 ** index)\n .filter((elem) => elem)\n .reverse()\n .filter(isNotZero);\n}", "function CSng(num) {\n var dec=7;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}", "static int160(v) { return n(v, -160); }", "function invers(numar) {\n let inv = 0;\n let nr = numar;\n let rest = 0;\n while (nr != 0) {\n rest = nr % 10;\n inv = inv * 10 + rest;\n nr = (nr - rest) / 10;\n }\n return inv;\n}", "static int144(v) { return n(v, -144); }", "function update_counts (n, s) {\n digits = PiMill.get_digits(n, s);\n n = digits.length; // In case we went past the end\n for (var i = 0; i < n; i++) {\n digit_counts[digits.charAt(i)]++;\n }\n return n;\n }", "function xLog(vMin, vMax, xSize, v) {\n\tif (v >= vMin && v <= vMax) {\n\t\tif (vMin > 0) {\n\t\t\treturn Math.log(v / vMin) / Math.log(vMax / vMin) * xSize;\n\t\t} else {\n\t\t\treturn Math.log(v) / Math.log(vMax) * xSize;\n\t\t}\n\t} else {\n\t\treturn 0;\n\t}\n}", "function nbDig(n, d) {\n let res = 0;\n for (let g = 0; g <= n; g++) {\n let square = (g * g + \"\").split(\"\");\n square.forEach((s) => s == d ? res++ : null)\n } return res;\n}", "static uint144(v) { return n(v, 144); }", "static int128(v) { return n(v, -128); }", "function babbage() {\n const endDigits = 269696;\n let num = Math.ceil(Math.sqrt(endDigits));\n\n while (num * num % 1000000 !== endDigits) {\n num += 2;\n }\n\n return num;\n}", "function divInt_(x,n) {\r\n var i,r=0,s;\r\n for (i=x.length-1;i>=0;i--) {\r\n s=r*radix+x[i];\r\n x[i]=Math.floor(s/n);\r\n r=s%n;\r\n }\r\n return r;\r\n }", "static int120(v) { return n(v, -120); }" ]
{ "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 ) { finalTime.textContent = minutesTimer + ":0" + secondsTimer; } else { finalTime.textContent = minutesTimer + ":" + secondsTimer; } finalMoves.textContent = moveCounter; finalStars.textContent = starCount; }
[ "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 = \"Congratulations! You won!\";\n\t\tdocument.getElementById(\"cancel\").style.display = \"none\";\n\t\tdocument.getElementById(\"restart-confirm\").innerHTML = \"Start new game\";\n\t\tgamesWon = gamesWon + 1;\n\n\t} else if (arguments[0] == \"youLost\") {\n\t\tdocument.getElementById(\"end-game-msg\").firstChild.innerHTML = \"You lost!\";\n\t\tdocument.getElementById(\"cancel\").style.display = \"none\";\n\t\tdocument.getElementById(\"restart-confirm\").innerHTML = \"Start new game\";\n\t} else {\n\t\tdocument.getElementById(\"end-game-msg\").firstChild.innerHTML = \"Are you sure you want to abandon game and restart? \";\n\t\tdocument.getElementById(\"cancel\").style.display = \"\";\n\t\n\t} \n\tdocument.getElementById(\"game-time\").innerHTML = timer();\n\tdocument.getElementById(\"game-moves\").innerHTML = \"Game moves \" + moves + \" out of \" + maximumMoves;\n\tdocument.getElementById(\"games-won\").innerHTML = \"Games won \"+ gamesWon + \" out of 5\";\n\tclearInterval(myTimer);\n\t\t\n\tdocument.getElementById(\"endGame\").showModal();\n\t}", "checkWinCondition() {\n if (this.y === -11) {\n setTimeout(function() {\n player.resetPlayer();\n }, 1000);\n\n modal.style.display = \"block\";\n startModal.style.display = \"none\";\n winModal.style.display = \"block\";\n span.onclick = () => modal.style.display = \"none\";\n window.onclick = function (event) {\n if (event.target === modal) {\n modal.style.display = 'none';\n }\n };\n }\n }", "function displayWin (condition) {\n if (condition < 2) {\n boardScreen.style.display = 'none';\n winScreen.style.display = '';\n winScreen.classList.remove('screen-win-one');\n winScreen.classList.remove('screen-win-two');\n winScreen.classList.remove('screen-win-tie');\n if (condition === 1) {\n winScreen.classList.add('screen-win-one');\n message.textContent = `Player 1: ${game1.player1} Wins!`\n } else if (condition === -1) {\n winScreen.classList.add('screen-win-two');\n message.textContent = `Player 2: ${game1.player2} Wins!`\n } else {\n winScreen.classList.add('screen-win-tie');\n message.textContent = `Tie Game!`\n }\n }\n }", "function renderWinModal(scoreboard)\n{\n // Create a variable that'll store the modal div.\n const modal = document.querySelector(\".modal\");\n\n // Render the win modal.\n modal.innerHTML = `\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <a href=\"about.html\" class=\"close\">&times;</a>\n <h2>You Won!</h2>\n </div>\n <div class=\"modal-body\">\n <p>\n Congrats on beating the CPU! Click the button below to play again, or\n click the close button above to load the About page. \n </p>\n </div>\n <div class=\"modal-footer\">\n <button id=\"retry-btn\" class=\"btn modal-btn\">Play Again</button>\n </div>\n </div>`;\n modal.style.display = \"block\";\n\n /*\n Add an event listener to the retry button that'll call resetScoreboard(scoreboard)\n and hide the modal.\n */\n document.querySelector(\"#retry-btn\").addEventListener(\"click\", () => {\n resetScoreboard(scoreboard);\n modal.style.display = \"none\";\n })\n}", "function win() {\n modal.style.display = \"block\";\n}", "function winGame() {\n flashColor();\n counter.innerHTML = \"GZ!\";\n on = false;\n win = true;\n}", "function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}", "function winScreen() {\n\t\n\tPhaser.State.call(this);\n\t\n}", "function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\n}", "function showWinMessage() {\n playerMoney += winnings;\n win.text = winnings;\n resetFruitTally();\n checkJackPot();\n}", "function winOrLose() {\n if (playerScore === randomNum) {\n winsCounter++;\n $(\"#wins\").html(\" \" + winsCounter);\n startGame();\n } else if (playerScore > randomNum) {\n lossCounter++;\n $(\"#losses\").html(\" \" + lossCounter);\n startGame();\n }\n }", "function isGameOver(){\n if (player1.health <= 0){\n player1.health = 0;\n $( \".fightButton1\" ).css( \"display\", \"none\" );\n $( \".fightButton2\" ).css( \"display\", \"none\" );\n displayStats(player1);\n // timeout used so the health can be seen before the modal box\n setTimeout(\n function(){ \n background.pause();\n horn.play();\n celebrate.play();\n document.getElementById(\"match-winner\").innerHTML = \"Loki, the god of mischief\";\n document.getElementById(\"winner-img\").src =\"images/loki.png\";\n document.getElementById(\"winner-gif\").src = \"images/fireworks.gif\"\n endModal.style.display = \"block\" ;\n }, \n 800);\n }\n if (player2.health <= 0){\n player2.health = 0;\n $( \".fightButton1\" ).css( \"display\", \"none\" );\n $( \".fightButton2\" ).css( \"display\", \"none\" );\n displayStats(player2);\n setTimeout(\n function(){ \n background.pause();\n horn.play();\n celebrate.play();\n document.getElementById(\"match-winner\").innerHTML = \"Thor, son of Odin\";\n document.getElementById(\"winner-img\").src = \"images/Thor.png\";\n document.getElementById(\"winner-gif\").src = \"images/giphyThunder.gif\";\n endModal.style.display = \"block\";\n }, \n 800);\n }\n }", "function advanceGameDialogue (slot) {\n players[slot].current++;\n \n /* update dialogue */\n $gameDialogues[slot-1].html(players[slot].state[players[slot].current].dialogue);\n \n /* determine if the advance dialogue button should be shown */\n if (players[slot].state.length > players[slot].current+1) {\n $gameAdvanceButtons[slot-1].css({opacity : 1});\n } else {\n $gameAdvanceButtons[slot-1].css({opacity : 0});\n }\n \n /* direct the dialogue bubble */\n if (players[slot].state[players[slot].current].direction) {\n $gameBubbles[slot-1].removeClass();\n\t\t$gameBubbles[slot-1].addClass(\"bordered dialogue-bubble dialogue-\"+players[slot].state[players[slot].current].direction);\n\t} \n \n /* update image */\n $gameImages[slot-1].attr('src', players[slot].folder + players[slot].state[players[slot].current].image);\n}", "function win() {\n displayText(`YOU WIN!`);\n}", "function updateYouLost() {\r\n if ( slotIds.indexOf(board[clickCount]) > -1 ) { //you're in a slot;\r\n document.getElementById(clickCount.toString()).className = 'losingSlot';\r\n } else if ( blockIds.indexOf(board[clickCount]) > -1 ) { // you're on a block\r\n document.getElementById(clickCount.toString()).className = 'losingBlock';\r\n }\r\n loseSound.play();\r\n gameOver = true;\r\n levelCount = 1;\r\n scoreCount = 0;\r\n timeLeft = 80;\r\n headerElement.textContent = 'you lost';\r\n headerElement.style.color = 'rgba(239,83,80,0.9)';\r\n scoreElement.textContent = `${scoreCount}`; \r\n clearInterval(setTimer);\r\n timerBar.style.display = 'none';\r\n nextLevelButton.style.display = 'flex';\r\n nextLevelButton.textContent = `restart?`;\r\n singleClickElement.style.display = 'none';\r\n doubleClickElement.style.display = 'none';\r\n mainElement.style.transition = 'auto';\r\n mainElement.style.backgroundColor = 'rgba(237, 240, 241, 0.9)';\r\n}", "function startNewGame(){\n\ttoggleNewGameSettings();\n\tnewGame();\n}", "function displayGameplay() {\n image(backgroundImg, width / 2, height / 2, 1500, 800);\n\n // Handle input for the player\n player.handleInput();\n\n // Move all the supplies\n player.move();\n for (let i = 0; i < supply.length; i++) {\n supply[i].move();\n // Handle the bee eating any of the supply\n player.handleEating(supply[i]);\n supply[i].display();\n }\n\n //Display firstAid kit\n firstAid.move();\n firstAid.display();\n\n //Display battery\n battery.move();\n battery.display();\n\n // Handle the player collecting any of the supply\n player.handleEating(water);\n player.handleEating(food);\n player.handleCharging(battery);\n player.handleHealing(firstAid);\n\n //Check if the player is dead and to end game\n player.endGame();\n // Display the player\n player.display();\n\n //display the flashlight\n flashlight.display();\n\n // display health (health bar)\n healthBar.updateHealth(player.health);\n healthBar.display();\n\n //display flashlight battery (battery bar)\n batteryBar.updateBattery(player.batteryLevel);\n batteryBar.display();\n}", "function startGame() {\r\n startScreen0.style.display = 'none';\r\n startScreen1.style.display = 'none';\r\n startScreen2.style.display = 'none';\r\n startScreen3.style.display = 'none';\r\n startScreen4.style.display = 'none';\r\n startScreen5.style.display = 'none';\r\n singleClickElement.style.display = 'flex';\r\n doubleClickElement.style.display = 'flex';\r\n initialize();\r\n startTimer();\r\n}" ]
{ "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: width + '%', }, 300, function() { progressBar.find('.point:eq(' + point + ')').addClass('active'); }); } }
[ "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 progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}", "function updateProgressValue() {\n progressBar.max = song.duration;\n progressBar.value = song.currentTime;\n document.querySelector('.currentTime').innerHTML = formatTime(Math.floor(song.currentTime));\n if (document.querySelector('.durationTime').innerHTML === 'NaN:NaN') {\n document.querySelector('.durationTime').innerHTML = '0:00';\n } else {\n document.querySelector('.durationTime').innerHTML = formatTime(Math.floor(song.duration));\n }\n}", "PrintProgress() {\n process.stdout.clearLine()\n process.stdout.cursorTo(0) \n process.stdout.write('Progress: '+this.folIter+' from '+this.totalFol)\n }", "#updateFormProgress() {\n if (this.#steps?.length) {\n let activeStepIndex = this.#steps.findIndex(\n ({ name }) => name === this.activeStep\n );\n let activeStepCount = activeStepIndex + 1;\n let progress =\n Math.ceil((activeStepIndex / (this.#steps.length - 1)) * 100) || 10;\n let indicator = this.#progressBar.querySelector(\".indicator\");\n indicator.style.setProperty(\"--progress\", progress + \"%\");\n // Ensure progressbar starts translated at -100% before we\n // set --progress to avoid a layout race.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n indicator.toggleAttribute(\"ready\", true);\n });\n });\n this.#progressBar.setAttribute(\"aria-valuenow\", activeStepCount);\n this.#progressBar.setAttribute(\n \"aria-label\",\n interpolate(gettext(\"Step %s of %s\"), [\n activeStepCount,\n this.#steps.length,\n ])\n );\n }\n }", "function updateProgress()\n{\n /* Set the width of the progress bars */\n for (const e of progressElts)\n e.style.width = 100 * curslide.b6slidenum / numslides + \"%\";\n\n /* Set the content of .slidenum elements to the current slide number */\n for (const e of slidenumElts)\n e.textContent = curslide.b6slidenum;\n}", "function progressBar(time) {\n \n //Generating the progress bar HTML and displaying it.\n var barDiv = '<div class=\"barProgress\" id=\"barProgress' + numOfBars + '\"><div class=\"bar\" id=\"bar' + numOfBars + '\"></div></div><br>';\n document.getElementById(\"short\").insertAdjacentHTML('beforebegin', barDiv);\n var element = document.getElementById('barProgress' + numOfBars);\n var elem = document.getElementById('bar' + numOfBars);\n numOfBars++;\n var width = 0;\n var progress = 0;\n \n //Starting the update function on set intervals of 250ms.\n var id = setInterval(frame, 250);\n \n //Updates the progress bar if it is not 100% and deletes it if it is.\n function frame() {\n if (progress >= 100) {\n clearInterval(id);\n element.parentNode.removeChild(element);\n numOfBars--;\n } else {\n width += 0.25;\n progress = (width/time) * 100;\n elem.style.width = progress + '%'; \n }\n }\n}", "fillProgress() {\n\n const radius = 35;\n const circumference = 2 * radius * Math.PI;\n\n // Add stroke-dasharray attribute to create a ring-like impression with stacked svg circles\n const circleElements = document.querySelectorAll(\"circle\");\n circleElements.forEach((circle) => {\n circle.setAttribute(\"stroke-dasharray\", circumference.toString());\n circle.setAttribute(\"r\", radius.toString());\n });\n\n if(this.state.onBreak) {\n // Changes color of timer radial to green during break time\n document.querySelector(\".radial-progress-border\").setAttribute(\"stroke\", \"#0f7864\");\n document.querySelector(\".radial-progress-background\").setAttribute(\"stroke\", \"#18bc9c\");\n } else {\n // Changes color of timer radial to red during work time\n document.querySelector(\".radial-progress-border\").setAttribute(\"stroke\", \"#e53c37\");\n document.querySelector(\".radial-progress-background\").setAttribute(\"stroke\", \"#eb6864\");\n }\n\n let elapsed = this.state.elapsed;\n const initialDuration = this.state.initialDuration;\n\n const that = this;\n\n (function fillProgress() {\n\n that.state.timeoutRadial = setTimeout(fillProgress, 1000);\n\n if (initialDuration < elapsed) {\n let dingSound = new Audio(\"../../../resources/audio/ding.wav\");\n dingSound.play();\n clearTimeout(that.state.timeoutRadial);\n /* If the end of the timer was during break time, we check whether we still have more cycles left, else\n it was during work time and we proceed with timing the break time */\n if(that.state.onBreak) {\n // Checks how many cycles left until the end of task session\n if(that.state.numberOfCycles > 1) {\n let workTime = that.stringToSeconds(that.props.currentTask.workTime);\n let breakTime = that.stringToSeconds(that.props.currentTask.breakTime);\n let numberOfCycles = that.state.numberOfCycles - 1;\n that.setState({\n initialDuration: workTime,\n\n duration: workTime,\n elapsed: 0,\n remaining: workTime,\n\n breakDuration: breakTime,\n\n numberOfCycles: numberOfCycles,\n\n onBreak: false,\n\n running: false,\n paused: false,\n\n timeoutRadial: 0,\n timeoutText: 0\n }, () => {\n // Repeat the progress\n that.fillProgress();\n that.renderTimerText();\n });\n } else {\n let timerButton = document.querySelector(\"#timer-button\");\n let timerButtonIcon = document.querySelector(\"#timer-button-icon\");\n timerButton.className = \"btn btn-lg btn-success\";\n timerButtonIcon.className = \"fa fa-play\";\n\n let workTime = 0;\n\n if (EmptyCheck.isObjectEmpty(this.props.currentTask)) {\n workTime = 1500;\n } else {\n workTime = this.stringToSeconds(this.props.currentTask.workTime);\n }\n\n that.setState({\n initialDuration: workTime,\n duration: workTime,\n elapsed: 0,\n remaining: workTime,\n running: false,\n onBreak: false\n });\n }\n } else {\n const breakDuration = that.state.breakDuration;\n that.setState({\n initialDuration: breakDuration,\n duration: breakDuration,\n elapsed: 0,\n remaining: breakDuration,\n onBreak: true,\n }, () => {\n // Repeat the progress for break time\n that.fillProgress();\n that.renderTimerText();\n });\n }\n }\n\n //If the full time hasn't elapsed yet, we add a portion relative to elapsed time to the ring of the radial timer\n if(elapsed<=initialDuration) {\n const offset = -(circumference / initialDuration).toPrecision(21) * elapsed + \"px\";\n document.querySelector(\".radial-progress-cover\").setAttribute(\"stroke-dashoffset\", offset);\n elapsed++;\n that.setState({\n elapsed: elapsed,\n remaining: initialDuration - elapsed\n });\n }\n })();\n\n }", "function updateProgress(showOverlay) {\n // update progress bar\n var correctThisLevel = state.numCorrect % correctPerLevel;\n $progressBarFill.width(correctThisLevel * progressBarWidthPerCorrect);\n // update percent correct\n var percent = state.numCorrect / (state.numCorrect + state.numWrong) * 100;\n percent = Math.round(percent || 0);\n $percentage.text(percent + \"%\");\n // update level number\n if (showOverlay && correctThisLevel == 0) {\n state.level += 1;\n }\n // setting level text in bottom right corner\n var levelColor = starColors[state.level % starColors.length];\n $levelDiv.text(\"Level \" + state.level);\n $levelDiv.removeClass().addClass(levelColor); // removing old class, adding new color\n\n // show overlay\n if (showOverlay && correctThisLevel == 0) {\n $starDiv.text(state.level);\n $starDiv.removeClass().addClass(\"star \" + levelColor);\n $overlay.fadeIn(500).delay(2000).fadeOut(500);\n $flashcard.fadeOut(200).delay(2600).fadeIn(200);\n setTimeout(function() {\n $answerInput.focus();\n }, 3000);\n }\n }", "function ProgressBar(fraction, size_arg = new ImVec2(-1, 0), overlay = null) {\r\n bind.ProgressBar(fraction, size_arg, overlay);\r\n }", "function run() {\n iteration++;\n drawVerticals(l, W, H, ctx);\n totalCrossed += drawSticks(sticks, l, W, H, ctx);\n console.log(totalCrossed);\n var pi = 2 * iteration * sticks / totalCrossed;\n document.getElementById(\"consola\").innerHTML = \"Iteration: \" + iteration;\n document.getElementById(\"consola\").innerHTML +=\n \", Total: \" + iteration * sticks;\n document.getElementById(\"consola\").innerHTML += \", Hits: \" + totalCrossed;\n document.getElementById(\"consola\").innerHTML += \", pi: \" + pi.toFixed(4);\n document.getElementById(\"consola\").innerHTML +=\n \", error: \" + Math.abs((pi / Math.PI - 1) * 100).toFixed(2) + \"%\";\n console.log(\"pi: \" + 2 * iteration * sticks / totalCrossed);\n\n console.log(iteration);\n if (iteration == nTries) clearInterval(timer);\n}", "function finishProcessing(id,percent,state,error){\n\t\tvar stateBar = getStateBarElement(id);\n\t\tvar btnStart = getBtnStartElement(id);\n\t\tvar btnDownlaod=getBtnDownloadElement(id);\n\t\t\n\t\tstateBar.innerHTML=state;\n\t\tif(error){\n\t\t\tupdateProgressBar (id, 0);\n\t\t\tresetColorsProgressBar (id);\n\t\t\tbtnStart.disabled=false;\n\t\t\tbtnDownlaod.disabled=true;\n\t\t} else{\n\t\t\tbtnStart.disabled=false;\n\t\t\tbtnDownlaod.disabled=false;\n\t\t\tprocessStateTabs(id);\n\t\t\tupdateProgressBar (id, percent);\n\t\t}\n\t}", "function diverge(){\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height);\n\t\tvar diff = 0.2;\n\t\t\n\t\t\n\t\tif(rad<=70){\n\t\t\trad = rad + diff;\n\t\t\tdrawCircle();\n\t\t\tdrawDuet();\n\t\t}\n\t\telse{\n\t\t\tclearInterval(check2);\n\t\t\tplay = true;\n\t\t\tflag = true;\n\t\t\trad = 70;\n\t\t\tconsole.log(rad);\n\t\t}\n\t}", "function drawUpdateBar(){\n\t\t\td3.select(\"#bar-cover #bar-chart\").selectAll(\"svg\").remove();\n\t\t\tdrawBar();\n\t\t}", "function adjustProgress() {\n\tvar current = shell.currPageNum;\n\tvar total = totalPageNum;\n\t//alert(\"current: \" + current + \" total: \" + total);\n\tif (shell.progress.type == 'text' || shell.progress.type == 'both') {\n\t\tada$(shell.progress.textDiv).innerHTML = current + \" of \" + total;\n\t} \n\tif (shell.progress.type == 'bar' || shell.progress.type == 'both') {\n\t\tvar minWidth = shell.progress.barMinWidth;\n\t\tvar ratio = current/total;\n\t\tvar pbWidth = shell.progress.barWidth*ratio;\n\t\tif (pbWidth < minWidth+4) pbWidth+= minWidth;\n\t\tvar myEl = ada$(shell.progress.barDiv);\n\t\tvar myEl2 = ada$(shell.progress.barInner);\n\t\tmyEl.style.width = pbWidth+'px';\n\t\tmyEl2.style.width = pbWidth+'px';\n\t\t// If it's only the progress bar, hide the text div\n\t\tif (shell.progress.type == 'bar') {\n\t\t\t$('#'+shell.progress.textDiv).addClass('off');\n\t\t}\n\t}\n}", "function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}", "function updateCurrentRound(){\n ++currentRound;\n}", "function endRound () {\n\t/* check to see how many players are still in the game */\n var inGame = 0;\n var lastPlayer = 0;\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n inGame++;\n lastPlayer = i;\n }\n }\n \n /* if there is only one player left, end the game */\n if (inGame == 1) {\n\t\tconsole.log(\"The game has ended!\");\n\t\t$gameBanner.html(\"Game Over! \"+players[lastPlayer].label+\" won Strip Poker Night at the Inventory!\");\n\t\tgameOver = true;\n \n for (var i = 0; i < players.length; i++) {\n if (HUMAN_PLAYER == i) {\n $gamePlayerCardArea.hide();\n } \n else {\n $gameOpponentAreas[i-1].hide();\n }\n }\n \n\t\thandleGameOver();\n\t} else {\n\t\t$mainButton.html(\"Deal\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n\t}\n\t$mainButton.attr('disabled', false);\n actualMainButtonState = false;\n}" ]
{ "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 )\n {\n res = false;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }", "static isArray(input) {\n return input instanceof Array;\n }", "function is_array(obj){\n return Array.isArray(obj);\n}", "function ISARRAY(value) {\n return Object.prototype.toString.call(value) === '[object Array]';\n}", "function is_stream(xs) {\n return is_null(xs) || (is_pair(xs) && is_list(stream_tail(xs)));\n}", "function isObject(element) {\n if (!element) return false\n if (typeof element !== 'object') return false\n if (element instanceof Array) return false\n return true\n}", "function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n }", "function getOnlyElement(iterable) {\n var iterator = iterable[Symbol.iterator]();\n\n var firstIteration = iterator.next();\n if (firstIteration.done)\n throw new Error('getOnlyElement was passed an empty iterable.');\n\n var secondIteration = iterator.next();\n if (!secondIteration.done)\n throw new Error(\n 'getOnlyElement was passed an iterable with multiple elements.');\n\n return firstIteration.value;\n }", "function allSameType(input) {\n return input.every((element, i, arr) => typeof(element) === typeof(arr[0]));\n}", "isEOF() {\n return this._index >= this.input.length;\n }", "function isMap (data) {\n return Object.prototype.toString.call(data) === '[object Map]';\n }", "function ifilter(iterable, predicate) {\n var _iteratorNormalCompletion6, _didIteratorError6, _iteratorError6, _iterator6, _step7, value;\n\n return _regenerator[\"default\"].wrap(function ifilter$(_context7) {\n while (1) {\n switch (_context7.prev = _context7.next) {\n case 0:\n _iteratorNormalCompletion6 = true;\n _didIteratorError6 = false;\n _iteratorError6 = undefined;\n _context7.prev = 3;\n _iterator6 = iterable[Symbol.iterator]();\n\n case 5:\n if (_iteratorNormalCompletion6 = (_step7 = _iterator6.next()).done) {\n _context7.next = 13;\n break;\n }\n\n value = _step7.value;\n\n if (!predicate(value)) {\n _context7.next = 10;\n break;\n }\n\n _context7.next = 10;\n return value;\n\n case 10:\n _iteratorNormalCompletion6 = true;\n _context7.next = 5;\n break;\n\n case 13:\n _context7.next = 19;\n break;\n\n case 15:\n _context7.prev = 15;\n _context7.t0 = _context7[\"catch\"](3);\n _didIteratorError6 = true;\n _iteratorError6 = _context7.t0;\n\n case 19:\n _context7.prev = 19;\n _context7.prev = 20;\n\n if (!_iteratorNormalCompletion6 && _iterator6[\"return\"] != null) {\n _iterator6[\"return\"]();\n }\n\n case 22:\n _context7.prev = 22;\n\n if (!_didIteratorError6) {\n _context7.next = 25;\n break;\n }\n\n throw _iteratorError6;\n\n case 25:\n return _context7.finish(22);\n\n case 26:\n return _context7.finish(19);\n\n case 27:\n case \"end\":\n return _context7.stop();\n }\n }\n }, _marked6, null, [[3, 15, 19, 27], [20,, 22, 26]]);\n}", "static isObject(input) {\n return input !== null && !this.isArray(input) && typeof (input) === 'object';\n }", "function isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}", "function isElementDecorative(element, elementData) {\n if ($(element).attr(\"aria-hidden\") === \"true\") {\n return true;\n //TODO: this logic may need to change if screen readers support spec that says aria-label\n //\t\tshould override role=presentation, thus making it not decorative\n } else {\n if (elementData.role === \"presentation\" || elementData.role === \"none\") { //role is presentation or none\n return true;\n } else if ($(element).is(\"img\") && elementData.empty && elementData.empty.alt) { //<img> and empty alt\n return true;\n }\n }\n return false;\n }", "function object (thing) {\n return typeof thing === 'object' && thing !== null && array(thing) === false && date(thing) === false;\n }", "function makeIterable(i) {\n function* iterate() {\n for (let r = i.next(); !r.done; r = i.next()) {\n yield r.value;\n }\n }\n return isIterable(i) ? i : iterate();\n}", "isOperationList(value) {\n return Array.isArray(value) && value.every(val => Operation.isOperation(val));\n }", "function isVariableViewPropertyIterator(prop, webConsole) {\n if (prop.displayValue == \"Iterator\") {\n return promise.resolve(true);\n }\n\n let deferred = promise.defer();\n\n variablesViewExpandTo({\n rootVariable: prop,\n expandTo: \"__proto__.__iterator__\",\n webconsole: webConsole,\n }).then(function onSuccess() {\n deferred.resolve(true);\n }, function onFailure() {\n deferred.resolve(false);\n });\n\n return deferred.promise;\n}" ]
{ "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) { return (d.value / numberOfDaysPerYear); }); }
[ "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 Stats(array) {\n const MonthYearsCompleted = [];\n const TotalStatstics = [];\n\n for (j = 0; j < array.length; j++) {\n const Month = new Date(array[j]['date']).getMonth();\n const Year = new Date(array[j]['date']).getFullYear();\n\n if (dateUsed((Month + (Year * 100)), MonthYearsCompleted)){\n\n TotalStatstics.push([Year, Month + 1,\n MonthStats(array, 'food', Month, Year),\n MonthStats(array, 'lifestyle', Month, Year),\n MonthStats(array, 'indulgent', Month, Year),\n MonthStats(array, 'other', Month, Year), \n MonthTotal(array, Month, Year)]);\n\n MonthYearsCompleted.push(Month + (Year * 100));\n }\n }\n\n return TotalStatstics;\n}", "function showAccidentsMonth(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"date\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let minDate = dim.bottom(1)[0].date;\n let maxDate = dim.top(1)[0].date;\n\n let composite = dc.compositeChart(\"#composite-month\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 10, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.time.scale().domain([minDate, maxDate]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" accidents\";\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .interpolate(\"monotone\")\n .group(totalCasByHour, \"Casualties\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" casualties\";\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" vehicles involved\";\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"8%\")\n .xAxis().ticks(12).tickFormat(d3.time.format(\"%b\")).outerTickSize(0);\n\n composite.yAxis().ticks(5).outerTickSize(0);\n}", "function calculateDogYears(dogYears){\n return dogYears * 7;\n}", "function show_no_of_suicides_by_year(ndx) {\n //Data dimension for year\n let year_dim = ndx.dimension(function(d) {\n return new Date(d.year);\n });\n\n //Data group for no of suicides per 100k people for each gender\n let male_suicides_per_year = year_dim.group().reduceSum(function(d) {\n if (d.sex == \"male\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n let female_suicides_per_year = year_dim.group().reduceSum(function(d) {\n if (d.sex == \"female\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n //Setting min and max year for x-axis\n let min_year = year_dim.bottom(1)[0].year;\n let max_year = year_dim.top(1)[0].year;\n\n dc.lineChart(\"#line-chart\")\n .renderArea(true)\n .width(500)\n .height(350)\n .transitionDuration(1000)\n .margins({ top: 30, right: 50, bottom: 40, left: 50 })\n .dimension(year_dim)\n .group(female_suicides_per_year, \"Female\")\n .stack(male_suicides_per_year, \"Male\")\n .ordinalColors(['#fa9fb5', '#67a9cf'])\n .elasticY(true)\n .transitionDuration(500)\n .x(d3.time.scale().domain([min_year, max_year]))\n .renderHorizontalGridLines(true)\n .renderVerticalGridLines(true)\n .useViewBoxResizing(true)\n .title(function(d) { return \"Year \" + d.key.getFullYear() + \"\\n No. of suicides: \" + d.value; })\n .legend(dc.legend().x(400).y(30).itemHeight(13).gap(5))\n .brushOn(false)\n .xAxisLabel(\"Year\")\n .yAxisLabel(\"No. of Suicides per 100k people\")\n .yAxis().ticks(10);\n}", "function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}", "function yearPercentagesRekenen(){\n YearPercentageGewerkteUren = YearGewerktUren/YearTotaalUren;\n YearPercentageOver100Uren = YearOver100Uren/YearTotaalUren;\n YearPercentageOver125Uren = YearOver125Uren/YearTotaalUren;\n YearPercentageVerlofUren = YearVerlofUren/YearTotaalUren;\n YearPercentageZiekteUren = YearZiekteUren/YearTotaalUren;\n\n \n}", "function calcAge(birthday, timeMultiplierInFunc) {\n //Get the users D.O.B. and split it into useable chunks\n var days = moment().diff(birthday, 'days');\n siteVisitor.years = days / timeMultiplierInFunc;\n\n \n \n}", "function find_average() {\n number_of_accounts = accounts.length;\n console.log(\"Number of bank accounts: \" + number_of_accounts);\n total = total_cash();\n average = total / number_of_accounts;\n console.log(\"Average bank account value: £\" + average);\n}", "getReportYear(){\n let goal = this.gCals() * 365;\n let eaten = this.getFoodYear().calories;\n let burned = this.getActivitiesYear().caloriesBurned;\n let calRemaining = goal - eaten + burned;\n return {eaten: eaten, burned: burned, goal: goal, \n remaining: calRemaining};\n }", "function totalDaysInYears(year) {\r\n var date = new Date();\r\n var currentYear = date.getFullYear();\r\n // var totalLeapYears = 0;\r\n var totalDays = 0;\r\n for (i = year; i <= currentYear; i++) {\r\n if (isBirthLeapYear(i)) {\r\n // totalLeapYears = totalLeapYears + 1;\r\n totalDays = totalDays + 366;\r\n } else {\r\n totalDays = totalDays + 365;\r\n }\r\n }\r\n return totalDays;\r\n}", "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 = indecimal;\r\n\r\n finalunit = (countunit == \"days\")? one_day : (countunit == \"months\")? one_month : one_year;\r\n decimals = (decimals <= 0)? 1 : decimals*10;\r\n\r\n if (unit != \"years\")\r\n {\r\n return (Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals);\r\n }\r\n else\r\n {\r\n yearspast=today.getFullYear()-yr-1;\r\n tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0;\r\n pastdate.setFullYear(today.getFullYear());\r\n pastdate2=new Date(today.getFullYear()-1, mon-1, day);\r\n tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;\r\n return (yearspast+tail);\r\n }\r\n}", "function averageAge(people){\n\tvar average = 0;\n\tfor(var i = 0; i < people.length; i++){\n\t\taverage += people[i].age;\n\t}\n\treturn average / people.length;\n}", "function showCasualtiesTotal(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"ref\"));\n let totalCas = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n\n dc.numberDisplay(\"#casualties-total\")\n .formatNumber(d3.format(\".2s\"))\n .group(totalCas);\n}", "function GalacticTest(year,month,day) {\n this.earthBirthday = new Date(year,month,day)\n this.testDate = new Date(2019,0,1)\n this.earthYears = Math.floor(this.dateDifference()/365)\n}", "getSumOfAgeRatios() {\n let sum = 0;\n for (let ageGroup of this.ageGroups) {\n sum += this.getAgeRatio(ageGroup);\n }\n return sum;\n }", "function showAccidentsHour(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"hour\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let composite = dc.compositeChart(\"#composite-hour\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 20, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.scale.linear().domain([0, 23]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\")\n .attr(\"dx\", \"-30\")\n .attr(\"dy\", \"-5\")\n .attr(\"transform\", \"rotate(-90)\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" accidents at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" accidents at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalCasByHour, \"Casualties\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" casualties at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" casualties at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" vehicles involved at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" vehicles involved at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"2%\")\n .xAxis().ticks(24).tickFormat(function(d) {\n if (d < 10) {\n return \"0\" + d + \":00\";\n }\n else { return d + \":00\"; }\n }).outerTickSize(0);\n composite.yAxis().ticks(5).outerTickSize(0);\n}", "function getDias(data) {\r\n\tvar campos = data.split(\"-\");\r\n\tvar anos = Number(campos[0]);\r\n\tvar meses = Number(campos[1]);\r\n\tvar dias = Number(campos[2]);\r\n\tvar totalDias = anos*365 + meses*30 + dias;\r\n\treturn totalDias;\r\n}", "getAverageHR() {\n let retval=0;\n if (this.countHR>0) { retval=parseInt(this.totalHR/this.countHR) }\n return retval;\n }" ]
{ "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 setMode(newMode) {\r\n bTextMode = newMode;\r\n var cont;\r\n if (bTextMode) {\r\n// show html\r\n cleanHtml();\r\n cleanHtml();\r\n cont= Composition.document.body.innerHTML;\r\n Composition.document.body.innerText=cont;\r\n } else {\r\n cont=Composition.document.body.innerText;\r\n Composition.document.body.innerHTML=cont;\r\n }\r\n Composition.focus();\r\n}", "function onModeSet(mode) {\n Y.log( 'Form mode changed to: ' + template.mode, 'debug', NAME );\n if ('shutdown' === mode) {\n // dispose of all KO and template events\n Y.log('Form ' + template.canonicalId + ' is being shut down, disposing events', 'debug', NAME);\n onUnload();\n }\n }", "setTransformMode(mode) {\n this.showControls(true);\n this._transformControls.setMode(mode);\n }", "function changeMode(){\n\tvar new_mode = $('#mode').val();\n\tedit_session.setMode(\"ace/mode/\"+new_mode);\n}", "function setMode(mode){\n\t\tif(mode !== undefined){\n\t\t\tcm.setOption('mode', mode);\n\t\t\tCodeMirror.autoLoadMode(cm, mode);\n\t\t\t/*var script = 'lib/codemirror/mode/'+mode+'/'+mode+'.js';\n\n\t\t\t$.getScript(script, function(data, success) {\n\t\t\t\tif(success) cm.setOption('mode', mode);\n\t\t\t\telse cm.setOption('mode', 'clike');\n\t\t\t});*/\n\t\t}else{\n\t\t\tcm.setOption('mode', 'clike');\n\t\t}\n\t}", "function showCompanyForm(mode, callback) {\n\n }", "function updateMode(newMode) {\n mode = newMode; // sets global 'mode' variable\n\n // Toggle the correct mode button\n d3.select('div#modes')\n .selectAll('button')\n .attr('class', null);\n d3.select('div#modes')\n .selectAll('button#' + mode)\n .attr('class', 'hidden');\n\n // Toggle the correct sub controls\n d3.select('div#sub-controls')\n .selectAll('div')\n .attr('class', 'hidden');\n d3.select('div#sub-controls')\n .select('div#sub-controls-' + mode)\n .attr('class', null);\n\n // Enable/disable editing the command list\n if (mode === 'run') {\n command_list.option('disabled', true);\n d3.select('ul#commands').attr('class', null);\n resetAries();\n } else {\n command_list.option('disabled', false);\n d3.select('ul#commands')\n .attr('class', 'editable')\n .selectAll(\"li\")\n .attr('class','');\n }\n }", "setBlockMode(mode) {\n if (mode === this.blockMode) { return; } // bail if there's no change\n this.blockMode = mode;\n if(mode) {\n this.savedOpts = {}\n cmOptions.forEach(opt => this.savedOpts[opt] = this.cm.getOption(opt));\n this.wrapper.setAttribute( \"role\", \"tree\"); \n this.scroller.setAttribute(\"role\", \"presentation\");\n this.wrapper.setAttribute(\"aria-label\", \"Block Editor\");\n this.say(\"Switching to Block Mode\");\n this.ast = this.parser.parse(this.cm.getValue());\n } else {\n cmOptions.forEach(opt => this.cm.setOption(opt, this.savedOpts[opt]));\n this.wrapper.removeAttribute( \"role\"); \n this.scroller.removeAttribute(\"role\");\n this.wrapper.setAttribute(\"aria-label\", \"Text Editor\");\n this.say(\"Switching to Text Mode\");\n }\n this.renderer.animateTransition(this.ast, mode);\n }", "function changeMode(mode, woNumber, previous){\n $('#modeParameter').val(mode);\n $('#woNumberParameter').val(woNumber);\n $('#previousParameter').val(previous);\n $('#passParamtersForm').submit(); \n}", "setMode() {\n errors.throwNotImplemented(\"setting mode (dequeue options)\");\n }", "set resolutionMode(value) {}", "function setTypingMode(_mode) {\n const mode = _mode.toLowerCase();\n\n switch (mode) {\n case \"words (fixed amount)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#word-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"words (against the clock)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#time-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"code snippets\":\n // Update ui\n document.querySelector(\"#typing-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#coding-area\").style.display = \"inline\";\n document.querySelector(\"#language-selected\").style.display = \"inline\";\n\n // Start typing test\n setCodeText();\n showCodeText();\n\n break;\n\n default:\n console.error(`Mode ${mode} is undefined`);\n }\n }", "function fillEditPageForm(what, mode, id) {\n\t\n\tif(mode == 'add' || mode == 'edit') {\n\t\tdocument.getElementById('mode').value = mode;\n\t}\n\telse {\n\t\treturn;\n\t}\n\t\n\t//collect the DOM elements for all the fields that need to be filled\n\tvar name = document.getElementById('name');\n\tvar descript = document.getElementById('descript');\n\tvar ref_type_full = document.getElementById('ref_type_full');\n\tvar ref_type_lim = document.getElementById('ref_type_lim');\n\t\n\t//pro contact information\n\tvar p_contact_id = document.getElementById('p_contact_id');\n\tvar title = document.getElementById('title');\n\tvar f_name = document.getElementById('f_name');\n\tvar l_name = document.getElementById('l_name');\n\tvar m_name = document.getElementById('m_name');\n\tvar suf = document.getElementById('suf');\n\tvar m_phone = document.getElementById('m_phone');\n\tvar w_phone = document.getElementById('w_phone');\n\tvar mail = document.getElementById('mail');\n\n\tvar s_contact_id = document.getElementById('s_contact_id');\n\tvar s_f_name = document.getElementById('s_f_name');\n\tvar s_l_name = document.getElementById('s_l_name');\n\tvar s_m_name = document.getElementById('s_m_name');\n\tvar s_m_phone= document.getElementById('s_m_phone');\n\tvar s_w_phone= document.getElementById('s_w_phone');\n\tvar s_mail = document.getElementById('s_mail');\n\t\n\tvar addr_id = document.getElementById('addr_id');\n\tvar street = document.getElementById('street');\n\tvar city = document.getElementById('city');\n\tvar state_us = document.getElementById('state_us');\n\tvar zip = document.getElementById('zip');\n\t\n\t//agency or program depending on the what parameter\n\tvar elem;\n\t\n\tif(what == 'agency') {\n\t\telem = agencies[id];\n\n\t\tdocument.getElementById('agency_id').value = elem.id;\n\t\tdocument.getElementById('program_id').value = -1;\n/*\t\tdocument.getElementById('agency_phone').value = elem.phone;\n\t\tdocument.getElementById('agency_fax').value = elem.fax;\n\t\tdocument.getElementById('agency_mail').value = elem.mail;\n*/\t\ts_contact_id.value = -1;\n\t}\n\telse if(what == 'program') {\n\t\telem = programs[id];\n\t\t\n\t\t//set the student contact info\n\t\ts_contact_id.value = (elem.s_contact.id) ? elem.s_contact.id : -1;\n\t\ts_f_name.value = elem.s_contact.f_name;\n\t\ts_l_name.value = elem.s_contact.l_name;\n\t\ts_f_name.value = elem.s_contact.f_name;\n\t\ts_m_phone.value = elem.s_contact.m_phone;\n\t\ts_w_phone.value = elem.s_contact.w_phone;\n\t\ts_mail.value = elem.s_contact.mail;\n\t\t\n\t\tdocument.getElementById('agency_id').value = elem.agency.id;\n\t\tdocument.getElementById('program_id').value = elem.id;\n/*\t\tdocument.getElementById('phone').value = elem.phone;\n*/\t\t\n\t\tif(elem.referal == referal.full) {\n\t\t\tref_type_full.checked = true;\n\t\t\tref_type_lim.checked = false;\n\t\t}\n\t\telse if(elem.referal == referal.limited){\n\t\t\tref_type_full.checked = false;\n\t\t\tref_type_lim.checked = true;\n\t\t}\n\t\t\n\t\t//check the interest boxes\n\t\tvar i;\n\t\tfor(i in elem.issues) {\n\t\t\tvar issue_index = elem.issues[i];\n\t\t\tvar currentIssue = issues[issue_index];\n\t\t\tvar issue_elem = document.getElementById(currentIssue.name).checked = true;\n\t\t}\n\t\t\n\t\t//check the hours boxes\n\t\tfor(i in elem.hours) {\n\t\t\tvar hour_index = elem.hours[i];\n\t\t\tvar currentHour = hours[hour_index];\n\t\t\tvar hour_elem = document.getElementById(currentHour).checked = true;\n\t\t}\n\t\t//check the seasons boxes\n\t\tfor(i in elem.seasons) {\n\t\t\tvar season_index = elem.seasons[i];\n\t\t\tvar currentSeason= seasons[season_index];\n\t\t\tvar season_elem = document.getElementById(currentSeason).checked = true;\n\t\t}\n\t\t\n\t}\n\tname.value = elem.name;\n\tdescript.value = elem.descript;\n\t\n\tp_contact_id.value = (elem.p_contact.id) ? elem.p_contact.id : -1;\n\tf_name.value = elem.p_contact.f_name;\n\tm_name.value = elem.p_contact.m_name;\n\tl_name.value = elem.p_contact.l_name;\n\ttitle.value = elem.p_contact.title;\n\tsuf.value = elem.p_contact.suf;\n\tw_phone.value = elem.p_contact.w_phone;\n\tm_phone.value = elem.p_contact.m_phone;\n\tmail.value = elem.p_contact.mail;\n\t\n\taddr_id.value = (elem.addr.id) ? elem.addr.id : -1;\n\tstreet.value = elem.addr.street;\n\tcity.value = elem.addr.city;\n\tstate_us.value = elem.addr.state_us;\n\tzip.value = elem.addr.zip;\n}", "setLensMode(lensMode) {\n this._lensMode = lensMode;\n if (!this._lensMode)\n this.setScreenPosition (this._screenPosition);\n }", "function setSelectMode() {\n mode = modes.SELECT\n GameScene.setRegionSelectPlaneVis(true)\n }", "_updateForm() {\n var form = this._getForm();\n form.find('#name').val(this.contact.name);\n form.find('#surname').val(this.contact.surname);\n form.find('#email').val(this.contact.email);\n form.find('#country').val(this.contact.country);\n }", "function setForm(target){ \n\t\tvar options = $.data(target, 'form').options; \n\t\tvar form = $(target); \n\t\tform.unbind('.form').bind('submit.form', function(){ \n\t\t\tajaxSubmit(target, options); \n\t\t\treturn false; \n\t\t}); \n\t}", "setShowInEditForm(show) {\n return spPost(Field(this, `setshowineditform(${show})`));\n }", "function displayModePatch() {\n\tif (PLAYER.type!=PLAYERTYPE) {\n\t\tPLAYERTYPE=PLAYER.type;\n\t\tif ($_modesel.val()==\"chMode\" || $_modesel.val()==\"rMode\") {\n\t\t\t$videowidth.removeClass().addClass('span1');\n\t\t\t$(\"#ytapiplayer\").attr(\"width\", '1').attr(\"height\", '1');\n\t\t}\n\n\t}\n}" ]
{ "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.state = { selectNames : props.selectNames, selectOptions : props.selectOptions, score : formScore, }; }
[ "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 onChange={this.onChange.bind(this)}\n value={this.props.code}\n\n />\n );\n\n }", "function addSkill() {\n let select = document.getElementById(\"skill-select\");\n let options = select.options; \n let opt;\n for(let i=1; i<options.length; i++){\n opt = options[i];\n if(opt.selected && !Object.keys(selectedSkills).includes(opt.innerText)) {\n selectedSkills[opt.innerText] = 0;\n renderSelectedSkills();\n break;\n }\n }\n}", "renderSelects(optObject, multipleSelect){\n let selects = [];\n for(let key in optObject){\n let keyLength = optObject[key].length;\n let opts = [];\n opts.push(<option key=\"dummy\" value='unselected'>Select...</option>)\n for(let i = 0; i < keyLength; i++){\n opts.push(<option key={optObject[key][i][0]} value={optObject[key][i][0]}>{optObject[key][i][1]}</option>);\n }\n if(!multipleSelect){\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control'>{opts}</select></div>);\n }\n else {\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength + 1} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control' multiple>{opts}</select></div>);\n }\n }\n return selects;\n }", "getSelectorParameters(selector, selectorNum) {\n \n // Add the options for the dropdowns\n if (selector.select == \"type\") { // If it is a type, add each of the calendar types\n var options = this.state.types.map((type) => {\n return (\n <option value={type}>{type}</option>\n )\n })\n\n // Add all and empty options\n options.unshift((<option value=\"all\">All</option>))\n options.push((<option value=\"\" hidden></option>))\n } else if (selector.select == \"day\") { // If it is a day, add each of the calendar days that aren't deselected\n var options = Object.keys(this.state.days).map((day) => {\n if (this.state.days[day]) {\n return (\n <option value={day}>{day}</option>\n )\n }\n })\n\n // Add all and empty options \n options.unshift((<option value=\"all\">All</option>))\n options.push((<option value=\"\" hidden></option>))\n }\n \n\n var i = -1\n\n // Iterate through parameter and get JSX\n var parameters = selector.parameters.map((parameter) => { \n i++ \n return ( // Select tag with the options defined above\n <select class=\"selectorParameter\" id={i} value={parameter} onChange={(e) => this.selectorParameterChange(e, selectorNum)}>\n {options}\n </select>\n )\n })\n\n return parameters\n }", "function renderSelectedSkills() {\n // Get div\n let selected = document.getElementById(\"selected-skills\");\n \n // Clear old skills\n while (selected.firstChild) {\n selected.removeChild(selected.firstChild);\n }\n\n // Create the skill name text and dropdown selector for each selected skill\n for(let name of Object.keys(selectedSkills)){\n // Create new skill div container\n let newSkill = document.createElement(\"div\");\n newSkill.className = \"skill\";\n let newSkillText = document.createElement(\"p\");\n newSkillText.innerText = name;\n\n // Add level selector dropdown\n let newSkillLevel = document.createElement(\"select\");\n newSkillLevel.className = \"selected-level\";\n newSkillLevel.onchange = function() {updateLevels(this)};\n createLevelRange(newSkillLevel, skillList[name], selectedSkills[name]);\n \n // Append to the skill list\n newSkill.appendChild(newSkillText);\n newSkill.appendChild(newSkillLevel);\n selected.appendChild(newSkill);\n }\n}", "function updateSelectPositions() {\n let selectY = 480;\n\n heightSelect.x = gameCanvas.getBoundingClientRect().left + 87;\n heightSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n massSelect.x = gameCanvas.getBoundingClientRect().left + 212;\n massSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n surfaceSelect.x = gameCanvas.getBoundingClientRect().left + 359;\n surfaceSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n positionSelect.x = gameCanvas.getBoundingClientRect().left + 506;\n positionSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n}", "handleSelect(thisSelector, nextSs, selectorLevel, data) {\n this.state[thisSelector] = data.value;\n this.setState({selectorLevel: selectorLevel})\n for(let i in nextSs){\n this.refs[nextSs[i]].resetValue();\n if(i == 0){\n this.refs[nextSs[i]].loadOptions();\n }\n }\n }", "setMatrixSelectValues() {\n // generate the matrix names based on the number of matrix inputs, e.g. A, B, C...\n const names = this.matrixInputs.map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i));\n let options = \"\";\n names.forEach((name, i) => options += `<option value=${i}>${name}</option>`);\n this.matrixSelects.forEach(select => select.innerHTML = options);\n }", "function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}", "function updateChoicesSlideScore_() {\n\n updateChoicesSlideView_(this.closest('.slide-choices__option-wrapper'));\n\n }", "get dessertOptions() {\n return [\n { label: 'Nothing for me, thanks!', value: 'Nothing for me, thanks!' },\n { label: 'Brownie', value: 'Brownie' },\n { label: 'Cupcake(Red Velvet)', value: 'Cupcake(Red Velvet)' },\n { label: 'Cupcake(Chocolate)', value: 'Cupcake(Chocolate)' },\n { label: 'Cupcake(Vanilla)', value: 'Cupcake(Vanilla)' },\n { label: 'Cookie(Chocolate Chip)', value: 'Cookie(Chocolate Chip)' },\n { label: 'Cookie(Oatmeal Raisin)', value: 'Cookie(Oatmeal Raisin)' },\n { label: 'Cookie(Peanut Butter)', value: 'Cookie(Peanut Butter)' },\n { label: 'Watermelon)', value: 'Watermelon' }\n ];\n }", "renderSeqReplaceFieldOptions()\n\t{\n\n\t\tif(this.state.data.type == \"sequentialreplace\" && (this.state.target == undefined || this.state.target instanceof StructuredData))\n\t\t{\n\n\t\t\tif(this.state.data.settings.fields == undefined)\n\t\t\t{\n\n\t\t\t\tthis.state.data.settings.fields = []\n\n\t\t\t}\n\n\t\t\treturn(<div>\n\t\t\t\t\t<Form.Group inline>\n\t\t\t\t\t\t<Form.Select \n\t\t\t\t\t\tmultiple selection \n\t\t\t\t\t\terror={this.genIsErrorSettings(\"field\",\"Please select a field\")}\n\t\t\t\t\t\tplaceholder='Choose Field'\n\t\t\t\t\t\tname='fields'\n\t\t\t\t\t\toptions={this.state.fieldTypes}\n\t\t\t\t\t\tvalue={this.state.data.settings.fields}\n\t\t\t\t\t\tlabel=\"Fields:\"\n\t\t\t\t\t\tonChange={this.handleSettingChange.bind(this)}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t </Form.Group>\n\t\t\t\t {this.renderSeqReplaceFieldWarningMessage()}\n\t\t\t\t </div>)\n\n\t\t}\n\n\t}", "renderSelect() {\n const options = {\n 0: 'Present',\n 1: 'Unexcused Absent',\n 2: 'Excused Absent',\n 3: 'Unexcused Late',\n 4: 'Excused Late'\n }\n\n const optionsAbbrev = {\n 0: 'Present',\n 1: 'UA',\n 2: 'EA',\n 3: 'UL',\n 4: 'EL'\n }\n\n const optionsColor = {\n 0: '#3BB273',\n 1: '#E53935',\n 2: '#E53935',\n 3: '#FF8300',\n 4: '#FF8300'\n }\n\n const attendanceButtonStyles = {\n style: styles.attendanceButton\n }\n\n return(\n <Dropdown\n onSelect={this.props.setType(this.props.index)}\n value={this.props.attendance.attendance_type__c}\n defaultText={optionsAbbrev[this.props.attendance.attendance_type__c]}\n options={options}\n styles={attendanceButtonStyles}\n optionsColor={optionsColor[this.props.attendance.attendance_type__c]}\n />\n )\n }", "function initArmorSkillDropdown(data){\n let dropdown = document.getElementById(\"skill-select\");\n for(let sk of Object.keys(data).sort()){\n // Create dropdown option\n let newSkill = document.createElement(\"option\");\n newSkill.innerText = sk;\n newSkill.value = sk;\n dropdown.appendChild(newSkill);\n }\n // Create charm dropdowns\n // ADD\n let addSkill1 = document.getElementById(\"add-skill1-label\");\n let clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"add-skill1\";\n // clonedDropdown.onchange = function() {updateAddCharm(this.id, this.value)}\n addSkill1.appendChild(clonedDropdown);\n\n let addSkill2 = document.getElementById(\"add-skill2-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"add-skill2\";\n // clonedDropdown.onchange = function() {updateAddCharm(this.id, this.value)}\n addSkill2.appendChild(clonedDropdown);\n\n let addSkill1Level = document.getElementById(\"add-level1-label\");\n let newSelect = document.createElement(\"select\");\n newSelect.id = \"add-level1\";\n createLevelRange(newSelect, 7, 0);\n addSkill1Level.appendChild(newSelect);\n\n let addSkill2Level = document.getElementById(\"add-level2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-level2\";\n createLevelRange(newSelect, 7, 0);\n addSkill2Level.appendChild(newSelect);\n\n let addSlot1Level = document.getElementById(\"add-slot1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot1\";\n createLevelRange(newSelect, 3, 0);\n addSlot1Level.appendChild(newSelect);\n\n let addSlot2Level = document.getElementById(\"add-slot2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot2\";\n createLevelRange(newSelect, 3, 0);\n addSlot2Level.appendChild(newSelect);\n\n let addSlot3Level = document.getElementById(\"add-slot3-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot3\";\n createLevelRange(newSelect, 3, 0);\n addSlot3Level.appendChild(newSelect);\n\n // EDIT\n let editSkill1 = document.getElementById(\"edit-skill1-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"edit-skill1\";\n // clonedDropdown.onchange = function() {updateeditCharm(this.id, this.value)}\n editSkill1.appendChild(clonedDropdown);\n\n let editSkill2 = document.getElementById(\"edit-skill2-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"edit-skill2\";\n // clonedDropdown.onchange = function() {updateeditCharm(this.id, this.value)}\n editSkill2.appendChild(clonedDropdown);\n\n let editSkill1Level = document.getElementById(\"edit-level1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-level1\";\n createLevelRange(newSelect, 7, 0);\n editSkill1Level.appendChild(newSelect);\n\n let editSkill2Level = document.getElementById(\"edit-level2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-level2\";\n createLevelRange(newSelect, 7, 0);\n editSkill2Level.appendChild(newSelect);\n\n let editSlot1Level = document.getElementById(\"edit-slot1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot1\";\n createLevelRange(newSelect, 3, 0);\n editSlot1Level.appendChild(newSelect);\n\n let editSlot2Level = document.getElementById(\"edit-slot2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot2\";\n createLevelRange(newSelect, 3, 0);\n editSlot2Level.appendChild(newSelect);\n\n let editSlot3Level = document.getElementById(\"edit-slot3-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot3\";\n createLevelRange(newSelect, 3, 0);\n editSlot3Level.appendChild(newSelect);\n // Save data object for later use\n skillList = data;\n}", "function updateLevelDropdown() {\n if (beginnerFlag === true && intermediateFlag === true && advancedFlag === true) {\n levelDropdown.selectpicker('val', 'allLevels');\n } else if (beginnerFlag === true) {\n levelDropdown.selectpicker('val', 'beginner');\n } else if (intermediateFlag === true) {\n levelDropdown.selectpicker('val', 'intermediate');\n } else if (advancedFlag === true) {\n levelDropdown.selectpicker('val', 'advanced');\n }\n noSeminarsParagraph();\n }", "initDefaultSelectInfo() {\n const {\n type: chartType,\n selectLabel,\n selectSeries,\n } = this.options;\n\n if (selectLabel.use) {\n let targetAxis = null;\n if (chartType === 'heatMap' && selectLabel?.useBothAxis) {\n targetAxis = this.defaultSelectInfo?.targetAxis;\n }\n\n this.defaultSelectInfo = !this.defaultSelectInfo?.dataIndex\n ? { dataIndex: [], label: [], data: [] }\n : this.getSelectedLabelInfoWithLabelData(this.defaultSelectInfo.dataIndex, targetAxis);\n }\n\n if (selectSeries.use && !this.defaultSelectInfo) {\n this.defaultSelectInfo = { seriesId: [] };\n }\n }", "getRules(selector, selectorNum) {\n\n // Generate the options for the category dropdown\n var categoryOptions = [\"All\", \"Chicken\",\"Beef\",\"Salad\",\"Soup\",\"Stew\",\"Pasta\",\"Egg\",\"Pork\",\"Fish\",\"Sandwich\",\"Seafood\",\"Baked\",\"Fried\",\"Bread\",\"Pizza\"].map(category => {\n return(<option value={category}/>)\n })\n categoryOptions.push(<option value=\"\" hidden/>)\n\n var i = -1\n // Generate each rule element\n var rules = selector.rules.map((rule) => {\n i++\n\n // Get the rule parameters\n var parameters = rule.parameters\n\n if ((selector.parameters.includes(\"all\") || selector.parameters.length > 1) && parameters) { // If there are multiple selector parameters, add the for (each/all) parameter\n var forSelector = (\n <div class=\"forSelector\">\n <div style={{display: \"inline\"}}>for </div>\n <select value={parameters.for} class=\"forSelectorSelect\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"for\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"each\">each</option>\n <option value=\"all\">all</option>\n </select>\n </div>\n )\n } else { // If there is just one selector parameter, don't show the for (each/all) option\n var forSelector = (\n <div style={{display: \"none\"}}></div>\n )\n }\n \n var ruleName;\n if (rule.new) { // If it is a new rule make the rulename a selector\n ruleName = (\n <select class=\"selectSelector\" value={rule.rule} id={i} onChange={(e) => this.changeRuleType(e, selectorNum)}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"Total\">Total</option>\n <option value=\"Repeats\">Repeats</option>\n <option value=\"Filter\">Filter</option>\n </select>\n )\n } else { // Otherwise just make it the name of the rule type\n ruleName = rule.rule\n }\n\n var actionButton;\n if (rule.new) { // If the rule is new make the rightmost button an add rule button\n actionButton = (\n <span class=\"plusiconrule\" id={i} onClick={(e) => this.addRule(e, selectorNum)}>+</span>\n )\n } else { // Otherwise make it a remove rule button\n actionButton = ( \n <span class=\"xicon\" id={i} onClick={(e) => this.removeSelectorRule(e, selectorNum)}>✕</span>\n )\n }\n\n if (rule.rule == \"Total\") { // If the rule is a \"total\" command\n var category = capitalize(parameters.category)\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"red\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <select selected={parameters.condition} value={parameters.condition} class=\"ruleCondition\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"condition\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"at most\">At most</option>\n <option value=\"exactly\">Exactly</option>\n <option value=\"at least\">At least</option>\n </select>\n <input type=\"number\" min=\"0\" value={parameters.amount} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"amount\")}></input>\n <input type=\"text\" list=\"categoryOptions\" class=\"catgeoryInput\" value={category} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"category\")}/>\n <datalist id=\"categoryOptions\" >\n {categoryOptions}\n </datalist>\n <div class=\"mealsText\">meals</div>\n {forSelector}\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else if (rule.rule == \"Filter\") { // If the rule is a \"filter\" command\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"green\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <select value={parameters.type} class=\"ruleCondition\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"type\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"exclude\">Exclude</option>\n <option value=\"apply\">Apply</option>\n </select>\n <input type=\"text\" class=\"filterInput\" value={parameters.filter} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"filter\")}/>\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else if (rule.rule == \"Repeats\") { // If the rule is a \"repeats\" command\n var category = capitalize(parameters.category)\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"blue\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <div class=\"filterRuleText\">At most</div>\n <input type=\"number\" min=\"0\" value={parameters.amount} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"amount\")}></input>\n <input type=\"text\" list=\"categoryOptions\" class=\"catgeoryInput\" value={category} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"category\")}/>\n <datalist id=\"categoryOptions\">\n {categoryOptions}\n </datalist>\n <div class=\"filterRuleText2\">meals in a row</div>\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else { // Otherwise display a empty new rule\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"#ccc\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n {actionButton}\n </th>\n </tr>\n </table>\n )\n }\n })\n\n return rules\n }", "function SelectField(props) {\n const validate = value => {\n if (props.required && isEmpty(value)) {\n return 'Required';\n }\n if (props.validate && typeof props.validate === 'function') {\n return props.validate(value);\n }\n };\n\n const [field, meta] = useField({ name: props.name, validate });\n\n const id = props.id || `select-${ props.name }`;\n const helpId = props.help ? `${ id }-help` : null;\n\n const onChangeHelper = e => {\n // Call custom callback.\n props.onChange && props.onChange(e);\n // Now delegate back to Formik to keep things working.\n return field.onChange(e);\n };\n const onBlurHelper = e => {\n props.onBlur && props.onBlur(e);\n return field.onBlur(e);\n };\n\n return (\n <div className=\"form-group\">\n { props.label && (\n <Label required={ props.required } for={ id } classes={ props.labelClasses }>{ props.label }</Label>\n ) }\n <Select\n id={ id }\n disabled={ props.disabled }\n required={ props.required }\n multiple={ props.multiple }\n options={ props.options }\n placeholder={ props.placeholder }\n defaultValue={ props.defaultValue }\n classes={ getFieldClasses(meta, props.classes) }\n ref={ props.innerRef }\n describedby={ helpId }\n // value, onChange and onBlur are being added here directly from `useField()`.\n { ...field }\n // If we have custom onChange and onBlur callbacks we need to wrap them to keep from breaking Formik.\n onChange={ onChangeHelper }\n onBlur={ onBlurHelper }\n />\n\n { props.help && <small id={ helpId } className=\"form-text text-muted\">{ props.help }</small> }\n\n <ErrorMessage meta={ meta }/>\n </div>\n );\n}", "render() {\n const { values } = this.props;\n return (\n <Grid\n verticalAlign=\"middle\"\n centered\n style={{ height: \"25vh\", marginTop: \"25vh\" }}\n >\n <Card>\n <Card.Header as=\"h1\" textAlign=\"center\">\n Select Data\n </Card.Header>\n <Card.Content>\n <Form color=\"green\">\n <Header as=\"h2\" style={{ marginTop: \"15%\" }}>\n Radius to Food:\n </Header>\n <Dropdown\n style={{ marginTop: \"25%\" }}\n onChange={this.props.handleChange(\"radius\")}\n label=\"Radius to Food\"\n selection\n fluid\n search\n options={options}\n values={values}\n placeholder=\"Radius in Miles\"\n />\n <Button\n onClick={this.saveAndContinue}\n style={{ marginTop: \"10px\" }}\n >\n Next\n </Button>\n </Form>\n </Card.Content>\n </Card>\n </Grid>\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' onClick=\"deleteLeader(" + i + "), changeScreen('editLeader', 'leaderList'), displayLeaders()\">"; content += "Yes</button> "; content += "<button id='deleteLeaderNoButton' class='deleteButton' onClick=\"changeScreen('editLeader', 'leaderInfo')\">"; content += "No</button>"; document.getElementById("deleteLeader").innerHTML = content; } // displayDeleteLeader
[ "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:3000/api/v1/players/${playerid}`, {\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n method: \"DELETE\",\n body: JSON.stringify({\n playerID: `${playerid}`,\n })\n })\n .then(response => response.json())\n .then(data => {\n renderPlayerDiv();\n let deletedListItm = document.getElementById(`${data.playerId}`);\n deletedListItm.remove();\n })\n}", "function DEL () {\n\t\tscreenDown.innerHTML = screenDown.innerHTML.slice(0,-1);\n\t\tsetNbsp();\n\t}", "function del(e) {\n current = display.innerHTML;\n if (calcReset) {\n current = '';\n calcReset = false;\n } else {\n current = current.slice(0, -1);\n }\n display.textContent = current;\n }", "function deleteNodeText() {\n\n deleteNodeInp = createInput();\n deleteNodeInp.input(myInputEvent);\n deleteNodeInp.position(1200,50);\n deleteNodeInp.size(80,40);\n deleteNodeInp.changed(deleteNode);\n\n}", "function removeHobby(hobby) {\n hobbyOutput.removeChild(hobby);\n}", "function messageLosing() {\n\n $(`<section class=\"game-over\"><div class=\"message-box\"><h2>Try harder Marites 😔</h2>\n <h3>Kulang ang almusal mong tsismis</h3>\n <p>Number of attempts: ${attempts}</p>\n <p>Total Time: ${60-(seconds/1000)} seconds <p>Rating: ${stars} </p><p><i class=\"fas fa-undo\"></i><i class=\"fas fa-sign-out-alt\"></i><object data=\"leaderboard.svg\"></object>\n </p></div></section>`).insertAfter($('.gamebg'));\n restart(); goBack();\n $('.message-box').fadeIn(1000);\n }", "function renderDeleteMessage(objectText) {\n closeMessages();\n var div = $('<div>')\n .appendTo('#messages')\n .addClass('alert alert-info alert-dismissable');\n $(\"<button>\").appendTo(div)\n .attr('type', 'button')\n .attr('data-dismiss', 'alert')\n .attr('aria-hidden', 'true')\n .addClass('close')\n .html(\"&times;\");\n div.append(\"Successfully deleted '\"+objectText+\"'\");\n}", "function deleteButton() {\n const idToDelete = $(this)\n .parent()\n .attr('data-id');\n console.log(idToDelete);\n\n API.deleteBill(idToDelete).then(() => {\n refreshBillList();\n });\n}", "function displayLeaderboard() { \n hideAll();\n clearTable();\n displayElement(leaderboardPageDiv);\n\n if (leaderboardArr.length > 0) {\n // sorts the leaderboardArr from highest \n // to lowest by score\n leaderboardArr.sort((a, b) => b.score - a.score);\n\n var rank = 1;\n\n // for each element create a new row in leaderboardTable\n for (var i = 0; i < leaderboardArr.length; i++) {\n var curr = leaderboardArr[i];\n // insert row at the bottom of the table\n var row = leaderboardTable.insertRow();\n \n\n // checks if the score is already on the leaderboard so if it \n // is everyone of that score has the same rank\n if (i !== 0 && curr.score !== leaderboardArr[i - 1].score) {\n rank++;\n }\n\n // create cell data for each heading in the table\n createCell(row, rank);\n createCell(row, curr.name);\n createCell(row, curr.score);\n }\n }\n}", "function cerrarPopDN(){\n document.getElementById(\"popupDN\").style.display = \"none\";\n $(\".textDeleteN\").remove();\n}", "function displayLeader(array) {\n if (userArr.length >= 3) {\n console.log(`updating the display with new array`);\n console.log(array);\n $(\"#leader0\").html(\n `<h6>1st: ${array[0].name} - ${array[0].score} points</h6>`\n );\n $(\"#leader1\").html(\n `<h6>2nd: ${array[1].name} - ${array[1].score} points</h6>`\n );\n $(\"#leader2\").html(\n `<h6>3rd: ${array[2].name} - ${array[2].score} points</h6>`\n );\n } else {\n $(\"#leader0\").html(`<h6>Waiting For More Players To Join</h6>`);\n }\n}", "function _hideHello() {\n Main.uiGroup.remove_actor(text);\n text = null;\n}", "function deleteDiv() {\n $(this).parent().remove();\n}", "function borrarPedido(fila, IDPedido)\n{\n if (confirm(\"¿Seguro que desea eliminar este pedido?\")) \n { \n fetch((url+ '/' +IDPedido),{\n 'method':'DELETE',\n 'mode': 'cors'\n })\n .then(function(respuesta){\n if(respuesta.ok) {\n let tabla = document.getElementById(\"tablaPedido\");\n tabla.removeChild(fila);\n }\n else {\n alert(\"No se pudo eliminar el pedido\");\n }\n });\n }\n}", "function mostrarDetalles (usuario) {\n $(\"#id\").html(usuario.id);\n $(\"#nombre\").html(usuario.nombre);\n $(\"#username\").html(usuario.username);\n $(\"#nacimiento\").html(usuario.nacimiento);\n $(\"#posts\").html(usuario.posts);\n }", "function ondelete() {\n var index = getToggledIndex();\n if (index >= 0) {\n children[index].ontoggle();\n children.splice(index,1);\n ctx.onmodify();\n recalcHeight(); // this will redraw the screen\n }\n }", "function removePatientInformation() {\n jQueryWriteTextToHTML(\"#patient-assignment\", \"Assign\");\n jQueryWriteTextToHTML(\"#profile-brain-test-result\", \"\");\n jQueryWriteTextToHTML(\"#profile-tremor-test-result\", \"\");\n jQueryWriteTextToHTML(\"#profile-message\", \"\");\n jQueryWriteTextToHTML(\"#profile-medication\", \"\");\n}", "function delWord() {\r\n var id = this.getAttribute('data-id');\r\n //set data key for modal\r\n document.querySelector(\"#del-confirm\").setAttribute('data-id', id);\r\n document.querySelector(\"#del-text\").innerHTML = \"Are you sure you want to delete the word '\" + idLookUp(id).Word + \"'?\";\r\n}" ]
{ "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 autoCloseBrackets: true,\r\n styleActiveLine: true,\r\n });\r\n let mirrorObj = this.mirror;\r\n this.fancyEditor.on('change', function (instance, obj) {\r\n mirrorObj.html(instance.getValue());\r\n });\r\n }", "buildCodeEditor() {\n let codeEditor = this.editor.CodeManager.getViewer('CodeMirror').clone();\n\n codeEditor.set({\n codeName: 'htmlmixed',\n readOnly: false,\n theme: 'hopscotch',\n autoBeautify: true,\n autoCloseTags: true,\n autoCloseBrackets: true,\n lineWrapping: true,\n styleActiveLine: true,\n smartIndent: true,\n indentWithTabs: true\n });\n\n return codeEditor;\n }", "function loadCodemirror(contentArea, dimensionsObj){\r\n\t//if codemirror was already loaded, don't load it again, or if no contentArea was sent, do nothing\r\n\t//-codemirror itself will fail if contentArea is not a textarea\r\n\tif(typeof(CodeMirror) != 'undefined' || typeof(contentArea) == 'undefined'){ return false; }\r\n\r\n\t//use default dimensions if none are sent\r\n\t//TODO: use the dimensions of the textarea instead\r\n\tif(typeof(dimensionsObj) != 'object'){\r\n\t\tdimensionsObj = {w: 1024, h: 538};\r\n\t}\r\n\t\r\n\t//this function gets called after the ext-codemirror file is loaded\r\n\t//-so define it here before loading the file to avoid a race condition\r\n\twindow._extCodeMirrorInit = function(){\r\n\t\t//create the new codemirror element\r\n\t\tcodemirrorElement = new extCodeMirror({\r\n\t\t\telement:contentArea,\r\n\t\t\tsize: dimensionsObj,\r\n\t\t\tonChange:function(cm,changeObj){\r\n\t\t\t\t//get the value and trim\r\n\t\t\t\tvar _val = (cm.getValue() || '').trim();\r\n\t\t\t\t//set the value from codemirror to the textarea\r\n\t\t\t\t//-could also have similar onchange function on the textarea that updates the codemirror\r\n\t\t\t\tcontentArea.val(_val);\r\n\t\t\t}});\r\n\t};//func _extCodeMirrorInit\r\n\r\n\t//load the codemirror css\r\n\t//-update the paths to match your actual paths\r\n\tdocument.head.innerHTML +=\r\n\t\t'\\n\\t<link rel=\"stylesheet\" type=\"text/css\" href=\"'\r\n\t\t\t+[\t\tchrome.runtime.getURL('js/inc/lib/codemirror'),\r\n\t\t\t\t\tchrome.runtime.getURL('js/inc/addon/dialog/dialog'),\r\n\t\t\t\t\tchrome.runtime.getURL('css/inc/ext/ext-codemirror')\r\n\t\t\t\t].join('.css\">\\n\\t<link rel=\"stylesheet\" type=\"text/css\" href=\"')\r\n\t\t+'.css\">';\r\n\r\n\t//call background function for adding scripts\r\n\t//-works similarly to require.js\r\n\t//-start with the main codemirror.js plugin file\r\n\t//--update the paths to match your actual paths\r\n\tcmConnection.postMessage({\r\n\t\tmethod: 'addScripts',\r\n\t\tscripts: [\r\n\t\t\t'js/inc/lib/codemirror.js'\r\n\t\t]\r\n\t}, function(resp){\r\n\t\t//then load all of the codemirror plugins that you might want\r\n\t\t//-update the paths to match your actual paths\r\n\t\tcmConnection.postMessage({\r\n\t\t\tmethod: 'addScripts',\r\n\t\t\tscripts: [\r\n\t\t\t\t'js/inc/mode/javascript/javascript.js',\r\n\t\t\t\t'js/inc/mode/css/css.js',\r\n\t\t\t\t'js/inc/mode/xml/xml.js',\r\n\t\t\t\t'js/inc/mode/htmlmixed/htmlmixed.js',\r\n\t\t\t\t'js/inc/addon/overlay/overlay.js',\r\n\t\t\t\t'js/inc/addon/search/search.js',\r\n\t\t\t\t'js/inc/addon/search/searchcursor.js',\r\n\t\t\t\t'js/inc/addon/search/match-highlighter.js',\r\n\t\t\t\t'js/inc/addon/dialog/dialog.js'\r\n\t\t\t]\r\n\t\t}, function(resp2){\r\n\t\t\t//then load the final script\r\n\t\t\t//-update the paths to match your actual paths\r\n\t\t\tcmConnection.postMessage({\r\n\t\t\t\tmethod: 'addScripts',\r\n\t\t\t\tscripts: [\r\n\t\t\t\t\t'js/inc/ext/ext-codemirror.js'\r\n\t\t\t\t]\r\n\t\t\t});\r\n\t\t});//plugin add\r\n\t});//req/cm add\r\n}", "function codemirror_init() {\n Boa.editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {\n\tmode: { name: \"python\",\n\t\tversion: 3,\n\t\tsingleLineStringErrors: false},\n\tlineNumbers: true,\n\tindentUnit: 4,\n\tmatchBrackets: true\n });\n}", "function create_iframe(textarea) {\n var $textarea = $(textarea),\n $iframe = $('<iframe />').attr(\n 'src', $textarea.data('mmSettings').base_url),\n $codemirror = $textarea.next('.CodeMirror');\n\n $iframe\n .addClass('CodeMirror-preview')\n .on({\n 'load': function() {\n var $this = $(this);\n $this.data('load', true);\n\n if( $this.data('replace') !== undefined ) {\n $this.trigger('_update', {html: $this.data('replace')});\n }\n },\n '_resize': function() {\n $(this).css({\n 'height': $(this).prev().outerHeight()\n });\n },\n '_update': function(e, data) {\n $(this)\n .contents()\n .find('body')\n .html(data.html);\n }\n })\n .trigger('_resize')\n .appendTo($codemirror);\n\n /* update iframe contents for the first time */\n update_preview($codemirror.get(0).CodeMirror);\n}", "function getCodeOrDiffEditor(editor) {\n if (editor) {\n var control = editor.getControl();\n if (control) {\n if (Object(__WEBPACK_IMPORTED_MODULE_1__editorBrowser_js__[\"d\" /* isCodeEditor */])(control)) {\n return {\n codeEditor: control,\n diffEditor: null\n };\n }\n if (Object(__WEBPACK_IMPORTED_MODULE_1__editorBrowser_js__[\"e\" /* isDiffEditor */])(control)) {\n return {\n codeEditor: null,\n diffEditor: control\n };\n }\n }\n }\n return {\n codeEditor: null,\n diffEditor: null\n };\n}", "function parseCodeFromMainEditor() {\n \n // TODO: fix how javascript is injected and executed\n\t// Read javascript code from the jsEditor\n\t// Inject JS into DOM, so that functions can be called from python\n\t// let js_code = buffers[\"js\"].getValue();\n\t// runJS(js_code);\n\n // gets code from main editor\n\tlet mainCode = buffers['main'].getValue();\n\t/* \n\tSplit code into chunks.\n\tUses %%keyword or %% keyword as separator\n\tReturned object has: \n\t - chunkContent, chunkType, chunkId, \n\t - evalFlags, startLine, endLine \n\t*/\n\tlet parsedCode = iomdParser(mainCode);\n\tparsedCode.forEach(async (chunk) => {\n\t\t// For each type of chunk, do somthing\n\t\t// so far have py for python, md for markdown and math for math ;p\n\t\tlet content = chunk.chunkContent;\n\t\tswitch (chunk.chunkType) {\n\t\t\t// by default assume this is python code\n\t\t\t// so users don't have to type py manually\n\t\t\tcase '':\n\t\t\tcase 'py':\n\t\t\t\trunPython(content, notebook, error);\n\t\t\t\tbreak;\n\t\t\t\t// TODO: fix how js is injected and ran \n\t\t\tcase 'js':\n\t\t\t\trunJS(content);\n\t\t\t\tbreak;\n\t\t\tcase 'md':\n\t\t\t\tnotebook.innerHTML += renderMarkdown(content);\n\t\t\t\tbreak;\n\t\t\tcase 'math':\n\t\t\t\tnotebook.innerHTML += renderMath(content);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t// do nothing when we see an unknown chunk for now\n\t\t}\n\t});\n}", "function getCodeSnippets(mdContent) {\n return mdContent.replace(/\\r?\\n|\\r/, '').replace(/```[a-zA-Z]+|```/g, '').trim();\n}", "function generateEditors() {\n for (var i=0; i<editorInstances.length; i++) {\n var editInst = editorInstances[i];\n editInst.ReplaceTextarea();\n }\n}", "function TiddlyWiki(CodeMirror) {\n CodeMirror.defineMode(\"tiddlywiki\", function () {\n // Tokenizer\n var textwords = {};\n\n var keywords = {\n \"allTags\": true, \"closeAll\": true, \"list\": true,\n \"newJournal\": true, \"newTiddler\": true,\n \"permaview\": true, \"saveChanges\": true,\n \"search\": true, \"slider\": true, \"tabs\": true,\n \"tag\": true, \"tagging\": true, \"tags\": true,\n \"tiddler\": true, \"timeline\": true,\n \"today\": true, \"version\": true, \"option\": true,\n \"with\": true, \"filter\": true\n };\n\n var isSpaceName = /[\\w_\\-]/i,\n reHR = /^\\-\\-\\-\\-+$/, // <hr>\n reWikiCommentStart = /^\\/\\*\\*\\*$/, // /***\n reWikiCommentStop = /^\\*\\*\\*\\/$/, // ***/\n reBlockQuote = /^<<<$/,\n\n reJsCodeStart = /^\\/\\/\\{\\{\\{$/, // //{{{ js block start\n reJsCodeStop = /^\\/\\/\\}\\}\\}$/, // //}}} js stop\n reXmlCodeStart = /^<!--\\{\\{\\{-->$/, // xml block start\n reXmlCodeStop = /^<!--\\}\\}\\}-->$/, // xml stop\n\n reCodeBlockStart = /^\\{\\{\\{$/, // {{{ TW text div block start\n reCodeBlockStop = /^\\}\\}\\}$/, // }}} TW text stop\n\n reUntilCodeStop = /.*?\\}\\}\\}/;\n\n function chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n }\n\n function tokenBase(stream, state) {\n var sol = stream.sol(), ch = stream.peek();\n\n state.block = false; // indicates the start of a code block.\n\n // check start of blocks\n if (sol && /[<\\/\\*{}\\-]/.test(ch)) {\n if (stream.match(reCodeBlockStart)) {\n state.block = true;\n return chain(stream, state, twTokenCode);\n }\n if (stream.match(reBlockQuote))\n return 'quote';\n if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop))\n return 'comment';\n if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop))\n return 'comment';\n if (stream.match(reHR))\n return 'hr';\n }\n\n stream.next();\n if (sol && /[\\/\\*!#;:>|]/.test(ch)) {\n if (ch == \"!\") { // tw header\n stream.skipToEnd();\n return \"header\";\n }\n if (ch == \"*\") { // tw list\n stream.eatWhile('*');\n return \"comment\";\n }\n if (ch == \"#\") { // tw numbered list\n stream.eatWhile('#');\n return \"comment\";\n }\n if (ch == \";\") { // definition list, term\n stream.eatWhile(';');\n return \"comment\";\n }\n if (ch == \":\") { // definition list, description\n stream.eatWhile(':');\n return \"comment\";\n }\n if (ch == \">\") { // single line quote\n stream.eatWhile(\">\");\n return \"quote\";\n }\n if (ch == '|')\n return 'header';\n }\n\n if (ch == '{' && stream.match(/\\{\\{/))\n return chain(stream, state, twTokenCode);\n\n // rudimentary html:// file:// link matching. TW knows much more ...\n if (/[hf]/i.test(ch) &&\n /[ti]/i.test(stream.peek()) &&\n stream.match(/\\b(ttps?|tp|ile):\\/\\/[\\-A-Z0-9+&@#\\/%?=~_|$!:,.;]*[A-Z0-9+&@#\\/%=~_|$]/i))\n return \"link\";\n\n // just a little string indicator, don't want to have the whole string covered\n if (ch == '\"')\n return 'string';\n\n if (ch == '~') // _no_ CamelCase indicator should be bold\n return 'brace';\n\n if (/[\\[\\]]/.test(ch) && stream.match(ch)) // check for [[..]]\n return 'brace';\n\n if (ch == \"@\") { // check for space link. TODO fix @@...@@ highlighting\n stream.eatWhile(isSpaceName);\n return \"link\";\n }\n\n if (/\\d/.test(ch)) { // numbers\n stream.eatWhile(/\\d/);\n return \"number\";\n }\n\n if (ch == \"/\") { // tw invisible comment\n if (stream.eat(\"%\")) {\n return chain(stream, state, twTokenComment);\n } else if (stream.eat(\"/\")) { //\n return chain(stream, state, twTokenEm);\n }\n }\n\n if (ch == \"_\" && stream.eat(\"_\")) // tw underline\n return chain(stream, state, twTokenUnderline);\n\n // strikethrough and mdash handling\n if (ch == \"-\" && stream.eat(\"-\")) {\n // if strikethrough looks ugly, change CSS.\n if (stream.peek() != ' ')\n return chain(stream, state, twTokenStrike);\n // mdash\n if (stream.peek() == ' ')\n return 'brace';\n }\n\n if (ch == \"'\" && stream.eat(\"'\")) // tw bold\n return chain(stream, state, twTokenStrong);\n\n if (ch == \"<\" && stream.eat(\"<\")) // tw macro\n return chain(stream, state, twTokenMacro);\n\n // core macro handling\n stream.eatWhile(/[\\w\\$_]/);\n return textwords.propertyIsEnumerable(stream.current()) ? \"keyword\" : null\n }\n\n // tw invisible comment\n function twTokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"%\");\n }\n return \"comment\";\n }\n\n // tw strong / bold\n function twTokenStrong(stream, state) {\n var maybeEnd = false,\n ch;\n while (ch = stream.next()) {\n if (ch == \"'\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"'\");\n }\n return \"strong\";\n }\n\n // tw code\n function twTokenCode(stream, state) {\n var sb = state.block;\n\n if (sb && stream.current()) {\n return \"comment\";\n }\n\n if (!sb && stream.match(reUntilCodeStop)) {\n state.tokenize = tokenBase;\n return \"comment\";\n }\n\n if (sb && stream.sol() && stream.match(reCodeBlockStop)) {\n state.tokenize = tokenBase;\n return \"comment\";\n }\n\n stream.next();\n return \"comment\";\n }\n\n // tw em / italic\n function twTokenEm(stream, state) {\n var maybeEnd = false,\n ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"/\");\n }\n return \"em\";\n }\n\n // tw underlined text\n function twTokenUnderline(stream, state) {\n var maybeEnd = false,\n ch;\n while (ch = stream.next()) {\n if (ch == \"_\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"_\");\n }\n return \"underlined\";\n }\n\n // tw strike through text looks ugly\n // change CSS if needed\n function twTokenStrike(stream, state) {\n var maybeEnd = false, ch;\n\n while (ch = stream.next()) {\n if (ch == \"-\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"-\");\n }\n return \"strikethrough\";\n }\n\n // macro\n function twTokenMacro(stream, state) {\n if (stream.current() == '<<') {\n return 'macro';\n }\n\n var ch = stream.next();\n if (!ch) {\n state.tokenize = tokenBase;\n return null;\n }\n if (ch == \">\") {\n if (stream.peek() == '>') {\n stream.next();\n state.tokenize = tokenBase;\n return \"macro\";\n }\n }\n\n stream.eatWhile(/[\\w\\$_]/);\n return keywords.propertyIsEnumerable(stream.current()) ? \"keyword\" : null\n }\n\n // Interface\n return {\n startState: function () {\n return {tokenize: tokenBase};\n },\n\n token: function (stream, state) {\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n return style;\n }\n };\n });\n\n CodeMirror.defineMIME(\"text/x-tiddlywiki\", \"tiddlywiki\");\n }", "function CLC_GetTextContent(target){\r\n if (!target){\r\n return \"\";\r\n }\r\n if (target.nodeType == 8){ //Ignore comment nodes\r\n return \"\";\r\n } \r\n var textContentFromRole = CLC_GetTextContentFromRole(target);\r\n if (textContentFromRole){\r\n return textContentFromRole;\r\n }\r\n //Ignore scripts in the body\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"script\"){\r\n return \"\";\r\n } \r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"noscript\"){\r\n return \"\";\r\n } \r\n //Do textarea twice because it may or may not have child nodes\r\n if (target.tagName && target.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText; \r\n }\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText; \r\n }\r\n //Same logic as textarea applies for buttons\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText + target.textContent; \r\n }\r\n if (target.tagName && target.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + target.textContent; \r\n }\r\n //Form controls require special processing\r\n if (target.tagName && target.tagName.toLowerCase() == \"input\"){\r\n if (target.type.toLowerCase() == \"radio\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindRadioButtonDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"checkbox\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindCheckboxDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"text\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindTextBlankDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"password\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindPasswordDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if ( (target.type.toLowerCase() == \"submit\") || (target.type.toLowerCase() == \"reset\") || (target.type.toLowerCase() == \"button\")){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.value;\r\n }\r\n if (target.type.toLowerCase() == \"image\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.alt;\r\n }\r\n return \"\";\r\n }\r\n //MathML element - Use the functions in clc_mathml_main.js to handle these\r\n if (target.tagName && target.tagName.toLowerCase() == \"math\"){\r\n return CLC_GetMathMLContent(target);\r\n }\r\n //Images\r\n if (target.tagName && target.tagName.toLowerCase() == \"img\"){\r\n if ( target.hasAttribute(\"alt\") && target.alt == \"\" ){\r\n return \"\";\r\n }\r\n if ( target.hasAttribute(\"alt\") ){\r\n return target.alt;\r\n }\r\n //Treat missing alt as null if the user is in Brief Mode\r\n if (CLC_InfoLang == 3){\r\n return \"\";\r\n }\r\n return target.src;\r\n }\r\n //Select boxes - ignore their textContent, only read out the selected value.\r\n //However, if there is a label, use it.\r\n if (target.tagName && target.tagName.toLowerCase() == \"select\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText;\r\n }\r\n //\"Normal\" elements that are just text content and do not require any special action\r\n if (target.textContent){\r\n return target.textContent;\r\n }\r\n return \"\";\r\n }", "function docEdits_mergeCodeBlocks(srcArray, openDelim, closeDelim)\n{\n var pattern, myRe, match, whiteSpace, innerWhiteSpace, retval = \"\";\n var eolCount = 0, i;\n var block2 = srcArray.pop();\n var block1 = srcArray.pop();\n var before = \"\";\n var block1New = \"\";\n\n pattern = \"(\\\\s*)\" + dwscripts.escRegExpChars(closeDelim) + \"([\\\\s|(?:&nbsp;)]*)$\";\n myRe = new RegExp(pattern, \"i\");\n match = block1.match(myRe);\n if (match)\n {\n innerWhiteSpace = match[1];\n whiteSpace = match[2];\n i = block1.lastIndexOf(openDelim);\n before = block1.substring(0, i);\n block1New = block1.substring(i, match.index);\n\n pattern = \"^([\\\\s|(?:&nbsp;)]*)\" + dwscripts.escRegExpChars(openDelim) + \"(\\\\s*)\";\n myRe = new RegExp(pattern, \"i\");\n match = block2.match(myRe);\n if (match)\n {\n whiteSpace += match[1];\n innerWhiteSpace += match[2];\n\n //ensure separation of at least 2 newlines between code blocks\n for (i = 0; i < innerWhiteSpace.length; i++)\n {\n var tempChar = innerWhiteSpace.charAt(i);\n if (tempChar == \"\\n\" || tempChar == \"\\r\")\n {\n eolCount++;\n // If using windows style newline, \"\\r\\n\", need to step past '\\n'.\n if ( tempChar == \"\\r\" && (i + 1 < innerWhiteSpace.length)\n && innerWhiteSpace.charAt(i + 1) == \"\\n\"\n )\n {\n ++eolCount;\n }\n }\n }\n\n for (i = eolCount; i < 2; i++)\n {\n innerWhiteSpace += dwscripts.getNewline();\n }\n\n retval = before + whiteSpace + block1New + innerWhiteSpace + block2.substring(match[0].length);\n srcArray.push(retval);\n }\n }\n\n // If we couldn't merge, push the two blocks back onto the array\n if (!retval)\n {\n srcArray.push(block1);\n srcArray.push(block2);\n }\n}", "function TCL(CodeMirror) {\n CodeMirror.defineMode(\"tcl\", function() {\n function parseWords(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n }\n var keywords = parseWords(\"Tcl safe after append array auto_execok auto_import auto_load \" +\n \"auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror \" +\n \"binary break catch cd close concat continue dde eof encoding error \" +\n \"eval exec exit expr fblocked fconfigure fcopy file fileevent filename \" +\n \"filename flush for foreach format gets glob global history http if \" +\n \"incr info interp join lappend lindex linsert list llength load lrange \" +\n \"lreplace lsearch lset lsort memory msgcat namespace open package parray \" +\n \"pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp \" +\n \"registry regsub rename resource return scan seek set socket source split \" +\n \"string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord \" +\n \"tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest \" +\n \"tclvars tell time trace unknown unset update uplevel upvar variable \" +\n \"vwait\");\n var functions = parseWords(\"if elseif else and not or eq ne in ni for foreach while switch\");\n var isOperatorChar = /[+\\-*&%=<>!?^\\/\\|]/;\n function chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n }\n function tokenBase(stream, state) {\n var beforeParams = state.beforeParams;\n state.beforeParams = false;\n var ch = stream.next();\n if ((ch == '\"' || ch == \"'\") && state.inParams) {\n return chain(stream, state, tokenString(ch));\n } else if (/[\\[\\]{}\\(\\),;\\.]/.test(ch)) {\n if (ch == \"(\" && beforeParams) state.inParams = true;\n else if (ch == \")\") state.inParams = false;\n return null;\n } else if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n } else if (ch == \"#\") {\n if (stream.eat(\"*\"))\n return chain(stream, state, tokenComment);\n if (ch == \"#\" && stream.match(/ *\\[ *\\[/))\n return chain(stream, state, tokenUnparsed);\n stream.skipToEnd();\n return \"comment\";\n } else if (ch == '\"') {\n stream.skipTo(/\"/);\n return \"comment\";\n } else if (ch == \"$\") {\n stream.eatWhile(/[$_a-z0-9A-Z\\.{:]/);\n stream.eatWhile(/}/);\n state.beforeParams = true;\n return \"builtin\";\n } else if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"comment\";\n } else {\n stream.eatWhile(/[\\w\\$_{}\\xa1-\\uffff]/);\n var word = stream.current().toLowerCase();\n if (keywords && keywords.propertyIsEnumerable(word))\n return \"keyword\";\n if (functions && functions.propertyIsEnumerable(word)) {\n state.beforeParams = true;\n return \"keyword\";\n }\n return null;\n }\n }\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end) state.tokenize = tokenBase;\n return \"string\";\n };\n }\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n }\n function tokenUnparsed(stream, state) {\n var maybeEnd = 0, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd == 2) {\n state.tokenize = tokenBase;\n break;\n }\n if (ch == \"]\")\n maybeEnd++;\n else if (ch != \" \")\n maybeEnd = 0;\n }\n return \"meta\";\n }\n return {\n startState: function() {\n return {\n tokenize: tokenBase,\n beforeParams: false,\n inParams: false\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n }\n };\n });\n CodeMirror.defineMIME(\"text/x-tcl\", \"tcl\");\n\n }", "function handleTextarea() {\n content = document.getElementById('paste-area').value;\n handlePackage(content);\n}", "function createXpathArea(){\n var tact =document.getElementById('xpathArea');\n var editor = CodeMirror.fromTextArea(document.getElementById(\"xpathArea\"), {\n lineNumbers: true,\n value: \"\",\n matchBrackets: true,\n styleActiveLine: true,\n theme: \"monokai\",\n mode: \"xquery\"\n }).on('change', editor => {\n tact.value=\"\";\n });\n\n}", "buildCodePopup() {\n const cfg = this.editor.getConfig();\n\n let codePopup = document.createElement('div');\n let btnEdit = document.createElement('button');\n let btnCancel = document.createElement('button');\n let textarea = document.createElement('textarea');\n\n btnEdit.innerHTML = this.opts.sourceEditBtnLabel;\n btnEdit.className = cfg.stylePrefix + 'btn-prim ' + cfg.stylePrefix + 'btn-code-edit';\n btnEdit.onclick = this.updateCode.bind(this);\n\n btnCancel.innerHTML = this.opts.sourceCancelBtnLabel;\n btnCancel.className = cfg.stylePrefix + 'btn-prim ' + cfg.stylePrefix + 'btn-code-cancel';\n btnCancel.onclick = this.cancelCode.bind(this);\n\n codePopup.appendChild(textarea);\n codePopup.appendChild(btnEdit);\n codePopup.appendChild(btnCancel);\n\n this.codeEditor.init(textarea);\n\n return codePopup;\n }", "function codeBlockRule(nodeType) {\n return textblockTypeInputRule(/^```$/, nodeType)\n }", "function getEditorCanvas(editor) {\n return getFirstSubElementByClass(editor, \"MinMineEditor-canvas\");\n }", "function Slim(CodeMirror) {\n CodeMirror.defineMode(\"slim\", function(config) {\n var htmlMode = CodeMirror.getMode(config, {name: \"htmlmixed\"});\n var rubyMode = CodeMirror.getMode(config, \"ruby\");\n var modes = { html: htmlMode, ruby: rubyMode };\n var embedded = {\n ruby: \"ruby\",\n javascript: \"javascript\",\n css: \"text/css\",\n sass: \"text/x-sass\",\n scss: \"text/x-scss\",\n less: \"text/x-less\",\n styl: \"text/x-styl\", // no highlighting so far\n coffee: \"coffeescript\",\n asciidoc: \"text/x-asciidoc\",\n markdown: \"text/x-markdown\",\n textile: \"text/x-textile\", // no highlighting so far\n creole: \"text/x-creole\", // no highlighting so far\n wiki: \"text/x-wiki\", // no highlighting so far\n mediawiki: \"text/x-mediawiki\", // no highlighting so far\n rdoc: \"text/x-rdoc\", // no highlighting so far\n builder: \"text/x-builder\", // no highlighting so far\n nokogiri: \"text/x-nokogiri\", // no highlighting so far\n erb: \"application/x-erb\"\n };\n var embeddedRegexp = function(map){\n var arr = [];\n for(var key in map) arr.push(key);\n return new RegExp(\"^(\"+arr.join('|')+\"):\");\n }(embedded);\n\n var styleMap = {\n \"commentLine\": \"comment\",\n \"slimSwitch\": \"operator special\",\n \"slimTag\": \"tag\",\n \"slimId\": \"attribute def\",\n \"slimClass\": \"attribute qualifier\",\n \"slimAttribute\": \"attribute\",\n \"slimSubmode\": \"keyword special\",\n \"closeAttributeTag\": null,\n \"slimDoctype\": null,\n \"lineContinuation\": null\n };\n var closing = {\n \"{\": \"}\",\n \"[\": \"]\",\n \"(\": \")\"\n };\n\n var nameStartChar = \"_a-zA-Z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\";\n var nameChar = nameStartChar + \"\\\\-0-9\\xB7\\u0300-\\u036F\\u203F-\\u2040\";\n var nameRegexp = new RegExp(\"^[:\"+nameStartChar+\"](?::[\"+nameChar+\"]|[\"+nameChar+\"]*)\");\n var attributeNameRegexp = new RegExp(\"^[:\"+nameStartChar+\"][:\\\\.\"+nameChar+\"]*(?=\\\\s*=)\");\n var wrappedAttributeNameRegexp = new RegExp(\"^[:\"+nameStartChar+\"][:\\\\.\"+nameChar+\"]*\");\n var classNameRegexp = /^\\.-?[_a-zA-Z]+[\\w\\-]*/;\n var classIdRegexp = /^#[_a-zA-Z]+[\\w\\-]*/;\n\n function backup(pos, tokenize, style) {\n var restore = function(stream, state) {\n state.tokenize = tokenize;\n if (stream.pos < pos) {\n stream.pos = pos;\n return style;\n }\n return state.tokenize(stream, state);\n };\n return function(stream, state) {\n state.tokenize = restore;\n return tokenize(stream, state);\n };\n }\n\n function maybeBackup(stream, state, pat, offset, style) {\n var cur = stream.current();\n var idx = cur.search(pat);\n if (idx > -1) {\n state.tokenize = backup(stream.pos, state.tokenize, style);\n stream.backUp(cur.length - idx - offset);\n }\n return style;\n }\n\n function continueLine(state, column) {\n state.stack = {\n parent: state.stack,\n style: \"continuation\",\n indented: column,\n tokenize: state.line\n };\n state.line = state.tokenize;\n }\n function finishContinue(state) {\n if (state.line == state.tokenize) {\n state.line = state.stack.tokenize;\n state.stack = state.stack.parent;\n }\n }\n\n function lineContinuable(column, tokenize) {\n return function(stream, state) {\n finishContinue(state);\n if (stream.match(/^\\\\$/)) {\n continueLine(state, column);\n return \"lineContinuation\";\n }\n var style = tokenize(stream, state);\n if (stream.eol() && stream.current().match(/(?:^|[^\\\\])(?:\\\\\\\\)*\\\\$/)) {\n stream.backUp(1);\n }\n return style;\n };\n }\n function commaContinuable(column, tokenize) {\n return function(stream, state) {\n finishContinue(state);\n var style = tokenize(stream, state);\n if (stream.eol() && stream.current().match(/,$/)) {\n continueLine(state, column);\n }\n return style;\n };\n }\n\n function rubyInQuote(endQuote, tokenize) {\n // TODO: add multi line support\n return function(stream, state) {\n var ch = stream.peek();\n if (ch == endQuote && state.rubyState.tokenize.length == 1) {\n // step out of ruby context as it seems to complete processing all the braces\n stream.next();\n state.tokenize = tokenize;\n return \"closeAttributeTag\";\n } else {\n return ruby(stream, state);\n }\n };\n }\n function startRubySplat(tokenize) {\n var rubyState;\n var runSplat = function(stream, state) {\n if (state.rubyState.tokenize.length == 1 && !state.rubyState.context.prev) {\n stream.backUp(1);\n if (stream.eatSpace()) {\n state.rubyState = rubyState;\n state.tokenize = tokenize;\n return tokenize(stream, state);\n }\n stream.next();\n }\n return ruby(stream, state);\n };\n return function(stream, state) {\n rubyState = state.rubyState;\n state.rubyState = CodeMirror.startState(rubyMode);\n state.tokenize = runSplat;\n return ruby(stream, state);\n };\n }\n\n function ruby(stream, state) {\n return rubyMode.token(stream, state.rubyState);\n }\n\n function htmlLine(stream, state) {\n if (stream.match(/^\\\\$/)) {\n return \"lineContinuation\";\n }\n return html(stream, state);\n }\n function html(stream, state) {\n if (stream.match(/^#\\{/)) {\n state.tokenize = rubyInQuote(\"}\", state.tokenize);\n return null;\n }\n return maybeBackup(stream, state, /[^\\\\]#\\{/, 1, htmlMode.token(stream, state.htmlState));\n }\n\n function startHtmlLine(lastTokenize) {\n return function(stream, state) {\n var style = htmlLine(stream, state);\n if (stream.eol()) state.tokenize = lastTokenize;\n return style;\n };\n }\n\n function startHtmlMode(stream, state, offset) {\n state.stack = {\n parent: state.stack,\n style: \"html\",\n indented: stream.column() + offset, // pipe + space\n tokenize: state.line\n };\n state.line = state.tokenize = html;\n return null;\n }\n\n function comment(stream, state) {\n stream.skipToEnd();\n return state.stack.style;\n }\n\n function commentMode(stream, state) {\n state.stack = {\n parent: state.stack,\n style: \"comment\",\n indented: state.indented + 1,\n tokenize: state.line\n };\n state.line = comment;\n return comment(stream, state);\n }\n\n function attributeWrapper(stream, state) {\n if (stream.eat(state.stack.endQuote)) {\n state.line = state.stack.line;\n state.tokenize = state.stack.tokenize;\n state.stack = state.stack.parent;\n return null;\n }\n if (stream.match(wrappedAttributeNameRegexp)) {\n state.tokenize = attributeWrapperAssign;\n return \"slimAttribute\";\n }\n stream.next();\n return null;\n }\n function attributeWrapperAssign(stream, state) {\n if (stream.match(/^==?/)) {\n state.tokenize = attributeWrapperValue;\n return null;\n }\n return attributeWrapper(stream, state);\n }\n function attributeWrapperValue(stream, state) {\n var ch = stream.peek();\n if (ch == '\"' || ch == \"\\'\") {\n state.tokenize = readQuoted(ch, \"string\", true, false, attributeWrapper);\n stream.next();\n return state.tokenize(stream, state);\n }\n if (ch == '[') {\n return startRubySplat(attributeWrapper)(stream, state);\n }\n if (stream.match(/^(true|false|nil)\\b/)) {\n state.tokenize = attributeWrapper;\n return \"keyword\";\n }\n return startRubySplat(attributeWrapper)(stream, state);\n }\n\n function startAttributeWrapperMode(state, endQuote, tokenize) {\n state.stack = {\n parent: state.stack,\n style: \"wrapper\",\n indented: state.indented + 1,\n tokenize: tokenize,\n line: state.line,\n endQuote: endQuote\n };\n state.line = state.tokenize = attributeWrapper;\n return null;\n }\n\n function sub(stream, state) {\n if (stream.match(/^#\\{/)) {\n state.tokenize = rubyInQuote(\"}\", state.tokenize);\n return null;\n }\n var subStream = new CodeMirror.StringStream(stream.string.slice(state.stack.indented), stream.tabSize);\n subStream.pos = stream.pos - state.stack.indented;\n subStream.start = stream.start - state.stack.indented;\n subStream.lastColumnPos = stream.lastColumnPos - state.stack.indented;\n subStream.lastColumnValue = stream.lastColumnValue - state.stack.indented;\n var style = state.subMode.token(subStream, state.subState);\n stream.pos = subStream.pos + state.stack.indented;\n return style;\n }\n function firstSub(stream, state) {\n state.stack.indented = stream.column();\n state.line = state.tokenize = sub;\n return state.tokenize(stream, state);\n }\n\n function createMode(mode) {\n var query = embedded[mode];\n var spec = CodeMirror.mimeModes[query];\n if (spec) {\n return CodeMirror.getMode(config, spec);\n }\n var factory = CodeMirror.modes[query];\n if (factory) {\n return factory(config, {name: query});\n }\n return CodeMirror.getMode(config, \"null\");\n }\n\n function getMode(mode) {\n if (!modes.hasOwnProperty(mode)) {\n return modes[mode] = createMode(mode);\n }\n return modes[mode];\n }\n\n function startSubMode(mode, state) {\n var subMode = getMode(mode);\n var subState = CodeMirror.startState(subMode);\n\n state.subMode = subMode;\n state.subState = subState;\n\n state.stack = {\n parent: state.stack,\n style: \"sub\",\n indented: state.indented + 1,\n tokenize: state.line\n };\n state.line = state.tokenize = firstSub;\n return \"slimSubmode\";\n }\n\n function doctypeLine(stream, _state) {\n stream.skipToEnd();\n return \"slimDoctype\";\n }\n\n function startLine(stream, state) {\n var ch = stream.peek();\n if (ch == '<') {\n return (state.tokenize = startHtmlLine(state.tokenize))(stream, state);\n }\n if (stream.match(/^[|']/)) {\n return startHtmlMode(stream, state, 1);\n }\n if (stream.match(/^\\/(!|\\[\\w+])?/)) {\n return commentMode(stream, state);\n }\n if (stream.match(/^(-|==?[<>]?)/)) {\n state.tokenize = lineContinuable(stream.column(), commaContinuable(stream.column(), ruby));\n return \"slimSwitch\";\n }\n if (stream.match(/^doctype\\b/)) {\n state.tokenize = doctypeLine;\n return \"keyword\";\n }\n\n var m = stream.match(embeddedRegexp);\n if (m) {\n return startSubMode(m[1], state);\n }\n\n return slimTag(stream, state);\n }\n\n function slim(stream, state) {\n if (state.startOfLine) {\n return startLine(stream, state);\n }\n return slimTag(stream, state);\n }\n\n function slimTag(stream, state) {\n if (stream.eat('*')) {\n state.tokenize = startRubySplat(slimTagExtras);\n return null;\n }\n if (stream.match(nameRegexp)) {\n state.tokenize = slimTagExtras;\n return \"slimTag\";\n }\n return slimClass(stream, state);\n }\n function slimTagExtras(stream, state) {\n if (stream.match(/^(<>?|><?)/)) {\n state.tokenize = slimClass;\n return null;\n }\n return slimClass(stream, state);\n }\n function slimClass(stream, state) {\n if (stream.match(classIdRegexp)) {\n state.tokenize = slimClass;\n return \"slimId\";\n }\n if (stream.match(classNameRegexp)) {\n state.tokenize = slimClass;\n return \"slimClass\";\n }\n return slimAttribute(stream, state);\n }\n function slimAttribute(stream, state) {\n if (stream.match(/^([\\[\\{\\(])/)) {\n return startAttributeWrapperMode(state, closing[RegExp.$1], slimAttribute);\n }\n if (stream.match(attributeNameRegexp)) {\n state.tokenize = slimAttributeAssign;\n return \"slimAttribute\";\n }\n if (stream.peek() == '*') {\n stream.next();\n state.tokenize = startRubySplat(slimContent);\n return null;\n }\n return slimContent(stream, state);\n }\n function slimAttributeAssign(stream, state) {\n if (stream.match(/^==?/)) {\n state.tokenize = slimAttributeValue;\n return null;\n }\n // should never happen, because of forward lookup\n return slimAttribute(stream, state);\n }\n\n function slimAttributeValue(stream, state) {\n var ch = stream.peek();\n if (ch == '\"' || ch == \"\\'\") {\n state.tokenize = readQuoted(ch, \"string\", true, false, slimAttribute);\n stream.next();\n return state.tokenize(stream, state);\n }\n if (ch == '[') {\n return startRubySplat(slimAttribute)(stream, state);\n }\n if (ch == ':') {\n return startRubySplat(slimAttributeSymbols)(stream, state);\n }\n if (stream.match(/^(true|false|nil)\\b/)) {\n state.tokenize = slimAttribute;\n return \"keyword\";\n }\n return startRubySplat(slimAttribute)(stream, state);\n }\n function slimAttributeSymbols(stream, state) {\n stream.backUp(1);\n if (stream.match(/^[^\\s],(?=:)/)) {\n state.tokenize = startRubySplat(slimAttributeSymbols);\n return null;\n }\n stream.next();\n return slimAttribute(stream, state);\n }\n function readQuoted(quote, style, embed, unescaped, nextTokenize) {\n return function(stream, state) {\n finishContinue(state);\n var fresh = stream.current().length == 0;\n if (stream.match(/^\\\\$/, fresh)) {\n if (!fresh) return style;\n continueLine(state, state.indented);\n return \"lineContinuation\";\n }\n if (stream.match(/^#\\{/, fresh)) {\n if (!fresh) return style;\n state.tokenize = rubyInQuote(\"}\", state.tokenize);\n return null;\n }\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && (unescaped || !escaped)) {\n state.tokenize = nextTokenize;\n break;\n }\n if (embed && ch == \"#\" && !escaped) {\n if (stream.eat(\"{\")) {\n stream.backUp(2);\n break;\n }\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n if (stream.eol() && escaped) {\n stream.backUp(1);\n }\n return style;\n };\n }\n function slimContent(stream, state) {\n if (stream.match(/^==?/)) {\n state.tokenize = ruby;\n return \"slimSwitch\";\n }\n if (stream.match(/^\\/$/)) { // tag close hint\n state.tokenize = slim;\n return null;\n }\n if (stream.match(/^:/)) { // inline tag\n state.tokenize = slimTag;\n return \"slimSwitch\";\n }\n startHtmlMode(stream, state, 0);\n return state.tokenize(stream, state);\n }\n\n var mode = {\n // default to html mode\n startState: function() {\n var htmlState = CodeMirror.startState(htmlMode);\n var rubyState = CodeMirror.startState(rubyMode);\n return {\n htmlState: htmlState,\n rubyState: rubyState,\n stack: null,\n last: null,\n tokenize: slim,\n line: slim,\n indented: 0\n };\n },\n\n copyState: function(state) {\n return {\n htmlState : CodeMirror.copyState(htmlMode, state.htmlState),\n rubyState: CodeMirror.copyState(rubyMode, state.rubyState),\n subMode: state.subMode,\n subState: state.subMode && CodeMirror.copyState(state.subMode, state.subState),\n stack: state.stack,\n last: state.last,\n tokenize: state.tokenize,\n line: state.line\n };\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n state.indented = stream.indentation();\n state.startOfLine = true;\n state.tokenize = state.line;\n while (state.stack && state.stack.indented > state.indented && state.last != \"slimSubmode\") {\n state.line = state.tokenize = state.stack.tokenize;\n state.stack = state.stack.parent;\n state.subMode = null;\n state.subState = null;\n }\n }\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n state.startOfLine = false;\n if (style) state.last = style;\n return styleMap.hasOwnProperty(style) ? styleMap[style] : style;\n },\n\n blankLine: function(state) {\n if (state.subMode && state.subMode.blankLine) {\n return state.subMode.blankLine(state.subState);\n }\n },\n\n innerMode: function(state) {\n if (state.subMode) return {state: state.subState, mode: state.subMode};\n return {state: state, mode: mode};\n }\n\n //indent: function(state) {\n // return state.indented;\n //}\n };\n return mode;\n }, \"htmlmixed\", \"ruby\");\n\n CodeMirror.defineMIME(\"text/x-slim\", \"slim\");\n CodeMirror.defineMIME(\"application/x-slim\", \"slim\");\n }" ]
{ "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); }, ImportDeclaration (path: NodePath) { if (path.node.importKind !== 'type') { return; } path.get('specifiers') .forEach(specifier => { const local = specifier.get('local'); if (local.isIdentifier()) { path.scope.setData(`typechecker:${local.node.name}`, specifier); } else { path.scope.setData(`typechecker:${local.node.id.name}`, specifier); } }); }, "Function|Class" (path: NodePath) { const node = path.node; if (node.typeParameters && node.typeParameters.params) { path.get('typeParameters').get('params').forEach(typeParam => { path.get('body').scope.setData(`typeparam:${typeParam.node.name}`, typeParam); }); } } }); }
[ "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.def) : type.def);\n\t\t\t\t\tUrlMatcher.prototype.$types[type.name] = def;\n\t\t\t\t});\n\t\t\t}", "function getVarDeclarations(info, path) {\n const results = [];\n for (let current = path.head; current; current = path.childOf(current)) {\n if (!(current instanceof compiler_1.EmbeddedTemplateAst)) {\n continue;\n }\n for (const variable of current.variables) {\n let symbol = getVariableTypeFromDirectiveContext(variable.value, info.query, current);\n const kind = info.query.getTypeKind(symbol);\n if (kind === symbols_1.BuiltinType.Any || kind === symbols_1.BuiltinType.Unbound) {\n // For special cases such as ngFor and ngIf, the any type is not very useful.\n // We can do better by resolving the binding value.\n const symbolsInScope = info.query.mergeSymbolTable([\n info.members,\n // Since we are traversing the AST path from head to tail, any variables\n // that have been declared so far are also in scope.\n info.query.createSymbolTable(results),\n ]);\n symbol = refinedVariableType(variable.value, symbolsInScope, info.query, current);\n }\n results.push({\n name: variable.name,\n kind: 'variable',\n type: symbol, get definition() { return getDefinitionOf(info, variable); },\n });\n }\n }\n return results;\n}", "function discoverTypes () {\n // rdf:type properties of subjects, indexed by URI for the type.\n\n const types = {}\n\n // Get a list of statements that match: ? rdfs:type ?\n // From this we can get a list of subjects and types.\n\n const subjectList = kb.statementsMatching(\n undefined,\n UI.ns.rdf('type'),\n tableClass, // can be undefined OR\n sourceDocument\n ) // can be undefined\n\n // Subjects for later lookup. This is a mapping of type URIs to\n // lists of subjects (it is necessary to record the type of\n // a subject).\n\n const subjects = {}\n\n for (let i = 0; i < subjectList.length; ++i) {\n const type = subjectList[i].object\n\n if (type.termType !== 'NamedNode') {\n // @@ no bnodes?\n continue\n }\n\n const typeObj = getTypeForObject(types, type)\n\n if (!(type.uri in subjects)) {\n subjects[type.uri] = []\n }\n\n subjects[type.uri].push(subjectList[i].subject)\n typeObj.addUse()\n }\n\n return [subjects, types]\n }", "resolve() {\n this.resolver.resolveAll(this.sources.definitions);\n }", "function collectRefsRecursive(host, content, refs) {\n var childNodes = host.childNodes;\n for (var i = 0, n = content.length; i < n; ++i) {\n var elem = content[i];\n var type = elem.type;\n if (type === 1 /* Node */) {\n var node = childNodes[i];\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = node;\n collectRefsRecursive(node, elem.children, refs);\n }\n else if (type === 2 /* Component */) {\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = componentMap.get(childNodes[i]);\n }\n }\n }", "function InferTypes () {\n ASTTransform.call(this);\n this.varDefs = {};\n this.fnSignatures = {};\n this.fnTypeHints = {};\n this.fnRenaming = {};\n this.runAgain = false;\n}", "visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getBaseDeclarations() {\r\n return utils_1.ArrayUtils.flatten(this.getType().getBaseTypes().map(t => {\r\n const symbol = t.getSymbol();\r\n return symbol == null ? [] : symbol.getDeclarations();\r\n }));\r\n }", "function generateResolversRecursively(path = '', module = {}) {\n /**\n * Create a resolver for the current level\n */\n resolvers.push(createResolver({ path, module }));\n\n /**\n * Recurse deeper if applicable\n */\n if (module.options && Array.isArray(module.options.modules)) {\n module.options.modules.forEach((module, i) => {\n if (module) {\n const nextPath = `${path}.options.modules[${i}]`;\n generateResolversRecursively(nextPath, module);\n }\n });\n }\n }", "pathRefs(editor) {\n var refs = PATH_REFS.get(editor);\n\n if (!refs) {\n refs = new Set();\n PATH_REFS.set(editor, refs);\n }\n\n return refs;\n }", "getDeclarativeTypes(_resourceExplorer) {\n return this.services.mustMakeInstance('declarativeTypes');\n }", "function everythingWasDeclared(files) {\n\tconst includes = []\n\tconst declared = []\n\tfiles.forEach(f => (\n\t\tincludes.push(...f.includes),\n\t\tdeclared.push(f.declares)\n\t))\n\tincludes.forEach(include => {\n\t\tif (!declared.includes(include)) {\n\t\t\tthrow new Error(`Attempted to include ${include} but it was never declared.`)\n\t\t}\n\t})\n}", "onResolve(context, reflection) {\n if (reflection.kindOf(index_1.ReflectionKind.ClassOrInterface)) {\n this.postpone(reflection);\n walk(reflection.implementedTypes, (target) => {\n this.postpone(target);\n if (!target.implementedBy) {\n target.implementedBy = [];\n }\n target.implementedBy.push(new index_2.ReferenceType(reflection.name, reflection, context.project));\n });\n walk(reflection.extendedTypes, (target) => {\n this.postpone(target);\n if (!target.extendedBy) {\n target.extendedBy = [];\n }\n target.extendedBy.push(new index_2.ReferenceType(reflection.name, reflection, context.project));\n });\n }\n function walk(types, callback) {\n if (!types) {\n return;\n }\n types.forEach((type) => {\n if (!(type instanceof index_2.ReferenceType)) {\n return;\n }\n if (!type.reflection ||\n !(type.reflection instanceof index_1.DeclarationReflection)) {\n return;\n }\n callback(type.reflection);\n });\n }\n }", "enterTypeImportOnDemandDeclaration(ctx) {\n\t}", "addTypes(types) {\n for (const [key, value] of Object.entries(types)) {\n this.addType(key, value);\n }\n return this;\n }", "function buildWebTypes() {\n const analysis = loadAnalysis();\n\n const packageJson = JSON.parse(fs.readFileSync(`./package.json`, 'utf8'));\n const entrypoints = analysis.modules.filter((el) => !el.path.startsWith('lib'));\n\n const plainWebTypes = createPlainWebTypes(packageJson, entrypoints);\n const plainWebTypesJson = JSON.stringify(plainWebTypes, null, 2);\n fs.writeFileSync(PLAIN_WEB_TYPES_FILE, plainWebTypesJson, 'utf8');\n\n const litWebTypes = createLitWebTypes(packageJson, entrypoints);\n const litWebTypesJson = JSON.stringify(litWebTypes, null, 2);\n fs.writeFileSync(path.join(LIT_WEB_TYPES_FILE), litWebTypesJson, 'utf8');\n}", "removeTypeBindings() {\n this.tokens.copyExpectedToken(_types.TokenType._import);\n if (\n this.tokens.matchesContextual(_keywords.ContextualKeyword._type) &&\n !this.tokens.matchesAtIndex(this.tokens.currentIndex() + 1, [_types.TokenType.comma]) &&\n !this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, _keywords.ContextualKeyword._from)\n ) {\n // This is an \"import type\" statement, so exit early.\n return true;\n }\n\n if (this.tokens.matches1(_types.TokenType.string)) {\n // This is a bare import, so we should proceed with the import.\n this.tokens.copyToken();\n return false;\n }\n\n let foundNonTypeImport = false;\n\n if (this.tokens.matches1(_types.TokenType.name)) {\n if (this.isTypeName(this.tokens.identifierName())) {\n this.tokens.removeToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n }\n } else {\n foundNonTypeImport = true;\n this.tokens.copyToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.copyToken();\n }\n }\n }\n\n if (this.tokens.matches1(_types.TokenType.star)) {\n if (this.isTypeName(this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 2))) {\n this.tokens.removeToken();\n this.tokens.removeToken();\n this.tokens.removeToken();\n } else {\n foundNonTypeImport = true;\n this.tokens.copyExpectedToken(_types.TokenType.star);\n this.tokens.copyExpectedToken(_types.TokenType.name);\n this.tokens.copyExpectedToken(_types.TokenType.name);\n }\n } else if (this.tokens.matches1(_types.TokenType.braceL)) {\n this.tokens.copyToken();\n while (!this.tokens.matches1(_types.TokenType.braceR)) {\n if (\n this.tokens.matches3(_types.TokenType.name, _types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches3(_types.TokenType.name, _types.TokenType.name, _types.TokenType.braceR)\n ) {\n // type foo\n this.tokens.removeToken();\n this.tokens.removeToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n }\n } else if (\n this.tokens.matches5(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches5(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.braceR)\n ) {\n // type foo as bar\n this.tokens.removeToken();\n this.tokens.removeToken();\n this.tokens.removeToken();\n this.tokens.removeToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n }\n } else if (\n this.tokens.matches2(_types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches2(_types.TokenType.name, _types.TokenType.braceR)\n ) {\n // foo\n if (this.isTypeName(this.tokens.identifierName())) {\n this.tokens.removeToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n }\n } else {\n foundNonTypeImport = true;\n this.tokens.copyToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.copyToken();\n }\n }\n } else if (\n this.tokens.matches4(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches4(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.braceR)\n ) {\n // foo as bar\n if (this.isTypeName(this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 2))) {\n this.tokens.removeToken();\n this.tokens.removeToken();\n this.tokens.removeToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n }\n } else {\n foundNonTypeImport = true;\n this.tokens.copyToken();\n this.tokens.copyToken();\n this.tokens.copyToken();\n if (this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.copyToken();\n }\n }\n } else {\n throw new Error(\"Unexpected import form.\");\n }\n }\n this.tokens.copyExpectedToken(_types.TokenType.braceR);\n }\n\n return !foundNonTypeImport;\n }", "update(_path, needValueType = false){\n if(_path){\n for(var [key,value] of _path.valueMap){\n var valuetype;\n if (valuetype = this.valueMap.get(key)){\n valuetype.update(value);\n }else{\n valuetype = new ValueType();\n if(!value)\n console.log(_path);\n valuetype.update(value);\n this.valueMap.set(key,valuetype);\n }\n \n }\n\n if(needValueType){\n this._valueType.update(_path._valueType);\n }\n }\n }", "function addType() {\n\t\tvar args = extract(\n\t\t\t{ name: 'name', test: function(o) { return typeof o === 'string'; } },\n\t\t\t{ name: 'type', parse: function(o) {\n\t\t\t\treturn (o instanceof Type) ? o : new Type(this.name || o.name, o);\n\t\t\t} }\n\t\t).from(arguments);\n\n\t\ttypeList.push(args.type);\n\t}" ]
{ "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(product_id, qty)\n{\n\t\n\t//Save new quantity into the product in order_list \n\tif(qty<0) return;\n\t\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\tredraw_order_list()\n\t}\n}", "function addInventory() {\n\n\t//Lets manager identify which item to credit\n\tinquirer\n\t\t.prompt ({\n\t\t\tname: \"restock_product\",\n\t\t\ttype: \"input\",\n\t\t\tmessage: \"Type the Id of the product you want to re-stock:\"\n\t\t})\n\t\t//Initiates database credit process\n\t\t.then(function(answer) {\n\n\t\t\t//Queries database and increases quantity by +5\n\t\t\tconnection.query(\"UPDATE products SET quantity = quantity + 5 WHERE id =\"+answer.restock_product, function(err, res) {\n\t\t\tif (err) throw err;\n\n\t\t\t//Returns the updated inventory table\n\t\t\tallInventory();\n\t\t\t})\n\t\t}\n\t)\n}", "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 addToInventory() {\n\t// Querying the Database\n\tconnection.query(\"SELECT * FROM products\", function (err, res) {\n\n\t\tif (err) throw err;\n \n // Setting up our results in the console.table NPM\n consoleTable(\"\\nCurrent Inventory Data\", res);\n \n\t\t// Inquirer asking Manager to select ID of the item they wish to add Inventory of\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\tname: \"id\",\n\t\t\t\tmessage: \"Input the item ID to increase inventory on.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0 && value <= res.length) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"amount\",\n\t\t\t\tmessage: \"Input the amount to increase inventory by.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t]).then(function(answer) {\n\n\t\t\tvar itemQty;\n\n\t\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\t\tif (parseInt(answer.id) === res[i].item_id) {\n\t\t\t\t\titemQty = res[i].stock_quantity;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Call the function to Increase the Quantity with the Parameters needed\n\t\t\tincreaseQty(answer.id, itemQty, answer.amount);\n\t\t});\n\t});\n}", "function updateQuantity () {\n connection.query(\"UPDATE products SET ? WHERE ?\",\n [\n {\n stock_quantity: newStockNum\n },\n {\n item_id: itemSelected\n }\n ], function (err, results) {\n if (err) {\n throw err;\n };\n console.log(`\\n${product_name} received ${addedStock} units for a total of ${newStockNum}`);\n }\n );\n connection.end();\n}", "function handleIncrease() {\n if (selectedAmount < stockCount) setSelectedAmount(selectedAmount + 1);\n }", "function updateQuantityLocalStorageBasket(id) {\n let input = event.target\n let found = false\n for(let i = 0; !found && i < basket.length; i++) {\n if(id === basket[i].productId){\n found = true\n basket[i].quantity = parseInt(input.value) //la méthode pour la transformation en type number n'est peut-être pas nécessaire car sera stringifié par la suite\n }\n }\n localStorage.setItem('basket', JSON.stringify(basket));\n}", "function quantityChanged(event) {\n let input = event.target;\n if(isNaN(input.value) || input.value <= 0) {\n input.value = 1\n }\n let id = input.parentElement.previousElementSibling.children[2].innerText\n updateQuantityLocalStorageBasket(id)\n updateBasketTotal();\n}", "function updateQuantity()\n{\n\tconsole.log(\"\\n**ADD TO INVENTORY**\");\n\n\tINQUIRER.prompt([\n\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tmessage: \"Product ID:\",\n\t\t\tname: \"id\",\n\t\t\tfilter: id => parseInt(id),\n\t\t\tvalidate: id => (id > 0 && id != NaN) ? true : console.log(\"ID Must Be A Number > 0\")\n\t\t},\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tmessage: \"Additional Quantity\",\n\t\t\tname: \"quantity\",\n\t\t\tfilter: q => parseInt(q),\n\t\t\tvalidate: q => (q > 0 && q != NaN) ? true : console.log(\"Quantity Must Be A Number > 0\")\n\t\t},\n\n\t]).then(function(product){\t\n\n\t\t// Data values provided by user used to update. \n\t\tlet update = [product.quantity, product.id];\n\n\t\tCONNECTION.query('UPDATE products SET stock_quantity=stock_quantity+? WHERE item_id=?', update, function (error, results, fields) {\t\n\t\t\tif (error) throw error;\n\t\t\n\t\t\tconsole.log(\"\\nProduct Quantity Successfully Added.\\n\");\n\n\t\t\tINQUIRER.prompt([\n\t\t\t{\t\n\t\t\t\ttype: 'list',\n\t\t\t\tmessage: \"What Would You Like To Do?\",\n\t\t\t\tchoices: [\t\"Add Another Product Inventory\",\n\t \t\t\t\t\t\"Return To Main Menu\",\n\t \t\t\t\t\t\"Quit\"\n\t \t\t \t\t ],\n\t\t\t\tname: \"choice\"\n\t\t\t}\t\n\n\t\t\t]).then(function(res){\n\n\t\t\t\tswitch (res.choice)\n\t\t\t\t{\n\t\t\t\t\tcase \"Add Another Product Inventory\":\n\t\t\t\t\t\tupdateQuantity();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"Return To Main Menu\":\t\n\t\t\t\t\t\tmainMenu();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconsole.log(\"\\nGOODBYE!\");\n\t\t\t\t\t\tCONNECTION.end();\n\t\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t});\n}//END updateQuantity()", "static updateInventory() {\n\t\tthis.resetInventory();\n\t\tstoryData.story.items.forEach(function(item) {\n\t\t\tif (item.owned) UI.addItem(item);\n\t\t});\n\t}", "function editProductLocalStorage(productId, quantity) {\n //get the local storage data\n let productsInStorage = getProductsFromStorage();\n let quantityNew = quantity;\n let productToEdit;\n\n //loop through the array to find the index to remove\n productsInStorage.map(function (productInStorage, index) {\n if (productInStorage.productId === productId) {\n productToEdit = productInStorage;\n productToEdit.quantity = quantityNew;\n productsInStorage.splice(index, 1);\n }\n });\n\n productsInStorage.push(productToEdit);\n // add the rest of the array\n localStorage.setItem(\"products\", JSON.stringify(productsInStorage));\n updateView();\n}", "function updateQuantity() {\n let quantityInputs = document.getElementsByClassName(\"quantity-input\");\n for (let i = 0; i < quantityInputs.length; i++) {\n let input = quantityInputs[i];\n input.addEventListener(\"change\", quantityChanged);\n }\n\n function quantityChanged(e) {\n let input = e.target;\n let stock = parseFloat(document.getElementById(\"stock\").innerText);\n if (isNaN(input.value) || input.value <= 0) {\n input.value = 1;\n }\n\n if (input.value > stock) {\n input.value = stock;\n }\n }\n}", "function qtyMath(qty, id) {\n var tst = connection.query(\n \"SELECT * FROM products WHERE ?\", [{\n item_id: id\n }],\n function (err, res) {\n let qtyLeft = (res[0].stock_quantity - qty);\n let total = (res[0].price * qty);\n if (qtyLeft < 0) {\n console.log(\"***quantity exceeds stock available, please try again!***\");\n start();\n } else {\n updateTable(qtyLeft, id, total);\n }\n });\n }", "function decQty() {\n\tconsole.log(\"Decreasing quantity\");\n\tconsole.log(this);\n\n\tvar id = this.getAttribute(\"id\");\n\tvar index = id.substr(3);\n\tvar count = --cart[index][0];\n\n\t// Removes the item from the list when the quantity is 0 or less.\n\tif (count <= 0) {\n\t\tcart.splice(index, 1)\n\t\tconsole.log($(this).parent().remove());\n\t}\n\n\tdisplayCart();\n}", "function updateQuantity(artId) {\n var deferred = q.defer();\n artModel.findById(artId, function(err, art) {\n if(err) {\n deferred.reject(err);\n } else {\n art.quantity = art.quantity - 1;\n art.save(function(error, result) {\n deferred.resolve(result);\n });\n }\n });\n return deferred.promise;\n }", "function itemQuantity() {\n let increase = document.querySelectorAll(\"i.fa-plus\");\n let decrease = document.querySelectorAll(\"i.fa-minus\");\n let currentQuantity = 0;\n let currentProduct = \"\";\n\n let foodItems = localStorage.getItem(\"foodsInCart\");\n foodItems = JSON.parse(foodItems);\n\n for (let i = 0; i < increase.length; i++) {\n increase[i].addEventListener(\"click\", () => {\n currentQuantity =\n increase[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = increase[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n foodItems[currentProduct].inCart += 1;\n cartCounter(foodItems[currentProduct]);\n totalCost(foodItems[currentProduct]);\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n });\n }\n\n for (let i = 0; i < decrease.length; i++) {\n decrease[i].addEventListener(\"click\", () => {\n currentQuantity =\n decrease[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = decrease[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n if (foodItems[currentProduct].inCart > 1) {\n foodItems[currentProduct].inCart -= 1;\n cartCounter(foodItems[currentProduct], \"decrease\");\n totalCost(foodItems[currentProduct], \"decrease\");\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n }\n });\n }\n}", "function C006_Isolation_Yuki_StealItems() {\t\n\tPlayerSaveAllInventory();\n\tPlayerRemoveAllInventory();\n}", "function reduceItems(item, quantity) {\n\tconnection.query(\"UPDATE products SET quantity = quantity -\"+quantity+\" WHERE id = \"+item, function(err,res) {\n\tif (err) throw err;\n\t})\n}" ]
{ "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 }", "function fDbg(v)\n{\n\tconsole.log(\"|~|\" + v);\n}", "function debugLog() {\n if (_debug) {\n console.log.apply(console, arguments);\n }\n }", "function debugLog(str) { if ( DEBUG && window.console ) console.log(str); }", "debugSuccess(message, metadata, metadataStyles) {\n let _messageType13 = t.string();\n\n let _metadataType15 = t.nullable(t.object());\n\n let _metadataStylesType14 = t.nullable(t.object());\n\n t.param('message', _messageType13).assert(message);\n t.param('metadata', _metadataType15).assert(metadata);\n t.param('metadataStyles', _metadataStylesType14).assert(metadataStyles);\n\n this.log(message, metadata, levels.DEBUG, {\n metadataStyles,\n symbol: '✔',\n styles: ['green']\n });\n }", "function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}", "function setupDebug(){\n debug = new DEBUGTOOL(false,null,[8,8,16]);\n}", "function debug(affichage) {\n if(jQuery.browser.opera) {\n opera.postError(affichage);// Opera\n }else if(jQuery.browser.mozilla) {\n if (window.console && window.console.firebug) { \n console.debug(affichage);// FF\n }\n }else if(jQuery.browser.webkit) {\n if (window.console) { \n console.log(affichage);// safari // Chrome\n }\n }\n }", "function log() {\n if (!started)\n started = Date.now();\n var elapsed = Math.round((Date.now() - started) / 1000);\n console.log.\n bind(undefined, '[' + elapsed + 's]').\n apply(undefined, arguments);\n}", "printDebug()\n {\n console.log(\"Tree contents\");\n this.iterateTree(function(node)\n {\n console.log(node);\n });\n }", "trace() {\n const tracing = remote.contentTracing;\n const opts = {\n categoryFilter: '*',\n traceOptions: 'record-until-full,enable-sampling,enable-systrace',\n };\n return tracing.startRecording(opts, () => {\n console.log('Tracing started');\n return setTimeout(() =>\n tracing.stopRecording('', p => console.log(`Tracing data recorded to ${p}`))\n\n , 5000);\n });\n }", "function isStatsLogEnabled () {\n return flags.DEBUG || flags.LOG_STATS\n }", "function consOut( mssg ) {\n\tif (window.debug) {\n\t\tconsole.log(mssg);\n\t}\n}", "function PrintDebugConsole() {\n\n let delegateHandlers = {\n giveDelegate: (name, amount) => {\n return name + \" ma dac ogolnie \" + amount.toFixed(2) + \" zl\\r\\n\";\n },\n receiveDelegate: (name, amount) => {\n return name + \" ma dostac ogolnie \" + amount.toFixed(2) + \" zl\\r\\n\";\n },\n tradeDelegate: (from, to, amount) => {\n return from + \" ma odddac \" + amount.toFixed(2) + \" zl dla \" + to + \"\\r\\n\";\n },\n };\n\n let arr = ExampleData();\t//array of people\n People.Add(arr);\n let res = People.Calculate(/*delegateHandlers*/);\t\t//calculate all\n\n //print statistics\n console.log(\"L. os: \" + res.PersonCount\t\t\t\t\t\t//liczba osob skladajacych sie\n + \"\\r\\nSuma: \" + res.Sum \t\t\t\t\t\t//suma wszystkich hajsow za prezent\n + \"\\r\\nZl/Os: \" + res.SumPerOs + \"\\r\\n\");\t\t//ile przypada na osobe\n\n\n console.log(res.ResultText);\t//print result of calculations\n}", "function onGenerateDebugInfo() {\n clearTimeout(timer);\n if (po.obj.lstatus.match(/ready/g) == \"ready\") {\n blockUI_confirm(\"Confirm to discard current log and generate new one\",\n sendobjects_setRefreshTimer, setRefreshTimer);\n return;\n }\n if (po.obj.lstatus.match(/waiting for result/g) == \"waiting for result\") {\n blockUI_confirm(\"Confirm to ignore current order and generate new one\", sendobjects_setRefreshTimer, setRefreshTimer);\n return;\n }\n sendobjects_setRefreshTimer();\n}", "function logText(text) {\n\tif(config.dev_log) {\n\t\tvar currentTime = new Date();\n\t\tvar currentDay = ensureNumberStringLength(currentTime.getDate(), 2);\n\t\tvar currentMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][currentTime.getMonth()];\n\t\tvar currentYear = currentTime.getFullYear();\n\t\tvar currentHours = ensureNumberStringLength(currentTime.getHours(), 2);\n\t\tvar currentMinutes = ensureNumberStringLength(currentTime.getMinutes(), 2);\n\t\tvar currentSeconds = ensureNumberStringLength(currentTime.getSeconds(), 2);\n\n\t\tvar timestamp = ' [{dd}/{month}/{yyyy} {hh}:{mm}:{ss}] '.format({\n\t\t\tdd: currentDay, month: currentMonth, yyyy: currentYear,\n\t\t\thh: currentHours, mm: currentMinutes, ss: currentSeconds\n\t\t});\n\n\t\tvar textArray = text.split('\\n');\n\n\t\tfor (var i = textArray.length - 1; i > 0; i--) {\n\t\t\t$('.log-pre').prepend('<span class=\"log-time\">{whitespace}</span>{text}\\n'.format({\n\t\t\t\twhitespace: ' '.repeat(24),\n\t\t\t\ttext: textArray[i]}));\n\t\t}\n\t\t$('.log-pre').prepend('<span class=\"log-time\">{stamp}</span>{text}\\n'.format({\n\t\t\tstamp: timestamp,\n\t\t\ttext: textArray[0]}));\n\t} else {\n\t\twindow.console.log(text);\n\t}\n}", "attackHitLog(enemyName){\n let logString = `\\n${this.name} hit ${enemyName} for ${this.attack} damage!`;\n this.updateBattleLog(logString);\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.0 / gamma)),\n clamp(Math.pow(b, 1.0 / gamma))\n\n );\n }", "function Color3(/**\n * Defines the red component (between 0 and 1, default is 0)\n */r,/**\n * Defines the green component (between 0 and 1, default is 0)\n */g,/**\n * Defines the blue component (between 0 and 1, default is 0)\n */b){if(r===void 0){r=0;}if(g===void 0){g=0;}if(b===void 0){b=0;}this.r=r;this.g=g;this.b=b;}", "static Green() {\n return new Color3(0, 1, 0);\n }", "static FromInts(r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n }", "static FromColor3(color3, alpha = 1.0) {\n return new Color4(color3.r, color3.g, color3.b, alpha);\n }", "function gamma(done) {\n var gamma = 2.8; // Correction factor\n var MAX_IN = 255; // Tope end of INPUT range\n var MAX_OUT = 255; // Tope end of OUTPUT range\n var destination = 'gamma.h';\n\n var ws = fs.createWriteStream(destination);\n\n ws.on('error', function (err) {\n console.log(err);\n });\n\n ws.write('// This table remaps linear input values to nonlinear gamma-corrected output\\n');\n ws.write('// values. The output values are specified for 8-bit colours with a gamma\\n');\n ws.write('// correction factor of 2.8\\n');\n ws.write('const static uint8_t PROGMEM gamma8[256] = {');\n for (var i = 0; i <= MAX_IN; i++) {\n if (i > 0) {\n ws.write(',');\n }\n\n if ((i & 15) === 0) {\n ws.write('\\n');\n }\n\n var level = (Math.floor(Math.pow(i / MAX_IN, gamma) * MAX_OUT + 0.5));\n ws.write((\" \" + level).slice(-4));\n }\n\n ws.write(' };\\n');\n ws.end();\n\n done();\n}", "function CMYK_TO_RGBA() {\n var c = this.c();\n var m = this.m();\n var y = this.y();\n var black = this.b();\n\n var r = 1 - Math.min(1, c * (1 - black) + black);\n var g = 1 - Math.min(1, m * (1 - black) + black);\n var b = 1 - Math.min(1, y * (1 - black) + black);\n return kolor.rgba(r * 255, g * 255, b * 255, this.a());\n }", "toLinearSpace() {\n const convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor);\n return convertedColor;\n }", "static Magenta() {\n return new Color3(1, 0, 1);\n }", "function GRAY_TO_RGBA() {\n var s = this.s();\n var a = this.a();\n\n return kolor.rgba(s, s, s, a);\n }", "function RGBA_TO_HSVA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var h;\n var s;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n if (max === 0) {\n s = 0;\n } else {\n s = diff / max;\n }\n\n var v = max;\n return kolor.hsva(h, s, v, a);\n }", "static Red() {\n return new Color3(1, 0, 0);\n }", "function REMOVE_ALPHA() {\n var space = this.space();\n var channels = SPACES[space].channels;\n var result = [];\n\n var l = channels.length;\n for (var i = 0; i < l - 1; i++) {\n result.push(this[channels[i].name]());\n }\n return new kolor[space.slice(0, -1)](result);\n }", "subtract(otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n }", "multiplyToRef(color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n }", "static Gray() {\n return new Color3(0.5, 0.5, 0.5);\n }", "static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }", "static Yellow() {\n return new Color3(1, 1, 0);\n }" ]
{ "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 ? if (index !== -1) { removeIndex(array, index); } if (toIndex == null) { array.push(element); } else { insertIndex(array, toIndex, element); } }
[ "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);\n array.splice(index, 1);\n array.push(item);\n}", "function pushIfNotIn(el, arr) {\n if (!~arr.indexOf(el)) {\n arr.push(el);\n }\n }", "function insert(array, element) {\n array.push(element);\n return function () {\n var index = array.indexOf(element);\n if (index > -1) {\n array.splice(index, 1);\n }\n };\n}", "sendToBack(element) {\n return this.changeIndexTo(element, 0, false);\n\n if (index > 0) {\n this._children.splice(index, 1);\n this._children.splice(0, 0, element);\n }\n }", "function add_elem(element, index) {\n //Get old element and copy to new element\n var ul = document.getElementById(element);\n var li_old = ul.children[ul.children.length-1];\n var li_new = li_old.cloneNode(true); \n\n //Empty values and change index\n EmptyValues(li_new);\n ChangeIndex(li_new, index+1);\n\n //Change index of all following elements in list.\n for (var i=index+1; i<ul.children.length; i++)\n ChangeIndex(ul.children[i], i+1);\n \n //Insert element at given position.\n InsertIntoList(ul, li_new, index);\n}", "push(element){\n\t\tthis.size++;\n\t\tthis.q2.push(element);\n\t\twhile(this.q1.length > 0)\n\t\t\tthis.q2.push(this.q1.shift()); // shift is same as dequeue\n\t\t//swap q1 and q2\n\t\tlet q = this.q1;\n\t\tthis.q1 = this.q2;\n\t\tthis.q2 = q;\n\t}", "push(element) {\r\n //this.stack.push(element);\r\n this.stack.unshift(element);\r\n }", "bringToFront(element) {\n return this.changeIndexTo(element, this._children.length, false);\n\n if (element.parent != this) return ;\n var index = this._children.indexOf(element);\n if (index >= 0 && index < this._children.length - 1) {\n this._children.splice(index, 1);\n this._children.push(element);\n }\n }", "addAtIndex(task, index) {\n if(index === 0) {\n this.addToFront(task);\n } else if(index === this._taskArr.length) {\n this.addToBack(task);\n } else if(index < this._taskArr.length) {\n this._taskArr.splice(index,0, task);\n this.adjustTaskStartTime(index + 1);\n }\n }", "push() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n this._addArgs.index = this._array.length;\n\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n var source = arguments[0];\n\n for (var i = 0, l = source.length; i < l; i++) {\n this._array.push(source[i]);\n }\n } else {\n this._array.push.apply(this._array, arguments);\n }\n\n this._addArgs.addedCount = this._array.length - this._addArgs.index;\n this.notify(this._addArgs);\n\n this._notifyLengthChange();\n\n return this._array.length;\n }", "function appendArr(num, arr){\n\tn = arr.length\n\tif(n<12){\n\t\tarr.push(num)\n\t}\n\telse{\n\t\tvar i = childIsEmpty(arr, -1)\n\t\tif(i === -1){\n\t\tfor(var j = 0;j < 12;j++){\n\t\t\tarr[j] = arr[j + 1]\t\t\t\n\t\t}\n arr[n - 1] = num\n\t\t}\n\t\telse arr[i] = num\n\t}\t\n}", "function addUnique(array, object) {\n for(var i in array) {\n if(array[i]==object) {\n return false;\n }\n }\n\n array[array.length] = object;\n return true;\n }", "addIfNotIncluded(arr, elem) {\n if (!arr || !elem) return 0;\n if (!Array.isArray(arr)) return 0;\n\n let elemJson = JSON.stringify(elem);\n\n // when the 'elem' is already included in the 'arr' array\n // don't add it again\n if (!JSON.stringify(arr).includes(elemJson)) {\n // let's create the deep copy of 'elem'\n arr.push(JSON.parse(elemJson));\n }\n\n return arr.length;\n }", "function arrayContainsAfterIndex(arr, ele, index) {\n for (let i = index + 1; i < arr.length; i++) {\n if (arr[i] == ele) {\n return true;\n }\n }\n return false;\n}", "changeIndexTo(element, indexOrDelta, relative) {\n if (element.parent != this) return ;\n\n var newIndex = indexOrDelta;\n if (relative || false) {\n newIndex = index + indexOrDelta;\n }\n\n if (newIndex < 0)\n newIndex = 0;\n if (newIndex >= this._children.length)\n newIndex = this._children.length - 1;\n\n var index = this._children.indexOf(element);\n if (newIndex == index) {\n return ;\n }\n var event = new events.ElementIndexChanged(element, index, newIndex);\n if (this.validateBefore(event.name, event) != false &&\n element.validateBefore(event.name, event) != false) {\n this._children.splice(index, 1);\n this._children.splice(newIndex, 0, element);\n this.triggerOn(event.name, event);\n element.triggerOn(event.name, event);\n }\n }", "sendBackward(element) {\n return this.changeIndexTo(element, -1, true);\n\n if (index > 0) {\n var temp = this._children[index];\n this._children[index] = this._children[index - 1];\n this._children[index - 1] = temp;\n }\n }", "function addChild(parent, child, childElement) {\n (parent.nodes || parent).push(child);\n (parent.el || rootTreeElement).appendChild(childElement);\n child.parentElement = (parent.el || rootTreeElement);\n }", "function addItemToFront(arr, item) {\n arr.unshift(item);\n return arr;\n}" ]
{ "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 var can = document.getElementById('can_hidden'),\n\n ctx = can.getContext('2d'),\n\n imgUrl = url;\n\n\n\n var img = new Image();\n\n img.src = url;\n\n\n\n var img2 = new Image();\n\n img2.src = 'https://'+dominio+'img/bg-canvas.jpg';\n\n\n\n ctx.drawImage(img2, 0, 0);\n\n ctx.drawImage(img, 30, 80);\n\n\n\n $('#can_hidden').hide();\n\n }", "function close_image() {\n image_viewer.style.display = \"none\";\n}", "function removePreviousImage() {\n $capturedImage.empty();\n $capturedImage.removeAttr('style');\n $fridge.removeClass('hide');\n}", "function newImage() {\n hangman.flagImage.style.opacity = 0;\n hangman.flagImage.style.backgroundImage = 'url(' + flagUrl(hangman.chosenWord) +')'\n }", "function blockPopupBackground() {\n $(\"#background-main-div\").removeClass(\"hidden\"); \n}", "function ImageError(image)\n{\n image.style.display = \"none\";\n}", "function showmain_img(btnsw,hid1,hid2,hid3,hid4,hid5,hid6,shwmain){\n\n\tbtnsw.click(function(){\n\n\t\thid1.hide(\"fast\");\n\n\t\thid2.hide(\"fast\");\n\n\t\thid3.hide(\"fast\");\n\n\t\thid4.hide(\"fast\");\n\n\t\thid5.hide(\"fast\");\n\n\t\thid6.hide(\"fast\");\n\n\t\tshwmain.show(\"fast\");\n\n\t});\n\n}", "function unblockPopupBackground() {\n $(\"#background-main-div\").addClass(\"hidden\"); \n}", "function closeGif() {\n $chosenGif.hide();\n}", "function showImgStyle(){\n\tviewStyling(\"none\");\n\tvar styleBlocks = document.getElementsByClassName(\"imgStyle\"); \n\tfor (var i = styleBlocks.length - 1; i >= 0; i--) {\n\t\tstyleBlocks[i].style.display = \"inline\"; \n\t};\n}", "function showOriginal() {\n const showOriginalBtn = document.querySelector('#show-original');\n if (originalImage.style.display == 'none') {\n originalImage.style.display = 'block';\n showOriginalBtn.style.color = '#CD343A';\n \n }\n else {\n originalImage.style.display = 'none';\n showOriginalBtn.style.color = '#ededed';\n } \n}", "function checkDeathCondition() {\n if (currentRoom === 0) {\n const img1 = document.querySelector(\".hiddenUntilDead\")\n img1.style.display = \"unset\"\n }\n}", "function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }", "function unhide()\r\n{\r\n if (document.querySelector('.pumpkin').style.visibility == \"visible\")\r\n {\r\n document.querySelector('.pumpkin').style.visibility = \"hidden\";\r\n }\r\n else\r\n {\r\ndocument.querySelector('.pumpkin').style.visibility = \"visible\";\r\n }\r\n}", "function showDefaultBuddyIcon(image_element) {\n image_element.onerror = '';\n image_element.src = 'https://www.flickr.com/images/buddyicon.gif';\n return true;\n}", "function MasklayerHide() {\r\n var bgObj = document.getElementById(\"MaskLayout\");\r\n bgObj.style.display = \"none\";\r\n//\tif($.browser.firefox){\r\n//\t\tvar bgObjfirefox=document.getElementById(\"MaskLayoutFirefox\");\r\n//\t\tbgObjfirefox.style.display = \"none\";\r\n//\t}\r\n}", "function ChangeImage(dest, img, hide)\n\t{\n\t\t//console.log(\"what i got: \" + img);\n\t\t$(dest).attr(\"src\", img);\n\t\t//document.getElementById(\"img01\").src=\"img1.jpg\";\n\n\t\t//hide the loaded img info\n\t\t$(hide).hide();\n\t}" ]
{ "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}", "function checkIfFloat(value) {\r\n if (value.toString().indexOf('.', 0) > -1) {\r\n return parseFloat(value).toFixed(2);\r\n }\r\n else {\r\n return value;\r\n }\r\n}", "function safeParseFloat(value) {\n if (!value) {\n return 0.00;\n }\n if (ok(value, tyString)) {\n return parseFloat(value);\n }\n if (ok(value, tyNumber)) {\n return value;\n }\n return 0.00;\n }", "function validFloatinRange(formField,fieldLabel,required,valueMin,valueMax)\r\n\t{\r\n\tvar result = true;\r\n\tif (!validFloat(formField,fieldLabel,required)) result = false;\t\r\n\tif (result)\r\n \t\t{\r\n \t\tif(formField.value < valueMin || formField.value > valueMax)\r\n\t\t\t{\r\n \t\t\talert('Please enter a number for: ' + fieldLabel +' which is greater than or equal to ' + valueMin + ' and less than or equal to ' + valueMax + '.');\r\n\t\t\tformField.focus();\t\t\r\n\t\t\tresult = false;\r\n\t\t\t}\r\n\t\t} \r\n\treturn result;\r\n\t}", "function CheckFloat3decimal(resid) {\r\n var num = document.getElementById(resid).value;\r\n var tomatch = /^\\d*(\\.\\d{1,3})?$/;\r\n if (tomatch.test(num)) {\r\n return true;\r\n }\r\n else {\r\n alert(\"Input error\");\r\n\r\n document.getElementById(resid).value = \"\";\r\n document.getElementById(resid).focus();\r\n return false;\r\n }\r\n}", "function checkDecimal()\n{\n let re = /^([0-9]*|[0-9]*\\.[0-9]*)$/;\n let number = this.value.trim();\n setErrorFlag(this, re.test(number) && number > 0);\n}", "function number (thing) {\n return typeof thing === 'number' && isNaN(thing) === false;\n }", "function readFloat(x, f)\n//\n// Input: none\n// Output: x = pointer to a float variable\n// Purpose: reads a floating point value from a hot start file\n//\n{\n // --- read a value from the file\n fread(x, sizeof(float), 1, f);\n\n // --- test if the value is NaN (not a number)\n if ( (x) != (x) )\n {\n report_writeErrorMsg(ERR_HOTSTART_FILE_READ, \"\");\n (x) = 0.0;\n return FALSE;\n }\n return TRUE;\n}", "function validate(n) {\n\tvar x = parseFloat(n);\n\treturn (!isNaN(x) && isFinite(x)) ? x : null;\n}", "function float(val, def)\n {\n if (isNaN(val)) return def;\n\n return parseFloat(val);\n }", "function AcceptDecimal(str) {\n //http://lawrence.ecorp.net/inet/samples/regexp-validate2.php\n str = trim(str);\n var regDecimal = /^[-+]?[0-9]+(\\.[0-9]+)?$/;\n return regDecimal.test(str);\n}", "function isNumber (input) {\n \t\treturn typeof input === \"number\" && !isNaN(input); \n }", "function toFloat(n, fallback) {\n\tif (fallback === undefined) fallback = 0.0;\n\tn = parseFloat(n);\n\tif (isNaN(n)) n = fallback;\n\treturn n;\n}", "function convertible(value, ty) {\n if (ok(value, ty)) {\n return true;\n }\n if (isNull(value) || isUndefined(value)) {\n return false;\n }\n if (ty === tyNumber && isNaN(value)) {\n return false;\n }\n // TODO: refine\n return true;\n }", "[symbols.call](obj=0.0)\n\t{\n\t\tif (typeof(obj) === \"string\")\n\t\t\treturn parseFloat(obj);\n\t\telse if (typeof(obj) === \"number\")\n\t\t\treturn obj;\n\t\telse if (obj === true)\n\t\t\treturn 1.0;\n\t\telse if (obj === false)\n\t\t\treturn 0.0;\n\t\tthrow new TypeError(\"float() argument must be a string or a number\");\n\t}", "equalsToFloats(x, y, z) {\n return this.x === x && this.y === y && this.z === z;\n }", "function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n const sign = value < 0 ? -1 : 1;\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\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 infectedGrid = {x:row+1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column+1] == opponent) { var infectedGrid = {x:row+1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column+1] == opponent) { var infectedGrid = {x:row, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column+1] == opponent) { var infectedGrid = {x:row-1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column] == opponent) { var infectedGrid = {x:row-1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column-1] == opponent) { var infectedGrid = {x:row-1, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column-1] == opponent) { var infectedGrid = {x:row, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column-1] == opponent) { var infectedGrid = {x:row+1, y:column-1}; infectedGridList.push(infectedGrid); } } if(row > 0 && row < length - 1 && column == 0) { if(currentBoard[row+1][column] == opponent) { var infectedGrid = {x:row+1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column+1] == opponent) { var infectedGrid = {x:row+1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column+1] == opponent) { var infectedGrid = {x:row, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column+1] == opponent) { var infectedGrid = {x:row-1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column] == opponent) { var infectedGrid = {x:row-1, y:column}; infectedGridList.push(infectedGrid); } } if(row > 0 && row < length - 1 && column == length - 1) { if(currentBoard[row-1][column] == opponent) { var infectedGrid = {x:row-1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column-1] == opponent) { var infectedGrid = {x:row-1, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column-1] == opponent) { var infectedGrid = {x:row, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column-1] == opponent) { var infectedGrid = {x:row+1, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column] == opponent) { var infectedGrid = {x:row+1, y:column}; infectedGridList.push(infectedGrid); } } if(row == 0 && column > 0 && column < length - 1) { if(currentBoard[row+1][column] == opponent) { var infectedGrid = {x:row+1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column+1] == opponent) { var infectedGrid = {x:row+1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column+1] == opponent) { var infectedGrid = {x:row, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column-1] == opponent) { var infectedGrid = {x:row, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row+1][column-1] == opponent) { var infectedGrid = {x:row+1, y:column-1}; infectedGridList.push(infectedGrid); } } if(row == length - 1 && column > 0 && column < length - 1) { if(currentBoard[row][column+1] == opponent) { var infectedGrid = {x:row, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column+1] == opponent) { var infectedGrid = {x:row-1, y:column+1}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column] == opponent) { var infectedGrid = {x:row-1, y:column}; infectedGridList.push(infectedGrid); } if(currentBoard[row-1][column-1] == opponent) { var infectedGrid = {x:row-1, y:column-1}; infectedGridList.push(infectedGrid); } if(currentBoard[row][column-1] == opponent) { var infectedGrid = {x:row, y:column-1}; infectedGridList.push(infectedGrid); } } return infectedGridList; }
[ "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_state, starting_square) {\n let valid_destinations = [];\n\n rows.forEach(row => {\n cols.forEach(col => {\n const chess_engine = new Chess(board_state);\n const square = `${col}${row}`;\n\n if (square != starting_square && chess_engine.move({\n from: starting_square,\n to: square,\n }) !== undefined) {\n valid_destinations.push(square);\n }\n\n });\n });\n\n return valid_destinations;\n}", "function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}", "function createGameGrid() {\n var grid = new Array(Constants.numberOfRows);\n for (var row = 0; row < Constants.numberOfRows; row++) {\n grid[row] = new Array(Constants.numberOfColumns);\n for (var col = 0; col < Constants.numberOfColumns; col++) {\n grid[row][col] = {\n state: 0,\n liveNeighbors: 0,\n bool: false,\n distance: 1000,\n indexRow: row,\n indexColumn: col,\n parent: null,\n\n };\n }\n }\n return grid;\n}", "function drawGrid() {\n for(var i = 0; i < nRows; i++) {\n\tfor(var j = 0; j < nCols; j++) {\n\t if(gol.getCell(i, j) == 1)\n\t\tgridCtx.fillStyle = \"white\";\n\t else\n\t\tgridCtx.fillStyle = \"black\";\n\t gridCtx.fillRect(j * cellWidth + 1, i * cellHeight + 1, cellWidth - 2, cellHeight - 2);\n\t}\n }\n //console.log(gol.toString());\n}", "function resetGrid(){\n for (var col = 0; col < width; col++){\n var drop = document.getElementById('drop-'+col);\n drop.setAttribute('style','');\n drop.setAttribute('fill-opacity','0');\n }\n document.getElementById('game_end').style.display = 'none';\n playerTurn = 1;\n moveNumber = 1;\n document.getElementById('player_turn').innerHTML = \"Player 1's Move\";\n gameOver = false;\n for (var row = 0; row < height; row++){\n for (var col = 0; col < width; col++){\n grid[row][col] = 0;\n }\n }\n drawGrid();\n makeBotMove();\n}", "function minimax(state, limit, player) {\n var moves = [];\n if(limit > 0) {\n //Loop over the state matrix checking if the squares are undefined (empty).\n //Values set to the gameboard columns, 7x6.\n for(var idx1 = 0; idx1 < 7; idx1++) {\n for(var idx2 = 0; idx2 < 6; idx2++) {\n //If the square is empty create a new object representing a potential move.\n if(state[idx1][idx2] === undefined) {\n //Added to code to ensure the computers markers drop to the bottom of the column. The same principle as\n //what can be found in 'click' function ensuring the users marker drops to the bottom of the column.\n idx2 = 5;\n while(state[idx1][idx2]) {\n idx2 = idx2 - 1;\n }\n if(idx2 >= 0) {\n var move = {\n x: idx1,\n y: idx2,\n //When a potential move is generated, use the deepClone function to also store the state after this move.\n state: deepClone(state),\n score: 0\n };\n move.state[idx1][idx2] = player;\n //Check to see if the game is at a leaf in the game tree or at an internal node. The distinction is made by first checking to see if the 'limit' is 1 or if the game has been won.\n if(limit === 1 || check_game_winner(move.state) !== undefined) {\n //Updated upon creation of heuristic function. Calls the function instead of the previous hard-coded heuristic based on game winner.\n move.score = heuristic(move.state);\n }\n // Handling of the internal node case.\n else {\n //Recursively calculate all moves and call the minimax function with the updated move.state, the 'limit' reduced by 1 and the players switched.\n //Assign list of all posible moves to move.moves.\n //It's important to remember that moves are given a score!\n move.moves = minimax(move.state, limit - 1, player == 'Red' ? 'Yellow' : 'Red');\n var score = undefined;\n //Loop over all of the move.moves handling one of three cases:\n for(var idx3 = 0; idx3 < move.moves.length; idx3++) {\n //Meaning this is the current move and assign the 'score' the moves score.\n if(score === undefined) {\n score = move.moves[idx3].score;\n }\n //The current player is 'Red' (user), calculate the score as the max of the score and that potential moves score.\n else if(player === 'Red') {\n score = Math.max(score, move.moves[idx3].score);\n }\n //The current player is 'Yellow' (computer), calculate the score as the max of the score and that potential moves score.\n else if(player === 'Yellow') {\n score = Math.min(score, move.moves[idx3].score);\n }\n }\n move.score = score;\n }\n moves.push(move);\n }\n }\n }\n }\n }\n return moves;\n}", "drawGrid() {\n const { id, selected } = this.currentWord;\n\n clear();\n this.logger.log(figlet.textSync(wordsearchConstants.GAME_TITLE, { font: 'Mini' }));\n this.logger.log(wordsearchConstants.GAME_INFO);\n this.logger.log(chalk.grey(wordsearchConstants.GAME_INSTRUCTIONS));\n\n this.grid.forEach((row, rowIdx) => {\n // first add all letters in the row (with correct colours)\n const rowData = [];\n row.forEach((item, itemIdx) => {\n if (this.guessedWords.indexOf(item.word) !== -1) {\n rowData.push(chalk.green(item.letter));\n } else if (item.word === id && selected.indexOf(`${rowIdx},${itemIdx}`) !== -1) {\n rowData.push(chalk.black.bgGreen(item.letter));\n } else {\n rowData.push(item.letter);\n }\n });\n let rowStr = rowData.join(' ');\n\n // then add a word from the word list to the right of the grid\n if (this.wordsearchWordList[rowIdx]) {\n rowStr += wordsearchConstants.WORD_SPACING;\n let word = this.wordsearchWordList[rowIdx];\n if (this.guessedWords.indexOf(rowIdx) !== -1) {\n word = chalk.green(word);\n }\n rowStr += word;\n }\n\n this.logger.log(rowStr);\n });\n\n this.setCursorPos();\n }", "function buildBoard() {\r\n randomMinePos()\r\n var board = [];\r\n for (var i = 0; i < gLevels[gChosenLevelIdx].SIZE; i++) {\r\n board[i] = [];\r\n for (var j = 0; j < gLevels[gChosenLevelIdx].SIZE; j++) {\r\n board[i][j] = createCell(i, j);\r\n\r\n }\r\n }\r\n setMinesNegsCount(board)\r\n return board;\r\n}", "function useGame({\n initialGrid,\n generateGrid,\n rows,\n columns,\n mines,\n}) {\n const [playGrid, setPlayGrid] = useState(\n Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(null)),\n );\n\n const [gameState, setGameState] = useState('playing');\n\n /**\n * Function to call when left click on cell\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const toggleFlag = (isFlagged, rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n newPlayGrid[rowIndex][columnIndex] = isFlagged ? null : 'F';\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Function to call when right click on cell\n * @param {event} event need event to prevent default behaviour\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const handleRightClickOnCell = (event, rowIndex, columnIndex) => {\n event.preventDefault();\n const content = playGrid[rowIndex][columnIndex];\n const isFlagged = content === 'F';\n if (gameState === 'playing' && (isFlagged || content === null)) {\n toggleFlag(isFlagged, rowIndex, columnIndex);\n }\n };\n\n /**\n * Update gameState (victory/defeat/playing)\n * @returns {void}\n */\n const checkResult = () => {\n let newState = 'playing';\n let remainingCellCount = 0;\n for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {\n for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {\n const content = playGrid[rowIndex][columnIndex];\n if (content === 'F' || content === null) {\n // Count cells that weren't tested\n remainingCellCount += 1;\n } else if (content === 'X') {\n newState = 'defeat';\n setGameState(newState);\n return;\n }\n }\n }\n if (remainingCellCount === mines) {\n newState = 'victory';\n }\n setGameState(newState);\n };\n\n const revealGrid = () => {\n const newPlayGrid = [...playGrid];\n playGrid.forEach(((row, rowIndex) => {\n row.forEach((cell, columnIndex) => {\n if (cell === 'X') {\n newPlayGrid[rowIndex][columnIndex] = 'B';\n } else {\n newPlayGrid[rowIndex][columnIndex] = initialGrid[rowIndex][columnIndex];\n }\n });\n }));\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Reveal safe zone around safe cell located at rowIndex, columnIndex\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const revealZone = (rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n\n let cellsToReveal = [[rowIndex, columnIndex]];\n let newCellsToReveal = [];\n let row;\n let column;\n\n const hasBeenChecked = Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(false));\n\n do {\n newCellsToReveal = [];\n for (let i = 0; i < cellsToReveal.length; i += 1) {\n [row, column] = cellsToReveal[i];\n // reveal current cell\n newPlayGrid[row][column] = initialGrid[row][column];\n hasBeenChecked[row][column] = true;\n\n // search for adjacent cells to reveal\n if (row - 1 >= 0) {\n if (!hasBeenChecked[row - 1][column]) {\n if (initialGrid[row - 1][column] === 0) {\n // add top cell\n newCellsToReveal.push([row - 1, column]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column] = initialGrid[row - 1][column];\n }\n hasBeenChecked[row - 1][column] = true;\n }\n if (column - 1 >= 0 && !hasBeenChecked[row - 1][column - 1]) {\n if (initialGrid[row - 1][column - 1] === 0) {\n // add top left hand corner cell\n newCellsToReveal.push([row - 1, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column - 1] = initialGrid[row - 1][column - 1];\n }\n hasBeenChecked[row - 1][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row - 1][column + 1]) {\n if (initialGrid[row - 1][column + 1] === 0) {\n // add top right hand corner cell\n newCellsToReveal.push([row - 1, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column + 1] = initialGrid[row - 1][column + 1];\n }\n hasBeenChecked[row - 1][column + 1] = true;\n }\n }\n\n if (column - 1 >= 0 && !hasBeenChecked[row][column - 1]) {\n if (initialGrid[row][column - 1] === 0) {\n // add left cell\n newCellsToReveal.push([row, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row][column - 1] = initialGrid[row][column - 1];\n }\n hasBeenChecked[row][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row][column + 1]) {\n if (initialGrid[row][column + 1] === 0) {\n // add right cell\n newCellsToReveal.push([row, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row][column + 1] = initialGrid[row][column + 1];\n }\n hasBeenChecked[row][column + 1] = true;\n }\n\n if (row + 1 < rows) {\n if (!hasBeenChecked[row + 1][column]) {\n if (initialGrid[row + 1][column] === 0) {\n // add bottom cell\n newCellsToReveal.push([row + 1, column]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column] = initialGrid[row + 1][column];\n }\n hasBeenChecked[row + 1][column] = true;\n }\n\n if (column - 1 >= 0 && !hasBeenChecked[row + 1][column - 1]) {\n if (initialGrid[row + 1][column - 1] === 0) {\n // add bottom left hand cell\n newCellsToReveal.push([row + 1, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column - 1] = initialGrid[row + 1][column - 1];\n }\n hasBeenChecked[row + 1][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row + 1][column + 1]) {\n if (initialGrid[row + 1][column + 1] === 0) {\n // add bottom right hand cell\n newCellsToReveal.push([row + 1, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column + 1] = initialGrid[row + 1][column + 1];\n }\n hasBeenChecked[row + 1][column + 1] = true;\n }\n }\n }\n // update cellsToReveal\n cellsToReveal = [...newCellsToReveal];\n // keep searching unless there are no more cells to reveal\n } while (cellsToReveal.length > 0);\n // update playGrid\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Reveal cell content located at rowIndex, columnIndex\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const revealCell = (rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n const content = initialGrid[rowIndex][columnIndex];\n newPlayGrid[rowIndex][columnIndex] = content;\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Check content of cell at (rowIndex, columnIndex) in initGrid and change state of playGrid\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {int}\n */\n const tryCell = (rowIndex, columnIndex) => {\n const content = initialGrid[rowIndex][columnIndex];\n\n if (content === 0) {\n // reveal zone\n revealZone(rowIndex, columnIndex);\n } else {\n // revealCell\n revealCell(rowIndex, columnIndex);\n }\n };\n\n /**\n * Function to call when left click on cell\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const handleLeftClickOnCell = (rowIndex, columnIndex) => {\n if (gameState !== 'playing' || playGrid[rowIndex][columnIndex] !== null) {\n return;\n }\n tryCell(rowIndex, columnIndex);\n };\n\n const reset = () => {\n generateGrid(rows, columns, mines);\n setPlayGrid(Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(null)));\n setGameState('playing');\n };\n\n useEffect(() => {\n reset();\n }, [rows, columns]);\n\n useEffect(() => {\n if (gameState === 'playing') {\n checkResult();\n }\n }, [playGrid]);\n\n useEffect(() => {\n if (gameState !== 'playing') {\n revealGrid();\n }\n }, [gameState]);\n\n return {\n playGrid,\n setPlayGrid,\n gameState,\n handleLeftClickOnCell,\n handleRightClickOnCell,\n tryCell,\n toggleFlag,\n checkResult,\n reset,\n };\n}", "placeShips() {\n if(this.ships.length > 0) {\n for(let i = 0; i < this.ships.length; i++) {\n const ship = this.ships[i];\n for(let j = 0; j < ship.coords.length; j++) {\n const index = this.findCellByXY(ship.coords[j].x, ship.coords[j].y);\n this.matrix[index].status = 's';\n }\n }\n }\n }", "revealPosition({row, col}) {\n // if game state is finished or cell is not hidden, return game state\n let gameFinished = this._state.endgame !== RSGame.GAME_IN_PROGRESS;\n let isHiddenCell = this._state.fog[row][col] === RSGame.HIDDEN_CELL;\n if (gameFinished || !isHiddenCell) {\n return this._state;\n }\n // find out which cells to reveal and reveal them\n let cellsToReveal = this._getCellsToReveal({row, col});\n cellsToReveal.forEach(({row, col}) => {\n this._state.fog[row][col] = RSGame.REVEALED_CELL;\n });\n // if revealing a mine cell, convert it to a hot mine and end the game\n if (this._state.minefield[row][col] === RSGame.MINE_CELL) {\n this._state.minefield[row][col] = RSGame.HOT_MINE_CELL;\n this._setPlayerLostEndgame();\n } else if (this._playerHasWon()) {\n this._setPlayerWonEndgame();\n }\n return this._state;\n }", "function getAdjacentTileIDs(id) {\n\tid = Number(id);\n\t// Format: top, right, bottom, left\n var neighbors = [];\n\n var top = false;\n var right = false;\n var bottom = false;\n var left = false;\n\n // Check if this chunk is on an edge\n if (0 <= id && id < cols) top = true;\n if ((id + 1) % cols == 0) right = true;\n if ((rows - 1) * cols <= id && id < rows * cols) bottom = true;\n if (id % cols == 0) left = true;\n \n // Top neighbor\n\tif (!top) neighbors.push(Number(id) - cols);\n else neighbors.push(-1); // Edge case, return -1 for this direction\n // Right neighbor\n if (!right) neighbors.push(Number(id) + 1);\n else neighbors.push(-1);\n // Bottom neighbor\n if (!bottom) neighbors.push(Number(id) + cols);\n else neighbors.push(-1);\n // Left neighbor\n if (!left) neighbors.push(Number(id) - 1);\n else neighbors.push(-1);\n\n return neighbors;\n}", "function checkGrid(grid) {\n var oldSpace = [];\n grid.forEach(function(ary) {\n ary.forEach(function(box) {\n\n //var banned = document.getElementById(box.id-1); //do not allow\n var north = document.getElementById(box.id-20);\n var northEast = document.getElementById(box.id-19);\n var northWest = document.getElementById(box.id-21);\n var east = document.getElementById(parseInt(box.id)+1);\n var west = document.getElementById(box.id-1);\n var south = document.getElementById(parseInt(box.id)+20);\n var southEast = document.getElementById(parseInt(box.id)+21);\n var southWest = document.getElementById(parseInt(box.id)+19);\n var boxConnect = 0;\n\n // if((box.id % 20 === 0 && box.checked === true) && banned.checked === true) {\n // console.log(box.id + \" \" + banned.id);\n // }\n if((box.checked === true && box.id > 19) && north.checked === true) {\n //console.log(\"North: \" + box.id + \" \" + north.id);\n boxConnect++;\n }\n if((box.checked === true && box.id > 19) && northEast.checked === true) {\n //console.log(\"Northeast: \" + box.id + \" \" + northEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id % 20 !== 0) && (box.id > 19 && northWest.checked === true)) {\n //console.log(\"Northwest: \" + box.id + \" \" + northWest.id);\n boxConnect+=2;\n }\n if((box.checked === true && (parseInt(box.id)+1)%20 !== 0) && east.checked === true) {\n //console.log(\"East: \" + box.id + \" \" + east.id);\n boxConnect++;\n }\n if(box.checked === true && west.checked === true && (box.id-1)%20 !== 19) {\n //console.log(\"West: \" + box.id + \" \" + west.id);\n boxConnect++;\n }\n if((box.checked === true && box.id < 380) && south.checked === true) {\n //console.log(\"South: \" + box.id + \" \" + south.id);\n boxConnect++;\n }\n if(box.checked === true && (box.id < 380) && southEast.checked === true) {\n //console.log(\"Southeast: \" + box.id + \" \" + southEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id < 380) && southWest.checked === true) {\n //console.log(\"Southwest: \" + box.id + \" \" + southWest.id);\n boxConnect+=2;\n }\n\n function ridSingles() {\n if(boxConnect < 2) {\n box.checked = false;\n }\n }\n\n //1.store old box.id in array\n //2.uncheck old position during random space move\n //3.check new position after random space move with new box.id\n // *******THIS IS THE PROBLEM*******\n function moveBoxes() {\n var spaces = [1, -1, 19, 20, 21, -19, -20, -21];\n var randNewSpace = Math.floor(Math.random()*spaces.length);\n if(box.checked === true && box.id < 400 || box.id > 0){\n box.id = parseInt(box.id)+ parseInt(spaces[randNewSpace]);\n //console.log(parseInt(box.id) + parseInt(spaces[randNewSpace]));\n box.id = parseInt(box.id);\n }\n else if(box.checked === true && box.id > 400 || box.id < 0){\n box.checked = false;\n }\n }\n\n setInterval(function() {\n ridSingles();\n moveBoxes();\n }, 1000);\n });\n //console.log(ary);\n });\n\n}", "function getNeighbors(cell) {\n let neighbors = [];\n\n // A cells neighbors is all vertically, horizontally, and\n // diagonally adjacent cells. To find all neighbors we need to\n // iterate the 3x3 area surrounding the target cell. We can\n // accomplish this by starting our iteration one cell less than\n // the target cell, and end one cell beyond.\n let y = cell.getY() - 1\n let yBoundary = cell.getY() + 1\n\n while (y <= yBoundary) {\n\n // If the starting cell is out of bounds then we need to\n // determine which boundary is being violated. We will treat this\n // as an infinite space so the cell will switch to evaluating\n // the cell on the opposite end of the board.\n\n // If we are within the accepted boundaries then use the position.\n let yPosition = 0\n\n if (y >= 0 && y < config.cellsPerColumn) {\n yPosition = y;\n } else {\n\n // If we are negative then we have stretched beyond the top boundary.\n // Update the position to be at the bottom boundary. Otherwise, we\n // have stretched beyond the bottom boundary so update the position\n // to be at the top boundary.\n if (y < 0) {\n yPosition = config.cellsPerColumn - 1;\n }\n }\n\n let x = cell.getX() - 1\n let xBoundary = cell.getX() + 1\n\n while (x <= xBoundary) {\n\n // Similar to the y boundary, we need to determine if a\n // boundary is being violated, and respond accordingly.\n let xPosition = 0\n\n if (x >= 0 && x < config.cellsPerRow) {\n xPosition = x;\n } else {\n if (x < 0) {\n xPosition = config.cellsPerRow - 1;\n }\n }\n\n // Determine the index of the neighboring cell.\n const cellPosition = new Map()\n .set(Cell.ATTR_POSITION_Y, yPosition)\n .set(Cell.ATTR_POSITION_X, xPosition)\n const neighborIndex = calculateCellIndex(cellPosition)\n\n // Verify this cell is not the same as the target cell.\n // If it's not the same cell then add it to the array of\n // neighboring cells.\n let neighboringCell = cells[neighborIndex];\n\n if (neighboringCell !== cell) {\n neighbors.push(neighboringCell);\n }\n\n // Increment x position\n x++\n }\n\n // Increment y position\n y++\n }\n\n return neighbors;\n }", "function createChessGrid() {\n var color = \"w\";\n for (var j = 0; j < 8; j++) {\n let line = [];\n for (var i = 0; i < 8; i++) {\n var tile = createTile(j * WIDTH + 20, i * HEIGHT + 20, color);\n tile.placedPiece = \"\";\n line.push(tile);\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n }\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n grid.push(line);\n }\n}", "function updateGameGrid(x, y, p){\n var t = pixToGrid(x, y);\n gameGrid[t.row][t.col] = p;\n}", "function gridify() {\n let numDivision = ceil(Math.sqrt(obj.numOfMols));\n let spacing = (width - obj.maxMolSize) / numDivision;\n\n molecules.forEach((molecule, index) => {\n\n let colPos = (index % numDivision) * spacing;\n let rowPos = floor(index / numDivision) * spacing;\n //console.log(`The col pos ${colPos} and the row pos ${rowPos}`);\n molecule.position.x = colPos + obj.maxMolSize;\n molecule.position.y = rowPos + obj.maxMolSize;\n\n });\n}", "function startGame () {\n var x = document.getElementsByClassName(\"hidden\");\n for (var i = 0; i < x.length; i++) {\n addListeners(x[i]);\n addCellToBoard(x[i]);\n }\n\n for (var i = 0; i < board.cells.length; i++) {\n var x = countSurroundingMines(board.cells[i]);\n board.cells[i].surroundingMines = x;\n }\n}" ]
{ "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.appState.data.seizureData;\n\n // Generate CSV\n let csv = 'is-seizure,is-seizure-user-corrected\\n';\n\n for( let i = 0; i < output.length; i++ ) {\n csv += `${Number(outputFrozen[i])},${Number(output[i])}\\n`;\n }\n\n // Generate data URI and associated link\n let blob = new Blob([csv], {type: 'text/csv'});\n let filename = 'export.csv';\n let objectURL = window.URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.setAttribute('download', filename);\n a.setAttribute('href', objectURL);\n\n // Trigger download\n a.click();\n\n // Clear blob from memory\n window.URL.revokeObjectURL(objectURL);\n }", "function clicSaveEverything() {\r\n var data_export = {};\r\n data_export[\"market\"] = data;\r\n data_export[\"simulation\"] = simopt;\r\n var save = JSON.stringify(data_export);\r\n document.location=\"data:text/csv;base64,\"+btoa(save);\r\n\r\n}", "saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }", "static save_both (comp) {\n if (comp.object3D) {\n const kid = comp.object3D\n kid.isVisible = true\n const kids = kid.getChildren()\n for (let i = 0; i < kids.length; i++) {\n kids[i].setEnabled(true)\n }\n kids[kids.length - 1].isVisible = false\n\n var myser = BABYLON.SceneSerializer.SerializeMesh(comp.object3D, false, true)\n var jsonData = JSON.stringify(myser)\n\n // Component.doDownload('part.babylon', new Blob([jsonData], { type: 'octet/stream' }))\n return [new Blob([jsonData], { type: 'octet/stream' }), new Blob([jsonData], { type: 'octet/stream' })]\n }\n }", "export() {\n let data = [];\n let totalAnimationSteps = this.stepCount + 1;\n\n writeUint8(totalAnimationSteps, data);\n \n for (var i = 0; i < totalAnimationSteps; i++) \n {\n\n let totalColorsInCurrentStep = Object.keys(this.colors[i]).length;\n\n if (totalColorsInCurrentStep === 0 && totalAnimationSteps === 0)\n {\n console.log(\"Nothing to export.\")\n return;\n }\n\n writeUint16(totalColorsInCurrentStep, data);\n\n for (const color of Object.keys(this.colors[i])) \n {\n let rgb = hexToRgb(color)\n writeUint8(rgb.r, data)\n writeUint8(rgb.g, data)\n writeUint8(rgb.b, data)\n let ledsWithThisColor = this.getLedsWithColor(i, color);\n writeUint16(ledsWithThisColor.length, data)\n ledsWithThisColor.forEach(elem => {\n writeUint16(elem, data);\n })\n }\n\n\n }\n\n var blob = new Blob(data, { type: \"application/octet-stream\" });\n var blobUrl = URL.createObjectURL(blob);\n window.location.replace(blobUrl);\n\n var fileLink = document.createElement('a');\n fileLink.href = blobUrl\n fileLink.download = \"animation.bin\"\n fileLink.click();\n\n }", "function saveData() {\n var self = this;\n\n try {\n localStorage.setItem(\n self.data.name,\n JSON.stringify(self.getArrayOfData())\n );\n } catch (e) {\n console.error('Local storage save failed!', e);\n }\n\n }", "_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }", "function M_objecto(collection) {\n V_objeto_dinamico = [];\n collection.forEach(doc => {\n V_objeto_dinamico.push(doc.data());\n });\n}", "downloadData() {\n let domEl = document.createElement('a');\n domEl.id = \"download\";\n domEl.download = this._options.download.filename || \"grapher_data.csv\";\n domEl.href = URL.createObjectURL(new Blob([Grapher.to_csv(this.data)]));\n domEl.click();\n }", "function salvandoDados () {\n\n localStorage.setItem('tarefas', JSON.stringify(tarefas));\n\n}", "_generateObjectDataFromFiles() {\n\t\t// ---- LANG FILE ---\n\t\tvar langFile = fs.readFileSync(this.langFilePath, 'utf16le');\n\t\tthis.langData = vdf.parse(langFile);\n\t\t//Hack for tought Little Indian Character in object name after VDF.parse\n\t\t//Little Indian Character here \"-->\\\"lang\\\"\"\n\t\tvar littleEndianName = '\\uFEFF\\\"lang\\\"';\n\t\tthis.langData.lang = this.langData[littleEndianName];\n\t\tdelete this.langData[littleEndianName];\n\n\t\t// ---- ITEMGAME FILE ---\n\t\tvar itemsFile = fs.readFileSync(this.itemsFilePath, 'utf8');\n\t\tthis.itemsData = simplevdf.parse(itemsFile);\n\n\t\t// ---- SCHEMA FILE --- \n\t\tvar schemaFile = fs.readFileSync(this.schemaFilePath, 'utf8');\n\t\tthis.schemaData = simplevdf.parse(schemaFile);\n\t}", "saveAsJSON() {\n const bench = this.state.benchInfo;\n for (const benchResult in this.state.benchResults) {\n if (\n (this.state.benchResults[benchResult].hasOwnProperty(\"time\") &&\n this.state.benchResults[benchResult].time != null &&\n this.state.benchResults[benchResult].time != NaN) ||\n (this.state.benchResults[benchResult].hasOwnProperty(\"size\") &&\n this.state.benchResults[benchResult].size != null &&\n this.state.benchResults[benchResult].size != NaN)\n ) {\n console.log(\"bench result :\");\n console.log({ benchResult });\n const description = this.state.benchResults[benchResult].description;\n console.log(\"time : \");\n console.log(this.state.benchResults[benchResult].time);\n console.log(\"size : \");\n console.log(this.state.benchResults[benchResult].size);\n console.log(\"bench : \");\n console.log(this.state.benchResults[benchResult]);\n const time = this.state.benchResults[benchResult].time;\n const size = this.state.benchResults[benchResult].size;\n const id = this.state.benchResults[benchResult].id;\n bench[\"bench\"].push({\n description: description,\n time: time,\n size: Math.trunc(size),\n id: id,\n });\n }\n }\n console.log(bench);\n const dataStr =\n \"data:text/json;charset=utf-8,\" +\n encodeURIComponent(JSON.stringify(bench));\n const downloadAnchorNode = document.createElement(\"a\");\n downloadAnchorNode.setAttribute(\"href\", dataStr);\n downloadAnchorNode.setAttribute(\"download\", \"exportName\" + \".json\");\n document.body.appendChild(downloadAnchorNode);\n downloadAnchorNode.click();\n downloadAnchorNode.remove();\n }", "saveToJSON () {\n\t\tlet digimonJSON = JSON.stringify(this);\n\n\t\treturn digimonJSON;\n\t}", "function exportarRuta() {\n\tvar rutaJSON = directionsDisplay.directions.routes[0];\n\t\n\tvar data={};\n\tvar path = [], pathinfo, steps;\n\t\n\tdata.start = {\n\t\t'name': rutaJSON.legs[0].start_address,\n\t\t'lat' : rutaJSON.legs[0].start_location.lat(),\n\t\t'lng' : rutaJSON.legs[0].start_location.lng()\n\t};\n\tdata.end = {\n\t\t'name': rutaJSON.legs[rutaJSON.legs.length-1].end_address,\t\n\t\t'lat' : rutaJSON.legs[rutaJSON.legs.length-1].end_location.lat(),\n\t\t'lng' : rutaJSON.legs[rutaJSON.legs.length-1].end_location.lng()\n\t};\n\tvar contar=0;\n\tfor(var i=0;i<rutaJSON.legs.length;i++){\n\t\tvar steps = rutaJSON.legs[i].steps;\n\t\tfor (var i = 0; i < steps.length; i++){\n\t\t\tpath[contar] = steps[i].path\n\t\t\tcontar++;\n\t\t}\n\t}\n\tdata.path = path;\n\t\n\t$.ajax({\n\t\turl : \"exportarRuta\",\n\t\ttype : \"POST\",\n\t\tdata : JSON.stringify(data),\n\t\tcontentType : \"application/json\",\n\t\tprocessData : false,\n\t\tsuccess : function(result) {\n\t\t\tdescargarArchivo(new Blob([result], {type:'application/xml'}));\n\t\t\talert(\"Ruta exportada con éxito.\")\n\t\t\t// sacar mensaje de ruta exportada correctamente.\n\t\t},\n\t\terror : function(result) {\n\t\t\talert(\"Error al exportar la ruta.\")\n\t\t\t// sacar mensaje de ruta no exportada con exito.\n\t\t}\n\t});\n\t\n}", "function guardar()\n{\n\tvar guardado = new partidaGuardada(partida.tipoJuego, partida.tableroJuego.casillas, partida.fichasAmarillas, partida.fichasAzules, numeroCelulas, vecino, partida.tableroJuego.filas, partida.tableroJuego.colum);\n\tvar data = \"text/json;charset=utf-8,\" + encodeURIComponent(JSON.stringify(guardado));\n\t$(\"#guardar\").attr(\"href\", \"data:\"+data);\n\t$(\"#guardar\").attr(\"download\", \"data.json\");\n}", "function exportList(theListObj, theFolder){\n\n\t\t\t// get the file.\n\t\t\tvar theListExport = new File(theFolder.fsName + \"/dc_projectSwitcher_list.json\");\n\n\t\t\t// open the file\n\t\t\tif(theListExport.open(\"w\")){\n\t\t\t\ttheListExport.encoding = \"UTF-8\"; // set encoding.\n\t\t\t\ttheListExport.write(JSON.stringify(theListObj)); // write the JS Obj to JSON.\n\t\t\t\ttheListExport.close(); // close file.\n\t\t\t}\n\n\t\t} // ----- end exportList function -----", "async function exportObjects(argv) {\n const url = new URL(argv.url);\n url.pathname = '/api/saved_objects/_export';\n\n const options = {\n method: 'GET',\n headers: {\n 'kbn-xsrf': true,\n },\n };\n\n try {\n const res = await fetch(url, { ...options });\n const body = JSON.stringify(await res.json(), null, 2);\n if (res.status === 200) {\n logger.info(`${res.status} ${res.statusText} Response:\\n${body}`);\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n}", "listToTXT() {\n const { articles } = this.props.articleData\n const articleArray = articles.map((article, i) => {\n const authors = article.authors.join()\n const conferences = article.conferences.join()\n return `${i + 1}: ${article.title}\\nAuthors: ${authors}\\nConferences: ${conferences}\\n`\n })\n const blob = new Blob(articleArray, {\n type: 'text/plain;charset=utf-8'\n })\n FileSaver.saveAs(blob, 'article-list.txt')\n }" ]
{ "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 message: 'Möchtest du den Eintrag löschen?',\n title: 'Nutztier Eintrag löschen',\n buttonLabels: ['Ja', 'Nein'],\n animation: 'default',\n primaryButtonIndex: 1,\n cancelable: true,\n callback: function (index) {\n if (index == 0) {\n //if type is 'Belegung' then delete also future action items\n if (type == \"Belegung\") {\n db.transaction(function (tx) {\n tx.executeSql('DELETE FROM livestock_action WHERE id = ? OR future = ?',\n [id, 'true']);\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n },\n function () {\n setActionDetailView('true')\n });\n //all others only delete action item and update futer itmes display field\n } else {\n db.transaction(function (tx) {\n tx.executeSql('DELETE FROM livestock_action WHERE id = ?', [id]);\n tx.executeSql('UPDATE livestock_action SET display = ? WHERE livestock_id = ? AND type = ? AND future = ? AND id > ?', ['true', livestock_id, type, 'true', startPointID]);\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n },\n function () {\n setActionDetailView('true')\n });\n }\n }\n }\n });\n}", "updateNextMessageAfterDelete() {\n this.hintAboutToDeleteMessages();\n }", "function prevMsgDelete() {\n message.delete([300])\n .then(msg => console.log(`Deleted message from ${msg.author.username}`))\n .catch(console.error);\n }", "function deleteButtonPressed(entity) {\n db.remove(entity);\n }", "deleteEmail() {\n\n \n switch (this.view) {\n\n // move item to trash\n case \"inbox\":\n this.$set(this.selectedEmail, \"deleted\", true);\n this.selectedEmail = \"\";\n break;\n // move item back from trash to inbox\n case \"trash\":\n this.$set(this.selectedEmail, \"deleted\", false);\n this.selectedEmail = \"\";\n break;\n }\n }", "handleDeleteItems(e){\n\t\tconst id = e.target.attributes.keyset.value\n\t\tActions.deleteTodo(id)\n\t}", "forgetMe(resource) {\n let result = this.searchMessages({modelName: MESSAGE, to: resource, isForgetting: true})\n let batch = []\n let ids = []\n result.forEach((r) => {\n let id = utils.getId(r)\n batch.push({type: 'del', key: id})\n ids.push(id)\n })\n let id = utils.getId(resource)\n ids.push(id)\n batch.push({type: 'del', key: id})\n return db.batch(batch)\n .then(() => {\n ids.forEach((id) => {\n this.deleteMessageFromChat(utils.getId(resource), this._getItem(id))\n delete list[id]\n })\n this.trigger({action: 'messageList', modelName: MESSAGE, to: resource, forgetMeFromCustomer: true})\n return this.meDriverSignAndSend({\n object: { [TYPE]: FORGOT_YOU },\n to: { permalink: resource[ROOT_HASH] }\n })\n })\n .catch((err) => {\n debugger\n })\n }", "function del()\n{\n var r = confirm(\"¿Estas seguro de eliminar?\");\n\n if(r == true)\n {\n agenda.results.splice(index, 1);\n primer();\n }\n\n}", "function deleteClickListener() {\n\t\t$('.container').on('click', '.delete-submission', event => {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\tconst submission = $(event.currentTarget)\n\t\t\t\t.parents('.submission-thumb')\n\t\t\t\t.prop('id');\n\n\t\t\tif (\n\t\t\t\tconfirm(\n\t\t\t\t\t'Are you sure that you would like to permanently remove this submission?'\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tapi\n\t\t\t\t\t.remove(`/api/submissions/${submission}`)\n\t\t\t\t\t.then(() => {\n return api\n .search(`/api/users/mysubmissions`)\n .then(res => {\n $('#user-submissions').empty();\n store.userSubmissions = res;\n \n displayUserSubmissions(res);\n \t })\n });\n\t\t }\n });\n }", "deleteAction(req, res) {\n Robot.remove({ _id: req.params.id }, (err, robot) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 204, { 'message': 'Deleted successfully!' });\n });\n }", "onDelete() {\n this.setState({ choice: '' });\n this.props.callbackParent(this.props.ind);\n }", "'click #delete'() {\n Meteor.call('setStatusCatador', this._id, '', 'D');\n }", "static deleteAction(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('mixing', 'delete', kparams);\n\t}", "function erase(e) {\n database.database_call(`DELETE FROM subnote WHERE id=${id} `);\n alerted.note(\"The current note was deleted!\", 1);\n Alloy.Globals.RenderSubNotesAgain();\n $.view_subnotes.close();\n}", "function deleteMessage(argMessageID, argFormName, argInputID, argAction)\n{\n if(confirm(R_U_SURE_DELETE))\n {\n $('#frmMessageID').val(argMessageID);\n $('#frmProcess').val(argAction);\n $('#'+argFormName).submit();\n\n }\n\n}", "onDeleteClick(id){\r\n\t\tthis.props.removePost(id)\r\n\t}", "function destroyItemAction() {\n return JSON.stringify({\n path: String(resource.path),\n data: {\n ':operation': 'delete'\n }\n });\n }", "function handle_delete(parsedRequest) {\n var resourceName = parsedRequest.resourceName, \n resourceId = parsedRequest.resourceId; \n\n // no data for the resource name is a 404\n if (!DATA[resourceName]) {\n return new ResponseData(404,\"did not find resource: \"+resourceName);\n };\n\n // resource Id specified but no data for that id\n // stored is a 404\n if (resourceId && !DATA[resourceName][resourceId]) {\n return new ResponseData(404,\"no data found for \"+resourceName+\" \"+resourceId);\n };\n\n delete DATA[resourceName][resourceId];\n\n return new ResponseData(200,\"Successfully deleted \"+resourceName+\" \"+resourceId);\n // TODO: figure out the best way to send a status response w/o a response body.\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); } var type = normalizeTypeName(node.type); switch (type) { case 'html_inline': case 'html_block': props.isBlock = type === 'html_block'; props.escapeHtml = opts.escapeHtml; props.skipHtml = opts.skipHtml; break; case 'code_block': var codeInfo = node.info ? node.info.split(/ +/) : []; if (codeInfo.length > 0 && codeInfo[0].length > 0) { props.language = codeInfo[0]; props.codeinfo = codeInfo; } break; case 'code': props.children = node.literal; props.inline = true; break; case 'heading': props.level = node.level; break; case 'softbreak': props.softBreak = opts.softBreak; break; case 'link': props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination; props.title = node.title || undef; if (opts.linkTarget) { props.target = opts.linkTarget; } break; case 'image': props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination; props.title = node.title || undef; // Commonmark treats image description as children. We just want the text props.alt = node.react.children.join(''); node.react.children = undef; break; case 'list': props.start = node.listStart; props.type = node.listType; props.tight = node.listTight; break; default: } if (typeof renderer !== 'string') { props.literal = node.literal; } var children = props.children || (node.react && node.react.children); if (Array.isArray(children)) { props.children = children.reduce(reduceChildren, []) || null; } return props; }
[ "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(...props) {\n let newTypes = []\n for (let type of this.types) {\n let newProps = null\n for (let source of props) {\n let add = source(type)\n if (add) {\n if (!newProps) newProps = Object.assign({}, type.props)\n newProps[add[0].id] = add[1]\n }\n }\n newTypes.push(\n newProps\n ? new dist_NodeType(type.name, newProps, type.id, type.flags)\n : type\n )\n }\n return new NodeSet(newTypes)\n }", "prop(prop) {\n return !prop.perNode\n ? this.type.prop(prop)\n : this.props\n ? this.props[prop.id]\n : undefined\n }", "function linkAllProps() {\n // Exceptions to mapping\n var exceptions = [ 24, 2, 21, 40, 15, 20, 0, 24, 110, 115 ]\n\n for ( aprop in s ) {\n // Check if this is a prop\n if ( aprop.indexOf( 'prop' ) > -1 ) {\n // Extract prop number\n var propNum = parseInt( aprop.replace( 'prop', '' ), 10 );\n // If number not in exceptions, link it to eVar\n if ( exceptions.indexOf( propNum ) === -1 ) {\n linkProps( 'eVar' + propNum, aprop );\n }\n }\n }\n }", "_addProperties(node, properties, labels, propMaker) {\n let tag = \"/\";\n for (let label of [...labels].sort()) {\n if (tag !== \"/\") tag += \"-\";\n tag += label;\n }\n\n for (let property in properties) {\n // Predicate\n let propertyNode = propMaker[property + tag];\n this._labelize(propertyNode, property);\n this._addQuad(propertyNode, rdf.type, prec.Property);\n this._addQuad(propertyNode, rdf.type, prec.CreatedProperty);\n this._addQuad(prec.CreatedProperty, rdfs.subClassOf, prec.CreatedVocabulary);\n\n // Object\n if (!Array.isArray(properties[property])) {\n let nodeValue = this._makeNodeForPropertyValue(properties[property]);\n this._addQuad(node, propertyNode, nodeValue);\n } else {\n let listHead = this._makeNodeForPropertyValues(properties[property]);\n this._addQuad(node, propertyNode, listHead);\n }\n }\n }", "visitPhysical_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function findNodeProperty(prop, contact) {\n\t\n\tif (prop.indexOf(getClassName(contact.m_node1.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node1.other, contact.m_node2.other]\n\t\t\n\t}\n\t\n\telse if (prop.indexOf(getClassName(contact.m_node2.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node2.other, contact.m_node1.other]\n\t\t\n\t}\n\t\n\telse return false;\n\t\n}", "visitColumn_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitObject_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "add(match) {\n if (this.perNode)\n throw new RangeError(\"Can't add per-node props to node types\")\n if (typeof match != 'function') match = dist_NodeType.match(match)\n return (type) => {\n let result = match(type)\n return result === undefined ? null : [this, result]\n }\n }", "constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new NodeProp();\n this.flags = options.flags;\n this.types = options.types;\n this.flagMask = Math.pow(2, this.flags.length) - 1;\n this.typeShift = this.flags.length;\n let subtypes = options.subtypes || 0;\n let parentNames = [undefined];\n this.typeIDs[\"\"] = 0;\n let typeID = 1;\n for (let type of options.types) {\n let match = /^([\\w\\-]+)(?:=([\\w-]+))?$/.exec(type);\n if (!match)\n throw new RangeError(\"Invalid type name \" + type);\n let id = typeID++;\n this.typeNames[id] = match[1];\n this.typeIDs[match[1]] = id;\n parentNames[id] = match[2];\n for (let i = 0; i < subtypes; i++) {\n let subID = typeID++, name = match[1] + \"#\" + (i + 1);\n this.typeNames[subID] = name;\n this.typeIDs[name] = subID;\n parentNames[subID] = match[1];\n }\n }\n this.parents = parentNames.map(name => {\n if (name == null)\n return 0;\n let id = this.typeIDs[name];\n if (id == null)\n throw new RangeError(`Unknown parent type '${name}' specified`);\n return id;\n });\n if (this.flags.length > 30 || this.typeNames.length > Math.pow(2, 30 - this.flags.length))\n throw new RangeError(\"Too many style tag flags to fit in a 30-bit integer\");\n }", "matches(node, props) {\n return Element$1.isElement(node) && Element$1.isElementProps(props) && Element$1.matches(node, props) || Text.isText(node) && Text.isTextProps(props) && Text.matches(node, props);\n }", "_buildPropertyProps(properties = {}) {\n const props = {};\n for (const propertyName in properties) {\n const property = properties[propertyName];\n const propData = NOTION_PAGE_PROPERTIES[property.type];\n\n if (!propData) continue;\n\n props[propertyName] = {\n type: propData.type,\n label: propertyName,\n description: this._buildPropDescription(property.type, propData.example),\n options: propData.options(property),\n optional: true,\n };\n }\n return props;\n }", "visitIndex_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXmltype_column_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "componentWillReceiveProps(nextProps) {\n if (nextProps.nodeTemplate.template) {\n this.setState({\n nodeTemplate: nextProps.nodeTemplate,\n newPropIndex: nextProps.nodeTemplate.template.properties.length\n });\n }\n }", "function evaluateProps(reference, props) {\n var out = _extends$1({}, props, {\n content: invokeWithArgsOrReturn(props.content, [reference])\n }, props.ignoreAttributes ? {} : getDataAttributeProps(reference));\n\n if (out.animateFill) {\n out.arrow = false;\n }\n\n if (out.arrow || isUCBrowser) {\n out.animateFill = false;\n }\n\n return out;\n}", "getChildrenProps() {\n const { children } = this.props;\n const targetNode = this.getPositionTarget();\n const childrenProps = { children };\n const childrenParams = {\n targetNode,\n visible: this.getVisible(),\n };\n if (typeof children === 'function') {\n return {\n children: children(childrenParams),\n };\n }\n if (children === undefined && targetNode) {\n const tooltip = targetNode.getAttribute('data-tooltip');\n if (tooltip != null) {\n return {\n dangerouslySetInnerHTML: {\n __html: tooltip,\n },\n };\n }\n }\n return childrenProps;\n }", "getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }" ]
{ "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.getElementById('left_container'); let left_content = generateStatistics("Total Time", weeklyTotalTimeData[0], weeklyTotalTimeData[1], ''); left_container.appendChild(left_content); // Add most frequent getMostFrequentTime() in procesing.js mostFrequentTimeData = await getMostFrequentTime(); var right_container = document.getElementById('right_container'); let right_content = generateStatistics("Most Frequent", weeklyMostFrequentTimeData[1], weeklyMostFrequentTimeData[2], weeklyMostFrequentTimeData[0]); right_container.appendChild(right_content); }
[ "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(x => !mappedData.find(item => item.group === x));\n\n return mappedData.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }", "function updateDailyUsage(){\n if (dailyUsageData.consumption.devices){\n for (let usageDevice of dailyUsageData.consumption.devices){\n updateDeviceDailyUsage({id: usageDevice.id, dailyUsage: (usageDevice.pct/100) * dailyUsageData.consumption.total});\n }\n }\n if (dailyUsageData.production.devices){\n for (let usageDevice of dailyUsageData.production.devices){\n updateDeviceDailyUsage({id: usageDevice.id, dailyUsage: (usageDevice.pct/100) * dailyUsageData.production.total});\n }\n }\n}", "function getTimeEntries() {\n time.getTime().then(function(results) {\n vm.timeentries = results;\n updateTotalTime(vm.timeentries);\n console.log(vm.timeentries);\n }, function(error) {\n console.log(error);\n });\n }", "function renderUserWatchlist() {\n var dbPath = appUser.getWatchPath();\n\n // empty out stock-ticker content\n $(\"#stock-ticker-content\").empty();\n\n console.log(\"in renderUserWatchList() appUser.getWatchPath: \" + appUser.getWatchPath());\n\n database.ref(dbPath).once(\"value\", (snapshot) => {\n snapshot.forEach((data) => {\n console.log(\"The \" + data.key + \" is \" + data.val());\n // get current price of stock symbol\n buildBatchURL(data.key, \"watch\");\n\n // get yesterday's close price of stock symbol\n buildTimeSeriesURL(data.key);\n\n // add row to watchListTable\n renderWatchTable(data.key);\n });\n }, (errorObject) => {\n console.log(\"Errors handled in renderWatchTable: \" + JSON.stringify(errorObject));\n });\n\n }", "function refreshHome() {\n let xhttp = new XMLHttpRequest;\n\n //Create empty object to push all the stock data into with HS\n hs = {};\n\n //Featured stocks\n let stockSymbol = ['AAPL', 'UBER', 'FB', 'GOOGL', 'JPM'];\n\n //XHR creates different xmlHTTP requests for each stock, which avoids a problem where the data couldn't be caught\n let xhr = [];\n\n //Loop that goes for the length of the featured stocks (5) that populates hs\n for (let i = 0; i < 5; i++) {\n\n //URL is created from existing strings to cut down on having to deal with URL confusion\n let URL = api + stockSymbol[i] + apiKey;\n console.log(URL);\n xhr[i] = new XMLHttpRequest();\n xhr[i].open('GET', URL, true);\n\n xhr[i].onload = function (data) {\n\n //Access the JSON data in here \n data = JSON.parse(this.response);\n\n //By getting the last refreshed date from the meta data, we can reference it in calling the latest data\n let latestDate = data['Meta Data']['3. Last Refreshed'];\n\n //The latest date that is given includes minutes, hours, and seconds which doesn't fit into the actual data\n //Thus, it's much easier to just cut it to the actual length of a regular date (10)\n trimmedLatestDate = latestDate.substring(0, 10);\n\n //This gets the stock symbol from the meta data\n let sym = data['Meta Data']['2. Symbol'];\n\n //This is the actual raw data from the latest date\n let stock = data['Time Series (Daily)'][trimmedLatestDate];\n\n /*\n Mod_stock is a replacement object with all the data from the original object - stock, except that\n it changes the key names such that they do not contain any fullstops, as firebase does not accept\n key names with fullstops in them.\n */\n let mod_stock = {};\n mod_stock.open = parseFloat(stock['1. open']);\n mod_stock.high = parseFloat(stock['2. high']);\n mod_stock.low = parseFloat(stock['3. low']);\n mod_stock.close = parseFloat(stock['4. close']);\n mod_stock.volume = parseFloat(stock['5. volume']);\n\n\n //Now, the stock within hs is being updated to contain all the data taken from mod_stock\n hs[sym] = mod_stock;\n\n //This updates the homeStock collection in Firebase everytime; it deletes old data every update per .update\n homeStocksRef.update(hs);\n }\n xhr[i].send();\n }\n //homeLoad gets the data from the Firebase and sorts it using a selection sort, shown further down\n homeLoad();\n }", "function setCredits() {\n console.log('check setCredits ', cache);\n let credits_by_id = cache['credits'];\n\n let credits = groupBy(Object.values(credits_by_id), 'day_id'); // TODO: sql join add date field\n\n // Count sum for each date\n let data_pre = {};\n for (let day_id in cache['days']) { // TODO: load days\n data_pre[cache['days'][day_id].date] = 0;\n }\n\n let total_sum = 0;\n for (let day_id in credits) {\n let sum = 0;\n let date = cache['days'][day_id].date;\n\n for (let credit of credits[day_id]) {\n sum += (credit.value === undefined ? 0 : credit.value);\n }\n\n data_pre[date] = sum;\n total_sum += sum;\n }\n\n // Setup progress bar\n console.log(total_sum +\" - \"+ cache['user'].total);\n bar.animate(total_sum / cache['user'].total ); // Number from 0.0 to 1.0\n\n document.querySelector('.credits__title').innerText = total_sum + ' / ' + cache['user'].total;\n\n // Correct setup.sh of zeros values (future days)\n data = [];\n dataShort = [];\n days = [];\n let flag = false;\n for (let day_id of Object.keys(cache['days']).reverse()) {\n // console.log(day_id);\n let date = cache['days'][day_id].date;\n\n if (data_pre[date] !== 0) {\n flag = true;\n }\n\n if (flag) {\n dataShort.unshift(data_pre[date]);\n }\n data.unshift(data_pre[date]);\n days.unshift(cache['days'][day_id].date);\n }\n\n\n // Load text data of credits\n let html_history = '';\n for (let day_id in credits) {\n html_history += '<div class=\"credits__history_day img-div\">';\n\n html_history += '<h3>' + cache['days'][day_id].date + '</h3>';\n\n for (let credit of credits[day_id]) {\n html_history += '<div class=\"credits__history_item\">' +\n '<div>'+\n '<i class=\"mobile__item__icon large material-icons\">' + (credit.type == 1 ? 'edit' : credits.type == 2 ? 'school' : 'event') + '</i>' +\n '<p>' + credit.title + '</p>' +\n '</div>' +\n '<p class=\"' + (credit.value > 0 ? 'credits_positive' : 'credits_negative') + '\">' + (credit.value > 0 ? '+' : '-') + credit.value + '</p>' +\n '</div>';\n }\n\n html_history += '</div>';\n }\n\n document.querySelector('.credits__history').innerHTML = html_history;\n\n console.log(days, data, dataShort);\n setupCreditsChart(days, data, dataShort);\n}", "function watchDashboardPageLoad() {\n displayName();\n getSchedules(displaySchedules);\n}", "function stored() {\n var storedDay = JSON.parse(localStorage.getItem(\"dailyDesc\"));\n\n if (storedDay) {\n dailyDesc = storedDay;\n }\n\n descSave();\n dispDesc();\n}", "function trend_periodically_update_graph () {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/dashboard/trend_data',\n\t\tdataType: 'json',\n\t\tsuccess: trend_generate_graph\n\t});\n}", "function loadWeeklyPeriod (previous) {\n\tif (previous === true) {\n\t\tchartsWeeklyPeriod += 1;\n\t} else {\n\t\tchartsWeeklyPeriod -= 1;\n\t}\n\n\tloadWeeklyCharts();\n}", "function getDaysData() {\n let days;\n if (localStorage.getItem(\"days\") === null) {\n days = [];\n } else {\n days = JSON.parse(localStorage.getItem(\"days\"));\n }\n\n // Sort days by day number\n for (let i = 0; i < days.length; i++) {\n let max = i;\n for (let j = i + 1; j < days.length; j++) {\n if (days[max][0] < days[j][0]) {\n max = j;\n }\n }\n let temp = days[max];\n days[max] = days[i];\n days[i] = temp;\n }\n\n days.forEach(function(day) {\n // Create new Data element\n const mainDiv = document.createElement(\"div\");\n // Add class\n mainDiv.className = \"bg-light text-dark rounded m-2 p-2\";\n\n // Create h6 node\n const h6 = document.createElement(\"h6\");\n // Add class\n h6.className = \"font-weight-bold\";\n h6.innerHTML = \"Day \" + day[0];\n\n mainDiv.appendChild(h6);\n\n // Create day description node\n const dayDescription = document.createElement(\"div\");\n // Add class\n dayDescription.className =\n \"day-description shadow py-2 mb-2 rounded border px-2\";\n\n dayDescription.innerHTML = day[1];\n\n mainDiv.appendChild(dayDescription);\n\n // Create time spent node\n const timeSpent = document.createElement(\"div\");\n\n timeSpent.innerHTML = \"Time spent: \" + day[2] + \"h \" + day[3] + \"min\";\n\n mainDiv.appendChild(timeSpent);\n\n // append mainDiv to menu\n menu.appendChild(mainDiv);\n });\n\n // update footer data\n\n daysLeft.innerHTML = 100 - days.length;\n progress.style.width = days.length + \"%\";\n\n // Calculate total time spent\n let totalMinutes = 0;\n days.forEach(function(day) {\n totalMinutes += parseInt(day[2]) * 60;\n totalMinutes += parseInt(day[3]);\n });\n totalTimeSpent.innerHTML =\n parseInt(totalMinutes / 60) + \"h \" + (totalMinutes % 60) + \"min\";\n\n // hide add tag if all 100 days are completed\n if (days.length == 100) {\n addTag.style.display = \"none\";\n }\n}", "async function periodicRefresh(){\n try {\n tsLogger('Refreshing monitor data, monitor data, and missed events...');\n\n //Get daily usage data\n let today = new Date();\n let todayMidnight = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);\n dailyUsageData = await mySense.getDailyUsage(moment.utc(todayMidnight).format());\n\n //Get monitor stats\n let monitor = await mySense.getMonitorInfo()\n monitorData = monitor;\n updateMonitorInfo();\n refreshDeviceList();\n getMissedEvents();\n } catch (error) {\n tsLogger(`Error in periodicRefresh: ${error.message}`)\n }\n}", "function fetchAndSendUpdatedTime() {\n if (windowOpen) {\n chrome.storage.local.get(\"timeLeft\", (data) => {\n var timeLeft = data.timeLeft;\n var timeObj = {\n minutes: timeLeft.minutes.toString(),\n seconds: timeLeft.seconds.toString(),\n };\n savePort.postMessage({\n status: \"time update\",\n time: stringifyTime(timeObj),\n });\n });\n }\n}", "function checkRecentlyWatched() {\n if (localStorage.getItem(\"recentlyWatched\") == null) {\n recentlyWatched = [];\n localStorage.setItem(\"recentlyWatched\", JSON.stringify(recentlyWatched));\n } else {\n recentlyWatched = JSON.parse(localStorage.getItem(\"recentlyWatched\"));\n }\n }", "function storeWebsites(){\n\tlocalStorage.removeItem(\"websites\");\n\tlocalStorage.websites=JSON.stringify(websites);\n\tchrome.alarms.clearAll();\n\twebsites.forEach(setAlarms);\t\n\n}", "function onRefresh3() {\n\tconfig3.data.datasets.forEach(function (dataset) {\n\t\tdataset.data.push({\n\t\t\tx: Date.now(),\n\t\t\ty: powerGenerate_real_2\n\t\t});\n\t});\n}", "function fetchData() {\n client.subscribe(\"/fx/prices\", function (data) { //subscribing for updates\n rawData.push(JSON.parse(data.body)); //storing retrived data\n });\n}", "async function addToChromeStorage(key1, value) {\n let key = key1;\n chrome.storage.sync.set({'omswebsites': value}, function() {\n fetchFromChromeStorage('arpit');\n return null;\n }); \n }", "function updateInspiration() {\n var by;\n var day;\n var inspiration ;\n var language = getLanguage();\n var xhr = new XMLHttpRequest();\n var now = new Date();\n var da = ('0' +(now.getMonth()+1)).slice(-2)+('0' +now.getDate()).slice(-2);\n url = 'http://' + language + '.kasahorow.org/app/m?format=json&source=chrome&da='+da;\n\n //notification_url = 'http://' + language + '.kasahorow.org/app/b' +'?utm_campaign=read&utm_medium='+ language + '&utm_source=chrome';\n\n //synchronization true, as not to show tab or pop up before changing the notification.\n xhr.open(\"GET\", url, true);\n xhr.onreadystatechange=function() {\n //Works after getting the feed\n if (xhr.readyState == 4 && this.status == 200) {\n var res = JSON.parse(xhr.response);\n by = res[\"by\"];\n day = res[\"day\"];\n inspiration = res[\"inspiration\"];\n \n localStorage.by = by;\n localStorage.day = day;\n localStorage.inspiration = inspiration;\n localStorage.updateDate = (new Date()).toDateString();\n localStorage.inspiration_language = language;\n }\n };\n xhr.send();\n return [getlanguageName(language) + ' kasahorow', 'kasahorow', now.getFullYear() + '-' + da.slice(0, 2) + '-' + da.slice(-2)];\n}" ]
{ "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. */_this.outerGlow=true;/** * An event triggered when the highlight layer is being blurred. */_this.onBeforeBlurObservable=new BABYLON.Observable();/** * An event triggered when the highlight layer has been blurred. */_this.onAfterBlurObservable=new BABYLON.Observable();_this._instanceGlowingMeshStencilReference=HighlightLayer.GlowingMeshStencilReference++;_this._meshes={};_this._excludedMeshes={};_this.neutralColor=HighlightLayer.NeutralColor;// Warn on stencil if(!_this._engine.isStencilEnable){BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");}// Adapt options _this._options=__assign({mainTextureRatio:0.5,blurTextureSizeRatio:0.5,blurHorizontalSize:1.0,blurVerticalSize:1.0,alphaBlendingMode:BABYLON.Engine.ALPHA_COMBINE,camera:null,renderingGroupId:-1},options);// Initialize the layer _this._init({alphaBlendingMode:_this._options.alphaBlendingMode,camera:_this._options.camera,mainTextureFixedSize:_this._options.mainTextureFixedSize,mainTextureRatio:_this._options.mainTextureRatio,renderingGroupId:_this._options.renderingGroupId});// Do not render as long as no meshes have been added _this._shouldRender=false;return _this;}
[ "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 BABYLON.Color4()};/**\n * The clear color of the texture used to generate the glow map.\n */this.neutralColor=new BABYLON.Color4();/**\n * Specifies wether the highlight layer is enabled or not.\n */this.isEnabled=true;/**\n * An event triggered when the effect layer has been disposed.\n */this.onDisposeObservable=new BABYLON.Observable();/**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */this.onBeforeRenderMainTextureObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture is being merged in the scene.\n */this.onBeforeComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture has been merged in the scene.\n */this.onAfterComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the efffect layer changes its size.\n */this.onSizeChangedObservable=new BABYLON.Observable();this.name=name;this._scene=scene||BABYLON.Engine.LastCreatedScene;var component=this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);if(!component){component=new BABYLON.EffectLayerSceneComponent(this._scene);this._scene._addComponent(component);}this._engine=this._scene.getEngine();this._maxSize=this._engine.getCaps().maxTextureSize;this._scene.effectLayers.push(this);// Generate Buffers\nthis._generateIndexBuffer();this._genrateVertexBuffer();}", "function addHighlight(feature) {\n //add feature to map\n var vectors = app.mapPanel.map.getLayersByName(\"highlightLayer\")[0];\n //reproject feature to mapProj (considering all overlays are in epsg:4326)\n if (app.mapPanel.map.baseLayer.projection.projCode != 'EPSG:4326') {\n var geom = feature.geometry.transform(new OpenLayers.Projection('EPSG:4326'), app.mapPanel.map.baseLayer.projection);\n feature = new OpenLayers.Feature.Vector(geom);\n }\n vectors.addFeatures([feature]);\n}", "function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\t\n\t\n\tinfo_panel.update(layer.feature.properties)\n\t\n\n\t\n\n\t\n\n}", "function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\tif (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n\t\tlayer.bringToFront();\n\t}\n\n\tinfo_panel.update(layer.feature.properties)\n\tcreateDashboard(layer.feature.properties)\n}", "function highlightFeature(e) {\n e.target.setStyle(highLightStyle);\n}", "addLayerSelection() {\n let mapButtonsContainer = this.ref.createMapButtonsContainer(this.map.height);\n let layerButtonContainer = this.ref.createDiv(\"layerButtonContainer\");\n let layerButtonList = this.ref.createLayerButtonList(\"layerButtonList\");\n\n for (let i = 0; i < this.ref.maxZ; i++) {\n let layerButton = this.ref.createLayerButton(\"layerButton-\" + String(i), \"layer-button\");\n layerButtonList.append(layerButton);\n }\n\n layerButtonContainer.append(layerButtonList);\n document.querySelector(\"body\").append(mapButtonsContainer);\n let layerSelector = this.ref.createDiv(\"mapLayerSelector\");\n\n for (let i = nrOfLayers - 1; i >= 0; i--) {\n let layerA = this.ref.createLayerA(\"#\", i + 1);\n layerA.addEventListener('click', (e) => {\n let selectedNr = Number(e.target.innerText) - 1;\n if (this.displayLayers.includes(selectedNr)) {\n let elIndex = this.displayLayers.indexOf(selectedNr);\n e.target.classList.remove('active');\n\n if (elIndex > -1)\n this.displayLayers.splice(elIndex, 1);\n } else {\n this.displayLayers.push(selectedNr);\n e.target.classList.add('active');\n\n }\n this.repaintMapCube(cubes, \"\", this.enhancedCubes, this.scaffoldingCubesCords, false)\n\n });\n layerSelector.append(layerA);\n }\n mapButtonsContainer.append(layerSelector);\n }", "function initScene() {\n gScene = new THREE.Scene();\n gScene.background = new THREE.Color(0xcccccc);\n gScene.fog = new THREE.FogExp2(0xcccccc, 0.002);\n}", "create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }", "function setupLight(){\r\n\r\n\t//an ambient light for \"basic\" illumination\r\n\tambientLight = new THREE.AmbientLight( 0x444444 );\r\n\tscene.add( ambientLight );\r\n\r\n\t//a directional light for some nicer additional illumination\r\n\tdirectionalLight = new THREE.DirectionalLight( 0xffeedd );\r\n\tdirectionalLight.position.set( 0, 0, 1 ).normalize();\r\n\tscene.add( directionalLight );\r\n\r\n\t//set up the point light but without adding it to the scene\r\n\tpointlight = new THREE.PointLight( 0x444444, 2, 30 );\r\n\tpointLight.position.set( 0, 0, 37 );\r\n\r\n}", "function loadSurfaceColor () {\n\n setShaderColor( controller.configure.color.surface );\n\n if ( controller.configure.color.selected === null ) {\n\n setHighlightColor( controller.configure.color.surface );\n\t\t\tconsole.log('highlight color===========>', controller.configure.color.surface)\n } else {\n\n setHighlightColor( controller.configure.color.selected );\n\n }\n\n }", "highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }", "function SceneNode() {}", "function lightingSetUp(){\n\n keyLight = new THREE.DirectionalLight(0xFFFFFF, 1.0);\n keyLight.position.set(3, 10, 3).normalize();\n keyLight.name = \"Light1\";\n\n fillLight = new THREE.DirectionalLight(0xFFFFFF, 1.2);\n fillLight.position.set(0, -5, -1).normalize();\n fillLight.name = \"Light2\";\n\n backLight = new THREE.DirectionalLight(0xFFFFFF, 0.5);\n backLight.position.set(-10, 0, 0).normalize();\n backLight.name = \"Light3\";\n\n scene.add(keyLight);\n scene.add(fillLight);\n scene.add(backLight);\n}", "createSingle_() {\n asserts.assert(this.layer != null);\n asserts.assert(this.view != null);\n\n olEvents.listen(this.layer, EventType.PROPERTYCHANGE, this.onLayerPropertyChange_, this);\n this.activeLayer_ = tileLayerToImageryLayer(this.layer, this.view.getProjection());\n\n if (this.activeLayer_) {\n // update the layer style and add it to the scene\n updateCesiumLayerProperties(this.layer, this.activeLayer_);\n this.onZoomChange_();\n this.cesiumLayers_.add(this.activeLayer_, this.lastStart_ > -1 ? this.lastStart_ : undefined);\n\n // register listeners to update the layer\n events.listenEach(this.layer, STYLE_KEYS, this.onStyleChange_, this);\n events.listenEach(this.layer, RESOLUTION_KEYS, this.onZoomChange_, this);\n olEvents.listen(this.layer, 'change:extent', this.synchronize, this);\n olEvents.listen(this.layer, 'change', this.onChange_, this);\n }\n }", "function addShapes() {\n scene.add(camera);\n scene.add(ambientLight);\n}", "constructor(options, areaType, map) {\n //If certain options were not set then provide a default value for them\n options.style = options.style || ol.style.areaStyleFunction(areaType);\n options.updateWhileAnimating = options.updateWhileAnimating || false;\n options.updateWhileInteracting = options.updateWhileInteracting || false;\n options.renderMode = options.renderMode || 'image'; //'vector' is default\n options.declutter = true;\n //Get zoom range from area type\n let minZoom = areaType.zoom_min;\n let maxZoom = areaType.zoom_max;\n //Set default options (if necessary) and call vector layer constructor\n super(options, map, minZoom, maxZoom);\n this.areaType = areaType;\n //Check if labels are desired for this area type\n if (this.areaType.labels) {\n this._hasLabels = true;\n //Create label layer and add it to the map\n this.labelLayer = new ol.layer.AreaLabel({\n source: new ol.source.Vector(),\n zIndex: this.areaType.z_index + LABEL_LAYER_Z_INDEX\n }, areaType.labels, map);\n //Add label layer to map\n map.addLayer(this.labelLayer);\n }\n else {\n this._hasLabels = false;\n }\n //No highlighting yet\n this.highlightLocation = null;\n //Save reference to current scope\n let _this = this;\n //Check if area source is used\n if (!(this.getSource() instanceof ol.source.Area)) {\n return;\n }\n //Cast to area source\n let source = this.getSource();\n //Register a feature listener\n source.addFeatureListener(function (feature) {\n _this.checkFeatureForHighlight(feature);\n _this.createLabelForFeature(feature);\n });\n }", "function create_3dView() {\n var scene = new WebScene({\n portalItem: {\n id: \"159d275b250b4db1978a728bd20fa2ec\"\n }\n });\n\n var view = new SceneView({\n map: scene,\n container: \"globe\"\n })\n }", "function GlowLayer(name,scene,options){var _this=_super.call(this,name,scene)||this;_this._intensity=1.0;_this._includedOnlyMeshes=[];_this._excludedMeshes=[];_this.neutralColor=new BABYLON.Color4(0,0,0,1);// Adapt options\n_this._options=__assign({mainTextureRatio:GlowLayer.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:undefined,camera:null,mainTextureSamples:1,renderingGroupId:-1},options);// Initialize the layer\n_this._init({alphaBlendingMode:BABYLON.Engine.ALPHA_ADD,camera:_this._options.camera,mainTextureFixedSize:_this._options.mainTextureFixedSize,mainTextureRatio:_this._options.mainTextureRatio,renderingGroupId:_this._options.renderingGroupId});return _this;}" ]
{ "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 (_is.undefined(caption)) { caption = ''; } // Set the span content if (_is.string(caption)) { content.innerHTML = caption.trim(); } else { content.appendChild(caption); } // Set new caption text container.appendChild(content); // Force redraw (for Safari) var redraw = container.offsetHeight; }
[ "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 if (node.lbcs >= 0) {\n capHelperText = (node.lbcs === 0 ? '不经过拉拔' : node.lbcs + '次拉拔');\n }\n $('.caption-helper', $detail).text(capHelperText);\n }", "function changeTitle() {\n\t$currenttitle.text($currenttitle.text().replace(/Currently Playing:/, TitleBarDescription_Caption));\n}", "function setCaptionSettings() {\r\n var textAlign = $('select[name=\"[_veditor_][.bx-caption][text-align]\"]').val();\r\n var textColor = $('input[name=\"[_veditor_][.bx-caption][color]\"]').val();\r\n var bgColor = $('input[name=\"[_veditor_][.bx-caption][background-color]\"]').val();\r\n var textSize = $('input[name=\"[_veditor_][.bx-caption][font-size]\"]').val();\r\n var props = {\r\n 'text-align': textAlign,\r\n 'color': textColor,\r\n 'background-color': bgColor,\r\n 'font-size': textSize\r\n };\r\n\r\n $('div#tieImg').find('div.bx-caption-preview').css(props);\r\n $('div#toeImg').find('div.bx-caption-preview').css(props);\r\n }", "function changeCaption(obj, htmlId) {\r\n\r\n var gname = obj.innerHTML;\r\n\r\n if (isExistingFuncName(CurModObj, gname) ||\r\n isExistingGridNameInFunc(CurFuncObj, gname)) {\r\n\r\n alert(\"Name \" + gname + \" alrady exists!\");\r\n return;\r\n }\r\n\r\n\r\n if (htmlId == PreviewHtmlGridId) { // while selecting existing grid\r\n\r\n NewGridObj.caption = gname;\r\n\r\n } else { // while within a step\r\n\r\n\tvar sO = CurStepObj;\r\n\tvar gridId = getGridIdOfHtmlId(htmlId); // find grid object\r\n\tvar gO = CurFuncObj.allGrids[gridId];\r\n\tgO.caption = gname;\r\n }\r\n}", "setAskMeContainerTitle() {\n if (this.botIntegrationContainer.classList.contains(\"container-show\")) {\n this.askMeContainerTitle.textContent = this.htmlTextContentCollection[this.languageCode].askMeContainerTitle[1];\n }\n else {\n this.askMeContainerTitle.textContent = this.htmlTextContentCollection[this.languageCode].askMeContainerTitle[0];\n }\n }", "function caption(date) {\n var monthName = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n \n var curMonth = date.getMonth();\n \n var curYear = date.getFullYear();\n \n var str = \"<caption>\" + monthName[curMonth] + \" \" + curYear + \"</caption>\";\n \n return str;\n }", "buildCaption() {\n var table = this.table;\n var caption = table.options.caption;\n var paginationInfo = KingTableHtmlBuilder.options.paginationInfo\n ? this.buildPaginationInfo()\n : null;\n return caption || paginationInfo ? new VHtmlElement(\"div\", {\n \"class\": \"king-table-caption\"\n }, [\n caption ? new VHtmlElement(\"span\", {}, new VTextElement(caption)) : null,\n paginationInfo\n ? (caption ? new VHtmlElement(\"br\") : null)\n : null, paginationInfo]) : null;\n }", "function testDefaultCaption() {\n select.render(sandboxEl);\n var item1 = new goog.ui.MenuItem('item 1');\n select.addItem(item1);\n select.addItem(new goog.ui.MenuItem('item 2'));\n assertEquals(defaultCaption, select.getDefaultCaption());\n assertEquals(defaultCaption, select.getCaption());\n\n var newCaption = 'new caption';\n select.setDefaultCaption(newCaption);\n assertEquals(newCaption, select.getDefaultCaption());\n assertEquals(newCaption, select.getCaption());\n\n select.setSelectedItem(item1);\n assertNotEquals(newCaption, select.getCaption());\n\n select.setSelectedItem(null);\n assertEquals(newCaption, select.getCaption());\n}", "function setCancelButtonTitle(name) {\n\t\t$cancelButton.html(name);\n\t}", "function setOkButtonTitle(name) {\n\t\t$okButton.html(name);\n\t}", "_setSubtitleText() {\n this.subtitle && this._setText(this.subtitle, '.js-OverlayHeader-subtitle');\n }", "function build_caption(item) {\n\t\t\tif (item !== undefined) {\n\t\t\t\treturn caption(item);\t\n\t\t\t} else {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}", "setCaption(html) {\n this.children.some((item) => {\n if (item instanceof NavbarCaption) {\n item.setCaption(html);\n return true;\n } else {\n return false;\n }\n });\n }", "static setAsDefault(captionAssetId){\n\t\tlet kparams = {};\n\t\tkparams.captionAssetId = captionAssetId;\n\t\treturn new kaltura.RequestBuilder('caption_captionasset', 'setAsDefault', kparams);\n\t}", "initTitle () {\n if (this.hasAttribute('pair-title')) {\n this.title = this.getAttribute('pair-title');\n this.modalTitle.innerText = this.title;\n }\n }", "function setSkillDesc(desc) {\n skillDesc.innerHTML = desc;\n}", "function setCaptionStyle( e )\n\t\t{\n\t\t\tvar att = new Array();\n\t\t\tatt[0] = '#000';\n\t\t\tatt[1] = '#FFF';\n\t\t\tatt[2] = 0.7;\n\t\t\tatt[3] = 'bottom';\n\t\t\t\n\t\t\t// if rel attribute specified, set @var att\n\t\t\tif(e.attr('rel') != 'undefined') {\n\t\t\t\tvar opt = e.attr('rel').split(';');\n\t\t\t\tfor(var i=0; i<opt.length; i++) {\n\t\t\t\t\tvar attribute = opt[i].split(':');\n\t\t\t\t\t\n\t\t\t\t\tswitch(attribute[0]) {\n\t\t\t\t\t\tcase 'bg' : att[0] = attribute[1]; break;\n\t\t\t\t\t\tcase 'txt' : att[1] = attribute[1]; break;\n\t\t\t\t\t\tcase 'opacity' : att[2] = attribute[1]; break;\n\t\t\t\t\t\tcase 'pos' : att[3] = attribute[1]; break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// set CSS of caption including positions\n\t\t\t_caption.css({'background-color':att[0],'color':att[1],'opacity':att[2]});\n\t\t\tif(att[3]=='top') {\n\t\t\t\t_caption.css({\n\t\t\t\t\t'width'\t\t: (opts.width - 16),\n\t\t\t\t\t'height'\t: '',\n\t\t\t\t\t'top'\t\t: 0,\n\t\t\t\t\t'left'\t\t: 0,\n\t\t\t\t\t'bottom'\t: '',\n\t\t\t\t\t'right'\t\t: ''\n\t\t\t\t});\n\t\t\t} else if(att[3] == 'right') {\n\t\t\t\t_caption.css({\n\t\t\t\t\t'width'\t\t: Math.round(opts.width / 4),\n\t\t\t\t\t'height'\t: (opts.height - 16),\n\t\t\t\t\t'top'\t\t: 0,\n\t\t\t\t\t'left'\t\t: '',\n\t\t\t\t\t'bottom'\t: '',\n\t\t\t\t\t'right'\t\t: 0\n\t\t\t\t});\n\t\t\t} else if(att[3]=='left') {\n\t\t\t\t_caption.css({\n\t\t\t\t\t'width'\t\t: Math.round(opts.width / 4),\n\t\t\t\t\t'height'\t: (opts.height - 16),\n\t\t\t\t\t'top'\t\t: 0,\n\t\t\t\t\t'left'\t\t: 0,\n\t\t\t\t\t'bottom'\t: '',\n\t\t\t\t\t'right'\t\t: ''\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t_caption.css({\n\t\t\t\t\t'width'\t\t:(opts.width - 16),\n\t\t\t\t\t'height'\t: '',\n\t\t\t\t\t'top'\t\t: '',\n\t\t\t\t\t'left'\t\t: '',\n\t\t\t\t\t'bottom'\t: 0,\n\t\t\t\t\t'right'\t\t: ''\n\t\t\t\t});\n\t\t\t}\n\t\t}", "static setContent(id, contentResource){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.contentResource = contentResource;\n\t\treturn new kaltura.RequestBuilder('caption_captionasset', 'setContent', kparams);\n\t}", "static set boldLabel(value) {}", "function setLabel(text) {\n label = text;\n var w = ctx.textWidth(label,0.5);\n if (w > 6) // there are 6 units across the screen\n w = 6;\n if (w < 2)\n w = 2;\n wbound = w / 2;\n ctx.onmodify();\n }" ]
{ "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 event listener - applicable to elements only if (tNode.type === 3 /* Element */) { var native = getNativeByTNode(tNode, viewData); ngDevMode && ngDevMode.rendererAddEventListener++; var renderer = getRenderer(); // In order to match current behavior, native DOM event listeners must be added for all // events (including outputs). if (isProceduralRenderer(renderer)) { var cleanupFn = renderer.listen(native, eventName, listenerFn); storeCleanupFn(viewData, cleanupFn); } else { var wrappedListener = wrapListenerWithPreventDefault(listenerFn); native.addEventListener(eventName, wrappedListener, useCapture); var cleanupInstances = getCleanup(viewData); cleanupInstances.push(wrappedListener); if (getFirstTemplatePass()) { getTViewCleanup(viewData).push(eventName, tNode.index, cleanupInstances.length - 1, useCapture); } } } // subscribe to directive outputs if (tNode.outputs === undefined) { // if we create TNode here, inputs must be undefined so we know they still need to be // checked tNode.outputs = generatePropertyAliases(tNode.flags, 1 /* Output */); } var outputs = tNode.outputs; var outputData; if (outputs && (outputData = outputs[eventName])) { createOutput(viewData, outputData, listenerFn); } }
[ "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 addEventListeners() {\n // pan watch point event\n var hammerPointer = new Hammer(document.querySelector('#pointer'));\n hammerPointer.on('pan', onPanPointer);\n}", "function addEventListeners(preboot, nodeEvents, strategy) {\n for (var _i = 0; _i < nodeEvents.length; _i++) {\n var nodeEvent = nodeEvents[_i];\n var node = nodeEvent.node;\n var eventName = nodeEvent.eventName;\n var handler = getEventHandler(preboot, strategy, node, eventName);\n // add the actual event listener and keep a ref so we can remove the listener during cleanup\n node.addEventListener(eventName, handler);\n exports.state.eventListeners.push({\n node: node,\n name: eventName,\n handler: handler\n });\n }\n}", "addNestedSub(listener) {\n //First, ensure itself has been subscribed, that's how the order of subscription is maintained\n this.trySubscribe()\n //THEN, subscribe the nested listener to its own listener collection\n this.listeners.push(listener)\n }", "function addListener(element, events, listener) {\n if (!element || !element.addEventListener)\n return;\n if (!Array.isArray(events))\n events = [events];\n element.addEventListener(events.join(' '), listener);\n}", "__removeParticleEventListener(){\n Utils.changeCursor(this.myScene.canvasNode, \"pointer\");\n this.myScene.canvasNode.addEventListener(\"mousedown\", this.__removeParticleDisposableEvent);\n }", "function addElementListeners() {\n addDarkModeListener();\n addColorSchemeListener();\n addResizeListener();\n addCreateNoteListener();\n addDeleteNoteListener();\n addFilterNoteListener();\n addFilterHashesListener();\n addTitleListener();\n addDownloadListener();\n addCitationButtonListener();\n addModeSwitchListeners();\n addOnCloseListener();\n addOptionsListeners();\n}", "function addListeners(element) {\n element.addEventListener('click', showCell);\n element.addEventListener('contextmenu', markCell);\n}", "function bindListenerToNodes(elemList, eventName, callback) {\n\t\tfor (let elem of elemList) {\n\t\t\telem.addEventListener(eventName, callback);\n\t\t}\n\t}", "add_out(func) {\n this.add_event(\"mouseout\", func);\n }", "_addServiceStreamDataListener ( ) {\n\n this.serviceStream.on(\n 'data'\n , this.boundStreamListener\n );\n }", "#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }", "function attachDefaultListeners() {\n\t\tvar listenerDiv = document.getElementById('listener');\n\t\tlistenerDiv.addEventListener('load', moduleDidLoad, true);\n\t\tlistenerDiv.addEventListener('message', handleMessage, true);\n\t\tlistenerDiv.addEventListener('error', handleError, true);\n\t\tlistenerDiv.addEventListener('crash', handleCrash, true);\n\t\tif (typeof window.attachListeners !== 'undefined') {\n\t\t\twindow.attachListeners();\n\t\t}\n\t}", "bindEvents() {\n PubSub.subscribe(\"Location:location-data-loaded\", event => {\n const allLocations = event.detail;\n this.selectLocationList(allLocations);\n });\n //listens for change in location selection from dropdown list and\n //publishes the index of the new location back to location.js\n this.element.addEventListener(\"change\", event => {\n const selectIndex = event.target.value;\n PubSub.publish(\"Location:change-location\", selectIndex);\n });\n }", "function addHandler(selector, event, handler) {\n var elements = document.querySelectorAll(selector);\n\n for (var i = 0, len = elements.length; i < len; i++) {\n var currentElement = elements[i];\n currentElement.addEventListener(event,handler);\n }\n }", "add_change(func) {\n this.add_event(\"change\", func);\n }", "_emit(event, args) {\n return Promise.all(this.listeners(event).map(listener => {\n if (typeof listener.listener === 'function'){\n this.removeListener(event, listener);\n }\n\n return (listener.listener || listener).apply(this, args);\n }));\n }", "function addMapEvents(){\n\t\t\t// Add tap event to add shapes for custom links\n\t\t\tmap.addEventListener('tap', initializeOraddPointToPolygon);\n\t\t\t\n\t\t\t// Add mouse-move listner to show polyline \n\t\t\tmap.addEventListener('pointermove', refreshNonFinalizedPolygon);\n\t}", "function VoyagerListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}", "function addMutationObserver() {\n const config = {\n childList: true,\n attributes: true,\n subtree: true,\n };\n observer.observe(document, config);\n}" ]
{ "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 // compile & write ts file for each json schema file\n fs.writeFileSync(\n __dirname + '/../src/shared/schemas/' + file.substring(0, file.length-5) + '.ts',\n await compileFromFile(file),\n );\n });\n}", "function sortedServices(providers, services) {\n let sortedServiceRecords = [];\n for (let record of providers) {\n for (let item of record.services){\n if (item in services) {\n sortedServiceRecords.push (record);\n }\n }\n };\n return (sortedServiceRecords);\n}", "async created() {\n this.broker.createService(metadata);\n this.broker.createService(packages);\n this.broker.createService(apps);\n this.broker.createService(objects);\n this.broker.createService(layouts);\n this.broker.createService(permissionsets);\n this.broker.createService(tabs);\n this.broker.createService(translations);\n this.broker.createService(triggers);\n this.broker.createService(queriesService);\n this.broker.createService(chartsService);\n this.broker.createService(pagesService);\n this.broker.createService(shareRulesService);\n this.broker.createService(restrictionRulesService);\n this.broker.createService(permissionFieldsService);\n this.broker.createService(processService);\n this.broker.createService(processTriggerService);\n this.broker.createService(objectTriggerService);\n this.broker.createService(permissionTabsService);\n this.broker.createService(importService);\n }", "function generateModels(ctx) {\n // Create Models\n var template = fs.readFileSync(\n require.resolve('./shared/model.ejs'),\n { encoding: 'utf-8' }\n );\n var results = [];\n var result;\n for (var modelName in ctx.models) {\n var meta = ctx.models[modelName];\n // capitalize the model name\n modelName = modelName[0].toUpperCase() + modelName.slice(1);\n result = ejs.render(template, {\n moduleName: ctx.moduleName,\n modelName: modelName,\n model: meta,\n urlBase: ctx.apiUrl.replace(/\\/+$/, ''),\n getModelType: getModelType\n });\n if (ctx.outputFolder) {\n ctx.outputFolder = path.resolve(ctx.outputFolder);\n fs.writeFileSync(\n ctx.outputFolder + '/models/' + modelName + '.ts',\n result\n );\n }\n results.push(result);\n }\n // Create Models index\n var indexTemplate = fs.readFileSync(\n require.resolve('./shared/models.ejs'),\n { encoding: 'utf-8' }\n );\n result = ejs.render(indexTemplate, {\n moduleName: ctx.moduleName,\n models: ctx.models,\n urlBase: ctx.apiUrl.replace(/\\/+$/, '')\n });\n if (ctx.outputFolder) {\n ctx.outputFolder = path.resolve(ctx.outputFolder);\n console.error('Saving the generated services source to %j', ctx.outputFolder);\n fs.writeFileSync(ctx.outputFolder + '/models/index.ts', result);\n }\n results.push(result);\n return results;\n}", "getServices() {\n let services = []\n this.informationService = new Service.AccessoryInformation();\n this.informationService\n .setCharacteristic(Characteristic.Manufacturer, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.Model, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.SerialNumber, \"opensprinkler-system\");\n services.push(this.informationService)\n\n // Add the irrigation system service\n this.irrigationSystemService = new Service.IrrigationSystem(this.name);\n this.irrigationSystemService.getCharacteristic(Characteristic.Active)\n .on(\"get\", syncGetter(this.getSystemActiveCharacteristic.bind(this)))\n .on('set', promiseSetter(this.setSystemActiveCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(this.getSystemInUseCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.ProgramMode)\n .on('get', syncGetter(this.getSystemProgramModeCharacteristic.bind(this)))\n\n this.irrigationSystemService.addCharacteristic(Characteristic.RemainingDuration)\n .on('get', syncGetter(this.getSystemRemainingDurationCharacteristic.bind(this)))\n\n this.irrigationSystemService.setPrimaryService(true)\n\n services.push(this.irrigationSystemService)\n\n // Add the service label service\n this.serviceLabelService = new Service.ServiceLabel()\n this.serviceLabelService.getCharacteristic(Characteristic.ServiceLabelNamespace).setValue(Characteristic.ServiceLabelNamespace.DOTS)\n\n // Add all of the valve services\n this.sprinklers.forEach(function (sprinkler) {\n sprinkler.valveService = new Service.Valve(\"\", \"zone-\" + sprinkler.sid);\n // sprinkler.valveService.subtype = \"zone-\" + sprinkler.sid\n\n // Set the valve name\n const standardName = 'S' + ('0' + sprinkler.sid).slice(-2);\n let userGaveName = standardName != sprinkler.name;\n // log(\"Valve name:\", sprinkler.name, userGaveName)\n if (userGaveName) {\n sprinkler.valveService.getCharacteristic(Characteristic.Name).setValue(sprinkler.name)\n // sprinkler.valveService.addCharacteristic(Characteristic.ConfiguredName).setValue(sprinkler.name)\n }\n\n sprinkler.valveService.getCharacteristic(Characteristic.ValveType).updateValue(Characteristic.ValveType.IRRIGATION);\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.Active)\n .on('get', syncGetter(sprinkler.getSprinklerActiveCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerActiveCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(sprinkler.getSprinklerInUseCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService.addCharacteristic(Characteristic.SetDuration)\n .on('get', syncGetter(() => sprinkler.setDuration))\n .on('set', (duration, next) => {\n sprinkler.setDuration = duration\n log.debug(\"SetDuration\", duration)\n next()\n })\n\n sprinkler.valveService.addCharacteristic(Characteristic.RemainingDuration)\n\n // Set its service label index\n sprinkler.valveService.addCharacteristic(Characteristic.ServiceLabelIndex).setValue(sprinkler.sid)\n \n // Check if disabled\n sprinkler.disabledBinary = this.disabledStations.toString(2).split('').reverse()\n sprinkler.isDisabled = sprinkler.disabledBinary[sprinkler.sid - 1] === '1'\n\n // log('DISABLED length + sid -------->' + this.sprinklers.length + ' ' + sprinkler.sid)\n // log('DISABLED DATA -------->' + sprinkler.disabledBinary + ' ' + (sprinkler.sid - 1) + ' ' + sprinkler.isDisabled)\n\n // Set if it's not disabled\n // const isConfigured = !sprinkler.isDisabled ? Characteristic.IsConfigured.CONFIGURED : Characteristic.IsConfigured.NOT_CONFIGURED\n sprinkler.valveService.getCharacteristic(Characteristic.IsConfigured)\n .on('get', syncGetter(sprinkler.getSprinklerConfiguredCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerConfiguredCharacteristic.bind(sprinkler)))\n // .setValue(isConfigured)\n\n // Link this service\n this.irrigationSystemService.addLinkedService(sprinkler.valveService)\n this.serviceLabelService.addLinkedService(sprinkler.valveService)\n\n services.push(sprinkler.valveService)\n }.bind(this))\n\n return services\n }", "function generate(opts){\n\n let models = opts.models;\n let appName = opts.appname;\n let routes = opts.models.map(model => model.name);\n\n console.log(\"Starting to Create CRUD API Boilerplate...\");\n console.log(\"Creating Server Folders...\");\n fileCreator.createServerTree(appName);\n\n\n console.log(\"Creating 'package.json' ...\");\n pkgCreator(appName);\n\n\n console.log(\"Creating Config Files ...\");\n configCreator(appName);\n\n console.log(\"Creating Cache Files ...\");\n cacheCreator(appName);\n\n\n console.log(\"Creating Logger Files ...\");\n loggerCreator(appName);\n\n \n console.log(\"Creating Server Files ...\");\n binCreator(appName);\n\n\n console.log(\"Creating Model Files ...\");\n modelCreator(appName, models);\n\n\n console.log(\"Creating Route Files ...\");\n routeCreator(appName, models);\n\n\n console.log(\"Creating App File ...\");\n serverCreator(appName, STDPACKAGES, routes);\n\n\n console.log(\"Done !\");\n}", "generateStubs() {\n this.classBuilder = ClassBuilder.fromDataObject(require(`./stubs-data/data_server.json`), typeHints);\n\n const events = require('./stubs-data/events_server.json');\n events.push(...require('./stubs-data/events_modules.json'));\n\n this.eventSystem = new EventSystem(this.classBuilder, events);\n }", "initServices () {\n this.services.db = new DBService({\n app: this,\n db: this.options.dbBackend\n })\n this.services.rpcServer = new RPCServerService({\n app: this,\n port: this.options.rpcPort\n })\n this.services.jsonrpc = new JSONRPCService({\n app: this\n })\n }", "generateOnionService(){\n let pkraw = forge.rsa.generateKeyPair(1024);\n let pkfp = forge.pki.getPublicKeyFingerprint(pkraw.publicKey, {encoding: 'hex', md: forge.md.sha1.create()})\n let pem = forge.pki.privateKeyToPem(pkraw.privateKey);\n\n if (pkfp.length % 2 !== 0) {\n // odd number of characters\n pkfp = '0' + pkfp;\n }\n let bytes = [];\n for (let i = 0; i < pkfp.length/2; i = i + 2) {\n bytes.push(parseInt(pkfp.slice(i, i + 2), 16));\n }\n\n let onion = base32.encode(bytes).toLowerCase() + \".onion\";\n return {onion: onion, privateKey: pem};\n }", "function createProvider(provider, email, refreshToken, token, freeStorage, totalStorage) {\n var credentials = Windows.Security.Credentials;\n var passwordVault = new credentials.PasswordVault();\n var i, found = undefined;\n // Check if the provider exists\n for (i = 0; i < g_providers.length; i++) {\n if (g_providers[i].name == provider && g_providers[i].user == email) {\n found = g_providers[i];\n }\n }\n if (found == undefined) {\n // Add the provider\n if (refreshToken == undefined) {\n cred = new credentials.PasswordCredential(provider, email, token)\n } else {\n cred = new credentials.PasswordCredential(provider, email, refreshToken)\n }\n passwordVault.add(cred);\n provider = {\n 'name': cred.resource, 'user': cred.userName, 'token': token, 'refresh': refreshToken,\n 'free': freeStorage, 'total': totalStorage\n };\n g_providers.push(provider);\n g_providers.sort(function (a, b) {\n return a.user.localeCompare(b.user);\n });\n // Add one chunk to notify the update of the provider list\n return provider;\n } else {\n found.token = token;\n found.refresh = refreshToken;\n found.free = freeStorage;\n found.total = totalStorage;\n return found;\n }\n}", "setupServices() {\n this.init = this.init.then(() => {\n // Instantiate independent core services.\n new NotificationEmailCoreSrv({mode: process.env.NODE_ENV});\n new NotificationSMSCoreSrv({mode: process.env.NODE_ENV});\n new SocketCoreSrv(this.server, {mode: process.env.NODE_ENV});\n\n return Promise.all([\n AuthSrv.connect(),\n UserSrv.connect(),\n FileSrv.connect(),\n ProductSrv.connect(),\n TagSrv.connect(),\n PriceSrv.connect(),\n OrderSrv.connect(),\n InvitationSrv.connect(),\n NotificationAlertSrv.connect(),\n CouponSrv.connect(),\n BrandSrv.connect(),\n ListSrv.connect(),\n ListSubscriptionSrv.connect(),\n CompanySrv.connect(),\n BillingSrv.connect(),\n AddressSrv.connect(),\n WalletSrv.connect(),\n TransferSrv.connect(),\n OrderItemSrv.connect()\n ]);\n });\n }", "_getServicesRecursively (serviceInfo) {\n if (Array.isArray(serviceInfo)) serviceInfo = serviceInfo[0]\n for (let i = 0; i < serviceInfo.service.length; i++) {\n const service = serviceInfo.service[i]\n if ('service' in service) this._getServicesRecursively(service)\n else {\n const srv = new Service(service)\n this.services[srv.name] = srv\n }\n }\n }", "async registerFrameworkServices() {\n if (this.isCli) {\n await this.container.loadDefinitions(path.join(this.getFrameworkDir(), \"services/commands.yml\"), \"framework\");\n }\n }", "transform() {\n // check for undefined variables in the generated file to determine if there are env variables being used and such.\n this.alertForUndefinedVariables();\n // remove some of the sample files that aren't used\n this.cleanUpSDKFiles();\n // map variables as per the file\n if (this.config.variablesToReplace) {\n this.replaceVariableInFile();\n }\n\n // HTTPD.CONF METHODS\n this.createVirtualHostFiles();\n this.createVhostSymLinks();\n this.replaceVariableInVhostFile();\n this.removeNonWhitelistedDirectives();\n if (this.config.appendToVhosts) {\n this.appendAdditionalDirectives();\n }\n\n // DISPATCHER.ANY METHODS\n this.createFarmFiles();\n this.checkIncludesInFarms();\n this.checkFarmDocRoot();\n this.checkRenderers();\n this.checkCache();\n this.checkClientHeaders();\n this.checkDispatcherVirtualhosts();\n this.checkFilter();\n this.checkRewrites();\n // symlinks are created once all the content is finalized to ignore duplicate file being returned\n this.createFarmSymLinks();\n this.removeNonPublishFarms();\n // create the summary report for the conversion performed\n SummaryReportWriter.writeSummaryReport(\n this.conversionSteps,\n path.dirname(this.dispatcherConfigPath),\n Constants.DISPATCHER_CONVERTER_REPORT\n );\n }", "startServices () {\n for (let serviceId in this.services) {\n let service = this.services[serviceId]\n service.start().then(() => {\n this.logger.log(`${service.name}: OK`)\n }).catch(() => {\n // TODO: Figure out how to handle errors here.\n })\n }\n }", "async registerApplicationServices() {\n return await this.container.loadDefinitions(`${this.getProjectDir()}/config/services/services.yml`, \"application\");\n }", "async registerPluginsServices() {\n for (let p of this.getPlugins()) {\n const { name, plugin, path } = p;\n this.currentPluginPath = path;\n if (plugin.registerServices) {\n if (!_.isFunction(plugin.registerServices)) {\n throw new PluginError(\n name,\n `Error register services for plugin \"${name}\", the \"registerServices\" property must be a function`\n );\n }\n try {\n await plugin.registerServices(this.container, name, this.isCli);\n } catch (e) {\n console.log(e);\n throw new PluginError(name, `Error registering services for plugin \"${name}\": ${e.message}`);\n }\n }\n }\n }", "function createLambdaSource(files) {\n _.forEach(files, function (obj) {\n let ressourceDir = path.join(__dirname, '..', 'src', 'resources', obj.resource + '/');\n let methodName = _.isNil(obj.params) ? obj.method : obj.method + '-by-' + obj.params;\n let methodDir = ressourceDir + methodName + '/';\n\n fs.access(ressourceDir, fs.F_OK, function (err) {\n if (err) {\n fs.mkdir(ressourceDir, function (e) {\n });\n }\n });\n\n let tmplDir = path.join(__dirname, '..', 'src', 'template/');\n let lambdaFile = 'index.js';\n let eventFile = 'event.json';\n let pkgFile = 'package.json';\n\n fs.access(methodDir, fs.F_OK, function (err) {\n if (err) {\n fs.mkdir(methodDir, function (e) {\n fs.writeFile(\n methodDir + lambdaFile,\n fs.readFileSync(tmplDir + 'index.js', 'utf8'),\n function (e) {\n if (e) {\n console.error(e);\n }\n });\n\n fs.writeFile(\n methodDir + eventFile,\n fs.readFileSync(tmplDir + eventFile, 'utf8'),\n function (e) {\n if (e) {\n console.error(e);\n }\n });\n\n updatePackageFile(tmplDir + pkgFile, obj.resource + '-' + methodName).then(function (res) {\n fs.writeFile(methodDir + pkgFile, res, function (e) {\n if (e) {\n console.error(e);\n }\n });\n });\n });\n }\n });\n\n });\n}", "_buildApexAll () {\n AllNameSpaces.forEach((namespace) => {\n const classes = NameSpaceStore.getClasses(namespace)\n Object.keys(classes).forEach((className) => {\n this._buildApex(classes[className])\n })\n })\n\n this.classes.forEach((classInfo) => {\n this._buildApex(classInfo)\n })\n }" ]
{ "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.stringify(name)}`, "domain", domain); domainFields.push({ name, type }); } domainFields.sort((a, b) => { return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); }); return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain); }
[ "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 var hostString = \"www\";\r\n \r\n if(domain == \"lexis\" || domain == \"nexis\") \r\n hostString = \"w3\"; \r\n \r\n return hostString;\r\n}", "static hash(domain, types, value) {\n return (0, index_js_2.keccak256)(TypedDataEncoder.encode(domain, types, value));\n }", "function domainParse(){\n var l = location.hostname\n return {\n \"prot\": location.protocol,\n \"host\": l,\n \"statics\" : 'cdn.kaskus.com'\n };\n}", "function addDomain(domain){\n\n\tdb.collection('domains').insert({\"domain\": domain, \"grade\": \"Calculating\"}, function(err, result) {});\n\n\ttestSSL(domain, 0, function(grade){\n\t\tdb.collection('domains').update({\"domain\": domain},{$set: {\"grade\": grade}}, function(err, result){});\n\t});\n}", "function askForDomain () {\n return inquirer.prompt([{\n type: 'input',\n name: 'domain',\n message: 'Enter a domain name'\n }]).then(answers => answers.domain);\n}", "function Domain(props) {\n return __assign({ Type: 'AWS::SDB::Domain' }, props);\n }", "static encode(domain, types, value) {\n return (0, index_js_4.concat)([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }", "function getHash(ctx) {\n\tif (DEBUG) {\n\t\treturn '';\n\t}\n\n\tconst paths = getEntryBundlesFromManifest(ctx);\n\n\treturn `${getHashPart(paths.app)}${getHashPart(paths.vendor)}${getHashPart(paths.runtime)}`;\n}", "function domainCounts(counts) {\n let output = {}; //{ google.com: 900, com: 900}\n\n for (let i = 0; i < counts.length; i++) {\n let splitCounts = counts[i].split(','); // [ \"60\", \"mail.yahoo.com\"]\n let count = splitCounts[0];\n let host = splitCounts[1];\n\n if (output[host]) {\n output[host] += parseInt(count);\n } else {\n output[host] = parseInt(count);\n }\n\n let periodIndex = host.indexOf('.'); //4\n let nextHost = host;\n\n while (periodIndex !== -1) {\n //com\n nextHost = nextHost.substring(periodIndex + 1, nextHost.length); //5,\n // console.log(nextHost);\n if (output[nextHost]) {\n output[nextHost] += parseInt(count);\n // console.log(output);\n } else {\n output[nextHost] = parseInt(count); //\n }\n periodIndex = nextHost.indexOf('.');\n // console.log(periodIndex);\n }\n }\n\n return output;\n}", "function GetHash160FromAddr(addr){\n const addrd = Address.fromString(addr);\n var script = bitcore.Script.buildPublicKeyHashOut(addrd).toString()\n script = script.split(\"0x\").pop();//Remove all text before 0x prefix of hash160\n script = script.replace(\" OP_EQUALVERIFY OP_CHECKSIG\",\"\");//Remove opcodes from output\n return script;\n}", "function getDomainInfoForSentence(theModel, sentence) {\n // this is sloppy and bad\n var res = {};\n var o = 0xFFFFFFF;\n sentence.forEach(w => {\n if (w.rule.wordType === index_model_1.IFModel.WORDTYPE.CATEGORY) {\n o = o & w.rule.bitSentenceAnd;\n index_model_1.Model.getDomainsForCategory(theModel, w.matchedString).forEach(d => {\n incHash(res, d);\n });\n }\n if (w.rule.wordType === index_model_1.IFModel.WORDTYPE.FACT) {\n o = o & w.rule.bitSentenceAnd;\n // console.log(`${w.rule.bitindex} ${w.bitindex} ${w.rule.bitSentenceAnd} ${o} `);\n index_model_1.Model.getDomainsForCategory(theModel, w.category).forEach(d => {\n incHash(res, d);\n });\n }\n });\n var domains = index_model_1.Model.getDomainsForBitField(theModel, o);\n if (domains.length !== 1) {\n throw new Error('more than one domain: \"' + domains.join('\", \"') + '\"');\n }\n if (!domains[0]) {\n console.log('query without a domain : ' + er_index_1.Sentence.dumpNiceArr([sentence]));\n }\n return {\n domain: domains[0],\n collectionName: index_model_1.Model.getMongoCollectionNameForDomain(theModel, domains[0]),\n modelName: index_model_1.Model.getModelNameForDomain(theModel.mongoHandle, domains[0])\n };\n}", "function getDomain(email) {\n let atIndex = email.indexOf('@') + 1;\n let domain = email.substring(atIndex);\n return domain;\n}", "hashCode () {\n\n /* x hash code. */\n const xstr = String(this._x);\n const len0 = xstr.length;\n let xhsh = 0;\n for (let i = 0; i < len0; ++i) {\n xhsh = Math.imul(31, xhsh) ^ xstr.charCodeAt(i) | 0;\n }\n xhsh >>>= 0;\n\n /* y hash code. */\n const ystr = String(this._y);\n const len1 = ystr.length;\n let yhsh = 0;\n for (let j = 0; j < len1; ++j) {\n yhsh = Math.imul(31, yhsh) ^ ystr.charCodeAt(j) | 0;\n }\n yhsh >>>= 0;\n\n /* Composite hash code. */\n let hsh = -2128831035;\n hsh = Math.imul(16777619, hsh) ^ xhsh;\n hsh = Math.imul(16777619, hsh) ^ yhsh;\n return hsh;\n }", "function getPrimaryDomain(givenHost) {\n\tif (givenHost.toLowerCase().indexOf(\"www.\") === 0)\n\t\tgivenHost = givenHost.substring(4, givenHost.length);\n\n\tvar splitHost = givenHost.split(\".\");\n\n\tvar lastTerm = splitHost[splitHost.length - 1];\n\t\t\n\tif (splitHost.length > 2) {\n\t\tif (lastTerm === \"au\" || lastTerm === \"jp\" || lastTerm === \"nz\" || lastTerm === \"za\") {\n\t\t\tif (splitHost[splitHost.length - 2] === \"co\" || splitHost[splitHost.length - 2] === \"com\")\n\t\t\t\tgivenHost = splitHost[splitHost.length - 3] + \".\" + splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\t\t\telse\n\t\t\t\tgivenHost = splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\t\t}\n\t\telse\n\t\t\tgivenHost = splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\n\t}\n\tconsole.log (\"currentHost: \" + givenHost);\n\t\n\treturn givenHost;\n}", "function getProcId(host) {\n var domainId = getDomainId(host)\n var subdomainId = getSubdomainId(host)\n\n return procs.list[subdomainId] ? subdomainId : domainId\n}", "static uniqueIdentityToHashObject(uniqueIdentity) {\n var terms = uniqueIdentity.split(':');\n if (terms.length != 2) {\n throw \"unique-identity has invalid format\";\n }\n let hashType = terms[0];\n let hashValue = terms[1];\n if (SUPPORTED_COMMON_NAME_HASH_TYPES.indexOf(hashType) < 0) {\n throw \"hash function '\" + hashType + \"' is not supported for certificate Common Name unique identity\";\n }\n return {\n 'hashType': hashType,\n 'hashValue': hashValue\n };\n }", "function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}" ]
{ "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 the state with that info
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) this.setState({ name: city.name, country: city.country }); this.props.getItineraries(city.name) } } if (prevProps.itineraries.itineraries !== this.props.itineraries.itineraries) { if (this.props.match.params.itineraryId) { const itineraries = this.props.itineraries.itineraries const itinerary = itineraries.find(itinerary => itinerary._id === this.props.match.params.itineraryId) // Check if itinerary exists (for coming back to the form once the itinerary being deleted) if (itinerary) { this.setState({ itineraryId: itinerary._id, title: itinerary.title, updatedTitle: itinerary.title, user: itinerary.user, rating: itinerary.rating, duration: itinerary.duration, price: itinerary.price, hashtag: itinerary.hashtag, cityName: itinerary.cityName, }); } } } }
[ "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 var cityName = city.name;\r\n var state = wazeModel.states.get(city.stateID);\r\n if(state && state.name != null && state.name.length > 0) {\r\n cityName += ', ' + state.name;\r\n }\r\n cityIds[city.id] = cityName;\r\n }\r\n }\r\n populateOption(highlightCity.getSelectId(), cityIds); \r\n}", "componentDidUpdate(prevProps) {\n const { pickup, fetchPickupBikes, fetchPickupReservations } = this.props;\n if (pickup.pickupId !== prevProps.pickup.pickupId) {\n fetchPickupBikes(pickup.pickupId);\n fetchPickupReservations(pickup.pickupId);\n }\n }", "componentDidUpdate(prevProps) {\n const { issue, fetchIssueBikeLocation } = this.props;\n\n if (issue.bikeId && prevProps.issue.id !== issue.id) {\n fetchIssueBikeLocation(issue.bikeId);\n }\n }", "nextCity(index) {\n this.setState({ slider1ActiveSlide: index });\n this.props.requestClimate(this.props.citys[index].key);\n }", "function getCityCurrent(){\n \n}", "getWeather (currentCity) {\n this.setState({ isLoading: ! this.state.isLoading })\n const apiKey = '1072dfe12c2f4f7e8ddfa30683df95ca';\n fetch(`https://api.weatherbit.io/v1.0/forecast/3hourly/geosearch?city=${currentCity}&days=1&key=${apiKey}`)\n .then( response => response.json())\n .then( response => {\n this.setState({ city: response.city_name,\n countryCode: response.country_code, \n items: response.data, \n error: false,\n temp: response.data[0].temp,\n isLoading: ! this.state.isLoading ,\n unit: 'C'})\n })\n //No response\n .catch( err => {\n this.setState({ error: true, isLoading: ! this.state.isLoading });\n })\n }", "function displayTeleportCityInfo(cityDetails) {\n if (cityDetails[`closestUrbanCity`] === null) {\n $(`.teleport_info`).append(`<h2>There are no large cities close to ${cityDetails[`cityName`]}.</h2>`);\n } \n else {\n if (cityDetails[`closestUrbanCity`] !== cityDetails[`cityName`]) {\n $(`.teleport_info`).append(`<h2>We have extensive data on ${cityDetails[`closestUrbanCity`]}, a nearby city. Click on a category for more details.</h2>`);\n }\n else {\n $(`.teleport_info`).append(`<h2>We have extensive data on this city. Click on a category for more details.</h2>`);\n }\n const cityKey = convertNameToReferenceKey(cityDetails[`closestUrbanCity`]);\n $(`.teleport_info`).append(`<div class=teleport_widget><a class=\"teleport-widget-link\" href=\"https://teleport.org/cities/${cityKey}/\">Life quality score</a><script async class=\"teleport-widget-script\" data-url=\"https://teleport.org/cities/${cityKey}/widget/scores/?currency=USD&citySwitcher=false\" data-max-width=\"770\" src=\"https://teleport.org/assets/firefly/widget-snippet.min.js\"></script>\n </div>`);\n }\n }", "function update_global_city(city_name) {\n // Update current city in the header\n update_current_city(city_name);\n\n // Update curve module\n change_curve_info(0);\n\n // // Update pollution amount module\n // setTimeout(function(){\n update_pollution_amount();\n // }, 200);\n\n // Update news module\n update_news_area_name(city_name);\n\n // Update province 3D map\n let date = document.getElementById(\"current_date\").innerText;\n update_province_3D(date, city_name);\n\n // Update analysis curve\n plot_analysis_curve();\n\n // Update wind info\n update_wind_direction();\n\n //Update weather amount\n update_weather_amount();\n\n //Update city sort histogram\n update_histogram();\n}", "getInitialData() {\n ServerCall.searchData(this.state)\n .then(res => {\n this.setState({ dbData: res[0] }, () => {\n const data = this.state.dbData;\n switch (this.state.searchSelect) {\n case (\"animal\"):\n {\n this.setState({\n animalType: data[\"ANIMAL TYPE\"],\n animalCage: data[\"CAGE NAME\"],\n animalId: data[\"ANIMAL ID\"]\n }, () => { this.showContents() })\n break;\n }\n case (\"worker\"):\n {\n this.setState({\n workerId: data[\"WORKER ID\"],\n workerFirst: data[\"FIRST NAME\"],\n workerLast: data[\"LAST NAME\"],\n workerPosition: data[\"POSITION\"]\n }, () => { this.showContents() })\n break;\n }\n case (\"food\"):\n {\n this.setState({\n foodId: data[\"FOOD ID\"],\n foodType: data[\"FOOD TYPE\"]\n }, () => { this.showContents() })\n break;\n }\n case (\"cage\"):\n {\n this.setState({\n cageId: data[\"CAGE NUMBER\"],\n cageName: data[\"CAGE NAME\"],\n cageSize: data[\"SQ FT\"]\n }, () => { this.showContents() })\n break;\n }\n case (\"approvedFoods\"):\n {\n this.setState({\n foodEntryId: data[\"ENTRY ID\"],\n animalId: data[\"ANIMAL ID\"],\n animalType: data[\"ANIMAL TYPE\"],\n foodType: data[\"FOOD TYPE\"],\n }, () => { this.showContents() })\n break;\n }\n case (\"workerAnimal\"):\n {\n this.setState({\n animalWorkerEntryId: data[\"ENTRY ID\"],\n animalId: data[\"ANIMAL ID\"],\n animalType: data[\"ANIMAL TYPE\"],\n workerId: data[\"ASSIGNED WORKER ID\"],\n workerFirst: data[\"WORKER FIRST NAME\"],\n workerLast: data[\"WORKER LAST NAME\"],\n }, () => { this.showContents() })\n break;\n }\n default:\n return;\n }\n })\n })\n .catch(err => console.log(err));\n }", "updateMeetup(state, payload) {\n // search for the meetup that has changes\n const meetup = state.loadedMeetUps.find(meetup => {\n return meetup.id === payload.id;\n });\n\n if (payload.title) {\n meetup.title = payload.title;\n }\n if (payload.description) {\n meetup.description = payload.description;\n }\n if (payload.date) {\n meetup.date = payload.date;\n }\n if (payload.time) {\n meetup.time = payload.time;\n }\n }", "function showInitialCities() {\n Object.keys(INITIALCITIES).forEach(function(cityName) {\n displayTeleportCity(cityName);\n });\n }", "componentDidMount() {\n const { book } = this.state;\n const {\n match: { params },\n } = this.props;\n\n // dirty check, check if we have book object or not\n if (params.id && book.id === undefined) {\n requester(\n {\n method: 'get',\n url: fetchBookByIdAPI(params.id),\n },\n response => {\n this.formApi.setState({ values: response.data.book });\n },\n );\n }\n }", "function change_city(findCity) {\n let apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${findCity}&appid=${apiKey}&units=${units}`;\n axios.get(apiURL).then(ShowCityTemp);\n//this portion is for forecast\n apiURL = `https://api.openweathermap.org/data/2.5/forecast?q=${findCity}&appid=${apiKey}&units=${units}`;\n axios.get(apiURL).then(ShowForecast);\n\n}", "function toSelectingLocations()\n{\n\tlet cityValid = false;\n\tlet currentUserRef = localStorage.getItem(CURRENT_USER_KEY); //Retrieves current logged in user\n\tlet city = document.getElementById(\"citiesId\").value; //Retrieves the data inputted by the user in the datalist\n\tfor(let i = 0; i < citiesArray.length; i++) //This for loop makes sure the chosen city exists in the chosen country\n\t{\n\t\tif(city === citiesArray[i])\n\t\t{\n\t\t\tcityValid = true;\n\t\t\tlistOfUsers.users[currentUserRef].trips[listOfUsers.users[currentUserRef].trips.length - 1].setStartCityId(citiesIdArray[i]);\n\t\t\tupdateLocalStorage(listOfUsers,USERS_DATA_KEY);;\n\t\t\twindow.location = \"selectingLocations.html\";\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!cityValid) //If the city is invalid (doesn't exist in chosen country) this code runs, as cityValid has not been set to true in the for loop\n\t{\n\t\talert(\"Invalid City\");\n\t\tcancel();\n\t}\n}", "get id() {\n let cityID = this.city\n\n if (cityID === 'Berlin') {\n cityID = 'Frankfurt'\n } else if (cityID.includes('_')) {\n cityID = cityID.replace('_', '-')\n }\n\n return cityID.toLowerCase()\n }", "async function getCountryId(selectedCountry) {\n const response = await fetch('land.json')\n const countryData = await response.json()\n\n for (let i = 0; i < countryData.length; i++) {\n if (selectedCountry === countryData[i].countryname) {\n countryValue = countryData[i].id;\n }\n }\n\n callCityData(countryValue);\n\n}", "function showcity() {\n let CS = document.getElementById(\"coutriesSelect\");\n let selectedCountry = CS.options[CS.selectedIndex].innerHTML;\n let selectedIdCountry = CS.value;\n\n //in case to prevent double-click:\n if (selectedIdCountry == last_click) {\n return;\n }\n //set the last_click to prevent double-click on the save country...\n last_click = selectedIdCountry;\n\n get_data_countries(selectedIdCountry);\n }", "componentDidMount() {\n this.showListKecamatan();\n this.showListCity();\n\n }", "function onUserInput() {\n columnID = this.getAttribute('data-city')\n if(deactivatedLasers[columnID - 1]) {\n return\n }\n $city = $('#city-' + columnID)\n shootLaser($city)\n isHit()\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 the new element - it used to show data return item; }
[ "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-typing').remove();\n template = '.template-chat-' + template;\n var data = {\n message: message\n }\n var templateHTML = $('.templates').find(template).html();\n var renderedHTML = Mustache.to_html(templateHTML, data);\n // append message and scroll to bottom of timeline\n $timeline.append(renderedHTML).scrollTop($timeline[0].scrollHeight);\n }\n}", "function newList() {\n let article = gen(\"article\");\n let titleInput = gen(\"input\");\n let taskInput = gen(\"input\");\n let ul = gen(\"ul\");\n\n article.classList.add(\"list\");\n\n titleInput.type = \"text\";\n titleInput.placeholder = \"Title\";\n titleInput.classList.add(\"title-in\");\n article.appendChild(titleInput);\n titleInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTitle(titleInput);\n }\n });\n\n taskInput.type = \"text\";\n taskInput.placeholder = \"+ New task\";\n taskInput.classList.add(\"task-in\");\n article.appendChild(taskInput);\n article.appendChild(ul);\n taskInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTask(taskInput);\n }\n });\n\n qs(\"section\").insertBefore(article, id(\"add\"));\n\n article.addEventListener(\"dblclick\", removeObj);\n }", "function appendChatMessageRoom(li) {\n\t$('#messagesRoom').append(li);\n\n\t// scrolling the list to bottom so that new message will be visible\n\t$('#messagesRoom').scrollTop($('#messagesRoom').height());\n}", "updateList(){\n\n\t\t//create an empty div to add the items to\n\t\tvar listItemsDOM = $('<div class=\"listItems\"></div>');\n\n\t\tvar top = this.listDOM.scrollTop();\n\n\t\t//loop over our styles and update the dom list\n\t\tfor(var i=0; i<this.styles.length; i++){\n\n\t\t\t//loop over all our items\n\t\t\tvar item = this.styles[i];\n\n\t\t\t//add a row for this item. Auto add in the \"selected\" identifier if the ID's match\n\t\t\tlistItemsDOM.append('<div id=\"style_'+item.ID+'\" class=\"listItem '+((item.ID==this.selectedStyle)?'selectedClassItem':'')+'\">'+item.name); //+' {'+item.getID()+'}</div>');\n\n\t\t}//next i\n\n\t\t//update the list DOM\n\t\t//this.listDOM.find('.listItems').remove();\n\t\tthis.listDOM.html(listItemsDOM);\n\n\t\tthis.listDOM.scrollTop(top);\n\n\t}", "function appendChatMessage(li) {\n\t$('#messages').append(li);\n\n\t// scrolling the list to bottom so that new message will be visible\n\t$('#messages').scrollTop($('#messages').height());\n}", "function ELEMENT_LIST$static_(){LinkListBEMEntities.ELEMENT_LIST=( LinkListBEMEntities.BLOCK.createElement(\"list\"));}", "static createListElement(removeFunction, modifyFunction, text, layerId) {\n\n const li = this.createEmptyListElement(removeFunction, modifyFunction, layerId);\n this.fillListText(li, text);\n this.setDataId(li, layerId);\n const ol = $(\"#allLayers\");\n ol.append(li);\n }", "_createMessageNode({author, time, body}) {\n // header of item\n var header = document.createElement(\"header\");\n header.className = \"list-group-item-heading\";\n header.innerHTML = `<strong>${myEscape(author)}</strong> <i class=\"text-muted\">${time}</i>`;\n // body of message\n var content = document.createElement(\"p\");\n content.className = \"list-group-item-text\";\n content.innerHTML = smilify(myEscape(body).replace(/\\n/g, \"<br>\"));\n // node o message\n var node = document.createElement(\"li\");\n node.className = \"list-group-item\";\n node.appendChild(header);\n node.appendChild(content);\n return node;\n }", "function createListItem (content, viewEvent) {\n\n\t\tvar listItemTemplate = importTemplate('list-item-template');\n\t\tvar listItem = listItemTemplate.querySelector('li');\n\n\t\tlistItem.textContent = content;\n\t\tlistItem.addEventListener('click', emitEvent(viewEvent, content));\n\n\t\treturn listItem;\n\n\t}", "function findOrCreateListTemplate(req, res) {\n\n\t if (!req.body.list.verb || !req.body.list.action) {\n\t res.status(403).end();\n\t return Q.reject('Invalid input');\n\t }\n\n\t var newList = new _list2.default(req.body.list);\n\t newList.cuid = (0, _cuid2.default)();\n\t newList._users.push(req.user);\n\n\t //search ListTemplate for matching actions\n\t _listTemplate2.default.findOne({ actions: req.body.list.action }).exec().then(function (template) {\n\t //if we have a template with that action already, create\n\t // a new list based on it\n\t if (template) {\n\t console.log('template found by name');\n\t return Q.when(template);\n\t }\n\t return findOrCreateTemplateByItems(req.body.list.action);\n\t }).then(function (template) {\n\t return newList.addItemsFromTemplate(template);\n\t }).then(function (list) {\n\t return _list2.default.populate(list, { path: '_users', select: 'name picture username' });\n\t }).then(function (list) {\n\t res.json({ list: list });\n\t }).catch(function (err) {\n\t console.log('error in the controller', err);\n\t res.status(422).send(err);\n\t });\n\t}", "_addToLists(list) {\n const listObj = {\n index: this.lists.length,\n name: list.getAttribute('name'),\n element: list,\n editable: this.isEditable(list),\n };\n if(this.lists.length === 0) this.activeList = listObj;\n this.lists.push(listObj);\n }", "function renderPlayerList(data) {\n const listPlayers = document.getElementById('list-player-names');\n let li = document.createElement('li');\n li.id = `${data.id}`\n li.innerHTML = `${data.player_name}`;\n li.addEventListener(\"click\", renderPlayerInfo );\n document.querySelector('#input-new-playername').value = \"\";\n listPlayers.appendChild(li);\n}", "createNode({id, date, time, notified}) {\n const elPARA = `<div class=\"entry\">\n <p>${new Date(date).toDateString()}&nbsp;\n ${this.getTimestamp(date, time).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}\n <span id=\"status${id}\" class=\"status ${(!notified)? 'hide':'show'}\">${(notified) ? \"Triggered\": \"\"}</span></p>\n <button type=\"button\" class=\"btn btn-delete\" id=\"del${id}\" value=\"${id}\">x</button>\n <div class=\"clearfix\"></div>\n </div>`;\n\n elAlarmsDIV.insertAdjacentHTML(\"afterbegin\", elPARA);\n }", "function TKR_rebuildTemplateMenu() {\n var parentEl = $('template_menu');\n while (parentEl.childNodes.length)\n parentEl.removeChild(parentEl.childNodes[0]);\n for (var i = 0; i < TKR_templateNames.length; i++) {\n if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NAME) {\n var option = TKR_createChild(\n parentEl, 'option', null, null, TKR_templateNames[i]);\n option.value = i;\n }\n }\n}", "function categoriesTemplate (\n textMessage=\"Some of the main important categories we have!\",\n additionalCategories=[]) {\n \n function categoryElementTemplate (category) {\n if (!category) {\n return\n }\n \n return {\n title: category + \"!\",\n subtitle: \"Get the most relevant \" + category + \" news\",\n buttons: [\n {\n type: \"postback\",\n title: \"Get \" + category + \" news\",\n payload: \"GET_CATEGORY_\" + category.toUpperCase()\n },\n {\n type: \"web_url\",\n title: \"On Google News!\",\n url: news.getNewsLink(category.toLowerCase(), undefined, undefined, false)\n }\n ]\n \n }\n \n }\n \n var elements = []\n \n categories.forEach(function (category, index, array) {\n if (index > 8) {\n return;\n }\n elements.push(categoryElementTemplate(category))\n })\n \n additionalCategories.forEach(function (category) {\n elements.push(categoryElementTemplate(category))\n })\n \n elements.push({\n title: \"Enter the query!\",\n subtitle: \"Type out anything you want to know about and we bet you'll get all good stuff.\",\n buttons: [\n {\n type: \"postback\",\n title: \"Need Help!\",\n payload: \"GET_HELP\"\n },\n {\n type: \"web_url\",\n title: \"Visit Google News!\",\n url: \"https://news.google.com\"\n }\n ]\n \n })\n \n return {\n attachment: {\n type: \"template\",\n payload: {\n template_type: \"generic\",\n elements: elements\n }\n }\n }\n \n}", "function createListHTML(list, container) {\n container.innerHTML = \"\"; //first, clean up any existing LI elements\n for (var i = 0; i < 6; i++) {\n container.innerHTML = container.innerHTML + \"<li data-index='\" + list[i][\"index\"] + \"'>\" + \"<span>\" + list[i][\"text\"] + \"</span>\" + \"</li>\";\n //OR shorter version: container.innerHTML += \"<li data-index='\" + list[i][\"index\"] + \"'>\" + list[i][\"text\"] + \"</li>\";\n }\n }", "function fillTopics(Ts){\n console.log(\"fillTopics()\");\n _.each(Ts,function(o,i){\n console.log(\"next topic to show:\");\n console.log(o);\n\n $T = $('#msgb-topics-template').clone().removeAttr(\"id\").attr(\"data-id\", o.id);\n $T.find('.msgb-topic-name').html(o.name);\n $T.find('.msgb-topic-date').attr('datetime',o.date_create);\n $('#msgb-topics').append($T);\n });\n $('time.timeago').timeago();\n }", "function setupTemplateList() {\n // load the templates, then load the accounts\n // working around missing accounts ui functionality at the moment\n __acctsServiceCall = EmailApp.Util.callService(\"palm://com.palm.service.accounts/listAccountTemplates\", {\n capability: \"MAIL\"\n }, function (resp) {\n\n if (!resp.results.length) {\n console.log(\"### oh my. We don't have any templates\");\n return;\n }\n that.templateList = resp.results;\n resp.results.forEach(function (elem) {\n if (!that.accountTemplates[elem.templateId]) {\n that.accountTemplates[elem.templateId] = elem;\n }\n });\n __acctsServiceCall = undefined;\n // now load the accounts\n refresh();\n });\n }", "updateListForBlock(block, pW) {\n // ignore if not a list block\n if (!block.isList()) {\n return;\n }\n // the node representing the parent block\n const parentNode = this.nodeFromElement(block.id);\n // get the focused list for this block\n const focusedOptionId = this.focusedOptions[block.id];\n // get only the options that are enabled for this block\n const enabled = Object.keys(block.options).filter(opt => block.options[opt]);\n // if block list is empty add a single placeholder block\n if (enabled.length === 0) {\n const node = this.emptyListBlockFactory(block.id, parentNode);\n node.set({\n bounds: new Box2D(0, kT.blockH + 1, pW, kT.optionH),\n fill: this.fillColor(block.id),\n updateReference: this.updateReference,\n listParentBlock: block,\n listParentNode: parentNode,\n hidden: block.isHidden(),\n });\n } else {\n // find the index of the focused list option, or default the first one\n let focusedIndex = enabled.findIndex(blockId => focusedOptionId === blockId);\n if (focusedIndex < 0) {\n focusedIndex = 0;\n }\n enabled.forEach((blockId, index) => {\n // ensure we have a hash of list nodes for this block.\n let nodes = this.listNodes[block.id];\n if (!nodes) {\n nodes = this.listNodes[block.id] = {};\n }\n // get the block in the list\n const listBlock = this.getListBlock(blockId);\n\n // create node as necessary for this block\n let listNode = nodes[blockId];\n if (!listNode) {\n listNode = nodes[blockId] = this.listBlockFactory();\n parentNode.appendChild(listNode);\n }\n // update position and other visual attributes of list part\n listNode.set({\n bounds: new Box2D(0, kT.blockH + 1 + index * kT.optionH, pW, kT.optionH),\n text: listBlock.metadata.name,\n fill: this.fillColor(block.id),\n color: this.fontColor(block.id),\n updateReference: this.updateReference,\n listParentBlock: block,\n listParentNode: this.nodeFromElement(block.id),\n listBlock,\n optionSelected: index === focusedIndex,\n hidden: block.isHidden(),\n });\n });\n }\n }" ]
{ "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, callback) {\n \n console.log(\"Attempting database query against id: \" + id);\n \n db.collection(DB_COLLECTION_NAME).findOne({ \"short_url_id\": id }, function(err, doc) { \n if (err) {\n console.error(err);\n // Error in reading from database\n callback(null);\n }\n \n if (doc) {\n // Document was retrieved, return the url corresponding to the short id.\n callback(doc.original_url);\n } else {\n // No Document with that id was found in the database\n callback(null);\n }\n });\n \n}", "function getToolByUrl(url) {\n console.log('Looking for: ' + url);\n return TOOLS.find(t => t.url == url);\n}", "function findHQ(player) {\n for (var row = 0; row < ySize; row++) {\n for (var col = 0; col < xSize; col++) {\n var square = board[row][col];\n if (square.player == player && square.HQ) {\n return square;\n }\n }\n }\n}", "function findKing(squares, color) {\n for (let j=0; j < 64; j++) {\n if (squares[j].piece === \"King\" && squares[j].color === color) {\n return (j);\n }\n }\n}", "function extractBoardToArray()\n{\n // Clear board array\n initBoardArray();\n\n // Board tiles have these properties : div class=\"board_pusher\" id=\"pusher_x_y\" (0..N-1)\n var tileNodes = document.querySelectorAll('[id*=pusher_]');\n if (tileNodes != null)\n {\n\n for(var i = 0; i < tileNodes.length; ++i)\n {\n // [0] = full match text, [1] = zero based X position of tile , [2] = zero based Y position of tile\n var tilePosMatch = /pusher_(\\d)_(\\d)/i.exec( tileNodes[i].id );\n\n if (tilePosMatch != null)\n {\n var xPos = parseInt(tilePosMatch[1]);\n var yPos = parseInt(tilePosMatch[2]);\n\n if ((xPos < boardArraySize) && (yPos < boardArraySize))\n {\n boardTiles[xPos][yPos] = tileNodes[i].innerText.toLowerCase(); // Dictionary is in lower case\n boardTileUsed[xPos][yPos] = 0;\n\n if (xPos > boardWidth) { boardWidth = xPos; }\n if (yPos > boardHeight) { boardHeight = yPos; }\n }\n }\n }\n\n // DEBUG - dump to console\n var strBoardText = \"\";\n for (x = 0; x < boardTiles.length;x++) {\n for (y = 0; y < boardTiles[x].length; y++) {\n strBoardText = strBoardText + boardTiles[x][y] + ' ';\n }\n strBoardText = strBoardText + '\\n';\n }\n\nconsole.debug('BOARD\\n=============\\n' + strBoardText);\n setStatusItemState('statusBoard','success');\n return (true);\n }\n else\n {\nconsole.debug('no board');\n setStatusItemState('statusBoard','error');\n return (false);\n }\n}", "function getPossibleBoards(board, player)\n{\n // what we'll ultimately return\n var allBoards = [];\n // retrieving move list\n var Moves = jump_possible(board, player);\n for (var i = 0; i < Moves.length; i++)\n {\n // don't want to modify originally passed in board\n var board1=copyBoard(board);\n // shortening my var name\n var m = Moves[i];\n // temp value\n var preVal = board1[m[0][0]][m[0][1]];\n // clearing the square we just moved off of\n board1[m[0][0]][m[0][1]] = 0;\n \n // setting the current square to val of piece moved to it\n board1[m[1][0]][m[1][1]] = preVal;\n if (preVal == 1 && m[1][0] == 7)\n {\n board1[m[1][0]][m[1][1]] = 2;\n }\n else if (preVal == 3 && m[1][0] == 0)\n {\n board1[m[1][0]][m[1][1]] = 4;\n }\n // checking to see if the move was a capture\n if (Math.abs(m[0][0]-m[1][0]) != 1)\n {\n // setting the captured square to 0;\n board1[(m[0][0]+m[1][0])/2][(m[0][1]+m[1][1]) / 2] = 0;\n // checking for all possible double jump permutations\n var moreBoards = possibleContinues(board1, m[1][0], m[1][1]);\n for (var x = 0; x < moreBoards.length; x++)\n {\n allBoards.push(moreBoards[x]);\n }\n }\n // if it wasn't a capture, then we're done. Simple, elegant\n else\n {\n allBoards.push(board1);\n }\n }\n return allBoards;\n}", "function checkDatabase(url, req, next) {\n\tURLModel.findOne({url: url}, function(err, result) {\n\t\tif (err) console.error(err);\n\t\tif (!result) {\n\t\t\taddURLToDatabase(url, req, next);\n\t\t} else {\n\t\t\treq.result = {\n\t\t\t\toriginal_url: \"https://\" + result.url,\n\t\t\t\tshort_url: result.shortURL\n\t\t\t};\n\t\t\tnext();\n\t\t}\n\t});\n}", "function searchForPlay(plays)\n{\n //all possible win combinations\n let matches = getPossibleMatches(plays);\n //a dumbed down version of possible win combinations (Basically, a count\n //of numbers of x's, o's, and blanks of each win combination on the board)\n let simplifiedMatches = simplifyMatches(matches);\n //the indexes for win combinations, based on a board like this: 0 1 2\n // 3 4 5\n // 6 7 8\n const matchIndexes = '012/345/678/036/147/258/048/246/';\n // the number of x's and o's respectively in a match possibility\n const typeOfPlays = [\n '02/', //checks if there is a play for a win\n '20/', //checks if the opponent needs to be blocked from a win\n '01/', //checks for possibility of two o tiles and a blank spot\n '00/' //checks for possibility of one o tile in a line of blank spots\n ];\n //the index for the variable 'matchIndexes' to chose\n let matchIndex = -1;\n\n //iterates through 'typeOfPlays' in respective order, and determines an\n //exact 'typeOfPlay' once the best option is found\n typeOfPlays.forEach(typeOfPlay =>\n {\n //checks the possiblility of given 'typeOfPlay'\n let isPlay = ((simplifiedMatches.horizontal.includes(typeOfPlay)) || (simplifiedMatches.vertical.includes(typeOfPlay)) || (simplifiedMatches.diagonal.includes(typeOfPlay)));\n\n //if a typeOfPlay has not yet been determined and a typeOfPlay has now\n //been determined than an exact 'matchIndex' is determined\n if(isPlay && matchIndex === -1)\n {\n matchIndex = determineExactPlay(simplifiedMatches, typeOfPlay);\n }\n });\n\n //checks if a play was found\n if(matchIndex > -1)\n {\n //finds match\n let indexesForMatch = matchIndexes.split('/')[matchIndex].split('');\n\n //iterates through the three spots of the match to find the blank spot\n //to play an 'o'\n for(let i = 0; i < indexesForMatch.length; i++)\n {\n if(plays[indexesForMatch[i]] === '_')\n {\n return indexesForMatch[i];\n }\n }\n }\n\n //if a logical play is not found an 'o' is placed anywhere that is blank\n return plays.indexOf('_');\n}", "function checkBoardTile(cx, cy, wordTreeNode, wordLen, strWorkString)\n{\n var tileLetter\n\n wordLen++;\n if (wordLen > maxWordLen) return;\n\n // Flag current tile as occupied\n boardTileUsed[cx][cy] = wordLen;\n\n // Read letter for current tile\n tileLetter = boardTiles[cx][cy];\n\n // Special handling for 'qu' tiles (the only tile with two letters)\n if (tileLetter == 'qu')\n {\n // If 'q' is a valid entry in word tree at this location then step past it and test with 'u'\n if ( wordTreeNode.hasOwnProperty( 'q' ) )\n {\n // Advance past 'q' to the letter 'u' in the word tree, append it to the working string, and check for words using 'u'\n if ( checkLetterInWordTree(wordTreeNode[ 'q' ], 'u', strWorkString + 'q', wordLen + 1) )\n {\n // Now check all adjacent tiles, including diagonals\n checkAdjacentTiles(cx, cy, wordTreeNode[ 'q' ], 'u', strWorkString + 'q', wordLen + 1);\n }\n }\n\n // Now drop through and handle 'q' as a singular letter without the trailing 'u'\n tileLetter = 'q';\n }\n\n // Test letter and explore further tiles and words if possible\n if ( checkLetterInWordTree(wordTreeNode, tileLetter, strWorkString, wordLen) )\n {\n // Now check all adjacent tiles, including diagonals\n checkAdjacentTiles(cx, cy, wordTreeNode, tileLetter, strWorkString, wordLen);\n }\n\n\n // Release tile for use again\n boardTileUsed[cx][cy] = 0;\n}", "function makeWinningMove(board){\n var boardString = mapSymbolToPatterns(board);\n for(var i = 0;i < winningMovePatterns.length;i++){\n if (boardString.match(winningMovePatterns[i][0])){\n console.log('make winning move');\n return winningMovePatterns[i][1];\n };\n }\n return -1;\n }", "function FindIdBoardFromBoardName(boardNameNew, callback) {\n\t//First try to get it from storage (more common)\n\tvar key = getKeyForIdFromBoard(boardNameNew);\n\tchrome.storage.local.get(key, function (obj) {\n\t\tvar value = obj[key];\n\t\t//If not in storage look for it on the db\n\t\tif (value === undefined) {\n\t\t\tvar sql = \"select idBoard FROM boards WHERE name=?\";\n\t\t\tvar values = [boardNameNew];\n\t\t\tgetSQLReport(sql, values,\n\t\t\t\tfunction (response) {\n\t\t\t\t\tif (response.rows === undefined || response.rows.length != 1 || response.rows[0].idBoard === undefined) {\n\t\t\t\t\t\tcallback(null);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcallback(response.rows[0].idBoard);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t} else {\n\t\t\tcallback(value.idBoard);\n\t\t}\n\t});\n}", "function search_in_board(element){\r\n\r\n var element_found = 0;\r\n \r\n for(i=0;i<8;i++)\r\n {\r\n for(j=0;j<8;j++)\r\n {\r\n if( document.getElementById(`${i}${j}`).textContent == element )\r\n {\r\n element_found = 1;\r\n \r\n var a = [];\r\n a[0] = i;\r\n a[1] = j;\r\n \r\n return a;\r\n }\r\n }\r\n }\r\n if(element_found == 0){\r\n return -1;\r\n }\r\n}", "function wordSearch(board, word) {\n if (word === \"\") return true;\n for (var row = 0; row < board.length; row++) {\n for (var col = 0; col < board[row].length; col++) {\n if (board[row][col] === word[0]) {\n if (dfs(0, row, col)) return true;\n }\n }\n }\n return false;\n\n function dfs(index, x, y) {\n if (index === word.length) return true;\n if (!board[x] || !board[x][y]) return false;\n if (board[x][y] !== '#' && board[x][y] === word[index]) {\n var ch = board[x][y];\n board[x][y] = '#';\n if (dfs(index + 1, x - 1, y)) return true; //up\n if (dfs(index + 1, x + 1, y)) return true; //down\n if (dfs(index + 1, x, y - 1)) return true; //left\n if (dfs(index + 1, x, y + 1)) return true; //right\n board[x][y] = ch;\n // backtracking到前一個節點\n }\n return false;\n }\n}", "function getMatchIdFromUrl(url)\n{\n const URL_OBJ = new URL(url);\n return URL_OBJ.pathname.split('/')[2];\n}", "function getWikidataURL(arr) {\n let r = new RegExp(regexStr);\n for (let url of arr)\n if (r.test(url))\n return url;\n}", "function getUrlEntry(key)\r\n{\r\n\tvar search=location.search.slice(1);\r\n\t//alert(search);\r\n\tvar my_id=search.split(\"&\");\r\n\t//alert(my_id);\r\n\ttry {\r\n\t\tfor(var i=0;i<my_id.length;i++)\r\n\t\t{\r\n\t\t\tvar ar=my_id[i].split(\"=\");\r\n\t\t\tif(ar[0]==key)\r\n\t\t\t{\r\n\t\t\t\treturn ar[1];\r\n\t\t\t}\r\n\t\t}\r\n\t} catch (e) {\r\n\t}\r\n\t\r\n\treturn null;\r\n}", "function findEntriesWithUrlPiece(entries, urlPieceMatches) {\n var matches = [], escapeRegExp = /[-[\\]{}()*+?.,\\\\^$|#\\s]/g;\n for (var i = 0, l = entries.length; i < l; i++ ) {\n var resp = HarParser.getResponseText(entries[i]), missing = false;\n for (var i2 = 0, l2 = urlPieceMatches.length; i2 < l2; i2++) {\n var index = resp.indexOf(urlPieceMatches[i2]);\n // Shortcut for performance. The regexp is expensive.\n if (index == -1) {\n missing = true;\n break;\n }\n\n // Escape any special characters\n // Check what the character immediately before is to see if its a word boundary.\n // Also allow for url encoded prefix, to catch: quantserve.com%2Fquant.js\n var match = new RegExp('([\\\\W\"\\'\\\\/]|%[A-Z0-9]{2})' + urlPieceMatches[i2].replace(escapeRegExp, \"\\\\$&\"));\n if (! match.test(resp)) {\n missing = true;\n break;\n }\n\n }\n if (!missing){\n matches.push(entries[i]);\n }\n }\n return matches;\n }" ]
{ "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 ? '' : ':' + port);\n var data = fs.readFileSync(fileName, defaultCharset);\n return data.replace(/http:\\/\\/localhost:8080/g, host);\n}", "function server_map_redirect(){ \n\t\t // get all servers listed through the status attribute\n\t\t\tvar list = document.getElementsByClassName(\"status\");\n\t\t\t\n\t\t\t// iterates each server found to update its map link based on current server status (online/offline)\n\t\t\tfor (var i = 0; i < list.length; i++) {\n\t\n\t\t\t\tvar sv_ip = $(list[i]).attr(\"data-playercounter-ip\");\n\t\t\t\tvar is_online = $(list[i]).text() == 'online' ? true : false;\n\t\t\t\tvar res = sv_ip.split(\":\");\n\t\t\t\tvar sv_port = res[1];\n\t\t\t\t// calculates dynmap port using the relation with sv ports\n\t\t\t\tvar sv_dynport = 8100 + (parseInt(sv_port)-25500); \n\n\t\t\t\t// if online, sets the link to the dynmap sv\n\t\t\t\tif(is_online) {\n\t\t\t\t\t// updates page\n\t\t\t\t\t$(list[i]).parents('.col.l4.s12').find('#dynmap').attr('href', 'http://omnium.serveminecraft.net:'+sv_dynport);\n\t\t\t\t} // if offline, link to error page\n\t\t\t\telse {\n\t\t\t\t\t$(list[i]).parents('.col.l4.s12').find('#dynmap').attr('href', 'error.php?did='+sv_dynport);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function urlReplace(url) {\n\tif (window.location.host.indexOf('localhost') !== -1) {\n\t\tvar urlNew = new URL(url);\n\t\turlNew.host = 'localhost';\n\t\turlNew.protocol = window.location.protocol;\n\t\treturn urlNew.toString();\n\t}\n\n\treturn url;\n}", "function build_localServer() {\n console.log(\"BrowserSync setting up the server in port 4000\");\n browserSync.init({\n port: 4000,\n server: {\n baseDir: \"./_site/\",\n },\n });\n}", "function GADGET_GEN_Launch()\n{\t\n\tSystem.Gadget.Settings.write(\"URL\", URL.Site);\n\tShell.Run(URL.Site);\n}", "function wakeUpServer() {\n\tvar h = require(\"http\");\n\th.get(SERVER_URL);\n}", "function target_launch_app() {\n var http = new XMLHttpRequest();\n http.open(\"GET\", \"./boa_launch.py\");\n http.onreadystatechange = function() {\n\tif (http.readyState == XMLHttpRequest.DONE) {\n\t if (http.status != 200) {\n\t\talert(\"target_launch_app()\\nError \" + http.status + \"\\n\" + http.statusText);\n\t } else\n\t\t// app has been launched.\n\t\t// try to connect\n\t\ttarget_connect(false);\n\t }\n }\n http.send();\n}", "function startServer(){\n if(isDev()){\n var options = {\n scriptPath: path.join(__dirname, '../../../engine/'),\n args: [TEMP_PATH],\n pythonPath: 'python'\n };\n\n PythonShell.run('dash_server.py', options, function (err, results) {\n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if (results) console.log('Results from dash server: ', results);\n });\n }else{\n var opt = function(){\n execFile(DASH_PATH, [TEMP_PATH], function(err, results) { \n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if(results) console.log('Results from dash server: ', results.toString()); \n });\n }\n opt();\n }\n\n}", "function onSuccess() {\n print(\"Url set successfully\");\n}", "function StartRemoteMov(url) {\n\tremoteWin = window.open('',\"GAGMEREMOTE2\",'width=670,height=520,resizable=yes,scrollbars=yes,statusbar=yes');\n\tremoteWin.statusbar.visibe = true;\n\tremoteWin.location = url;\n\tremoteWin.focus();\n}", "function main() {\n urlParameters = new URLSearchParams(window.location.search);\n serverClient = new ServerClient(urlParameters);\n noVNCClient = new NoVNCClient(\n connectCallback, disconnectCallback, \n document.getElementById('session-screen'));\n addOnClickListenerToElements();\n let /** number */ setIntervalId = setInterval(() => {\n serverClient.getSession().then(session => {\n clearInterval(setIntervalId);\n noVNCClient.remoteToSession(session.getIpOfVM(), \n session.getSessionId());\n setReadOnlyInputs(session.getSessionId());\n document.getElementById('welcome-message').style.display = 'block';\n updateUI();\n }).catch(error => {\n window.alert('No contact with the server, retrying!');\n });\n }, sessionScriptConstants.SERVER_RECONNECT_CADENCE_MS);\n}", "function updateLinks() {\n var programName=programNameField.value;\n loadLink.href=\"?program=\"+programName;\n runLink.href=loadLink.href+\"&run=\"+window.localStorage.getItem(getProgramAccessTokenKey(programName));\n}", "function init_url( url ) {\n\treturn api_url + url;\n}", "function ejecutarOperacionLocal() {\n\t if (utils_isComuServidorWeb()){\n\t\t utils_servidorWeb_enviaPlano(document.forms[0].SRVPRESENTACION_CONTEXTO_ENTRADA.value);\n\t }else{\n\t\t document.PlugIn.enviaPlano(document.forms[0].SRVPRESENTACION_CONTEXTO_ENTRADA.value);\n\t}\n}", "function getServerTargetUrl(path) {\n var x = require('MeshAgent').ServerUrl;\n //sendConsoleText(\"mesh.ServerUrl: \" + mesh.ServerUrl);\n if (x == null) { return null; }\n if (path == null) { path = ''; }\n x = http.parseUri(x);\n if (x == null) return null;\n return x.protocol + '//' + x.host + ':' + x.port + '/' + path;\n}", "function start()\n{\n if(!checkSite()) return;\n types = defineTypes();\n banned = [];\n banUpperCase(\"./public/\", \"\");\n var service = https.createServer(options, authenticate);\n\n/*\nservice.listen(PORT, () => {\n console.log(\"Our app is running on port \"+PORT);\n});\n*/\n\n service.listen(PORT);\n var address = \"https://localhost\";\n if(PORT != 80) address = address+\":\"+PORT+\"/\";\n console.log(\"Server running at\", address);\n\n}", "function updateURL() {\n const URLelement = elements.get(\"title\").querySelector(\"a\");\n switch (URLelement) {\n case null:\n currentURL = undefined;\n break;\n default:\n const id = URLelement.href.replace(/[^0-9]/g, \"\");\n currentURL = `https://tidal.com/browse/track/${id}`;\n break;\n }\n}", "function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}" ]
{ "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 return amountString;\n }", "function get_currency_code(str) {\n return str.match(/\\((.*?)\\)/)[1];\n}", "function convertPriceStringToNumber(price){\n\treturn Number(price.replace(/[^0-9\\.]+/g,\"\"));\n}", "function isCurrency(str, addDollarSign) {\n\tvar resultStr = \"\";\n\tvar outStr = \"\";\n\tvar\tisMinus = false\n\n\t// Return immediately if an invalid value was passed in\n\tif (str+\"\" == \"undefined\" || str == null) return null;\n\n\t// Default addDollarSign to false when undefined or null\n\t//if (addDollarSign+\"\" == \"undefined\" || addDollarSign+\"\" == \"null\")\t\n\t// addDollarSign = false;\n\taddDollarSign = addDollarSign || false;\n\n\t// Make sure the argument is a string\n\tstr += \"\";\n\n\tstr = Trim( str )\n\n\tif (str.charAt(0) == \"-\") {\n\t\tisMinus = true\n\t\tstr = str.substring(1,str.length)\n\t} else if ((str.charAt(0) == \"(\") && (str.charAt(str.length-1) == \")\")) {\n\t\tisMinus = true\n\t\tstr = str.substring(1,str.length)\n\t\tstr = str.substring(0,str.length-1)\n\t}\n\n\twhile (str.charAt(0) == \"0\" && str.length > 1) {\n\t\tstr = str.substring(1,str.length)\n\t}\n\n\t// Get the index of any decimal point.\n\t// If there is a decimal point, strip it\n\tidx = str.indexOf(\".\");\t\n\tif (idx >= 0)\n\t\tstr = str.substring(0, idx);\n\n\t// Loop through entire string, adding each character from the original\n\t// string if it is a number, removing dollar signs, commas.\n\tfor (var i=0; i < str.length; i++)\n\t{\n\t\tif ( (str.charAt(i) >= \"0\") && (str.charAt(i) <= \"9\") )\n\t\t\tresultStr += str.charAt(i);\n\t\telse if (!((str.charAt(i) == \"$\") || (str.charAt(i) == \",\")))\n\t\t\treturn null; \n\t} // end for loop\n\n\tif (resultStr.length == 0) return null; \n\n\t// Format output string\n\tif (isMinus) outStr = \"-\"\n\n\tif (addDollarSign) outStr += \"$\"\n\n\t// Insert commas\n\tif (resultStr.length > 3) {\n\t\tvar x = resultStr.length % 3 //length of first chunck\n\t\tif (x > 0) outStr += resultStr.substring(0, x) + \",\"\n\t\tresultStr = resultStr.substring(x, resultStr.length)\n\t\twhile (resultStr.length > 3) {\n\t\t\toutStr += resultStr.substring(0, 3) + \",\"\n\t\t\tresultStr = resultStr.substring(3, resultStr.length)\n\t\t}\n\t}\n\toutStr += resultStr\n\n\treturn outStr;\n}", "function getPrice(idPriceLabel) {\n var price = document.getElementById(idPriceLabel).innerText;\n price = price.replace(/[^.\\d]/g, '');\n price = parseInt(price);\n return price;\n}", "function marketCapToNum(mcString) {\r\n if (!mcString) {\n return;\n }\r\n const suffix = mcString.charAt(mcString.length-1);\r\n let mcNum;\r\n switch(suffix) {\r\n // billions\r\n case \"B\":\r\n mcNum = Number(mcString.replace(\"B\", \"\")) * 1000000000;\r\n break;\r\n // millions\r\n case \"M\":\r\n mcNum = Number(mcString.replace(\"M\", \"\")) * 1000000;\r\n break;\r\n // < 1 million, no suffix, remove commas\r\n default:\r\n mcNum = Number(mcString.replace(\",\", \"\"));\r\n }\r\n return mcNum;\r\n }", "function get_currency_name(str) {\n return str.replace(` (${get_currency_code(str)})`, '');\n}", "function cleanCashString(str) {\n return str.replace(\"$\", \"\");\n}", "function currencyFormat(x) {\n return x.toString().replace(/\\B(?<!\\.\\d*)(?=(\\d{3})+(?!\\d))/g, \".\");\n}", "function formatCurrency(num, addDollarSign) {\n\tvar resultStr = \"\";\n\tvar Str = \"\";\n\n\t// Return immediately if a null value was passed in\n\tif (num == null) return \"0\"\n\n\t// Return immediately if a NaN value was passed in\n\tif (isNaN(num)) return num; // return unchanged\n\n\tif (num < 0) resultStr = \"-\"\n\n\tif (addDollarSign == true) resultStr += \"$\"\t\n\n\t// convert the argument to a string\n\tStr = \"\" + num; \n\tif (Str.charAt(0) == \"-\") {\n\t\tStr = Str.substring(1,Str.length)\n\t}\n\n\t// Get the index of any decimal point.\n\t// If there is a decimal point, strip it\n\tidx = Str.indexOf(\".\");\t\n\tif (idx >= 0)\n\t\tStr = Str.substring(0, idx);\n\n\t// Format output string - insert commas\n\tif (Str.length > 3) {\n\t\tvar x = Str.length % 3 //length of first chunck\n\t\tif (x > 0) resultStr += Str.substring(0, x) + \",\"\n\t\tStr = Str.substring(x, Str.length)\n\t\twhile (Str.length > 3) {\n\t\t\tresultStr += Str.substring(0, 3) + \",\"\n\t\t\tStr = Str.substring(3, Str.length)\n\t\t}\n\t}\n\tresultStr += Str\n\treturn resultStr;\n}", "function getDollarAmount(amount) {\r\n return Math.round(amount).toString();\r\n}", "function getPay(isCustomer) {\n return isCustomer ? \"$5.0\" : \"$7.0\";\n}", "function GetAdjustPrice(adjust, source, numeratorUnit, denominator) {\n var returnVal = \"\";\n var IntPart;\n var NumPart;\n var IntPartAdjust;\n var NumPartAdjust;\n var IntPartSource;\n var NumPartSource;\n var NumPartSourceReal;\n var PointPos;\n var LinePos;\n var Diff; //the difference of the numeric part of the adjust and the numeric part of the source\n\n LinePos = source.indexOf(\"/\");\n PointPos = adjust.indexOf(\".\");\n //GetIntNumPartFmAdjust(adjust, IntPartAdjust, NumPartAdjust);\n {\n var pointPosTemp = adjust.indexOf(\".\");\n if (pointPosTemp == -1)\n IntPartAdjust = \"\";\n else {\n IntPartAdjust = adjust.substr(0, pointPosTemp);\n }\n NumPartAdjust = adjust.substr(pointPosTemp + 1);\n }\n\n //GetIntNumPartFmSource(source, IntPartSource, NumPartSource);\n {\n var pointPosTemp = source.indexOf(\".\");\n if (pointPosTemp == -1) {\n IntPartSource = source;\n NumPartSource = \"\";\n }\n else {\n IntPartSource = source.substr(0, pointPosTemp);\n NumPartSource = source.substr(pointPosTemp + 1);\n }\n }\n\n if (NumPartSource.length == 0) {\n //NumPartAdjust = parseInt(adjust, 10);\n NumPartAdjust = Math.round(parseInt(adjust * 10, 10) / 10).toString();\n Diff = NumPartAdjust.length - IntPartSource.length;\n if (Diff < 0) {\n IntPart = IntPartSource.substr(0, Math.abs(Diff)) + NumPartAdjust;\n IntPart = ((parseInt(IntPart) / numeratorUnit + (parseInt(IntPart) % numeratorUnit < numeratorUnit / 2 ? 0 : 1)) * numeratorUnit).toString();\n } else {\n IntPart = NumPartAdjust; //(parseInt(NumPartSource) / numeratorUnit) * numeratorUnit;\n }\n returnVal = IntPart;\n }\n else {\n if (LinePos == -1) {\n var decimalPart;\n Diff = NumPartAdjust.length - NumPartSource.length;\n if (PointPos == -1) {\n if (Diff > 0) {\n //NumPart = NumPartAdjust.substr(0, NumPartSource.length);\n\n //NumPart = Math.round(NumPartAdjust.substr(0, NumPartSource.length + 1) / 10);\n decimalPart = \"0.\" + NumPartAdjust.substr(0, NumPartSource.length + 1);\n } else {\n //NumPart = NumPartSource.substr(0, Math.abs(Diff)) + NumPartAdjust;\n decimalPart = \"0.\" + NumPartSource.substr(0, Math.abs(Diff)) + NumPartAdjust;\n }\n IntPart = IntPartSource;\n }\n else {\n if (Diff > 0) {\n //NumPart = NumPartAdjust.substr(0, NumPartSource.length);\n\n //NumPart = Math.round(NumPartAdjust.substr(0, NumPartSource.length + 1) / 10);\n decimalPart = \"0.\" + NumPartAdjust.substr(0, NumPartSource.length + 1);\n\n } else {\n //NumPart = NumPartAdjust.substr(0, NumPartSource.length) + NumPartSource.substr(NumPartSource.length - Math.abs(Diff));\n decimalPart = \"0.\" + NumPartAdjust.substr(0, NumPartSource.length) + NumPartSource.substr(NumPartSource.length - Math.abs(Diff));\n }\n Diff = IntPartAdjust.length - IntPartSource.length;\n if (Diff >= 0) {\n IntPart = IntPartAdjust;\n } else {\n IntPart = IntPartSource.substr(0, Math.abs(Diff)) + IntPartAdjust;\n }\n }\n NumPart = Math.round(decimalPart * denominator * Math.pow(10, numeratorUnit.toString().length - 1)); // 1, 1000, 0.1125, 0.1149, 10, 1000\n NumPart = Math.round(NumPart / Math.pow(10, numeratorUnit.toString().length - 1));\n var roundValue = Math.round(NumPart / numeratorUnit) * numeratorUnit;\n var intValue = parseInt(NumPart / numeratorUnit) * numeratorUnit;\n var decimalValue = parseFloat(decimalPart) * denominator;\n NumPart = (roundValue - decimalValue > decimalValue - intValue ? intValue : roundValue);\n\n // NumPart = Math.round(NumPart / numeratorUnit) * numeratorUnit;\n // normalizedValue = wholePart + parseFloat(numerator) / denominator;\n\n //returnVal = IntPart + \".\" + NumPart;\n\n if (NumPart < denominator) {\n //normalize numerator to multiple of _numeratorUnit\n NumPart = Math.round(NumPart / numeratorUnit) * numeratorUnit;\n //var normalizedValue = parseInt(IntPart) + parseFloat(NumPart) / denominator;\n\n //Denominator is 10,100....\n if (denominator == 10 || denominator == 100 || denominator == 1000 || denominator == 10000\n\t\t\t\t\t\t\t\t|| denominator == 100000 || denominator == 1000000 || denominator == 10000000 || denominator == 100000000)\n //var power10=Math.log(denominator)/Math.log(10);\n //if(Math.pow(10,Math.round(power10)) == denominator)\n {\n var iCount = (denominator.toString()).length - 1;\n returnVal = FormatAdjustPrice(parseInt(IntPart) + parseFloat(NumPart) / denominator, iCount);\n //normalizedValue = parseFloat(normalizedPrice);\n }\n else {\n if (parseFloat(NumPart) == 0) {\n returnVal = IntPart;\n //normalizedValue = parseFloat(normalizedPrice);\n }\n else {\n returnVal = IntPart + \".\" + NumPart.toString() + \"/\" + denominator.toString();\n }\n }\n }\n else {\n IntPart = parseInt(IntPart) + 1;\n var power10 = Math.log(denominator) / Math.log(10);\n if (Math.pow(10, Math.round(power10)) == denominator) {\n returnVal = IntPart + \".\" + denominator.toString().substr(1, Math.round(power10));\n }\n else {\n returnVal = IntPart;\n }\n //normalizedValue = parseFloat(normalizedPrice);\n }\n\n }\n else {\n NumPartSourceReal = NumPartSource.substr(0, NumPartSource.indexOf(\"/\"));\n if (PointPos == -1) {\n if (parseInt(NumPartAdjust) >= denominator) {\n returnVal = \"\";\n return returnVal;\n }\n else {\n if (NumPartAdjust.length < NumPartSourceReal.length) {\n NumPart = Trim(NumPartSourceReal.substr(0, NumPartSourceReal.length - NumPartAdjust.length) + NumPartAdjust);\n }\n else {\n NumPart = NumPartAdjust;\n }\n }\n IntPart = IntPartSource;\n }\n else {\n if (parseInt(NumPartAdjust.substr(0, (denominator.toString()).length - 1)) >= denominator) {\n returnVal = \"\";\n return returnVal;\n }\n else {\n if (NumPartSourceReal.length > NumPartAdjust.length) {\n if (parseInt(NumPartAdjust + NumPartSourceReal.substr(NumPartSourceReal.length - NumPartAdjust.length)) > denominator) {\n returnVal = \"\"\n return returnVal;\n }\n else {\n if (NumPartAdjust.length < NumPartSourceReal.length) {\n NumPart = Trim(NumPartAdjust + NumPartSourceReal.substr(NumPartSourceReal.length - NumPartAdjust.length));\n }\n else {\n NumPart = NumPartAdjust;\n }\n }\n }\n else {\n NumPart = NumPartAdjust.substr(0, (denominator.toString()).length - 1);\n }\n }\n Diff = IntPartAdjust.length - IntPartSource.length;\n if (Diff >= 0) {\n IntPart = IntPartAdjust;\n }\n else {\n IntPart = IntPartSource.substr(0, Math.abs(Diff)) + IntPartAdjust;\n }\n }\n if (parseInt(NumPart) > denominator) {\n returnVal = \"\";\n return returnVal;\n }\n\n if (parseInt(NumPart) % numeratorUnit > numeratorUnit / 2) {\n NumPart = ((parseInt(NumPart) / numeratorUnit + 1) * numeratorUnit).toString() + \"/\" + denominator.toString();\n }\n else {\n NumPart = ((parseInt(NumPart) / numeratorUnit) * numeratorUnit).toString() + \"/\" + denominator.toString();\n }\n returnVal = IntPart + \".\" + NumPart;\n }\n //returnVal = IntPart + \".\" + NumPart;\n }\n\n returnVal = GetAdjustPriceResult(Trim(returnVal));\n\n return returnVal;\n}", "function currencyConversor(value, currency) {\n let upperCaseCurrency = `${currency}`.toUpperCase();\n console.log('Last value update: July 10th 2021');\n\n if (value != Number) {\n console.log('The value typped is not a number');\n return;\n }\n\n switch (upperCaseCurrency) {\n case 'AMERICAN DOLLARS':\n let americanDollarsExchangeRate = 5.26;\n let americanDollarsresult = value * americanDollarsExchangeRate;\n\n console.log(\n `Your value of ${value} ${currency} equals ${americanDollarsresult} Brazilian Real`\n );\n break;\n case 'HONG KONG DOLLARS':\n let hongKongDollarsexchangeRate = 0.68;\n let hongKongDollarsresult = value * hongKongDollarsexchangeRate;\n\n console.log(\n `Your value of ${value} ${currency} equals ${hongKongDollarsresult} Brazilian Real`\n );\n break;\n default:\n console.log(\n `Please type the correct currency to converter to Brazilian Real. Available currencies:\n Hong Kong Dollars, American Dollars\n `\n );\n break;\n }\n}", "function ParseAndCalcShipCost(val) {\n console.log('ParseAndCalcShipCost()')\n\n if (val == null || val == '')\n return 0\n\n var expression = val.toLowerCase().replace(/&#39;/g, '\"')\n\n // var expression = '20 + [ fee percent=\"10\" min_fee=\"4\" ]'\n // var expression = '20 + [ qty]*10'\n // var expression = '[qty] * 10 + [fee percent=\"10\" min_fee=\"4\"]'\n // var expression = '10 + (1 + 2) * [qty]'\n\n return ParseWithLexer(expression) // see parseShipping.js\n} // ParseAndCalcShipCost()", "callback(value) { return ynabToolKit.shared.formatCurrency(value); }", "function USDconversion(bitcoinAmount) {\n var response = UrlFetchApp.fetch('https://api.bitcoinaverage.com/ticker/global/USD/last');\n return response * bitcoinAmount;\n}", "function getHouseholdIncome(input){\n let money = input.split(\"-$\");\n\n let Average = 0\n\n if (input ===\"$200,000+\"){\n Average = 200000\n }\n else if(input ===\"$0-$9,999\"){\n Average = 5000\n }else{\n \n let minMoney = money[0].slice(1,money[0].length-1).replace(\",\",\"\")\n console.log(money[1])\n let maxMoney = money[1].replace(\",\",\"\")\n Average = (parseInt(minMoney) + parseInt(maxMoney)+1 ) / 2\n }\n\n return Average\n \n}", "function getPriceOnly(text) {\n\tif (text.indexOf(\"stop loss\") > -1) {\n\t\ttext = text.substring(0, text.indexOf(\"stop loss\"));\n\t}\n\treturn text.replace(/[^0-9.]/g, \"\");\n}" ]
{ "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].name == fertilisersAdded[i].name) break; } var tmp = fertiliserData[j]; // rate fertilisersAdded[i].rate = Math.round(100 / (tmp.urea + tmp.nh4n + tmp.no3n) * fertilisersAdded[i].netRate / 100); // cost fertilisersAdded[i].cost = round2(tmp.cost / (tmp.urea + tmp.nh4n + tmp.no3n) * tmp.fractionCost / 1000); } return fertilisersAdded; }
[ "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\t\t\t}\n\t\t}\n\t}", "function addUsersSessionBounceRate(number_of_users_session_bounce_rate){\n var users = parseInt(number_of_users_session_bounce_rate.rows[0][0]);\n var sessions = parseInt(number_of_users_session_bounce_rate.rows[0][1]);\n var bounceRate = parseFloat(number_of_users_session_bounce_rate.rows[0][2]).toFixed(0);\n\n $(\"#n-volunteers\").html(users.toString());\n $(\"#n-sessions\").html(sessions.toString());\n\n $(\"#p-bounce-rate\").html(bounceRate.toString()+\" %\");\n}", "function setBetAmount(n, neg) {\r\n if (neg) {\r\n betAmount += -Math.abs(parseFloat(n))\r\n } else {\r\n betAmount += parseFloat(n);\r\n }\r\n if (betAmount >= playerTotal) {\r\n betAmount = playerTotal;\r\n }\r\n updateBetAmount();\r\n }", "function ratefeed(currency, askrate, bidrate) {\r\n var tag = currency.replace(\"/\", \"\")\r\n latestrate[currency] = {\r\n \"bid\": bidrate,\r\n \"ask\": askrate\r\n }\r\n\r\n updateChart({\r\n currency: tag,\r\n askrate: askrate,\r\n bidrate: bidrate\r\n})\r\n\r\n var txtaskrate = parseFloat($(\"#\" + tag + \"ask\").html())\r\n var txtbidrate = parseFloat($(\"#\" + tag + \"bid\").html());\r\n (parseFloat(askrate) > txtaskrate) ? $(\"#\" + tag + \"ask\").removeClass('blue-text red-text').addClass('green-text'):\r\n (parseFloat(askrate) < txtaskrate) ? $(\"#\" + tag + \"ask\").removeClass('blue-text green-text').addClass('red-text'):\r\n $(\"#\" + tag + \"ask\").removeClass('red-text green-text').addClass('blue-text');\r\n\r\n (parseFloat(bidrate) > txtbidrate) ? $(\"#\" + tag + \"bid\").removeClass('blue-text red-text').addClass('green-text'):\r\n (parseFloat(bidrate) < txtbidrate) ? $(\"#\" + tag + \"bid\").removeClass('blue-text green-text').addClass('red-text') :\r\n $(\"#\" + tag + \"bid\").removeClass('red-text green-text').addClass('blue-text');\r\n\r\n $(\"#\" + tag + \"ask\").html(askrate);\r\n $(\"#\" + tag + \"bid\").html(bidrate);\r\n\r\n}", "addLayers(numLayersToAdd = 1, numNodesInLayer = 1) {\n for (let i = 0; i < numLayersToAdd; i++) {\n const numOfLayers = Object.keys(this.layers).length;\n this.layers[`layer ${numOfLayers + 1}`] = {\n 'activation': 'sigmoid',\n 'neurons': numNodesInLayer,\n }\n }\n }", "function insertgetUniRates2(event) {\n\t event.preventDefault();\n\t var uniRates2 = {\n\t category: 'Technical_Engineering',\n\t location: 'RTP',\n\t ed_level: 'Masters',\n\t pay_minimum: 86000,\n\t pay_maximum: 106000\n\t };\n\n\t $.post(\"/api/UniRates2\", uniRates2, getUniRates2);\n \t}", "function normConv(rate, symbol) {\n curPrice = parseFloat(basePrice * rate).toFixed(2);\n curDaily = parseFloat(baseChange * rate).toFixed(2);\n $price.text(symbol + curPrice);\n $daily.text(symbol + curDaily);\n}", "function updateDebtInterestRate(token, debtID, newInterestRate) {\n try {\n var userData = validateToken(token);\n var userEmail = userData.email;\n var updateQuery = 'UPDATE Debts SET interestRate=?, lastUpdated=CURRENT_TIMESTAMP WHERE email=? AND debtID=?;';\n var parameters = [newInterestRate, userEmail, debtID];\n executeManipulationQuery(updateQuery, parameters);\n return \"Success\";\n }\n catch (err) {\n throw new Error( \"Error modifying debts!\" );\n }\n}", "function taxCalculator(amount, taxrate){\n return amount + (amount * taxrate);\n}", "function efficiency(snr) {\n return Math.log2(1.0 + Math.pow(10,snr/10));\n }", "addNodes(layerIndex, numNodesAdded = 1) {\n const jsonLayerIndex = Object.keys(this.layers)[layerIndex];\n this.layers[jsonLayerIndex].neurons += numNodesAdded;\n console.log(this.layers);\n }", "function calculateRate ()\n{\n $(\"#currentRate\").html(\"0\");\n\n if (SellCurrency.value != \"void\" && BuyCurrency.value != \"void\")\n {\n updateRate(SellCurrency.value, BuyCurrency.value);\n if (inputSellAmount.value != \"\")\n updateBuyValue(parseFloat(inputSellAmount.value), SellCurrency.value, BuyCurrency.value);\n else\n inputBuyAmount.value = 0;\n }\n}", "function compoundInterest(p, t, r, n) {\n\treturn Number((p * Math.pow((1 + r / n), n * t)).toFixed(2));\n}", "function updateForexRateFromServer() {\n\t\t$http({\n\t\t\tmethod : 'GET',\n\t\t\turl : NJS_API + \"/currency-adjustments/get-all-active-forex-rate/\"\n\t\t}).success(function(response) {\n\t\t\tconsole.log(response.result);\n\t\t\twindow.localStorage.setItem(\"currency_rate\", JSON.stringify(response.result));\n\t\t});\n\t}", "calcNettoPayment() {\n if (elements.ageInputWork.checked) {\n this.calcTax();\n this.netAmount = this.payment - this.PIT;\n } else {\n this.netAmountUnderAge = this.payment;\n }\n }", "function getRate(i) {\n // console.log(hotelsArr[i][\"room-rates\"][\"room-rate\"]);\n let tempRateArr = hotelsArr[i][\"room-rates\"][\"room-rate\"];\n let rateArr = new Array();\n\n if(Array.isArray(tempRateArr)) {\n for(let d=0; d < 2; d++){\n // console.log(tempRateArr[d][\"rate-breakdown\"]);\n let tempBreakdown = tempRateArr[d][\"rate-breakdown\"][\"common:rate\"][\"common:pricing-elements\"][\"common:pricing-element\"];\n tempBreakdown.forEach(function(item) {\n rateArr.push(item);\n });\n }\n } else {\n rateArr.push(tempRateArr[\"rate-breakdown\"][\"common:rate\"][\"common:pricing-elements\"][\"common:pricing-element\"]);\n }\n\n let cost = 0;\n\n rateArr.forEach(function (item) {\n cost += item[\"common:amount\"];\n });\n\n return cost.toFixed(2);\n}", "function updateRateLimit() {\n api.getRateLimit(function(remaining, limit) {\n $limit.html(\"Rate Limit: \" + remaining + \"/\" + limit);\n });\n }", "function countKurtaMwfPlus() {\n\t\t\tinstantObj.noOfKurtaMWF = instantObj.noOfKurtaMWF + 1;\n\t\t\tcountTotalBill();\n\t\t}", "trending(event) {\n document.getElementById(\"StartPrice\").value = \"21.00\";\n document.getElementById(\"msPerSec\").value = \"15\";\n document.getElementById(\"numLiq\").value = \"100\";\n document.getElementById(\"numInf\").value = \"50\";\n document.getElementById(\"numMom\").value = \"50\";\n document.getElementById(\"numPStar\").value = \"3\";\n document.getElementById(\"FracOfDay\").value = \"1\";\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 to generate the decompressed list. Return the decompressed list. / Input: nums = [1,2,3,4] Output: [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
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); } // // console.log([frequency, val]); } return arr; }
[ "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 let j = nums.length - 1;\n while (j >= 0 && nums[i] > nums[j]) {\n j--;\n }\n //swap to get ready to increment\n [nums[i], nums[j]] = [nums[j], nums[i]];\n }\n //reverse the right of the mutation part to increasing\n reverse(nums, i + 1)\n return nums;\n}", "function radixSort(arr){\n var maxDigitCountInArray = maxDigitCount(arr);\n //creating 10 buckets from 0 to 9 as empty arrays for once place 10's place form 0 to 9\n \n for(var k =0; k < maxDigitCountInArray; k++){\n var digitBucket = Array.from({length:10}, () => [])\n //loop for maxDigitCountInArray\n for(var i =0; i < arr.length; i++){\n digitBucket[getDigit(arr[i],k)].push(arr[i])\n }\n arr = [].concat(...digitBucket);\n }\n return arr;\n}", "function intermediateSums(arr) {\n var lastSet = arr.length % 10;\n var sum = 0;\n for (var i = arr.length - 1; i > arr.length - (1 + lastSet); i--) {\n sum += arr[i];\n }\n arr[arr.length] = sum;\n // for loop incremented by 11 (10 plus the total one)\n for (var i = 0; i < arr.length; i += 11) {\n sum = 0;\n for (var j = i; j < i + 10; j++) {\n sum += arr[j];\n }\n // console.log(\"Sum: \" + sum)\n for (var k = arr.length - 1; k > i + 10; k--) {\n [arr[k], arr[k-1]] = [arr[k-1], arr[k]];\n }\n arr[i + 10] = sum;\n }\n // add first 10 values\n // loop back to 10, shifting all elements one to the right.\n // assign sum to 10,\n // do the next set.\n return arr;\n}", "function composeRanges(nums) {\n\n let stringArr = [];\n let firstNum = nums[0];\n let prevNum = nums[0];\n let currStr = `${nums[0]}`;\n\n if(nums.length === 0){\n return [];\n }\n\n for(let x = 1; x < nums.length; x++){\n\n if(nums[x] - 1 === prevNum){\n currStr = `${firstNum}->${nums[x]}`;\n\n } else {\n stringArr.push(currStr);\n currStr = `${nums[x]}`;\n firstNum = nums[x];\n }\n\n prevNum = nums[x];\n }\n\n stringArr.push(currStr);\n\n return stringArr;\n}", "function radixSort(arr) {\n let loopCount = mostDigits(arr);\n\n for (let i = 0; i < loopCount; i++) {\n let buckets = Array.from({ length: 10 }, () => []);\n for (let j = 0; j < arr.length; j++) {\n buckets[getDigit(arr[j], i)].push(arr[j]);\n }\n \n arr = [].concat(...buckets);\n }\n\n return arr;\n}", "function countingSort(stringArr, pfxlen){\n if(pfxlen === undefined){ pfxlen = 1; }\n\n var i, k, p, counts, sortedArr;\n\n /* For a given item, reuturn its 0-based array index integer key.\n * This should be a constant-time function mapping an item/prefix\n * to its array index.\n */\n var _keyfn = function(idx, itm){\n return punycode.ucs2.decode(itm[idx])[0];\n };\n\n // Prefix block method:\n // idx, start, end\n var prefixBlocks = [[0, 0, stringArr.length - 1]];\n var block, keyfn, idx, pfx, curPfx, curStart, start, end;\n\n while(prefixBlocks.length > 0){\n sortedArr = [];\n block = prefixBlocks.pop();\n idx = block[0]; start = block[1]; end = block[2];\n if(idx > pfxlen){ break; }\n if(start === end){ continue; }\n\n keyfn = partial(_keyfn, [idx]);\n counts = countItems(stringArr, keyfn, start, end);\n counts = init0(counts);\n counts = accumulate(counts);\n\n for(i=start; i<=end; i++){\n k = keyfn(stringArr[i]);\n sortedArr[counts[k]] = stringArr[i];\n counts[k]++;\n }\n\n // copy sorted items back to original array (sub-range now sorted)\n for(i=0; i<sortedArr.length; i++){\n stringArr[i+start] = sortedArr[i];\n }\n\n if(idx < pfxlen){\n curStart = start;\n curPfx = stringArr[start].slice(0, idx+1);\n for(i=start; i<=end; i++){\n pfx = stringArr[i].slice(0, idx+1);\n if(pfx !== curPfx){\n if(curStart !== i-1){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, i-1]);\n }\n curStart = i;\n curPfx = stringArr[i].slice(0, idx+1);\n }\n }\n if(curStart !== end){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, end]);\n }\n }\n\n }\n\n return stringArr;\n}", "function lastKNums (length, sequence) {\n let arrWithNums = [1];\n while (arrWithNums.length < length) {\n let result = 0;\n if (sequence >= arrWithNums.length) {\n let currentNum = arrWithNums.reduce ((acc, val) => {return acc + val});\n result += currentNum;\n arrWithNums.push(result);\n }\n else{\n for (let j = 1; j < sequence + 1; j++) {\n result += arrWithNums[arrWithNums.length - j];\n }\n arrWithNums.push(result);\n }\n }\n console.log(arrWithNums.join(' '));\n}", "function solution_2 (nums) {\r\n const output = Array(nums.length).fill(1); // we never have to create a new `productsToRight` array\r\n for (let i = nums.length - 2; i >= 0; i--) {\r\n output[i] *= output[i + 1] * nums[i + 1]; // e.g. [24, 12, 4, 1]\r\n }\r\n let productToLeft = 1; // this single `productToLeft` variable starts at 1, and represents the cumulative product\r\n for (let i = 0; i < nums.length; i++) {\r\n output[i] *= productToLeft; // take `output[i]` and multiply through with current `productToLeft`...\r\n productToLeft *= nums[i]; // ...then update `productToLeft` with current `nums[i]`\r\n }\r\n return output;\r\n}", "nCr_wo_repitition_3(n, r) {\r\n // ht tps://www.geeks forgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/\r\n // This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn2(n, r, index, tmp, i) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // When no more elements are there to put in tmp[]\r\n if (i >= n) return;\r\n\r\n // current is included, put next at next location\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn2(n, r, index + 1, tmp, i + 1);\r\n\r\n // current is excluded, replace it with next (Note that\r\n // i+1 is passed, but index is not changed)\r\n nCr_wo_reptn2(n, r, index, tmp, i + 1);\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn2(n, r, 0, tmp, 0);\r\n\r\n return res;\r\n }", "function removeDups(nums) {\n // place the first index start at one because its always unique\n var output = 1;\n // nums.sort();\n // console.log(nums);\n // now we want to run thorugh the array and compare each element with the following element. and we do nums.length - 1 when we compare the second to last value to the last value, we don;t go out of bounds. \n // this function is replacing indecies with the current value. no need to use .sort()\n for(var i = 0; i < nums.length - 1; i++){\n if(nums[i] != nums[i + 1]) {\n // we want to place the current number at the current index we're on.\n nums[output++] = nums[i + 1];\n // output.push(i);\n }\n }\n return output;\n \n}", "function merge(x, y, len_x) {\n // cnt is number of out of order triples\n // res is the new sorted array(each element is tri)\n // x and y are going to be combined\n // len_x is number of elements that have not been added to the new array\n // used_y is number of elements that have been added to the new array\n function helper(cnt, res, x, y, len_x, used_y) {\n if(is_empty_list(x) && is_empty_list(y)) {\n return pair(cnt, res);\n } else if(is_empty_list(x)) {\n const yy = head(y);\n const num_y = head(yy);\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n return helper(cnt, append(res, list(tri(num_y,\n lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n } else if(is_empty_list(y)) {\n const xx = head(x);\n const num_x = head(xx);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n const xx = head(x);\n const yy = head(y);\n const num_x = head(xx);\n const num_y = head(yy);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n if(num_x <= num_y) {\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n return helper(cnt + len_x * rt_y,\n append(res, list(tri(num_y,\n len_x + lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n }\n }\n }\n return helper(0, [], x, y, len_x, 0);\n }", "function orderIntoRGBs(arr) {\n let startIndex =-1;\n\n while (startIndex !== arr.length - 1) {\n startIndex += 1;\n let endIndex = arr.length-1;\n\n while (startIndex !== endIndex) {\n let startVal = arr[startIndex];\n let endVal = arr[endIndex];\n\n if (startVal < endVal) {\n arr[startIndex] = endVal;\n arr[endIndex] = startVal;\n }\n endIndex -= 1;\n }\n }\n \n // console.log(arr)\n return arr\n}", "nCr_wo_repitition_2(n, r) {\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn(tmp, start, end, index, r) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // replace index with all possible elements. The condition\r\n // \"end-i+1 >= r-index\" makes sure that including one element\r\n // at index will make a combination with remaining elements\r\n // at remaining positions\r\n for (let i = start; i <= end && end - i + 1 >= r - index; i++) {\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn(tmp, i + 1, end, index + 1, r);\r\n }\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn(tmp, 0, n - 1, 0, r);\r\n\r\n return res;\r\n }", "function longestIncreasingSubsequence(nums) {\n let dp = new Array(nums.length).fill(1)\n let max = 0\n for (let i = 1; i < nums.length; i++) {\n for (let j = 0; j < i; j++) {\n if (nums[j] < nums[i]) {\n dp[i] = Math.max(dp[j] + 1, dp[i])\n }\n }\n max = Math.max(max, dp[i])\n }\n return max\n}", "function runningSum(nums) {\n let arr = [];\n for(let i = 0; i < nums.length; i++) {\n if(i===0) {\n arr.push(nums[i])\n } else {\n arr.push(nums[i] + arr[i - 1]);\n };\n };\n return arr;\n}", "function zFunction(list, startIndex) {\n var n = list.length - startIndex;\n if (n === 0)\n return [];\n\n var z = new Array(n);\n z[0] = 0;\n\n for (var i = 1, left = 0, right = 0; i < n; ++i) {\n var maxLength;\n if (i <= right)\n maxLength = Math.min(right - i + 1, z[i - left]);\n else\n maxLength = 0;\n\n while (i + maxLength < n && list[startIndex + maxLength] ===\n list[startIndex + i + maxLength]) {\n ++maxLength;\n }\n\n if (i + maxLength - 1 > right) {\n left = i;\n right = i + maxLength - 1;\n }\n\n z[i] = maxLength;\n }\n\n return z;\n }", "function getCompressedIntervals(intervals) {\n // keep track of whether an interval has an overlapping partner\n let intervalOverlapsAnother = new Array(intervals.length).fill(false);\n let compressedIntervals = [];\n for (let x=0; x < intervals.length; x++) {\n for (let y=x+1; y < intervals.length; y++) {\n let find = findOverlap(intervals[x], intervals[y]);\n if (find.overlaps) {\n compressedIntervals.push([find.min, find.max]);\n intervalOverlapsAnother[x] = true;\n intervalOverlapsAnother[y] = true;\n }\n }\n }\n intervalOverlapsAnother.forEach((intHasOverlap, idx) => {\n // this is needed so that we include points for lone intervals (no overlaps)\n if (!intHasOverlap) compressedIntervals.push(intervals[idx]);\n });\n return compressedIntervals;\n}", "function reverse_append(xs, tl) /* forall<a> (xs : list<a>, tl : list<a>) -> list<a> */ {\n function reverse_acc(acc, ys) /* forall<a> (acc : list<a>, ys : list<a>) -> list<a> */ { tailcall: while(1)\n {\n if (ys != null) {\n {\n // tail call\n var _x1 = Cons(ys.head, acc);\n acc = _x1;\n ys = ys.tail;\n continue tailcall;\n }\n }\n else {\n return acc;\n }\n }}\n return reverse_acc(tl, xs);\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_indices = _.map(lists, function(arr) { return arr.length })\n var aggregate_reverse_index = _.reduce(reverse_indices, function(sum, len) {\n return sum + len \n }, 0)\n\n while ( aggregate_reverse_index > 0 ) {\n var pull_arr_index = null, pull_val = null\n\n for (var i = 0; i < lists.length; i++) {\n if (reverse_indices[i] == 0) {\n // Reached the end of this list.\n continue;\n } else if ( pull_arr_index != null && dup_fn &&\n dup_fn(lists[i][lists[i].length-reverse_indices[i]], pull_val) ) {\n // Found a duplicate, advance the index of the list in which the\n // duplicate was found.\n reverse_indices[i] -= 1\n aggregate_reverse_index -= 1\n } else if ( pull_arr_index == null ||\n cmp_fn(lists[i][lists[i].length-reverse_indices[i]], pull_val) < 0 ) {\n // Found a lower value.\n pull_arr_index = i\n pull_val = lists[i][lists[i].length-reverse_indices[i]]\n }\n }\n if (pull_arr_index != 0) {\n // Add the lowest found value in place into the first array.\n lists[0].splice(lists[0].length - reverse_indices[0], 0, pull_val)\n }\n aggregate_reverse_index -= 1\n reverse_indices[pull_arr_index] -= 1\n }\n return lists[0]\n }" ]
{ "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.getForm('login.username').object.value;\n }\n app.getView({\n ContinueURL: URLUtils.https('Account-RegistrationForm')\n }).render('account/user/registration');\n}", "function getOrganization() {\n return settings.getOrganization();\n}", "function registrationForm() {\n app.getForm('profile').handleAction({\n confirm: function () {\n var email, profileValidation, password, passwordConfirmation, existingCustomer, Customer, target, customerExist;\n\n Customer = app.getModel('Customer');\n email = app.getForm('profile.customer.email').value();\n \n profileValidation = true;\n customerExist = false;\n \n password = app.getForm('profile.login.password').value();\n passwordConfirmation = app.getForm('profile.login.passwordconfirm').value();\n\n if (password !== passwordConfirmation) {\n app.getForm('profile.login.passwordconfirm').invalidate();\n profileValidation = false;\n }\n\n // Checks if login is already taken.\n existingCustomer = Customer.retrieveCustomerByLogin(email);\n if (existingCustomer !== null) {\n app.getForm('profile.customer.email').invalidate();\n profileValidation = false;\n customerExist = true;\n }\n\n if (profileValidation) {\n profileValidation = Customer.createAccount(email, password, app.getForm('profile'));\n }\n\n if (!profileValidation) {\n \tif(customerExist){\n \t\tresponse.redirect(URLUtils.https('Login-Show','existing', true));\n \t} else {\n \t\tresponse.redirect(URLUtils.https('Account-Show'));\n \t}\n } else {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n app.getForm('profile').clear();\n target = session.custom.TargetLocation;\n if (target) {\n delete session.custom.TargetLocation;\n //@TODO make sure only path, no hosts are allowed as redirect target\n dw.system.Logger.info('Redirecting to \"{0}\" after successful login', target);\n response.redirect(target);\n } else {\n response.redirect(URLUtils.https('Account-Show', 'registration', 'true'));\n }\n }\n }\n });\n}", "function fillCreateProfileFromPromoRegister() {\n\t$('#emailIdChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#confrmEmailIdChkOut').val($(\"#confrmEmailIdPromoCode\").val());\n\t$('#passwordChkOut').val($(\"#passwordPromoCode\").val());\n\t$('#mobileNoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeChkOut').val($(\"#zipCodePromoCode\").val());\n\t$('#promoCodeDiscount2').val($(\"#promoCodeDiscount1\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', false);\n\t}\n\t$(\"#createAccountBoxChkOut\").show();\n\tvalidateCreateProfile();\n}", "function fillPromoRegisterFromCreateProfile() {\n\t$('#emailIdPromoCode').val($(\"#emailIdChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#confrmEmailIdChkOut\").val());\n\t$('#passwordPromoCode').val($(\"#passwordChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeChkOut\").val());\n\t$('#promoCodeDiscount1').val($(\"#promoCodeDiscount2\").val());\n\tif ($('#chkOptInEnhCreatProf').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"createAccountBoxChkOut\");\n\t$(\"#createAccountBoxChkOut\").hide();\n\tclearIntervalApp(chkRegisterBtnCount);\n}", "validateOrganisation(ctx, organisation) {\n\t \tconst orgMSPId = ctx.clientIdentity.getMSPID();\n\t \tif (orgMSPId !== organisation) {\n\t\t\t throw new Error(\"Only users from Registrar Organisation can invoke this function call\");\n\t \t}\n \t}", "function gadgetShowSettings(){\r\n \r\n //toggle display of settings\r\n if($('#gadgetSettings').css('display')!='none'){\r\n $('#gadgetSettings').css('display','none');\r\n return;\r\n }\r\n else $('#gadgetSettings').css('display','block');\r\n \r\n //if form elements already drawn, return\r\n if($('#prefsForm').attr('id')) return;\r\n \r\n //get prefs profiles obj\r\n profilesOn = prefs.getArray('profiles');\r\n \r\n //build settings html form\r\n html = '<form id=\"prefsForm\">';\r\n \r\n //checkbox's for turning profile display on/off\r\n for(var i=0; i<profiles.length; i++){\r\n id = profiles[i].getTableId().getValue();\r\n \r\n //if profileId is in profilesOn[] then checked=checked\r\n html += '<input type=\"checkbox\" value=\"' + id + '\" id=\"settingsProfile'+i+'\" name=\"profile\"';\r\n if($.inArray(id, profilesOn) >= 0) html += ' checked=\"checked\"';\r\n html += '/>' + \r\n '<label for=\"settingsProfile'+i+'\">'+profiles[i].getPropertyValue('ga:AccountName')+'</label><br/>';\r\n }\r\n\r\n //finish form, submit btn\r\n html += '</form>';\r\n html += '<button onclick=\"gadgetSetSettings()\">Save</button>';\r\n \r\n //append form\r\n document.getElementById('gadgetSettings').innerHTML = html;\r\n \r\n //resize window\r\n _IG_AdjustIFrameHeight();\r\n }", "function fillAdditionalInfoFromPromoRegister() {\n\t$('#emailIdAddInfoChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#mobileNoAddInfoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeAddInfoChkOut').val($(\"#zipCodePromoCode\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', false);\n\t}\n\t$(\"#additional_info_box\").show();\n\tvalidateAdditionalInfo();\n}", "function fillPromoRegisterFromAdditionalInfo() {\n\t$('#emailIdPromoCode').val($(\"#emailIdAddInfoChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#emailIdAddInfoChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoAddInfoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeAddInfoChkOut\").val());\n\tif ($('#chkOptInEnhAddInfo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"additional_info_box\");\n\t$(\"#additional_info_box\").hide();\n}", "DisplayAspNetConfigSettings() {\n\n }", "function showRegistrationDetails() {\n\tselectOne(sessionStorage.getItem('userID'), function(record) {\n\t\t\n\t\tif(!record) {\n\t\t\tconsole.log('Not found');\n\t\t}\n\t\telse {\n\t\t\t$('#txtFirstName').val(record.firstname);\n\t\t\t$('#txtLastName').val(record.lastname);\n\t\t\t$('#txtAddressline1').val(record.addressline1);\n\t\t\t$('#txtAddressline2').val(record.addressline2);\n\t\t\t$('#txtPostcode').val(record.postcode);\n\t\t\t$('#txtCity').val(record.city);\n\t\t\t$('#txtEmail').val(record.email);\n\t\t}\n\t});\n}", "function set_new_patron_defaults(prs) {\n if (!$scope.patron.passwd) {\n // passsword may originate from staged user.\n $scope.generate_password();\n }\n $scope.hold_notify_type.phone = true;\n $scope.hold_notify_type.email = true;\n $scope.hold_notify_type.sms = false;\n\n // staged users may be loaded w/ a profile.\n $scope.set_expire_date();\n\n if (prs.org_settings['ui.patron.default_ident_type']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_ident_type'];\n var ident_type = $scope.ident_types.filter(\n function(type) { return type.id() == id })[0];\n $scope.patron.ident_type = ident_type;\n }\n if (prs.org_settings['ui.patron.default_inet_access_level']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_inet_access_level'];\n var level = $scope.net_access_levels.filter(\n function(lvl) { return lvl.id() == id })[0];\n $scope.patron.net_access_level = level;\n }\n if (prs.org_settings['ui.patron.default_country']) {\n $scope.patron.addresses[0].country = \n prs.org_settings['ui.patron.default_country'];\n }\n }", "getAdminInfo() {\n return {\n admin_1: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_1),\n admin_2: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_2),\n signature_1: this.data.config.AG_REGISTER_SIGNATURE_1,\n signature_2: this.data.config.AG_REGISTER_SIGNATURE_2,\n address_pos_left: this.data.config.ADDRESS_POS_LEFT,\n address_pos_top: this.data.config.ADDRESS_POS_TOP,\n }\n }", "function updateInstitutionOwner() \n{\n\tvar dataObjTemp = $('#sensorTagConfigForm').serializeJSON();\n\tvar newMetadata = {}\n\tnewMetadata.institution = dataObjTemp.institution\n\tnewMetadata.owner = dataObjTemp.owner\n\t\n\treadSensorTagConfigFile(updateSensorTagConfigFileMetadata, newMetadata);\n\t\n\talert(\"SensorTag Mapping file updated\")\n}", "function showConfigUser() {\n\n\tdocument.getElementById('sel_editor_font_size').value = v_editor_font_size;\n\tdocument.getElementById('sel_editor_theme').value = v_theme_id;\n\n\tdocument.getElementById('txt_confirm_new_pwd').value = '';\n\tdocument.getElementById('txt_new_pwd').value = '';\n\n\t$('#div_config_user').show();\n\n}", "function registerAudience(){\n \taudienceFirstName=frmRegistration.txtBoxFirstName.text;\n \tif(audienceFirstName==null||audienceFirstName==\"\"){\n \talert(\"please enter first name\");\n \treturn;\n \t}\n \taudienceLastName=frmRegistration.txtBoxLastName.text;\n \tif(audienceLastName==null||audienceLastName==\"\"){\n \talert(\"please enter last name\");\n \treturn;\n \t}\n \taudienceEmail=frmRegistration.txtBoxEmail.text;\n \tif(audienceLastName==null||audienceLastName==\"\"){\n \talert(\"please enter email id\");\n \treturn;\n \t}\n \taudienceMob=frmRegistration.txtBoxMob.text;\n \tif(audienceMob==null||audienceMob==\"\"){\n \talert(\"please enter mobile number\");\n \treturn;\n \t}\n /*\tkony.print(\"\\n--audienceFirstName->\"+audienceFirstName);\n\tkony.print(\"\\n--audienceLastName-->\"+audienceLastName);\n\tkony.print(\"\\n--audienceEmail-->\"+audienceEmail);\n\tkony.print(\"\\n--audienceMob-->\"+audienceMob);\n\tkony.print(\"\\n--audienceStatus-->\"+audienceStatus);\n\tkony.print(\"\\n--audiencePushSubs-->\"+audiencePushSubs);\n\tkony.print(\"\\n--audienceEmailSubs-->\"+audienceEmailSubs);\n\tkony.print(\"\\n--audienceSmsSubs-->\"+audienceSmsSubs);*/\n\tif(audiencePushSubs){\n\tkony.print(\"\\n--calling pushregister()--\");\n\tif(kony.os.deviceInfo().name==\"iPhone Simulator\"){\n\t\t//audiencePushSubs=false;\n\t\talert(\"push doesn't support in iPhone simulator.\");\n\t\treturn;\n\t}else{\n\t\tpushRegister();\n\t}\n\tkony.print(\"\\n--returned from pushregister()--\");\n\t}\n\t\tregister();\n}", "affiliateSignup (form_data, success_callback, failure_callback)\n {\n var url = '/global/crm/user/affiliate/signup';\n return WebClient.basicPost(form_data, url, success_callback, failure_callback);\n }", "async getUserOrganisation() {\n let userId = await getUserId()\n if (userId != 0) {\n var url = `api/userorganisation?userId=${userId}`;\n return Method.dataGet(url, token)\n }\n }", "function save_existing_account()\r\n {\r\n if(!validate_dwolla_id()) return;\r\n\r\n charity_info.dwolla_id=$(\"#dwolla_id\").val();\r\n\r\n $.ajax(\r\n {\r\n url: \"/save_charity\",\r\n type: \"POST\",\r\n data: charity_info,\r\n success:\r\n function(data)\r\n {\r\n if(data.success)\r\n {\r\n charity_info.id=data.charity_id;\r\n $(\"#charity_id\").html(charity_info.id);\r\n _gaq.push([\"_trackPageView\",\"/register/step3\"]);\r\n show_next();\r\n }\r\n else\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was an internal problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n },\r\n error:\r\n function(data)\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was a problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n }); //end save_charity ajax call\r\n }" ]
{ "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() + parseInt(service.token.expired_in) - 60); // 60 seconds less to secure browser and response latency service.token.expires_at = expires_at; } else { service.token.expires_at = null; } }
[ "_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 }", "setAccessToken(token) {\n localStorage.setItem('accessToken', token);\n }", "async setRefreshToken (token) {\n this.client.auth.refresh_token = token\n }", "get realmAccessToken() {\n return this.realmUser.then(\n // refresh access_token\n // TODO: should optimally call only when the access_token is close to expiration?\n (user) => user.refreshCustomData().then(() => user.accessToken)\n );\n }", "function setAutoRefreshTimeout() {\n clearTimeout(autoRefreshTimeoutId);\n if (auth.autoRefresh && typeof auth.expires !== 'undefined') {\n autoRefreshTimeoutId = setTimeout(auth.refresh, auth.expires + 1000);\n }\n }", "function getExpirationDate () {\n\tvar date = new Date();\n\tdate.setTime(date.getTime() + (14 * 24 * 60 * 60 * 1000));\n\texpireDate = date.toUTCString();\n\treturn expireDate;\n}", "function setJwtCookie(jwt, response, minutesTilExpire) {\n response.state(_appConfig.settings.get('/JWT/COOKIE/NAME'), jwt, {\n ttl: minutesTilExpire * 60 * 1000, // In milliseconds\n path: _appConfig.settings.get('/JWT/COOKIE/PATH'),\n domain: _appConfig.settings.get('/JWT/COOKIE/DOMAIN')\n });\n}", "function expired() {\n return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date());\n }", "checkIdToken() {\r\n console.log('check Id token expiration')\r\n let user = this.user();\r\n if (user) {\r\n const expirationDateSecs = user.idTokenClaims.exp\r\n const expDate = new Date(expirationDateSecs * 1000)\r\n console.log('expDateSecs: '+expDate);\r\n\r\n if ((new Date()).getTime() >= expirationDateSecs * 1000) {\r\n console.log('IdToken expired. Clearing internal cache')\r\n this.clearLocal()\r\n return false \r\n } else {\r\n console.log('ID token is still valid')\r\n return true\r\n } \r\n } else {\r\n return false\r\n }\r\n }", "removeAccessToken() {\n localStorage.removeItem('accessToken');\n }", "setAccessToken(roomId, token){\n if(!this.isValidRoomId(roomId)){\n return null;\n }\n\n this.roomsUsed[roomId]['accessToken'] = token;\n }", "getAccessToken() {\n return new Promise((resolve, reject) => {\n if (this.isAccessTokenValid()) {\n resolve(this.accessToken);\n } else {\n this.renewTokens().then(authResult => {\n resolve(authResult.accessToken);\n }, reject);\n }\n });\n }", "function getTokenRefreshTimeout(token) {\n if (token) {\n var decoded = jwt.decode(token);\n\n // expiry date in future?\n if (decoded.exp && 1000 * decoded.exp > Date.now()) {\n // refresh once a day or halfway to expiry\n var timeout = Math.min(24 * 3.6e6, Math.ceil((1000 * decoded.exp - Date.now()) / 2));\n return timeout;\n }\n }\n\n // retry in 1s\n return 1000;\n }", "function setToken(account, callback) {\n\t// Check keys presence\n\tvar keys = account.keys;\n\tif (!keys.access_token) {\n\t\treturn false;\n\t}\n\n\t// Set token\n\tfacebook.setAccessToken(keys.access_token);\n\treturn true;\n}", "function updateAuthToken(state, body) {\n // Add Access Token to Auth Record\n var newAuthInfo = {\n access_token: body.access_token || '',\n token_type: body.token_type || '',\n token_expires: Math.round((new Date().getTime()) + ((body.expires_in || 3600) * 1000))\n };\n if (body.refresh_token) {\n newAuthInfo.refresh_token = body.refresh_token;\n }\n return db_1.DB.knex('spotify_auth').update(newAuthInfo).\n where('token_state_auth', state).catch(function (err) {\n console.log('Update Auth Token Error!', err);\n });\n}", "function setCookie(c_name, value) {\n var exdate = new Date();\n exdate.setDate(exdate.getDate() + 365);\n var c_value = escape(value) + \"; expires=\" + exdate.toUTCString();\n document.cookie = c_name + \"=\" + c_value;\n }", "setLastAccess(){\n this.lastAccess = Date.now();\n }", "changeCredentialsToRefreshCredentials({ refresh_token }) {\n this.credentials = OAuthRefreshCredentials.from(\n this.credentials.credentials.client_id,\n this.credentials.credentials.client_secret,\n refresh_token\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 finestra deve essere visualizzata o meno alla creazione | valore [true|false] $opt['isTip']> Indica se a finestra deve avere o meno la freccetta tips | valore [true|false] $opt['isPermanent']> Se impostato a true la finestra non viene chiusa ma solo nascosta | valore [true|false] $opt['width']> La larghezza della finestra | valore [numero] $opt['height']> L'altezza della finestra | valore [numero] $opt['top']> Posizionamento dall'alto | valore [numero] $opt['left']> Posizionamento dal sinistra | valore [numero] $opt['autoCloseTime']> Chiusura automatica onmouseout | valore [millisecondi]
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.visibility="hidden"; return; }; this.show= function(){ this.windows.style.visibility="visible"; return; }; this.centra= function(){ var MyWindowsHeight=this.windows.offsetHeight; var MyWindowsWidth=this.windows.offsetWidth; var browserHeight=getTop(document.getElementById('SpaceCalculator')); var browserWidth=getLeft(document.getElementById('SpaceCalculator')); var MyTop=(browserHeight-MyWindowsHeight)/2; var MyLeft=(browserWidth-MyWindowsWidth)/2; this.windows.style.top=MyTop; this.windows.style.left=MyLeft; return; }; this.fadeOut= function(){ this.windows.style.opacity=0.9; return; }; this.fadeIn=function($to, $time){ if($time){//se ho impostato un tempo calcolo quanti cicli servono var $numCicli=Math.round($time/$MyTimer) }else{//se non l'ho impostato allora vuole dire che voglio sia fatto subito var $numCicli=1; } var $step=$differenza/$numCicli; var $resta=$to-$step; for($ciclo=1;$ciclo<=$numCicli;$ciclo++){ // opacity = (opacity == 100)?99.999:h; // IE/Win //this.windows.style.filter = "alpha(opacity:"+h+")"; // Safari<1.2, Konqueror //this.windows.style.KHTMLOpacity = (this.windows.style.KHTMLOpacity+$step/100); // Older Mozilla and Firefox //this.windows.style.MozOpacity = (this.windows.style.MozOpacity+$step/100); // Safari 1.2, newer Firefox and Mozilla, CSS3 //this.windows.style.opacity = $step*$ciclo; //h=h-Conf['DecrementoOpacita']; //alert($ciclo+'->'+this.windows.style.opacity); } if(timerID!=''){ clearTimeout(timerID); } var timerID=setTimeout(this.fadeIn(),$MyTimer,$resta,$time-$MyTimer) return; }; var $id='MyWindowsID_'+$opt['name']; /*Definisco tutti i tag html che mi serviranno per costruire la mia finestrella*/ //contorno superore var MyTopSx= document.createElement("td"); MyTopSx.setAttribute("class","TopSx"); var MyTopDx= document.createElement("td"); MyTopDx.setAttribute("class","TopDx"); var MyBgTop= document.createElement("td"); MyBgTop.setAttribute("class","BgTop"); var MyTopTr=document.createElement("tr"); MyTopTr.appendChild(MyTopSx); MyTopTr.appendChild(MyBgTop); MyTopTr.appendChild(MyTopDx); //contorno testo var MyBgDx= document.createElement("td"); MyBgDx.setAttribute("class","BgDx"); var MyBgSx= document.createElement("td"); MyBgSx.setAttribute("class","BgSx"); var MyBgMainContainer=document.createElement("div"); MyBgMainContainer.setAttribute("class","main"); MyBgMainContainer.innerHTML=$opt['txt']; //Eventuale barra del tittolo if($opt['title']!=null){ var MyTitle=document.createElement("div"); MyTitle.setAttribute("class","TitleBarTxt"); MyTitle.innerHTML=$opt['title']; var MyCloseButtonImage=document.createElement("img"); MyCloseButtonImage.setAttribute("src","./../oLibs/MyWindow/img/chiudi.png"); MyCloseButtonImage.setAttribute("alt","X"); var MyCloseButtonLink=document.createElement("a"); MyCloseButtonLink.appendChild(MyCloseButtonImage); if($opt['isPermanent']==true){ MyCloseButtonLink.onclick=function(){ _self.hide(); } }else{ MyCloseButtonLink.onclick=function(){ _self.chiudi(); } } var MyCloseButton=document.createElement("div"); MyCloseButton.appendChild(MyCloseButtonLink); MyCloseButton.setAttribute("class","closeButton"); var MyTitleBar=document.createElement("div"); MyTitleBar.setAttribute("class","TitleBar"); MyTitleBar.appendChild(MyTitle); MyTitleBar.appendChild(MyCloseButton); } //fine barra del titolo continuo con la finestrella var MyBgMain= document.createElement("td"); MyBgMain.setAttribute("class","mainBG"); if($opt['title']){ //se ho creato la barra del titolo la mostro MyBgMain.appendChild(MyTitleBar); } MyBgMain.appendChild(MyBgMainContainer); var MyBgTr=document.createElement("tr"); MyBgTr.appendChild(MyBgSx); MyBgTr.appendChild(MyBgMain); MyBgTr.appendChild(MyBgDx); //contorno inferiore var MyBottomSx= document.createElement("td"); MyBottomSx.setAttribute("class","BottomSx"); var MyBottomDx= document.createElement("td"); MyBottomDx.setAttribute("class","BottomDx"); var MyBgBottom= document.createElement("td"); MyBgBottom.setAttribute("class","BgBottom "); var MyBottomTr=document.createElement("tr"); MyBottomTr.appendChild(MyBottomSx); MyBottomTr.appendChild(MyBgBottom); MyBottomTr.appendChild(MyBottomDx); //Tabella var MyTable=document.createElement("table"); MyTable.setAttribute("class","MyTable"); MyTable.setAttribute("cellspacing","0px"); MyTable.appendChild(MyTopTr); MyTable.appendChild(MyBgTr); MyTable.appendChild(MyBottomTr); MyTable.style.zIndex=$zindex; if($opt['width']){ MyTable.width=$opt['width']+'px'; } if($opt['height']){ MyTable.height=$opt['height']+'px'; MyTable.style.maxheight=$opt['height']+'px'; } //La aggiungo al body tenendola nascosta MyTable.style.visibility='hidden'; MyTable.style.top=0;//imposto a zero per evitare sfarfallamenti con la barra di scorrimento su firefox MyTable.style.left=0;//idem come sopra document.body.appendChild(MyTable); //posiziono la finestrella al centro del browser var MyWindowsHeight=MyTable.offsetHeight; var MyWindowsWidth=MyTable.offsetWidth; //se mi sono passato qualche parametro per il posizionamento mi ricavo i dati if($opt['position']){ switch ($opt['position']){ case 'top-left': $opt['top']=getTop($opt['this']); $opt['left']=getLeft($opt['this']); break; case 'top-right': $opt['top']=getTop($opt['this']); $opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth; break; case 'bottom-left': $opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight; $opt['left']=getLeft($opt['this']); break; case 'bottom-right': $opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight; $opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth; break; default: $opt['top']=getTop($opt['this']); $opt['left']=getLeft($opt['this']); break; } } if(isNaN($opt['top']) || isNaN($opt['left'])){ var browserHeight=getTop(document.getElementById('SpaceCalculator')); var browserWidth=getLeft(document.getElementById('SpaceCalculator')); var MyTop=(browserHeight-MyWindowsHeight)/2; var MyLeft=(browserWidth-MyWindowsWidth)/2; }else{ var MyTop=$opt['top']-MyWindowsHeight; var MyLeft=$opt['left']; } /*---------------------------------------------------------------------------*/ if($opt['isTip']){//se si tratta di un tips //MyTop-=18; //Altezza //MyLeft+=54;//larghezza } MyTable.style.top=MyTop+'px'; MyTable.style.left=MyLeft+'px'; //finito di posizionarla posso finalmente mostrarla if($opt['isVisible']!=false){ MyTable.style.visibility='visible'; } if($opt['title']){//se c'è un titolo e quindi una barra del titolo allora probabilmente voglio che la finestra sia draggabile //aggiongo il drag and drop var theHandle = MyTitleBar; var theRoot = MyTable; Drag.init(theHandle, theRoot); } //---------------- this.windows=MyTable; if($opt['autoCloseTime']){ this.timer=''; //programmo già una chiusura se non vado sopra col mouse /* $opt['this'].onmouseout=function(){ this.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime']) } */ this.windows.onmouseout=function(){ //var _self=this; //if(this.timer==''){ //alert('test'); this.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime']) //} } this.windows.onmouseover=function(){ if(this.timer){ clearTimeout(this.timer); this.timer=''; } } return; }; return this; }
[ "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\nvar process=(cov_50nz68pmo.s[9]++,setInterval(function(){cov_50nz68pmo.f[5]++;// get clockBar instant\nlet itself=(cov_50nz68pmo.s[10]++,sendTosetInterval());// get current time\nvar now=(cov_50nz68pmo.s[11]++,new Date().getTime());// find the distance between now and the init time\nvar distance=(cov_50nz68pmo.s[12]++,now-initTime);cov_50nz68pmo.s[13]++;if(distance>limited){cov_50nz68pmo.b[2][0]++;cov_50nz68pmo.s[14]++;drawFluid('0%');cov_50nz68pmo.s[15]++;clearInterval(process);cov_50nz68pmo.s[16]++;itself.setTimeout('true');}else{cov_50nz68pmo.b[2][1]++;}// set percentage of time cooldown\ncov_50nz68pmo.s[17]++;fracTime=Math.round(100-distance/limited*100);// draw percentage to page\ncov_50nz68pmo.s[18]++;drawFluid(fracTime+'%');},timeUpdate));}", "function SlideWindow(name, url, p_wth, p_hgt, p_to) {\r\n\tthis.base = AbstractWindow;\r\n\tthis.base(url, 0, 0, p_wth, 1);\r\n\t/* Atributes */\r\n\tthis.name = name;\r\n\tthis.timeOut = p_to * 1000 || 15000; //TimeOut\r\n\tthis.yoEnd; //Ending move coordinate\r\n\tthis.xoEnd; //Ending move coordinate\r\n\tthis.process = -1; //Generic process\r\n\t\r\n\tthis.createContent = \tfunction() {\r\n\t\t\t\t\t\t\t\tvar ifrm = document.createElement(\"iframe\");\r\n\t\t\t\t\t\t\t\tifrm.className= this.classShow;\r\n\t\t\t\t\t\t\t\tifrm.setAttribute(\"class\", this.classShow);\r\n\t\t\t\t\t\t\t\tifrm.height = this.hgt;\r\n\t\t\t\t\t\t\t\tifrm.src = this.url;\r\n\t\t\t\t\t\t\t\tifrm.style.scrolling = \"auto\";\r\n\t\t\t\t\t\t\t\treturn ifrm;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\tthis.ultimoElementoActivo = function() {\r\n\t\t\t\t\t\t\t\t\tvar index = slideRegister.length - 1;\r\n\t\t\t\t\t\t\t\t\twhile ((index >= 0) && (slideRegister[index] == undefined)) index--;\r\n\t\t\t\t\t\t\t\t\tvar ret = (slideRegister[index])? slideRegister[index] : undefined;\r\n\t\t\t\t\t\t\t\t\t//Si se acumularon muchas ventanas cerradas y no hay ninguna activa, reinicio el registro.\r\n\t\t\t\t\t\t\t\t\tif ((!ret) && (slideRegister.length > 50)) slideRegister = Array();\r\n\t\t\t\t\t\t\t\t\treturn ret;\r\n\t\t\t\t\t\t\t\t}\r\n\t/* Determina Xo e Yo */\r\n\t//Asume que es la primera ventana.\r\n\tthis.xo = this.determineWidth() - this.wth - 5;\r\n\tthis.yo = this.determineHeight() - 5;\r\n\t//Se posiciona basandose en el slide anterior.\r\n\tvar elem = this.ultimoElementoActivo();\r\n\tif (elem != undefined) {\r\n\t\t//Se supone que la nueva ventana va a estar encima de la ultima mostrada.\r\n\t\tvar xoAux = this.xo;\r\n\t\tthis.xo = elem.xo;\r\n\t\t//Se calcula hasta donde llega, si se sale de la pantalla, lo mueve al costado.\r\n\t\tvar yoAux = elem.yoEnd;\r\n\t\tif ((yoAux - p_hgt) < 0)\r\n\t\t\t//Se va de pantalla.\t\r\n\t\t\tthis.xo = this.xo - this.wth - 5;\r\n\t\telse\r\n\t\t\t//No se va de pantalla.\r\n\t\t\tthis.yo = elem.yoEnd;\r\n\t}\r\n\t/* Determina la posicion final */\r\n\tthis.yoEnd = this.yo - p_hgt - 5;\r\n\tthis.xoEnd = this.xo;\r\n\t/* Se setean los estilos */\r\n\tthis.classShow = \"iwinSlideWindow\";\r\n\t/* Muestra la ventana */\r\n\tthis.show();\r\n\t/* Registra la ventana */\r\n\tslideRegister.push(this); \r\n\tslideNameRegister[this.name] = this;\r\n\t/* Mueve la ventana */\r\n\tiwinMoveIt(slideRegister.length - 1);\r\n\treturn this;\r\n}", "function AbstractWindow(url, p_xo, p_yo, p_wth, p_hgt) {\r\n /* Clase para mostrar la ventana*/\r\n\tthis.classHide = \"iwinContainerHide\";\r\n\t/* Clase para ocultar la ventana*/\r\n\tthis.classShow = \"iwinContainer\";\t\r\n\t/* Atributos */\r\n this.xo = p_xo || 0;\r\n this.yo = p_yo || 0;\r\n this.wth = p_wth || 100;\r\n this.hgt = p_hgt || 100;\r\n this.url = url;\r\n this.created = false;\r\n this.visible = false;\r\n /*HTML Atributes */\r\n this.element = null;\r\n /* Methods */\r\n\t/* This function shows de basedow */\r\n\tthis.show = function() {\r\n\t\t\t\t\t\tthis.show_prev();\r\n\t\t\t\t\t\t/* Se crea la ventana */\r\n\t\t\t\t\t\tthis.element = document.createElement(\"div\");\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.element.appendChild(this.createContent());\r\n\t\t\t\t\t\t/* Se agrega la ventana al cuerpo de la pagina */\r\n\t\t\t\t\t\tdocument.body.appendChild(this.element);\r\n\t\t\t\t\t\tthis.element.className = this.classShow;\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.locateWindow(this.xo, this.yo, this.wth, this.hgt);\r\n\t\t\t\t\t\tthis.visible = true;\r\n\t\t\t\t\t\tthis.show_next();\r\n\t\t\t\t}\r\n\t\r\n /* This function Hides the basedow */\r\n\tthis.hide =\tfunction() {\t\t\r\n\t\t\t\t\tvar ret = true;\r\n\t\t\t\t\tif (this.onHideStart) eval(this.onHideStart);\r\n\t\t\t\t\tif (ret) {\r\n\t\t\t\t\t\tthis.hide_prev();\r\n\t\t\t\t\t\tthis.element.className = this.classHide;\r\n\t\t\t\t\t\tthis.visible = false;\r\n\t\t\t\t\t\tthis.hide_next();\r\n\t\t\t\t\t\tif (this.onHideEnd) eval(this.onHideEnd);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\tthis.locateWindow =\tfunction (x, y, w, h) {\r\n\t\t\t\t\t\t\t\tthis.wth=w;\r\n\t\t\t\t\t\t\t\tthis.hgt=h;\r\n\t\t\t\t\t\t\t\tthis.xo=x;\r\n\t\t\t\t\t\t\t\tthis.yo=y;\r\n\t\t\t\t\t\t\t\tthis.element.style.left = x + 'px' ;\r\n\t\t\t\t\t\t\t\tthis.element.style.top = y + 'px';\t\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineWidth = \tfunction() {\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar w = window.innerWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.documentElement.clientWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.body.clientWidth;\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\treturn w;\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineHeight =\tfunction() {\r\n\t\t\t\t\t\t\t\tvar h = window.innerHeight\r\n\t\t\t\t\t\t\t\t\t|| document.documentElement.clientHeight\r\n\t\t\t\t\t\t\t\t\t|| document.body.clientHeight; \r\n\t\t\t\t\t\t\t\treturn h;\r\n\t\t\t\t\t\t\t}\r\n\t/****\r\n\t** Metodos a definir en una clase hijo\r\n\t*****/\r\n\t/* Funcion que genera el contenido de la ventana, debe ser redefinida por las clases herederas para cambiar su funcionamiento \r\n\t* @Abstract\r\n\t*/\r\n\tthis.createContent = \tfunction() { alert(\"Debe redefinir el metodo 'createContent'\");\t}\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion show*/\t\t\t\r\n\tthis.show_prev = function() {}\r\n\tthis.show_next = function() {}\t\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion hide */\t\t\t\r\n\tthis.hide_prev = function() {}\r\n\tthis.hide_next = function() {}\t\r\n\t/**\r\n\t * Eventos que el usuario puede definir para obtener control de la ventana\r\n\t * Si devuelven false, susupende la ejecución del evento. \r\n\t */\r\n\tthis.onHideStart = undefined;\t//Antes de Cerrar (Debe devolver true/false).\r\n\tthis.onHideEnd = undefined;\t//Despues de Cerrar\r\n}", "function timerJuego() {\n // Genera el letrero del timer\n mensajeTimer = pad(minutos) + \":\" + pad(segundos);\n // Muestra el timer en la página\n $(\"#labelTimer\").text(mensajeTimer);\n // Verifica si se debe pasar el siguiente minuto\n if (segundos == 59) {\n segundos = -1;\n minutos++;\n }\n // Incrementa los segundos\n segundos++;\n }", "function OnMessageTimeOut(id) {\n\n\tif (id == DVDMSGTIMER) {\n\t\tMessage.Text = \"\";\n\t\tMessageFull.Text = \"\";\n if (g_LTRReading)\n {\n xCoord = TitleFull.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - TitleFull.TextWidth - MessageFull.TextWidth - g_nButPosFull[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1] - 1000;\n\n\t\tMFBar.SetObjectPosition(\"MessageFull\", xCoord, yCoord,\n\t\t\tMessageFull.TextWidth, g_nButPosFull[g_nIndexMessage][3]);\n\n if (g_LTRReading)\n {\n xCoord = Title.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - Title.TextWidth - Message.TextWidth - g_nButPos[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1];\n\n\t\tMFBar.SetObjectPosition(\"Message\", xCoord, yCoord,\n\t\t\tMessage.TextWidth, g_nButPos[g_nIndexMessage][3]);\n\t}\n\n\telse if (id == FOCUSTIMER) {\n\t\tif (MFBar.ObjectEnabled(g_strFocusObj)) {\n\t\t\tbtn = MFBar.GetObjectUnknown(g_strFocusObj);\n\t\t\tif (!btn.Disable)\n\t\t\t\tMFBar.SetObjectFocus(g_strFocusObj, true);\n\t\t}\n\t\telse {\n\t\t}\n\t}\n}", "function drawControl_grow(header_ypos)\r\n{\r\n // now draw the feedback panel with an appropriate sized gap\r\n header_ypos += (button_gap*3);\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (24.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'center';\r\n // draw title\r\n \r\n \r\n if (timelim > 0 )\r\n {\r\n if (timelim >10)\r\n {\r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText((Math.round(timelim*10)/10.0).toString() , 185, header_ypos);\r\n drawclock(80,header_ypos,20,1-(timelim/original_timelim),'rgb(0,0,0)',Hcontext);\r\n\r\n header_ypos += 45;\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n }\r\n else\r\n {\r\n // if (timelim >1)\r\n // {\r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText((Math.round(timelim*100)/100.0).toString() , 185, header_ypos);\r\n drawclock(80,header_ypos,20,1-(timelim/original_timelim),'rgb(0,0,0)',Hcontext);\r\n\r\n header_ypos += 45;\r\n\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n // }\r\n }\r\n header_ypos += 30;\r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText( gpmapper(timelim) + ' period', 147, header_ypos);\r\n \r\n \r\n }\r\n else\r\n {\r\n //header_ypos += 25;\r\n //Hcontext.font = (30.0).toString() + 'px '+fonttype;\r\n //Hcontext.fillText('Present day' , 147, header_ypos);\r\n //header_ypos += 50;\r\n \r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('0' , 147, header_ypos);\r\n \r\n header_ypos += 45;\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n \r\n header_ypos += 30;\r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText( 'Present day', 147, header_ypos);\r\n \r\n }\r\n \r\n header_ypos += 30;\r\n \r\n // growth control buttons\r\n control_button(\"Reverse\",header_ypos,\"growrev\",null,(!growing)||growingdir);\r\n draw_reverse_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"Pause\",header_ypos,\"growpause\",null,!growingpause);\r\n draw_pause_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"Play\",header_ypos,\"growplay\",null,(!growing)||(!growingdir));\r\n draw_play_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"End\",header_ypos,\"growend\",null,(growing)||((growingpause)||(timelim >= 0)));\r\n draw_stop_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n // reset button\r\n control_button(\"Reset tree view\",header_ypos,\"viewReset\",null,true);\r\n header_ypos += (button_gap+button_height);\r\n\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (18.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'left';\r\n // draw title\r\n\r\n \r\n temp_txt = [\" \",\r\n \"This function shows you an\",\r\n \"animation of the tree growing\",\r\n \"over time. The tree doesn't\",\r\n \"show extinct species, other than\",\r\n \"those where extinction has\",\r\n \"occured very recently. You can\",\r\n \"still explore the tree in the\",\r\n \"usual way during this animation.\",\" \",\r\n \"Touch the screen with two\",\r\n \"fingers and pinch to zoom in or\",\r\n \"out. You can also tap any of\",\r\n \"the circular images to zoom in\",\r\n \"to that area of the tree.\"];\r\n skipper = 22\r\n \r\n for (var iii = 0 ; iii < temp_txt.length ; iii ++)\r\n {\r\n Hcontext.fillText (temp_txt[iii] , control_margin, header_ypos+skipper*iii);\r\n }\r\n \r\n \r\n \r\n}", "function drawNewTimer(id){\n let newDiv = document.createElement(\"div\");\n newDiv.id = id;\n newDiv.className = \"child\";\n\n let startbutton = document.createElement(\"input\");\n startbutton.type=\"button\";\n startbutton.value=\"Start / Reset\";\n startbutton.id= id;\n startbutton.addEventListener(\"click\", function() {startWatch(id)}, false);\n\n let pausebutton = document.createElement(\"input\");\n pausebutton.type=\"button\";\n pausebutton.value=\"Pause\";\n pausebutton.id= id;\n pausebutton.addEventListener(\"click\", function() {pauseTimer(id)}, false);\n\n let resumebutton = document.createElement(\"input\");\n resumebutton.type=\"button\";\n resumebutton.value=\"Resume\";\n resumebutton.id= id;\n resumebutton.addEventListener(\"click\", function() {resumeTimer(id)}, false);\n\n let deletebutton = document.createElement(\"input\");\n deletebutton.type=\"button\";\n deletebutton.value=\"Delete\";\n deletebutton.id= id;\n deletebutton.addEventListener(\"click\", function() {deleteTimer(id)}, false);\n\n let timeDisplay = document.createElement(\"h1\");\n timeDisplay.id=id+\"h1\";\n timeDisplay.innerHTML = id;\n\n //Add all new items to the previous div tag\n newDiv.appendChild(timeDisplay);\n newDiv.appendChild(startbutton);\n newDiv.appendChild(pausebutton);\n newDiv.appendChild(resumebutton);\n newDiv.appendChild(deletebutton);\n \n //insert all into the page\n let currentDiv = document.getElementById(\"original\");\n document.getElementById(\"wrapper\").insertBefore(newDiv, currentDiv);\n\n //Create Timer Object\n collection.timer.push(new stopWatch(id));\n}", "function newTimer(formulario) {\r\n\t// se formulario for nulo, não faz nada\r\n\tif (formulario == undefined || formulario == null) {\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tvar intervalo = 30 * 1000; // 30 sec\r\n\t\r\n\t// cria timer\r\n\tvar ret = setTimeout(\"autosaveForm('\"+formulario+\"')\", intervalo);\r\n\t\r\n\t// retorna\r\n\treturn ret;\r\n}", "function definePsycho(){\r\n\t\t\r\n\t var PsychoPara = {};\r\n PsychoPara.condition = function(condition){\r\n\t\r\n\tif(condition.transition == true){\r\n\t\tPsychoPara.transition();\r\n\t}else{console.log(\"Wrong use of parameter : transition, or set to false.\")}\r\n\r\n\tif(condition.color == true){\r\n\t\tif(condition.interval){\r\n\t\t\tsetInterval(PsychoPara.color, condition.interval);\r\n\t\t}else{\r\n\t\t\t//if not set by USER give default value of 3000.\r\n\t\t\tsetInterval(PsychoPara.color, 3000);\r\n\t\t}\r\n\t}else{console.log(\"Wrong use of parameter : color, or set to false.\")}\r\n\r\n\tif(condition.spacing == true){\r\n\t\tif(condition.interval){\r\n\t\t\t//Use interval set by user.\r\n\t\t\tsetInterval(PsychoPara.spacing, condition.interval);\r\n\t\t}else{\r\n\t\t\t//if not set by USER give default value of 3000.\r\n\t\t\tsetInterval(PsychoPara.spacing, 3000);\r\n\t\t}\r\n\t}else{console.log(\"Wrong use of parameter : spacing, or set to false.\")}\r\n\t}\r\n\r\n\t\r\n\t\tPsychoPara.color = function () {\r\n\t\t\tdocument.getElementById(\"Psycho\").style.color = getRandomColor();\r\n\t\t};\r\n\t\tPsychoPara.spacing = function (){\r\n\t\t\tdocument.getElementById(\"Psycho\").style.letterSpacing = getRandomSpacing();\r\n\t\t};\r\n\t\tPsychoPara.transition = function (){\r\n\t\t\tdocument.getElementById(\"Psycho\").style.transition = \"all 1s\";\r\n\t\t};\r\n\t\t\r\n\r\n\t\treturn PsychoPara;\r\n\t}", "function createTimerDisplay() {\n var timerDisplay = document.createElement('div');\n timerDisplay.setAttribute('id','theTimer');\n timerDisplay.style.color = 'red';\n timerDisplay.style.fontSize = '30px';\n timerDisplay.style.paddingTop = '15px';\n timerDisplay.style.fontWeight = 'bolder';\n return timerDisplay;\n}", "function popUpCorretorStart() {\n var popUpExibida = $( '#hfSessao' ).val();\n \n if( ( popUpExibida == \"False\" || popUpExibida == \"0\" ) && timerPopUp === null ) {\n \n timerPopUp = setTimeout( function(e) {\n popUpCorretorOpen();\n }, timeToOpen );\n\n }\n\n }", "function createWindow() {\n\n windowPanel = $(\"<div></div>\"); //Sliding Window\n windowPanel.addClass(\"swindow\");\n var sfSlot = sfSlots[windowSb];\n var width = sfSlot.outerWidth() * windowSize + windowSize * 10 + 2;\n windowPanel.css(\"width\", width);\n windowPanel.css({\n top: sfSlot.position().top - 10,\n left: sfSlot.position().left,\n position: \"absolute\"\n });\n $(\"#medium\").append(windowPanel);\n}", "function f_mensajeProceso(p_titulo,p_mensaje,ptipo_mensaje) {\n \n Swal.fire({\n title: \"\"+p_titulo,\n text: \"\"+p_mensaje,\n icon: \"\"+ptipo_mensaje,\n showCancelButton: true,\n cancelButtonText: 'Cerrar',\n showClass: {\n popup: 'animated fadeInDown faster'\n },\n hideClass: {\n popup: 'animated fadeOutUp faster'\n },\n timer: 5000\n });\n }", "function gameWin( )\n {\n //==Open You Win modal box=================================================================================\n modal.style.display = \"block\";\n\n //==Display the final time, moves, and star rating=========================================================\n if( secondsTimer < 10 )\n {\n finalTime.textContent = minutesTimer + \":0\" + secondsTimer;\n }\n else\n {\n finalTime.textContent = minutesTimer + \":\" + secondsTimer;\n }\n\n finalMoves.textContent = moveCounter;\n finalStars.textContent = starCount;\n }", "function cronometro() {\n var mili = 0;\n var seconds = 0;\n var minutes = 0;\n\n stopWatch = setInterval(function () {\n mili++;\n document.getElementById(\"milisegundos\").innerHTML = mili;\n if (mili == 60) {\n mili = 0;\n seconds++;\n document.getElementById(\"segundos\").innerHTML = seconds + \":\";\n }\n\n if (seconds == 60) {\n minutes++;\n seconds = 0;\n document.getElementById(\"minutos\").innerHTML = minutes + \":\";\n }\n }, 10);\n\n}", "onSpawnFruitTimer() {\n }", "updateTimeWindow(timeWindow){\n var oldWindow = this.timeWindow ;\n this.scaleTimeWindow.setUniform('oldWindow',oldWindow ) ;\n this.scaleTimeWindow.setUniform('newWindow',timeWindow ) ;\n this.timeWindow = timeWindow ;\n this.scaleTimeWindow.render() ;\n this.wA2b.render() ;\n this.hist.setUniform('shift',0) ;\n this.hist.render() ;\n this.wA2b.render() ;\n this.render() ;\n return ;\n }", "function fastupdateGodTimer(){\r\n\t\r\n\t//Check if round is ongoing\r\n\tif(godtimer_in_seconds > 0){\r\n\t\tgodtimer_in_seconds = godtimer_in_seconds - 0.2;\r\n\t\t////console.log(godtimer_in_seconds);\r\n\t\tgod_numhours = Math.floor(godtimer_in_seconds / 3600);\r\n\t\tgod_numminutes = Math.floor((godtimer_in_seconds % 3600) / 60);\r\n\t\tgod_numseconds = parseFloat((godtimer_in_seconds % 3600) % 60).toFixed(0);\r\n\t\t\r\n\t\ta_godTimer = god_numhours + \"h \" + god_numminutes + \"m \" + god_numseconds + \"s \";\r\n\t\tgodtimerdoc.textContent = a_godTimer;\r\n\t}\r\n}", "function afficherProgressBar() {\r\n \r\n var counter = 0;\r\n var counterPercent = 0;\r\n var progress = 0;\r\n var id = setInterval(frame ,50)\r\n\r\n function frame(){\r\n if(counter == 47) {\r\n oPercentMax.style.display = \"block\";\r\n clearInterval(id);\r\n oPercentTotal.style.display = \"none\";\r\n \r\n setTimeout(() => { \r\n oPage.style.animation = \"fadeout 1.5s\";\r\n \r\n setTimeout(() => { \r\n oPage.style.display = \"none\";\r\n oPagePrincipal.style.animation = \"fadein 1.5s\";\r\n oPagePrincipal.style.display = \"block\";\r\n }, 1000);\r\n }, 800);\r\n } \r\n else {\r\n if(counter < 47) {\r\n counter += 1;\r\n } \r\n counterPercent += 2.12;\r\n progress += 2.13;\r\n oSmallPercent.style.display = \"flex\";\r\n oPercentLeft.style.paddingLeft = counter + \"%\";\r\n oPercentLeft.innerHTML = Math.floor(counterPercent) + \"%\";\r\n oPercentRight.style.paddingRight = counter + \"%\"; \r\n oPercentRight.innerHTML = Math.floor(counterPercent) + \"%\";\r\n oProgressBar[0].style.width = Math.floor(progress) + \"%\";\r\n oProgressBar[1].style.width = Math.floor(progress) + \"%\";\r\n }\r\n } \r\n}" ]
{ "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}", "function display_pet_page() {\n str = '';\n for (i = 0; i < products.length; i++) {\n str += `\n <section class=\"pups\">\n <h2>${products[i].color}</h2>\n <p>$${products[i].price}</p>\n <label id=\"quantity${i}_label\"}\">Quantity</label>\n <input type=\"text\" placeholder=\"# of Puppies\" name=\"quantity${i}\" \n onkeyup=\"checkQuantityTextbox(this);\">\n <img src=\"./images/${products[i].image}\">\n </section>\n `;\n }\n return str;\n }", "function trkDisplayAmount() {\n for(i = 0; i < trkFilteredProducts.length; i++) {\n trkFilteredProducts[i].style.display = \"none\";\n }\n if(trkSelectedPageValue == 1) {\n trkShowPageOne();\n } else if(trkSelectedPageValue == 2) {\n trkShowPageTwo();\n } else if(trkSelectedPageValue == 3) {\n trkShowPageThree();\n } else if(trkSelectedPageValue == 4) {\n trkShowPageFour();\n } else if(trkSelectedPageValue == 5) {\n trkShowPageFive();\n } else if(trkSelectedPageValue == 6) {\n trkShowPageSix();\n } else {\n console.log(\"Unknown page selection.\");\n }\n}", "function showProductsScreen() {\n\t//Show next page\n\tif($(\"#js-table\").attr(\"data-extractUrl\")){\n\t\t$(\"section.jsContainer #extractResults\").text(\"Extract Next Page\");\n\t\t$(\"section.jsContainer #extractResults\").fadeIn();\n\t}else{\n\t\t$(\"section.jsContainer #extractResults\").css(\"display\",\"none\");\n\t}\n\t\n\t$(\"section.jsContainer .main-screen\").css(\"display\",\"none\");\n\t$(\"section.jsContainer .export-section\").fadeIn();\n\t$(\"section.jsContainer #js-table\").fadeIn();\n}", "function photographersPage() {\n // RAZ of the tag's filters on logo's click\n const logo = document.getElementsByClassName(\"logo--photographer\")[0];\n logo.addEventListener(\"click\", function() {\n localStorage.removeItem(\"id\");\n }, true);\n // Redirect to home page, if there is no photographer's id in the local storage\n const id = localStorage.getStorage(\"id\");\n if (id === null) window.location.href = \"./index.html\";\n // Instanciate the pages renderer with the values\n const photographerPage = new PhotographersPage(getArraysJsonElement(photographers, \"id\", id)[0]);\n // Render the clickable tags list in the header\n photographerPage.renderPhotographerTags();\n // Render the header information\n photographerPage.renderHeaderInformation();\n // Render all the photographers's photos\n photographerPage.renderPhotographersCards(0);\n // Render the photographer's further information\n photographerPage.renderPhotographersFurtherInformations();\n // Prepare the contact modal\n photographerPage.initializeContactForm();\n // Prepare the photo modal\n photographerPage.initializePhotoLightboxModal();\n}", "function funderMode() {\n //If the URL contains the word 'capacity', use these CTAs\n if (window.location.pathname.match('capacity')) {\n document.getElementById(\"capacityOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"capacityTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n } \n //If the URL contains the word 'circular', use these CTAs\n else if (window.location.pathname.match('circular')) {\n document.getElementById(\"circularOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"circularTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n }\n //If the URL contains the word 'cities', use these CTAs\n else if (window.location.pathname.match('cities')) {\n document.getElementById(\"citiesOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"citiesTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n } \n //If the URL contains the word 'climate', use these CTAs\n else if (window.location.pathname.match('climate')) {\n document.getElementById(\"climateOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"climateTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n }\n //If the URL contains the word 'health', use these CTAs\n else if (window.location.pathname.match('health')) {\n document.getElementById(\"healthOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"healthTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n }\n //If the URL contains the word 'inclusive', use these CTAs\n else if (window.location.pathname.match('inclusive')) {\n document.getElementById(\"inclusiveOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"inclusiveTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n } \n //If the URL contains the word 'leadership', use these CTAs\n else if (window.location.pathname.match('leadership')) {\n document.getElementById(\"leadershipOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"leadershipTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n }\n //If the URL contains the word 'unprecedented', use these CTAs\n else if (window.location.pathname.match('unprecedented')) {\n document.getElementById(\"unprecedentedOne\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n document.getElementById(\"unprecedentedTwo\").innerHTML = '<div class=\"cta\">Funder mode on!</div>';\n }\n console.log(\"Funder mode on!\");\n }", "function displayView(view) {\n console.log(view);\n // hämta alla sidor/get all views\n const pageView = document.getElementById(\"page1\") \n const loginView = document.getElementById(\"logIn\") \n const varningView = document.getElementById(\"varning\") \n \n \n // dölj alla sidor/hide all views\n pageView.style.display = \"none\"\n loginView.style.display = \"none\"\n varningView.style.display = \"none\" \n \n\n // visa den specifika sidan/display specified view\n if (view === 'pageView') {\n pageView.style.display = \"block\"\n }\n \n if (view === 'loginView') {\n loginView.style.display = \"block\"\n }\n\n if (view === 'varningView') {\n varningView.style.display = \"block\"\n } \n \n}", "function renderPlanetProfile() {\n if (STORE.questionNumber === 0) {\n let output = `<h1>Solar System Quiz</h1>\n <p class=\"planet-profile js-planet-profile\">Journey through the Solar System with this short quiz and learn some cool facts along the way.</p>`;\n $('.js-quiz-intro-planet-profile').append(output);\n }\n else {\n for (let i = 0; i < STORE.planets.length; i++) {\n let planet = Object.keys(STORE.planets[i]).toString();\n for (let j = 0; j < STORE.planets[i][planet].length; j++) {\n let id = STORE.planets[i][planet][j].id;\n if (typeof (id) != 'undefined') {\n if (id === STORE.questionNumber) {\n STORE.currentPlanet = planet;\n let output = `<img class=\"planet-picture js-planet-picture\" src=\"images/${planet}.jpg\" alt=\"Image , picture of ${planet}\">\n <section><h1>${planet}</h1>\n <p class=\"planet-profile js-planet-profile\">\n <span class=\"planet-circumference js-planet-circumference\"><strong>Circumference:</strong> ${STORE.planets[i][planet][2].facts[0].circumference} </span><br />\n <span class=\"planet-distance js-planet-distance\"><strong>Distance from Sun (light minutes):</strong> ${STORE.planets[i][planet][2].facts[1].distance} </span><br />\n <span class=\"planet-type js-planet-type\"><strong>Planet Type:</strong> ${STORE.planets[i][planet][2].facts[2].type} </span><br />\n <span class=\"planet-temp js-planet-temp\"><strong>Daytime Temperature:</strong> ${STORE.planets[i][planet][2].facts[3].temp}</span>\n </p></section>`;\n $('.js-quiz-intro-planet-profile').empty();\n $('.js-quiz-intro-planet-profile').append(output);\n }\n }\n }\n }\n }\n}", "function showSingleListing(req, res) {\n // get a single listing\n Listing.findOne({ slug: req.params.slug }, (err, listing) => {\n if (err) {\n res.status(404);\n res.send('Listing not found!');\n }\n\n res.render('pages/single-listing', { \n listing: listing,\n success: req.flash('success')\n });\n });\n}", "function renderSingleProductPage (index, data) {\n var page = $('.single-product'),\n c = $('.single-product .preview-large');\n\n data.forEach(function (item) {\n if (parseInt(index, 10) === parseInt(item.id, 10)) {\n c.find('h3').text(item.title);\n c.find('img').attr('src', 'http://farm7.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_z.jpg');\n }\n });\n page.addClass('visible');\n }", "function showPage(list, page)\n{\n const startIndex = MAX_ITEMS_PER_PAGE * (page - 1); // index of first element.\n const endIndex = MAX_ITEMS_PER_PAGE * page - 1; // index of last element.\n\n for(let i=0; i<list.length; i++)\n {\n if (i>=startIndex && i<=endIndex) // item belongs to the page --> show it .\n list[i].style.display = ''; \n else // item doesn't belong to the page --> hide it.\n list[i].style.display = 'none'; \n } \n}", "function displayPage(pageNumber) {\n //First and last profiles on each page\n const startIndex = (pageNumber - 1) * profilesPerPage;\n const endIndex = startIndex + profilesPerPage;\n //Looping through array of all profiles to display suitable profiles\n for (let i = 0; i < totalProfiles.length; i++) {\n if (i >= startIndex && i < endIndex) {\n totalProfiles[i].style.display = '';\n } else {\n totalProfiles[i].style.display = 'none';\n }\n }\n}", "function renderMain(response) {\n\tBurger.getAllBurgers()\n\t\t.then((burgers) => {\n\t\t\tburgers = burgers.map( el => {\n\t\t\t\treturn {\n\t\t\t\t\tid: el.id,\n\t\t\t\t\tburger_name: el.name,\n\t\t\t\t\tdevoured: el.devoured\n\t\t\t\t};\n\t\t\t} )\n\t\t\t// render the page\n\t\t\tresponse.render(\"index\", { burgers: burgers });\n\t\t});\n}", "viewAnimals() {\n let speciesString = '';\n for (let i =0; i < this.animalSpecies.length; i++) {\n speciesString += i + ') ' + this.animalSpecies[i].name + '\\n';\n }\n let index = prompt(`${speciesString}` + '\\n' +\n '----------------------------------------' + '\\n' +\n 'Enter the index of the species you would like to view:');\n\n if (index > -1 && index < this.animalSpecies.length) {\n this.selectedSpecies = this.animalSpecies[index];\n let description = 'Viewing: ' + this.selectedSpecies.name + '\\n';\n let currentIndex = index\n \n for (let i = 0; i < this.selectedSpecies.pets.length; i++) {\n description += i + ') ' + this.selectedSpecies.pets[i].name \n + ' - ' + this.selectedSpecies.pets[i].breed\n + ' - ' + this.selectedSpecies.pets[i].sex\n + ' - age: ' + this.selectedSpecies.pets[i].age + '\\n';\n }\n let selection = this.showAdoptionMenuOptions(description);\n switch (selection) {\n case '1':\n this.adoptPet(currentIndex);\n break;\n }\n }\n }", "function getPage() {\n\tvar sPath = window.location.pathname;\n\tvar sPage = sPath.substring(sPath.lastIndexOf('/') + 1);\n\tif (sPage == \"scheduled.jsf\") {\n\t\tdocument.getElementById(\"scheduledLink\").setAttribute(\"class\",\"active\");\n\t} else if (sPage == \"reports.jsf\") {\n\t\tdocument.getElementById(\"reportsLink\").setAttribute(\"class\",\"active\");\n\t} else {\n\t\tdocument.getElementById(\"homeLink\").setAttribute(\"class\",\"active\");\n\t}\n }", "function toRatingsPage() {\r\n id(\"result-view\").classList.add(\"hidden\");\r\n id(\"rate-view\").classList.remove(\"hidden\");\r\n id(\"rating\").addEventListener(\"change\", rateEgg);\r\n }", "function render (url) {\n $('.main-content .page').removeClass('visible');\n var section = url.split('/')[0],\n mapping = {\n '': function () {\n filters = {};\n checkboxes.prop('checked',false);\n renderProductsPage(products);\n },\n '#product': function () {\n var index = url.split('#product/')[1].trim();\n\n renderSingleProductPage(index, products);\n },\n '#filters': function () {\n try {\n filters = JSON.parse(url.split('#filters/')[1]);\n }\n catch (err) {\n window.location.hash = \"#\";\n return;\n }\n renderFilterResults(filters, products);\n }\n };\n if (mapping[section]) {\n mapping[section]();\n } else {\n renderError();\n }\n }", "function showLunch() {\n if (this.id == \"today\") {\n content.style.display = \"none\";\n } else if (content.style.display == \"block\" && content.classList.contains(this.id)\n ) {\n content.style.display = \"none\";\n content.className = \"\";\n } else {\n content.classList = this.id;\n if (this.id == \"veg\") {\n content.textContent = menuList[0];\n } else if (this.id == \"met\") {\n content.textContent = menuList[1];\n } else if (this.id == \"soup\") {\n content.textContent = menuList[2];\n } else if (this.id == \"dess\") {\n content.textContent = menuList[3];\n } else if (content.style.display == \"block\") {\n content.style.display = \"none\";\n }\n content.style.display = \"block\";\n }\n}", "function pageContentRouter(){\n if (window.location.hash === \"#concerts\"){\n pageContentConcerts();\n } else if (window.location.hash === \"#carpools\"){\n pageContentCarpools();\n } else if (window.location.hash === \"#flights\"){\n pageContentFlights();\n } else {\n window.location.hash = \"#home\";\n pageContentHome();\n };\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, prefix) {\n\treturn word.startsWith(prefix.slice(0, -1));\n}", "function isPrefix(sub,str) {\n return str.lastIndexOf(sub,0)===0;\n}", "function isPrefix(trie, word){ \n for(let temp_word of trie){\n if( temp_word.substr(0, word.length) == word){\n return true;\n }\n }\n return false; \n}", "function starts_with_java(str){\n\tconst i = str.indexOf(\"Java\");\n\tif (i == 0) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function starts_with(s, pre) /* (s : string, pre : string) -> maybe<sslice> */ {\n if ((s.substr(0,pre.length) === pre)) {\n return Just(Sslice(s, pre.length, (((s.length) - (pre.length))|0)));\n }\n else {\n return Nothing;\n }\n}", "search(word) {\n let root = this.root \n while (word.length > 0) {\n let char = ward[0]\n if (root[char]) {\n word = word.substr(1)\n root = root[char]\n } else {\n return false;\n }\n }\n\n // Returns if there is any word in the trie that starts with the given prefix\n //startsWith(prefix) {}\n}", "function createStartsWithFilter(startsWith) {\n // YOUR CODE BELOW HERE //\n // I = string character\n // O = function that returns Boolean\n // if else conditional to see if first letter of string === startsWith arg\n // find value of first letter of newString using charAt() method\n // use .toLowerCase string method on both arguments so that strict equality gives desired result\n return function(newString) {\n if (newString.charAt(0).toLowerCase() === startsWith.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n \n }\n \n // YOUR CODE ABOVE HERE //\n}", "constructor (phrase) {\r\n this.phrase = phrase.toLowerCase();\r\n }", "function latinWordStartCheck(contextParams) {\n\t var char = contextParams.current;\n\t var prevChar = contextParams.get(-1);\n\t return (\n\t // ? latin first char\n\t (prevChar === null && isLatinChar(char)) ||\n\t // ? latin char preceded with a non latin char\n\t (!isLatinChar(prevChar) && isLatinChar(char))\n\t );\n\t}", "function InStr(start, srchStr, fndStr, cmp) {\n if (!fndStr || fndStr==null || fndStr==\"\") {\n\t\tfndStr += \"\";\n if (fndStr.length == 0) {\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n start=Math.floor(start);\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (start > srchStr.toString().length) { return 0; }\n return start;\n }\n\t\tcmp=0;\n fndStr=srchStr;\n srchStr=start;\n start=1;\n }\n\tif (!isNumeric(Math.floor(start))) {\n cmp=fndStr;\n\t\tfndStr=srchStr;\n srchStr=start;\n start=1;\n\t}\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (!fndStr || fndStr==null) { fndStr=''; }\n start=Math.floor(start);\n\n if (srchStr == \"\") { return 0; }\n var osrchStr=srchStr.toString();\n if (start > osrchStr.length) { return 0; }\n if (fndStr == \"\") { return start; }\n\n srchStr=osrchStr;\n fndStr=fndStr.toString();\n if (start>1) { srchStr=srchStr.substr(start-1); }\n\tcmp = cmp + \"\";\n\tvar loc=0;\n\tif (cmp=='1') { //insensitive\n\t\tvar osrchStr=srchStr.toLowerCase();\n\t\tvar ofndStr=fndStr.toLowerCase();\n\t\tif (osrchStr.indexOf(ofndStr) == -1) { return 0; }\n\t\tloc=osrchStr.indexOf(ofndStr)+1+(start-1);\n\t} else {\n\t\tif (srchStr.indexOf(fndStr) == -1) { return 0; }\n\t\tloc=srchStr.indexOf(fndStr)+1+(start-1);\n\t}\n return loc;\n}", "function startend(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.startsWith(\"saya\"));\n\tconsole.log(aku.endsWith(\"di\"));\n\t}", "function matchBeginningStringPattern(string, target) {\n // This will find target only in the beginning of the string.\n let regex = new RegExp(\"^\" + target);\n return string.match(regex);\n}", "function include(){\n\tvar aku = ' saya belajar di pasar ';\n\tconsole.log(aku.includes(\"belajar\"));\n\tconsole.log(aku.includes(\"sa\"));\n\t}", "function strngFunction (string) {\n if (string.slice(-1).toLowerCase() === endsWith.toLowerCase()){\n return true; \n } else {\n return false;\n }\n }", "function checkPattern(aLength, bLength, pattern, string, startsWith){\r\n var aString = string.substring(0, aLength)\r\n var bString;\r\n var startAt = aLength\r\n\r\n //find bString\r\n for(var i = 1; i < pattern.length; i++) {\r\n if(pattern[i] === startsWith)\r\n startAt += aLength\r\n bString = string.substring(startAt, startAt + bLength)\r\n break;\r\n }\r\n\r\n if(aString === bString)\r\n return false\r\n\r\n var testString = []\r\n pattern.split('').forEach(letter => {\r\n letter === startsWith ? testString.push(aString) : testString.push(bString)\r\n })\r\n\r\n return testString.join('') === string\r\n}", "function twoStrings(s1, s2) {\n // O(n*n) still due to using include. Could be more optimized if I checked for smaller string to iterate through\n let arr1 = s1.split(\"\");\n for (let i = 0; i < arr1.length; i++) {\n if (s2.includes(arr1[i])) {\n return \"YES\";\n }\n }\n return \"NO\";\n}", "function mutation([first, second]) {\n return second.toLowerCase()\n .split('')\n .every(letter => first.toLowerCase()\n .indexOf(letter) !== -1)\n}", "function startsWithUppercase(str) {\n return /^[A-Z]/.test(str);\n}" ]
{ "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_indices = _.map(lists, function(arr) { return arr.length })\n var aggregate_reverse_index = _.reduce(reverse_indices, function(sum, len) {\n return sum + len \n }, 0)\n\n while ( aggregate_reverse_index > 0 ) {\n var pull_arr_index = null, pull_val = null\n\n for (var i = 0; i < lists.length; i++) {\n if (reverse_indices[i] == 0) {\n // Reached the end of this list.\n continue;\n } else if ( pull_arr_index != null && dup_fn &&\n dup_fn(lists[i][lists[i].length-reverse_indices[i]], pull_val) ) {\n // Found a duplicate, advance the index of the list in which the\n // duplicate was found.\n reverse_indices[i] -= 1\n aggregate_reverse_index -= 1\n } else if ( pull_arr_index == null ||\n cmp_fn(lists[i][lists[i].length-reverse_indices[i]], pull_val) < 0 ) {\n // Found a lower value.\n pull_arr_index = i\n pull_val = lists[i][lists[i].length-reverse_indices[i]]\n }\n }\n if (pull_arr_index != 0) {\n // Add the lowest found value in place into the first array.\n lists[0].splice(lists[0].length - reverse_indices[0], 0, pull_val)\n }\n aggregate_reverse_index -= 1\n reverse_indices[pull_arr_index] -= 1\n }\n return lists[0]\n }", "function combineOperations(startVal,arrOfFuncs){\n\n //////////solution 1\n // return arrOfFuncs.reduce((acc,func)=> {\n // return func(acc)\n // },startVal)\n\n ///////////solution 2\n // let output = startVal\n // arrOfFuncs.forEach(element=>{\n // output = element(output)\n // })\n // return output\n}", "function combineOperations(startVal, arrOfFuncs) {\n let output;\n for (let i = 0; i < arrOfFuncs.length; i += 1) {\n if (output === undefined) {\n output = arrOfFuncs[i](startVal);\n } else {\n output = arrOfFuncs[i](output);\n }\n }\n return output;\n}", "fold (f, a) {\n return fold(f, a, this)\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 zipWith(f, xs, ys) {\n return xs.map((x, idx) => f(x, ys[idx]));\n}", "function zipwith_indexed(xs, ys, f) /* forall<a,b,c,e> (xs : list<a>, ys : list<b>, f : (int, a, b) -> e c) -> e list<c> */ {\n return _bind_zipwith_indexed(xs, ys, f);\n}", "function partition(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> (list<a>, list<a>) */ {\n return partition_acc(xs, pred, Nil, Nil);\n}", "function applyFunction(x1, x2, f){\n var data = [];\n for (var i = 0, x; i <= 100; ++i) {\n x = x1 + i * (x2 - x1) / 100;\n data.push([x, f(x)]);\n }\n\n return data;\n}", "function _fast_zipwith_indexed(xs, ys, f) /* forall<a,b,c,e> (xs : list<a>, ys : list<b>, f : (int, a, b) -> e c) -> e list<c> */ {\n return _fast_zipwith_iter(f, 0, xs, ys);\n}", "function within(x, xs) {\n x = _vectorize(x)\n xs = _vectorize(xs)\n var fn = function(a,i) {\n if (i >= length(xs)) return false\n return a == xs[i] || fn(a,i+1)\n }\n return map(x, function(i) { return fn(i,0) })\n}", "function and(xs) {\n return xs.reduce((x,acc) => x && acc, true);\n}", "function _fast_list_1(lo, hi, f) /* forall<a,e> (lo : int, hi : int, f : (int) -> e a) -> e list<a> */ {\n function enumerate(low, high, acc) /* (low : int, high : int, acc : list<11103>) -> 11104 list<11103> */ { tailcall: while(1)\n {\n if ($std_core._int_gt(low,high)) {\n return acc;\n }\n else {\n {\n // tail call\n var _x5 = ($std_core._int_sub(high,1));\n var _x6 = Cons(f(high), acc);\n high = _x5;\n acc = _x6;\n continue tailcall;\n }\n }\n }}\n return enumerate(lo, hi, Nil);\n}", "function reverse_append(xs, tl) /* forall<a> (xs : list<a>, tl : list<a>) -> list<a> */ {\n function reverse_acc(acc, ys) /* forall<a> (acc : list<a>, ys : list<a>) -> list<a> */ { tailcall: while(1)\n {\n if (ys != null) {\n {\n // tail call\n var _x1 = Cons(ys.head, acc);\n acc = _x1;\n ys = ys.tail;\n continue tailcall;\n }\n }\n else {\n return acc;\n }\n }}\n return reverse_acc(tl, xs);\n}", "function minimum_1(xs) /* (xs : list<double>) -> double */ {\n return (xs == null) ? 0.0 : foldl(xs.tail, xs.head, min_1);\n}", "function _fast_apply(f, x) /* forall<a,b,e> (f : (a) -> e b, x : a) -> e b */ {\n return f(x);\n}", "function intermediateSums(arr) {\n var lastSet = arr.length % 10;\n var sum = 0;\n for (var i = arr.length - 1; i > arr.length - (1 + lastSet); i--) {\n sum += arr[i];\n }\n arr[arr.length] = sum;\n // for loop incremented by 11 (10 plus the total one)\n for (var i = 0; i < arr.length; i += 11) {\n sum = 0;\n for (var j = i; j < i + 10; j++) {\n sum += arr[j];\n }\n // console.log(\"Sum: \" + sum)\n for (var k = arr.length - 1; k > i + 10; k--) {\n [arr[k], arr[k-1]] = [arr[k-1], arr[k]];\n }\n arr[i + 10] = sum;\n }\n // add first 10 values\n // loop back to 10, shifting all elements one to the right.\n // assign sum to 10,\n // do the next set.\n return arr;\n}", "function mapReduce(f, a, seed) {\n\t\n\tfor (var i=0;i<a.length;i++){\n\t\tif (typeof a[i] != \"string\"){\n\t\t\ta[i] = a[i].toString()\n\t\t}\n\t\ta[i]=f(a[i]);\n\n\t}\n\tfor (var i=1;i<a.length;i++){\n\t\tif (typeof seed != \"undefined\"){\n\t\t\tfor (i=0;i<a.length;i++){\n\t\t\t\tseed = seed + f(a[i]);\n\t\t\t}\n\t\treturn seed;\n\t\t}\n\t\telse {\n\t\t\tif (typeof a[i] == \"string\"){\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\ta[i] = a[i].toString();\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t}\n\treturn a[0];\n\n}", "function hops(arr) {\nvar current = 0;\nvar flag = false;\n\twhile (current !== arr.length - 1) {\n\t\tcurrent += arr[current];\n\t\tif (current === arr.length - 1) {\n\t\t\treturn true;\n\t\t} else if (current === current + arr[current]) {\n\t\t\treturn false;\n\t\t}\n\t}\n}" ]
{ "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 = [...prevSeats.slice(0, index), 'available', ...prevSeats.slice(index + 1)]; this.updateState(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 vipSeatCount--;\n vipTicketNum.innerHTML = vipSeatCount; //display vip ticket num\n Seat.calcTotalPrice(vipSeatCount, this._seatType);\n };\n //total ticket count\n this._totalTicketNum = regularSeatCount + vipSeatCount;\n totalTicketNum.innerHTML = this._totalTicketNum;\n }", "function deselectSeat (id) {\n if (parseInt(numSeats) === 1) {\n firebase.database().ref('/Saler/' + settings.salNummer + '/Personer/' + sessionId).remove()\n removeGreenBoxes()\n }\n _selected = $.grep(_selected, function (item) {\n return item !== id\n })\n\n var _seatObj = _seats.filter(function (seat) {\n return seat.id === id\n })\n\n // Endrar status til at setet ikkje er reservert.\n _seatObj[0].selected = false\n _seatObj[0].notavailable = false\n\n // Oppdaterar databasen.\n var dbRef = firebase.database().ref('/Saler/' + settings.salNummer + '/Plassering/' + _seatObj[0].id)\n dbRef.transaction(function (sete) {\n if (sete) {\n sete.id = _seatObj[0].id\n sete.reservert = false\n sete.booked = false\n sete.label = _seatObj[0].label\n sete.sessionId = null\n } else {\n console.log('Feilmelding for transaksjon')\n }\n return sete\n })\n\n settings.seterReservert--\n let resSeterRef = firebase.database().ref('/Saler/' + settings.salNummer + '/Sal_Info/')\n resSeterRef.child('SeterReservert').set(settings.seterReservert)\n resSeterRef.child('SisteOppdatering').set(firebase.database.ServerValue.TIMESTAMP)\n }", "removeSlot() {\n this.closet.removeSlot();\n var closet_slot_face_id = this.closet_slots_faces_ids.pop();\n this.group.remove(this.group.getObjectById(closet_slot_face_id));\n this.updateClosetGV();\n }", "function removeWantToVisitPark(visit){\nwantToVisitPark.splice(visit, 1);\n\n}", "function deleteVassalOnClick(e){\r\n // Remove the element\r\n g_vassals.splice(parseInt(e.currentTarget.parentNode.id.split('vassal_')[1]), 1);\r\n\r\n setVassals();\r\n setVassalTable();\r\n}", "removeOccupant(id) {\n const theShelter = this.state.currentShelter;\n const unit = id;\n const occupant = {\n shelters: { shelterName: theShelter.shelterName },\n organizations: { orgName: theShelter.organizationName },\n occupant: unit,\n };\n ManagerActions.removeOccupant(occupant);\n }", "function removeSelected(sel){\n if (isNode(sel))\n {\n graph.removeNode(sel)\n }\n else if (isEdge(sel))\n {\n graph.removeEdge(sel)\n } \n selected = undefined\n repaint()\n }", "deselect() {\n if (this.selected != null) {\n this.selected.deselect();\n this.selected = null;\n }\n }", "function remove(element) {\n var index = element.getAttribute('data-index');\n select[0].options[index].selected = false;\n element.parentNode.parentNode.removeChild(element.parentNode);\n }", "function removecolor() {\n let color = document.getElementById(\"colorSelect\");\n color.remove(color.selectedIndex);\n}", "onRemoveMealButtonPressed(event) {\n\t\tevent.currentTarget.parentNode.parentNode.removeChild(event.currentTarget.parentNode);\n\t}", "removeGene (gene) {\n var geneArray = [this.state.currentChoice] // make a separate copy of the array\n this.state.currentChoice.splice(gene, 1);\n this.setState({\n currentChoice: this.state.currentChoice});\n this.fetchBokeh(this.state.currentChoice)\n }", "function clearSelection() {\n currentPizza = undefined;\n $('input[name=\"e-item\"]').prop('checked', false);\n $('input[name=\"psize\"]').prop('checked', false);\n $(\".lists-wrapper\").hide();\n\n currentBeverage = undefined;\n $('input[name=\"bsize\"]').prop('checked', false);\n $(\".beverage-size-list\").hide();\n\n currentOrder = undefined;\n\n }", "function deleteSelectedProgram() {\n var $this = $(this)\n var $program = $this.closest('.program')\n var transferSchoolCode = $this.closest('.transfer-school').attr('data-transfer-school-code')\n var programCode = $this.parent().attr('data-id')\n var programContainer = $this.parents('.program_container')[0]\n $(programContainer).find(\".program_list a[data-id='\" + programCode + \"']\").removeAttr(\"data-selected\")\n $program.remove()\n \n for (var i = 0; i < selectedPrograms.length; i++) {\n if (selectedPrograms[i] === programCode) {\n selectedPrograms.splice(i, 1);\n }\n }\n}", "function removeCurrentBooking() {\n\t// remove the marker first\n\tif (bookedVehicle) {\n\t\tbookedVehicle.marker.setMap(null);\n\t\tbookedVehicle = null;\n\t}\n\t// remove the card\n\tvar currentBookingCard = document.getElementById(\"current-booking\");\n\tif (currentBookingCard) {\n\t\t// fancy transition\n\t\tcurrentBookingCard.className = \"transition-start\";\n\t\tsetTimeout(function() {\n\t\t\tdocument.body.removeChild(currentBookingCard);\n\t\t}, 200);\n\t}\n}", "situationDeleted(situation) {\n let id = situation._id;\n let marker = SituationMarkers[id];\n // remove marker layer from map\n map.removeLayer(marker);\n\n // remove from hashtable\n delete SituationMarkers[id];\n }", "function clickRemoveB() {\n removePrefect(prefectB);\n makePrefect(selectedStudent);\n buildList();\n closeDialog();\n }", "function view_deleteStudentFromView(id) {\n $(`#${id}`).remove();\n}", "deselect(option) {\n this.deselectValue(option.value);\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 = document.getElementById('postBody');\n var postText = postBody.innerText;\n if(postText.startsWith(\"UPDATED:\\n\"))\n postText = postText.replace(\"UPDATED:\\n\",\"\");\n postBody.innerHTML = postText;\n postBody.contentEditable = \"true\";\n postBody.classList.add(\"edit\");\n}", "titleUpdated(event) {\n this.lessonToUpdate.title = event.target.value;\n }", "function displayEditPost(post){\r\n\t\t\t$(\"form#edit-form input#title\").val(post.title);\r\n\t\t\t$(\"form#edit-form textarea#content\").val(post.body);\r\n\t\t}", "function onTitleChange()\n {\n var modifiedTitle = $( \"#article-title\" )[0].value\n if( currentTitle == modifiedTitle ) return\n currentTitle = modifiedTitle\n if( currentTitle == \"\" )\n visualState( STATUS_NEW )\n else( onArticleVerify( currentTitle ) )\n }", "set title(title) {\n if (Lang.isNull(title)) {\n this._study.title = null;\n return;\n }\n let titleObj = new Title();\n titleObj.value = title;\n this._study.title = titleObj;\n }", "fillMetaTitle(title = '') {\n repoBlogForm.getMetaTitleInput().typeAndCheck(title);\n }", "function EditPost() {\n if (post.user._id === \"60af83bbbe9b150015506e18\") {\n setEdited(!edited);\n } else {\n alert(\"You can't Edit someone's post!!!\");\n }\n }", "fillEditForm() {\n let post = editor.currentPost,\n editTitle = document.getElementById('editTitle'),\n postTitle = h.getPostTitle(),\n titleField = h.getEditorTitleField();\n\n // Update the title and content fields\n editTitle.value = post.title;\n editContent.value = post.content;\n\n // Initialize the wysiwyg editor\n wysiwyg = wysiwygEditor(document.getElementById('editContent'));\n\n // Add listeners to update the view on field changes\n if (post.type !== 'settings') {\n // Actions if not editing a setting\n titleField.addEventListener('input', function () {\n editor.currentPost.title = this.value;\n view.updateTitle(this.value);\n }, false);\n wysiwyg.onUpdate(function () {\n view.updateContent(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {\n // Live update controls for settings\n if (post.slug === 'site-name') {\n wysiwyg.onUpdate(function () {\n view.updateSiteName(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else if (post.slug == 'site-description') {\n wysiwyg.onUpdate(function () {\n view.updateSiteDescription(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {}\n }\n }", "_updateTitle() {\n let ttl = '';\n if (this._curPage) {\n ttl = this._curPage.title();\n }\n document.title = this._rootArea.title(ttl);\n }", "function saveTitle() {\n\n var id = $(\"#current-note-display\")[0].getAttribute(\"data-id\");\n var title = $(\"#current-note-title\").text();\n editNote(id=id, title=title);\n\n //Replace title of note block in notes display with new title\n var curNote = findNoteElement(id);\n if (curNote != null) {\n curNote.innerHTML = trimTitle(title, titleDisplayLen);\n }\n\n}", "_updateTitle()\n {\n document.head.querySelector('title').innerText = `[${this._toString('HH:mm:ss')}] @amjs/working-on`;\n }", "_updateTitleTab() {\n var self = this;\n super._updateTitleTab();\n if (_.isUndefined(self.m_sceneMime))\n return;\n $(Elements.BLOCK_SUBPROPERTIES_TITLE).text(self.m_config[self.m_sceneMime].tabTitle);\n }", "function updTitleEnter(state){\n $('.delete_update').on('keypress', '#updateTitle', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setTitleValue(state,$('#updateTitle'),$('.delete_update'));\n $('#updateTitle').val('');\n }\n });\n}", "function rewriteTitle() {\n\tif( typeof( SKIP_TITLE_REWRITE ) != 'undefined' && SKIP_TITLE_REWRITE ) {\n\t\treturn;\n\t}\n\n\tvar titleDiv = document.getElementById( 'title-meta' );\n\n\tif( titleDiv == null || titleDiv == undefined ) {\n\t\treturn;\n\t}\n\n\tvar cloneNode = titleDiv.cloneNode( true );\n\tvar firstHeading = document.getElementById( 'firstHeading' );\n\tvar node = firstHeading.childNodes[0];\n\n\t// new, then old!\n\tfirstHeading.replaceChild( cloneNode, node );\n\tcloneNode.style.display = 'inline';\n\tif ( titleDiv.childNodes[0].nodeValue.toLowerCase() == wgPageName.replace( /_/g, ' ' ).toLowerCase() ) {\n\t\tdocument.title = titleDiv.childNodes[0].nodeValue;\n\t}\n\n\tvar titleAlign = document.getElementById( 'title-align' );\n\tfirstHeading.style.textAlign = titleAlign.childNodes[0].nodeValue;\n}", "function AmendPageTitle()\r\n{\r\n //console.log(\"Amend Title\");\r\n if (document.title != \"\" && docTitle != document.title)\r\n {\r\n docTitle = document.title;\r\n for (var i = 0; i < amendList.length; i++)\r\n {\r\n var item = amendList[i];\r\n\r\n if (item.enabled == 1)\r\n {\r\n var re = RegExp(item.url, \"i\");\r\n var m = re.exec(document.URL);\r\n\r\n if (m != null)\r\n {\r\n re = RegExp(item.search, \"gi\");\r\n docTitle = docTitle.replace(re, item.replace);\r\n }\r\n }\r\n }\r\n document.title = docTitle;\r\n }\r\n}", "function updatedPost(){\n var postBody = document.getElementById('postBody');\n var editedText = postBody.innerText.replaceAll(\"\\n\",\"<br/>\");\n postBody.innerHTML = \"UPDATED:<br/>\"+editedText;\n postBody.classList.remove(\"edit\");\n postBody.contentEditable = \"false\";\n}", "_updateTitle(text, tooltip, limit) {\n // Polymer 2: check for undefined\n if ([text, limit, tooltip].includes(undefined)) {\n return;\n }\n\n this.hasTooltip = !!tooltip || (!!limit && text.length > limit);\n if (this.hasTooltip && !this.disableTooltip) {\n // Combine the text and title if over-length\n if (limit && text.length > limit) {\n this.title = `${text}${tooltip? ` (${tooltip})` : ''}`;\n } else {\n this.title = tooltip;\n }\n } else {\n this.title = '';\n }\n }", "function modify_title()\n{\n if( title != undefined ) document.title = \"Scheduler - \" + title;\n\n var title_state;\n \n if( document.readyState == \"interactive\" ) title_state = \"(running)\";\n else\n if( document.readyState == \"complete\" ) title_state = \"(terminated)\";\n\n if( title_state ) document.title = document.title.replace( / *(\\(.*\\))|$/, \" \" + title_state );\n}" ]
{ "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() { $notify.add({ message: 'The bulk onboard has been created and sent for approval', type: 'success' }); $location.path(Paths.get('recruit.onboards.bulkDetails', bulkOnboardId).path); $route.reload(); }) .catch(function() { $notify.add({ message: 'The bulk onboard could not be created at this time. Please try again later', type: 'error' }); }) .finally(function(res) { hideLoadingIndicator(0); }); } } else { $notify.add({ message: 'The bulk onboard has been created', type: 'success' }); $location.path(Paths.get('recruit.onboards.bulk').path); $route.reload(); } }
[ "@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 project.id, {\n max: this.content.hours ? project.max + this.content.hours : project.max,\n due: this.content.due ? this.content.due : project.due\n }\n ).commit();\n }", "applyDisapproval () {\n this.update({\n 'data.class.disapproval': this.data.data.class.disapproval + 1\n })\n }", "function InsertAccountLinkOnBegin() {\n isajaxrunning = true;\n\n //Show spinner and add margin to submit button text\n $('#modal-account-guestaccounts-create-submit-spin').css('display', '');\n $('#modal-account-guestaccounts-create-submit-spin').prev().css('margin-left', '17px');\n\n //Disable select2 input\n $(\"#account-guestaccounts-create-permissions\").select2('disable');\n\n //Disable datepicker\n $('#account-guestaccount-create-startdate').find(':input').prop('disabled', true);\n $('#account-guestaccount-create-enddate').find(':input').prop('disabled', true);\n\n //Set read only on inputs\n $('.modal-account-guestaccounts-create-input').prop('readonly', true);\n //Disable submit button\n $('#modal-account-guestaccounts-create-submitbtn').prop('disabled', true);\n\n //Set cursor for datepicker button\n $('#account-guestaccount-create-startdate').find('.input-group-addon').css('cursor', 'default');\n //Set cursor for datepicker button\n $('#account-guestaccount-create-enddate').find('.input-group-addon').css('cursor', 'default');\n }", "function BtnTaskApplyClick(){\n SaveTask(); \n}", "function UpdateStatusforSupplierAfterModify(req, multi, supplierAddress, callback) {\n var json = {};\n multi.signbyAssignee.sendTransaction(supplierAddress, false, props.status_pending, '', '', true, {\n from: req.session.address,\n gas: 3000000\n }, function(err, contract) {\n json.error = err;\n json.result = contract;\n callback(null, json);\n });\n}", "function handleBpSaveBillerCorpAcctCredsOnSuccess() {\n\t/* Storing the biller boxes data into tempBillArray so that is can be populated later after BP_ACCOUNT_LITE API call */\n\tsetTempBillArray(); \n\tif (isGuestMsg) {\n\t\tgettingInfoOfBillerAcc();\n\t\t$('#myAccountBox').show();\n $('#guestUserMyAccountBox').hide();\n isGuestMsg = false;\n\t\tshowGeneralSuccessMsg(messages['addEditBiller.GuestUserBillerSaved'],\n messages['inLine.message.successMessage']);\n } else {\n \t/* Checking for scheduled biller edited and updated credentials it will raise pop up */\n \tif(bp_save_biller_corp_acct_creds_obj.scheduled === true){\n \t\tsuccessfulCredUpdatePopup();\t\n \t\tgettingInfoOfBillerAcc();\n \t} else {\n \t\tgettingInfoOfBillerAcc();\n \t\tshowGeneralSuccessMsg(messages['addEditBiller.alert.billerSaved'],\n \t\t messages['inLine.message.successMessage']);\n \t}\n }\n}", "function cmdUpdate_ClickCase100() {\n console.log(\"cmdUpdate_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n console.log(\"cmdUpdate_ClickCase100.1\", $scope.CompletedQty);\n //if ($scope.McType.toLowerCase() == \"inhouse\") {\n // ReCheck($scope.selectedWOID);\n // //CheckWOOpnStatus();\n // console.log(\"saveCompleteModal2\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //} else {\n // ReCheck($scope.selectedWOID);\n // //CheckSubconWOOpnStatus();\n // console.log(\"saveCompleteModal3\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //}\n\n\n }", "function confirmed(request, response, form, stVB)\n{\n\tvar stLoggerTitle = 'suitelet_confirmVendorBillApproval';\t\n\tnlapiLogExecution('DEBUG', stLoggerTitle, 'VB = ' + stVB);\n\t\n\tnlapiSubmitField('vendorbill', stVB, 'approvalstatus', '2');\n\tnlapiLogExecution('DEBUG', stLoggerTitle, 'Successfully set status to Approved.');\n\t\n\tnlapiSetRedirectURL('RECORD', 'vendorbill', stVB);\n}", "function DeletePendingAccountLinksOnBegin() {\n isajaxrunning = true;\n\n //Show spinner and add margin to submit button text\n $('#modal-account-pending-guestaccounts-remove-spin').css('display', '');\n $('#modal-account-pending-guestaccounts-remove-spin').prev().css('margin-left', '17px');\n\n //Disable submit button\n $('#modal-account-pending-guestaccounts-remove-btn').prop('disabled', true);\n }", "function workflowAction_confirmVendorBillApproval()\n{\t\n\tvar stLoggerTitle = 'workflowAction_confirmVendorBillApproval';\n\t\t\n\tnlapiLogExecution('DEBUG', stLoggerTitle, '>>Entry<<');\n \n try\n { \t\n \tvar stVB = nlapiGetRecordId()\n \tnlapiLogExecution('DEBUG', stLoggerTitle, 'Vendor Bill = ' + stVB);\n \t\n \tvar arrParams = new Array();\n\t\tarrParams['custpage_vb']=stVB;\n \t\n \tnlapiSetRedirectURL('SUITELET','customscript_confirm_vb_approval_suitele','customdeploy_confirm_vb_approval_suitele', null, arrParams);\n \n nlapiLogExecution('DEBUG', stLoggerTitle, '>>Exit<<'); \n return true;\n } \n catch (error)\n {\n \tif (error.getDetails != undefined)\n {\n nlapiLogExecution('ERROR','Process Error', error.getCode() + ': ' + error.getDetails());\n throw error;\n }\n else\n {\n nlapiLogExecution('ERROR','Unexpected Error', error.toString()); \n throw nlapiCreateError('99999', error.toString());\n } \t \n return false;\n } \n}", "completeAllItems() {\n this.items.forEach(item => {\n item.status = 'Completed';\n item.finishedAt = Date.now;\n });\n }", "function wpbs_booking_bt_update_status() {\n $(\".wpbs-order-information-bt-payment-actions\").each(function () {\n var $wrap = $(this);\n\n // Prepare the data\n var data = {\n action: 'wpbs_booking_bt_update_status',\n wpbs_token: wpbs_localized_data_booking.change_payment_status,\n id: $wrap.data('booking-id')\n }\n\n // Send the request\n $.post(ajaxurl, data, function (response) {\n $wrap.html(response);\n });\n\n })\n }", "function _rsvpSuccess() {\n\t\t\t\trf.btnSaved = true;\n\t\t\t\trf.btnSubmitText = _isCreate ? 'Submitted!' : 'Updated!';\n\n\t\t\t\t$rootScope.$broadcast('rsvpSubmitted');\n\n\t\t\t\t// user has submitted an RSVP; update create/edit status in case they edit without refreshing\n\t\t\t\t_isCreate = false;\n\t\t\t\t_isEdit = true;\n\n\t\t\t\t// restart $watch on rf.formModel.attending\n\t\t\t\t_startWatchAttending();\n\n\t\t\t\t$timeout(function() {\n\t\t\t\t\t_btnSubmitReset();\n\t\t\t\t\trf.showModal = false;\n\t\t\t\t}, 1000);\n\t\t\t}", "function batchUpload() {\n var queueName = dijit.byId('vl-queue-name').getValue();\n currentType = dijit.byId('vl-record-type').getValue();\n\n var handleProcessSpool = function() {\n if( \n vlUploadQueueImportNoMatch.checked || \n vlUploadQueueAutoOverlayExact.checked || \n vlUploadQueueAutoOverlay1Match.checked) {\n\n vlImportRecordQueue(\n currentType, \n currentQueueId, \n function() {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n );\n } else {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n }\n\n var handleUploadMARC = function(key) {\n dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');\n processSpool(key, currentQueueId, currentType, handleProcessSpool);\n };\n\n var handleCreateQueue = function(queue) {\n currentQueueId = queue.id();\n uploadMARC(handleUploadMARC);\n };\n \n if(vlUploadQueueSelector.getValue() && !queueName) {\n currentQueueId = vlUploadQueueSelector.getValue();\n uploadMARC(handleUploadMARC);\n } else {\n createQueue(queueName, currentType, handleCreateQueue, vlUploadQueueHoldingsImportProfile.attr('value'));\n }\n}", "function userApply () {\n updateMe().then(function() {\n $scope.listingId // Push listingId into User Applications Array\n // Push userId into Listing Applications Array\n var user = Parse.User.current();\n if (user){\n user.addUnique(\"applications\", $scope.listingId)\n user.save();\n } else {\n alert(\"Yikes! For some reason the little magic elves aren't working hard enougha and your application did not submit. Try again later. Every good elf needs a break.\")\n }\n });\n }", "function updateUserQuestionProgress(user,question,quiz,tags,ok_for_alexa,tallySuccess) {\n\t\t//\tconsole.log(['update progress',user,question,quiz,tags,ok_for_alexa,tallySuccess]);\n\t\t\treturn new Promise(function(resolve,reject) {\n\t\t\t\tinitdb().then(function(db) {\n\t\t\t\t\tdb.collection('userquestionprogress').findOne({$and:[{'user': {$eq:ObjectId(user)}},{question:ObjectId(question)} , {block:{ $not: { $gt: 0 } }}]}).then(function(progress) {\n\t\t\t\t\t\t//console.log(['UPDATE PROGRESS FOUND',progress])\n\t\t\t\t\t\tvar isNew = false;\n\t\t\t\t\t\tif (!progress) {\n\t\t\t\t\t\t\tisNew = true;\n\t\t\t\t\t\t\tprogress = {user:ObjectId(user),question:ObjectId(question)};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprogress.topic=quiz;\n\t\t\t\t\t\tprogress.tags=tags;\n\t\t\t\t\t\tprogress.ok_for_alexa=ok_for_alexa;\n\t\t\t\t\t\tprogress.seenTally = parseInt(progress.seenTally,10) > 0 ? parseInt(progress.seenTally,10) + 1 : 1;\n\t\t\t\t\t\t//console.log(['trySETSEEN',new Date().getTime()/1000])\n\t\t\t\t\t\tprogress.seen = parseInt(new Date().getTime()/1000,10);\n\t\t\t\t\t\t//console.log(['SETSEEN',progress.seen])\n\t\t\t\t\t\tif (tallySuccess) {\n\t\t\t\t\t\t\tprogress.successTally = parseInt(progress.successTally,10) > 0 ? parseInt(progress.successTally,10) + 1 : 1;\n\t\t\t\t\t\t\tprogress.success = progress.seen;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprogress.successRate = (parseInt(progress.successTally,10) > 0 && parseInt(progress.seenTally,10) > 0) ? progress.successTally/progress.seenTally : 0;\n\t\t\t\t\t\tprogress.block=0;\n\t\t\t\t\t // console.log(['update progress NOW',progress]);\n\t\t\t\t\t\tif (isNew) {\n\t\t\t\t\t\t\tdb.collection('userquestionprogress').insertOne(progress).then(function(res) {\n\t\t\t\t\t\t\t//\tconsole.log(['inserted progre00ss',res])\n\t\t\t\t\t\t\t\tupdateUserStats(user,question,tallySuccess).then(function() {\n\t\t\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}).catch(function(e) {\n\t\t\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdb.collection('userquestionprogress').updateOne({_id:ObjectId(progress._id)},{$set:progress}).then(function(res) {\n\t\t\t\t\t\t\t//\tconsole.log(['updated progre00ss',res])\n\t\t\t\t\t\t\t\tupdateUserStats(user,question,tallySuccess).then(function() {\n\t\t\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}).catch(function(e) {\n\t\t\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} \n\t\t\t\t }).catch(function(e) {\n\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t });\n\t\t\t\t})\n\t\t\t})\n\t\t}", "function submit() {\n var order = Order.get(request.httpParameterMap.order_id.stringValue);\n var orderPlacementStatus;\n if (order.object && request.httpParameterMap.order_token.stringValue === order.getOrderToken()) {\n orderPlacementStatus = Order.submit(order.object);\n if (!orderPlacementStatus.error) {\n clearForms();\n return app.getController('COSummary').ShowConfirmation(order.object);\n }\n }\n app.getController('COSummary').Start();\n}", "function cmdUpdateReceived_ClickCase100() {\n console.log(\"cmdUpdateReceived_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n if (config.BypassExecutionStart) {\n //todo: line 5619\n }\n\n\n\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{ elementoInvalido(campo); return false; } }
[ "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 }", "function navidad(fecha) {\n return fecha == \"25/12/2021\" ? \"Es navidad\" : \"No es navidad\";\n}", "function comprobarVacio(campo){\r\n\t//Obtenemos el valor que contiene el campo\r\n\tvar valor = campo.value;\r\n\t//Comprobamos si el campo esta vacio(true) o no(false)\r\n\tif( valor==\"\" ){\r\n\t\treturn true;\t\t\r\n\t}\r\n\t//No es vacio retornamos false\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}", "function esFechaMenorActual(date) {\n\tvar x = new Date();\n\tvar fecha = date.split(\"-\");\n\tif (fecha[0]>1000) {\n\t\tx.setFullYear(fecha[0], fecha[1]-1, fecha[2]);\n\t} else {\n\t\tx.setFullYear(fecha[2], fecha[1]-1, fecha[0]);\t\n\t}\n\tvar today = new Date();\n\tif (x >= today) {\n\t\tvar error = \"La fecha de desaparición es posterior al día de hoy\";\n\t\tmostrarModal(\"rojo\", error);\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}", "function checkDateOnBlur(field,dataBaseField)\n{\t\n\t\n\t/*if (wrongDate)\t\n \t{\t\n \t\twrongDate=false;\n \t\treturn;\n \t}\n \t\t\n \tif (field.value!=\"\")\n \t{\n \t\t//se il campo comincia con il carattere . oppure - seguito da un numero\n \t\t//si aggiungere/sottrae alla dataBase il numero di giorni specificato\n \t\tif((field.value.substr(0,1)==\".\" || field.value.substr(0,1)==\"-\") \n \t\t\t && dataBaseField && isDateField(dataBaseField))\n \t\t{\n \t\t\tvar offset=parseInt(field.value.substr(1));\n \t\t\tif(!isNaN(offset))\t//se l'offset � un numero\n \t\t\t{\n \t\t\t\tif(offset>9999)\n \t\t\t\t\toffset=9999;\n \t\t\t\tif(offset!=0)\n \t\t\t\t\toffset--;\t//in modo che la differenza fra data di partenza e quella finale coincide con l'offset\n \t\t\t\tif(field.value.substr(0,1)==\"-\")\n \t\t\t\t\toffset=-offset;\n\t \t\t\tvar d = getDateFromText(dataBaseField.value);\n\t \t\td.setDate(d.getDate()+offset);\n\t\t\t\tvar curr_date = d.getDate();\n\t\t\t\tvar curr_month = d.getMonth();\n\t\t\t\tcurr_month++;\n\t\t\t\tvar curr_year = d.getFullYear();\n\t \t\t\tfield.value=curr_date + \"/\" + curr_month + \"/\" + curr_year;\n \t\t\t}\n \t\t}\t\n \t\t\n\t \tif (!isDateField(field))\n\t \t{\n\t \t\talert(\"Data non valida\");\n\t \t\tfield.focus();\n\t \t\twrongDate=true;\n\t \t}\n\t \telse\n\t \t\twrongDate=false;\n }\n else\n wrongDate=false;\n if (wrongDate)\t\n \t{\t\n \t\twrongDate=false;\n \t\treturn;\n \t}*/\n \t\n \tif (field.getValue()!=\"\")\n \t{\n \t\t//se il campo comincia con il carattere . oppure - seguito da un numero\n \t\t//si aggiungere/sottrae alla dataBase il numero di giorni specificato\n \t\t\n \t\tif((field.getValue().substr(0,1)==\".\" || field.getValue().substr(0,1)==\"-\") \n \t\t\t && dataBaseField && isDateField(dataBaseField))\n \t\t{\n \t\t\tvar offset=parseInt(field.getValue().substr(1));\n \t\t\tif(!isNaN(offset))\t//se l'offset � un numero\n \t\t\t{\n \t\t\t\tif(offset>9999)\n \t\t\t\t\toffset=9999;\n \t\t\t\tif(offset!=0)\n \t\t\t\t\toffset--;\t//in modo che la differenza fra data di partenza e quella finale coincide con l'offset\n \t\t\t\tif(field.getValue().substr(0,1)==\"-\")\n \t\t\t\t\toffset=-offset;\n\t \t\t\tvar d = getDateFromText(dataBaseField.getValue());\n\t \t\td.setDate(d.getDate()+offset);\n\t\t\t\tvar curr_date = d.getDate();\n\t\t\t\tvar curr_month = d.getMonth();\n\t\t\t\tcurr_month++;\n\t\t\t\tvar curr_year = d.getFullYear();\n\t \t\t\tfield.setValue(curr_date + \"/\" + curr_month + \"/\" + curr_year);\n \t\t\t}\n \t\t}\t\n \t\t\n\t \tif (!isDateField(field))\n\t \t{\n\t \t\talert(\"Data non valida\");\n\t \t\tfield.focus();\n\t \t\twrongDate=true;\n\t \t}\n\t \telse\n\t \t\twrongDate=false;\n }\n else\n wrongDate=false;\n}", "function validaCadenaVacia(campo, nombreCampo){\n\tif(campo === null \n\t\t\t|| campo === undefined\n\t\t\t|| trimTexto(campo).length === 0){\n\t\talert(\"El campo \" + nombreCampo + \" debe ser informado.\");\n\t\treturn false;\n\t}\n\treturn true;\n}", "static supportsDateInput() {\n const input = document.createElement('input');\n input.setAttribute('type', 'date');\n\n const notADateValue = 'not-a-date';\n input.setAttribute('value', notADateValue);\n\n return !(input.value === notADateValue);\n }", "function ValidarFechaDia(ValidacionFecha, EventoDia){\n if (ElMesEs == '10' && HoyEs == Dia1 ){\n this.ValidacionFecha = true;\n this.EventoDia = 1;\n }\n else if (ElMesEs == 10 && HoyEs == Dia2 ){\n this.ValidacionFecha = true;\n this.EventoDia = 2;\n }\n else if (ElMesEs == 10 && HoyEs == Dia3 ){\n this.ValidacionFecha = true;\n this.EventoDia = 3;\n }\n else{\n this.ValidacionFecha = false;\n this.EventoDia = 0;\n }\n}", "function chkIsDate(str)\r\n{\r\n\tvar strSeparator = \"-\"; //???????????????\r\n\tvar strDateArray;\r\n\tvar intYear;\r\n\tvar intMonth;\r\n\tvar intDay;\r\n\tvar boolLeapYear;\r\n\tstrDateArray = str.split(strSeparator);\r\n\tif(strDateArray.length!=3) \r\n\t\treturn false;\r\n\t\t\r\n\tif(strDateArray[0].length!=4)\r\n\t\treturn false;\r\n\tintYear = parseInt(strDateArray[0],10);\r\n\tintMonth = parseInt(strDateArray[1],10);\r\n\tintDay = parseInt(strDateArray[2],10);\r\n\r\n\tif(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)) \r\n\t\treturn false;\r\n\tif(intYear<1 || intYear>2500)\r\n\t\treturn false;\r\n\tif(intMonth>12||intMonth<1) \r\n\t\treturn false;\r\n\r\n\tif((intMonth==1||intMonth==3||intMonth==5||intMonth==7||intMonth==8||intMonth==10||intMonth==12)&&(intDay>31||intDay<1)) \r\n\t\treturn false;\r\n\tif((intMonth==4||intMonth==6||intMonth==9||intMonth==11)&&(intDay>30||intDay<1)) \r\n\t\treturn false;\r\n\tif(intMonth==2){\r\n\t\tif(intDay<1) \r\n\t\t\treturn false;\r\n\r\n\t\tboolLeapYear = false;\r\n\t\tif((intYear%100)==0){\r\n\t\t\tif((intYear%400)==0) \r\n\t\t\t\tboolLeapYear = true;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif((intYear%4)==0) \r\n\t\t\t\tboolLeapYear = true;\r\n\t\t}\r\n\r\n\t\tif(boolLeapYear){\r\n\t\t\tif(intDay>29) \r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif(intDay>28) \r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}", "function filterDate(aliens) {\n return aliens.datetime == $dateInput.value.trim().toLowerCase();\n}", "function hasGroupByDate(curTgrp){\n var sortFields = curTgrp.sortFields;\n if ((sortFields) && (sortFields.length > 0)) {\n \tfor(var i=0; i<sortFields.length; i++){\n \t\tvar sortField = sortFields[i];\n var groupByDate = sortFields[i].groupByDate;\n if ((groupByDate != '')) {\n \t return true;\n }\n \t}\n }\n return false; \n}", "function validateCreated(cb_err) {\n if (typeof this.created !== 'undefined') {\n if (!validator.isDate(this.created)) {\n cb_err();\n }\n }\n }", "function isDateACHSafe(dateFieldIdName)\n{\n\tvar dateOne = Date.parse(nextSafeACHDueDate);\n\t\n\tvar dateValue = document.getElementById(dateFieldIdName);\n\n\tif(!dateOne || !dateValue) return false;\n\t\n\tvar dateTwo = Date.parse(dateValue.value);\n\t\n\tvar diff = dateTwo - dateOne;\n\tvar days = Math.floor(diff / ( 1000 * 60 * 60 * 24));\n\n\tif(days >= 0)\n\t{\n\t\treturn true\n\t}\n\n\treturn false;\n}", "function validDates() {\n if (checkIn.val() != '' && checkOut.val() != '') {\n inDate = new Date(checkIn.val())\n outDate = new Date(checkOut.val())\n if (inDate < outDate) {\n return true\n }\n }\n return false\n }", "_isADateRule (rule) {\n return !! ~['after', 'before', 'date_between', 'date_format'].indexOf(rule);\n }", "function validar_dato_letras(dato){\n const regex = /^[A-Z]+$/i;\n return regex.test(dato); // true\n}", "function validateDate(a, b, c) {\n\t\t\t\t\t// Value in the field\n\t\t\t\t\tvar date = $(a).val();\n\t\t\t\t\t// Regular Expression to validate value against\n\t\t\t\t\tvar regularExpression = /^(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9])-(?:[0-9]{2})?[0-9]{2}$/;\n\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\t// Validating field content\n\t\t\t\t\t\tif (!regularExpression.test(date)) {\n\t\t\t\t\t\t\t$(b).text(\"Your input is invalid. Date number only!\")\n\t\t\t\t\t\t\t\t\t.attr(\"class\", \"invalid\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(b).text(\"valid\").attr(\"class\", \"valid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}", "function checkDate(time) {\r\n let today = new Date();\r\n today = today.getTime() - (today.getTime() % oneDayInMilliseconds); // Convert 'today' in multiple of a entire date\r\n let errors = []\r\n\r\n if (isNaN(time)) errors.push(\"Must provide a date.\");\r\n\r\n if (time < today) errors.push(\"Date must be in the future.\");\r\n\r\n // Search for a date conflict\r\n for (let i = 0; i < travelDates.length; i++) {\r\n if (travelDates[i].date == time) {\r\n errors.push(\"Date conflict.\");\r\n break;\r\n }\r\n }\r\n\r\n return errors;\r\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 HERE
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 $${afterTax.toFixed(2)}`);\n }", "function calculateTax() {\n return payGrades[getCadre()].taxMultiplier * salary;\n}", "function calculateTaxes(income) {\n if (income < 10000) {\n return (income * .05);\n } else if (income >10000 <20000) {\n return (income * .10);\n } else if (income > 20000) {\n return (income * 15);\n } \n}", "function solve(meal_cost, tip_percent, tax_percent) {\n // Write your code here\n let mealCost = meal_cost;\n let tipPercent = tip_percent;\n let taxPercent = tax_percent;\n\n // tip = 12 and 12/100 x 20 = 2.4\n let tip = (mealCost / 100) * tipPercent;\n // console.log(tip);\n\n // tax = 8 and 8/100 x 20 = 0.96\n let tax = (mealCost / 100) * taxPercent;\n // console.log(tax);\n\n // total_cost = meal_cost + tip + tax = 12 + 2.4 + 0.96 = 15.36\n let totalCost = Math.round(mealCost + tip + tax);\n // console.log(totalCost);\n\n // round(total_cost) = 15 (rounded total_cost to the nearest integer)\n return totalCost;\n}", "function tax_on_item(amount, tax_rate)\n{\n return Math.round(tax_rate * amount) / 100.0;\n}", "calcTax() {\n let costGettingIncome, costGettingIncomePercentage, taxBase;\n \n if (elements.workContractCosts20.checked) {\n costGettingIncomePercentage = 0.2;\n } else if (elements.workContractCosts50.checked) {\n costGettingIncomePercentage = 0.5;\n }\n \n if (!elements.flatTax.checked) {\n costGettingIncome = Math.round(this.payment * costGettingIncomePercentage);\n taxBase = Math.round(this.payment - costGettingIncome);\n } else {\n taxBase = Math.round(this.payment);\n }\n\n this.PIT = Math.round(taxBase * 0.17);\n }", "function tipAmount(bill, service) {\n if (service == 'good') {\n return (bill) + (bill * 0.2);\n }\n else if (service == 'fair') {\n return (bill) + (bill * 0.15);\n }\n else if (service == 'bad') {\n return (bill) + (bill * 0.10);\n }\n else {\n return \"That is not a valid input\";\n }\n }", "function calculateBill(total, tax = 0.12, tip = 0.15) {\n return total + (total * tax) + (total * tip);\n}", "function calculateBonus() {\n return .02 * salary;\n}", "function ParseAndCalcShipCost(val) {\n console.log('ParseAndCalcShipCost()')\n\n if (val == null || val == '')\n return 0\n\n var expression = val.toLowerCase().replace(/&#39;/g, '\"')\n\n // var expression = '20 + [ fee percent=\"10\" min_fee=\"4\" ]'\n // var expression = '20 + [ qty]*10'\n // var expression = '[qty] * 10 + [fee percent=\"10\" min_fee=\"4\"]'\n // var expression = '10 + (1 + 2) * [qty]'\n\n return ParseWithLexer(expression) // see parseShipping.js\n} // ParseAndCalcShipCost()", "function calcAmount(cost, discount) {\n return cost - discount;\n}", "function calculateTax(totalSales, companyProv){\r\n // Multiple totalSales by province tax rate.\r\n return totalSales * salesTaxRates[companyProv];\r\n}", "function calculateTip(tipPercentage, billTotal) {\n var tipPercentage = tipPercentage\n var tipAmount = tipPercentage * billTotal;\n tipAmount = tipAmount.toFixed(2);\n return parseFloat(tipAmount);\n}", "function math_vat_rate(vat) {\n\tvar math_tax_rate = '';\n\tif(vat.length == 2){ math_tax_rate = parseFloat('1.'+vat); }\n\telse { math_tax_rate = parseFloat('1.'+'0'+vat); }\n\treturn math_tax_rate;\n}", "function fnalCrsMrk() {\r\n //Creating a variable fmark and assign to it the functions exam(75) + crsmark(40)\r\n //exam(75) outputs (60/100)*75 == 45\r\n //crsmarks(40) outputs (170/2) * (40/100) == 34\r\n let fmark = exam(75) + crsmark(40);\r\n //Calling the result from the variable fmark to write to the console\r\n console.log(fmark);\r\n }", "function getTaxBill(income) {\n if (income < 0) {\n setTaxBill(0);\n } else if (income < 9875) {\n setTaxBill(income * 0.1);\n } else if (income < 40125) {\n setTaxBill(987.5 + (income - 9875) * 0.12);\n } else if (income < 85525) {\n setTaxBill(4617.5 + (income - 40125) * 0.22);\n } else if (income < 163301) {\n setTaxBill(14605.5 + (income - 85525) * 0.24);\n } else if (income < 207350) {\n setTaxBill(33271.5 + (income - 163300) * 0.32);\n } else if (income < 518400) {\n setTaxBill(47367.5 + (income - 207350) * 0.35);\n } else {\n setTaxBill(156235 + (income - 518400) * 0.37);\n }\n }", "function doDemo(formulaStr) {\n formulaElem.value = formulaStr;\n doBalance();\n}", "function calculateTip(tipPercentage, totalBill) {\n return tipPercentage * totalBill;\n }" ]
{ "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.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}", "function getRoutes(){\n\n routeLayer.clearLayers();\n\n var travelOptions = r360.travelOptions();\n travelOptions.addSource(sourceMarker); \n travelOptions.setDate(date);\n travelOptions.setTime(time);\n travelOptions.setTravelType(autoComplete.getTravelType());\n travelOptions.setElevationEnabled(true);\n travelOptions.setWaitControl(waitControl);\n travelOptions.addTarget(targetMarker);\n\n r360.RouteService.getRoutes(travelOptions, function(routes) {\n\n var html = \n '<table class=\"table table-striped\" style=\"width: 100%\"> \\\n <thead>\\\n <tr>\\\n <th>Source</th>\\\n <th>Time</th>\\\n <th>Distance</th>\\\n <th>Target</th>\\\n </tr>\\\n </thead>';\n\n _.each(routes, function(route, index){\n\n currentRoute = route;\n r360.LeafletUtil.fadeIn(routeLayer, route, 500, \"travelDistance\", { color : elevationColors[index].strokeColor, haloColor : \"#ffffff\" });\n\n html +=\n '<tr style=\"margin-top:5px;\">\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/source'+index+'.png\"></td>\\\n <td>' + r360.Util.secondsToHoursAndMinutes(currentRoute.getTravelTime()) + '</td>\\\n <td>' + currentRoute.getDistance().toFixed(2) + ' km </td>\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/target.png\"></td>\\\n </tr>'\n });\n\n html += '</table>';\n\n targetMarker.bindPopup(html);\n targetMarker.openPopup();\n }, \n function(code, message){\n\n if ( 'travel-time-exceeded' == code ) \n alert(\"The travel time to the given target exceeds the server limit.\");\n if ( 'could-not-connect-point-to-network' == code ) \n alert(\"We could not connect the target point to the network.\");\n });\n }", "function findMyNearestGardaStation() {\n //console.log(map.getBounds());\n //console.log(map.getBounds().contains(user.getLatLng()));\n //console.log(user.getLatLng().distanceTo(markers[311].getLatLng()));\n\n var closestDist = Number.MAX_SAFE_INTEGER;\n var currentDist;\n for(var i = 0; i < markers.length; i++)\n {\n currentDist = user.getLatLng().distanceTo(markers[i].getLatLng())\n if (currentDist < closestDist){\n closestIndex = i;\n closestDist = currentDist;\n }\n\n }\n markers[closestIndex].openPopup();\n\n if(map.hasLayer(route))\n map.removeLayer(route);\n}", "function displayRoute() {\r\n clearOverlays();\r\n var start\r\n var end\r\n if (inputLocation == \"\") { start = currentLocation; end = currentCafeLocation; }\r\n else { start = inputLocation; end = currentCafeLocation; }\r\n\r\n var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get \"DirectionsRendererOptions\" object\r\n directionsDisplay.setMap(map); // map should be already initialized.\r\n\r\n var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING };\r\n var directionsService = new google.maps.DirectionsService();\r\n directionsService.route(request, function (response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n }\r\n });\r\n markersArray.push(directionsDisplay);\r\n}", "function create_new_route(newPlace, handler){\n newStart = newPlace[0];\n newDest = newPlace[1];\n\n /*Create an array with all the places to visit.*/\n var places = placesVisited.slice();\n places.push(newStart);\n places.push(newDest);\n\n /*Create the request for matrix distances service.*/\n var request = {\n origins: places,\n destinations: places,\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n matrixService.getDistanceMatrix(request, function(response, status){\n if(status === google.maps.DistanceMatrixStatus.OK){\n var minDist = Number.MAX_VALUE, dijk;\n\n /*For every start, apply Dijkstra.*/\n for(var row = 0; row < response.rows.length; row += 2){\n dijk = Dijkstra(response.rows, row);\n\n /*If the returned route is the shortest one, save it.*/\n if(dijk.dist < minDist){\n minDist = dijk.dist;\n newRoute.start = response.originAddresses[dijk.start];\n newRoute.destination = response.originAddresses[dijk.dest];\n newRoute.waypoints = [];\n for(var i = 0; i < dijk.waypoints.length; i++)\n newRoute.waypoints.push({location: response.originAddresses[dijk.waypoints[i]]});\n } \n }\n /*Recall the handler.*/\n handler(minDist);\n }\n else\n alert(\"Problemi con i servizi google, assicurarsi che vi sia connessione o riprovare più tardi.\\n\\\n Errore: \" + status);\n });\n}", "function additionalPass(result, status) {\n\n // if Maps returns a valid response\n if (status == google.maps.DirectionsStatus.OK) {\n \n // initialize variable for checking if route needs any changes\n var needsCorrection = false;\n\n // iterate over legs of route\n for (var i = 0, n = result.routes[0].legs.length; i < n; i++) {\n\n var legLength = result.routes[0].legs[i].distance.value;\n\n // if leg is longer than range\n if (legLength > range) {\n\n // create new polyline for this leg\n var polyline = new google.maps.Polyline({ path: [] });\n\n // iterate over steps of the leg\n for (var j = 0, m = result.routes[0].legs[i].steps.length; j < m; j++) {\n\n // iterate over segments of step\n for (var k = 0, l = result.routes[0].legs[i].steps[j].path.length; k < l; k++) {\n\n // add segment to polyline\n polyline.getPath().push(result.routes[0].legs[i].steps[j].path[k]);\n }\n }\n \n // find point 75% of range along this line\n var nextPoint = polyline.GetPointAtDistance(0.75 * range);\n\n // get closest station to halfway point\n var newStation = getClosestStation(nextPoint);\n \n // create waypoint at that station\n var newWaypoint = {\n location: newStation.latlng,\n stopover: true\n }\n\n // add to waypoints array\n waypoints.push(newWaypoint);\n\n // add station to station stops array\n stationStops.push(newStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: stationStops[i].latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n\n // indicate that route needs correction\n needsCorrection = true;\n }\n }\n\n // if route needs correction\n if (needsCorrection == true) {\n\n // create new directions request\n var nextRequest = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n waypoints: waypoints,\n optimizeWaypoints: true\n }\n\n // send new directions request\n directionsService.route(nextRequest, function(nextResult, nextStatus) {\n\n // try again\n additionalPass(nextResult, nextStatus)\n });\n }\n\n // otherwise our route is fine as is\n else {\n\n // check for legs longer than 85% of range\n warnLong(result);\n\n // create a clickable info window for each waypoint\n createInfoWindows();\n\n // display route\n directionsDisplay.setDirections(result);\n }\n }\n \n // handle errors returned by the Maps API\n else {\n \n handleErrors(status);\n }\n}", "function parseRoutingResponse(resp) {\n\t\t\tclearRoute();\n routeLinkHashMap = new Object();\n\n // create link objects\n for (var r = 0; r < resp.response.route.length; r++) {\n for(var k = 0; k<resp.response.route[r].leg.length; k++){\n for (var m = 0; m < resp.response.route[r].leg[k].link.length; m++) {\n // only add new link if it does not exist so far - so alternatives are not drawn multiple times\n var linkId = (resp.response.route[r].leg[k].link[m].linkId.lastIndexOf(\"+\", 0) === 0 ? resp.response.route[r].leg[k].link[m].linkId.substring(1) : resp.response.route[r].leg[k].link[m].linkId);\n if (routeLinkHashMap[linkId] == null) {\n var strip = new H.geo.Strip(),\n shape = resp.response.route[r].leg[k].link[m].shape,\n i,\n l = shape.length;\n\n for (i = 0; i < l; i += 2) {\n strip.pushLatLngAlt(shape[i], shape[i + 1], 0);\n }\n\n var link = new H.map.Polyline(strip, {\n style: {\n lineWidth: (routeStroke - (r + 1)), // alternatives get smaller line with\n strokeColor: routeColor[r],\n lineCap: 'butt'\n }\n });\n link.setArrows({\n color: \"#F00F\",\n width: 2,\n length: 3,\n frequency: 8\n });\n link.$linkId = resp.response.route[r].leg[k].link[m].linkId;\n\n //The router can send back links ids with \"-\" or \"+\" prefix: only \"-\" prefix is kept and stored in this HashMap, the \"+\" is removed\n routeLinkHashMap[linkId] = link;\n legLinkHashMap[linkId] = resp.response.route[r].leg[k].link[m];\n // add event listener to link\n link.addEventListener(\"mouseover\", function(e) {\n if (currentOpenBubble)\n ui.removeBubble(currentOpenBubble);\n var html = '<div>' +\n '<p style=\"font-family:Arial,sans-serif; font-size:12px;\">LinkId: ' + e.target.$linkId + '</p>'\n '</div>';\n\n var pos = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);\n\n currentOpenBubble = new H.ui.InfoBubble(pos, {\n content: html\n });\n ui.addBubble(currentOpenBubble);\n });\n }\n }\n }\n }\n\n /**\n * draw a smooth route\n */\n for (var r = 0; r < resp.response.route.length; r++) {\n for(var k = 0; k<resp.response.route[r].leg.length; k++){\n for (var linkIdx in resp.response.route[r].leg[k].link) {\n var strip = new H.geo.Strip();\n var shape = resp.response.route[r].leg[k].link[linkIdx].shape;\n var l = shape.length;\n\n for (var i = 0; i < l; i = i + 2) {\n strip.pushLatLngAlt.apply(strip, [shape[i], shape[i + 1]].map(function(item) {\n return parseFloat(item);\n }));\n }\n var polyline = createPolylineForIndex(strip, linkIdx);\n polyline.setArrows(true);\n routingGroup.addObject(polyline);\n }\n var maneuvers = resp.response.route[r].leg[k].maneuver\n for(var i in maneuvers){\n addManueversToMap(maneuvers[i]);\n }\n }\n\t\t\t\t// Add waypoints on the map\n\t\t\t\t for(var k = 0; k<resp.response.route[r].waypoint.length; k++){\n\t\t\t\t\tvar waypoint = resp.response.route[r].waypoint[k];\n\t\t\t\t\tvar lat = waypoint.originalPosition.latitude;\n var lon = waypoint.originalPosition.longitude;\n var point = new H.geo.Point(parseFloat(lat), parseFloat(lon));\n\t\t\t\t\tvar marker = new H.map.Marker(point, { icon: createIconMarker( \"Waypoint:\"+k, waypoint.mappedRoadName,) });\n routingGroup.addObject(marker);\n\t\t\t\t }\n\t\t\t\t\n }\n\t\t\t\n\t\t\t// add tap action for maneuve markers\n\t\t\troutingGroup.addEventListener('tap', function (evt) {\n\t\t\t\tmap.setCenter(evt.target.getPosition());\n\t\t\t\tif(evt.target.instruction)\n\t\t\t\topenBubble(\n\t\t\t\t evt.target.getPosition(), evt.target.instruction);\n\t\t\t }, false);\n\t\t\t\n\t\t\tmap.addObject(routingGroup);\n\t\t\tmap.setViewBounds(routingGroup.getBounds());\n feedbackTxt.innerHTML = \"\";\n\t}", "function addRouteMarkers() {\n\n // Add start location\n map.addMarker({\n lat: startLocation[0],\n lng: startLocation[1],\n title: \"Start Location: \" + startLocation[2],\n icon: \"images/start.png\"\n });\n\n // Add end location\n if (endLocation != startLocation) {\n map.addMarker({\n lat: endLocation[0],\n lng: endLocation[1],\n title: \"End Location: \" + endLocation[2],\n icon: \"images/end.png\"\n });\n }\n\n // Add all path markers\n for (var i = 0; i < path.length; i++) {\n map.addMarker({\n lat: path[i][0],\n lng: path[i][1],\n title: path[i][2],\n icon: markers[i],\n infoWindow: {\n content: \"<p>\" + path[i][2] + \"</p><p><input onclick='search([\" + path[i][0] + \",\" + path[i][1] + \"], \\\"\\\")'\" + \" type='button' value='Search Nearby'></p>\" + \n \"<span id='marker' class='delete' onclick='cancelStopMarker(\\\"\" + path[i][2] + \"\\\")'><img src='images/cancel.png' alt='cancel' /></span>\"\n }\n });\n }\n\n fitMap();\n}", "function drivingRoute(start, end){\n\t\tdirectionsDisplay = new google.maps.DirectionsRenderer();\n\t\tvar myOptions = {\n\t\t zoom:5,\n\t\t mapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t} \n\t\tmap = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n\t\tdirectionsDisplay.setMap(map);\n\t\tvar directionsService = new google.maps.DirectionsService();\n\t\t\n\t\tvar request = {\n\t\t\t\torigin:start,\n\t\t\t\tdestination:end,\n\t\t\t\twaypoints: waypts,\n\t\t\t optimizeWaypoints: true,\n\t\t\t\ttravelMode: google.maps.DirectionsTravelMode.DRIVING\n\t\t\t};\n\t\t// calculating distance from google maps (Driving directions)\n\t\t\t\tdirectionsService.route(request, function(response, status) {\n\t\t\t\tif (status == google.maps.DirectionsStatus.OK) {\n\t\t\t\t\tdirectionsDisplay.setDirections(response);\n\t\t\t\t var route = response.routes[0];\n\t\t\t\t \n\t\t\t\t var summaryPanel = document.getElementById('1234');\n\t\t\t\t summaryPanel.innerHTML = ''; // For each route, display summary information.\n\t\t\t\t for (var i = 0; i < route.legs.length; i++) {\n\t\t\t\t var routeSegment = i + 1;\n\t\t\t\t summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +\n\t\t\t\t '</b><br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].start_address + ' to ';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].end_address + '<br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';\n\t\t\t\t if(i==0)\n\t\t\t\t \t {\n\t\t\t\t \t document.getElementById(\"distance\").value=route.legs[i].distance.value / 1000;\n\t\t\t\t \t document.getElementById(\"mySubmit\").disabled = false;\n\t\t\t\t \t }\n\t\t\t\t else\n\t\t\t\t \t dist=dist+route.legs[i].distance.value / 1000;\n\t\t\t\t }\n\t\t\t\t document.getElementById(\"distance1\").value=dist;\t\t\t\t \n\t\t\t\t }});\n\t}", "function addLocation()\r\n{\r\n let newWaypoint = currentRoute.routeMarker.getPosition();\r\n currentRoute.waypoints.push(newWaypoint);\r\n currentRoute.displayPath();\r\n}", "roadLineDrawtest()\n {\n this.direction.route({\n origin:{lng:-78,lat:39.137},\n destination:{lat:39.281,lng:-76.60},\n travelMode:google.maps.TravelMode.DRIVING\n },(r,s)=>{\n var pathPoints=r.routes[0].overview_path;\n var path=new google.maps.Polyline({\n path:pathPoints\n });\n\n path.setMap(this.map);\n });\n }", "function setupCreateNewPathwayButton() {\n var newItem;\n $(\"div[name='createNewPathway']\").click(function(){\n if ( newItem == undefined )\n newItem = \n\t\tcreateDialog(\"div.createPathway\", \n\t\t\t\t{position:[250,150], width: 700, height: 350, \n\t\t\t\ttitle: \"Create a New Pathway Analysis\"});\n $.get(\"pathway.jsp\", function(data){\n newItem.dialog(\"open\").html(data);\n\t\tcloseDialog(newItem);\n });\n });\n}", "function addPremadeRoutes() {\n layerToAdd.forEach((tablica, index) => {\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + tablica + '?geometries=geojson&steps=true&&access_token=' + mapboxgl.accessToken;\n var req = new XMLHttpRequest();\n req.responseType = 'json';\n req.open('GET', url, true);\n req.onload = function () {\n var jsonResponse = req.response;\n var coords = jsonResponse.routes[0].geometry;\n console.log(coords);\n // add the route to the map\n addRoute(coords);\n };\n req.send();\n function addRoute(coords) {\n // check if the route is already loaded\n let color = \"\";\n if (index === 0) color = '#e68580';\n if (index === 1) color = '#329999';\n if (index === 2) color = '#db9000';\n addRouteToTheMap(\"route\" + index, coords, color, 0.8);\n map.setLayoutProperty(\"route\" + index, 'visibility', 'none');\n };\n })\n }", "function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}", "function calculateAndDisplayRoute(directionsService, directionsDisplay) {\n var originLoc = getOrigin();\n\n var directionsRequest = {\n origin: originLoc,\n destination: inputs.locationTo[0].geometry.location, \n travelMode: google.maps.DirectionsTravelMode.DRIVING,\n };\n\n sendData();\n\n directionsService.route(directionsRequest, function(response, status) {\n if (status === google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n // Box the overview path of the first route\n var path = response.routes[0].overview_path;\n var boxes = rboxer.box(path, distance);\n //drawBoxes(boxes); // draws out boxes, only for debugging\n for (var i = 0; i < boxes.length; i++) {\n var bounds = boxes[i];\n // this is where we will perform search over this bounds \n restaurant_initialize(bounds);\n }\n }\n else {\n window.alert('Directions request failed due to ' + status);\n }\n });\n}", "function randomRobot(state) { \n return {direction: randomPick(roadGraph[state.place])};\n}", "function findRoute(start, end, map, opt) {\n\n var step = opt.step;\n var startPoints, endPoints;\n var startCenter, endCenter;\n\n // set of points we start pathfinding from\n if (start instanceof g.rect) {\n startPoints = getRectPoints(start, opt.startDirections, opt);\n startCenter = start.center();\n } else {\n startCenter = start.clone().snapToGrid(step);\n startPoints = [start];\n }\n\n // set of points we want the pathfinding to finish at\n if (end instanceof g.rect) {\n endPoints = getRectPoints(end, opt.endDirections, opt);\n endCenter = end.center();\n } else {\n endCenter = end.clone().snapToGrid(step);\n endPoints = [end];\n }\n\n // take into account only accessible end points\n startPoints = _.filter(startPoints, map.isPointAccessible, map);\n endPoints = _.filter(endPoints, map.isPointAccessible, map);\n\n // Check if there is a accessible end point.\n // We would have to use a fallback route otherwise.\n if (startPoints.length > 0 && endPoints.length > 0) {\n\n // The set of tentative points to be evaluated, initially containing the start points.\n var openSet = new SortedSet();\n // Keeps reference to a point that is immediate predecessor of given element.\n var parents = {};\n // Cost from start to a point along best known path.\n var costs = {};\n\n _.each(startPoints, function(point) {\n var key = point.toString();\n openSet.add(key, estimateCost(point, endPoints));\n costs[key] = 0;\n });\n\n // directions\n var dir, dirChange;\n var dirs = opt.directions;\n var dirLen = dirs.length;\n var loopsRemain = opt.maximumLoops;\n var endPointsKeys = _.invoke(endPoints, 'toString');\n\n // main route finding loop\n while (!openSet.isEmpty() && loopsRemain > 0) {\n\n // remove current from the open list\n var currentKey = openSet.pop();\n var currentPoint = g.point(currentKey);\n var currentDist = costs[currentKey];\n var previousDirAngle = currentDirAngle;\n var currentDirAngle = parents[currentKey]\n ? getDirectionAngle(parents[currentKey], currentPoint, dirLen)\n : opt.previousDirAngle != null ? opt.previousDirAngle : getDirectionAngle(startCenter, currentPoint, dirLen);\n\n // Check if we reached any endpoint\n if (endPointsKeys.indexOf(currentKey) >= 0) {\n // We don't want to allow route to enter the end point in opposite direction.\n dirChange = getDirectionChange(currentDirAngle, getDirectionAngle(currentPoint, endCenter, dirLen));\n if (currentPoint.equals(endCenter) || dirChange < 180) {\n opt.previousDirAngle = currentDirAngle;\n return reconstructRoute(parents, currentPoint);\n }\n }\n\n // Go over all possible directions and find neighbors.\n for (var i = 0; i < dirLen; i++) {\n\n dir = dirs[i];\n dirChange = getDirectionChange(currentDirAngle, dir.angle);\n // if the direction changed rapidly don't use this point\n if (dirChange > opt.maxAllowedDirectionChange) {\n continue;\n }\n\n var neighborPoint = currentPoint.clone().offset(dir.offsetX, dir.offsetY);\n var neighborKey = neighborPoint.toString();\n // Closed points from the openSet were already evaluated.\n if (openSet.isClose(neighborKey) || !map.isPointAccessible(neighborPoint)) {\n continue;\n }\n\n // The current direction is ok to proccess.\n var costFromStart = currentDist + dir.cost + opt.penalties[dirChange];\n\n if (!openSet.isOpen(neighborKey) || costFromStart < costs[neighborKey]) {\n // neighbor point has not been processed yet or the cost of the path\n // from start is lesser than previously calcluated.\n parents[neighborKey] = currentPoint;\n costs[neighborKey] = costFromStart;\n openSet.add(neighborKey, costFromStart + estimateCost(neighborPoint, endPoints));\n };\n };\n\n loopsRemain--;\n }\n }\n\n // no route found ('to' point wasn't either accessible or finding route took\n // way to much calculations)\n return opt.fallbackRoute(startCenter, endCenter, opt);\n }", "loadMapWithRoute(elem, route) {\n var centerStop = route[Math.floor(route.length/2)]; //Get the center element\n var centerLoc = new google.maps.LatLng(centerStop.lat, centerStop.lon);\n var opts = {\n mapTypeId: google.maps.MapTypeId.ROADMAP,\n zoom: 14,\n center: centerLoc,\n };\n var map = new google.maps.Map(elem, opts);\n _.forEach(route, stop => {\n //Add a marker for each stop in the route\n var loc = new google.maps.LatLng(stop.lat, stop.lon);\n new google.maps.Marker({\n map: map,\n position: loc,\n title: stop.stop_name\n });\n });\n return map;\n }", "function createSearchEngine() {\n var olsLayer= createLayer();\n var gazetteer= new Geoportal.Control.LocationUtilityService.CadastralParcel(olsLayer, {\n // force drawLocation\n drawLocation:true,\n // suffix of all fields' form - suffixe des champs du formulaire\n id:'Gazetteer',\n // place where to display results - endroit où lister les résultats\n resultDiv: OpenLayers.Util.getElement('resultsGazetteer'),\n outsideViewport:true,\n fields:{\n 'q0':'freeformparcel',\n 'c' :null,\n 's' :'search',\n 'w' :null\n },\n activate: function() {\n this.layer.selectCntrl.deactivate();\n this.layer.destroyFeatures();\n this.loadContent(OpenLayers.Util.getElement('gpSearch'));\n if (!this.layer.map) {\n this.map.addLayer(this.layer);\n }\n this.resultDiv.innerHTML= '';\n this.resultDiv.style.display= 'none';\n\n // turn auto-completion on :\n if (this.autoCompleteControl) {\n this.map.addControl(this.autoCompleteControl);\n }\n\n },\n deactivate: function() {\n this.layer.cleanQueries();\n },\n loadContent: function(form) {\n // add mapping :\n this.inputs[this.fields.q0]= OpenLayers.Util.getElement('nameGazetteer');\n this.buttons[this.fields.s]= OpenLayers.Util.getElement('searchGazetteer');\n // add listeners :\n var e= this.buttons[this.fields.s];\n OpenLayers.Event.observe(\n form,\n \"keypress\",\n OpenLayers.Function.bind(function(evt) {\n if (evt.keyCode==13 || evt.keyCode==10) {\n return this.onSearchClick.apply(this,[e,evt]);\n }\n return true;\n },this)\n );\n e.onclick= OpenLayers.Function.bind(this.onSearchClick,this,e);\n\n // turn auto-completion on :\n if (this.autoCompleteOptions) {\n this.autoCompleteControl= new Geoportal.Control.AutoComplete(\n this.inputs[this.fields.q0],\n OpenLayers.Util.extend({\n url: this.getAutoCompleteUrl(),\n type: this.countryCode\n }, this.autoCompleteOptions)\n );\n }\n\n },\n onSearchClick: function(element,evt) {\n if (evt || window.event) OpenLayers.Event.stop(evt? evt : window.event);\n \n var v= OpenLayers.String.trim(this.inputs[this.fields.q0].value);\n if (v=='') { return false; }\n var s= new Geoportal.OLS.Street();\n s.name= v;\n var sa= new Geoportal.OLS.StreetAddress();\n sa.addStreet(s);\n var a= new Geoportal.OLS.Address(this.countryCode);\n a.streetAddress= sa;\n //send request to OpenLS service :\n this.layer.GEOCODE(\n [a],\n {\n onSuccess: this.LUSSuccess,\n onFailure: this.LUSFailure,\n scopeOn: this\n });\n a.destroy()\n a= null;\n return true;\n },\n setZoom: function(f) {\n return this.map.getNumZoomLevels() - 4;\n },\n onResultClick: function(evt) {\n if (this.cntrl.map) {\n var xy= new OpenLayers.LonLat(this.feature.geometry.x, this.feature.geometry.y);\n var ll= xy.clone().transform(this.cntrl.map.getProjection(), OpenLayers.Projection.CRS84);\n var t= this.cntrl.map.catalogue.findTerritory(ll);\n if (t!==this.cntrl.map.baseLayer.territory) {\n var oMap= this.cntrl.map;\n this.feature.geometry.transform(oMap.getProjection(), OpenLayers.Projection.CRS84);\n \n var div= OpenLayers.Util.getElement(\"___$\"+currentTerritory+\"$___\");\n if (!div) {\n div= OpenLayers.getDoc().createElement(\"div\");\n div.id= \"___$\"+currentTerritory+\"$___\";\n div.style.position= \"absolute\";\n div.style.left= \"-9999px\";\n div.style.width= oMap.div.parentNode.clientWidth+\"px\";\n div.style.height= oMap.div.parentNode.clientHeight+\"px\";\n oMap.div.parentNode.appendChild(div);\n }\n oMap.render(div);\n var features= [];\n var response= this.cntrl.layer.queriedAddresses.slice();\n for (var i in response[0].features) {\n var feature= response[0].features[i].clone();\n feature.geometry.transform(oMap.getProjection(), OpenLayers.Projection.CRS84);\n features.push(feature);\n }\n this.cntrl.deactivate();\n if (territoriesViewer[t]==null) {\n viewerOptions.territory= t;\n createMap();\n var gazetteer= createSearchEngine();\n territoriesViewer[t].getMap().addControls([gazetteer]);\n gazetteer.activate();\n this.cntrl= gazetteer;\n } else {\n territoriesViewer[t].getMap().render(OpenLayers.Util.getElement('viewerDiv'));\n this.cntrl= territoriesViewer[t].getMap().getControlsByClass('Geoportal.Control.LocationUtilityService.CadastralParcel')[0];\n this.cntrl.activate();\n currentTerritory= t;\n }\n this.cntrl.layer.queriedAddresses= response;\n for (var i in features) {\n features[i].geometry.transform(OpenLayers.Projection.CRS84, this.cntrl.map.getProjection());\n }\n this.cntrl.layer.queriedAddresses[0].features= features;\n this.cntrl.LUSSuccess();//display results again !\n this.feature.geometry.transform(OpenLayers.Projection.CRS84, this.cntrl.map.getProjection());\n xy= ll.transform(OpenLayers.Projection.CRS84, this.cntrl.map.getProjection());\n }\n this.cntrl.map.setCenter(xy,this.zoom,false,false);\n xy= null;\n if (this.cntrl.drawLocation) {\n this.cntrl.layer.destroyFeatures();\n this.cntrl.layer.addFeatures([this.feature.clone()]);\n this.cntrl.layer.selectCntrl.activate();\n }\n }\n this.cntrl.onSelectLocation(this.feature);\n },\n onSelectLocation: function(f) {\n if (!f) { return; }\n this.resultDiv.innerHTML= '';//clean up\n this.resultDiv.style.display= 'none';\n this.inputs[this.fields.q0].focus();\n },\n closeForm: function() {\n this.layer.abortRequest();\n this.inputs[this.fields.q0].value= '';\n this.resultDiv.innerHTML= '';\n this.resultDiv.style.display= 'none';\n },\n\n // turn auto-completion on :\n autoCompleteOptions: {}\n\n });\n\n return gazetteer;\n}" ]
{ "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 \"SelectAll\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tselectAll();\n\t\t\t\t\t$scope.set(\"SelectAll\",false);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"InternalSelections\":\n\t\t\t\tif(eventData.slotValue != internalSelectionsInternallySetTo) {\n\t\t\t\t\tsetSelectionsFromSlotValue();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"TreatNullAsUnselected\":\n\t\t\t\tupdateLocalSelections(false);\n\t\t\t\tbreak;\n\t\t\tcase \"UsePercent\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tusePercent = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tusePercent = false;\n\t\t\t\t}\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"FontSize\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"DrawingArea:height\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"DrawingArea:width\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"root:height\":\n\t\t\t\tupdateSize();\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"root:width\":\n\t\t\t\tupdateSize();\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"UseGlobalColorGradients\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tuseGlobalGradients = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tuseGlobalGradients = false;\n\t\t\t\t}\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"PluginName\":\n\t\t\t\t$scope.displayText = eventData.slotValue;\n\t\t\t\tbreak;\n\t\t\tcase \"PluginType\":\n\t\t\t\tif(eventData.slotValue != \"VisualizationPlugin\") {\n\t\t\t\t\t$scope.set(\"PluginType\", \"VisualizationPlugin\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"GlobalSelections\":\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"Highlights\":\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"GroupColors\":\n\t\t\t\tcolorPalette = null;\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tdrawSelections();\n\t\t\t\tbreak;\n\t\t\tcase \"DataValuesSetFilled\":\n\t\t\t\tparseData();\n\t\t\t\tbreak;\n\t\t}\n\t}", "function setSlotId(event) {\n const { slotId } = event.data.payload;\n const initiator = document.getElementById('initiator');\n\n initiator.innerHTML = slotId;\n initiator.dataset.slot = slotId;\n }", "function setSlotForDragandDrop(device){\n\tvar cnt = 0;\n\tif(device.SLOT == null || device.SLOT == undefined || device.SLOT.length == 0){\n\t\tvar slotpath = device.ObjectPath+ \".\" + \"Slot_\"+cnt;\n\t\tvar slotname = \"Slot_\" + cnt;\n\t\tvar devName = (device.ObjectPath).split(\".\")[0];\n\t\tstoreSlotInformation(\"\",\"\",slotname,slotpath,\"\",\"\",\"\",\"\",\"\",device.ObjectPath,\"\",\"\",\"new\",\"\");\n\t}\n}", "function slotPortInfoShow(id,val){\n $(\".infoshowhide\").hide();//Hide content\n $(\"#infoshowhide-\"+val+\"\").show();//Show content\n for(var a=1; a<=257; a++){\n \t$(\"#slot-port-\"+a+\" li a\").css(\"color\",\"#fffff\");\n\t}\n $(\"#\"+id+\" a\").css(\"color\",\"#00000\");\n\t//$(\"#tabs-\"+val+\"-slot\").show();\n\t$(\"#tabs-\"+val+\"-slot\"+GlobalSlotId).show();\n}", "_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }", "async onAddSlot(slotId) {\n const {navigation, fetchDetailById: fetchDetailByIdLocal} = this.props;\n await fetchDetailByIdLocal(slotId);\n navigation.navigate('Detail', {\n slotId,\n });\n }", "function getSlotCount(device,slotcnt){\n\tif(device.SLOT != null && device.SLOT != undefined){\n\t\tfor(var t=0; t<device.SLOT.length; t++){\n\t\t\tvar slotpath = device.SLOT[t].ObjectPath.split(\".\");\n\t\t\tvar pathArr = slotpath[slotpath.length -1].split(\"_\");\n\t\t\tslotcnt = pathArr[1];\n\t\t}\n\t}\n\treturn slotcnt;\n}", "function transformOldSlotSyntax(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n if (_.has(child.attribs, 'slot')) {\n const vslotShorthandName = `#${child.attribs.slot}`;\n child.attribs[vslotShorthandName] = '';\n delete child.attribs.slot;\n }\n });\n}", "function portSlotContent(){\n\tvar content = \"\";\n\tvar a = conterninfor.num\n\tvar addinfo = conterninfor.str\n\tcontent += \"<table \"+addinfo+\" id='tabs-\"+a+\"-slot\"+GlobalSlotId+\"'\";\n\tcontent += \" class='infoshowhide'>\";\n\tcontent += \"<tr><td style='width: 90px;'>\";\n\tcontent += \"<p>Physical port type: <br></td><td><br>\";\n\tcontent += \"<select id='porttypeinfo\"+a+\"' \";\n\tcontent += \"data-mini='true' style='width: 150px;'>\";\n\tcontent += \"<option value=''>Layer 1</option>\";\n\tcontent += \"<option value=''>Layer 2</option>\"\n\tcontent += \"<option value=''>Open Port</option>\";\n\tcontent += \"<option value=''>Direct connect\";\n\tcontent += \"</option></select>\";\n\tcontent += \"</p><br></td><td><br><p>Media type</p><br></td>\";\n\tcontent += \"<td><br><p><select></select></p><br></td>\";\n\tcontent += \"</tr><tr><td><p>Port name: <br></td><td><br>\";\n\tcontent += \"<input id='portnamenumber\"+a+\"' \";\n\tcontent += \"type='text'/></p><br></td>\";\n\tcontent += \"</tr><tr><td style='width: 90px;'><br>\";\n\tcontent += \"<p>Sub chanel</p></td></tr></table>\";\n\treturn content\n}", "function checkSlotPortNumber(){\n\tvar ipadd = GlobalMapPort.MAINCONFIG[0].DEVICE\t\n\tvar slot = \"\";\n\tvar newslot = \"\";\n\tvar slotnumber = $(\"#partnerslot\").val();\n\tvar ports = \"\";\n\tvar port = \"\";\n\tvar portid = \"\";\n\tvar val = $(\"#partnerhostname\").val();\n\tfor (var a=0; a<ipadd.length; a++){\n\t\thost = ipadd[a].HostName\n\t\tvar ip = ipadd[a].IpAddress\n\t\tif(val == host){\n\t\t\tfor (var x=0; x<ipadd[a].SLOT.length; x++){\n\t\t\t\tnewslot = ipadd[a].SLOT[x].Number;\n\t\t\t\tif(slotnumber==newslot){\n\t\t\t\t\tfor (var z=0; z<ipadd[a].SLOT[x].PORT.length; z++){\n\t\t\t\t\t\tport = ipadd[a].SLOT[x].PORT[z].PortName\n\t\t\t\t\t\tportid = ipadd[a].SLOT[x].PORT[z].PortId\n\t\t\t\t\t\tports += \"<option value='\"+port+\"_\"+portid+\"'>\"+port+\"</option>\"\t\n\t\t\t\t\t}\n\t\t\t\t\t$(\"#partnerportinfo\").empty().append(ports);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}", "function Window_SlotInstruction() {\n this.initialize.apply(this, arguments);\n}", "function createSlots(slots, dynamicSlots) {\n for (let i = 0; i < dynamicSlots.length; i++) {\n const slot = dynamicSlots[i];\n // array of dynamic slot generated by <template v-for=\"...\" #[...]>\n if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isArray)(slot)) {\n for (let j = 0; j < slot.length; j++) {\n slots[slot[j].name] = slot[j].fn;\n }\n }\n else if (slot) {\n // conditional single slot generated by <template v-if=\"...\" #foo>\n slots[slot.name] = slot.key\n ? (...args) => {\n const res = slot.fn(...args);\n // attach branch key so each conditional branch is considered a\n // different fragment\n if (res)\n res.key = slot.key;\n return res;\n }\n : slot.fn;\n }\n }\n return slots;\n}", "slot$(name,ctx){\n\t\tvar slots_;\n\t\tif (name == '__' && !this.render) {\n\t\t\treturn this;\n\t\t}\t\t\n\t\treturn (slots_ = this.__slots)[name] || (slots_[name] = imba$1.createLiveFragment(0,null,this));\n\t}", "function drawTileSlot(ctx, style, tile_slot, tile_x_pos, tile_y_pos){\n ctx.fillStyle = style;\n tile_slot.drawSelf(ctx, tile_x_pos, tile_y_pos);\n}", "function dynamicSlotTab(num,id,name,limit,type){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\tif (type ==\"slotport\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"slotinfoshow('\"+id+a+\"','\"+a+\"','slotport')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t\t}else if (type==\"slotmodule\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"slotinfoshow('\"+id+a+\"','\"+a+\"','slotmodule')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\n\t\t}\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n\n\n}", "function updateSlotDisplays(player){\n\t\tdocument.getElementById(\"header\").innerHTML = \n\t\t\t\t\t\"<h3>3-of-a-Kind Slot-o-Rama</h3>\" + \n\t\t\t\t\t\"<h4>$\" + payout + \" per credit bet<br>\" +\n\t\t\t\t\t\"Max bet = \" + multiplierMax + \" credits</h4>\";\n\t\tdocument.getElementById(\"credit_cost\").innerHTML = \"<b>$\" + creditCost + \"</b><br>per credit\";\n\t\tdocument.getElementById(\"recent_win_payout\").innerHTML = \"Recent Win Payout:<br><b>$\" + recentWinPayout + \"</b>\";\n\t\tdocument.getElementById(\"previous_turn_payout\").innerHTML = \"Previous Turn Payout:<br><b>$\" + previousTurnPayout + \"</b>\";\n\t\tdocument.getElementById(\"current_bet\").innerHTML = \"Current Bet:<br><b>\" + multiplier + \" credit</b>\";\n\t\tif (player) {\n\t\t\tdocument.getElementById(\"balance\").innerHTML = \"Balance:<br><b>$\" + player.getBalance().toFixed(2) + \"</b>\";\t\n\t\t}\n\t\toutputResults();\n\t}", "function slotsChange(e) {\n\t\tlet i= this.id.substring(this.id.indexOf('.')+1);\n\t\t\n\t\t//Otherwise, they are still treated as strings and will run into trouble in double digits.\n\t\tlet oldSlots= parseInt(aSlots[i]);\n\t\tlet newSlots= parseInt(this.value);\n\t\t\n\t\tif (newSlots < oldSlots) {\n\t\t\t//Need to remove some slots! Start from the top.\n\t\t\tfor (let j = oldSlots-1; j >= newSlots; j--) {\n\t\t\t\t\n\t\t\t\tlet obj= oSkills[i][j];\n\t\t\t\tlet span= obj.parentNode;\n\t\t\t\tlet par= span.parentNode;\n\t\t\t\tpar.removeChild(span);\n\t\t\t\t\n\t\t\t\t//If this was a multiple of 3 -- and thus, the first on a new line -- remove the BRs as well.\n\t\t\t\tif ((j%3) == 0) {\n\t\t\t\t\t//Save the now-last child.\n\t\t\t\t\tlet lastChild= par.children[par.children.length-1];\n\t\t\t\t\t// If the now-last child element is a br...\n\t\t\t\t\tif (lastChild.toString() == \"[object HTMLBRElement]\") {\n\t\t\t\t\t\t//Remove it.\n\t\t\t\t\t\tpar.removeChild(lastChild);\n\t\t\t\t\t}\n\t\t\t\t\t//Remove the second one, too.\n\t\t\t\t\tlastChild= par.children[par.children.length-1];\n\t\t\t\t\t// If the now-last child element is a br...\n\t\t\t\t\tif (lastChild.toString() == \"[object HTMLBRElement]\") {\n\t\t\t\t\t\t//Remove it.\n\t\t\t\t\t\tpar.removeChild(lastChild);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (newSlots > oldSlots) {\n\t\t\t//Need to add some slots!\n\t\t\tfor (let j = oldSlots; j < newSlots; j++) {\n\t\t\t\t//Get the parent object.\n\t\t\t\tlet par= O(`skillboxes.${i}`);\n\t\t\t\t\n\t\t\t\tmakeNewSkill(par,i,j);\n\n\t\t\t}\n\t\t}\n\t\taSlots[i]= this.value;\n\t\t\n\t\t//Check for repeat skills and run the update functions.\n\t\tcheckForRepeatSkills();\n\t\tupdateUnused();\n\t\tupdateSP();\n\t}", "function getStashValidSlotsAndFrameId(stashSlotId, results) {\r\n\tvar stashItemSpan = $(\"#stashSlot\"+stashSlotId+\" > .itemDrop\");\r\n\tif(stashItemSpan.length < 1) return;\r\n\tvar stashFrameSpanId = stashItemSpan.attr('id');\r\n\tvar regex1 = /^[^\\d]+([\\d]+)$/;\r\n\tresults.stashFrameId = stashFrameSpanId.match(regex1)[1];\r\n\tvar compareSpan = $(\"#lb_charslot_emptyStash\"+results.stashFrameId);\r\n\tif(compareSpan.length < 1) {\r\n\t compareSpan = $(\"[id^=lb_charslot_][id$=equipmentstashFrame\"+results.stashFrameId+\"]\");\r\n\t results.empty = false;\r\n\t} else {\r\n\t\tresults.empty = true;\r\n\t}\r\n\tif(compareSpan.length < 1) return;\r\n\tvar compareClasses = compareSpan.attr('class');\r\n\tvar regex2 = /charslot_([\\d]+)/g;\r\n\tvar match = regex2.exec(compareClasses);\r\n\tresults.validSlots = \"[\";\r\n\tvar seperator = \"\";\r\n\twhile (match != null) {\r\n\t\tvalidSlot = match[1];\r\n\t\tresults.validSlots += seperator + validSlot;\r\n\t\tseperator = \",\";\r\n\t match = regex2.exec(compareClasses);\r\n\t}\r\n\tresults.validSlots += \"]\";\r\n}" ]
{ "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 = 890;\n let scaledHeight = 300;\n\n switch (textStyle) {\n case 1:\n scaledWidth = Math.max(getTextWidth(primaryText, \"bold 120px Metropolis,Arial\"), getTextWidth(secondaryText, \"bold 120px Metropolis,Arial\"));\n if (scaledWidth < 800) {\n scaledWidth = 800;\n }\n if (secondaryText === \"\") {\n scaledHeight = 450;\n } else {\n scaledHeight = 600;\n }\n break;\n\n default:\n scaledWidth = 800;\n scaledHeight = 300;\n }\n\n let width = Math.round(scaledWidth * scale);\n let height = Math.round(scaledHeight * scale);\n if (width % 2 !== 0) {\n width += 1;\n }\n if (height % 2 !== 0) {\n height += 1;\n }\n\n if (displaySize) {\n let dimension_icon = document.getElementById('dimensions-icon');\n dimension_icon.textContent = \"(Size: \" + size + \"x\" + size + \") \";\n\n let dimension_symbol = document.getElementById('dimensions-symbol');\n dimension_symbol.textContent += \"(Size: \" + height + \"x\" + width + \") \";\n }\n\n return [height, width]\n}", "function get_font_size(obj)\n {\n // Standard way:\n if(window.getComputedStyle)\n return window.getComputedStyle(obj, \"\").getPropertyValue(\"font-size\");\n\n // MS IE way:\n if(obj.currentStyle)\n return obj.currentStyle.fontSize;\n\n return \"16px\";\n }", "calcCompFontSize(num) {\n // num is the main display size in digits\n const d1 = 4; // minimum display size\n const d2 = 32; // maximum display size\n const f1 = 10; // minimum font size\n const f2 = 30; // maximum font size\n let f = f1 + (d2 - num) * ((f2 - f1) / (d2 - d1));\n f = f.toFixed(1);\n f = parseFloat(f, 10);\n // store the font size in variable\n runText.fontSizeComp = `${f}px`;\n }", "function fontSize(d) {\n d.fontsize = Math.floor(d.radius/3);\n return d.fontsize + \"px\";\n }", "function textWidth(txt,fontHeight) {\n var w;\n var sx = canvas.width / 2;\n var sy = canvas.height / currentBlock.getHeight();\n var fontSz = fontHeight * sy;\n\n ctx.save();\n ctx.scale(1/sx,1/sy);\n ctx.font = fontSz + \"px \" + DEFAULT_FONT;\n w = ctx.measureText(txt).width;\n ctx.restore();\n\n return w / sx;\n }", "function setUpTextDimensions() {\n // isFirefox(): checks for Firefox-ness of the browser.\n // Why? Because we have to adjust SVG font spacing for Firefox's\n // sake.\n // It would be better if SVG-font-sizing differences were detectable\n // directly, but so far I haven't figured out how to test for just\n // that, so we check for Firefox. (Many use 'InstallTrigger' to\n // check for FF, but that's been deprecated.)\n function isFirefox() {\n return navigator\n && /firefox/i.test(\n navigator.userAgent || navigator.vendor || ''\n );\n }\n\n // First, how big are an em and an ex in the current font, roughly?\n const emSize = measureText('m', 'em'),\n boundingBoxH = emSize.h, // (same for all characters)\n emW = emSize.w,\n // The WIDTH of an 'x' is a crude estimate of the x-HEIGHT, but\n // it's what we have for now:\n exH = measureText('x', 'ex').w,\n // Firefox has unique SVG measurements in 2022, so we look for it:\n browserKey = isFirefox() ? 'firefox' : '*',\n metrics\n = fontMetrics[browserKey][cfg.labels_fontface]\n || fontMetrics[browserKey]['*'],\n m = {\n dy: metrics.dy * boundingBoxH,\n top: metrics.top * exH,\n bot: metrics.bot * exH,\n inner: metrics.inner * emW,\n outer: metrics.outer * emW,\n };\n // Compute the remaining values (which depend on values above).\n // lblMarginAfter = total margin to give a label when it is after a node\n // (Note: this value basically includes m.inner)\n // lblMarginBefore = total margin when label is before a node\n m.lblMarginAfter\n = (cfg.node_border / 2) + metrics.marginRight * m.inner;\n m.lblMarginBefore\n = (cfg.node_border / 2)\n + (metrics.marginRight + metrics.marginAdjLeft) * m.inner;\n return m;\n }", "getFontSize() {\n return (this.props.cellSizeInPx / 2.77) + 'px';\n }", "fontMetrics() {\n if (!this._fontMetrics) {\n this._fontMetrics = getGlobalMetrics(this.size);\n }\n\n return this._fontMetrics;\n }", "getCharWidth() {\n var el = document.createElement( 'span' );\n el.style.opacity = 0;\n el.innerHTML = 'm';\n this.parent.appendChild( el );\n var fontWidth = el.offsetWidth;\n this.parent.removeChild( el );\n return fontWidth;\n }", "function scaleTextSize(ts)\n{\n // The textSize is dynamically computed based on the number of items ;)\n // Make the text the biggest possible but make sure everything fits inside the canvas\n textSize(ts);\n\n // Horizontally we have to leave minimum 25% of the space for the arrow\n if (tListStart[1] + items.length*ts > canvas_size[1] || tListStart[0] + getMaxWidth(items) > 0.75*canvas_size[0])\n {\n return scaleTextSize(ts-1)\n }\n else\n {\n return ts;\n }\n}", "function increaseFontSize() {\n gMeme.currText.size += 3\n}", "getTextMetrics()\n\t{\n\t\tif (typeof this._textMetrics === \"undefined\")\n\t\t{\n\t\t\tthis._textMetrics = PIXI.TextMetrics.measureText(this._text, this._getTextStyle());\n\t\t}\n\n\t\treturn this._textMetrics;\n\t}", "function canvas_set_font(ctx, size, monospaced) {\n var s = window.getComputedStyle(onscreen_canvas);\n // First set something that we're certain will work. Constructing\n // the font string from the computed style is a bit fragile, so\n // this acts as a fallback.\n ctx.font = `${size}px ` + (monospaced ? \"monospace\" : \"sans-serif\");\n // In CSS Fonts Module Level 4, \"font-stretch\" gets serialised as\n // a percentage, which can't be used in\n // CanvasRenderingContext2d.font, so we omit it.\n ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +\n (monospaced ? \"monospace\" : s.fontFamily);\n}", "function resizeText(pixels) {\r\n\r\n}", "function getFontPreferences() {\n\t\treturn withNaturalFonts((document, container) => {\n\t\t\tconst elements = {}\n\t\t\tconst sizes = {}\n\t\t\t// First create all elements to measure. If the DOM steps below are done in a single cycle,\n\t\t\t// browser will alternate tree modification and layout reading, that is very slow.\n\t\t\tfor (const key of Object.keys(presets)) {\n\t\t\t\tconst [style = {}, text = defaultText] = presets[key]\n\t\t\t\tconst element = document.createElement('span')\n\t\t\t\telement.textContent = text\n\t\t\t\telement.style.whiteSpace = 'nowrap'\n\t\t\t\tfor (const name of Object.keys(style)) {\n\t\t\t\t\tconst value = style[name]\n\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\telement.style[name] = value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telements[key] = element\n\t\t\t\tcontainer.appendChild(document.createElement('br'))\n\t\t\t\tcontainer.appendChild(element)\n\t\t\t}\n\t\t\t// Then measure the created elements\n\t\t\tfor (const key of Object.keys(presets)) {\n\t\t\t\tsizes[key] = elements[key].getBoundingClientRect().width\n\t\t\t}\n\t\t\treturn sizes\n\t\t})\n\t}", "function sizeShouldReturnDimensionsForElementWithMargin() {\n const data = element.size(fixture.el.querySelector(\".size\"))\n expect(data)\n .toEqual({\n width: 100,\n height: 100\n })\n}", "_getTextMetrics(text) {\n var textSpan = document.createElement('span');\n textSpan.id = 'content-span';\n textSpan.innerHTML = text;\n\n var block = document.createElement(\"div\");\n block.id = 'content-block';\n block.style.display = 'inline-block';\n block.style.width = '1px';\n block.style.height = '0px';\n\n var div = document.createElement('div');\n div.appendChild(textSpan);\n div.appendChild(block);\n div.style.font = this.fontSize + 'px ' + this.fontName;\n\n var body = document.body;\n body.appendChild(div);\n\n var ascent = -1;\n var descent = -1;\n var height = -1;\n\n try {\n block.style['vertical-align'] = 'baseline';\n ascent = block.offsetTop - textSpan.offsetTop;\n block.style['vertical-align'] = 'bottom';\n height = block.offsetTop - textSpan.offsetTop;\n descent = height - ascent;\n } finally {\n document.body.removeChild(div);\n }\n\n return {\n ascent: ascent,\n descent: descent,\n height: height\n };\n }", "__getSize(node) {\n const sizeClass = this.__getClassStartingWith(node, 'fs');\n const fontSize = this.__parseCSSValueToInt(\n cssTree[`.${sizeClass}`]['font-size']\n );\n return fontSize;\n }", "_restyleCanvas() {\n this._canvas.getContext('2d').font = \"\".concat(BubbleStyle.FONT_SIZE, \"px \").concat(BubbleStyle.FONT, \", sans-serif\");\n }" ]
{ "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 easing = 'easeOutExpo';\n var $overlay = $('#modals .overlay');\n var $modal = $('#modals .modal');\n if (!$modal.hasClass('velocity-animating')) {\n $('body').addClass('prevent-scroll'); // prevent users from scrolling the content behind the modal\n $('#modals').show();\n checkModalCentre();\n $overlay.velocity('stop').velocity({\n opacity: 1\n }, speed, easing);\n $modal.velocity('stop').velocity({\n translateY: ['0%', '10%'],\n scale: [1, 0.9]\n }, speed, easing);\n }\n}", "get modalClass() {\n return `slds-modal slds-modal_medium ${\n this.isModalOpen ? \"slds-fade-in-open\" : \"\"\n }`;\n }", "function revealLyrics(title, lyrics) {\r\n qs(\"#modal h2\").innerText = title;\r\n qs(\"#modal p\").innerText = lyrics;\r\n $(\"modal\").classList.remove(\"hidden\");\r\n }", "function removeAnim() {\n let removeStartAnim = (document.getElementById(\n \"slideAnimStart\"\n ).style.display = \"none\");\n content.style.visibility = \"hidden\";\n\n // display second layer of animation ONLY if the first layer has been removed\n if (removeStartAnim) {\n animEnd.style.display = \"block\";\n }\n}", "function hideStrokeAnim() {\n zdStrokeAnim.kill();\n $(\"#soaBox\").css(\"display\", \"none\");\n zdPage.modalHidden();\n }", "function fadeOutSkills() {\n\n skillContent.fadeOut(500);\n\n skillContainer.fadeOut(500, () => {\n\n skillContainer.removeClass('col-lg-5');\n\n skillContainer.addClass('col-lg-12');\n\n for (let i = 0; i < skills.length; i++) {\n\n $(skills[i]).css(styles[i]);\n\n }\n\n skillContainer.fadeIn(500);\n\n });\n\n skillPicker = true;\n\n}", "function FadeInTransition() {}", "function introAnimation() {\n introMenu.animate({\n opacity: 0\n }, 1000, function() {\n introMenu.hide();\n info.show();\n info.animate({\n opacity: 1\n }, 1000);\n });\n}", "function showInstructions()\n{\n $(\"#instructions_modal\").modal();\n}", "function animationCollapsed() {\n APPLICATION_STATE = 'collapsed';\n\n cleanupDots();\n\n audioManager.addTrack(currentTrack);\n removeEventListeners();\n }", "function toggleSignupModal() {\n signup_modal.classList.toggle(\"show-modal\");\n}", "static revealSongPanel() {\n let self = Settings.current;\n if (!self.songMenuLocked) {\n document.getElementById(\"songmenusidebar\").toggleAttribute(\"open\", true);\n var _a = function () {\n if (!self.songMenuLocked) {\n document.getElementById(\"songmenusidebar\").toggleAttribute(\"open\", false);\n }\n document.getElementById(\"songmenusidebar\").removeEventListener(\"mouseover\", _a);\n };\n document.getElementById(\"songmenusidebar\").addEventListener(\"mouseover\", _a);\n }\n }", "function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}", "function _showEmployeelessDepartmentModal() {\r\n $employeelessDepartmentModal = $(\"#employeelessDepartmentModal\");\r\n $employeelessDepartmentModal.css(\"margin-top\", Math.max(0, ($(window).height() - $employeelessDepartmentModal.height()) / 2));\r\n $employeelessDepartmentModal.modal('show');\r\n }", "function SlideVerticallyTransition() {}", "slideNext() {\n super.slideNext();\n this.slides[this.lastSlide].style.opacity = 0;\n this.slides[this._index].style.opacity = 1;\n }", "function fadeInSkills(clickedItem) {\n\n skillContainer.fadeOut(500, () => {\n\n skillContainer.removeClass('col-lg-12');\n\n skillContainer.addClass('col-lg-5');\n\n for (let i = 0; i < skills.length; i++) {\n\n $(skills[i]).attr('style', '');\n\n }\n\n clickedZIndex = clickedItem.css('z-index');\n\n clickedLeftPosition = clickedItem.css('left');\n\n clickedTopPosition = clickedItem.css('top');\n\n clickedItem.css({\n\n top: firstTopPozition,\n\n left: firstLeftPozition,\n\n zIndex: firstZIndedx\n\n });\n\n $('#skill1').css({\n\n top: clickedTopPosition,\n\n left: clickedLeftPosition,\n\n zIndex: clickedZIndex\n\n });\n\n var itemID = clickedItem.attr('id');\n\n skillContent.html(skillsDescription[itemID].desc);\n\n skillContainer.fadeIn(500);\n\n skillContent.fadeIn(500);\n\n });\n\n skillPicker = false;\n\n}", "function modalOut() {\n interval = setInterval(fadeOut, 7);\n}" ]
{ "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 = pts;\n\t\tpointTotals.push(team);\n\t}\n\telse\n\t{\n\t\tteamObj.points += pts;\n\t\treturn teamObj;\n\t}\n}", "async handleNewSearch(result) {\n const newLocation = {\n latitude: result.result.center[1],\n longitude: result.result.center[0]\n }\n setLSLocation(newLocation)\n\n try {\n await this.props.getMyLocationArt(newLocation)\n await this.props.getUserLocation(newLocation)\n } catch (error) {\n console.error('could not retrieve all artworks')\n }\n this.setState({\n viewport: {\n latitude: this.props.location.latitude,\n longitude: this.props.location.longitude,\n width: '100vw',\n height: '100vh',\n zoom: 13\n },\n artworks: this.props.artNearMe\n })\n this.handleGeocoderViewportChange(this.state.viewport)\n }", "function resultUpdate() {\n\n\t\t$.each(results, function(test, value) {\n\t\t\tif(typeof allTotal === 'number') {\n\t\t\t\t$.each(folders, function(index, folder) {\n\t\t\t\t\tif (test == folder) {\n\t\t\t\t\t\tallTotal = allTotal + parseInt(value);\n\t\t\t\t\t}\n\t\t\t\t});\t\n\t\t\t}\n\n\t\t\tif($('#'+test+'Result').length) {\n\t\t\t\t$('#'+test+'Result').html(value);\n\t\t\t} else {\n\t\t\t\t$('.'+test+'Result').html(value);\n\t\t\t}\n\n\t\t\t\n\t\t});\n\n\t\tif (allTotal) {\n\t\t\t$('#allResult').html(allTotal);\n\t\t}\n\t\tallTotal = null;\n\t}", "function updatePlacesLocationInformation() {\n\tupdatePlacesLocationInformationFromCategory(\"\", \"All Categories\");\n}", "function addToCache() {\n var lat = tempResults[0].geometry.location.lat();\n var lng = tempResults[0].geometry.location.lng();\n var nickname = document.getElementById(\"nickname\").value;\n var formattedAddress = tempResults[0].formatted_address\n if (nickname == \"\") {\n nickname = formattedAddress;\n }\n var locationCacheInstance = new LocationWeatherCache();\n locationCacheInstance.addLocation(lat, lng, nickname);\n \n \n}", "set result(newResult) {\n this._result = newResult;\n setValue(`cmi.interactions.${this.index}.result`, newResult);\n }", "setResult(result) {\n console.log('result: ', result);\n if (null != this.config.getCacheHook()) {\n this.data = this.config.getCacheHook().put(result);\n }\n else {\n this.data = result;\n }\n }", "function getGooglePlacesData2(results, status) {\n //\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n //\n for (var i = 0, l = results.length; i < l; i++) {\n //\n placesObj = {\n id: \"\",\n name: \"\",\n status: \"\",\n openNow: \"\",\n rating: \"\",\n userRatingTotal: \"\",\n priceLevel: \"\",\n photos: [],\n types: [],\n };\n //\n // Place data\n //\n placesObj.id = results[i].place_id;\n placesObj.name = results[i].name;\n placesObj.status = results[i].business_status;\n // placesObj.openNow = results[i].opening_hours.isOpen;\n placesObj.rating = results[i].rating;\n placesObj.userRatingTotal = results[i].user_ratings_total;\n placesObj.priceLevel = results[i].price_level;\n //\n // Photos\n //\n for (var j = 0, m = results[i].photos.length; j < m; j++) {\n //\n photoObj = {\n url: \"\",\n };\n //\n photoObj.url = results[i].photos[j].html_attributions[0];\n //\n placesObj.photos.push(photoObj);\n //\n }\n //\n // Types\n //\n for (var k = 0, n = results[i].types.length; k < n; k++) {\n //\n typeObj = {\n name: \"\",\n };\n //\n typeObj.name = results[i].types[k];\n //\n placesObj.types.push(typeObj);\n //\n }\n //\n places.push(placesObj);\n //\n }\n //\n renderGooglePlacesData();\n //\n }\n //\n}", "function updateSpaceInJive(res, accountData, accountValues, spaceId, callback) {\n\n var updatedOptions = {\n url: jiveLoginUrl + '/api/core/v3/places/' + spaceId + '',\n method: 'PUT',\n headers: headers,\n body: {\n \"Description\": accountData.Description\n }\n };\n console.log(updatedOptions.url);\n if (accountData.placeType == \"group\") {\n updatedOptions.body.groupType = \"OPEN\";\n }\n else if (accountData.placeType == \"project\") {\n\n\n accountData.startDate = new Date(accountData.startDate);\n\n accountData.startDate = accountData.startDate.toISOString();\n\n\n accountData.dueDate = new Date(accountData.dueDate);\n\n accountData.dueDate = accountData.dueDate.toISOString();\n\n insertionOptions.body.parent = accountData.parent;\n insertionOptions.body.startDate = accountData.startDate;\n insertionOptions.body.dueDate = accountData.dueDate;\n }\n accountData.mapping.forEach(function (result) {\n updatedOptions.body[result.jiveField] = accountValues[result.salesforceField];\n\n });\n\n updatedOptions.body = JSON.stringify(updatedOptions.body);\n console.log(\"updated options\", updatedOptions);\n request(updatedOptions, function (error, response, data) {\n console.log(error);\n console.log(data);\n\n console.log(error);\n console.log(data);\n if (!error && response.statusCode == 200) {\n data = JSON.parse(data);\n accountLogs.push({\n \"message\":\"Place Updated in jive \",\n \"placeId\": spaceId,\n \"accountId\":accountValues.Id,\n \"status\" : \"Success\",\n \"timestamp\": new Date()\n });\n updateNavigationSettingsOfSpace(res, accountData, data.placeID, callback);\n\n }\n else{\n\n accountLogs.push({\n \"message\": data,\n \"placeId\": 0,\n \"accountId\":accountValues.Id,\n \"status\" : \"Updation Failure\",\n \"timestamp\": new Date()\n });\n callback(null);\n }\n\n\n\n });\n\n\n}", "function searchPlace(){\n var search = new google.maps.places.PlacesService(map);\n var request = {\n keyword: [searchType],\n location: map.getCenter(),\n rankBy: google.maps.places.RankBy.DISTANCE\n }\n search.nearbySearch(request, function(data, status){\n if(status == google.maps.places.PlacesServiceStatus.OK){\n loc = data[0].name;\n add = data[0].vicinity;\n rating = data[0].rating;\n latitude = data[0].geometry.location.k;\n longitude = data[0].geometry.location.D;\n\n var placeLoc = data[0].geometry.location;\n var marker = new google.maps.Marker({ map: map, position: data[0].geometry.location});\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(data[0].name);\n infowindow.open(map, this); //google\n });\n // var loc = data[0].place_id;\n\n }\n });\n\n}", "addResult(result){\n this.results.push(result.state);\n }", "function placeSearch(lat, lng) {\n var query = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\" + lat + \",\" + lng + \"&radius=50000&type=park&keyword=kyak&key=AIzaSyDAhGg64lKOYPK-6jEMFKqQlc2TSTHTI2M\";\n\n $.ajax({\n url: query,\n method: \"GET\"\n }).done(function(response) {\n console.log(response);\n var placeId = response.results[0].place_id;\n console.log(placeId);\n\n placeDetail(placeId);\n });\n}", "function getAllPlacesByState(states, result, callback) {\n\t\n\tvar items_processed = 0;\n\tif (states.length !== 0) {\n\t\t\tstates.map( (state_id) => { \n\n\t\t\t\treqStates(`${API_URL}/states/${state_id}/places`, (json) => {\n\t\t\t\t\titems_processed++;\n\t\t\t\t\tconst places = new Schema('places');\n\t\t\t\t\tlet norm_json = normalize(json, arrayOf(places));\n\t\t\t\t\tconsole.log(\"ta\", norm_json.entities);\n\t\t\t\t\tObject.assign(result.places, norm_json.entities.places);\n\t\t\t\t\tif (items_processed === states.length) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\tcallback();\n\t\t}\n}", "addToRef(otherVector, result) {\n return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }", "_placeChange() {\n if (DEBUG) {\n console.log('[*] ' + _name + ':_placeChange ---');\n }\n\n // Store place in LocalStoreApi\n LocalStoreApi.setItem('place', getPlaceState());\n\n this.setState({\n place: getPlaceState()\n });\n }", "function addResult( $result ) {\n\t\tif ( Util.elementCount( $result ) === 0 ) { return };\n\t\t$results = $results.add( $result );\n\t}", "function geocoder(state) {\n geocoder = new google.maps.Geocoder();\n\n geocoder.geocode( { 'address': state}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n\n var lat = results[0].geometry.location.lat();\n var lng = results[0].geometry.location.lng();\n dispLoc = results[0].formatted_address;\n var placeID = results[0].place_id;\n console.log(dispLoc);\n console.log(placeID);\n\n placeSearch(lat, lng);\n\n console.log(\"lat: \"+lat+\" lng: \"+ lng);\n console.log(results);\n }\n else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n\n}" ]
{ "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[0] = p1;\n swapping[1] = p2;\n\n for (var p of swapping) {\n if ((p.pos.x < 400) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((p.pos.x < 400) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((400 < p.pos.x) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(805, yval));\n }\n } else if ((400 < p.pos.x) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(805, yval));\n }\n }\n }\n\n swapInterval = setInterval( function() {\n court.animatePlayerSwap();\n }, 20 );\n } else {\n this.draw();\n\n var moved = 0;\n for (var p of swapping) {\n moved += p.takeStep();\n }\n\n if (moved <= 0) {\n clearInterval(swapInterval);\n }\n }\n }", "function switchPlayers() {\r\n if (currentPlayer == \"p1\") {\r\n currentPlayer = \"p2\";\r\n $(\"h1\").removeClass(\"p1T\");\r\n $(\"h1\").addClass(\"p2T\");\r\n // $(\"playerInd\").addClass(\"srb\");\r\n $(\".button\").removeClass(\"element-animation\");\r\n } else {\r\n currentPlayer = \"p1\";\r\n $(\"h1\").removeClass(\"p2T\");\r\n $(\"h1\").addClass(\"p1T\");\r\n $(\".button\").removeClass(\"element-animation1\");\r\n }\r\n }", "function swapPieces(face, times) {\n\tfor (var i = 0; i < 6 * times; i++) {\n\t\tvar piece1 = getPieceBy(face, i / 2, i % 2),\n\t\t\t\tpiece2 = getPieceBy(face, i / 2 + 1, i % 2);\n\t\tfor (var j = 0; j < 5; j++) {\n\t\t\tvar sticker1 = piece1.children[j < 4 ? mx(face, j) : face].firstChild,\n\t\t\t\t\tsticker2 = piece2.children[j < 4 ? mx(face, j + 1) : face].firstChild,\n\t\t\t\t\tclassName = sticker1 ? sticker1.className : '';\n\t\t\tif (className)\n\t\t\t\tsticker1.className = sticker2.className,\n\t\t\t\tsticker2.className = className;\n\t\t}\n\t}\n}", "function playPlayerVsComputer(){\n setPlayerVsPlayer({\n AI:true,\n AImove:false\n });\n }", "function swap(x1, y1, x2, y2, callback) {\n var tmp, swap1, swap2, //modified on p.246\n events = []; //modified on p.246\n\n //p.246\n swap1 = {\n \ttype : \"move\",\n \tdata : [{\n \t\ttype: getJewel(x1, y1),\n \t\tfromX : x1, fromY : y1, toX : x2, toY : y2 \n \t}, {\n \t\ttype: getJewel(x2, y2),\n \t\tfromX: x2, fromY: y2, toX: x1, toY: y1 \n \t}]\n };//end of swap1\n\n swap2 = {\n \ttype: \"move\",\n \tdata: [{\n \t\ttype: getJewel(x2,y2),\n \t\tfromX: x1, fromY:y1, toX: x2, toY: y2\n \t}, {\n \t\ttype: getJewel(x1,y1),\n \t\tfromX: x2, fromY: y2, toX: x1, toY: y1 \n \t}]\n };\n\n if (isAdjacent(x1, y1, x2, y2)) {\n \tevents.push(swap1);\n\n \tif (canSwap(x1, y1, x2, y2)) {\n\n // swap the jewels\n tmp = getJewel(x1, y1);\n jewels[x1][y1] = getJewel(x2, y2);\n jewels[x2][y2] = tmp;\n\n events = events.concat(check());\n } else {\n \tevents.push(swap2, {type: \"badswap\"});\n }\n /*\n // check the board and get list of events\n events = check();\n\t\t*/\n callback(events);\n /*} else {\n callback(false);\n */\n }\n }", "function swapGun()\n{\n let tmp = gun;\n selectGun(prevGun);\n prevGun = tmp;\n}", "setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }", "function swap(x1, y1, x2, y2, callback) {\n var temp, events;\n\n if (canSwap(x1,y1,x2,y2)) {\n // swap the jewels\n temp = getJewel(x1,y1);\n jewels[x1][y1] = getJewel(x2,y2);\n jewels[x2][y2] = temp;\n\n // Check the board and get list of events\n events = check();\n\n callback(events);\n } else {\n callback(events);\n }\n }", "swap() {\n const { top, stack } = this;\n const tmp = stack[top - 2];\n\n stack[top] = stack[this.top];\n stack[this.top] = tmp;\n }", "function merge(p1, p2) {\n var newWidth = 2 * Math.sqrt(Math.pow(currentPlayer.width, 2) / 2)\n if(isXYCoordClear(p1.x, p1.body.bottom - newWidth, newWidth)) {\n var scale = newWidth / originalSize;\n p1.scale.setTo(scale, scale);\n p1.body.y -= newWidth / 2\n players.remove(p2);\n if(currentPlayer === p1 || currentPlayer === p2) {\n currentPlayer = p1;\n GeometrySplit.game.camera.follow(p1);\n currentPlayer.animations.play('current', 8, true);\n }\n } else if(currentPlayer === p1 || currentPlayer === p2) {\n setLocks(p1, p2);\n }\n}", "function positionTanks() {\r\n var divisionSize = stageXblocks / playerTanks.length;\r\n for (var i in playerTanks) {\r\n var xPosition = (i * divisionSize) + (divisionSize / 2);\r\n xPosition = (xPosition <= stageXblocks / 2) ? Math.floor(xPosition) : Math.ceil(xPosition);\r\n playerTanks[i].x = xPosition * landBlockSize;\r\n playerTanks[i].y = stageYdimens - (blocks[xPosition].length * landBlockSize);\r\n }\r\n}", "function swapCoordinateValues(coordinateA, coordinateB){\n\t\tlet temp = arr[coordinateA.x][coordinateA.y];\n\t\tarr[coordinateA.x][coordinateA.y] = arr[coordinateB.x][coordinateB.y];\n\t\tarr[coordinateB.x][coordinateB.y] = temp;\n\t}", "function play() {\n\n\n\t\tvar winner = war(card1, card2 )\n\n\n\n\t\tif (winner === \"player2\") {\n\t\t\tcards_player_2.push(card1, card2);\n\t\t} else if (winner === \"player1\") {\n\t\t\tcards_player_1.push(card1, card2);\n\t\t}else {\n\t\t\tcards_player_1.push(card1);\n\t\t\tcards_player_2.push(card2);\n\t\t}\n\t\t}", "movePiece(p_index, t_index) {\n // Pull variables out of loop to expand scope\n let piece = null;\n let o_tile = null;\n let t_tile = null;\n\n // Look for old and new tiles by index\n for (let line of this.board) {\n for (let tile of line) {\n if (tile.index === p_index) {\n // Grap piece and old tile\n piece = tile.piece;\n o_tile = tile;\n }\n if (tile.index === t_index) {\n // Grab target tile\n t_tile = tile;\n }\n }\n }\n\n // Only move piece if old tile has one to move and move id valid\n // Make sure you can't take out your own pieces\n if (o_tile.piece && t_tile.valid) {\n if (o_tile.piece.color === this.turn) {\n if (t_tile.piece) {\n if (o_tile.piece.color !== t_tile.piece.color) {\n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n } else { \n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n }\n }\n\n // Reset all valid tags\n for (let line of this.board) {\n for (let tile of line) {\n tile.valid = false;\n }\n }\n }", "function lastBlockWorldsSwap(e, target1, target2, content1, content2){\n e.preventDefault();\n target1.classList.remove('active_world');\n target2.classList.add('active_world');\n content1.classList.remove('visible'); \n content2.classList.add('visible');\n}", "function swap (mapping, rank1, rank2, qualifier) {\n const temp = {...mapping[rank2], qualifier};\n mapping[rank2] = mapping[rank1];\n mapping[rank1] = temp;\n}", "function turnIs() {\n if (turn == player2) {\n turn = player1;\n symbol = \"o\";\n } else {\n turn = player2;\n symbol = \"x\";\n }\n\n }", "function orderPlayers() {\n vm.competition.players = $filter('orderBy')(vm.competition.players, 'position');\n }" ]
{ "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 === x.toUpperCase() ? 2 : 3))];\n\treturn a.length > 1 ? \"mixed\" : a[0] === 1 ? \"lower\" : \"upper\";\n}", "function alternatingCaps(s) {\n\treturn s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]());\n}", "function caps(str){\n return str.replace(/\\w\\S*/g, function(txt){\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n}", "function reverseCase(string) {\n var removeDups = /([a-zA-Z])\\1+/g;\n return string.replace(removeDups, convertCase);\n}", "function stringTransformer(str) {\n // Your code here\n return str.split(' ').reverse().join(' ').split('').map((el)=> {\n if (el == el.toUpperCase()) return el.toLowerCase()\n else if (el == el.toLowerCase()) return el.toUpperCase()\n }).join('')\n}", "function firstLettersToUpperCase(s) {\r\n let words = s.split(' ');\r\n let wordsUpperCased = words.map(word => word.charAt(0).toUpperCase() + word.substring(1))\r\n return wordsUpperCased.join(' ');\r\n}", "function toScottishScreaming(str) {\n\treturn str.replace(/[aiou]/gi, 'e').toUpperCase();\n}", "function invertCase(someString) {\n const mappedString = someString.split(\"\").map(character => character === character.toUpperCase() ? \n character.toLowerCase() : character.toUpperCase()).join(\"\");\n return mappedString;\n}", "capitalizer(str) {\n\t\treturn str.replace(/[aeiou]/g, char => char.toUpperCase());\n\t}", "function camelize(s) {\n\t\t\t\t// Remove data- prefix and convert remaining dashed string to camelCase:\n\t\t\t\treturn s.replace(regexDataPrefix, '$1').replace(regexDashB4, function (m, m1) {\n\t\t\t\t\t\treturn m1.toUpperCase();\n\t\t\t\t});\n\t\t}", "function SwapCase(str) { \n\n let result = ''\n \n for (let char of str) {\n if (char >= 'a' && char <= 'z') {\n result += char.toUpperCase()\n } else if (char >= 'A' && char <= 'Z') {\n result += char.toLowerCase()\n } else {\n result += char\n }\n }\n return result\n }", "function logWhisper(string) {\n console.log(string.toLowerCase());\n}", "function norm(str){\n return str\n .toLowerCase()\n .replace(/Á|á/,'azzz').replace(/É|é/,'ezzz').replace(/Í|í/,'izzz')\n .replace(/Ð|ð/,'dzzz').replace(/Ó|ó/,'ozzz').replace(/Ú|ú/,'uzzz')\n .replace(/Ý|ý/,'yzzz').replace(/Þ|þ/,'zz').replace(/Æ|æ/,'zzz').replace(/Ö|ö/,'zzzz');\n }", "function titlelize (string) {\nvar title = string.split(\" \");\nreturn title.forEach(function(x){\nreturn capitalize(x).join(\" \");\n\n});\n\n}", "function stirvify(string) {\n // let newString = string.slice(0,7) === \"Strive\"? string: \"Strive \"+ string\n\n return string.startsWith(\"Strive\") ? string : \"Strive\" + string;\n}", "static toStyleClass(str) {\n return str.replace(/(\\w)([A-Z])/g, (_m, m1, m2) => m1 + \"-\" + m2).toLowerCase();\n }", "function className(string) {\n // remove special characters\n string = string.replace(/[^a-zA-Z0-9]+/g, '');\n // uppercase first character\n return string.charAt(0).toUpperCase() + string.slice(1);\n}", "function normalize(word) {\n\n return stem(word.toLowerCase()).replace(/[^a-z]/g, '');\n\n}" ]
{ "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\"] = 7;\n city_tile_map[\" -1-1\"] = 8;\n city_tile_map[\" 20\"] = 9;\n city_tile_map[\" 02\"] = 10;\n city_tile_map[\" 0-2\"] = 11;\n city_tile_map[\" -20\"] = 12;\n city_tile_map[\" 21\"] = 13;\n city_tile_map[\" 2-1\"] = 14;\n city_tile_map[\" 12\"] = 15;\n city_tile_map[\" 1-2\"] = 16;\n city_tile_map[\" -12\"] = 17;\n city_tile_map[\" -1-2\"] = 18;\n city_tile_map[\" -21\"] = 19;\n city_tile_map[\" -2-1\"] = 20;\n\n return city_tile_map[\" \"+dx+\"\"+dy];\n\n}", "get tileOffset() {}", "getRegionForPos(p) {\n let x = p.x;\n let y = p.y;\n return {\n x: Math.floor(x / CELLS_IN_REGION),\n y: Math.floor(y / CELLS_IN_REGION)\n };\n }", "function getMid(obj) {\r\n\tvar top = obj.offset().top;\r\n\tvar left = obj.offset().left;\r\n\tvar height = obj.height();\r\n\tvar width = obj.width();\r\n\r\n\tvar mid = {\r\n\t\tx : left + width / 2,\r\n\t\ty : top + height / 2\r\n\t}\r\n\r\n\treturn mid;\r\n}", "function delta_index(start, current) {\n return {left: current.left - start.left, top: current.top - start.top};\n}", "function get_planet_matrix_position(x, y) {\n var my = Math.floor((y - map.y) / (map.planet_h - map.planet_s));\n\n var indent = 1;\n\n if(insert_counter % 2) {\n indent = 0;\n }\n\n var xoffset = 0;\n if((my + 1) % 2 == indent) {\n xoffset = map.planet_w / 2;\n }\n\n var mx = Math.floor(((x - xoffset) - map.x) / map.planet_w);\n return {x: mx, y: my};\n }", "function getTileIndex(x, y) {\n return y * 12 + x;\n}", "function getMapCell(x, y, sx, sy, map) {\n var cell,\n i = getMapIndex(x, y, sx);\n \n if (i > map.length || i < 0) {\n console.warn('OOB!');\n return null;\n }\n \n cell = map[i];\n \n return cell;\n}", "center(cell) {\n const {x, z} = cell instanceof Map ? cell.toJS() : cell;\n return {\n x: (x * HEX_WIDTH * 3/4),\n y: (z * HEX_HEIGHT) + (x * HEX_HEIGHT / 2)\n };\n }", "function getPlayerLocation(player) {\n var m = stateMachine.map;\n for (var row=0; row < m.length; row++) {\n for (var col=0; col < m[0].length; col++) {\n if (m[row][col] == player) {\n return [row, col];\n }\n }\n }\n throw(\"cannot getPlayerLocation for player \" + player);\n}", "function findNewMarker(){\r\n\r\n for (let i = 0; i < allMarkers.length; i++){\r\n\r\n if (allMarkers[i].inPreviousFrame === false && allMarkers[i].marker.isVisible()) { // tile just entered scene\r\n return allMarkers[i];\r\n }\r\n\r\n }\r\n\r\n return null;\r\n\r\n}", "function index(x, y) {\n return x * gridSize + y;\n}", "function make3dIndex(cellSide, xsize, ysize) {\n var index = this;\n \n index.side = cellSide;\n index.xsize = xsize;\n index.ysize = ysize;\n index.ycoeff = 2*index.xsize;\n index.zcoeff = 4*index.xsize*index.ysize;\n index.k = 1/index.side;\n index.cells = {};\n index.objectCache = {};\n index.indexCache = {};\n index.neighbourCache = {};\n index.neighbourhood = new Int32Array([\n 0,0,0,\n 0,0,1,\n 1,0,1,\n -1,0,1,\n 0,1,1,\n 0,-1,1,\n 1,1,1,\n 1,-1,1,\n -1,1,1,\n -1,-1,1,\n 1,0,0,\n -1,0,0,\n 0,1,0,\n 0,-1,0,\n 1,1,0,\n 1,-1,0,\n -1,1,0,\n -1,-1,0,\n 0,0,-1,\n 1,0,-1,\n -1,0,-1,\n 0,1,-1,\n 0,-1,-1,\n 1,1,-1,\n 1,-1,-1,\n -1,1,-1,\n -1,-1,-1\n ]);\n \n return index;\n}", "mapPos(pos, assoc = -1, mode = MapMode.Simple) {\n let posA = 0, posB = 0;\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;\n if (ins < 0) {\n if (endA > pos)\n return posB + (pos - posA);\n posB += len;\n }\n else {\n if (mode != MapMode.Simple && endA >= pos &&\n (mode == MapMode.TrackDel && posA < pos && endA > pos ||\n mode == MapMode.TrackBefore && posA < pos ||\n mode == MapMode.TrackAfter && endA > pos))\n return -1;\n if (endA > pos || endA == pos && assoc < 0 && !len)\n return pos == posA || assoc < 0 ? posB : posB + ins;\n posB += ins;\n }\n posA = endA;\n }\n if (pos > posA)\n throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);\n return posB;\n }", "_mapMaze () {\n return this.maze.map((row, rowIndex) => {\n const mappedRow = row.map((column, columnIndex) => ({\n row: rowIndex,\n column: columnIndex,\n parent: null,\n value: column,\n f: 0,\n g: 0,\n h: 0\n }))\n\n return mappedRow\n })\n }", "function get_planet_real_position(column, row) {\n var x = map.x + column * map.planet_w;\n \n var indent = 1;\n\n if(insert_counter % 2) {\n indent = 0;\n }\n\n if((row + 1) % 2 == indent) {\n x += map.planet_w / 2;\n }\n\n var y = map.y + row * (map.planet_h - map.planet_s);\n return {x: x, y: y};\n }", "function rebuildIndexMapBruteForce() {\n var i;\n indexMap = {};\n\n for (i = 0; i < array.length; i += 1) {\n indexMap[array[i].id] = i;\n }\n }", "function PuplishMap(){}", "function hashCoordinates(i, j) {\n\tif (!isInBoundaries(i, j)) {\n\t\treturn 0;\n\t}\n\treturn i * gameSize + j + 1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }