query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Takes ids from hidden field and clone li's | function cloneSelectedImages(site_img_div, attached_img_div) {
var hidden_ids = jQuery(attached_img_div).prev().prev(),
ids_array = (hidden_ids.val().length > 0) ? hidden_ids.val().split(",") : new Array(),
img_ul = attached_img_div.find('.gallery_widget_attached_images_list');
img_ul.html('');
jQuery.each(ids_array, function (index, value) {
jQuery(site_img_div).find('img[rel=' + value + ']').parent().clone().appendTo(img_ul);
});
attachedImgSortable(img_ul);
} | [
"function refresh_ul_list_from_hidden(dom) {\n\n var fields = get_fields(dom);\n var names = $(fields.name_list).val().split(', ');\n var codes = $(fields.code_list).val().split(', ');\n\n $.each(names, function (i, name) {\n if (name !== '') {\n var code = codes[i];\n $(fields.ul_list).append(create_li(code, name, dom));\n }\n });\n}",
"function cloneSelectedImages( site_img_div, attached_img_div ) {\n var hidden_ids = jQuery( attached_img_div ).prev().prev(),\n ids_array = (hidden_ids.val().length > 0) ? hidden_ids.val().split( \",\" ) : new Array(),\n img_ul = attached_img_div.find( '.gallery_widget_attached_images_list' );\n\n img_ul.html( '' );\n\n jQuery.each(\n ids_array, function( index, value ) {\n jQuery( site_img_div ).find( 'img[rel=' + value + ']' ).parent().clone().appendTo( img_ul );\n }\n );\n attachedImgSortable( img_ul );\n}",
"function populateMoreList(hiddenEls) {\n\t\temptyMoreList();\n\t\tresetIds();\n\n\t\tfor (let c = 0, l = hiddenEls.length; c < l; c++) {\n\t\t\tconst aEl = hiddenEls[c].querySelector('a');\n\t\t\tconst ulEl = hiddenEls[c].querySelector('ul');\n\n\t\t\tif (hiddenEls[c].hasAttribute('data-o-hierarchical-nav-is-cloneable')) {\n\t\t\t\tcloneItemToMoreList(hiddenEls[c]);\n\t\t\t} else {\n\t\t\t\tconst aText = (typeof aEl.textContent !== 'undefined') ? aEl.textContent : aEl.innerText;\n\t\t\t\taddItemToMoreList(aText, aEl.href, ulEl);\n\t\t\t}\n\t\t}\n\t}",
"function clonePlaylistSelected() {\n $(\"input[name=cloneplaylist]\").each(function() {\n $(this).parent().parent().parent().removeClass(\"playlistsel-selected\");\n });\n $(\"input[name=cloneplaylist]:checked\").parent().parent().parent().addClass(\"playlistsel-selected\");\n $(\"#ed-clonelink\").val(\"\");\n}",
"function buildIdLists() {\n\n $A( $(\"have\").options ).each( function( opt ) {\n var i = document.createElement( \"input\" );\n i.type = \"hidden\";\n i.name = \"have\";\n i.value = opt.value;\n $(\"domainSearchForm\").appendChild( i );\n } );\n \n $A( $(\"not\").options ).each( function( opt ) {\n var i = document.createElement( \"input\" );\n i.type = \"hidden\";\n i.name = \"not\";\n i.value = opt.value;\n $(\"domainSearchForm\").appendChild( i );\n } );\n\n $('domainSearchForm').submit();\n}",
"function createElementClone(cloneElementClass, insertAfterElementClas) {\n var cloneEl = $(\".\"+cloneElementClass+\":last\").clone(true);\n var childInputs = $(\".\"+cloneElementClass+\":last input\");\n var childSelect = $(\".\"+cloneElementClass+\":last select\");\n $.each(childInputs, function(i,el){\n var inputID = el.id;\n var newID = getElementNewID(el);\n $(cloneEl).find('input[id='+inputID+']').attr(\"id\", newID);\n $(cloneEl).find('label[for='+inputID+']').attr(\"for\", newID);\n });\n\n $.each(childSelect, function(i,el) {\n var inputID = el.id;\n var newID = getElementNewID(el);\n $(cloneEl).find('select[id='+inputID+']').attr(\"id\", newID);\n $(cloneEl).find('label[for='+inputID+']').attr(\"for\", newID);\n });\n\n $(cloneEl).find('select').val(\"\");\n $(cloneEl).find('textarea').val(\"\");\n $(cloneEl).find('input').val(\"\");\n $(cloneEl).find('input:checked').prop(\"checked\", false);\n if (insertAfterElementClas !== undefined) {\n $(cloneEl).insertAfter(\".\"+insertAfterElementClas);\n } else {\n $(cloneEl).insertAfter(\".\"+cloneElementClass+\":last\");\n }\n\n // every element must have id ending with underscore ( _ ) and a number\n function getElementNewID(el) {\n var elID = el.id;\n if (!elID) {\n alert(\"Every elemet should have a unique id to use function getElementNewID()\");\n return false;\n }\n var splitID = elID.split('_');\n var index = 1;\n var newIndex = 1;\n var newID = \"\";\n if (splitID.length > 1) {\n index = splitID.length - 1;\n newIndex = Number(splitID[index]) + 1;\n splitID.pop();\n newID = splitID.join(\"\") + \"_\" + newIndex;\n } else {\n newID = elID + \"_\" + index;\n }\n return newID;\n }\n}",
"function addListIds() {\n const ul = document.querySelectorAll(\"#ul-items li\");\n for (let i = 0; i < ul.length; i++) {\n ul[i].addEventListener('click', selectFromList);\n ul[i].id = i + 'l';\n }\n}",
"function ParseToItemHiddenField() {\n var itemArray = new Array();\n $(\"#tItemData li span.ti\").each(function (index) {\n var tItem = $(this).html();\n if (tItem != null) {\n itemArray.push(tItem);\n }\n });\n $(\"input[id=itemHiddenField]\").attr(\"value\", JSON.stringify(itemArray));\n}",
"function ListItem(){\n\tvar item =$('#new-item').val();\n\tvar OnList=$('<li>' + item + '</li>');\n\t$('#new-item').prepend($('#list-items'));\n}",
"function append_clone(){\n $(\"#contain li\").each(function(){\n $(\"#contain li\").clone().appendTo(\"#contain\");\n if ($(\"#contain li\").length > 200) //evitamos buble infinito con 100 elementos máx.\n return false; //similar a break.\n });\n}",
"function addNewIds(ids) {\n // add new section ids\n $('#sections-list > .list-group-item').each((i, section) => {\n if(section.id === '') {\n const id = ids['newSections'].shift();\n section.id = 'section_' + id;\n }\n\n // add new item ids\n $(`.items[data-section-id = ${$(section).attr('data-section-id')}] .item`).each((i, item) => {\n if(item.id === '') {\n const itemId = ids['newItems'].shift();\n item.id = 'item_' + itemId;\n }\n });\n });\n}",
"function handleAddId(){\n if(nextId < 1) return false; \n nextId = nextId.split(' ')\n pageIds.push(...nextId)\n nextId = nextId.join('</li><li>');\n\n nextId = `<li>${nextId}</li>`;\n collectiveIds.innerHTML = collectiveIds.innerHTML + nextId\n\n nextId = '';\n newId.value = '';\n}",
"function copyIds()\n{\n $('.sf_admin_batch_checkbox:checked').each(function() {\n $('#batch_checked_ids').append('<option value=\"'+$(this).val()+'\" selected=\"selected\">'+$(this).val()+'</option>');\n });\n}",
"function UpdateVisibleElementList(){\n $(\"#desktop_element_list\").html(\"\");\n $.each(ElementList,function(id, element){\n var $li = \n $(`<li draggable='true'>\n <input type='hidden' class='desktop_object_id' value='${id}'></input>\n ${element.name}\n </li>`);\n $li.on(\"dragstart\",function(event){ \n //For firefox combatibility\n event.originalEvent.dataTransfer.setData('text/plain', 'anything');\n //Hide the dekstop menu\n //$(\"aside\").slideUp();\n CurrentElement = ElementList[$(this).find(\".desktop_object_id\").val()];\n });\n $(\"#desktop_element_list\").append($li);\n });\n \n }",
"function cloneElement(id, initialSizeOfClonedSiblings, inputNamePrefix) {\n\tif (numberOfClonedElements[id] != null) {\n\t\tnumberOfClonedElements[id] = numberOfClonedElements[id] + 1;\n\t}\n\telse {\n\t\tnumberOfClonedElements[id] = initialSizeOfClonedSiblings;\n\t}\n\t\n\tvar elementToClone = document.getElementById(id);\n\tvar clone = elementToClone.cloneNode(true);\n\tvar inputs = clone.childNodes;\n\tfor (var x = 0; x < inputs.length; x++) {\n\t\tvar input = inputs[x];\n\t\tif (input.name) {\n\t\t\tinput.name = inputNamePrefix + input.name.replace('[x]', '[' + numberOfClonedElements[id] + ']')\n\t\t}\n\t}\n\tclone.id = \"\";\n\telementToClone.parentNode.insertBefore(clone, elementToClone);\n\tclone.style.display = \"\";\n\t\n}",
"function addId(listId) {\n if( $(\"idSelection\").hasChildNodes() ) {\n var selected = $(\"idSelection\").selectedIndex;\n if( selected >= 0 ) {\n var chosen = $(\"idSelection\").options[selected];\n $(\"idSelection\").removeChild( chosen );\n $(listId).appendChild( chosen ); \n }\n }\n}",
"function addDecklist() {\n let newList = qs(\"#list-wrap ul li:first-child\").cloneNode(true);\n newList.querySelector(\".list-title\").value = \"\";\n newList.querySelector(\".list-link\").value = \"\";\n newList.querySelector(\".has-primer\").checked = false;\n newList.querySelector(\".delete-list\").addEventListener(\"click\", deleteDecklist);\n qs(\"#list-wrap ul\").appendChild(newList);\n}",
"function buildSiblingListview(listviewId) {\n var style = 'color: Blue';\n $('#' + listviewId + ' li').remove();\n var notebookFileName = getNotebookFileName(currentTabEntryId);\n var entryId = getEntryId(currentTabEntryId);\n var xmlDoc = $.parseXML($('#txtCache-' + notebookFileName).text());\n var parentElement = $(xmlDoc).find('entry[id=\"' + entryId + '\"]')[0].parentNode;\n var parentEntryId = parentElement.getAttribute(\"id\");\n if (parentEntryId == null) { // current tab has no entry parent\n var titleElements = $(xmlDoc).find('notebook title');\n $.each(titleElements, function(key, value) {\n if (typeof value != 'undefined') {\n if (value.parentNode.parentNode.nodeName == 'notebook') { // just select the immediate children of parent node\n if (value.childNodes.length > 0) {\n var id = value.parentNode.getAttribute(\"id\");\n var title = value.childNodes[0].nodeValue;\n if (id == entryId) {\n $('<li data-name=\"' + id + '\" style=\"' + style + '\">' + title + '</li>').appendTo($('#' + listviewId)); \n }\n else {\n $('<li data-name=\"' + id + '\">' + title + '</li>').appendTo($('#' + listviewId)); \n }\n } \n } \n }\n }); \n }\n else {\n var titleElements = $(xmlDoc).find('entry[id=\"' + parentEntryId + '\"] title');\n $.each(titleElements, function(key, value) {\n if (typeof value != 'undefined') {\n if (value.parentNode.parentNode.getAttribute(\"id\") == parentEntryId) { // just select the immediate children of parent node\n if (value.childNodes.length > 0) {\n var id = value.parentNode.getAttribute(\"id\");\n var title = value.childNodes[0].nodeValue;\n if (id == entryId) {\n $('<li data-name=\"' + id + '\" style=\"' + style + '\">' + title + '</li>').appendTo($('#' + listviewId));\n }\n else {\n $('<li data-name=\"' + id + '\">' + title + '</li>').appendTo($('#' + listviewId));\n }\n } \n } \n }\n }); \n }\n MathJax.Hub.Queue(['Typeset', MathJax.Hub, listviewId]); \n }",
"function generate_multi_list_html() {\n var field_label = $jQ('#sib_multi_field_label').val();\n var field_html = '<p class=\"sib-multi-lists-area\">\\n';\n var list_id = '';\n var list_name = '';\n var required = false;\n var required_label = '';\n var required_attr = '';\n if ( $jQ('#sib_multi_field_required').is(\":checked\"))\n {\n required = true;\n required_label = '*';\n required_attr = 'required';\n }\n if ( field_label != '' )\n {\n field_html += '<label>' + field_label + required_label + '</label>\\n';\n }\n\n field_html += '<div class=\"sib-multi-lists\" data-require=\"' + required_attr + '\">\\n';\n var selected_lists = $jQ('#sib_select_multi_list').find('option:selected', this);\n selected_lists.each(function(){\n list_id = $jQ(this).val();\n list_name = $jQ(this).data('list');\n field_html += '<div style=\"block\"><input type=\"checkbox\" class=\"sib-interesting-lists\" value=\"' + list_id + '\" name=\"listIDs[]\">' + list_name + '</div>\\n';\n });\n field_html += '</div></p>';\n $jQ('#sib_multi_field_html').html(field_html);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an anchor url for the given reflection and all of its children. | static applyAnchorUrl(reflection, container) {
if (!reflection.url || !DefaultTheme.URL_PREFIX.test(reflection.url)) {
const anchor = DefaultTheme.getUrl(reflection, container, ".");
reflection.url = container.url + "#" + anchor;
reflection.anchor = anchor;
reflection.hasOwnDocument = false;
}
reflection.traverse((child) => {
if (child instanceof index_1.DeclarationReflection) {
DefaultTheme.applyAnchorUrl(child, container);
}
});
} | [
"static applyAnchorUrl(reflection, container) {\n if (!(reflection instanceof models_1.DeclarationReflection) && !(reflection instanceof models_1.SignatureReflection)) {\n return;\n }\n if (!reflection.url || !DefaultTheme.URL_PREFIX.test(reflection.url)) {\n const anchor = DefaultTheme.getUrl(reflection, container, \".\");\n reflection.url = container.url + \"#\" + anchor;\n reflection.anchor = anchor;\n reflection.hasOwnDocument = false;\n }\n reflection.traverse((child) => {\n DefaultTheme.applyAnchorUrl(child, container);\n return true;\n });\n }",
"buildUrls(reflection, urls) {\n const mapping = this.mappings.find((mapping) => reflection.kindOf(mapping.kind));\n if (mapping) {\n if (!reflection.url || !MarkdownTheme.URL_PREFIX.test(reflection.url)) {\n const url = this.toUrl(mapping, reflection);\n urls.push(new typedoc_1.UrlMapping(url, reflection, mapping.template));\n reflection.url = url;\n reflection.hasOwnDocument = true;\n }\n for (const child of reflection.children || []) {\n if (mapping.isLeaf) {\n this.applyAnchorUrl(child, reflection);\n }\n else {\n this.buildUrls(child, urls);\n }\n }\n }\n else if (reflection.parent) {\n this.applyAnchorUrl(reflection, reflection.parent);\n }\n return urls;\n }",
"applyAnchorUrl(reflection, container) {\n if (!reflection.url || !MarkdownTheme.URL_PREFIX.test(reflection.url)) {\n const reflectionId = reflection.name.toLowerCase();\n const anchor = this.toAnchorRef(reflectionId);\n reflection.url = container.url + '#' + anchor;\n reflection.anchor = anchor;\n reflection.hasOwnDocument = false;\n }\n reflection.traverse((child) => {\n if (child instanceof typedoc_1.DeclarationReflection) {\n this.applyAnchorUrl(child, container);\n }\n });\n }",
"static buildUrls(reflection, urls) {\n const mapping = DefaultTheme.getMapping(reflection);\n if (mapping) {\n if (!reflection.url ||\n !DefaultTheme.URL_PREFIX.test(reflection.url)) {\n const url = [\n mapping.directory,\n DefaultTheme.getUrl(reflection) + \".html\",\n ].join(\"/\");\n urls.push(new UrlMapping_1.UrlMapping(url, reflection, mapping.template));\n reflection.url = url;\n reflection.hasOwnDocument = true;\n }\n for (const child of reflection.children || []) {\n if (mapping.isLeaf) {\n DefaultTheme.applyAnchorUrl(child, reflection);\n }\n else {\n DefaultTheme.buildUrls(child, urls);\n }\n }\n }\n else if (reflection.parent) {\n DefaultTheme.applyAnchorUrl(reflection, reflection.parent);\n }\n return urls;\n }",
"buildUrls(reflection, urls) {\n const mapping = this.getMapping(reflection);\n if (mapping) {\n if (!reflection.url || !DefaultTheme.URL_PREFIX.test(reflection.url)) {\n const url = [mapping.directory, DefaultTheme.getUrl(reflection) + \".html\"].join(\"/\");\n urls.push(new UrlMapping_1.UrlMapping(url, reflection, mapping.template));\n reflection.url = url;\n reflection.hasOwnDocument = true;\n }\n reflection.traverse((child) => {\n if (child instanceof models_1.DeclarationReflection) {\n this.buildUrls(child, urls);\n }\n else {\n DefaultTheme.applyAnchorUrl(child, reflection);\n }\n return true;\n });\n }\n else if (reflection.parent) {\n DefaultTheme.applyAnchorUrl(reflection, reflection.parent);\n }\n return urls;\n }",
"toUrl(mapping, reflection) {\n return mapping.directory + '/' + this.getUrl(reflection);\n }",
"function anchor(children, photo, link_to_size) {\n return ('<a href=\"' + link(photo, link_to_size) + '\" title=\"' + photo.title + '\">' +\n children + '</a>');\n }",
"function buildAnchor( object, linkcode ){\n var baseURL = document.getElementById(\"baseURL\").value;\n var a = document.createElement(\"a\");\n a.textContent = object.name;\n a.setAttribute(\"href\", baseURL + \"/\"+ linkcode +\"/\" + object.__id__);\n a.setAttribute(\"target\", \"_blank\");\n return a;\n}",
"static getUrl(reflection, relative, separator = \".\") {\n let url = reflection.getAlias();\n if (reflection.parent &&\n reflection.parent !== relative &&\n !(reflection.parent instanceof index_1.ProjectReflection)) {\n url =\n DefaultTheme.getUrl(reflection.parent, relative, separator) +\n separator +\n url;\n }\n return url;\n }",
"static getUrl(reflection, relative, separator = \".\") {\n let url = reflection.getAlias();\n if (reflection.parent && reflection.parent !== relative && !(reflection.parent instanceof models_1.ProjectReflection)) {\n url = DefaultTheme.getUrl(reflection.parent, relative, separator) + separator + url;\n }\n return url;\n }",
"function Links (){\r\n\taddMethod(this, \"byText\", function(ExpectedName, DesiredName){\r\n\t\tExpectedName = \"^\" + ExpectedName.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\tre = new RegExp(ExpectedName)\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.innerHTML)){\r\n\t\t\t\tif (DesiredName != \"\"){\r\n\t\t\t\t\ttmp.innerHTML = DesiredName;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n\t\r\n\taddMethod(this, \"byText\", function(ExpectedName, DesiredName, RegexEnabled){\r\n\t\tif (RegexEnabled != 1){\r\n\t\t\tExpectedName = \"^\" + ExpectedName.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\t}\r\n\t\tre = new RegExp(ExpectedName)\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.innerHTML)){\r\n\t\t\t\tif (DesiredName != \"\"){\r\n\t\t\t\t\ttmp.innerHTML = DesiredName;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n\t\r\n\taddMethod(this, \"byText\", function(ExpectedName, DesiredName, DesiredTarget, RegexEnabled){\r\n\t\tif (RegexEnabled != 1){\r\n\t\t\tExpectedName = \"^\" + ExpectedName.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\t}\r\n\t\tre = new RegExp(ExpectedName)\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.innerHTML)){\r\n\t\t\t\tif (DesiredName != \"\"){\r\n\t\t\t\t\ttmp.innerHTML = DesiredName;\r\n\t\t\t\t}\r\n\t\t\t\tif (DesiredTarget != \"\"){\r\n\t\t\t\t\ttmp.href = DesiredTarget;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\t\telse if(re.test(tmp.href)){\r\n\t\t\t\tif (DesiredName != \"\"){\r\n\t\t\t\t\ttmp.innerHTML = DesiredName;\r\n\t\t\t\t}\r\n\t\t\t\tif (DesiredTarget != \"\"){\r\n\t\t\t\t\ttmp.href = DesiredTarget;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n\t\r\n\taddMethod(this, \"byTarget\", function (ExpectedTarget, DesiredTarget){\r\n\t\tExpectedTarget = \"^\" + ExpectedTarget.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\tre = new RegExp(ExpectedTarget);\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.href)){\r\n\t\t\t\tif (DesiredTarget != \"\"){\r\n\t\t\t\t\ttmp.href = DesiredTarget;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n\t\r\n\taddMethod(this, \"byTarget\", function (ExpectedTarget, DesiredTarget, RegexEnabled){\r\n\t\tif (RegexEnabled != 1){\r\n\t\t\tExpectedTarget = \"^\" + ExpectedTarget.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\t}\r\n\t\tre = new RegExp(ExpectedTarget);\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.href)){\r\n\t\t\t\tif (DesiredTarget != \"\"){\r\n\t\t\t\t\ttmp.href = DesiredTarget;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n\t\r\n\taddMethod(this, \"byTarget\", function (ExpectedTarget, DesiredName, DesiredTarget, RegexEnabled){\r\n\t\tif (RegexEnabled != 1){\r\n\t\t\tExpectedTarget = \"^\" + ExpectedTarget.replace(toReplace, \"\\\\$1\") + \"$\";\r\n\t\t}\r\n\t\tre = new RegExp(ExpectedTarget);\r\n\t\tfor(i = 0; i < lnk.snapshotLength; i++) {\r\n\t\t\ttmp = lnk.snapshotItem(i);\r\n\t\t\tif(re.test(tmp.href)){\r\n\t\t\t\tif (DesiredName != \"\"){\r\n\t\t\t\t\ttmp.innerHTML = DesiredName;\r\n\t\t\t\t}\r\n\t\t\t\tif (DesiredTarget != \"\"){\r\n\t\t\t\t\ttmp.href = DesiredTarget;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t});\r\n}",
"function buildExprUrl(expr) {\n\t// Build a template context from the search attr/values\n\tvar ctx = {};\n\tif (expr.terms) {\n\t\tfor (var i=0; i < expr.terms.length; i++) {\n\t\t\tif (Array.isArray(expr.terms[i])) {\n\t\t\t\tctx[expr.terms[i][0]] = expr.terms[i][1];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn web.renderUri(expr.link.href, ctx);\n}",
"function buildUrl (obj) {\n\t\treturn (obj.protocol || 'http') + '://' +\n\t\t\t (obj.host ||\n\t\t\t\tobj.hostname + (obj.port ? ':' + obj.port : '')) +\n\t\t\t (obj.pathname || '') +\n\t\t\t (obj.search ? '?' + formatQS(obj.search || '') : '') +\n\t\t\t (obj.hash ? '#' + obj.hash : '');\n\t}",
"makeHref (api, operationSpec, params) {\n const { host, basePath } = api\n const scheme = api.schemes ? api.schemes[0] : 'http'\n const path = operationSpec.url\n let href = `${scheme}://${host}${basePath}${path}`\n\n Object.keys(params).forEach(key => {\n const rex = new RegExp(`{${key}}`)\n if (rex.test(href)) {\n href = href.replace(rex, params[key])\n delete params[key]\n }\n })\n\n let uri = new URI(href).query(params)\n uri.normalizePath()\n\n return uri.toString()\n }",
"function update_anchor_properties() {\n return (ast, vfile) => {\n visit(ast, \"element\", (node) => {\n if (node.tagName !== \"a\") return;\n\n let {href} = node.properties;\n if (!href) return;\n\n const url = parse(href);\n if (is_external_link(href, url)) {\n node.properties.target = \"_blank\";\n node.properties.rel = \"noopener\";\n } else if (is_internal_link(href, url)) {\n const {path} = url;\n const {dirname} = vfile;\n\n href = get_documentation_link(dirname, path);\n } else if (is_absolute_link(href, url)) {\n href = \"#\" + url.path.slice(1);\n } else if (is_selector_link(href, url)) {\n const {dirname, path} = vfile;\n\n href = \"?selector=\" + href.slice(1);\n href = get_documentation_link(dirname, path) + href;\n }\n\n node.properties.href = href;\n });\n };\n}",
"_build_link(){\n\n\t\tconst link_data = [\n\t\t\tthis.opts.link_version,\n\t\t\tthis.opts.link_random_data,\n\t\t\tbtoa(this.names.flat().join(\"/\") + \"|\" + this.mapping.join(\"/\"))\n\t\t].join(\".\")\n\n\t\treturn `${this.opts.link_root}${link_data}`\n\t}",
"buildAnchorElement(link) {\n return '<a href=\\\"' + link.url + '\\\">' + link.name + \"</a>\"\n }",
"function buildLink(xx,yy,ii,jj,kk,ll,colonyData){\r\n\tgetCell(xx,yy,ii,jj).innerHTML = createLink(constructionUrl(kk,ll,colonyData),getCell(xx,yy,ii,jj).innerHTML);\r\n}",
"function drawURL(obj){\n\tlet element = document.querySelector(\"#tools > ul\")\n\tlet li = document.createElement(\"li\");\n\tlet ahref = document.createElement('a');\n\tlet linkText = document.createTextNode(obj.owner);\n\tahref.appendChild(linkText);\n\tahref.title = obj.owner;\n\tahref.href = obj.href;\n\tli.appendChild(ahref);\n\telement.appendChild(li)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parser tests are automatically generated from Processing files to call this. | function _checkParser() {
eval(Processing(canvas, parserTest.body));
_pass();
} | [
"function _Parser() {\n\t}",
"function Parser() {}",
"beforeParse() {}",
"function Parser() {\n}",
"beforeStep () {\n this.firstPass()\n this.parser = new Parser(this.assemblyCode)\n return this.parser\n }",
"_parseEntities() {\n this._parseAllTestFiles();\n this._parseFixtures();\n this._parseFunctionalTests();\n this._parsePerformanceTests();\n }",
"function _setupParser(){\n\t\t//Extend the parser with the local displayError function\n\t\tparser.displayError = displayError;\n\n\t\t$('html')\n\t\t\t.fileDragAndDrop(function(fileCollection){\n\t\t\t\t_resetUI();\n\n\t\t\t\t//Reset lists\n\t\t\t\tparser.errorList = [];\n\t\t\t\tparser.songList = [];\n\n\t\t\t\t//Loop through each file and parse it\n\t\t\t\t$.each(fileCollection, parser.parseFile);\n\n\t\t\t\t//Parsing complete, run the display/output functions\n\t\t\t\tparser.complete($output);\n\n\t\t\t\t//Update the total converted song count\n\t\t\t\t_updateSongCount(parser.songList.length);\n\t\t\t\t\n\t\t\t\t//Also display errors if there are any\n\t\t\t\tif(parser.errorList.length){\n\n\t\t\t\t\tvar errorTitle = parser.errorList.length == 1 ? \"One song ran into an error and could not be converted\": \"We ran into errors with \" + parser.errorList.length + \" of the songs, and they were not converted\";\n\n\t\t\t\t\t//Join all the error messages together\n\t\t\t\t\tdisplayError(parser.errorList.join(\"<br/>\"), errorTitle);\n\t\t\t\t}\n\n\t\t\t});\n\t}",
"function PageParser(){\n}",
"parse(text, parsedInfo) {\n if (this.nextParser) {\n this.nextParser.parse(text, parsedInfo);\n }\n }",
"testParse (initTokens, expectedNode, expectedTokensAfter) {\n parser.init(initTokens);\n const node = parseFn();\n expect(node).toEqual(expectedNode);\n expect(parser.tokens).toEqual(expectedTokensAfter);\n }",
"afterParse() {}",
"preParse() {\n return;\n }",
"get parser() { return this.p.parser; }",
"function runCoreParserTests()\n{\n\tfor (var i = 0; i < CORE_PARSER_TESTS.length; i++)\n\t{\n\t\tvar test = CORE_PARSER_TESTS[i];\n\t\tvar passed = runTest(test);\n\t\tif (passed)\n\t\t\tpassCount++;\n\t\telse\n\t\t\tfailCount++;\n\t}\n\n\tfunction runTest(test)\n\t{\n\t\tvar actual = new Baby.Parser(test.config).parse(test.input);\n\t\tvar results = compare(actual.data, actual.errors, test.expected);\n\t\tdisplayResults('#tests-for-core-parser', test, actual, results);\n\t\treturn results.data.passed && results.errors.passed\n\t}\n}",
"parse () {\n this._ast = Parser.parse(this.regex)\n }",
"parse(){\n throw new Error(\"Scrapey:: parse() function not implemented by inheriting class!\");\n }",
"getParser(){\n \treturn this.parser;\n }",
"function Parser() {\n\t\t\n /**\n * Analiza los datos recibidos y los devuelve en el formato deseado. Por\n * defecto, el parser se limita a devolver los datos sin tratarlos.\n * @param data Los datos recibidos\n * @return Un ParserResult con el resultado del parseo\n */\n this.parse = function(data) \n {\n return new psd.framework.ParserResult(psd.framework.ParserResult.PARSER_SUCCESS_CODE\n , psd.framework.ParserResult.PARSER_SUCCESS\n , data);\n };\n }",
"parse(text, start = null, on_error = null) {\r\n return this.parser.parse(text, start, on_error);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
requestFunds function allows user to request funds from another user | function requestFunds() {
console.log("\nREQUEST FUNDS");
console.log("-----------------------------");
console.log(user.name + ", (ID: " + user.id + ")");
console.log("Current balance: " + Math.floor(user.balance* 100) / 100);
console.log("-----------------------------");
const requestTarget = readline.question("Please enter the ID you want to send " +
"request to (or 'quit' to go back):\n>> ");
if (requestTarget === "quit") {
currentLoc = "funds";
} else {
const userArray = JSON.parse(fs.readFileSync("./accountDetails.json", "utf8"));
// Compare userArray:s id:s with transferTarget's ID and take true/false in checkBoolean
const checkBoolean = userArray.some((x)=> x.id === requestTarget);
if (checkBoolean) {
const requestAmount = readline.question("How much money do you want to request? Min. is 1.\n>> ");
if (requestAmount === "quit") {
currentLoc = "funds";
} else if (requestAmount > 1) {
const toCheckPassword = readline.question("To request funds, please enter your password " +
"(or type 'quit' to go back):\n>> ");
if (toCheckPassword === "quit") {
currentLoc = "funds";
} else {
if (toCheckPassword === user.password) {
// Using mapping to find requestTarget and pushing id+requestAmount to it's fundRequests array
const newAllUsers = userArray.map(pushFunction);
function pushFunction(x) {
if (x.id === requestTarget) {
x.fundRequests.push([user.id, requestAmount]);
return x;
} else {
return x;
}
}
// Saving newAllUsers back to accountDetails.json file
fs.writeFileSync("./accountDetails.json", JSON.stringify(newAllUsers), "utf8", (err) => {
if (err) {
console.log("Could not save userData to file!");
}
});
console.log("\nRequest sent successfully to " + requestTarget + ".");
} else {
console.log("\nThe password is incorrect, please try again. (or 'quit' to go back to start)");
requestFunds();
}
}
} else {
console.log("Minimum request amount is 1 and you can only use numbers. Please try again.");
requestFunds();
}
} else {
console.log("No user found by that ID. Try again.");
requestFunds();
}
}
} | [
"function fundRequests() {\n if (user.fundRequests.length === 0) {\n console.log(\"No-one has sent fund request to you, returning to menu.\");\n } else {\n console.log(\"\\nFUND REQUESTS\");\n console.log(\"-----------------------------\");\n console.log(user.name + \", (ID: \" + user.id + \")\");\n console.log(\"Current balance: \" + Math.floor(user.balance* 100) / 100);\n console.log(\"-----------------------------\");\n\n console.log(\"\\nYou have following fund requests (ID, amount):\");\n for (const i in user.fundRequests) {\n if (user.fundRequests) {\n console.log((Number(i)+1) + \": \" + user.fundRequests[i]);\n }\n }\n\n const acceptInput = readline.question(\"\\nPlease enter number of request to accept transfer \" +\n \"(or 'quit' to go back in menu)\\n>> \");\n\n if (acceptInput === \"quit\") {\n currentLoc = \"funds\";\n // If accept input is >= 1 and given fundRequest index is not undefined (there IS request by that number)\n } else if (user.fundRequests[Number(acceptInput) - 1][1] > user.balance) {\n console.log(\"You dont have enough balance to pay requested amount.\");\n fundRequests();\n } else if ((acceptInput >= 1) && (user.fundRequests[Number(acceptInput) - 1] !== undefined)) {\n // Check for ID of fundRequest matching acceptInput\n const transferTarget = user.fundRequests[Number(acceptInput) - 1][0];\n // Check for requested amount matching acceptInput\n const transferAmount = user.fundRequests[Number(acceptInput) - 1][1];\n\n const passwordCheck = readline.question(\"Please enter your password to accept payment \"+\n \"for following request: \\n\" + \"To ID: \" + transferTarget + \", Amount: \" + transferAmount +\n \". (or 'quit' to return back to menu)\\n>> \");\n\n if (passwordCheck === \"quit\") {\n fundRequests();\n } else if (passwordCheck === user.password) {\n user.balance = Number(user.balance) - Number(transferAmount);\n\n const userArray = JSON.parse(fs.readFileSync(\"./accountDetails.json\", \"utf8\"));\n\n // Search userArray for transferTarget and add it with modified values to newAllUsers array.\n const newAllUsers = userArray.map(balanceFunction);\n function balanceFunction(x) {\n if (x.id === transferTarget) {\n // Modify target's balance to receive transferAmount\n x.balance = Number(x.balance) + Number(transferAmount);\n return x;\n } else if (x.id === user.id) {\n // Modify balance in newAllUsers to match user.balance\n x.balance = user.balance;\n\n // Remove correct fundRequest from array\n x.fundRequests.splice((Number(acceptInput) - 1), 1);\n\n // Update user.fundRequests\n user.fundRequests = x.fundRequests;\n return x;\n } else {\n return x;\n }\n }\n\n // Saving newAllUsers back to accountDetails.json file\n fs.writeFileSync(\"./accountDetails.json\", JSON.stringify(newAllUsers), \"utf8\", (err) => {\n if (err) {\n console.log(\"Could not save userData to file!\");\n }\n });\n\n console.log(\"\\nTransfer successful, your balance in your account is now: \" +\n Math.floor(user.balance* 100) / 100);\n } else {\n console.log(\"Password was incorrect, please try again.\");\n fundRequests();\n }\n } else {\n console.log(\"You didn't have request matching that number, please try again.\");\n fundRequests();\n }\n }\n}",
"request_funds() {\n const fundForm = document.querySelector(\"#fund-form\");\n fundForm.addEventListener(\"submit\", function (e) {\n e.preventDefault();\n\n // get fund request form info\n const userName = fundForm[\"user-name\"].value;\n const userEmail = fundForm[\"user-email\"].value;\n const fundPurpose = fundForm[\"fund-purpose\"].value;\n const fundRequested = fundForm[\"fund-requested\"].value;\n //const fundBreakdown =\n });\n }",
"function lodgefunds() {\n var e = document.getElementById(\"accountSelector\");\n var strUser = parseInt(e.value) + 1;\n sendRequest((\"http://localhost:49000/api/customers/\" + customerId + \"/accounts/\" + strUser + \"/transactions/lodge\"), getLodgeDetails(), \"post\");\n}",
"async withdrawFunds() {\n // FIXME Need systemic handling of default from address.\n await EthereumHelpers.sendSafely(this.contract.methods.withdrawFunds())\n }",
"async transferFunds({request,response,auth}){\n const data = request.only(['email','amount','pin']) \n \n const validation = await validateAll(data, {\n email :'required|email',\n amount :'required',\n pin:'required',\n })\n\n if(validation.fails()){\n return response.status(400).json({\n messag:validation.messages()\n })\n }\n\n var {email,amount:amount_to_send_from_client,pin} = data\n\n //get id of the client from email\n const {id:user_id_client} = await User.findBy('email',email)\n \n // get the pin from client\n var {pin:pin_from_db,balance:client_balance_from_db} = await Client.findBy('user_id',user_id_client)\n\n // if client has no pin set\n if(pin_from_db == null){\n return response.status(200).json({message: \"Invalid Transaction\"})\n }\n //if pin is invalid\n if(pin != pin_from_db ){\n return response.status(200).json({message: \"Invalid pin\"})\n }\n\n //if balance is insufficient\n if( parseFloat(amount_to_send_from_client) > parseFloat(client_balance_from_db) ){\n return response.status(200).json({message: \"Insufficient fund\"})\n }\n\n // check for if client is sending to Client \n \n // Debit Client\n const new_client_balance = parseFloat(client_balance_from_db) - parseFloat(amount_to_send_from_client)\n\n await Client.query().where('user_id',user_id_client).update({balance:parseFloat(new_client_balance)})\n \n \n // Credit Merchant\n const user = await auth.getUser() \n\n const {balance:merchant_balance_from_db,user_id:user_id_merchant} = await user.merchant().fetch()\n\n const new_merchant_balance = parseFloat(merchant_balance_from_db) + parseFloat(amount_to_send_from_client)\n\n await Merchant.query().where('user_id',user_id_merchant).update({balance:parseFloat(new_merchant_balance)})\n\n //add record in Transfer Table\n var timestamp = new Date().getTime()\n var amount = amount_to_send_from_client\n var sender_id = user_id_client\n var reciever_id = user_id_merchant\n const transfer_details ={amount,sender_id,reciever_id,timestamp}\n await Transfer.create({...transfer_details})\n\n\n\n return response.status(200).json({message:\"Transaction Successfull\"})\n\n\n }",
"function transferFunds(amount, user, escrow, loanId, orderBookId) {\n\n var amt = web3.toWei(amount);\n // console.log(orderBookId, amt);\n loanCreatorInstance.transferFunds(loanId, orderBookId, {\n from: user,\n value: amt\n }, function(err, res) {\n console.log(res);\n if (!err) {\n // var xhr = new XMLHttpRequest();\n // xhr.open(\"POST\", absolute_url + '/lender/fundTransferEvent', true);\n // xhr.setRequestHeader('Content-Type', 'application/json');\n // xhr.send(JSON.stringify({\n // from: user,\n // to: escrow,\n // txnId: res,\n // orderBookId: orderBookId,\n // loanId: loanId\n // }));\n } else {\n Snackbar.show({\n pos: 'top-center',\n text: \"Transaction Was Cancelled\"\n });\n }\n });\n}",
"function withdrawFunds() {\n \n var nullWithdrawalField = document.getElementById(\"withdraw-field\");\n if (nullWithdrawalField.value == \"\") {\n document.getElementById(\"popup-1\").classList.toggle(\"active\");\n return;\n }\n \n if(currentSelectedToken == \"ETH\") {\n var dep = contractInstance.methods.withdraw(web3.utils.toWei(String(nullWithdrawalField.value), \"ether\")).send({from: account}).on(\"transactionHash\", function(hash) { \n loadLoader();\n \n }).on(\"receipt\", function(receipt) {\n \n hideLoader();\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"Withdrawal successful! Balance has been updated\";\n displayAddOwnerPopup(popupMessage);\n \n }).on(\"error\", function(error) {\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"User denied the transaction\";\n displayAddOwnerPopup(popupMessage);\n hideLoader();\n \n }).then(function(result) {\n displayBalance()\n })\n }\n else {\n var dep = contractInstance.methods.withdrawERC20Token(web3.utils.toWei(String(nullWithdrawalField.value), \"ether\"), currentSelectedToken).send({from: account}).on(\"transactionHash\", function(hash) { \n loadLoader();\n \n }).on(\"receipt\", function(receipt) {\n \n hideLoader();\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"Withdrawal successful! Balance has been updated\";\n displayAddOwnerPopup(popupMessage);\n \n }).on(\"error\", function(error) {\n hideLoader();\n \n }).then(function(result) {\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"User denied the transaction\";\n displayAddOwnerPopup(popupMessage);\n displayBalance()\n })\n }\n \n updateAdminTables(\"fundsWithdrawed\")\n }",
"async withdrawFunds() {\n try {\n const receipt = await privateTokenSale.methods.withdrawFunds().send({ from: account });\n return receipt;\n } catch (e) {\n throw new Error(e);\n }\n }",
"async sendFundTransferRequests(id) {\n const transfer = this.bankTxRequestQueue[id];\n const data = {\n '$class': 'org.clearing.SubmitTransferRequest',\n 'transferId': transfer.id,\n 'toBank': transfer.toBank,\n 'state': 'PENDING',\n 'details': {\n '$class': 'org.clearing.Transfer',\n 'currency': transfer.currency,\n 'amount': transfer.amount,\n 'fromAccount': transfer.fromAccount,\n 'toAccount': transfer.toAccount\n }\n }\n try {\n const response = await rest.createTransferRequest(this.restURL, data);\n logger.debug(this.bankID + ': sendTransferRequest ' + id + 'response.status = ' + response.status);\n if (response.status == 200) {\n delete this.bankTxRequestQueue[id];\n }\n }\n catch (error) {\n logger.error('ERROR: ' + error);\n }\n }",
"function transferFundingFee(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount) { \r\n var options = {broadcast: true}; \r\n eos\r\n .contract(code)\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:feeAccount,quantity:arbPaidFee + \" \" + token,memo:\"arbitration release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n if (Number(doneeRelease) <= 0) {\r\n // skip donee - nothing to release\r\n transferFundingP1(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n } else {\r\n transferFundingDonee(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n })\r\n .catch(function (err) { console.log('error100'); }) \r\n }) \r\n}",
"async function showFundsOf(user, chain) {\n const method = simpleChargeContract.showFundsOf(user);\n const sender = nodeSender;\n\n if (chain === 'ropsten') {\n return await callFromRopsten(sender, method, null, 'uint256');\n } else {\n return await callFromRinkeby(sender, method, null, 'uint256');\n }\n}",
"async fundAccount(fundAmount) {\n await reach.transfer(this.state.faucet, this.state.acc, reach.parseCurrency(fundAmount));\n this.setState({view: 'ValidatorOrMember'});\n }",
"function transferFunds() {\n console.log(\"\\nTRANSFER FUNDS\");\n console.log(\"-----------------------------\");\n console.log(user.name + \", (ID: \" + user.id + \")\");\n console.log(\"Current balance: \" + Math.floor(user.balance* 100) / 100);\n console.log(\"-----------------------------\");\n const transferAmount = readline.question(\"How much money do you want to transfer (min. 1)?\\n>> \");\n\n if (transferAmount === \"quit\") {\n currentLoc = \"funds\";\n } else if (transferAmount > user.balance) {\n console.log(\"You don't have enough balance for that. Please try again with lower amount.\");\n transferFunds();\n } else if (transferAmount >= 1) {\n const transferTarget = readline.question(\"Which ID will receive transfer? (or 'quit' to go back)\\n>> \");\n\n const userArray = JSON.parse(fs.readFileSync(\"./accountDetails.json\", \"utf8\"));\n\n if (transferTarget === \"quit\") {\n currentLoc = \"funds\";\n } else if (transferTarget === user.id) {\n console.log(\"Receiving ID must be different than your own ID\");\n currentLoc = \"funds\";\n } else {\n // Compare userArray:s id:s with transferTarget's ID and take true/false in checkBoolean\n const checkBoolean = userArray.some((x)=> x.id === transferTarget);\n\n if (checkBoolean) {\n const toCheckPassword = readline.question(\"To transfer funds, please enter your password \" +\n \"(or type 'quit' to go back):\\n>> \");\n\n if (toCheckPassword === \"quit\") {\n currentLoc = \"funds\";\n } else {\n if (toCheckPassword === user.password) {\n user.balance = Number(user.balance) - Number(transferAmount);\n\n // Map wanted id from userArray, update balance and return data to newAllUsers.\n const newAllUsers = userArray.map(balanceFunction);\n function balanceFunction(x) {\n if (x.id === transferTarget) {\n x.balance = Number(x.balance) + Number(transferAmount);\n return x;\n } else if (x.id === user.id) {\n x.balance = user.balance;\n return x;\n } else {\n return x;\n }\n }\n\n // Saving newAllUsers back to accountDetails.json file\n fs.writeFileSync(\"./accountDetails.json\", JSON.stringify(newAllUsers), \"utf8\", (err) => {\n if (err) {\n console.log(\"Could not save userData to file!\");\n }\n });\n\n console.log(\"\\nTransfer successful, your balance in your account is now: \" +\n Math.floor(user.balance * 100) / 100);\n } else {\n console.log(\"\\nThe password is incorrect, please try again. (or 'quit' to go back to start)\");\n transferFunds();\n }\n }\n } else {\n console.log(\"No user found by that ID. Try again.\");\n transferFunds();\n }\n }\n } else {\n console.log(\"\\nSorry but min. transfer amount is 1e and you can only use numbers (or 'quit' to go back).\");\n transferFunds();\n }\n}",
"function transferAccountFunds(btcAmount, sourceAddress, targetAddress, sourceButton) {\n\tif ((targetAddress==null) || (targetAddress==undefined) || (targetAddress==\"\")) {\n\t\ttargetAddress = $(\"#transferTargetAddress\").val();\n\t}\n\tif ((targetAddress==null) || (targetAddress==undefined) || (targetAddress==\"\")) {\n\t\talert (\"No target address specified. Cannot transfer funds.\");\n\t\tthrow (new Error(\"No target address specified. Cannot transfer funds.\"));\n\t}\n\tvar params = new Object();\n\tparams.account = sourceAddress;\n\tparams.receiver = targetAddress;\n\tparams.btc = btcAmount;\n\tcurrentBatchTransferAccount = sourceAddress;\n\t$(sourceButton).replaceWith(\"<button class=\\\"transferButton\\\" data =\\\"\"+sourceAddress+\"\\\" disabled>Transfer pending...</button>\");\n\tcallServerMethod(\"admin_transferAccountFunds\", params, onTransferAccountFunds);\n}",
"function chargeUsers(params){\n let dfr = Q.defer();\n\n let requestId = params.requestId;\n let tokenUser2 = params.token;\n let expdate = params.expdate;\n let guests2 = params.guests;\n let verifyTransactionUser2 = params.transactionId;\n let transactionUser1;\n let transactionUser2;\n\n getRequest(requestId).then(function(request){\n let user1 = request.user1;\n let user2 = request.user2;\n let tokenUser1 = request.verifyTransactionUser1.token;\n let index1 = request.verifyTransactionUser1.index;\n let guests1 = request.guests1;\n let nights = request.nights;\n let plan = request.plan;\n\n let payment = {\n plan: plan,\n guests: guests1,\n nights: nights,\n };\n\n checkAvailability(user1._id, user2._id, request.checkin, request.checkout)\n .then(function() {\n if(user1.community && user1.community.discount)\n payment.discount = user1.community.discount;\n return transactionService.chargeRequest(tokenUser1, index1, user1, payment, user1.email);\n })\n .then(function(transactionId){\n transactionUser1 = transactionId;\n payment.guests = guests2;\n if(user2.community && user2.community.discount)\n payment.discount = user2.community.discount;\n // we still have the expiration date of the confirming user\n return transactionService.chargeRequest(tokenUser2, null, user2, payment, user2.email, expdate);\n })\n .then(function(transactionId){\n transactionUser2 = transactionId;\n let results = {\n requestId: requestId,\n verifyTransactionUser2: verifyTransactionUser2,\n transactionUser1: transactionUser1,\n transactionUser2: transactionUser2,\n };\n dfr.resolve(results);\n },function(err){\n dfr.reject(err);\n });\n });\n return dfr.promise;\n}",
"function transferFunding(person1,expectedBalance) { \r\n var options = {broadcast: true}; \r\n eos\r\n .contract('eosio.token')\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:person1,quantity:expectedBalance + \" \" + token,memo:\"rejected release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n finalReturn(outputMessage);\r\n })\r\n .catch(function (err) { console.log('error100'); }) \r\n }) \r\n}",
"function allFundingActionsForUser(userAddress) {\n return __awaiter(this, void 0, void 0, function* () {\n let query = `query {\n fpmmFundingAdditions(\n where: {funder: \"${userAddress}\"}\n first: 1000\n ){\n id\n fpmm {\n id\n }\n amountsAdded\n amountsRefunded\n sharesMinted\n timestamp\n }\n fpmmFundingRemovals(\n where: {funder: \"${userAddress}\"}\n first: 1000\n ){\n id\n fpmm {\n id\n }\n amountsRemoved\n collateralRemoved\n sharesBurnt\n timestamp\n }\n }`;\n var fundingData = null;\n yield query_subgraph(query).then((res) => {\n fundingData = res.data.data;\n }).catch((error) => {\n console.log(error);\n throw error;\n });\n return fundingData;\n });\n}",
"function transferFundingP1(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount) { \r\n if (Number(person1Release > 0)) {\r\n var options = {broadcast: true}; \r\n eos\r\n .contract(code)\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:person1,quantity:person1Release + \" \" + token,memo:\"arbitration release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n if (Number(person2Release) <= 0) {\r\n // finish - nothing to release\r\n finalReturn(outputMessage);\r\n } else {\r\n transferFundingP2(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n })\r\n .catch(function (err) { console.log('error102'); }) \r\n }) \r\n } else {\r\n // skip to person2\r\n transferFundingP2(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n}",
"function pledgeFund (req, res, callback){\n\tvar inputPayload = req.body;\n\tvar bankName = inputPayload.receiver;\n\tvar channel = inputPayload.channel;\n\tvar chaincodeName = helper.chainCodeMapping['bilateral'];\n\tif (!helper.validateBankInChannel(bankName,channel)){\n\t\tres.status(400)\n\t\tcallback({ error : util.format('%s / %s not found', bankName, channel ) });\n\t} else {\n\t\tvar response = {};\n\t\tvar amount = inputPayload.amount == null ? inputPayload.transactionAmount : inputPayload.amount;\n\t\tvar currency = config.default.currency == null ? inputPayload.currency : config.default.currency;\n\t\tvar masUsername = helper.getRUsername();\n\t\tvar masOrgName = helper.getOrg(masUsername);\n\t\tvar peers = helper.getPeersFromChannel(channel);\n\t\tvar fcn = 'pledgeFund';\n var args = [ bankName, currency, amount ];\n logger.warn(\"peers: %s, channel: %s, chaincodeName: %s, fcn: %s, args: %s, username: %s, orgname: %s\", peers, channel , chaincodeName , fcn, helper.stringify(args), masUsername, masOrgName)\n\t\tinvoke.invokeChaincode(peers, channel , chaincodeName , fcn, helper.stringify(args), masUsername, masOrgName)\n\t\t.then(function(message) {\n\t\t\tresponse = message;\n\t\t\tlogger.debug(message);\n\t\t\tif( message.status != 200 ){\n\t\t\t\tres.status(message.status)\n\t\t\t\tdelete response.status;\n\t\t\t} else {\n\t\t\t\tres.status(201)\n\t\t\t\tvar counterparty = helper.getCounterparty(helper.bankOrgMapping[bankName], channel)\n\t\t\t\tfundService.checkQueueAndSettle(bankName,counterparty,function(callback){}) //no need to wait for this function.\n\t\t\t}\n\t\t\tcallback(response);\n\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that copies resource files to choosen platform | function filesToCopy(obj, platform) {
var srcFile, destFile, destDir;
Object.keys(obj).forEach(function(key) {
var filename = path.basename(obj[key]);
srcFile = path.join(pluginRootDir, obj[key]);
destFile = path.join(rootdir, platformIosPath, filename);
console.log('copying ' + srcFile + ' to ' + destFile);
destDir = path.dirname(destFile);
if (fs.existsSync(srcFile) && fs.existsSync(destDir)) {
ncp(srcFile, destDir);
}
});
} | [
"function copyResources(platformName) {\r\n var resourcesFolder = __dirname + \"../../../\" + grunt.config.get('apps.resources');\r\n var appFolder = __dirname + \"../../../\" + grunt.config.get('apps.output.appsdir') + '/platforms/' + platformName;\r\n if (platformName === \"android\") {\r\n //Copy icons\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/android/icon-96-xhdpi.png'), path.normalize(appFolder + '/res/drawable/icon.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/android/icon-96-xhdpi.png'), path.normalize(appFolder + '/res/drawable-xhdpi/icon.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/android/icon-72-hdpi.png'), path.normalize(appFolder + '/res/drawable-hdpi/icon.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/android/icon-48-mdpi.png'), path.normalize(appFolder + '/res/drawable-mdpi/icon.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/android/icon-36-ldpi.png'), path.normalize(appFolder + '/res/drawable-ldpi/icon.png'));\r\n //Create folders for landscape splashscreen\r\n shell.mkdir('-p', path.normalize(appFolder + '/res/drawable-land-xhdpi'));\r\n shell.mkdir('-p', path.normalize(appFolder + '/res/drawable-land-hdpi'));\r\n shell.mkdir('-p', path.normalize(appFolder + '/res/drawable-land-mdpi'));\r\n shell.mkdir('-p', path.normalize(appFolder + '/res/drawable-land-ldpi'));\r\n //Copy splashscreen\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-xhdpi-portrait.png'), path.normalize(appFolder + '/res/drawable-xhdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-xhdpi-landscape.png'), path.normalize(appFolder + '/res/drawable-land-xhdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-hdpi-portrait.png'), path.normalize(appFolder + '/res/drawable-hdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-hdpi-landscape.png'), path.normalize(appFolder + '/res/drawable-land-hdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-mdpi-portrait.png'), path.normalize(appFolder + '/res/drawable-mdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-mdpi-landscape.png'), path.normalize(appFolder + '/res/drawable-land-mdpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-ldpi-portrait.png'), path.normalize(appFolder + '/res/drawable-ldpi/splash.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/android/screen-ldpi-landscape.png'), path.normalize(appFolder + '/res/drawable-land-ldpi/splash.png'));\r\n }\r\n else if (platformName === \"wp8\") {\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/wp8/icon-62-tile.png'), path.normalize(appFolder + '/ApplicationIcon.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/wp8/icon-173-tile.png'), path.normalize(appFolder + '/Background.png'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/wp8/screen-portrait.jpg'), path.normalize(appFolder + '/SplashScreenImage.jpg'));\r\n shell.cp('-f', path.normalize(resourcesFolder + '/configWP8.xml'), path.normalize(appFolder + '/config.xml'));\r\n }\r\n else if (platformName === \"ios\") {\r\n //Copy icons\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/icon/ios/*'), path.normalize(appFolder + '/KitchenSink/Resources/icons/'));\r\n //Copy splashscreen\r\n shell.cp('-f', path.normalize(resourcesFolder + '/res/screen/ios/*'), path.normalize(appFolder + '/KitchenSink/Resources/splash/'));\r\n }\r\n }",
"async copy_portable(loc){\n try{\n for(let p of [\n // burden\n portable,\n // commands\n ['run', 'app.js'],\n // docker related files\n 'Dockerfile', '.dockerignore', 'docker-compose.yml', 'docker-compose.dev.yml', \n ]){\n await fsx.copy(\n [this.config.base].concat(p).join(path.sep),\n [loc].concat(p).join(path.sep),\n { overwrite: false }\n );\n }\n }catch(e){\n //\n }\n }",
"function filesToCopy(obj, platform) {\n var srcFile, destFile, destDir;\n\n Object.keys(obj).forEach(function(key) {\n if(platform === 'android') {\n srcFile = path.join(rootdir, configAndroidPath, key);\n destFile = path.join(buildDir, platformAndroidPath, obj[key]);\n }\n console.log('copying ' + srcFile + ' to ' + destFile);\n\n console.log('file exists: ' + fs.existsSync(srcFile));\n console.log('destination directory exists: ' + fs.existsSync(destDir));\n\n destDir = path.dirname(destFile);\n console.log(\"destination dir: \" + destDir);\n if(!fs.existsSync(destDir)) {\n console.log('directory doesn\\'t exist');\n fs.mkdirSync(destDir, {recursive: true});\n };\n\n console.log('destination directory exists: ' + fs.existsSync(destDir));\n\n if (fs.existsSync(srcFile) && fs.existsSync(destDir)) {\n fs.createReadStream(srcFile).pipe(fs.createWriteStream(destFile));\n }\n });\n}",
"function copyResource() {\n return src(paths.resources)\n .pipe(dest(paths.dist));\n}",
"function copyResources() {\n const resourcesFolder = path.join(config.rootFolder, 'resources');\n fs.copy(resourcesFolder, config.docFolder, (error) => {\n if (error) logger.error(`Unable to copy resources in documentation folder ${config.docFolder}: ${error}`);\n });\n}",
"static copyTestApp(platform) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst\n\t\t\t\tappRoot = path.join(global.projRoot, 'Build', platform, app.name),\n\t\t\t\tfilePath = path.join(appRoot, 'Resources', 'app.js'),\n\t\t\t\ttestApp = path.join(global.projRoot, 'Config', 'Support', 'app.js');\n\n\t\t\treadFilePromise(testApp)\n\t\t\t\t.then(data => fs.writeFile(filePath, data))\n\t\t\t\t.then(resolve())\n\t\t\t\t.catch(e => reject(e));\n\n\t\t});\n\t}",
"function copyAdditionalContent(slidedeck) {\n\n let params = {};\n const path = slidedeck.fullpath.substring(0, slidedeck.fullpath.lastIndexOf(\"/\"));\n\n staticAdditionalContent.forEach(function (folder) {\n folder = escape(folder);\n params.src = path + \"/\" + folder;\n params.target = staticDefaultOutput + slidedeck.relpath + folder;\n console.log(params.src + \"->\" + params.target);\n \n if(fs.existsSync(params.src)){ fs.copySync(params.src, params.target); }\n });\n fs.copySync(basepath + \"/../\" + theme_folder + \"/\",\n staticDefaultOutput + \"/\" + slidedeck.relpath + \"/\" + staticAssetFolder + \"/\" + theme_folder + \"\");\n \n}",
"function copyResources (rootDir, resourceMap) {\n resourceMap.forEach(element => {\n const elementKeys = Object.keys(element);\n\n if (elementKeys.length) {\n const value = elementKeys.map((e) => element[e])[0];\n fs.copySync(path.join(rootDir, elementKeys[0]), value);\n }\n });\n}",
"function getCopyPath(platform, begPath, endPath) \n{\n return [\n path.resolve(begPath + config('defaultPlatformsConfig')[platform].root + endPath)\n ];\n}",
"function copy() {\n console.log( taskHeader(\n '3/5',\n 'Release',\n 'Copy files',\n 'To temporary folder'\n ) );\n\n const getReleaseFiles = () => {\n let files = [];\n\n if ( WORDPRESS_PARENT_THEME ) {\n files = sources.wordPressThemeReleaseFiles;\n } else if ( WORDPRESS_PLUGIN || WORDPRESS_PLUGIN_BOILERPLATE ) {\n files = sources.wordPressPluginReleaseFiles;\n }\n\n return files;\n };\n\n // return stream or promise for run-sequence\n // https://stackoverflow.com/a/32188928/6850747\n return src( getReleaseFiles(), { allowEmpty: true, base: '.' } )\n .pipe( print() )\n .pipe( dest( targets.zipSource ) );\n}",
"addResource(fileRelativePath) {\n\n // Add file reference, fix bug in xcode about uuid vs fileRef\n let file = this.pbx.addFile(fileRelativePath, )\n file.uuid = file.fileRef = file.fileRef || file.uuid\n\n // Go through all projects\n for (let project of this.projects()) {\n\n // Find Resources group\n let mainGroup = this.object(project.value.mainGroup)\n let children = mainGroup.value.children.map(c => this.object(c.value))\n let resourceGroup = children.find(c => c.value.name == 'Resources')\n if (!resourceGroup) {\n\n // No resource group, create one\n let id = this.pbx.generateUuid()\n this.pbx.hash.project.objects['PBXGroup'][id + '_comment'] = 'Resources'\n this.pbx.hash.project.objects['PBXGroup'][id] = {\n isa: 'PBXGroup',\n name: 'Resources',\n sourceTree: '\"<group>\"',\n children: []\n }\n\n // Add group to main group\n this.pbx.hash.project.objects['PBXGroup'][mainGroup.id].children.push({\n value: id,\n comment: 'Resources'\n })\n\n resourceGroup = this.object(id)\n\n }\n\n // Add file to Resources group\n this.pbx.hash.project.objects['PBXGroup'][resourceGroup.id].children.push({\n value: file.uuid,\n comment: fileRelativePath\n })\n\n // Go through all targets in this project\n for (let target of this.projectTargets(project.id)) {\n\n // Skip if target is not an application\n if (!target.value.productType.includes('com.apple.product-type.application'))\n continue\n\n // Find resource build phase\n let buildPhases = target.value.buildPhases.map(bp => this.object(bp.value))\n let resourcePhase = buildPhases.find(bp => bp.value.isa == 'PBXResourcesBuildPhase')\n if (!resourcePhase)\n continue\n\n // Add a build file reference\n let buildID = this.pbx.generateUuid()\n this.pbx.hash.project.objects['PBXBuildFile'][buildID + '_comment'] = fileRelativePath\n this.pbx.hash.project.objects['PBXBuildFile'][buildID] = {\n isa: 'PBXBuildFile',\n fileRef: file.uuid,\n fileRef_comment: fileRelativePath\n }\n\n // Add file to this phase\n this.pbx.hash.project.objects['PBXResourcesBuildPhase'][resourcePhase.id].files.push({\n value: buildID,\n comment: fileRelativePath\n })\n\n }\n }\n\n }",
"function copyImages (version) {\n\t\t\t\t\t\tvar images = ['blue.jpg', 'green.jpg', 'orange.jpg', 'red.jpg'];\n\n\t\t\t\t\t\tfse.copy(`${appRoot}/base-template/global-images`, `${dir}/${Static}/${versions[version]}/${img}`, (err) => {\n\t\t\t \tif (err) {\n return console.error(\"error:\", err);\n }\n\n console.info(chalk.green(\"static images folder copied successfully.\"));\n\t\t\t });\n\t\t\t\t\t}",
"checkFile(name) {\n if(!fs.existsSync(this.folder + \"/\" + name)) {\n if(fs.existsSync(\"default/\" + name)) {\n fs.copyFileSync(\"default/\" + name, this.folder + \"/\" + name)\n } else {\n fs.copyFileSync(\"resources/app/default/\" + name, this.folder + \"/\" + name)\n }\n }\n }",
"function createResourceMap (cordovaProject, locations, resources) {\n const resourceMap = [];\n\n for (const key in resources) {\n const resource = resources[key];\n\n if (!resource) {\n continue;\n }\n\n let targetPath;\n switch (key) {\n case 'customIcon':\n // Copy icon for the App\n targetPath = path.join(locations.www, 'img', `app${resource.extension}`);\n resourceMap.push(mapResources(cordovaProject.root, resource.src, targetPath));\n // Copy icon for the Installer\n targetPath = path.join(locations.buildRes, `installer${resource.extension}`);\n resourceMap.push(mapResources(cordovaProject.root, resource.src, targetPath));\n break;\n case 'appIcon':\n targetPath = path.join(locations.www, 'img', `app${resource.extension}`);\n resourceMap.push(mapResources(cordovaProject.root, resource.src, targetPath));\n break;\n case 'installerIcon':\n targetPath = path.join(locations.buildRes, `installer${resource.extension}`);\n resourceMap.push(mapResources(cordovaProject.root, resource.src, targetPath));\n break;\n case 'highResIcons':\n for (const key in resource) {\n const highResIcon = resource[key];\n targetPath = path.join(locations.www, 'img', 'icon');\n targetPath += highResIcon.suffix === '1x' ? highResIcon.extension : `@${highResIcon.suffix}${highResIcon.extension}`;\n resourceMap.push(mapResources(cordovaProject.root, highResIcon.src, targetPath));\n }\n break;\n case 'splashScreen':\n targetPath = path.join(locations.www, '.cdv', `splashScreen${resource.extension}`);\n resourceMap.push(mapResources(cordovaProject.root, resource.src, targetPath));\n break;\n }\n }\n return resourceMap;\n}",
"function copyDirInit() {\n window.resolveLocalFileSystemURL(cordova.file.applicationDirectory+\"www\",\n function(sourceDir) {\n let srcDir = 'hymnals-data'; \n let destDir = 'hymnals-data'; \n sourceDir.getDirectory(srcDir, {create: false}, function (directory){\n window.resolveLocalFileSystemURL(cordova.file.dataDirectory+\"www\",\n function(parentDir){\n directory.copyTo(parentDir, destDir, function(){},function(e){} )\n }\n ,null);\n }\n , \n function(){});\n }\n ,function(){});\n}",
"function copyStatic() {\n console.log(\"Copying static files...\");\n fs.readdirSync(\"_static\").forEach(function(file, index) {\n var curPath = \"_static/\" + file;\n if (fs.lstatSync(curPath).isDirectory()) {\n if (!fs.existsSync(curPath.replace(\"_static\", \"_site\"))) {\n fs.mkdirSync(curPath.replace(\"_static\", \"_site\"));\n }\n fs.readdirSync(curPath).forEach(function(file, index) {\n fs.readFile(curPath + '/' + file, function(err, data) {\n fs.writeFileSync(curPath.replace(\"_static\", \"_site\") + '/' + file, data);\n });\n });\n } else {\n fs.readFile(\"_static/\" + file, function(err, data) {\n fs.writeFileSync(\"_site/\" + file, data);\n });\n }\n });\n console.log(\"Copied to _site.\");\n if (job == \"build\" || job == false) {\n preprocess();\n } else {\n finish();\n }\n}",
"function copyToWP() {\n return gulp.src( '../www/{images,fonts,js,css}/**/*' ).pipe( gulp.dest( PATHS.wp ) );\n}",
"function addDefaultImagesToProjectResources(projectDirectory, platform) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n // Copy default resources into the platform directory\r\n const resourcesDir = path.resolve(projectDirectory, 'resources', platform);\r\n const platformResourceDir = path.resolve(DEFAULT_RESOURCES_DIR, platform);\r\n yield cli_utils_1.fsMkdirp(platformResourceDir);\r\n yield cli_utils_1.copyDirectory(platformResourceDir, resourcesDir);\r\n const resourceJson = yield getResourceConfigJson();\r\n return addResourcesToConfigXml(projectDirectory, [platform], resourceJson);\r\n });\r\n}",
"function copyAssets(cb) {\n if (name) {\n console.log('copying assets…');\n src([\n './themes/' + name + '/archetypes',\n './themes/' + name + '/layouts/*.*',\n './themes/' + name + '/layouts/_default/**/*',\n './themes/' + name + '/layouts/partials/**/*',\n ], { read: false })\n .pipe(clean());\n src('./themes/bugo-src/assets/scss/custom/**/*')\n .pipe(dest('./themes/' + name + '/assets/scss/custom'));\n addConfigTheme(cb);\n } else { \n console.log('error no name');\n cb();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attaches the RightPanel to a Right Panel. | attach() {
if (!this.panel) {
this.panel = atom.workspace.addRightPanel({item: this, visible: false, priority: -1000});
}
} | [
"setRightPanel(panel)\n {\n this.addSubPanel(panel);\n this.rightPanel = panel;\n // TODO: Resize the panel!\n // TODO: Check that the right panel did not set before!\n }",
"addToRightArea(widget, options) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n options = options || this._sideOptionsCache.get(widget) || {};\n this._sideOptionsCache.set(widget, options);\n let rank = 'rank' in options ? options.rank : DEFAULT_RANK;\n this._rightHandler.addWidget(widget, rank);\n this._onLayoutModified();\n }",
"_addToRightArea(widget, options) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n options = options || this._sideOptionsCache.get(widget) || {};\n const rank = 'rank' in options ? options.rank : DEFAULT_RANK;\n this._sideOptionsCache.set(widget, options);\n this._rightHandler.addWidget(widget, rank);\n this._onLayoutModified();\n }",
"expandRight() {\n this._rightHandler.expand();\n this._onLayoutModified();\n }",
"collapseRight() {\n this._rightHandler.collapse();\n this._onLayoutModified();\n }",
"attachToRightController() {\n this.root.parent = this.vrHelper.controller.right.grip;\n this.root.position = new BABYLON.Vector3(-this.verticalWeb,0,.1);\n this.root.rotation = new BABYLON.Vector3(Math.PI/2,0,-Math.PI/2);\n //this.rowOffset = new BABYLON.Vector3(this.verticalXR,0,0);\n this.rowOffset = new BABYLON.Vector3(0,this.verticalXR,0);\n this.currentController = 'right';\n }",
"setRight(newRight) {\n this.#rightChild = newRight;\n }",
"function ELEMENT_RIGHT$static_(){CommentMetaDataPanel.ELEMENT_RIGHT=( CommentMetaDataPanel.BLOCK.createElement(\"right\"));}",
"function open_right_panel() {\n // if already open, bail out\n if ( __is_panel_open ) {\n return;\n }\n __is_panel_open = true;\n $( '#part-right' ).addClass( 'expanded' );\n}",
"function PanelOpener(element, rightPanel, parameters){\n\tthis.element = element;\n\tthis.rightPanel = rightPanel;\n\tthis.parameters = parameters;\n\t\n\tthis.onClick = function(params){\n\t\tvar passedParameters = params.data;\n\t\tvar newPanel = passedParameters.opener.rightPanel;\n\t\tif(newPanel == null){\n\t\t\tconsole.log(\"Right panel is null for mainMenu, not doing anything\");\n\t\t} else {\n\t\t\tnewPanel.show(passedParameters.rightPanel, passedParameters.opener.parameters); \n\t\t}\n\t}\n}",
"shiftRight() {\n this.manager.shiftRight(this);\n }",
"dockRight(referenceNode, newNode) {\n this._performDock(referenceNode, newNode, 'horizontal', false);\n }",
"function initRightMenu() {\r\n rmenu = node({className: 'helperMenu', style: {position: 'absolute'}});\r\n rmenu.style.right = '2px';\r\n rmenu.style.top = '0px';\r\n rmenu.style.position = \"fixed\";\r\n document.body.appendChild(rmenu);\r\n// rmenu.appendChild(createMenuLink(0,'Options',popupOptions));\r\n rmenu.appendChild(node({className: 'helperMenu', html: 'Quick Bookmarks', style: {textDecoration: 'underline'}}));\r\n addMarkLocations();\r\n displayQuickMarks();\r\n}",
"function slideRight () {\n\n if (canSlideRight()) {\n index = Math.min(getMaxIndex(), index + cols);\n update(true);\n }\n }",
"showRight() {\n this.tooltipElement.classList.add(getClass(\"right\"));\n this.element.style.setProperty(\"left\", toPx(this.node.getBoundingClientRect().left + this.node.offsetWidth + 10));\n this.centerVertically();\n }",
"function shiftToRight(){\n updateCurrentRight();\n updateDisplayRight();\n $slider.addClass('moving');\n $slideContainer.animate({'margin-left': '-='+totalWidth}, animationSpeed, function(){\n $slider.removeClass('moving');\n });\n }",
"function createRightPanel() {\n var rightPanel = '<td class=\"Bu\"><div id =\"rightPanel\" style=\"z-index:10; display:none; top: 47px; right: 30px; width: 240px; height: 350px; position: absolute; background-color:white;\">';\n rightPanel += '</div></td>';\n return rightPanel;\n}",
"function makeRightPanel(tier, title, color) {\n\tif($(\"#\" + title).data(\"thistext\") != undefined) {\n\t\tvar thisText = $(\"#\" + title).data(\"thistext\");\n\t} else {\n\t\tvar thisText = \"\";\n\t}\t\n var rightPanelHTML = \"<div id='right-panel-\" + tier + \"' class='right-panel'>\";\n rightPanelHTML = rightPanelHTML + \"<div id='right-panel-top-\" + tier + \"' class='right-panel-top'><div class='title-text'>\" + title + \"</div></div>\";\n rightPanelHTML = rightPanelHTML + \"<form>\";\n rightPanelHTML = rightPanelHTML + \"<textarea class='right-panel-textarea'>\" + thisText + \"</textarea>\";\n\trightPanelHTML = rightPanelHTML + \"<button type='button' id='right-panel-submit-normal-green' class='right-panel-submit-normal' title='\" + title + \"'>Add Normal</button>\";\n\trightPanelHTML = rightPanelHTML + \"<input type='submit' id='right-panel-submit-red' class='right-panel-submit' title='\" + title + \"' value='Add Issue'>\";\n\trightPanelHTML = rightPanelHTML + \"<div class='push'></div>\";\n rightPanelHTML = rightPanelHTML + \"</form>\";\n rightPanelHTML = rightPanelHTML + \"</div>\";\n $(\"#right-panel-wrapper\").append(rightPanelHTML);\n $(\"#right-panel-\" + tier).transition({opacity: 1, x: 0}, 500);\n}",
"_addToLeftArea(widget, options) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n options = options || this._sideOptionsCache.get(widget) || {};\n this._sideOptionsCache.set(widget, options);\n const rank = 'rank' in options ? options.rank : DEFAULT_RANK;\n this._leftHandler.addWidget(widget, rank);\n this._onLayoutModified();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================== 38. Write a JavaScript function to check if a number is a whole number or has a decimal place. Note : Whole Numbers are simply the numbers 0, 1, 2, 3, 4, 5, ... (and so on). No Fractions! Test Data : console.log(number_test(25.66)); "Number has a decimal place." console.log(number_test(10)); "It is a whole number." ============================== | function isWholeOrDecimal(num){
if (parseInt(num) === num){
return "whole num";
}else {
return "decimal num";
}
} | [
"function number_test(n)\r\n{\r\n var result = (n - Math.floor(n)) !== 0;\r\n\r\n if (result)\r\n return 'Number has a decimal place.';\r\n else\r\n return 'It is a whole number.';\r\n }",
"function testWholeNumber(number) {\n let result = (number - Math.floor(number)) !== 0;\n result ? console.log(\"Decimal Number\") : console.log(\"Whole Number Found\")\n}",
"function number_test(n) {\n var result = (n - Math.floor(n)) !== 0; \n \n if (result)\n return 'decimal';\n else\n return 'whole';\n}",
"function wholeNumber(value) {\n var integer = Number.isInteger(parseFloat(value));\n var sign = Math.sign(value);\n if (integer && (sign === 1)) {\n return true;\n } else {\n return 'Errr...please enter a whole number.';\n }\n}",
"function checknumericalInput(number) {\r\n let regexpattern = new RegExp(\"^\\\\d+\\.?\\\\d*$\");\r\n return regexpattern.test(number); // returns true if passed\r\n}",
"function isdecimal(num) {\n return (/^\\d+(\\.\\d+)?$/.test(num + \"\"));\n}",
"function isDecimal(number)\r\n{\r\n //var decimal= /^[0-9]+(\\.[0-9]+)+$/;\r\n \r\n var integer = /^[0-9]+$/;\r\n \r\n if(number.match(integer)) {\r\n\r\n return true;\r\n }\r\n else {\r\n\r\n return false;\r\n }\r\n}",
"function IsAWholeNumber(value)\n { \n if (!(isNaN(value)))\n {\n if (value % 1 == 0)\n {\n //alert('Whole Number');\n return true;\n }\n else\n {\n //value('Not a Whole Number');\n return false;\n }\n }\n else\n {\n return false;\n }\n }",
"function decimal_check(value) {\n\tconsole.log(current_num);\n\tif (current_num.indexOf(\".\") == -1) {\n\t\tdisplay_value(value);\n\t} \n}",
"function decimalpoint(number) {\n \t\treturn (number.indexOf(\".\") > 0);\n\t}",
"function isDecimalNumber (handsontable, row, col, value, limit) {\n var valid; \n \n if (value) { \n \t\n\t\t// trunk the Integer part\n\t\tvar dotIdx = value.indexOf(\".\");\n\t\t\n\t\tif (dotIdx > -1) {\n\t\t\tvar leftDot = value.substring(0, dotIdx);\n\t\t} else {\n\t\t\tleftDot = value;\n\t\t}\n\t\n\t if (limit == undefined) {\n\t valid = (floatPattern.test(value));\n\t } else {\n\t \tvalid = (floatPattern.test(value) && leftDot.length <= limit);\n\t }\n } else {\n \tvalid = true;\n }\n \n if (valid) {\n \thandsontable.getCellMeta(row, col).valid = true;\n handsontable.render();\n \n return true;\n \n } else {\n \thandsontable.getCellMeta(row, col).valid = false;\n handsontable.render();\n \n return false;\n }\n}",
"function testNumber(value) {\r\n\t\tif(!isNaN(parseFloat(value)) && isFinite(value)) { /* Test passes, it is a number*/ return true; }\r\n\t\telse { return false; }\r\n}",
"function testNumber(n, amtPRow)\n{\n var newN = n / amtPRow;\n var result = (newN - Math.floor(newN)) !== 0;\n\n\n return result;\n}",
"function checkDecimalNotAllowed() {\n let equation = inputDisplay.textContent.split(\" \");\n let firstNum = equation[0];\n let mathOp = equation[1];\n let secondNum = equation[2];\n\n if (mathOp === undefined) mathOp = \"\";\n if (secondNum === undefined) secondNum = \"\";\n\n if (firstNum.length !== 0 && mathOp.length === 0\n && secondNum.length === 0 && firstNum.includes(\".\")) {\n return true\n } else if (firstNum.length !== 0 && mathOp.length !== 0\n && secondNum.length !== 0 && secondNum.includes(\".\")) {\n return true;\n }\n\n return false;\n}",
"function verifyFrac(test00)\n {\n \n if (/^(\\d{1,10}[.,]\\d{1,5})$/.test(test00) && !/^(\\d{1,10}[.,][0])$/.test(test00)\n && !/^(\\d{1,10}[.,][0][0])$/.test(test00) && !/^(\\d{1,10}[.,][0][0][0])$/.test(test00) \n && !/^(\\d{1,10}[.,][0][0][0][0])$/.test(test00) && !/^(\\d{1,10}[.,][0][0][0][0][0])$/.test(test00))\n {\n var msg0 = \"It's a fraction!\";\n \n message(msg0);\n return msg0; \n \n }\n else {\n var msg0 = \"It's not a fraction!\";\n \n message(msg0);\n return msg0;\n \n }\n\n }",
"function wholeNumber(fraction) {\n assert.equal(typeof fraction, 'number');\n\n return Math.abs(Math.round(fraction));\n}",
"function isNumber(data) {\n var intRegex = /^\\d+$/;\n var floatRegex = /^((\\d+(\\.\\d *)?)|((\\d*\\.)?\\d+))$/;\n if (intRegex.test(data) || floatRegex.test(data)) {\n return true;\n }\n return false\n}",
"function checkDecimal () {\n if (decimalCounter <= 1) {\n return true;\n } else {\n return false;\n }\n}",
"function CheckThirdDigit(number) {\n var digit = (number / 100) % 10 | 0,\n check = digit == 7; // round with | 0\n\n if (check) {\n return console.log(check);\n } else {\n return console.log('false ' + digit);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a boolean telling if a macro exists | static hasMacro(name) {
return !!this.getMacro(name);
} | [
"has(e) {\n\t\t\te = insensitiveName(e);\n\t\t\treturn macroRegistry.hasOwnProperty(e);\n\t\t}",
"function isDefinition(token) {\n return token == HABILIS.FUNCTIONS['define'];\n}",
"function isMacroFile(fileName) {\r\n return /\\.iim$/i.test(fileName);\r\n}",
"function functionExists( name ) {\n\treturn( 'function' === eval('typeof ish.' + name) );\n}",
"function _defined(moduleName) {\n return _moduleMap[moduleName] ? true : false;\n}",
"function findMacro(macroName) {\n\n console.log(\"Searching for '\" + macroName +\"' in macros file ...\");\n for (i = 0; i < totalMacros; i++) {\n if (macros[i].name.toUpperCase() == macroName) {\n console.log(\"Found! (\" + i + \")\");\n return i;\n }\n }\n\n console.log(\"Not found!\");\n return -1;\n}",
"function IsMacro()\n{\n return gameStyle;\n}",
"function checkMacros() {\n const playerList = findObjs({ _type: 'player', _online: true });\n const gm = playerList.find((player) => {\n return playerIsGM(player.id) === true;\n });\n const macroArr = [\n {\n name: 'PaladinAuraHelp',\n action: `${apiCall} help`\n },\n {\n name: 'PaladinAuraToggle',\n action: `${apiCall}`\n },\n {\n name: 'PaladinAuraConfig',\n action: `${apiCall} config`\n }\n ];\n macroArr.forEach((macro) => {\n const macroObj = findObjs({\n _type: 'macro',\n name: macro.name\n })[0];\n if (macroObj) {\n if (macroObj.get('visibleto') !== 'all') {\n macroObj.set('visibleto', 'all');\n toChat(`**Macro '${macro.name}' was made visible to all.**`, true);\n }\n if (macroObj.get('action') !== macro.action) {\n macroObj.set('action', macro.action);\n toChat(`**Macro '${macro.name}' was corrected.**`, true);\n }\n }\n else if (gm && playerIsGM(gm.id)) {\n createObj('macro', {\n _playerid: gm.id,\n name: macro.name,\n action: macro.action,\n visibleto: 'all'\n });\n toChat(`**Macro '${macro.name}' was created and assigned to ${gm.get('_displayname') + ' '.split(' ', 1)[0]}.**`, true);\n }\n });\n }",
"function _functionExists(functionName) {\n\t\t\treturn typeof ABTest[functionName] == 'function';\n\t\t}",
"function checkMacros() {\n\n\t_.each(macros,function(macroName){\n\n\t\tvar macro = findObjs({_type: \"macro\", name: macroName})[0];\n \tvar playerList = findObjs({_type: \"player\"});\n\t\tvar playerID = playerList[0].id;\n\t\tvar GMFound = false;\n\t\t\n\t\t_.find(playerList,function(player){ \n var thisID = player.id;\n if(playerIsGM(thisID)){\n playerID = thisID;\n return thisID;\n }\n });\n\t\t\n var GMid = playerID;\n\n\t\tif(!macro) {\n\t\t\tswitch(macroName) {\n\t\t\t\tcase \"Saves\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n break;\n\t\t\t\tcase \"ScatterDie\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ScatterDie ?{Ballistic Skill|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToPen\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToWound\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n \n\t\t\tswitch(macroName) {\n\t\t\t\tcase \"Saves\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ScatterDie\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ScatterDie ?{Ballistic Skill|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ScatterDie ?{Ballistic Skill|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToPen\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToWound\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t});\n}",
"isDefinition() {\r\n return this.compilerObject.isDefinition;\r\n }",
"get isDefined() {\n return !!fastRegistry.getByType(this.type);\n }",
"hasHelper(name) {\n return !!hbs.helpers[name];\n }",
"isRegistered(name) {\n return this.plugins.has(name);\n }",
"hasProcessor(name) {\n let found = false;\n for (let processor of this.processors)if (processor.name === name) found = true;\n return found;\n }",
"function function_exists( function_name ) {\n if (typeof function_name == 'string'){\n return (typeof window[function_name] == 'function');\n } else{\n return (function_name instanceof Function);\n }\n}",
"static getMacro(name) {\n return this.macros[name];\n }",
"hasComponent(name){\n return this.#components.has(name);\n }",
"function module_exists (name) {\n try { return require.resolve(name) } catch (e) { return false }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display all text objects in a table | function printListTextobjects(textobjects) {
logger(1, 'DEBUG: printing text objects list');
var text
, body = '<div class="table-responsive">' +
'<table class="table">' +
'<thead>' +
'<tr>' +
'<th>' + MESSAGES[92] + '</th>' +
'<th>' + MESSAGES[19] + '</th>' +
'<th>' + MESSAGES[95] + '</th>' +
'<th style="width:69%">' + MESSAGES[146] + '</th>' +
'<th style="width:9%">' + MESSAGES[99] + '</th>' +
'</tr>' +
'</thead>' +
'<tbody>'
;
$.each(textobjects, function (key, value) {
var textClass = '',
text = '';
if (value['type'] == 'text') {
text = $('#customText' + value['id'] + ' p').html();
textClass ='customText'
}
body +=
'<tr class="textObject' + value['id'] + '">' +
'<td>' + value['id'] + '</td>' +
'<td>' + value['name'] + '</td>' +
'<td>' + value['type'] + '</td>' +
'<td>' + text + '</td>' +
'<td>';
if (ROLE != "user" && LOCK == 0 ) {
body += '<a class="action-textobjectdelete '+ textClass +'" data-path="' + value['id'] + '" data-name="' + value['name'] + '" href="javascript:void(0)" title="' + MESSAGES[65] + '">' +
'<i class="glyphicon glyphicon-trash" style="margin-left:20px;"></i>' +
'</a>'
}
body += '</td>' +
'</tr>';
});
body += '</tbody></table></div>';
addModalWide(MESSAGES[150], body, '');
} | [
"function printListTextobjects(textobjects) {\n logger(1, 'DEBUG: printing text objects list');\n var text,\n body =\n '<div class=\"table-responsive\">' +\n '<table class=\"table\">' +\n '<thead>' +\n '<tr>' +\n '<th>' +\n MESSAGES[92] +\n '</th>' +\n '<th>' +\n MESSAGES[19] +\n '</th>' +\n '<th>' +\n MESSAGES[95] +\n '</th>' +\n '<th style=\"width:69%\">' +\n MESSAGES[146] +\n '</th>' +\n '<th style=\"width:9%\">' +\n MESSAGES[99] +\n '</th>' +\n '</tr>' +\n '</thead>' +\n '<tbody>';\n $.each(textobjects, function (key, value) {\n if (value['type'] == 'text') {\n text = $('#customText' + value['id'] + ' p').html();\n } else {\n text = '';\n }\n\n body +=\n '<tr class=\"textObject' +\n value['id'] +\n '\">' +\n '<td>' +\n value['id'] +\n '</td>' +\n '<td>' +\n value['name'] +\n '</td>' +\n '<td>' +\n value['type'] +\n '</td>' +\n '<td>' +\n text +\n '</td>' +\n '<td>';\n if (ROLE != 'user') {\n body +=\n '<a class=\"action-textobjectdelete\" data-path=\"' +\n value['id'] +\n '\" data-name=\"' +\n value['name'] +\n '\" href=\"javascript:void(0)\" title=\"' +\n MESSAGES[65] +\n '\">' +\n '<i class=\"glyphicon glyphicon-trash\" style=\"margin-left:20px;\"></i>' +\n '</a>';\n }\n body += '</td>' + '</tr>';\n });\n body += '</tbody></table></div>';\n addModalWide(MESSAGES[150], body, '');\n}",
"populateTable(text) {\n document.getElementById(\"text-dropdown\").innerHTML = text.title;\n document.getElementById(\"tot_time\").innerHTML = text.tot_time + \" minutes\";\n document.getElementById(\"num_words_read\").innerHTML = text.num_words_read + \" words\";\n document.getElementById(\"wpm\").innerHTML = text.wpm + \" wpm\";\n document.getElementById(\"diff_words\").innerHTML = text.diff_words;\n }",
"function createTableText(people){\n var person;\n var text = \"<tr><th>User</th><th>Jobs</th><th>Processors</th></tr>\";\n for (person of people){\n text += \"<tr><td>\"+person.name+\"</td><td>\"+person.jobs+\"</td><td>\"+person.proc+\"</td></tr>\";\n }\n return text;\n}",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get get the current aliensObject object and its fields\n var aliensObject = filteredAliens[i];\n var info = Object.keys(aliensObject);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < info.length; j++) {\n // For every field in the aliensObject object, create a new cell at set its inner text to be the current value at the current aliensObject' info\n var alien = info[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = aliensObject[alien];\n }\n }\n }",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < UFO.length; i++) {\n // Get get the current UFO object and its fields\n var ufo = UFO[i];\n var observations = Object.keys(ufo);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < observations.length; j++) {\n // For every observations in the ufo object, create a new cell at set its inner text to be the current value at the current ufo'sobservation\n var observation = observations[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo[observation];\n }\n }\n}",
"function TextRow() {}",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < ufo.length; i++) {\n // Get get the current ufo object and its fields\n var ufo_data = ufo[i];\n var fields = Object.keys(ufo_data);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the ufo object, create a new cell at set its inner text to be the current value at the current ufo's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo_data[field];\n }\n }\n}",
"splitTextIntoTable (text) {\n const firstLineArray = this.getColumnHeader(text)\n const contentArray = this.getRows(text)\n const contentObject = this.createContentForTable(firstLineArray, contentArray)\n\n this.fields = firstLineArray\n this.data = contentObject\n }",
"function loadAllTableText() {\r\n var tablesearchTables = $('.tablesearch-table');\r\n\r\n for (var count = 0; count < tablesearchTables.length; count++)\r\n loadTableText(tablesearchTables[count]);\r\n}",
"function displayTableHead(objectArray) {\r\n let displayedResults = \"<tr>\";\r\n let properties = Object.keys(objectArray[0])\r\n for (let i = 0; i < properties.length; i++) {\r\n displayedResults += `<td>${properties[i]}</td>`;\r\n }\r\n displayedResults += \"</tr>\";\r\n tableHeadTarget.innerHTML = displayedResults;\r\n}",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredDataSet.length; i++) {\n\n // Get the current object and its fields\n var data = filteredDataSet[i];\n var fields = Object.keys(data);\n\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n\n // For every field in the table object, create a new cell at set its inner text to be the current value at the current field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = data[field];\n }\n }\n}",
"function textObjectArrayHtml(content, relexMap) {\n let html = \"\";\n let isList = content.length > 1;\n if (isList) {\n html += \"<ul>\";\n }\n\n for (let textObject of content) {\n if (isList) {\n html += \"<li>\";\n }\n if (textObject.tag === undefined) {\n let lines = textObject.text.split(\"\\n\");\n for (let line = 0; line < lines.length; line++) {\n if (line > 0) {\n html += isList ? \"</ul><ul>\" : \"<br/>\";\n }\n html += \"<span class='nbx-text'>\" + encode(lines[line]) + \"</span>\";\n }\n }\n else {\n // Tagged element => entity with an offset as its id.\n html += \"<table>\";\n let relations = relexMap[textObject.offset];\n if (relations !== undefined) {\n for (let r = 0; r < relations.length; r++) {\n let relation = relations[r];\n let odd = r % 2 === 0 ? \"even\" : \"odd\";\n html += \"<tr class='nbx-RELEX-\" + odd + \"'><td>\" + encode(relation.type) + \"</td></tr>\";\n if (relation.endOffset !== relation.startOffset) {\n html += \"<tr><td class='nbx-ref-\" + odd + \" ref-\" + getId(relation.endOffset) + \"'>\" + encode(relation.endToken) + \"</td></tr>\";\n }\n }\n }\n\n let text = textObject.text.replace(/ *[\\n] */g, \" \");\n html +=\"<tr><td class='nbx-\" + textObject.tag + \"'>\" + encode(textObject.type) + \"</td></tr>\" +\n \"<tr><td class='ref-\" + getId(textObject.offset) + \" nbx-text' id='\" + getId(textObject.offset) + \"'>\" + encode(text) + \"</td></tr>\" +\n \"</table>\";\n if (textObject.text.includes(\"\\n\")) {\n html += isList ? \"</ul><ul>\" : \"<br/>\";\n }\n }\n if (isList) {\n html += \"</li>\";\n }\n }\n if (isList) {\n html += \"</ul>\";\n }\n return html;\n}",
"function displayTableBody(objectArray) {\r\n if (objectArray.length == 0) {\r\n //If no succesful name matches\r\n failureTarget.innerHTML = '<h2 id=\"no-results-target\">No results found</h2>';\r\n tableTarget.innerHTML = \"\";\r\n } else {\r\n //Otherwise, if atleast one name match was found\r\n let displayedResults = \"\";\r\n let properties = Object.keys(objectArray[0]);\r\n for (var i = 0; i < objectArray.length; i++) {\r\n let tableData = \"<tr>\";\r\n for (let j = 0; j < properties.length; j++) {\r\n let objectDetails = properties[j];\r\n tableData += `<td>${objectArray[i][objectDetails]}</td>`;\r\n }\r\n displayedResults += `${tableData}</tr>`;\r\n }\r\n failureTarget.innerHTML = '<h2 id=\"no-results-target\"></h2>';\r\n tableTarget.innerHTML = displayedResults;\r\n\r\n // Turn table entries into buttons on mobile\r\n if (isMobile()) {\r\n for (let i = 0; i < objectArray.length; i++) {\r\n let htmlRow = tableTarget.children[i];\r\n htmlRow.addEventListener(\"click\", function() {\r\n expand(objectArray[i]); //pass entry to expand() function\r\n });\r\n }\r\n }\r\n }\r\n}",
"function createObjectTable(obj) {\n var heads = [], colWidths = [], vals = [];\n _.each(obj, function(v, k) {\n v = String(v);\n heads.push(k.replace(/(^|\\s)([a-z])/g, uppercaseRegexMatch));\n vals.push(v);\n var width = Math.max(strlen(k), strlen(v)) + 2;\n if (width > exports.maxTableCell) {\n width = exports.maxTableCell;\n }\n colWidths.push(width);\n });\n\n var table = new Table({\n head: heads,\n colWidths: colWidths,\n style: exports.style()\n });\n\n table.push(vals);\n return table;\n}",
"function display(data) {\ntbody.text(\"\")\ndata.forEach(function(data) {\n var row = tbody.append(\"tr\");\n Object.entries(data).forEach(function([key, value]) {\n var cell = row.append(\"td\");\n cell.text(value);\n });\n})}",
"function display_object_in_table(o)\n{\n\t// get the table div element\n\tvar divTable = document.getElementById(\"tbl\");\n\tconsole.log(divTable);\n\t// create the table element\n\tvar newTableNode = document.createElement(\"table\");\n\n\t// apply style to table\n\tnewTableNode.style.border = \"1px solid black\";\n\n\t// build the table rows and columns\n\tfor (var key in o)\n\t{\n\t\t// create a table row node\n\t\tvar newTrNode = document.createElement(\"tr\");\n\t\t// create a td element for the key\n\t\tvar newTdKey = document.createElement(\"td\");\n\t\t// create an element for the value\n\t\tvar newTdValue = document.createElement(\"td\");\n\n\t\t// assign text to the td elements\n\t\tvar newTextNodeKey = document.createTextNode(key);\n\t\tvar newTextNodeValue = document.createTextNode(o[key]);\n\n\t\t// add the text to the td elements\n\t\tnewTdKey.appendChild(newTextNodeKey);\n\t\tnewTdValue.appendChild(newTextNodeValue);\n\n\t\t// apply styles to td elements\n\t\tnewTdKey.style.border = \"1px solid black\";\n\t\tnewTdValue.style.border = \"1px solid black\";\n\n\t\t// add the td elements to the tr element\n\t\tnewTrNode.appendChild(newTdKey);\n\t\tnewTrNode.appendChild(newTdValue);\n\n\t\t// add the tr to the table\n\t\tnewTableNode.appendChild(newTrNode);\n\t}\n\n\t// add the new table to our div element.\n\tdivTable.appendChild(newTableNode);\n}",
"function exportText()\n{\n const padding = ' '; // 35 whitespaces\n\n const display = (found, obj) => {\n\tvar res = accumulate(found, obj);\n\tObject.keys(res).sort().forEach(p => {\n\t var left = p + ': ';\n\t var pad = padding.slice(left.length);\n\t console.log(left + pad + res[p]);\n\t});\n };\n\n console.log('# db props');\n display(byName, props.database);\n console.log('# srv props');\n display(byName, props.server);\n console.log('# db paths');\n display(byPath, props.database);\n console.log('# srv paths');\n display(byPath, props.server);\n}",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredData.length; i++) {\n // Get current data and its field\n var business = filteredData[i];\n var fields = Object.keys(business);\n\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the object, create a new cell and set its inner text to be the current value at the current object's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = business[field];\n }\n }\n }",
"function renderTable() {\n tbody.innerHTML = \"\";\n for (var i = 0; i < ufoData.length; i++) {\n //for (var i = 0; i < 50; i++) {\n // Get get the current ufoSighting object and its fields\n var ufoSighting = ufoData[i];\n var fields = Object.keys(ufoSighting);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var row = tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the ufoSighting object, create a new cell at set its inner text to be the current value at the current ufoSighting's field\n var field = fields[j];\n var cell = row.insertCell(j);\n cell.innerText = ufoSighting[field];\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort Section and Cache it... | doSortSection() {
this.sortedSections = [];
for (let [sectionId, sectionObject] of Object.entries(this.formData.sections)) {
this.sortedSections.push(sectionObject)
}
this.sortedSections.sort((a, b) => {
return a.sortOrder - b.sortOrder;
})
} | [
"function arrayDataInOrder() {\n sectionList.sort(relativeSectionOrder)\n\n console.log(sectionList)\n }",
"function sortBySection(obj){\n const ordered = Object.keys(obj).sort().reduce(\n (object, key) => { \n object[key] = obj[key]; \n return object;\n }, \n {}\n );\n return ordered;\n}",
"static sectionSort(arr) {\n for (let i = 0; i < arr.length - 1; i++) {\n let last = i;\n for (let j = i + 1; j < arr.length; j++) {\n if (arr[j] < arr[last]) {\n last = j;\n }\n }\n let number = arr[last];\n arr[last] = arr[i];\n arr[i] = number;\n }\n return arr\n }",
"function sortSectionGroup(sectionGroup) {\r\n sectionGroup.sort(function(a, b){\r\n return a.offsetTop - b.offsetTop;\r\n });\r\n}",
"function sortSectionDetailsBy(element, attribute) {\n sectionDetails.sort(function(a,b) { \n if (attribute.includes(\"time\")) {\n return sortAlphaNum(toMilitaryTime(b[attribute]), toMilitaryTime(a[attribute])); \n } else {\n return sortAlphaNum(b[attribute], a[attribute]); \n }\n });\n updateSectionDetails(true);\n $(element).parent().children(\"th\").each(function(index,value) {\n $(value).toggleClass(\"sorted\", false);\n });\n $(element).toggleClass(\"sorted\");\n}",
"function sortSectionDetailsBy(element, attribute) {\n sectionDetails.sort(function(a,b) { return a[attribute].localeCompare(b[attribute]); });\n updateSectionDetails(true);\n $(element).parent().children(\"th\").each(function(index,value) {\n $(value).toggleClass(\"sorted\", false);\n });\n $(element).toggleClass(\"sorted\");\n}",
"sortedSections () {\n return [...this.xcSections].sort((a, b) => a.host < b.host ? -1 : 1)\n }",
"function sortSections(sections) {\n return sorted = sections.sort((sectionA, sectionB) => {\n if (sectionA.duration > sectionB.duration) {\n return -1\n }\n if (sectionA.duration < sectionB.duration) {\n return 1\n }\n return 0\n })\n}",
"function groupBySection(arr){\n result = arr.reduce((r,a)=>{\n r[a.section] = r[a.section] || [];\n r[a.section].push(a);\n return r;\n },Object.create(null));\n \n //now sorting keys(sections) by alphabet\n result = sortBySection(result);\n return result;\n}",
"function sortStreamersByPropertie(groupSection,propertieName){\n let splitByOnlineAndOffline = getOnlineAndOfflineStreamers(groupSection)\n splitByOnlineAndOffline.online = splitByOnlineAndOffline.online.sort(sortBy(propertieName))\n let newList = splitByOnlineAndOffline.online.concat(splitByOnlineAndOffline.offline)\n groupSection.setGroupList(newList)\n}",
"function sortJson() {\r\n\t \r\n}",
"sortCache(cacheType) {\n const method = `sortCache(${CACHE_TYPES[cacheType]})`;\n const cache = this.getCache(cacheType);\n fns.logTrace(__filename, method, `Sorting cache of ${cache.length} items.`);\n cache.sort((first, second) => {\n if (cacheType === CACHE_TYPES.GAME) {\n // For games only, we'll massively devalue games that aren't IN_PROGRESS\n const fVal = first.Item.State >= Enums_1.GAME_STATES.FINISHED ? first.SortKey / 2 : first.SortKey;\n const sVal = second.Item.State >= Enums_1.GAME_STATES.FINISHED ? second.SortKey / 2 : second.SortKey;\n return sVal - fVal;\n }\n else {\n // for everyting else, we'll use the existing hit/time-based value\n return second.SortKey - first.SortKey;\n }\n });\n fns.logDebug(__filename, method, 'Cache sorted.');\n }",
"sort() {\n const a = this.dict;\n const n = a.length;\n\n if( n < 2 ) { // eslint-disable-line \n } else if( n < 100 ) {\n // insertion sort\n for( let i = 1; i < n; i += 1 ) {\n const item = a[ i ];\n let j = i - 1;\n while( j >= 0 && item[ 0 ] < a[ j ][ 0 ] ) {\n a[ j + 1 ] = a[ j ];\n j -= 1;\n }\n a[ j + 1 ] = item;\n }\n } else {\n /**\n * Bottom-up iterative merge sort\n */\n for( let c = 1; c <= n - 1; c = 2 * c ) {\n for( let l = 0; l < n - 1; l += 2 * c ) {\n const m = l + c - 1;\n const r = Math.min( l + 2 * c - 1, n - 1 );\n if( m > r ) continue;\n merge( a, l, m, r );\n }\n }\n }\n }",
"sort() {\n const a = this.dict;\n const n = a.length;\n\n if( n < 2 ) ; else if( n < 100 ) {\n // insertion sort\n for( let i = 1; i < n; i += 1 ) {\n const item = a[ i ];\n let j = i - 1;\n while( j >= 0 && item[ 0 ] < a[ j ][ 0 ] ) {\n a[ j + 1 ] = a[ j ];\n j -= 1;\n }\n a[ j + 1 ] = item;\n }\n } else {\n /**\n * Bottom-up iterative merge sort\n */\n for( let c = 1; c <= n - 1; c = 2 * c ) {\n for( let l = 0; l < n - 1; l += 2 * c ) {\n const m = l + c - 1;\n const r = Math.min( l + 2 * c - 1, n - 1 );\n if( m > r ) continue;\n merge( a, l, m, r );\n }\n }\n }\n }",
"sortSegmentData(segmentData, sortingRule) {\n let sortedData;\n\n switch(sortingRule) {\n case \"group_Asc,segment_Asc\":\n default:\n sortedData = segmentData.sort((a,b) => {\n return ((a.group_position_no - b.group_position_no) || (a.position - b.position))\n })\n }\n\n return sortedData;\n }",
"compileSegmentDataOrderedList(unorderedSegmentData, groupData, chronotopeData, sortingRule) { \n \n //add cooresponding group data to segmentData\n unorderedSegmentData.forEach(segment => {\n let coorespondingGroup = groupData.find(group => {return segment.group_no === group.group_no})\n \n segment.group_position_no = coorespondingGroup.position;\n segment.group_hex_color = coorespondingGroup.hex_color;\n segment.group_name = coorespondingGroup.name;\n })\n \n const orderedSegmentData = this.sortSegmentData(unorderedSegmentData, sortingRule);\n this.assignChronotopeDataToSegment(orderedSegmentData, chronotopeData)\n \n return orderedSegmentData;\n }",
"function getGroupOrder() {\r\n\t\tvar sections = document.getElementsByClassName('section');\r\n\t\tvar alerttext = '';\r\n\t\tsections.each(function(section) {\r\n\t\t\tvar sectionID = section.id;\r\n\t\t\tvar order = Sortable.serialize(sectionID);\r\n\t\t\talerttext += sectionID + '&';\r\n\t\t});\r\n\t\talert(alerttext);\r\n\t\treturn false;\r\n\t}",
"function sortSectionsPriceArray(singleRowData) {\n sectionsPriceArray.push(parseInt(singleRowData.gsx$skipass.$t));\n sectionsPriceArray.sort((a, b) => {\n return a - b;\n });\n\n //remove duplicates\n uniqueSectionsPriceArray = [...new Set(sectionsPriceArray)];\n}",
"function ci_set_sort(key){\n\t\tif (self.cinfo_settings.sort == key){\n\t\t\tself.cinfo_settings.order = !self.cinfo_settings.order;\n\t\t} else {\n\t\t\tself.cinfo_settings.sort = key;\n\t\t\tself.cinfo_settings.order = false;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
var id_1=["inp_020","inp_030","inp_040","inp_050","inp_060","inp_070","inp_080","inp_090","inp_100","inp_110","inp_120","inp_130","inp_140","inp_150","inp_160","inp_170","inp_180","inp_190","inp_200"]; var var_1=["unit/dHdGlobal.gsHMIdata.sStep[2].eCmd","unit/dHdGlobal.gsHMIdata.sStep[3].eCmd","unit/dHdGlobal.gsHMIdata.sStep[4].eCmd","unit/dHdGlobal.gsHMIdata.sStep[5].eCmd","unit/dHdGlobal.gsHMIdata.sStep[6].eCmd","unit/dHdGlobal.gsHMIdata.sStep[7].eCmd","unit/dHdGlobal.gsHMIdata.sStep[8].eCmd","unit/dHdGlobal.gsHMIdata.sStep[9].eCmd","unit/dHdGlobal.gsHMIdata.sStep[10].eCmd","unit/dHdGlobal.gsHMIdata.sStep[11].eCmd","unit/dHdGlobal.gsHMIdata.sStep[12].eCmd","unit/dHdGlobal.gsHMIdata.sStep[13].eCmd","unit/dHdGlobal.gsHMIdata.sStep[14].eCmd","unit/dHdGlobal.gsHMIdata.sStep[15].eCmd","unit/dHdGlobal.gsHMIdata.sStep[16].eCmd","unit/dHdGlobal.gsHMIdata.sStep[17].eCmd","unit/dHdGlobal.gsHMIdata.sStep[18].eCmd","unit/dHdGlobal.gsHMIdata.sStep[19].eCmd","unit/dHdGlobal.gsHMIdata.sStep[20].eCmd"]; var id_5=["inp_025","inp_035","inp_045","inp_055","inp_065","inp_075","inp_085","inp_095","inp_105","inp_115","inp_125","inp_135","inp_145","inp_155","inp_165","inp_175","inp_185","inp_195","inp_205"]; var var_5=["unit/dHdGlobal.gsHMIdata.sStep[2].P1","unit/dHdGlobal.gsHMIdata.sStep[3].P1","unit/dHdGlobal.gsHMIdata.sStep[4].P1","unit/dHdGlobal.gsHMIdata.sStep[5].P1","unit/dHdGlobal.gsHMIdata.sStep[6].P1","unit/dHdGlobal.gsHMIdata.sStep[7].P1","unit/dHdGlobal.gsHMIdata.sStep[8].P1","unit/dHdGlobal.gsHMIdata.sStep[9].P1","unit/dHdGlobal.gsHMIdata.sStep[10].P1","unit/dHdGlobal.gsHMIdata.sStep[11].P1","unit/dHdGlobal.gsHMIdata.sStep[12].P1","unit/dHdGlobal.gsHMIdata.sStep[13].P1","unit/dHdGlobal.gsHMIdata.sStep[14].P1","unit/dHdGlobal.gsHMIdata.sStep[15].P1","unit/dHdGlobal.gsHMIdata.sStep[16].P1","unit/dHdGlobal.gsHMIdata.sStep[17].P1","unit/dHdGlobal.gsHMIdata.sStep[18].P1","unit/dHdGlobal.gsHMIdata.sStep[19].P1","unit/dHdGlobal.gsHMIdata.sStep[20].P1"]; var id_6=["inp_026","inp_036","inp_046","inp_056","inp_066","inp_076","inp_086","inp_096","inp_106","inp_116","inp_126","inp_136","inp_146","inp_156","inp_166","inp_176","inp_186","inp_196","inp_206"]; var var_6=["unit/dHdGlobal.gsHMIdata.sStep[1].P2","unit/dHdGlobal.gsHMIdata.sStep[2].P2","unit/dHdGlobal.gsHMIdata.sStep[3].P2","unit/dHdGlobal.gsHMIdata.sStep[4].P2","unit/dHdGlobal.gsHMIdata.sStep[5].P2","unit/dHdGlobal.gsHMIdata.sStep[6].P2","unit/dHdGlobal.gsHMIdata.sStep[7].P2","unit/dHdGlobal.gsHMIdata.sStep[8].P2","unit/dHdGlobal.gsHMIdata.sStep[9].P2","unit/dHdGlobal.gsHMIdata.sStep[10].P2","unit/dHdGlobal.gsHMIdata.sStep[11].P2","unit/dHdGlobal.gsHMIdata.sStep[12].P2","unit/dHdGlobal.gsHMIdata.sStep[13].P2","unit/dHdGlobal.gsHMIdata.sStep[14].P2","unit/dHdGlobal.gsHMIdata.sStep[15].P2","unit/dHdGlobal.gsHMIdata.sStep[16].P2","unit/dHdGlobal.gsHMIdata.sStep[17].P2","unit/dHdGlobal.gsHMIdata.sStep[18].P2","unit/dHdGlobal.gsHMIdata.sStep[19].P2","unit/dHdGlobal.gsHMIdata.sStep[20].P2"]; var id_7=["inp_017","inp_027","inp_037","inp_047","inp_057","inp_067","inp_077","inp_087","inp_097","inp_107","inp_117","inp_127","inp_137","inp_147","inp_157","inp_167","inp_177","inp_187","inp_197","inp_207"]; var var_7=["unit/dHdGlobal.gsHMIdata.sStep[1].tMon","unit/dHdGlobal.gsHMIdata.sStep[2].tMon","unit/dHdGlobal.gsHMIdata.sStep[3].tMon","unit/dHdGlobal.gsHMIdata.sStep[4].tMon","unit/dHdGlobal.gsHMIdata.sStep[5].tMon","unit/dHdGlobal.gsHMIdata.sStep[6].tMon","unit/dHdGlobal.gsHMIdata.sStep[7].tMon","unit/dHdGlobal.gsHMIdata.sStep[8].tMon","unit/dHdGlobal.gsHMIdata.sStep[9].tMon","unit/dHdGlobal.gsHMIdata.sStep[10].tMon","unit/dHdGlobal.gsHMIdata.sStep[11].tMon","unit/dHdGlobal.gsHMIdata.sStep[12].tMon","unit/dHdGlobal.gsHMIdata.sStep[13].tMon","unit/dHdGlobal.gsHMIdata.sStep[14].tMon","unit/dHdGlobal.gsHMIdata.sStep[15].tMon","unit/dHdGlobal.gsHMIdata.sStep[16].tMon","unit/dHdGlobal.gsHMIdata.sStep[17].tMon","unit/dHdGlobal.gsHMIdata.sStep[18].tMon","unit/dHdGlobal.gsHMIdata.sStep[19].tMon","unit/dHdGlobal.gsHMIdata.sStep[20].tMon"]; var id_RealPosition = ["inp_X_Postion","inp_Y1_Postion","inp_Z1_Postion"]; var id_014=["inp_011","inp_012","inp_013"]; var var_014=["unit/dHdGlobal.gsHMIdata.sStep[1].x","unit/dHdGlobal.gsHMIdata.sStep[1].y1","unit/dHdGlobal.gsHMIdata.sStep[1].z1"]; var id_024=["inp_021","inp_022","inp_023"]; var var_024=["unit/dHdGlobal.gsHMIdata.sStep[2].x","unit/dHdGlobal.gsHMIdata.sStep[2].y1","unit/dHdGlobal.gsHMIdata.sStep[2].z1"]; var id_034=["inp_031","inp_032","inp_033"]; var var_034=["unit/dHdGlobal.gsHMIdata.sStep[3].x","unit/dHdGlobal.gsHMIdata.sStep[3].y1","unit/dHdGlobal.gsHMIdata.sStep[3].z1"]; var id_044=["inp_041","inp_042","inp_043"]; var var_044=["unit/dHdGlobal.gsHMIdata.sStep[4].x","unit/dHdGlobal.gsHMIdata.sStep[4].y1","unit/dHdGlobal.gsHMIdata.sStep[4].z1"]; var id_054=["inp_051","inp_052","inp_053"]; var var_054=["unit/dHdGlobal.gsHMIdata.sStep[5].x","unit/dHdGlobal.gsHMIdata.sStep[5].y1","unit/dHdGlobal.gsHMIdata.sStep[5].z1"]; var id_064=["inp_061","inp_062","inp_063"]; var var_064=["unit/dHdGlobal.gsHMIdata.sStep[6].x","unit/dHdGlobal.gsHMIdata.sStep[6].y1","unit/dHdGlobal.gsHMIdata.sStep[6].z1"]; var id_074=["inp_071","inp_072","inp_073"]; var var_074=["unit/dHdGlobal.gsHMIdata.sStep[7].x","unit/dHdGlobal.gsHMIdata.sStep[7].y1","unit/dHdGlobal.gsHMIdata.sStep[7].z1"]; var id_084=["inp_081","inp_082","inp_083"]; var var_084=["unit/dHdGlobal.gsHMIdata.sStep[8].x","unit/dHdGlobal.gsHMIdata.sStep[8].y1","unit/dHdGlobal.gsHMIdata.sStep[8].z1"]; var id_094=["inp_091","inp_092","inp_093"]; var var_094=["unit/dHdGlobal.gsHMIdata.sStep[9].x","unit/dHdGlobal.gsHMIdata.sStep[9].y1","unit/dHdGlobal.gsHMIdata.sStep[9].z1"]; var id_104=["inp_101","inp_102","inp_103"]; var var_104=["unit/dHdGlobal.gsHMIdata.sStep[10].x","unit/dHdGlobal.gsHMIdata.sStep[10].y1","unit/dHdGlobal.gsHMIdata.sStep[10].z1"]; var id_114=["inp_111","inp_112","inp_113"]; var var_114=["unit/dHdGlobal.gsHMIdata.sStep[11].x","unit/dHdGlobal.gsHMIdata.sStep[11].y1","unit/dHdGlobal.gsHMIdata.sStep[11].z1"]; var id_124=["inp_121","inp_122","inp_123"]; var var_124=["unit/dHdGlobal.gsHMIdata.sStep[12].x","unit/dHdGlobal.gsHMIdata.sStep[12].y1","unit/dHdGlobal.gsHMIdata.sStep[12].z1"]; var id_134=["inp_131","inp_132","inp_133"]; var var_134=["unit/dHdGlobal.gsHMIdata.sStep[13].x","unit/dHdGlobal.gsHMIdata.sStep[13].y1","unit/dHdGlobal.gsHMIdata.sStep[13].z1"]; var id_144=["inp_141","inp_142","inp_143"]; var var_144=["unit/dHdGlobal.gsHMIdata.sStep[14].x","unit/dHdGlobal.gsHMIdata.sStep[14].y1","unit/dHdGlobal.gsHMIdata.sStep[14].z1"]; var id_154=["inp_151","inp_152","inp_153"]; var var_154=["unit/dHdGlobal.gsHMIdata.sStep[15].x","unit/dHdGlobal.gsHMIdata.sStep[15].y1","unit/dHdGlobal.gsHMIdata.sStep[15].z1"]; var id_164=["inp_161","inp_162","inp_163"]; var var_164=["unit/dHdGlobal.gsHMIdata.sStep[16].x","unit/dHdGlobal.gsHMIdata.sStep[16].y1","unit/dHdGlobal.gsHMIdata.sStep[16].z1"]; var id_174=["inp_171","inp_172","inp_173"]; var var_174=["unit/dHdGlobal.gsHMIdata.sStep[17].x","unit/dHdGlobal.gsHMIdata.sStep[17].y1","unit/dHdGlobal.gsHMIdata.sStep[17].z1"]; var id_184=["inp_181","inp_182","inp_183"]; var var_184=["unit/dHdGlobal.gsHMIdata.sStep[18].x","unit/dHdGlobal.gsHMIdata.sStep[18].y1","unit/dHdGlobal.gsHMIdata.sStep[18].z1"]; var id_194=["inp_191","inp_192","inp_193"]; var var_194=["unit/dHdGlobal.gsHMIdata.sStep[19].x","unit/dHdGlobal.gsHMIdata.sStep[19].y1","unit/dHdGlobal.gsHMIdata.sStep[19].z1"]; var id_204=["inp_201","inp_202","inp_203"]; var var_204=["unit/dHdGlobal.gsHMIdata.sStep[20].x","unit/dHdGlobal.gsHMIdata.sStep[20].y1","unit/dHdGlobal.gsHMIdata.sStep[20].z1"]; | function Read(id)
{
if(id == "inp_014")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
//console.log(tmpValue);
writeValueFN(tmpValue, var_014[i]);
}
ReadValue(id_014, var_014);
}
else if(id == "inp_024")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_024[i]);
}
ReadValue(id_024, var_024);
}
else if(id == "inp_034")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_034[i]);
}
ReadValue(id_034, var_034);
}
else if(id == "inp_044")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_044[i]);
}
ReadValue(id_044, var_044);
}
else if(id == "inp_054")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_054[i]);
}
ReadValue(id_054, var_054);
}
else if(id == "inp_064")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_064[i]);
}
ReadValue(id_064, var_064);
}
else if(id == "inp_074")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_074[i]);
}
ReadValue(id_074, var_074);
}
else if(id == "inp_084")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_084[i]);
}
ReadValue(id_084, var_084);
}
else if(id == "inp_094")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_094[i]);
}
ReadValue(id_094, var_094);
}
else if(id == "inp_104")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_104[i]);
}
ReadValue(id_104, var_104);
}
else if(id == "inp_114")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_114[i]);
}
ReadValue(id_114, var_114);
}
else if(id == "inp_124")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_124[i]);
}
ReadValue(id_124, var_124);
}
else if(id == "inp_134")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_134[i]);
}
ReadValue(id_134, var_134);
}
else if(id == "inp_144")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_144[i]);
}
ReadValue(id_144, var_144);
}
else if(id == "inp_154")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
//console.log(tmpValue);
writeValueFN(tmpValue, var_154[i]);
}
ReadValue(id_154, var_154);
}
else if(id == "inp_164")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_164[i]);
}
ReadValue(id_164, var_164);
}
else if(id == "inp_174")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_174[i]);
}
ReadValue(id_174, var_174);
}
else if(id == "inp_184")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_184[i]);
}
ReadValue(id_184, var_184);
}
else if(id == "inp_194")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_194[i]);
}
ReadValue(id_194, var_194);
}
else if(id == "inp_204")
{
for(var i = 0; i < id_RealPosition.length; i++)
{
var tmpValue = document.getElementById(id_RealPosition[i]).value;
writeValueFN(tmpValue, var_204[i]);
}
ReadValue(id_204, var_204);
}
} | [
"function Read(id)\n{\n\tif(id == \"inp_014\")\n\t{$(\"#inp_011\").val($(\"#inp_X_Postion\").val());\n $(\"#inp_012\").val($(\"#inp_Y1_Postion\").val());\n $(\"#inp_013\").val($(\"#inp_Z1_Postion\").val());\n $(\"#y2_01\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_01\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\t\n\t\t\twriteValueFN(tmpValue, var_014[i]);\n\t\t\t\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_024\")\n{$(\"#inp_021\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_022\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_023\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_02\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_02\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_024[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_034\")\n\t{$(\"#inp_031\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_032\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_033\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_03\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_03\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_034[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_044\")\n\t{$(\"#inp_041\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_042\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_043\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_04\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_04\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_044[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_054\")\n\t{$(\"#inp_051\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_052\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_053\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_05\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_05\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_054[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_064\")\n\t{$(\"#inp_061\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_062\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_063\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_06\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_06\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_064[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_074\")\n\t{$(\"#inp_071\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_072\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_073\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_07\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_07\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_074[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_084\")\n\t{$(\"#inp_081\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_082\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_083\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_08\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_08\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_084[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_094\")\n\t{$(\"#inp_091\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_092\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_093\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_09\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_09\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_094[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_104\")\n\t{$(\"#inp_101\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_102\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_103\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_10\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_10\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_104[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_114\")\n\t{$(\"#inp_111\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_112\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_113\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_11\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_11\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_114[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_124\")\n\t{$(\"#inp_121\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_122\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_123\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_12\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_12\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_124[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_134\")\n\t{$(\"#inp_131\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_132\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_133\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_13\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_13\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_134[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_144\")\n\t{$(\"#inp_141\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_142\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_143\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_14\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_14\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_144[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_154\")\n\t{$(\"#inp_151\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_152\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_153\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_15\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_15\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\t//console.log(tmpValue);\n\t\t\twriteValueFN(tmpValue, var_154[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_164\")\n\t{$(\"#inp_161\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_162\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_163\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_16\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_16\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_164[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_174\")\n\t{$(\"#inp_171\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_172\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_173\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_17\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_17\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_174[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_184\")\n\t{$(\"#inp_181\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_182\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_183\").val($(\"#inp_Z1_Postion\").val());\n\n\n $(\"#y2_18\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_18\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_184[i]);\n\t\t}\n\t\t\t\n\t}\n\telse if(id == \"inp_194\")\n\t{$(\"#inp_191\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_192\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_193\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_19\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_19\").val($(\"#inp_Z2_Postion\").val());\n\t\tfor(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_194[i]);\n\t\t}\n\t\t\n\t}\n\telse if(id == \"inp_204\")\n\t{$(\"#inp_201\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_202\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_203\").val($(\"#inp_Z1_Postion\").val());\n\n\n $(\"#y2_20\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_20\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_204[i]);\n\t\t}\n\t\t\t\n\t}\n\t\telse if(id == \"inp_214\")\n\t{$(\"#inp_211\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_212\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_213\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_21\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_21\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_214[i]);\n\t\t}\n\t\t\t\n\t}\n\t\telse if(id == \"inp_224\")\n\t{$(\"#inp_221\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_222\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_223\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_22\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_22\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_224[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\telse if(id == \"inp_234\")\n\t{$(\"#inp_231\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_232\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_233\").val($(\"#inp_Z1_Postion\").val());\n\n\n $(\"#y2_23\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_23\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_234[i]);\n\t\t}\n\t\t\t\n\t}\n\n\t\t\telse if(id == \"inp_244\")\n\t{$(\"#inp_241\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_242\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_243\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_24\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_24\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_244[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\t\telse if(id == \"inp_254\")\n\t{$(\"#inp_251\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_252\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_253\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_25\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_25\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_254[i]);\n\t\t}\n\t\t\t\n\t}\n\n\t\t\telse if(id == \"inp_264\")\n\t{$(\"#inp_261\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_262\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_263\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_26\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_26\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_264[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\telse if(id == \"inp_274\")\n\t{$(\"#inp_271\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_272\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_273\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_27\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_27\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_274[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\telse if(id == \"inp_284\")\n\t{$(\"#inp_281\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_282\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_283\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_28\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_28\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_284[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\telse if(id == \"inp_294\")\n\t{$(\"#inp_291\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_292\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_293\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_29\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_29\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_294[i]);\n\t\t}\n\t\t\t\n\t}\n\t\t\telse if(id == \"inp_304\")\n\t{$(\"#inp_301\").val($(\"#inp_X_Postion\").val());\n$(\"#inp_302\").val($(\"#inp_Y1_Postion\").val());\n$(\"#inp_303\").val($(\"#inp_Z1_Postion\").val());\n\n $(\"#y2_30\").val($(\"#inp_Y2_Postion\").val());\n $(\"#z2_30\").val($(\"#inp_Z2_Postion\").val());\n\t for(var i = 0; i < id_RealPosition.length; i++)\n\t\t{\n\t\t\tvar tmpValue = document.getElementById(id_RealPosition[i]).value;\n\t\t\twriteValueFN(tmpValue, var_304[i]);\n\t\t}\n\t\t\t\n\t}\n\n}",
"function salio(id,xyz)\n{\n console.log(\"salio del campo \"+ id);\n //verificar que no este vacio\n var iddetriple = id+\"_TRIPLE\";\n var contaa = 0;\n var varvalor=\"\";\n $('input', $('#'+iddetriple)).each(function() \n {\n var varubicacion = $(this).attr(\"id\")[1];\n if(xyz== varubicacion )\n {\n if(this.value.length<1)\n {\n console.log(\"campo vacio\");\n return;\n }\n if(this.value == \"variable\")\n {\n console.log(\"campo vacio\");\n return;\n }\n\n console.log(\"encontre el valor \"+ this.value );\n varvalor=this.value;\n }\n });\n //si no existe la variable agregarla\n for (var i = 0; i < variablesArray.length; i++) \n {\n if(variablesArray[i][0]== varvalor)\n {\n console.log(\"ya existe la variable\");\n return;\n }\n }\n console.log(\"no existe la variable\");\n variablesArray[variablesArray.length] = new Array(varvalor);\n}",
"function insertStimuli(dataInput, optionInput, btnInput){\n var randomTxtArray = [];\n var workingArray = [];\n var txtNumber;\n var txtSelector;\n\tvar varSelector;\n\tvar boxLabelSelector;\n var sideLabelCounter = 0;\n \n \n for(i = 0; i < order.length; i++){\n \n optionInput.forEach(function(item){\n \n if(item[\"name\"] == order[i]){\n var cellCounter = 0;\n \n if(i==0 && dataInput[\"attOrder\"]==\"random\"){\n for(h=0; h<(item[\"attributes\"][0][\"txt\"]).length; h++){\n workingArray.push(h);\n }\n randomTxtArray = shuffle(workingArray);\n }\n \n for(j=0; j<(item[\"attributes\"].length); j++){\n \n sideLabelCounter++;\n \n for(k=0; k<(item[\"attributes\"][j][\"txt\"]).length; k++){\n cellCounter++;\n \n if(dataInput[\"attOrder\"]==\"standard\"){\n txtNumber = k;\n txtSelector = (item[\"attributes\"][j][\"txt\"][k]);\n boxLabelSelector = (item[\"attributes\"][j][\"box\"][k]);\n\t\t\t\t\t\t\tvarSelector = (item[\"attributes\"][j][\"var\"][k]);\n\t\t\t\t\t\t\t\n }else if(dataInput[\"attOrder\"] == \"reverse\"){\n txtNumber = ((item[\"attributes\"][j][\"txt\"].length)-(k+1));\n txtSelector = (item[\"attributes\"][j][\"txt\"][txtNumber]);\n boxLabelSelector = (item[\"attributes\"][j][\"box\"][txtNumber]);\n\t\t\t\t\t\t\tvarSelector = (item[\"attributes\"][j][\"var\"][txtNumber]);\n\t\t\t\t\t\t\t\n }else{\n txtNumber = (randomTxtArray[k]);\n txtSelector = item[\"attributes\"][j][\"txt\"][txtNumber];\n boxLabelSelector = (item[\"attributes\"][j][\"box\"][txtNumber]);\n\t\t\t\t\t\t\tvarSelector = (item[\"attributes\"][j][\"var\"][txtNumber]);\n }\n if(i == 0 && j == 0){\n if(attributeOrder != \"\"){\n attributeOrder += \"/\";\n attNumericOrder += \"/\";\n }\n attributeOrder += item[\"attributeLabels\"][txtNumber];\n attNumericOrder += txtNumber;\n }\n \n \n $(\"#\" + order[i] + (cellCounter)).attr(\"name\",varSelector);\n $(\"#\" + order[i] + (cellCounter) + \"_txt\").append('<div class=\"w3-display-middle\"><p>' + txtSelector + '</p></div>');\n $(\"#\" + order[i] + (cellCounter) + \"_box\").append('<div class=\"w3-display-middle\"><p>' + boxLabelSelector + '</p></div>');\n \n if(i == 0){\n if(dataInput[\"displayLabels\"] == \"attOnly\" || dataInput[\"displayLabels\"] == \"all\"){\n if(dataInput[\"layout\"] == \"attributeCol\"){\n $(\"#headerLabel\" + (cellCounter) + \"_txt\").append('<div class=\"w3-display-middle\"><p>' + item[\"attributeLabels\"][txtNumber] + '</p></div>');\n }else{\n $(\"#sideLabel\" + (cellCounter) + \"_txt\").append('<div class=\"w3-display-middle\"><p>' + item[\"attributeLabels\"][txtNumber] + '</p></div>');\n }\n }\n }\n }\n \n if(dataInput[\"displayLabels\"] == \"optOnly\" || dataInput[\"displayLabels\"] == \"all\"){\n if(dataInput[\"layout\"] == \"attributeCol\"){\n $(\"#sideLabel\" + (sideLabelCounter) + \"_txt\").append('<div class=\"w3-display-middle\"><p>' + item[\"attributes\"][j][\"label\"] + '</p></div>');\n }else{\n $(\"#headerLabel\" + (sideLabelCounter) + \"_txt\").append('<div class=\"w3-display-middle\"><p>' + item[\"attributes\"][j][\"label\"] + '</p></div>');\n }\n } \n }\n $(\"#button\" + item[\"name\"] + \"_txt\").append('<button type=\"button\" class=\"choiceButton\" id=\"' + item[\"optionName\"] + '\" name=\"choice\" value=\"' + item[\"optionName\"] + '\">' + item[\"optionName\"] + '</button>'); \n \n }\n });\n }\n}",
"function build_dive_segment(levels_segment_arr , levels_mix_segment_arr){\n\n var rate_asc = document.getElementById(\"opt_rate_asc\");\n var rate_asc_idx = rate_asc.options[rate_asc.selectedIndex].value;\n\n var rate_dsc = document.getElementById(\"opt_rate_dsc\");\n var rate_dsc_idx = rate_dsc.options[rate_dsc.selectedIndex].value;\n var output = [];\n\n if(max_lvl_depth(levels_segment_arr) < 7){\n //Not Deco Dive Segment\n\n if($( \"#tn_plan_ccr\" ).val()*1.0 == 2){\n //CCR dive and we need hide consumption\n element_id_hide(\"t_total_cons\");\n element_id_hide(\"7-header\");\n element_id_hide(\"7-content\");\n //console.log(\"true\");\n }\n\n tmp_arr = [];\n tmp_end_depth = levels_segment_arr[1];\n tmp_time = (levels_segment_arr[0+1]*1.0/rate_dsc_idx)*1.0;\n tmp_mx_arr =[];\n tmp_mx_arr.push(levels_mix_segment_arr[0],levels_mix_segment_arr[1]);\n tmp_gass_name = mix_to_txt_arr(tmp_mx_arr);\n\n //add first descent lvl\n tmp_arr.push(\n {\n endDepth: tmp_end_depth,\n startDepth: 0,\n time: tmp_time,\n gasName: tmp_gass_name\n }\n );\n //loop for all added levels\n a3 = 0;\n b3 = 0;\n for (i = 0; i < levels_segment_arr.length/3; i++) {\n //for every flat levels\n tmp_end_depth = levels_segment_arr[a3+1];\n tmp_start_depth = levels_segment_arr[a3+1];\n tmp_time = levels_segment_arr[a3+2];\n tmp_mx_arr =[];\n tmp_mx_arr.push(levels_mix_segment_arr[b3],levels_mix_segment_arr[b3+1]);\n tmp_gass_name = mix_to_txt_arr(tmp_mx_arr);\n\n tmp_arr.push(\n {\n endDepth: tmp_end_depth,\n startDepth: tmp_start_depth,\n time: tmp_time,\n gasName: tmp_gass_name\n }\n );\n //add lvl change.if it is not last change\n if(levels_segment_arr[a3+4] !== undefined){\n tmp_end_depth = levels_segment_arr[a3+4]*1.0;\n tmp_start_depth = levels_segment_arr[a3+1]*1.0;\n\n //compute travel time from one to next lvl\n tt_time = Math.abs(tmp_start_depth - tmp_end_depth);\n if(tmp_start_depth - tmp_end_depth < 0){\n tmp_time = (tt_time*1.0/rate_dsc_idx);\n }\n else\n {\n tmp_time = (tt_time*1.0/rate_asc_idx);\n }\n //return char mix name\n tmp_mx_arr =[];\n tmp_mx_arr.push(levels_mix_segment_arr[b3],levels_mix_segment_arr[b3+1]);\n tmp_gass_name = mix_to_txt_arr(tmp_mx_arr);\n\n tmp_arr.push(\n {\n endDepth: tmp_end_depth,\n startDepth: tmp_start_depth,\n time: tmp_time,\n gasName: tmp_gass_name.toString()\n }\n );\n }\n\n b3 = b3 + 2;\n a3 = a3 + 3;\n }\n\n //add last lvl to surface\n tmp_time = ((tmp_arr[tmp_arr.length-1].endDepth)*1.0/rate_asc_idx)*1.0;\n tmp_arr.push(\n {\n endDepth: 0,\n startDepth: tmp_arr[tmp_arr.length-1].endDepth,\n time: tmp_time,\n gasName: tmp_arr[tmp_arr.length-1].gasName\n }\n );\n output = tmp_arr;\n }\n else\n\n //Deco Dive_Segment! \n {\n if($( \"#tn_plan_ccr\" ).val()*1.0 == 1){\n\n //OC dive and we need hide consumption\n element_id_show(\"t_total_cons\");\n element_id_show(\"7-header\");\n element_id_show(\"7-content\");\n\n }\n\n //reset compartment info array every graph rebuild\n comp_tiss_arr =[];\n\n //reset previos plan\n var plan = [];\n var mdl = document.getElementById(\"tn_mdl\");\n var mdl_idx = mdl.options[mdl.selectedIndex].value;\n var buhlmann = dive.deco.buhlmann();\n vpm = dive.deco.vpm();\n //Select algorithm\n if(mdl_idx == 1){\n plan = new buhlmann.plan(buhlmann.ZH16ATissues);\n }\n if(mdl_idx == 2){\n plan = new buhlmann.plan(buhlmann.ZH16BTissues);\n }\n if(mdl_idx == 3){\n plan = new buhlmann.plan(buhlmann.ZH16CTissues);\n }\n if(mdl_idx == 4){\n plan = new vpm.plan(1,true);\n }\n\n //Add Bottom/travel gases\n aaa = 0;\n for(c = 0 ; c < levels_mix_segment_arr.length/2 ; c++){\n ff = [levels_mix_segment_arr[aaa] , levels_mix_segment_arr[aaa+1]];\n\n plan.addBottomGas(mix_to_txt_arr(ff), levels_mix_segment_arr[aaa]*0.01, levels_mix_segment_arr[aaa+1]*0.01);\n\n //add bottom gass as deco gass !!!_need_deep_test_!!!\n //plan.addDecoGas(mix_to_txt_arr(ff), levels_mix_segment_arr[aaa]*0.01, levels_mix_segment_arr[aaa+1]*0.01);\n\n aaa = aaa + 2;\n }\n\n //Add deco gases\n var mix_deco = document.getElementById(\"opt_deco\");\n var mix_deco_idx = mix_deco.options[mix_deco.selectedIndex].value;\n aaa = 0;\n\n mix_mod_arr = [];\n var counter = 0;\n\n for(c = 0 ; c < mix_deco_idx ; c++){\n tmp3 = [deco_mix_arr[aaa],deco_mix_arr[aaa+1]];\n\n //This CCR Bailout Dive or OC Dive and deco gases is enable\n if(opt_blt_dln == 1){\n if(deco_mix_depth_arr[counter] != 0){\n //Manual MOD set for current deco mix\n var curMixMOD = deco_mix_depth_arr[counter];\n }\n else{\n ////Auto MOD set for current deco mix\n var curMixMOD = GetDecoMODinMeters(deco_mix_arr[aaa], deco_mix_arr[aaa+1]);\n }\n\n //Do a curMixMOD multiple of three\n curMixMOD = (3 * ((curMixMOD / 3).toFixed(0)));\n if($( \"#opt_lst_stop\" ).val() == 6){\n //console.log(curMixMOD);\n //6 meters last stop. Check current mix MOD and if less that 6 meters does`t add to the deco gas list\n if(curMixMOD >= 6){\n plan.addDecoGas(mix_to_txt_arr(tmp3), deco_mix_arr[aaa]*0.01, deco_mix_arr[aaa+1]*0.01);\n mix_mod_arr.push(\n {\n mix : mix_to_txt_arr(tmp3),\n mod : deco_mix_depth_arr[counter]\n });\n }\n }\n else\n {\n //3 meters last stop. Do nothing. Simply add deco gases to the list\n plan.addDecoGas(mix_to_txt_arr(tmp3), deco_mix_arr[aaa]*0.01, deco_mix_arr[aaa+1]*0.01);\n mix_mod_arr.push(\n {\n mix : mix_to_txt_arr(tmp3),\n mod : deco_mix_depth_arr[counter]\n });\n }\n }\n else{\n //it is CCR Diluent Dive and no Bailout(Deco gases add) dive\n }\n //as Bottom/Travel gases, for lvl compatibility\n plan.addBottomGas(mix_to_txt_arr(tmp3), deco_mix_arr[aaa]*0.01, deco_mix_arr[aaa+1]*0.01);\n counter = counter + 1;\n aaa = aaa + 2;\n\n }\n\n //Add lvl changes\n //Get current ascending deco speed\n aaa = 0;\n fff = 0;\n for(c = 0 ; c < levels_mix_segment_arr.length/2 ; c++){\n ff = [levels_mix_segment_arr[aaa] , levels_mix_segment_arr[aaa+1]];\n if(c === 0){\n tmp_time = levels_segment_arr[fff+1]*1.0/rate_dsc_idx;\n plan.addDepthChange(0, levels_segment_arr[fff+1]*1.0, mix_to_txt_arr(ff), tmp_time*1.0);\n plan.addDepthChange(levels_segment_arr[fff+1]*1.0, levels_segment_arr[fff+1]*1.0, mix_to_txt_arr(ff), levels_segment_arr[fff+2]*1.0);\n }\n else\n {\n if(((levels_segment_arr[fff+1-3]*1.0) - (levels_segment_arr[fff+1]*1.0))>= 0){\n tmp_time = (Math.abs((levels_segment_arr[fff+1-3]*1.0) - (levels_segment_arr[fff+1]*1.0)))/rate_asc_idx;\n }\n else\n {\n tmp_time = (Math.abs((levels_segment_arr[fff+1-3]*1.0) - (levels_segment_arr[fff+1]*1.0)))/rate_dsc_idx;\n }\n //fix lib crush because time can`t == 0;\n if(tmp_time === 0){\n tmp_time = 0.001;\n }\n plan.addDepthChange(levels_segment_arr[fff+1-3]*1.0, levels_segment_arr[fff+1]*1.0, mix_to_txt_arr(ff), tmp_time);\n plan.addDepthChange(levels_segment_arr[fff+1]*1.0, levels_segment_arr[fff+1]*1.0, mix_to_txt_arr(ff), levels_segment_arr[fff+2]*1.0);\n }\n aaa = aaa + 2;\n fff = fff + 3;\n }\n\n var ppo2_deco = document.getElementById(\"opt_ppo2_deco\");\n var ppo2_deco_idx = ppo2_deco.options[ppo2_deco.selectedIndex].value;\n\n //fix computation GF error with zero\n if(gf_arr[0] === 0){\n gf_arr[0] = 1;\n }\n //compute END for specific lib param\n var ppn2_max_deco = document.getElementById(\"opt_ppn2_max_deco\");\n var ppn2_max_deco_idx = ppn2_max_deco.options[ppn2_max_deco.selectedIndex].value;\n\n //OLD!\n //var mxis_end = (((parseFloat(ppn2_max_deco_idx))/0.79)-1)*10;\n\n //NEW!\n var WaterDensTempCompensation = (1 / ((water_density_temperature_correction() * water_density() * 0.001 * (1))));\n var mxis_end = (((parseFloat(ppn2_max_deco_idx))/0.79)-1)*10 * height_to_bar() * WaterDensTempCompensation;\n //console.log(mxis_end, WaterDensTempCompensation, height_to_bar());\n\n output = plan.calculateDecompression(false, gf_arr[0]*0.01, gf_arr[1]*0.01, ppo2_deco_idx*1.0, mxis_end);\n\n }\n //fix ascent error on very short dives\n for(c = 0 ; c < output.length ; c++){\n if(output[c].endDepth < 0){\n output[c].endDepth = 3;\n output.push(\n {\n endDepth: 0,\n startDepth: output[c].endDepth,\n time: output[c].time,\n gasName: output[c].gasName\n }\n );\n }\n }\n\n return output;\n }",
"function fn_movenextstep(id,stepid)\n{\t\n\tvar dataparam = \"\";\n\t\n\tif(stepid == 1) {\n\t\t\n\t\tvar sec = '';\n\t\tvar chkval = 0;\n var flag=\"false\";\n\t\t$(\"input[id^='check']\").each(function(index, element) {\t\t\t\n\t\t\tif($(this).is(':checked')==true){\n\t\t\t\tchkval = 1;\n flag=\"true\";\n\t\t\t}\n\t\t\telse if($(this).is(':checked')==false) {\n\t\t\t\tchkval = 2;\t\n\t\t\t}\n \n if(sec == '') \n {\n sec = chkval;\t\n }\n else \n {\n sec += \",\"+chkval;\t\n }\n });\n \n var gradeid = [];\n\t var gradename = \"\";\n \n\t\t$(\"div[id^=list8_]\").each(function()\n\t\t{\n\t\t\tvar guid = $(this).attr('id').replace('list8_',''); \n\t\t\tgradeid.push(guid);\n \n\t\t\tif(gradename == \"\") \n {\n\t\t\t gradename = $('#'+guid).html();\t\t\t\n\t\t\t}\n\t\t\telse\n {\n\t\t\t gradename += \"~\" + $('#'+guid).html();\t\t\t\n\t\t\t} \n\t\t});\n \n/* For multiple select standard */\n \n var stdid = [];\n\t\t\n\t\t$(\"div[id^=list6_]\").each(function()\n\t\t{\n\t\t\tvar guid = $(this).attr('id').replace('list6_','');\n\t\t\tstdid.push(\"'\"+guid+\"'\");\n \n\t\t});\n \n\t\t\n\t\tif($(\"#frmbasicinfo\").validate().form())\n {\n \n if(flag==\"false\")\n {\n $.Zebra_Dialog(\"Please Select Show Sections\", { 'type': 'information', 'buttons': false, 'auto_close': 2000 });\n return false;\n }\n \n if(stdid=='')\n {\n $.Zebra_Dialog(\"Please Select Atleast one documents\", { 'type': 'information', 'buttons': false, 'auto_close': 2000 });\n return false;\n }\n \n if(gradeid=='')\n {\n $.Zebra_Dialog(\"Please Select Atleast one Grades\", { 'type': 'information', 'buttons': false, 'auto_close': 2000 });\n return false;\n }\n\t\t dataparam = \"oper=savestep1&rpttitle=\"+$('#txtrpttitle').val()+\"&ownerid=\"+$('#selectowner').val()+\"&prepfor=\"+$('#txtpreparefor').val()+\"&prepon=\"+$('#txtprepareon').val()\n +\"&rptsytle=\"+$('#selectrptstyle').val()+\"&selectschool=\"+$('#selectschool').val()+\"&sec=\"+sec\n +\"&state=\"+$('#selectstate').val()+\"&documentid=\"+stdid+\"&gradeids=\"+gradeid+\"&gradename=\"+gradename+\"&rptid=\"+id; \n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n \n\tif(stepid == 2) {\n\t\t\t\tvar combi='';\n\t\t\t\tvar newcom='';\n\t\t\t\tvar productid = [];\n var tagproductid = [];\n var reqtagproductid=[];\n\t\t\t\tvar reqproductid= [];\n\t\t\t\tvar gradename = \"\";\n var notitrecomm=$('#trecomm').val();\n var maxrecom=$('#maxrecomm').val();\n var totcombi=$('#totcombi').val();\n var combi=$('#jsonval').val();\n\t\t\t\tvar newcom=$('#newcombi').val();\n var reqcombi=$('#reqcombi').val();\n var tagpid = $('#form_tags_products').val();\n var chktype = $('input:radio[name=types]:checked').val();\n var notagrecomm=$('#tagtrecomm').val();\n var maxtagrecom=$('#tagmaxrecomm').val();\n var tottagcombi=$('#tagtotcombi').val();\n\t\t\t\tvar show_titletype=$('#showtitle').val(); \n \n if($('input:checkbox[name=check_1]').is(':checked') == true)\n {\n var truchk = 1;\n }\n else if($('input:checkbox[name=check_1]').is(':checked') == false)\n {\n var truchk = 0;\n } \n \n if($('input:checkbox[name=check_2]').is(':checked') == true)\n {\n var tagtruchk = 1;\n }\n else if($('input:checkbox[name=check_2]').is(':checked') == false)\n {\n var tagtruchk = 0;\n }\n \n \n if($('#trecomm').val() == '' && $('#tagtrecomm').val() == ''){\n \n $.Zebra_Dialog(\"Please enter a value for</br>No of Title in each recommendation.\", { 'type': 'information'});\n\t\t\t\t\t\n return false;\n }\n \n if($('#maxrecomm').val() == '' && $('#tagmaxrecomm').val() == ''){\n \n $.Zebra_Dialog(\"Please enter a value for</br>Max no of recommendation .\", { 'type': 'information'});\n \n return false;\n } \n \n\t\tif(combi!='')\n\t\t{\n if(chktype == '5') {\n\t\t\t$(\"div[id^=list8_]\").each(function()\n\t\t\t{\n if($(this).attr(\"style\") != \"display: none;\") {\n\t\t\t\t\tvar pid = $(this).children(\":first\").attr('id');\n\t\t\t\t\tproductid.push(escape(pid));\n }\n\t\t\t\t\n\t\t\t}); \n $(\"div[id^=list10_]\").each(function()\n\t\t\t\t{\n if($(this).attr(\"style\") != \"display: none;\") {\n var pid = $(this).children(\":first\").attr('id');\n reqproductid.push(escape(pid));\n }\n });\n tagproductid='';\n reqtagproductid = '';\n }else {\n $(\"div[id^=list12_]\").each(function()\n\t\t\t{\n if($(this).attr(\"style\") != \"display: none;\") {\n\t\t\t\t\tvar pid = $(this).children(\":first\").attr('id');\n\t\t\t\t\ttagproductid.push(escape(pid));\n }\n \n\t\t\t});\n $(\"div[id^=list14_]\").each(function()\n {\n if($(this).attr(\"style\") != \"display: none;\") {\n var pid = $(this).children(\":first\").attr('id');\n reqtagproductid.push(escape(pid));\n }\n\n });\n productid='';\n reqproductid = '';\n } \n \n var cntreq_prod = reqproductid.length; \n\t\t\t\tif($('input:checkbox[name=check_1]').is(':checked'))\n {\t\t \n\t\t\tif(reqproductid=='')\n\t\t\t\t\t{\n\t\t\t\t\t$.Zebra_Dialog(\"Please Select Atleast one products\", { 'type': 'information'});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\t\t\t\t\t \n\t\t\t\t}\n var cnttagreq_prod = reqtagproductid.length;\n \n if($('input:checkbox[name=check_2]').is(':checked'))\n {\t\t \n\tif(reqtagproductid=='')\n {\n $.Zebra_Dialog(\"Please Select Atleast one products\", { 'type': 'information'});\n\n return false;\n }\t\t\t\t\t \n }\n if(productid !='' || reqproductid!='' )\n {\n\t\tdataparam = \"oper=savestep2&productid=\"+productid+\"&rptid=\"+id+\"&reqproductid=\"+reqproductid\n +\"¬itrecomm=\"+notitrecomm+\"&maxrecom=\"+maxrecom+\"&totcombi=\"+totcombi+\"&cntreq_prod=\"+cntreq_prod+\"&truchk=\"+truchk+\"&show_titletype=\"+show_titletype;\n \n }\n else if(tagproductid!='' || reqtagproductid!='')\n {\n dataparam = \"oper=savestep2&tagproductid=\"+tagproductid+\"&rptid=\"+id+\"&tagreqproductid=\"+reqtagproductid\n +\"¬itrecomm=\"+notagrecomm+\"&maxrecom=\"+maxtagrecom+\"&totcombi=\"+tottagcombi+\"&cntreq_prod=\"+cnttagreq_prod+\"&truchk=\"+tagtruchk+\"&tagpid=\"+tagpid;\n }\n\t\t\n }\n }\n if(stepid == 3)\n {\n /*generate page*/\n var selcombi=$('#selcombi').val(); \n }\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: 'reports/bestfit/reports-bestfit-ajax.php',\n\t\tdata: dataparam,\n\t\tbeforeSend: function()\n\t\t{\n\t\t\tshowloadingalert('Loading, please wait.');\n\t\t},\n\t\tsuccess:function(data) { \n\t\t\tcloseloadingalert();\n\t\t\tid = trim(data);\n \n\t\t\tif(trim(id) != \"invalid\") {\n\t\t\t\n\t\t\t\t$('#bbasicstandardinfo').parent().attr('name',id);\n\t\t\t\t$('#bselectproduct').parent().attr('name',id);\n\t\t\t\t$('#bgenerate').parent().attr('name',id);\n\t\t\t\t$('#bviewreport').parent().attr('name',id);\n\t\t\t\t\n\t\t\t\tremovesections('#reports-bestfit-steps');\n\t\t\t\t\n\t\t\t\tif(stepid == 1){\n\t\t\t\t\tsetTimeout('showpageswithpostmethod(\"reports-bestfit-select_product\",\"reports/bestfit/reports-bestfit-select_product.php\",\"id='+id+'\");',500);\n \n\t\t\t\t}\n\t\t\t\telse if(stepid == 2) {\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tajaxloadingalert('Loading, please wait.');\n\t\t\t\t\tsetTimeout('showpageswithpostmethod(\"reports-bestfit-generate_report\",\"reports/correlation/reports-bestfit-generate_report.php\",\"id='+id+'\");',500);\n }\n\t\t\t\telse if(stepid == 3) {\t\t\t\t\t\n ajaxloadingalert('Loading, please wait.');\n setTimeout('showpageswithpostmethod(\"reports-bestfit-view_report\",\"reports/bestfit/reports-bestfit-view_report.php\",\"id='+id+'\");',500);\n \n\t\t\t\t}\n \n\t\t\t}\n\t\t\telse {\n\t\t\t\tshowloadingalert(\"Duplicate Report Name\");\t\n\t\t\t\tsetTimeout('closeloadingalert()',2000);\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t});\n}",
"function generate_inputs()\t{\r\n\t\tvar count = 0;\r\n\t\tvar temp = \"\";\r\n\t\tvar s = \"\";\r\n\t\t\r\n\t\t//lenth\r\n\t\t$('#add_form').append(\"<input type='hidden' name='text_length' value='\"+text.length+\"' />\");\r\n\t\t//lenth end\r\n\t\t\r\n\t\t//key_areas\r\n\t\tvar val = \"\";// will contain this: begin~end~themes~locations~persons~genre~misc~system~direct_links| 'NEXT KEY AREA'\r\n\t\tfor(var i = 0 ; i <= clic_areas_nb ; i++ )\r\n\t\t{\r\n\t\t\t//begin\r\n\t\t\tval += tab_of_areas_position[i][0]+\"~\";\r\n\t\t\t\r\n\t\t\t//end\r\n\t\t\tval += tab_of_areas_position[i][1]+\"~\";\r\n\t\t\t\r\n\t\t\t//keywords\r\n\t\t\tvar field ='';\r\n\t\t\tfor(var k = 0 ; k< 6 ; k++){\r\n\t\t\t\tcount = 0; temp = \"\";\r\n\t\t\t\tswitch(k){\r\n\t\t\t\t\tcase 1: field ='location'; break;\r\n\t\t\t\t\tcase 2: field ='person'; break;\r\n\t\t\t\t\tcase 3: field ='genre'; break;\r\n\t\t\t\t\tcase 4: field ='misc'; break;\r\n\t\t\t\t\tcase 5: field ='system'; break;\r\n\t\t\t\t\tdefault: field ='theme'; break;\r\n\t\t\t\t}\r\n\t\t\t\tfor(var j in tab_of_areas[i][k])\r\n\t\t\t\t{\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(count >0 ) s = \",\"; else s = \"\";\r\n\t\t\t\t\tif(tab_of_areas[i][k][j] > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(tab_of_areas[i][k][j] <= max_value){\r\n\t\t\t\t\t\t\ttemp += s+tab_keywords[k][j];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\ttemp += s+options_values[field][tab_of_areas[i][k][j] - max_value];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcount++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tval += temp+\"~\";\r\n\t\t\t}\r\n\t\r\n\t\t\t\r\n\t\t\t//direct_links\r\n\t\t\tcount = 0; temp = \"\";\r\n\t\t\tfor(var j in tab_of_areas[i][6])\r\n\t\t\t{\r\n\t\t\t\tif(count >0 ) s = \",\"; else s = \"\";\r\n\t\t\t\tif(tab_of_areas[i][6][j] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttemp += s+tab_direct_link[j];\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tval += temp+\"|\";\r\n\t\t}\r\n\t\t\r\n\t\tval = val.substr(0,val.length - 1);\r\n\t\t$('#add_form').append(\"<input type='hidden' name='key_areas' value='\"+val+\"' />\");\r\n\t\t//key areas end\r\n\t\t\r\n\t\t//keywords\r\n\t\tvar field =''; var _field = '';\r\n\t\tfor(var k = 0 ; k< 6 ; k++){\r\n\t\t\tcount = 0; temp = \"\";\r\n\t\t\tswitch(k){\r\n\t\t\t\tcase 1: field ='location'; _field ='locations'; break;\r\n\t\t\t\tcase 2: field ='person'; _field ='persons'; break;\r\n\t\t\t\tcase 3: field ='genre'; _field ='genre'; break;\r\n\t\t\t\tcase 4: field ='misc'; _field ='misc'; break;\r\n\t\t\t\tcase 5: field ='system'; _field ='system'; break;\r\n\t\t\t\tdefault: field ='theme'; _field = 'themes'; break;\r\n\t\t\t}\r\n\t\t\tfor(var i in tab_of_keywords[k])\r\n\t\t\t{\r\n\t\t\t\tif(count >0 ) s = \",\"; else s = \"\";\r\n\t\t\t\tif(tab_of_keywords[k][i] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(tab_of_keywords[k][i] <= max_value){\r\n\t\t\t\t\t\ttemp += s+tab_keywords[k][i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\ttemp += s+options_values[field][tab_of_keywords[k][i] - max_value];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t$('#add_form').append(\"<input type='hidden' name='\"+_field+\"' value='\"+temp+\"' />\");\r\n\t\t}\r\n\t\t//keywords end\r\n\t\t\r\n\t\t//direct_links\r\n\t\tcount = 0; temp = \"\";\r\n\t\tfor(var i in tab_of_keywords[6])\r\n\t\t{\r\n\t\t\tif(count >0 ) s = \",\"; else s = \"\";\r\n\t\t\tif(tab_of_keywords[6][i] > 0)\r\n\t\t\t{\r\n\t\t\t\ttemp += s+tab_direct_link[i];\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t$('#add_form').append(\"<input type='hidden' name='direct_links' value='\"+temp+\"' />\");\r\n\t\t//direct_links end\r\n\t\t\r\n\t\t//keywords added\r\n\t\tvar field =''; var _field = '';\r\n\t\tfor(var k = 0 ; k< 6 ; k++){\r\n\t\t\tcount = 0; temp = \"\";\r\n\t\t\tswitch(k){\r\n\t\t\t\tcase 1: field ='location'; _field ='locations'; break;\r\n\t\t\t\tcase 2: field ='person'; _field ='persons'; break;\r\n\t\t\t\tcase 3: field ='genre'; _field ='genres'; break;\r\n\t\t\t\tcase 4: field ='misc'; _field ='misc'; break;\r\n\t\t\t\tcase 5: field ='system'; _field ='systems'; break;\r\n\t\t\t\tdefault: field ='theme'; _field = 'themes'; break;\r\n\t\t\t}\r\n\t\t\tfor(var i in options_values[field])\r\n\t\t\t{\r\n\t\t\t\tif(count >0 ) s = \",\"; else s = \"\";\r\n\t\t\t\tif(i>0) temp += s+options_values[field][i];\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t\t$('#add_form').append(\"<input type='hidden' name='\"+_field+\"_added' value='\"+temp+\"' />\");\r\n\t\t}\r\n\t\t//keywords added end\t\t\t\r\n\t}",
"function FUN_DI_EVENT_VALIDATION(BaseId,CtrlId)\n {\n \n \n var ExpMessage=\"\"\n var ExpCtrlID=\"\"\n\n var obj=document.getElementById(\"Ucodelevel1\")\n var obj1=document.getElementById(\"FLD_14_30\")\n if(obj!=null && obj1 !=null)\n {\n\n var selIndex=obj.selectedIndex\n var deptname=obj.options(selIndex).text\n selIndex=obj1.selectedIndex\n var Initdeptname=obj1.options(selIndex).text\n if (Initdeptname!=deptname)\n {\n // alert(\"Initiation Department and Ucode-Department Name Should Be Equal\")\n ExpMessage=\"Initiation Department Name Should be Equal to Unique Item Value:Department Name\"\n \n \n }\n ExpCtrlID=\"Ucodelevel1\"\n var idStr=\"Ucodelevel1\"\n setExpMessage(ExpMessage,ExpCtrlID,idStr)\n } \n \n \n var EventRelTo =document.getElementById(\"FLD_\" + BaseId + \"_\" + CtrlId).value\n var ExpMessage=\"\"\n var ExpCtrlID=\"\"\n var PoupIdArr =new Array()\n\n var FldBaseIdList='2,17,3,18,92,80,19'//'21,4,22,23,24'//'111,115,116,112,113,97,98,92,95,26' \n var FldCtrlIdList='1,11,2,11,73,53,11'//'23,11,11,11,11'//'1,23,54,1,47,11,11,38,11,11'\n var FldTypeLst ='Product,Product,Material,Material,System,Equipment,Others'//'Product,Product,System,Utility,Others'//'1,1,2,3,4'//'1,1,2,2,2,3,3,4,4,5' \n var FldDataTypeLst='1,6,1,6,6,6,6'//'1,6,6,6,6'//'1,13,4,1,13,1,11,11,1,11,11,'\n var FldExpMessage=\"Select Value For: Product #*# Enter Value For: Batch No.(s) #*# Select Value For: Material #*# Enter Value For: Lot No.(s) #*# Enter Value For: System #*#Enter Value For: Equipment #*#Enter Value For: Other Details \"//\"Select Product #*# Select Batch(s) Details #*#Select Type of Material #*# Select Material #*# Select Lot(s) Details #*# Enter Document - Name #*# Enter Document - Number #*# Select Equipment / Facility #*#Enter Equipment / Facility - Area Located #*# Enter Other Details\" //#*# Select product type\n\n var FldBaseIdArr=new Array()\n var FldCtrlIdArr=new Array()\n var FldExpMsgArr=new Array()\n var FldTypeArr=new Array()\n var FldDataTyepArr=new Array()\n\n FldBaseIdArr=FldBaseIdList.split(\",\")\n FldCtrlIdArr=FldCtrlIdList.split(\",\")\n FldExpMsgArr=FldExpMessage.split(\"#*#\")\n FldTypeArr=FldTypeLst.split(\",\")\n FldDataTyepArr=FldDataTypeLst.split(\",\")\n\n \n for(var k=0;k<=FldBaseIdArr.length-1;k++)\n {\n\n if (FldCtrlIdArr[k] !=12 )\n var obj=document.getElementById(\"FLD_\" + FldBaseIdArr[k] + \"_\" + FldCtrlIdArr[k])\n else\n var obj=document.getElementById(\"FLD_\" + FldBaseIdArr[k] + \"_\" + FldCtrlIdArr[k] + \":CalDateVal\")\n\n if(obj!=null)\n { \n if (FldTypeArr[k] == EventRelTo) \n \n { \n if(FldDataTyepArr[k]==4)\n {\n var CheckFld=false\n var ItemsLen=obj.cells.length \n for( var i=0;i<ItemsLen;i++)\n {\n if ((obj.id + \"_\" + i).checked == true)CheckFld=true\n }\n if(CheckFld!=true){ ExpMessage= ExpMessage + FldExpMsgArr[k] + '#*#' ; ExpCtrlID=ExpCtrlID + obj.id + '#*#' }\n }\n else\n {\n if(obj.value==\"\") { ExpMessage= ExpMessage + FldExpMsgArr[k] + '#*#' ; ExpCtrlID=ExpCtrlID + obj.id + '#*#' }\n }\n document.getElementById(\"FLDLBL_\" + FldBaseIdArr[k] + \"_\" + FldCtrlIdArr[k]).className=\"MainTD\" \n } \n else document.getElementById(\"FLDLBL_\" + FldBaseIdArr[k] + \"_\" + FldCtrlIdArr[k]).className=\"HideRow\" \n }\n }\n var idStr=BaseId + '_' + CtrlId\n setExpMessage(ExpMessage,ExpCtrlID,idStr)\n }",
"function alreadyCoveredCoverageData() {\n\tvar abc = \"\";\n\tvar temp;\n\tif ($('#availddLgdLBVillageCAreaSourceLUnmapped').is(\":visible\")) {\n\t\tvar selObj = document.getElementById('availddLgdLBVillageCAreaSourceLUnmapped');\n\t\tfor ( var i = 0; i < selObj.options.length; i++) {\n\t\t\ttemp = selObj.options[i].value;\n\t\t\tvar test = temp.split(\"_\");\n\t\t\tvar id = test[0] + \"_V\";\n\t\t\t// alert(\"id:\"+id);\n\t\t\tabc = abc + id + \"@\";\n\t\t}\n\t}\n\n\tvar temp1;\n\tif ($('#availddLgdLBInterCAreaSourceLUmapped').is(\":visible\")) {\n\t\tvar selObj1 = document.getElementById('availddLgdLBInterCAreaSourceLUmapped');\n\t\tfor ( var i = 0; i < selObj1.options.length; i++) {\n\t\t\ttemp1 = selObj1.options[i].value;\n\t\t\tvar test1 = temp1.split(\"_\");\n\t\t\tvar id1 = test1[0] + \"_T\";\n\t\t\tabc = abc + id1 + \"@\";\n\t\t}\n\t}\n\tvar temp2;\n\tif ($('#availddLgdLBVillageSourceLatICAUmapped').is(\":visible\")) {\n\t\tvar selObj2 = document.getElementById('availddLgdLBVillageSourceLatICAUmapped');\n\t\tfor ( var i = 0; i < selObj2.options.length; i++) {\n\t\t\ttemp2 = selObj2.options[i].value;\n\t\t\tvar test2 = temp2.split(\"_\");\n\t\t\tvar id2 = test2[0] + \"_V\";\n\t\t\tabc = abc + id2 + \"@\";\n\t\t}\n\t}\n\tvar temp3;\n\tif ($('#availddLgdLBDistCAreaSourceLUmapped').is(\":visible\")) {\n\t\tvar selObj3 = document.getElementById('availddLgdLBDistCAreaSourceLUmapped');\n\t\tfor ( var i = 0; i < selObj3.options.length; i++) {\n\t\t\ttemp3 = selObj3.options[i].value;\n\t\t\tvar test3 = temp3.split(\"_\");\n\t\t\tvar id3 = test3[0] + \"_D\";\n\t\t\tabc = abc + id3 + \"@\";\n\t\t}\n\t}\n\tvar temp4;\n\tif ($('#availddLgdLBSubDistrictSourceLatDCAUmapped').is(\":visible\")) {\n\t\tvar selObj4 = document.getElementById('availddLgdLBSubDistrictSourceLatDCAUmapped');\n\t\tfor ( var i = 0; i < selObj4.options.length; i++) {\n\t\t\ttemp4 = selObj4.options[i].value;\n\t\t\tvar test4 = temp4.split(\"_\");\n\t\t\tvar id4 = test4[0] + \"_T\";\n\t\t\tabc = abc + id4 + \"@\";\n\t\t}\n\t}\n\tvar temp5;\n\tif ($('#availddLgdLBVillageSourceLatDCAUmapped').is(\":visible\")) {\n\t\tvar selObj5 = document.getElementById('availddLgdLBVillageSourceLatDCAUmapped');\n\t\tfor ( var i = 0; i < selObj5.options.length; i++) {\n\t\t\ttemp5 = selObj5.options[i].value;\n\t\t\tvar test5 = temp5.split(\"_\");\n\t\t\tvar id5 = test5[0] + \"_V\";\n\t\t\tabc = abc + id5 + \"@\";\n\t\t}\n\t}\n\n\tvar temp6;\n\tif ($('#availddLgdLBInterCAreaSourceLUmappedUrban').is(\":visible\")) {\n\t\tvar selObj6 = document.getElementById('availddLgdLBInterCAreaSourceLUmappedUrban');\n\t\tfor ( var i = 0; i < selObj6.options.length; i++) {\n\t\t\ttemp6 = selObj6.options[i].value;\n\t\t\tvar test6 = temp6.split(\"_\");\n\t\t\tvar id6 = test6[0] + \"_T\";\n\t\t\tabc = abc + id6 + \"@\";\n\t\t}\n\t}\n\n\tvar alredycovered = abc.split(\"@\");\n\tvar alreadycoveredsplit = finalval1.split(\"@\");\n\tfor ( var i = 0; i < alredycovered.length - 1; i++) {\n\t\tvar alreadycoveredfinal = alredycovered[i];\n\t\tfor ( var j = 0; j < alreadycoveredsplit.length; j++) {\n\t\t\tvar checkval = alreadycoveredsplit[j];\n\t\t\tif (checkval == alreadycoveredfinal) {\n\t\t\t\talert(\"Selected area has already mapped with this local body\");\n\t\t\t\tfinalval1 = \"\";\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t}\n\n\t\t}\n\t}\n\treturn true;\n}",
"function fn_createlicense(id)\n{\n\tvar list4 = [];\t //module id\n\tvar list6 = [];\t //unit id\n\tvar list8 = [];\t //ipl id\n\tvar list10 = []; //assessmentid\t\n\tvar list12 = []; //Questid\t\n\tvar list14 = []; //expdetion / destination id\n var list16= []; //courses\n var list18= []; //units\n var list20= []; //phases\n var list22= []; //videos\n var list24= []; //pd lessons\n var list26= []; //Missions\n var list28= []; //documents\n\tvar list30= []; //Product\n var list32= []; //Nondigitalcontent\n\tvar extids = [];\n\t\n\t$(\"div[id^=list4_]\").each(function()\n\t{\n\t\tlist4.push($(this).attr('name').replace('list4_',''));\n\t});\t\n\t\n\t$(\"div[id^=list6_]\").each(function()\n\t{\n\t\tlist6.push($(this).attr('id').replace('list6_',''));\n\t});\t\n\t\n\t$(\"div[id^=list10_]\").each(function()\n\t{\n\t\tlist10.push($(this).attr('id').replace('list10_',''));\n\t});\t\t\n\t\t\n\t$(\"div[id^=list8_]\").each(function()\n\t{\n\t\tlist8.push($(this).attr('name').replace('list8_',''));\n\t});\n\t\t\n\t$(\"div[id^=list12_]\").each(function()\n\t{\n\t\tlist12.push($(this).attr('name').replace('list12_',''));\n\t});\n\t\n\t$(\"div[id^=list14_]\").each(function()\n\t{\n\t\tlist14.push($(this).attr('name').replace('list14_',''));\n\t});\n\t\n $(\"div[id^=list16_]\").each(function()\n {\n list16.push($(this).attr('id').replace('list16_',''));\n });\n\t\n $(\"div[id^=list24_]\").each(function()\n {\n list24.push($(this).attr('name').replace('list24_',''));\n });\n //pd\n \n //SOS\n $(\"div[id^=list18_]\").each(function()\n {\n list18.push($(this).attr('id').replace('list18_',''));\n });\n \n $(\"div[id^=list20_]\").each(function()\n {\n list20.push($(this).attr('name').replace('list20_',''));\n });\n \n $(\"div[id^=list22_]\").each(function()\n {\n list22.push($(this).attr('name').replace('list22_',''));\n });\n \n $(\"div[id^=list26_]\").each(function()\n {\n list26.push($(this).attr('name').replace('list26_',''));\n });\n \n $(\"div[id^=list32_]\").each(function()\n {\n list32.push($(this).attr('id').replace('list32_',''));\n });\n \n $(\"div[id^=list28_]\").each(function()\n {\n list28.push($(this).attr('name').replace('list28_',''));\n });\n\t\t//sim product\n\t\t$(\"div[id^=list30_]\").each(function()\n\t\t{\n\t\t\t\tlist30.push($(this).attr('name').replace('list30_',''));\n\t\t});\n \n\t$(\"input[id^=exid_]\").each(function()\n\t{\n\t\textids.push($(this).val());\n\t});\n\t\n\tvar dataparam = \"oper=savelicense\"+\"&licennsename=\"+$('#licennsename').val()+\"&duration=\"+$('#duration').val()+\"&amount=\"+$('#amount').val()+\"&sales=\"+$('#sales').val()+\"&month=\"+$('#hidmonth').val()+\"&licensetype=\"+$('#hidlicensetype').val()+\"&id=\"+id+\"&list4=\"+list4+\"&list6=\"+list6+\"&list8=\"+list8+\"&list12=\"+list12+\"&list14=\"+list14+\"&tags=\"+$('#form_tags_license').val()+\"&extids=\"+extids+\"&list16=\"+list16+\"&list24=\"+list24+\"&list26=\"+list26+\"&list18=\"+list18+\"&list20=\"+list20+\"&list22=\"+list22+\"&contenttype=\"+$('#contenttype').val()+\"&list28=\"+list28+\"&list10=\"+list10+\"&list30=\"+list30+\"&list32=\"+list32;\n\tif($(\"#createlicense\").validate().form())\n\t{\n\t\t\t\t\t\n\t\t\tif(id!=0 && id!=undefined){\n\t\t\t\tactionmsg = \"Updating\";\n\t\t\t\talertmsg = \" License has been updated successfully\"; \n\t\t\t}\n\t\t\telse {\n\t\t\t\tactionmsg = \"Saving\";\n\t\t\t\talertmsg = \"License has been created successfully\"; \n\t\t\t}\t \n\t\t\t\n\t\t\t$.ajax({\n\t\t\t\ttype: 'post',\n\t\t\t\turl: \"licenses/newlicense/licenses-newlicense-newlicenseajax.php\",\n\t\t\t\tdata: dataparam,\n\t\t\t\tbeforeSend: function(){\n\t\t\t\t\tshowloadingalert(actionmsg+\", please wait.\");\t\n\t\t\t\t},\n\t\t\t\tsuccess: function (data) {\t\t\t\t\t\n\t\t\t\t\tif(trim(data)==\"success\")\n\t\t\t\t\t{\n\t\t\t\t\t\t$('.lb-content').html(alertmsg);\n\t\t\t\t\t\tsetTimeout('closeloadingalert()',1000);\n\t\t\t\t\t\tsetTimeout('removesections(\"#home\");',500);\n\t\t\t\t\t\tsetTimeout('showpages(\"licenses\",\"licenses/licenses.php\");',500);\n\t\t\t\t\t}\n\t\t\t\t\telse if(trim(data)==\"fail\")\n\t\t\t\t\t{\n\t\t\t\t\t\t$('.lb-content').html(\"Incorrect Data\");\n\t\t\t\t\t\tsetTimeout('closeloadingalert()',1000);\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t},\n\t\t\t});\n\t\t\n\t}\n}",
"regla6_7_8_9() {\n for (let i = 0; i < this.cadenaSplit.length; i++) {\n\n let instruccion = this.cadenaSplit[i].trim();\n\n if (this.reAsignacionOp01.test(instruccion)) {\n\n let instruccionSplit = instruccion.replace(';','').split('=');\n let id1 = instruccionSplit[0].trim();\n\n // Regla 6 y 10\n if (instruccionSplit[1].includes('+')) {\n let operacionSplit = instruccionSplit[1].split('+');\n let idOperacion = operacionSplit[0].trim();\n let valOperacion = operacionSplit[1].trim();\n\n console.log(instruccion);\n console.log(' ', id1, '----', idOperacion);\n console.log(' ', valOperacion);\n\n // Regla 6\n if ((id1 === idOperacion) && (valOperacion === '0')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 6,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n }\n \n if ((id1 === valOperacion) && (idOperacion === '0')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 6,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n } \n\n \n\n // Regla 10\n if ((id1 !== idOperacion) && (valOperacion === '0')) {\n let nuevaInstruccion = `${id1} = ${idOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 10,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n if ((id1 !== valOperacion) && (idOperacion === '0')) {\n let nuevaInstruccion = `${id1} = ${valOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 10,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n } \n\n\n }\n\n //Regla 7 y 11\n if (instruccionSplit[1].includes('-')) {\n let operacionSplit = instruccionSplit[1].split('-');\n let idOperacion = operacionSplit[0].trim();\n let valOperacion = operacionSplit[1].trim();\n\n // Regla 7\n if ((id1 === idOperacion) && (valOperacion === '0')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 7,\n linea: i,\n instruccion: `${idOperacion} = ${idOperacion} - 0;`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n }\n\n // Regla 11\n if ((id1 !== idOperacion) && (valOperacion === '0')) {\n let nuevaInstruccion = `${id1} = ${idOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 11,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n }\n\n //Regla 8 y 12 y 14 Y 15\n if (instruccionSplit[1].includes('*')) {\n let operacionSplit = instruccionSplit[1].split('*');\n let idOperacion = operacionSplit[0].trim();\n let valOperacion = operacionSplit[1].trim();\n\n // Regla 8\n if ((id1 === idOperacion) && (valOperacion === '1')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 8,\n linea: i,\n instruccion: `${idOperacion} = ${idOperacion} * 1;`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n }\n\n if ((id1 === valOperacion) && (idOperacion === '1')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 8,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n } \n\n // Regla 12\n if ((id1 !== idOperacion) && (valOperacion === '1')) {\n let nuevaInstruccion = `${id1} = ${idOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 12,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n if ((id1 !== valOperacion) && (idOperacion === '1')) {\n let nuevaInstruccion = `${id1} = ${valOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 12,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n // Regla 14\n if ((id1 !== idOperacion) && (valOperacion === '2')) {\n let nuevaInstruccion = `${id1} = ${idOperacion} + ${idOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 14,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n if ((id1 !== valOperacion) && (idOperacion === '2')) {\n let nuevaInstruccion = `${id1} = ${valOperacion} + ${valOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 14,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n // Regla 15\n if ((id1 !== idOperacion) && (valOperacion === '0')) {\n let nuevaInstruccion = `${id1} = 0;`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 15,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n\n });\n continue;\n }\n\n if ((id1 !== valOperacion) && (idOperacion === '0')) {\n let nuevaInstruccion = `${id1} = 0;`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 15,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n\n });\n continue;\n }\n }\n\n //Regla 9 y 13 y 16\n if (instruccionSplit[1].includes('/')) {\n let operacionSplit = instruccionSplit[1].split('/');\n let idOperacion = operacionSplit[0].trim();\n let valOperacion = operacionSplit[1].trim();\n\n // Regla 9\n if ((id1 === idOperacion) && (valOperacion === '1')) {\n this.cadenaOptimizada[i] = '';\n this.cadenaSplit[i] = '';\n this.bitacoraOptimizaciones.push({\n regla: 9,\n linea: i,\n instruccion: `${idOperacion} = ${idOperacion} / 1;`,\n cambio: `Se elimina la instruccion`\n });\n continue;\n }\n\n // Regla 13\n if ((id1 !== idOperacion) && (valOperacion === '1')) {\n let nuevaInstruccion = `${id1} = ${idOperacion};`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 13,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n\n // Regla 16\n if ((id1 !== valOperacion.trim()) && (idOperacion === '0')) {\n let nuevaInstruccion = `${id1} = 0;`;\n\n this.cadenaOptimizada[i] = nuevaInstruccion;\n this.cadenaSplit[i] = nuevaInstruccion;\n this.bitacoraOptimizaciones.push({\n regla: 16,\n linea: i,\n instruccion: `${instruccion}`,\n cambio: `${nuevaInstruccion}`\n });\n continue;\n }\n }\n }\n this.cadenaOptimizada[i] = instruccion;\n }\n }",
"function GenerateDynamicInputs(element, groupElement) {\n\t\tvar nGroups = $(groupElement).val();\n\t\tvar html_String = \"\";\n\t\tfor (var i=1;i<=nGroups;i++){\n\t\t\tvar total_sub = $(element).find('input[id=edit_total_sub_question_'+i+']').val();\n\t\t\tif (total_sub == null) total_sub = 1;\n\t\t\ttotal_sub = parseInt(total_sub);\n\t\t\thtml_String += '<li class=\"field comp-setting-entry is-set\">';\n\t\t\thtml_String += '<div class=\"wrapper-comp-setting\">';\n\t\t\thtml_String += '<label class=\"label setting-label\">Q'+i+': Total question</label>';\n\t\t\thtml_String += '<input class=\"input setting-input edit_sub_number\" id=\"edit_total_sub_question_'+i+'\" value=\"'+total_sub+'\" type=\"number\" >';\n\t\t\thtml_String += '<div class=\"min-max-button\" id=\"'+i+'\">-</div>';\n\t\t\thtml_String += '</div>';\n\t\t\thtml_String += '<div class=\"question-set\" id = \"question-group-'+i+'\">';\n\t\t\tfor (var j=1;j<=total_sub;j++){\n\t\t\t\tvar question_name = $(element).find('input[name=question' + i + '\\\\.'+ j + ']').val();\n\t\t\t\tif (question_name == null){question_name = \"\";}\n\t\t\t\tvar picture_link = $(element).find('input[name=question' + i + '\\\\.'+ j + '_pic]').val();\n\t\t\t\tif (picture_link == null){picture_link = \"\";}\n\t\t\t\thtml_String += '<div id=\"Q'+i+'.'+j+'\">';\n\t\t\t\thtml_String += '<div class=\"wrapper-comp-setting\">';\n\t\t\t\t//question label\n\t\t\t\thtml_String += '<label class=\"label setting-label\">Q' + i + '.' + j +' Question</label>';\n\t\t\t\t//question content input\n\t\t\t\thtml_String += '<input class=\"input setting-input question-name\" name=\"question' + i + '.' + j +'\" id=\"question' + i + '.' + j +'\" value=\"' + question_name + '\" type=\"text\">';\n\t\t\t\t//minimize buton\t\t\t\t\t\n\t\t\t\thtml_String += '<div class=\"min-max-button\" id=\"'+i+'.'+j+'\">-</div>';\n\t\t\t\thtml_String += '</div>';\n\n\t\t\t\t//picture part + to be minimized part\n\t\t\t\thtml_String += '<div id=\"QS'+i+'.'+j+'\">';\n\t\t\t\t// picture\n\t\t\t\thtml_String += '<div class=\"wrapper-comp-setting\" >';\n\t\t\t\thtml_String += '<label class=\"label setting-label\">Q' + i + '.' + j +' Picture</label>';\n\t\t\t\thtml_String += '<input class=\"input setting-input question-name\" name=\"question' + i + '.' + j +'_pic\" id=\"question' + i + '.' + j +'_pic\"';\n\t\t\t\thtml_String += 'value=\"' + picture_link + '\" type=\"text\">';\n\t\t\t\thtml_String += '</div>';\n\t\t\t\t//answers\n\t\t\t\tfor (var k=1;k<=4;k++){\n\t\t\t\t\tvar ischecked = \"\";\n\t\t\t\t\tif ($(element).find('input[id=answer' + i + '\\\\.'+ j + '_'+ k + '_cb]').is(':checked')) { ischecked = \"checked\";}\n\t\t\t\t\tvar ans = $(element).find('input[name=answer' + i + '\\\\.'+ j + '_'+ k + ']').val();\n\t\t\t\t\tif (ans == null){ans = \"\";}\n\t\t\t\t\thtml_String += '<div class=\"wrapper-comp-setting\">';\n\t\t\t\t\thtml_String += '<label class=\"label setting-label\">Answer ' + k + '</label>';\n\t\t\t\t\thtml_String += '<input class=\"input setting-input answer-name\" name=\"answer' + i +'.' + j + '_' + k +'\" id=\"answer' + i +'.' + j + '_' + k +'\"';\n\t\t\t\t\thtml_String += 'value=\"' + ans +'\" type=\"text\">';\n\t\t\t\t\thtml_String += '<span class=\"tip setting-help\"><input class=\"checkboxer\" name=\"answer' + i +'.' + j + '_cb\" id=\"answer' + i +'.' + j + '_' + k +'_cb\"';\n\t\t\t\t\thtml_String += 'type=\"checkbox\" '+ ischecked+'></span>';\n\t\t\t\t\thtml_String += '</div>';\t \n\t\t\t\t}\n\t\t\t\t//learning object\n\t\t\t\tif ((total_sub >1 && j != 1) || total_sub == 1){\n\t\t\t\t\tvar lo_url = $(element).find('input[name=lo' + i + '\\\\.' + j + '_link]').val();\n\t\t\t\t\tvar lo_name = $(element).find('input[name=lo' + i + '\\\\.' + j + '_name]').val();\n\t\t\t\t\tif (lo_url == null) lo_url = \"\";\n\t\t\t\t\tif (lo_name == null) lo_name = \"\";\n\t\t\t\t\t//url\n\t\t\t\t\thtml_String += '<div class=\"wrapper-comp-setting\">';\n\t\t\t\t\thtml_String += '<label class=\"label setting-label\">Learning Object Url</label>';\n\t\t\t\t\thtml_String += '<input class=\"input setting-input lo-link\" name=\"lo'+i+'.'+j+'_link\"';\n\t\t\t\t\thtml_String += 'id=\"lo'+i+'.'+j+'_link\" value=\"'+lo_url+'\" type=\"text\">';\n\t\t\t\t\thtml_String += '<span class=\"tip setting-help\">Example:\"vbv45ad59svsrtu81\"</span>';\n\t\t\t\t\thtml_String += '</div>';\n\t\t\t\t\t//name\n\t\t\t\t\thtml_String += '<div class=\"wrapper-comp-setting\">';\n\t\t\t\t\thtml_String += '<label class=\"label setting-label\">Learning Object Name</label>';\n\t\t\t\t\thtml_String += '<input class=\"input setting-input lo-name\" name=\"lo'+i+'.'+j+'_name\"';\n\t\t\t\t\thtml_String += 'id=\"lo'+i+'.'+j+'_name\" value=\"'+lo_name+'\" type=\"text\">';\n\t\t\t\t\thtml_String += '<span class=\"tip setting-help\">Example: \"Multipler\"</span>';\n\t\t\t\t\thtml_String += '</div>';\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\thtml_String += '</div>';\n\t\t\t\thtml_String += '</div>';\n\t\t\t}\n\t\t\thtml_String += '</div></li>'\n }\n\t\tvar toggle_list = [];\n\t\tvar toggle_sub_list = [];\n\t\tfor (var i=1;i<=nGroups;i++){\n\t\t\tif ($(element).find('#' + i).html()=='+'){\n\t\t\t\ttoggle_list.push(i)\n\t\t\t}\n\t\t\tvar total_sub = $(element).find('input[id=edit_total_sub_question_'+i+']').val();\n\t\t\tfor (var j=1;j<=total_sub;j++){\n\t\t\t\tif ($(element).find('#' + i + '\\\\.' + j).html()=='+'){\n\t\t\t\t\ttoggle_sub_list.push([i,j]);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n $(\"#panel2\", element).html(html_String);\n\t\tfor (var i=0;i<toggle_sub_list.length;i++){\n\t\t\t$(element).find('#' + toggle_sub_list[i][0] + '\\\\.' + toggle_sub_list[i][1]).html(\"+\");\n\t\t\t$(\"#QS\" + toggle_sub_list[i][0] +'\\\\.' + toggle_sub_list[i][1]).slideUp(0);\n\t\t}\n\t\tfor (var i=0;i<toggle_list.length;i++){\n\t\t\t$(element).find('#' + toggle_list[i]).html(\"+\");\n\t\t\t$(\"#question-group-\" + toggle_list[i]).slideUp(0);\n\t\t}\n\t\t\n }",
"function first9DartsArraySesssion(dart1, dart2, dart3){\n var darts_hit = [];\n if ((dart1 == true && dart2 == true && dart3 == true) || (dart1 == false && dart2 == false && dart3 == false)){\n for (i = 1; i <= darts_thrown_in_session; i++)\n {\n if (window['dart_throw' + i].darts_in_leg < 9){\n darts_hit.push(window['dart_throw' + i].hit_location);\n }\n }\n }else{\n if (dart1 == true){\n for (i = 1; i <= darts_thrown_in_session; i++)\n {\n if (window['dart_throw' + i].dart_number_in_throw == \"1\" && window['dart_throw' + i].darts_in_leg < 9){\n darts_hit.push(window['dart_throw' + i].hit_location);\n }\n }\n }\n if (dart2 == true){\n for (i = 1; i <= darts_thrown_in_session; i++)\n {\n if (window['dart_throw' + i].dart_number_in_throw == \"2\" && window['dart_throw' + i].darts_in_leg < 9){\n darts_hit.push(window['dart_throw' + i].hit_location);\n }\n }\n }\n if (dart3 == true){\n for (i = 1; i <= darts_thrown_in_session; i++)\n {\n if (window['dart_throw' + i].dart_number_in_throw == \"3\" && window['dart_throw' + i].darts_in_leg < 9){\n darts_hit.push(window['dart_throw' + i].hit_location);\n }\n }\n }\n }\n return darts_hit;\n}",
"function addDSParams(output){\n// incorrect in some cases:\n// var rho = output.slice(1,-1).split(\"\\\\n\")[2].split(\":\")[1].replace(/ /g,'');\n var rho = output.slice(1,-1).split(\"Value:\")[1].replace(/ /g,''); \n if (rho.slice(-1) === \"1\"){\n var is_int = true;\n } else if (rho.slice(-1) === \"2\"){\n var is_int = false;\n }\n var num_inputs = output.split(\",\").length;\n const div = $('<div>').attr({\"id\":\"dsinstru_div\",\"class\":\"form-group\"})\n $('#specify').append(div);\n $('#dsinstru_div').append(\"<p>rho=\"+rho);\n const param_div = $('<div>').attr({\"id\":\"dsparam_div\",\"class\":\"form-group\"})\n $('#specify').append(param_div);\n if (is_int){\n $('#dsparam_div').append(\"<p>Input Harish-Chandra parameters (all integers):</p>\");\n } else {\n $('#dsparam_div').append(\"<p>Input Harish-Chandra parameters (all half integers):</p>\");\n }\n for (var i=1;i<num_inputs;i++){\n $('#dsparam_div').append(\"<input type=\\\"float\\\" id=\"+i+\" maxlength=\\\"5\\\" size=\\\"4\\\">\");\n $('#dsparam_div').append(\", \");\n }\n $('#dsparam_div').append(\"<input type=\\\"float\\\" id=\"+num_inputs+\" maxlength=\\\"5\\\" size=\\\"4\\\">\");\n setOnchangeFuncs(num_inputs,\"clearElements([\\\"notice_choose_show\\\"]),displayNotice()\");\n}",
"function fn_load_assessment(id)\n{\n\t\t\n\tvar list8= []; // get ipl ids\n\t$(\"div[id^=list8_]\").each(function() \n\t{\n\t\tlist8.push($(this).attr('id').replace('list8_',''));\n\t});\t\n\t\n\tvar list4= []; // get module id\n\t$(\"div[id^=list4_]\").each(function() \n\t{\n\t\tlist4.push($(this).attr('id').replace('list4_',''));\n\t});\n\t\n\tvar list12= []; // get Quest id\n\t$(\"div[id^=list12_]\").each(function() \n\t{\n\t\tlist12.push($(this).attr('id').replace('list12_',''));\n\t});\n\t\n\tvar list14= []; // get expedition id\n\t$(\"div[id^=list14_]\").each(function() \n\t{\n\t\tlist14.push($(this).attr('id').replace('list14_',''));\n\t});\n\t\n\t\n\tvar list24= []; // get PD id\n\t$(\"div[id^=list24_]\").each(function() \n\t{\n\t\tlist24.push($(this).attr('id').replace('list24_',''));\n\t});\n\t\n\tvar list26= []; // get Mission id\n\t$(\"div[id^=list26_]\").each(function() \n\t{\n\t\tlist26.push($(this).attr('id').replace('list26_',''));\n\t});\n \n \n\tvar dataparam = \"oper=loadassessment\"+\"&iplids=\"+list8+\"&maduleids=\"+list4+\"&expids=\"+list14+\"&questids=\"+list12+\"&pdids=\"+list24+\"&missionids=\"+list26+\"&id=\"+id;\t\n\t//alert(dataparam);\n\t $.ajax({\n\t\t \ttype: 'post',\n\t\t\turl: \"licenses/newlicense/licenses-newlicense-newlicenseajax.php\",\n\t\t\tdata: dataparam,\n\t\t\tsuccess: function (data) {\t\n\t\t\t \n\t\t\t $('#assessment').html(data);\n\t\t\t\t\n\t\t\t},\n\t\t});\t\n}",
"function geneList() {\n\n clearLists();\n var set = {};\n\n $(\"#identical\").empty();\n $(\"#load_icon\").show();\n\n var entry_fields = {\"a\":\"gl1\", \"b\":\"gl2\", \"c\":\"gl3\", \"d\":\"gl4\"};\n\n for (item in entry_fields){\n if(document.getElementById(entry_fields[item]).value ){\n var temp = \"orig\" + item.toUpperCase();\n set[temp] = document.getElementById(entry_fields[item]).value.split(/[\\s,]+/).unique();\n set[item] = set[temp].length;\n } \n }\n\n\n set.iab = intersect(set.origA, set.origB);\n set.iac = intersect(set.origA, set.origC);\n set.iad = intersect(set.origA, set.origD);\n set.ibc = intersect(set.origB, set.origC);\n set.ibd = intersect(set.origB, set.origD);\n set.icd = intersect(set.origC, set.origD);\n\n\n\n\n\n// spam abcd\n set.iaNab = arr_diff(set.origA, set.iab);\n set.iaNac = arr_diff(set.origA, set.iac);\n set.iaNad = arr_diff(set.origA, set.iad);\n set.iaNbc = arr_diff(set.origA, set.ibc);\n set.iaNbd = arr_diff(set.origA, set.ibd);\n set.iaNcd = arr_diff(set.origA, set.icd);\n\n set.ibNab = arr_diff(set.origB, set.iab);\n set.ibNac = arr_diff(set.origB, set.iac);\n set.ibNad = arr_diff(set.origB, set.iad);\n set.ibNbc = arr_diff(set.origB, set.ibc);\n set.ibNbd = arr_diff(set.origB, set.ibd);\n set.ibNcd = arr_diff(set.origB, set.icd);\n\n\n set.icNab = arr_diff(set.origC, set.iab);\n set.icNac = arr_diff(set.origC, set.iac);\n set.icNad = arr_diff(set.origC, set.iad);\n set.icNbc = arr_diff(set.origC, set.ibc);\n set.icNbd = arr_diff(set.origC, set.ibd);\n set.icNcd = arr_diff(set.origC, set.icd);\n\n\n set.idNab = arr_diff(set.origD, set.iab);\n set.idNac = arr_diff(set.origD, set.iac);\n set.idNad = arr_diff(set.origD, set.iad);\n set.idNbc = arr_diff(set.origD, set.ibc);\n set.idNbd = arr_diff(set.origD, set.ibd);\n set.idNcd = arr_diff(set.origD, set.icd);\n \n//end spam\n\n\n\n\n\n\n\n set.iabc = intersect(set.iab, set.iac);\n set.iabd = intersect(set.iab, set.ibd);\n set.iacd = intersect(set.iac, set.icd);\n set.ibcd = intersect(set.ibc, set.icd);\n\n\nif(set.origA && set.origB && set.origC){\n\n set.iabNabc = arr_diff(set.iab, set.iabc);\n set.iacNabc = arr_diff(set.iac, set.iabc);\n set.iadNabc = arr_diff(set.iad, set.iabc);\n set.ibcNabc = arr_diff(set.ibc, set.iabc);\n set.ibdNabc = arr_diff(set.ibd, set.iabc);\n set.icdNabc = arr_diff(set.icd, set.iabc);\n\n}\n\n\n if(set.origA && set.origB && set.origC && set.origD){\n\n set.iabNabd = arr_diff(set.iab, set.iabd);\n set.iacNabd = arr_diff(set.iac, set.iabd);\n set.iadNabd = arr_diff(set.iad, set.iabd);\n set.ibcNabd = arr_diff(set.ibc, set.iabd);\n set.ibdNabd = arr_diff(set.ibd, set.iabd);\n set.icdNabd = arr_diff(set.icd, set.iabd);\n\n set.iabNacd = arr_diff(set.iab, set.iacd);\n set.iacNacd = arr_diff(set.iac, set.iacd);\n set.iadNacd = arr_diff(set.iad, set.iacd);\n set.ibcNacd = arr_diff(set.ibc, set.iacd);\n set.ibdNacd = arr_diff(set.ibd, set.iacd);\n set.icdNacd = arr_diff(set.icd, set.iacd);\n\n set.iabNbcd = arr_diff(set.iab, set.ibcd);\n set.iacNbcd = arr_diff(set.iac, set.ibcd);\n set.iadNbcd = arr_diff(set.iad, set.ibcd);\n set.ibcNbcd = arr_diff(set.ibc, set.ibcd);\n set.ibdNbcd = arr_diff(set.ibd, set.ibcd);\n set.icdNbcd = arr_diff(set.icd, set.ibcd);\n\n }\n\n\n\n set.iabcd = intersect(set.iab, set.icd);\n\n\n\n set.ab = set.iab.length;\n set.ac = set.iac.length;\n set.ad = set.iad.length;\n set.bc = set.ibc.length;\n set.bd = set.ibd.length;\n set.cd = set.icd.length;\n\n set.abc = set.iabc.length;\n set.abd = set.iabd.length;\n set.acd = set.iacd.length;\n set.bcd = set.ibcd.length;\n\n set.abcd = set.iabcd.length;\n\n\n\n if (set.origA && set.origB && !set.origC && !set.origD) {\n twoSetBoilerPlate(set);\n }\n\n if (set.origA && set.origB && set.origC && !set.origD) {\n threeSetBoilerPlate(set);\n }\n\n if (set.origA && set.origB && set.origC && set.origD) {\n fourSetBoilerPlate(set);\n }\n\n\n $(\"#load_icon\").hide();\n\n\n\n}",
"function validateLTCGSectionWiseDTAA() {\r\n\t\r\n\tvar arr = {'B1e':0,'B2e':0,'B3e':0,'B4e_22':0,'B4e_5ACA1b':0,'B5c':0,'B6e_21ciii':0,'B6e_5AC1c':0,'B6e_5ADiii':0,'B7c':0,'B7f':0,'B8e':0,'B9':0};\r\n\tvar tab = document.getElementById('scheduleLtcgDtaa');\r\n\t var rowCount = tab.rows.length -2;\r\n\t for(var i=0; i<rowCount; i++) {\r\n\t var itemIncluded = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].itemIncluded')[0].value;\r\n\t var amount = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].amount')[0].value; \r\n\t if(itemIncluded == 'B1e') {\r\n\t arr['B1e'] = parseInt(arr['B1e'],10) + parseInt(coalesce(amount),10);\r\n\t } else if(itemIncluded == 'B2e') {\r\n\t\t arr['B2e'] = parseInt(arr['B2e'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B3e') {\r\n\t\t arr['B3e'] = parseInt(arr['B3e'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B4e_22') {\r\n\t\t arr['B4e_22'] = parseInt(arr['B4e_22'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B4e_5ACA1b') {\r\n\t\t arr['B4e_5ACA1b'] = parseInt(arr['B4e_5ACA1b'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B5c') {\r\n\t\t arr['B5c'] = parseInt(arr['B5c'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B6e_21ciii') {\r\n\t\t arr['B6e_21ciii'] = parseInt(arr['B6e_21ciii'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B6e_5AC1c') {\r\n\t\t\t arr['B6e_5AC1c'] = parseInt(arr['B6e_5AC1c'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B6e_5ADiii') {\r\n\t\t arr['B6e_5ADiii'] = parseInt(arr['B6e_5ADiii'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B7c') {\r\n\t\t arr['B7c'] = parseInt(arr['B7c'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B7f') {\r\n\t\t arr['B7f'] = parseInt(arr['B7f'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B8e') {\r\n\t\t arr['B8e'] = parseInt(arr['B8e'],10) + parseInt(coalesce(amount),10);\r\n\t\t} else if(itemIncluded == 'B9') {\r\n\t\t arr['B9'] = parseInt(arr['B9'],10) + parseInt(coalesce(amount),10);\r\n\t\t}\r\n\t }\r\n\t\r\n\tvar table = document.getElementById('scheduleLtcgDtaa');\r\n\tvar rowCount = table.rows.length -2;\r\n\t\r\n\tvar dtaaSection = [];\r\n\t\r\n\tfor(var i=0; i<rowCount; i++) {\r\n\t\tvar itemIncluded = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].itemIncluded')[0].value;\r\n\t\tif(itemIncluded != '' && dtaaSection.indexOf(itemIncluded) == -1) {\r\n\t\t\tdtaaSection.push(itemIncluded);\r\n\t\t}\r\n\t}\r\n\r\n\tvar fullConsideration50C = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0];\r\n\tif(dtaaSection.indexOf('B1e') != -1 && arr['B1e'] > 0 && fullConsideration50C.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C','B1(aiii) value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(fullConsideration50C,'B1(aiii) value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar fullConsideration = document.getElementsByName('scheduleCGFor4.shortTermCapGainFor4.capGainSlumpSale.fullConsiderationB')[0];\r\n\tif(dtaaSection.indexOf('B2e') != -1 && arr['B2e'] > 0 && fullConsideration.value == 0) {\r\n\t\tj.setFieldError('scheduleCGFor4.shortTermCapGainFor4.capGainSlumpSale.fullConsiderationB','B2a value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(fullConsideration,'B2a value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar fullConsiderationB3e = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.fullConsideration')[0];\r\n\tif(dtaaSection.indexOf('B3e') != -1 && arr['B3e'] > 0 && fullConsiderationB3e.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.fullConsideration','B3a value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(fullConsiderationB3e,'B3a value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar table1 = document.getElementById('scheduleCGltcg3');\r\n\tvar rowCount1 = table1.rows.length/11;\r\n\t \r\n\tvar arrSection = [];\r\n\tvar arrAmount = {'22':0,'5ACA1b':0};\r\n\t\r\n\tfor(var k=0; k<rowCount1; k++) {\r\n\t var sectionCode = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable['+k+'].sectionCode')[0].value;\r\n\t var fullConsideration = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable['+k+'].fullConsideration')[0].value;\r\n\t\t if(sectionCode != '' && arrSection.indexOf(sectionCode) == -1) {\r\n\t\t\t arrSection.push(sectionCode);\r\n\t\t\t arrAmount[sectionCode] = fullConsideration;\r\n\t\t\t}\r\n\t }\r\n\t\r\n\tif(dtaaSection.indexOf('B4e_22') != -1 && arr['B4e_22'] > 0 && (arrSection.indexOf('22') == -1 || arrAmount['22'] == 0)) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','22 section in B4 should be selected and amount should not be zero, as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'22 section in B4 should be selected and amount should not be zero, as there is an entry in DTAA table.',true);\r\n\t}\r\n\tif(dtaaSection.indexOf('B4e_5ACA1b') != -1 && arr['B4e_5ACA1b'] > 0 && (arrSection.indexOf('5ACA1b') == -1 || arrAmount['5ACA1b'] == 0)) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','5ACA1b section in B4 should be selected and amount should not be zero, as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'5ACA1b section in B4 should be selected and amount should not be zero, as there is an entry in DTAA table.',true);\r\n\t}\r\n\t\r\n\tvar BalanceCG = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.BalanceCG')[0];\r\n\tif(dtaaSection.indexOf('B5c') != -1 && arr['B5c'] > 0 && BalanceCG.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.BalanceCG','B5c value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(BalanceCG,'B5c value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\t\r\n\tvar table2 = document.getElementById('stcg10pctTab');\r\n\tvar rowCount2 = table2.rows.length/11;\r\n\t \r\n\tvar arrSection1 = [];\r\n\tvar arrAmount1 = {'21ciii':0,'5AC1c':0,'5ADiii':0};\r\n\t\r\n\tfor(var a=0; a<rowCount2; a++) {\r\n\t var sectionCode = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115['+a+'].sectionCode')[0].value;\r\n\t var amount = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115['+a+'].fullConsideration')[0].value;\r\n\t\t if(sectionCode != '' && arrSection1.indexOf(sectionCode) == -1) {\r\n\t\t\t arrSection1.push(sectionCode);\r\n\t\t\t arrAmount1[sectionCode] = amount;\r\n\t\t\t}\r\n\t }\r\n\t\r\n\tif(dtaaSection.indexOf('B6e_21ciii') != -1 && arr['B6e_21ciii'] > 0 && (arrSection1.indexOf('21ciii') == -1 || arrAmount1['21ciii'] == 0)) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode','21ciii section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode')[0],'21ciii section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.',true);\r\n\t}\r\n\t\r\n\tif(dtaaSection.indexOf('B6e_5AC1c') != -1 && arr['B6e_5AC1c'] > 0 && (arrSection1.indexOf('5AC1c') == -1 || arrAmount1['5AC1c'] == 0)) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode','5AC1c section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode')[0],'5AC1c section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.',true);\r\n\t}\r\n\t\r\n\tif(dtaaSection.indexOf('B6e_5ADiii') != -1 && arr['B6e_5ADiii'] > 0 && (arrSection1.indexOf('5ADiii') == -1 || arrAmount1['5ADiii'] == 0)) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode','5ADiii section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].sectionCode')[0],'5ADiii section in B6 should be selected and amount should not be zero, as there is an entry in DTAA table.',true);\r\n\t}\r\n\t\r\n\tvar balonSpeciAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balonSpeciAsset')[0];\r\n\tif(dtaaSection.indexOf('B7c') != -1 && arr['B7c'] > 0 && balonSpeciAsset.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balonSpeciAsset','B7c value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(balonSpeciAsset,'B7c value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar balOtherthanSpecAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balOtherthanSpecAsset')[0];\r\n\tif(dtaaSection.indexOf('B7f') != -1 && arr['B7f'] > 0 && balOtherthanSpecAsset.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balOtherthanSpecAsset','B7f value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(balOtherthanSpecAsset,'B7f value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar fullConsiderationB8e = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.fullConsideration')[0];\r\n\tif(dtaaSection.indexOf('B8e') != -1 && arr['B8e'] > 0 && fullConsiderationB8e.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.fullConsideration','B8a value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(fullConsiderationB8e,'B8a value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n\t\r\n\tvar totAmtStcgUnderDtaa = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.stcgUnderDtaa.totAmtStcgUnderDtaa')[0];\r\n\tif(dtaaSection.indexOf('B9') != -1 && arr['B9'] > 0 && totAmtStcgUnderDtaa.value == 0) {\r\n\t\tj.setFieldError('scheduleCGPost45.longTermCapGainPost45.stcgUnderDtaa.totAmtStcgUnderDtaa','B9 value should not be zero as there is an entry in DTAA table.');\r\n\t\taddErrorXHTML(totAmtStcgUnderDtaa,'B9 value should not be zero as there is an entry in DTAA table.',true);\t\r\n\t}\r\n}",
"function dataInput_getVarFieldsJson() {\n var dataJSON = '[';\n var jsonToSent = [];\n var spread = getSpreadJS();\n var writeNan = getWriteNan();\n var firstRowIdx = dataInput_firstRowIndex();\n var fieldsNum = $('#inputs-fields').children().length;\n for (var i = 0; i < fieldsNum; i++) {\n var inputBox = getInputDrop(i);\n /* data-attr's are in div with id \"data-input-field-%N%\" */\n var inputField = getInputField(i);\n if (inputBox) {\n /* value is stored in input */\n var inputBoxValue = inputBox.querySelector('input').value; \n var inputFieldType = inputField.getAttribute(\"data-type\");\n /* if non empty */\n if (inputBoxValue.replace(/\\s/g, \"\") != \"\") { \n var numericRange = (inputFieldType == \"VarRange\");\n var isValid = true;\n if (numericRange)\n var validator = new $.wijmo.wijspread.DefaultDataValidator.createNumberValidator(7, -9999999, -9999999, false);\n if (i != 0)\n dataJSON += ',';\n var minCols = inputField.getAttribute(\"data-mincols\");\n if (!minCols) minCols = 1;\n var minRows = inputField.getAttribute(\"data-minrows\");\n if (!minRows) minRows = 2;\n var isMulti = inputField.getAttribute(\"data-multi\") == \"true\";\n var constsubstitute = inputBox.getAttribute(\"constsubstitute\") == \"true\";\n /* Cell or constsubstitute (text instead of VarRange) */\n //WAS: if (inputField.getAttribute(\"type\") == \"Cell\" || ( constsubstitute && isNumber(inputBoxValue))) {\n if (inputField.getAttribute(\"data-type\") == \"Cell\" || ( constsubstitute && isNumber(inputBoxValue))) {\n dataJSON += '{ \"ValueReference\":\"' + inputBoxValue.replace(\",\", \".\") + '\", \"Cols\":[], \"text\":false, \"multi\":false}';\n jsonToSent.push({\n ValueReference : inputBoxValue.replace(\",\", \".\"),\n Cols : [],\n text : false,\n multi : false\n })\n continue;\n }\n /* else prepare matrix */\n dataJSON += '{ \"ValueReference\" :\"' + inputBoxValue + '\", \"text\":' + !numericRange + ', \"multi\":' + isMulti + ', \"Cols\":[{';\n jsonToSent.push({\n ValueReference : inputBoxValue,\n text : !numericRange,\n multi : isMulti,\n Cols : []\n })\n\n //WAS: var refs = inputBoxValue.split(\";\");\n var refs = inputBoxValue.split(\",\");\n /* \n var refs = checkSavedVal()[i];\n \n\n */\n var groupsIndex = 0;\n var curentColCount = 0;\n for (var j = 0; j < refs.length; j++) {\n console.log(j);\n var refValue = refs[j];//\"Sheet1!A1:A10\";\n if (refValue != \"\" && curentColCount < maxColForAnalysis()) {\n var sheet = spread.getSheetFromName(refValue.split(\"!\")[0]);\n var selection = refValue.split(\"!\")[1].split(\":\");\n var startRowIndex, finishRowIndex, startColIndex, finishColIndex;\n var varIndex = 1;\n if (selection[0].search(/[0-9]{1}/) == -1 && selection[0] == selection[1]) {\n startRowIndex = firstRowIdx;\n finishRowIndex = Math.min(sheet.getRowCount(), maxRowForAnalysis());\n startColIndex = finishColIndex = stringToRange(selection[0] + \"1\", sheet).col;\n curentColCount++;\n }\n else {\n var startCell = stringToRange(selection[0], sheet);\n var finishCell = stringToRange(selection[1], sheet);\n var remainingColCount = maxColForAnalysis - curentColCount;\n startRowIndex = startCell.row + firstRowIdx;\n startColIndex = startCell.col;\n finishRowIndex = Math.min(finishCell.row, maxRowForAnalysis() + startRowIndex);\n finishColIndex = Math.min(finishCell.col, remainingColCount + startColIndex);\n curentColCount += finishColIndex - startColIndex + 1;\n //console.log(startColIndex);console.log(finishColIndex);console.log(startRowIndex);console.log(finishRowIndex);\n if ((finishRowIndex - startRowIndex + 1) < minRows) {\n return { \"isIncorrect\": true, \"data\": \"Invalid number of rows! Please, enter more then \" + minRows + \" rows for \" + $(inputBox).attr(\"fieldtitle\").replace('\\r', '').replace('\\n', '') + \" field\" };\n }\n }\n sheet.isPaintSuspended(true);\n for (var k = startColIndex, arrI = 0; k <= finishColIndex; k++, arrI++) {\n var label;\n if (firstRowIdx > 0) {\n label = sheet.getValue(startRowIndex - 1, startColIndex);\n }\n else {\n label = \"Var\" + varIndex++;\n }\n if (groupsIndex != 0)\n dataJSON += ',{';\n groupsIndex++;\n dataJSON += '\"Label\":\"' + label + '\", \"Cells\":[';\n \n var newArr = []; //ADD\n for (var m = startRowIndex; m <= finishRowIndex; m++) {\n \n if (sheet.getValue(m, k) === null || (\"\" + sheet.getValue(m, k)).replace(/\\s/g, \"\") == \"\") {\n if (writeNan == \"1\") {\n if (m != startRowIndex)\n dataJSON += ',';\n dataJSON += '\"\"';\n }\n continue;\n }\n if (m != startRowIndex)\n dataJSON += ',';\n if (numericRange) {\n sheet.setDataValidator(m, k, validator);\n if (isValid) {\n isValid = (Number(sheet.getValue(m, k)).toString() != \"NaN\");\n }\n }\n dataJSON += '\"' + sheet.getValue(m, k) + '\"';\n newArr.push(sheet.getValue(m, k))\n }\n dataJSON += ']}';\n if(jsonToSent[i]){\n\n jsonToSent[i].Cols.push({\n Label : label,\n Cells : newArr\n });\n }\n\n }\n sheet.isPaintSuspended(false);\n }\n }\n if (curentColCount < minCols) {\n return { \"isIncorrect\": true, \"mes\": \"Invalid number of variables. Please select at least \" + minCols + \" columns for \" + $(inputBox).attr(\"fieldtitle\").replace('\\r', '').replace('\\n', '') + \" field\" };\n }\n dataJSON += ']}';\n }\n else {\n /* input field is empty */\n if (i != 0)\n dataJSON += ',';\n dataJSON += '{ \"ValueReference\":\"' + inputBoxValue.replace(\".\", \",\") + '\", \"Cols\":[], \"text\":\"false\", \"multi\":\"false\"}';\n jsonToSent.push({\n ValueReference : inputBoxValue.replace(\".\", \",\"),\n Cols : [],\n text : false,\n multi : false\n })\n }\n }\n else\n break;\n }\n if (!isValid)\n return null;\n dataJSON += ']';\n // return { \"result\": false, \"data\": dataJSON };\n jsonToSent = {\n result : false,\n data : jsonToSent\n }\n return JSON.stringify(jsonToSent);\n}",
"function\ngseq_iforeach_5155_(a4x1)\n{\nlet xtmp252;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15031(line=1228, offs=1) -- 15162(line=1237, offs=25)\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15075(line=1232, offs=1) -- 15160(line=1236, offs=8)\n// L1DCLnone0();\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14634(line=1194, offs=1) -- 14935(line=1220, offs=8)\nfunction\ngseq_iforall_5108_(a5x1)\n{\nlet xtmp254;\nlet xtmp255;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14677(line=1199, offs=1) -- 14693(line=1199, offs=17)\n{\nxtmp254 = XATS2JS_new_var1(0);\n} // val(i0(137))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14694(line=1200, offs=1) -- 14712(line=1200, offs=19)\n{\n;\n} // val(H0Pvar(p0(138)))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14726(line=1205, offs=1) -- 14868(line=1215, offs=8)\n// L1DCLnone0();\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 7903(line=678, offs=1) -- 7958(line=680, offs=41)\n// { // val-binding\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 3474(line=307, offs=1) -- 3677(line=323, offs=13)\nfunction\nlist_forall_3143_(a7x1)\n{\nlet xtmp275;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 3532(line=312, offs=1) -- 3675(line=322, offs=5)\nfunction\nloop_3535_(a8x1)\n{\nlet a8y1;\nlet xtmp258;\nlet xtmp259;\nlet xtmp260;\nlet xtmp261;\nlet xtmp262;\ndo {\n;\n{\nxtmp259 = 0;\ndo {\ndo {\nif(0!==a8x1[0]) break;\nxtmp259 = 1;\n} while(false);\nif(xtmp259 > 0 ) break;\ndo {\nif(1!==a8x1[0]) break;\n//L1PCKany();\n//L1PCKany();\nxtmp259 = 2;\n} while(false);\nif(xtmp259 > 0 ) break;\n} while(false);\n} // case-patck0\nswitch\n(xtmp259) {\ncase 1:\nxtmp258 = true;\nbreak;\ncase 2:\nxtmp260 = a8x1[1];\nxtmp261 = a8x1[2];\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14726(line=1205, offs=1) -- 14868(line=1215, offs=8)\nfunction\nforall$test_3500_(a9x1)\n{\nlet xtmp264;\nlet xtmp265;\nlet xtmp266;\nlet xtmp267;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14793(line=1211, offs=1) -- 14824(line=1212, offs=23)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/unsafe.dats: 239(line=19, offs=1) -- 292(line=21, offs=35)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\np2tr_get_1962_ = XATS2JS_UN_p2tr_get\n;\nxtmp264 = p2tr_get_1962_(xtmp254);\n}\n;\n;\n} // val(H0Pvar(i0(140)))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14825(line=1213, offs=1) -- 14866(line=1214, offs=33)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/unsafe.dats: 401(line=30, offs=1) -- 454(line=32, offs=35)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\np2tr_set_1998_ = XATS2JS_UN_p2tr_set\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/basics.dats: 2015(line=148, offs=1) -- 2064(line=149, offs=42)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\ngint_succ_sint_1861_ = XATS2JS_gint_succ_sint\n;\nxtmp266 = gint_succ_sint_1861_(xtmp264);\n}\n;\nxtmp265 = p2tr_set_1998_(xtmp254, xtmp266);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(265)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(265)));\n} // val(H0Pnil())\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15075(line=1232, offs=1) -- 15160(line=1236, offs=8)\nfunction\niforall$test_5435_(a10x1, a10x2)\n{\nlet xtmp270;\n;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15114(line=1235, offs=1) -- 15148(line=1235, offs=35)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/array.dats: 2166(line=179, offs=1) -- 2274(line=186, offs=8)\nfunction\niforeach$work_5677_(a11x1, a11x2)\n{\nlet xtmp273;\nlet xtmp274;\n;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/array.dats: 2203(line=182, offs=1) -- 2235(line=183, offs=25)\n{\n{\nxtmp273 = XATS2JS_fcast(a11x1);\n}\n;\n;\n} // val(H0Pvar(i(131)))\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/prelude.dats: 8573(line=539, offs=1) -- 8636(line=541, offs=47)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\na1ptr_set_at_raw_4387_ = XATS2JS_a1ptr_set_at_raw\n;\nxtmp274 = a1ptr_set_at_raw_4387_(xtmp249, xtmp273, a11x2);\n}\n;\nreturn xtmp274;\n} // function // iforeach$work(78)\n;\nxtmp270 = iforeach$work_5677_(a10x1, a10x2);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(270)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(270)));\n} // val(H0Pnil())\n;\nreturn true;\n} // function // iforall$test(82)\n;\nxtmp267 = iforall$test_5435_(xtmp264, a9x1);\n}\n;\nreturn xtmp267;\n} // function // forall$test(84)\n;\nxtmp262 = forall$test_3500_(xtmp260);\n}\n;\nif\n(xtmp262)\n// then\n{\n{\n// tail-recursion:\n// L1CMDapp(tmp(258); L1VALfcst(loop(90)); L1VALtmp(tmp(261)))\na8y1 = xtmp261; a8x1 = a8y1; continue;\n}\n;\n} // if-then\nelse\n{\nxtmp258 = false;\n} // if-else\n;\nbreak;\ndefault: XATS2JS_matcherr0();\n} // case-switch\n;\nbreak;//return\n} while( true );\nreturn xtmp258;\n} // function // loop(90)\n;\n{\nxtmp275 = loop_3535_(a7x1);\n}\n;\nreturn xtmp275;\n} // function // list_forall(89)\n;\n// } // val-binding\nconst // implval/fun\ngseq_forall_1939_ = list_forall_3143_\n;\nxtmp255 = gseq_forall_1939_(a5x1);\n}\n;\nreturn xtmp255;\n} // function // gseq_iforall(83)\n;\nxtmp252 = gseq_iforall_5108_(a4x1);\n}\n;\n;\n} // val(H0Pvar(test(133)))\n;\nreturn null;\n}",
"function\ngseq_iforeach_5155_(a7x1)\n{\nlet xtmp435;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15031(line=1228, offs=1) -- 15162(line=1237, offs=25)\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15075(line=1232, offs=1) -- 15160(line=1236, offs=8)\n// L1DCLnone0();\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14634(line=1194, offs=1) -- 14935(line=1220, offs=8)\nfunction\ngseq_iforall_5108_(a8x1)\n{\nlet xtmp437;\nlet xtmp438;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14677(line=1199, offs=1) -- 14693(line=1199, offs=17)\n{\nxtmp437 = XATS2JS_new_var1(0);\n} // val(i0(198))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14694(line=1200, offs=1) -- 14712(line=1200, offs=19)\n{\n;\n} // val(H0Pvar(p0(199)))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14726(line=1205, offs=1) -- 14868(line=1215, offs=8)\n// L1DCLnone0();\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 7903(line=678, offs=1) -- 7958(line=680, offs=41)\n// { // val-binding\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 3474(line=307, offs=1) -- 3677(line=323, offs=13)\nfunction\nlist_forall_3143_(a10x1)\n{\nlet xtmp460;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 3532(line=312, offs=1) -- 3675(line=322, offs=5)\nfunction\nloop_3535_(a11x1)\n{\nlet a11y1;\nlet xtmp441;\nlet xtmp442;\nlet xtmp443;\nlet xtmp444;\nlet xtmp445;\ndo {\n;\n{\nxtmp442 = 0;\ndo {\ndo {\nif(0!==a11x1[0]) break;\nxtmp442 = 1;\n} while(false);\nif(xtmp442 > 0 ) break;\ndo {\nif(1!==a11x1[0]) break;\n//L1PCKany();\n//L1PCKany();\nxtmp442 = 2;\n} while(false);\nif(xtmp442 > 0 ) break;\n} while(false);\n} // case-patck0\nswitch\n(xtmp442) {\ncase 1:\nxtmp441 = true;\nbreak;\ncase 2:\nxtmp443 = a11x1[1];\nxtmp444 = a11x1[2];\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14726(line=1205, offs=1) -- 14868(line=1215, offs=8)\nfunction\nforall$test_3500_(a12x1)\n{\nlet xtmp447;\nlet xtmp448;\nlet xtmp449;\nlet xtmp450;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14793(line=1211, offs=1) -- 14824(line=1212, offs=23)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/unsafe.dats: 239(line=19, offs=1) -- 292(line=21, offs=35)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\np2tr_get_1962_ = XATS2JS_UN_p2tr_get\n;\nxtmp447 = p2tr_get_1962_(xtmp437);\n}\n;\n;\n} // val(H0Pvar(i0(201)))\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 14825(line=1213, offs=1) -- 14866(line=1214, offs=33)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/unsafe.dats: 401(line=30, offs=1) -- 454(line=32, offs=35)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\np2tr_set_1998_ = XATS2JS_UN_p2tr_set\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/basics.dats: 2015(line=148, offs=1) -- 2064(line=149, offs=42)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\ngint_succ_sint_1861_ = XATS2JS_gint_succ_sint\n;\nxtmp449 = gint_succ_sint_1861_(xtmp447);\n}\n;\nxtmp448 = p2tr_set_1998_(xtmp437, xtmp449);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(448)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(448)));\n} // val(H0Pnil())\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15075(line=1232, offs=1) -- 15160(line=1236, offs=8)\nfunction\niforall$test_5435_(a13x1, a13x2)\n{\nlet xtmp453;\n;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 15114(line=1235, offs=1) -- 15148(line=1235, offs=35)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 2045(line=174, offs=1) -- 2174(line=185, offs=8)\nfunction\niforeach$work_5677_(a14x1, a14x2)\n{\nlet xtmp456;\nlet xtmp457;\nlet xtmp459;\n;\n;\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gseq.dats: 2116(line=181, offs=3) -- 2172(line=184, offs=32)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/basics.dats: 2400(line=174, offs=1) -- 2455(line=175, offs=48)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\ngint_gt_sint_sint_2209_ = XATS2JS_gint_gt_sint_sint\n;\nxtmp457 = gint_gt_sint_sint_2209_(a14x1, 0);\n}\n;\nif\n(xtmp457)\n// then\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/list.dats: 7730(line=665, offs=1) -- 7794(line=668, offs=35)\nfunction\ngseq_print$sep_1446_()\n{\nlet xtmp458;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/g_print.dats: 915(line=80, offs=1) -- 1034(line=89, offs=21)\n// { // val-binding\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/g_print.dats: 977(line=86, offs=1) -- 1032(line=88, offs=31)\n;\n// } // val-binding\nconst // implval/fun\nstring_print_4753_ = XATS2JS_string_print\n;\nxtmp458 = string_print_4753_(\";\");\n}\n;\nreturn xtmp458;\n} // function // gseq_print$sep(104)\n;\nxtmp456 = gseq_print$sep_1446_();\n}\n;\n} // if-then\nelse\n{\n} // if-else\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(456)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(456)));\n} // val(H0Pnil())\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/gint.dats: 1899(line=71, offs=1) -- 1940(line=72, offs=34)\n// { // val-binding\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/g_print.dats: 344(line=33, offs=1) -- 472(line=42, offs=24)\n// { // val-binding\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/g_print.dats: 412(line=39, offs=1) -- 470(line=41, offs=31)\n;\n// } // val-binding\nconst // implval/fun\ngint_print_sint_1513_ = XATS2JS_gint_print_sint\n;\n// } // val-binding\nconst // implval/fun\ng_print_2168_ = gint_print_sint_1513_\n;\nxtmp459 = g_print_2168_(a14x2);\n}\n;\nreturn xtmp459;\n} // function // iforeach$work(103)\n;\nxtmp453 = iforeach$work_5677_(a13x1, a13x2);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(453)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(453)));\n} // val(H0Pnil())\n;\nreturn true;\n} // function // iforall$test(106)\n;\nxtmp450 = iforall$test_5435_(xtmp447, a12x1);\n}\n;\nreturn xtmp450;\n} // function // forall$test(108)\n;\nxtmp445 = forall$test_3500_(xtmp443);\n}\n;\nif\n(xtmp445)\n// then\n{\n{\n// tail-recursion:\n// L1CMDapp(tmp(441); L1VALfcst(loop(114)); L1VALtmp(tmp(444)))\na11y1 = xtmp444; a11x1 = a11y1; continue;\n}\n;\n} // if-then\nelse\n{\nxtmp441 = false;\n} // if-else\n;\nbreak;\ndefault: XATS2JS_matcherr0();\n} // case-switch\n;\nbreak;//return\n} while( true );\nreturn xtmp441;\n} // function // loop(114)\n;\n{\nxtmp460 = loop_3535_(a10x1);\n}\n;\nreturn xtmp460;\n} // function // list_forall(113)\n;\n// } // val-binding\nconst // implval/fun\ngseq_forall_1939_ = list_forall_3143_\n;\nxtmp438 = gseq_forall_1939_(a8x1);\n}\n;\nreturn xtmp438;\n} // function // gseq_iforall(107)\n;\nxtmp435 = gseq_iforall_5108_(a7x1);\n}\n;\n;\n} // val(H0Pvar(test(194)))\n;\nreturn null;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone and add prefixes for atrule | add(rule, prefix) {
let prefixed = prefix + rule.name
let already = rule.parent.some(
i => i.name === prefixed && i.params === rule.params
)
if (already) {
return undefined
}
let cloned = this.clone(rule, { name: prefixed })
return rule.parent.insertBefore(rule, cloned)
} | [
"add(rule, prefix) {\n let prefixeds = this.prefixeds(rule)\n\n if (this.already(rule, prefixeds, prefix)) {\n return\n }\n\n let cloned = this.clone(rule, { selector: prefixeds[this.name][prefix] })\n rule.parent.insertBefore(rule, cloned)\n }",
"rewrite(turtle){\n var localPrefixMap = {};\n turtle.split(/\\n/).forEach((line)=>{\n var result = line.match(/\\@prefix (\\w+):\\s*<(.+?)>\\s*\\./);\n if (result != null){\n localPrefixMap[result[1]] = {namespace:result[2],altPrefix:Object.keys(this.prefixMap).find((key)=>this.prefixMap[key]===result[2])}\n }\n });\n Object.keys(localPrefixMap).forEach((key)=>turtle = turtle.replace(eval(`/${key}\\:/g`),`${localPrefixMap[key].altPrefix}:`))\n //return turtle;\n return turtle\n }",
"prefixeds(rule) {\n if (rule._autoprefixerPrefixeds) {\n if (rule._autoprefixerPrefixeds[this.name]) {\n return rule._autoprefixerPrefixeds\n }\n } else {\n rule._autoprefixerPrefixeds = {}\n }\n\n let prefixeds = {}\n if (rule.selector.includes(',')) {\n let ruleParts = list.comma(rule.selector)\n let toProcess = ruleParts.filter(el => el.includes(this.name))\n\n for (let prefix of this.possible()) {\n prefixeds[prefix] = toProcess\n .map(el => this.replace(el, prefix))\n .join(', ')\n }\n } else {\n for (let prefix of this.possible()) {\n prefixeds[prefix] = this.replace(rule.selector, prefix)\n }\n }\n\n rule._autoprefixerPrefixeds[this.name] = prefixeds\n return rule._autoprefixerPrefixeds\n }",
"function appendToPrefixes(cm, prefix) {\n\tvar lastPrefix = null;\n\tvar lastPrefixLine = 0;\n\tvar numLines = cm.lineCount();\n\tfor (var i = 0; i < numLines; i++) {\n\t\tvar firstToken = getNextNonWsToken(cm, i);\n\t\tif (firstToken != null && (firstToken.string == \"PREFIX\" || firstToken.string == \"BASE\")) {\n\t\t\tlastPrefix = firstToken;\n\t\t\tlastPrefixLine = i;\n\t\t}\n\t}\n\n\tif (lastPrefix == null) {\n\t\tcm.replaceRange(\"PREFIX \" + prefix + \"\\n\", {line: 0, ch:0});\n\t} else {\n\t\tvar previousIndent = getIndentFromLine(cm, lastPrefixLine);\n\t\tcm.replaceRange(\"\\n\" + previousIndent + \"PREFIX \" + prefix, {line: lastPrefixLine});\n\t}\n\t\n}",
"function appendToPrefixes(cm, prefix) {\n\tvar lastPrefix = null;\n\tvar lastPrefixLine = 0;\n\tvar numLines = cm.lineCount();\n\tfor ( var i = 0; i < numLines; i++) {\n\t\tvar firstToken = getNextNonWsToken(cm, i);\n\t\tif (firstToken != null\n\t\t\t\t&& (firstToken.string == \"PREFIX\" || firstToken.string == \"BASE\")) {\n\t\t\tlastPrefix = firstToken;\n\t\t\tlastPrefixLine = i;\n\t\t}\n\t}\n\n\tif (lastPrefix == null) {\n\t\tcm.replaceRange(\"PREFIX \" + prefix + \"\\n\", {\n\t\t\tline : 0,\n\t\t\tch : 0\n\t\t});\n\t} else {\n\t\tvar previousIndent = getIndentFromLine(cm, lastPrefixLine);\n\t\tcm.replaceRange(\"\\n\" + previousIndent + \"PREFIX \" + prefix, {\n\t\t\tline : lastPrefixLine\n\t\t});\n\t}\n\n}",
"updatePrefix() {\r\n\r\n }",
"startWith(prefix) {\n this.addBefore(`^${Rule(prefix).source}`);\n return this;\n }",
"rewrite(turtle){\n let localPrefixMap = {};\n let inverseMap = this.inverseMap();\n turtle.split(/\\n/).forEach((line)=>{\n var result = line.match(/\\@prefix (\\w+):\\s*<(.+?)>\\s*\\./);\n if (result != null){\n localPrefixMap[result[1]] = {namespace:result[2],altPrefix:Object.keys(this.prefixMap).find((key)=>this.prefixMap[key]===result[2])}\n }\n });\n Object.keys(localPrefixMap).forEach((key)=>turtle = turtle.replace(eval(`/${key}\\:/gim`),`${localPrefixMap[key].altPrefix}:`))\n turtle = turtle.replace(/(@prefix .*?\\>\\s*?\\.\\n)/gim,'');\n Object.keys(this.prefixMap).forEach((prefix)=>{\n var nakedURL = new RegExp(`<${this.prefixMap[prefix]}>`,\"g\");\n turtle = turtle.replace(nakedURL,`${prefix}:`);\n });\n turtle = `${this.turtle()}\\n${turtle}`;\n // Convert inline URIs with their corresponding curies\n var re = /<(.+?\\/|#)([A-Za-z0-9_\\-]+?)>/gi;\n turtle = turtle.replace(re,($1,$2,$3)=>`${inverseMap[$2]}:${$3}`);\n return turtle\n }",
"function add_prefix() {\n obj.val(prefix + get());\n }",
"addPrefixes() {\n\t\tif(this.CFG.PROJECT_PREFIXES) {\n\t\t\tq(\"#projectPrefixes\").innerHTML = \"\";\n\t\t\tconst prefixes = this.CFG.PROJECT_PREFIXES.split(\",\") || [];\n\t\t\tprefixes.forEach((v) => {\n\t\t\t\tconst pf = q(\".prefixItemTemplate\").cloneNode(true);\n\t\t\t\tpf.querySelector(\".projectPrefix\").innerText = v.trim();\n\t\t\t\tpf.querySelector(\".projectPrefix\").onclick = function() {\t\t\t\t\n\t\t\t\t\tq(\"#queryText\").value = this.innerText + \"-\";\n\t\t\t\t\tq(\"#queryText\").focus();\n\t\t\t\t}\t\t\t\n\t\t\t\tq(\"#projectPrefixes\").appendChild(pf);\n\t\t\t\tpf.style.display=\"\";\n\t\t\t});\t\t\n\t\t}\n\t}",
"function applyPrefix( style, prop, value ) {\n style[ PREFIX + prop ] = style[ prop ] = value;\n }",
"addPrefix(prefix,namespace){\n this.prefixMap[prefix] = namespace;\n xdmp.documentInsert('/ns/ns.json',this.prefixMap);\n }",
"function buildPrefixedAttributeSetter(prefix) {\n var otherPrefixes = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n otherPrefixes[_i - 1] = arguments[_i];\n }\n var prefixes = __spreadArray([prefix], __read(otherPrefixes), false);\n return function (e, attr, value) {\n setPrefixedAttribute(prefixes, e, attr, value);\n };\n}",
"function createPrefix(datasetURI){\n\tvar prefixes = \"conversion: http://purl.org/twc/vocab/conversion/ \"\n\tprefixes += \": \" + datasetURI + \" \";\n\t\n\treturn prefixes;\n}// /createPrefix",
"addPrefixesFromTurtle(turtle){\n let localPrefixMap = {};\n turtle.split(\"\\r\\n\").forEach((line)=>{\n let result = line.match(/\\@prefix (\\w+):\\s*<(.+?)>\\s*\\./);\n if (result != null){\n localPrefixMap[result[1]] = result[2];\n this.prefixMap[result[1]] = result[2];\n }\n });\n xdmp.documentInsert('/ns/ns.json',this.prefixMap); \n return localPrefixMap\n}",
"addPrefix(prefix, iri, done) {\n var prefixes = {};\n prefixes[prefix] = iri;\n this.addPrefixes(prefixes, done);\n }",
"function add_prefix()\n\t\t\t{\n\t\t\t\tvar val = obj.val();\n\t\t\t\tobj.val(prefix + val);\n\t\t\t}",
"function parsePrefixDefinition(element) {\nvar prefixName = element.attributes.name,\nprefixIri = element.attributes.IRI;\n\nif (prefixName === null || !prefixIri) {\nthrow 'Incorrect format of Prefix element!';\n}\n\nontology.addPrefix(prefixName, prefixIri);\n}",
"old(prop, prefix) {\n return [this.prefixed(prop, prefix)]\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receives a callback that accepts (node, parent graph) and returns a value. This function is invoked recursively per scope (including scope nodes), unless the return value is false, upon which the subscope will not be visited. The function also accepts an optional postsubscope callback (same signature as `func`). | function traverse_sdfg_scopes(sdfg, func, post_subscope_func=null) {
function scopes_recursive(graph, nodes, processed_nodes=null) {
if (processed_nodes === null)
processed_nodes = new Set();
for (let nodeid of nodes) {
let node = graph.node(nodeid);
if (node !== undefined && processed_nodes.has(node.id.toString()))
continue;
// Invoke function
let result = func(node, graph);
// Skip in case of e.g., collapsed nodes
if (result !== false) {
// Traverse scopes recursively (if scope_dict provided)
if (node.type().endsWith('Entry')) {
let state = node.sdfg.nodes[node.parent_id];
if (state.scope_dict[node.id] !== undefined)
scopes_recursive(graph, state.scope_dict[node.id], processed_nodes);
}
// Traverse states or nested SDFGs
if (node.data.graph) {
let state = node.data.state;
if (state !== undefined && state.scope_dict[-1] !== undefined)
scopes_recursive(node.data.graph, state.scope_dict[-1]);
else // No scope_dict, traverse all nodes as a flat hierarchy
scopes_recursive(node.data.graph, node.data.graph.nodes());
}
}
if (post_subscope_func)
post_subscope_func(node, graph);
processed_nodes.add(node.id.toString());
}
}
scopes_recursive(sdfg, sdfg.nodes());
} | [
"function parentFunc() {\n var parentVar = 1;\n function childFunc () { // the inner function is a closure function\n var childVar = 2;\n return parentVar + childVar; // nested childFunc can access parent's variables\n }\n}",
"function parentFunc(money){\n \n var parentsMoney = money\n \n function kidFunc(){\n \n \n \n return parentsMoney = \"my money now!\" //here parentsMoney is a closure because it is borrowing the variable from parent scope\n }\n \n}",
"function walk(node, fn, state) {\n const ancestors = [node];\n const callback = (ctx) => {\n fn(ctx, ancestors, state);\n ancestors.push(ctx);\n ctx.children.forEach(callback);\n ancestors.pop();\n };\n node.children.forEach(callback);\n}",
"function getEnclosingScope(node) {\n while (node.type !== 'FunctionDeclaration' && \n node.type !== 'FunctionExpression' && \n node.type !== 'CatchClause' &&\n node.type !== 'Program') {\n node = node.$parent;\n }\n return node;\n}",
"function traverseASTTree(node, func){\n func(node);\n\t for(var key in node){\n var child = node[key];\n if(typeof child === \"object\" && child !== null){\n if(Array.isArray(child)){\n child.forEach(function(node) {\n traverseASTTree(node, func);\n });\n } else {\n traverseASTTree(child, func);\n }\n }\n\t }\n}",
"function parentFunc(money){\n \n var parentsMoney = money\n \n function kidFunc(){\n \n \n \n return parentsMoney = \"my money now!\" //kidFunc is modifying the variable from parent scope\n }\n \n}",
"function walk(node, fn, state) {\n const ancestors = [node];\n const callback = (ctx) => {\n fn(ctx, ancestors, state);\n ancestors.push(ctx);\n ctx.children.forEach(callback);\n ancestors.pop();\n };\n node.children.forEach(callback);\n }",
"function findScope(tree, key) {\n var q = []\n , scope\n , info\n , node\n\n // Queue node for processing.\n function push(node) {\n q.push({node: node, scope: scope})\n }\n\n push(tree)\n\n while ((info = q.pop())) {\n node = info.node\n scope = info.scope\n\n // Stop processing and return the scope if this is the wanted node.\n if (key(node)) {\n return scope\n }\n\n // Add child nodes to visit from select attributes of this node, if the\n // current node is a block it will be used as the scope for the child\n // nodes otherwise the scope is inherited from the parent.\n\n if (node.type === 'BlockStatement') {\n scope = node\n }\n\n if (node.expression) {\n push(node.expression)\n }\n\n if (node.body) {\n if (node.body.forEach) {\n node.body.forEach(push)\n } else {\n push(node.body)\n }\n }\n\n if (node.callee) {\n node.arguments.forEach(push)\n push(node.callee)\n }\n\n if (node.object) {\n push(node.object)\n }\n }\n}",
"function buildTreeScope(treeCollection, nodes, callback) {\n\tvar allNodes = [];\n\tfindAllParentsMapByNodes(treeCollection, nodes, function(err, allParents,\n\t\t\tallParentsMap) {\n\t\tif (err) {\n\t\t\treturn callback(err);\n\t\t}\n\n\t\tasyncUtils.eachSeries(allParents,\n\t\t// iterator function\n\t\tfunction(parent, eachResultCallback) {\n\t\t\tgetTreeNodesByParents(treeCollection, [ parent ],\n\t\t\t\t\teachResultCallback);\n\t\t},\n\t\t// iterator result callback\n\t\tfunction(treeNodes) {\n\t\t\tallNodes = allNodes.concat(treeNodes);\n\t\t},\n\t\t// finish iterator result\n\t\tfunction(err) {\n\t\t\tif (err) {\n\t\t\t\treturn callback(err);\n\t\t\t}\n\n\t\t\treturn callback(null, allNodes);\n\t\t});\n\n\t});\n}",
"function recursive(node, state, funcs, baseVisitor, override) {\n var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor;(function c(node, st, override) {\n visitor[override || node.type](node, st, c);\n })(node, state, override);\n}",
"function parentFunc2() {\n var parentVar = 1;\n // console.log(childVar); // Reference Error: childVar is not defined\n function childFunc () {\n var childVar = 2;\n return parentVar + childVar; // 3\n }\n}",
"function traceBackNodes(currNode, nodeFunc, edgeFunc){\n nodeFunc(currNode);\n if (currNode!=0){\n var parentId = nodes.get(currNode)['parent'];\n if(parentId!=0)edgeFunc(parentId, currNode);\n traceBackNodes(parentId, nodeFunc, edgeFunc);\n }\n}",
"function reduceAncestors(person, func, default_value){\n //inner function, that can be called recursively\n //in order to traverse the ancestry tree upwards\n function computeValueFor(person){\n if(person == null){\n return default_value;\n }\n else{\n //make a recursive call to compute ancestral values...\n return func(person, computeValueFor(byName[person.mother]), computeValueFor(byName[person.father]));\n }\n }\n return computeValueFor(person);\n }",
"traverseDepthFirst(callback) {\n\n }",
"function recursive(node, state, funcs, baseVisitor, override) {\n var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor\n ;(function c(node, st, override) {\n visitor[override || node.type](node, st, c);\n })(node, state, override);\n}",
"function task_traverse(root, functor, depth) {\n if (root.isTask()) { \n depth++;\n for (var i = 0; i <root.getNumSubs(); i++) {\n var sub = root.getSubConfig(i);\n if (functor(sub, depth, i)) {\n task_traverse(sub, functor, depth, 0)\n }\n }\n } \n}",
"function recurse(tree) {\n callback.call(tree, tree.value)\n\n if (tree.left !== undefined) {\n recurse(tree.left)\n }\n\n if (tree.right !== undefined) {\n recurse(tree.right);\n }\n }",
"traverseChildren(crossScope, func) {\n if (crossScope) {\n return super.traverseChildren(crossScope, func);\n }\n }",
"function walk(node, func, depth, rootNode, parentingElement) {\n func(node, depth, parentingElement, rootNode);\n if (node.uid) { parentingElement = node; }\n node = node.firstChild;\n while (node) {\n walk(node, func, depth + 1, rootNode, parentingElement);\n node = node.nextSibling;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks that date and time supplied had not past returns true if the date is valid the date and time are in the future and false if the date and time are in the past //in order to allow to put in todays date as well added the time of the end of the day to the date supplied (if time was not supplied) | function checkDate(date, time) {
let inputDate = new Date(date);
if (time) {
let hours = time.slice(0, 2);
let minutes = time.slice(3, 5);
inputDate.setHours(hours);
inputDate.setMinutes(minutes);
inputDate.setSeconds(99);
}
else {
inputDate.setHours(23);
inputDate.setMinutes(59);
inputDate.setSeconds(99);
}
//gets current date and time to compare against
let today = new Date();
if (inputDate < today) {
return false;
}
return true;
} | [
"function isAppointmentInTheFuture(date, time){\n date.setHours(Number(time.split(\"-\")[1].split(\":\")[0]));\n date.setMinutes(Number(time.split(\"-\")[1].split(\":\")[1]));\n return new Date() < date;\n}",
"function checkFutureTime(inTime){\n\tcheckTime(inTime);\n\tvar today = new Date();\n\tvar currentHours = today.getHours();\n\tvar currentMinutes = today.getMinutes();\n\tvar inTimeValue = inTime.value;\n\tvar inTimeHours = inTimeValue.substring(0,2);\n\tvar inTimeMinutes = inTimeValue.substring(3);\n\tif (inTimeHours > currentHours || (inTimeHours == currentHours && inTimeMinutes > currentMinutes)){\n\t\talert(commonFutureTimeErrMsg);\n\t\tinTime.value = \"\";\n\t\tsetTimeout(function(){inTime.focus();},10);\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}",
"function isValidDate() {\n var isValid = false;\n var runAtTime = jQuery('#runAtTime').val()\n\n if (runAtTime !== undefined && runAtTime !== '') {\n // Get the last date which was set\n var $picker = jQuery('#datetimepicker');\n var startTime = $picker.data('DateTimePicker').date();\n\n if (startTime !== null && startTime.isAfter(moment())) {\n isValid = true;\n }\n }\n\n return isValid;\n}",
"function isfutureDate(value) {\n\tvar now = new Date();\n\tvar target = new Date(value);\n\n\tif (target.getFullYear() > now.getFullYear()) {\n\t\treturn true;\n\t} \n\telse if (target.getFullYear() == now.getFullYear()) {\n\t\tif (target.getMonth() > now.getMonth()) {\n\t\t\treturn true;\n\t\t} \n\t\telse if (target.getMonth() == now.getMonth()) {\n\t\t\tif (target.getDate() > now.getDate()) {\n\t\t\t\treturn true;\n\t\t\t} \n\t\t\telse if(target.getDate() == now.getDate()) {\n\t\t\t\t// current time less than market open time then return true\n\t\t\t\tvar time = now.getHours();\n\t\t\t\tif(time <= 9) {\n\t\t\t\t\treturn true;\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\treturn false;\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\treturn false;\n\t}\n}",
"function checkDate(){\n\t\treqDate = document.getElementsByName('reqsDate')[0].valueAsDate\n\t\treqDate = reqDate.setDate(reqDate.getDate()-2)\n\t\tif(reqDate < new Date().getTime()){\n\t\t\talert(\"The test drive request time must later than today\");\n\t\t\tsetTimeToNow();\n\t\t}\n\t}",
"function isPastTime(tt) {\n var today = moment().local();\n var chkTime = moment(tt, \"HH:mm\");\n\n if (today.date() == chkTime.date()) {\n if (today.hour() > chkTime.hour()) {\n chkTime.add(1, 'days');\n }\n }\n if (today.local() > chkTime) {\n return true;\n } else {\n return false;\n }\n}",
"function validTimeInput(){\n var futureVal, afterStartVal, afterStartTimeVal, formatVal;\n\n //checj if future dates\n if($scope.checkIfFutureDate($scope.startDatepicker.date) || $scope.checkIfFutureDate($scope.endDatepicker.date)) futureVal=false;\n else futureVal=true;\n\n //check if startDate is past endDate\n if($scope.afterStartDate()) afterStartVal=false;\n else afterStartVal=true;\n\n ////check if startTime is past endTime\n if($scope.afterStartTime()) afterStartTimeVal=false;\n else afterStartTimeVal=true;\n\n //Invalid input\n if($scope.validDate($scope.startDatepicker.date) || $scope.validDate($scope.endDatepicker.date)) formatVal=false;\n else formatVal=true;\n\n\n //final test\n if (futureVal === true &&\n afterStartVal === true &&\n afterStartTimeVal === true &&\n formatVal === true ) UrlService.setTimeValidService(true);\n else{\n UrlService.setTimeValidService(false);\n }\n }",
"function dateCheck() {\n let input = getInputByID(\"#start-date\");\n let value = new Date(input.value + \"T12:00:00\");\n\n if (isEmpty(input)) {\n removeMsg(input, \"Start date begins tomorrow\", \"error\");\n markEmpty(input);\n }\n else if (value < dateCurrent) {\n notification(input, \"Start date begins tomorrow\", \"error\");\n }\n else {\n removeMsg(input, \"Start date begins tomorrow\", \"error\");\n validEntry(getFormEntry(input));\n }\n}",
"function checkEndDate(end_date_time,currt)\n{\n\tvar en=end_date_time.value;\n\tvar end_arr = en.split(\" \");\n\tvar enddate = end_arr[0];\n\tvar endtime = end_arr[1];\n\tvar end_date_split = enddate.split(\"-\");\n\tvar end_time_split = endtime.split(\":\");\n\tvar end_year = end_date_split[0];\n\tvar end_month = end_date_split[1] - 1;\n\tvar end_date = end_date_split[2];\n\tvar end_hour = end_time_split[0];\n\tvar end_min = end_time_split[1];\n\tvar end_sec = end_time_split[2];\n\n\tvar currt_arr = currt.split(\" \");\n\tvar currtdate = currt_arr[0];\n\tvar currttime = currt_arr[1];\n\tvar currt_date_split = currtdate.split(\"-\");\n\tvar currt_time_split = currttime.split(\":\");\n\tvar currt_year = currt_date_split[0];\n\tvar currt_month = currt_date_split[1] - 1;\n\tvar currt_date = currt_date_split[2];\n\tvar currt_hour = currt_time_split[0];\n\tvar currt_min = currt_time_split[1];\n\tvar currt_sec = currt_time_split[2];\n\n\tvar e=new Date(end_year,end_month,end_date,end_hour,end_min,end_sec);\n\tvar c=new Date(currt_year,currt_month,currt_date,currt_hour,currt_min,currt_sec);\n\tif(c > e)\n\t{\n\t\talert(\"End date & time should be greater than current date & time \");\n\t\tend_date_time.focus();\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function reservationNotInTheFuture(reservation_date, reservation_time) {\n const reservationDateTimestamp = Date.parse(\n `${reservation_date} ${reservation_time} PST`\n );\n return reservationDateTimestamp < Date.now();\n}",
"function futureDate(date) {\r\n return ( new Date(date) > new Date() ) ? true : false ;\r\n}",
"function checkValidTime() {\n let dateRef = document.getElementById(\"date\");\n let date = dateRef.value;\n // Convert user entered date to Date object\n let selectedDate = new Date(date);\n let todayDate = new Date();\n let timeRef = document.getElementById(\"time\");\n let time = timeRef.value;\n // Obtain specific hour entered\n let hour = Number(time.substring(0,2));\n // Obtain specific minute entered\n let minute = Number(time.substring(3));\n // Set specific time for user entered date\n selectedDate.setHours(hour);\n selectedDate.setMinutes(minute);\n\n // Check to see if user has entered a date first (time cannot be validiated\n // unless a date has been specified by the user)\n if (date === \"\") {\n // alert user if date is not entered\n let output = `Please enter date first.`;\n alert(output);\n timeRef.value = \"\";\n }\n // Compare if time of selectedTime is < current time\n if (selectedDate.getTime() <= todayDate.getTime()) {\n // alert user if time has passed\n let output = `Cannot book flight for current time or time that has passed.\n \\n\\nPlease enter a valid time.`;\n alert(output);\n }\n}",
"function validation(text, date, time) {\n const currentDate = new Date()\n const parsedDate = date.split(\"-\")\n const currentHour = currentDate.getHours();\n const currentMinutes = currentDate.getMinutes();\n const currentDateStruct = {\n year: parseInt(currentDate.getFullYear()),\n month: parseInt(currentDate.getMonth() + 1),\n day: parseInt(currentDate.getDate())\n }\n const inputDateStruct = {\n year: parseInt(parsedDate[0]),\n month: parseInt(parsedDate[1]),\n day: parseInt(parsedDate[2])\n }\n if (date === \"\") {\n alert(\"date cannot be empty\\nif you want to add note you must choose date\")\n return false;\n }\n if (inputDateStruct.year < currentDateStruct.year) {\n alert(\"Time cannot be in past\")\n return false;\n } else if (inputDateStruct.year === currentDateStruct.year) {\n if (inputDateStruct.month < currentDateStruct.month) {\n alert(\"month cannot be in past\")\n return false;\n } else if (inputDateStruct.month === currentDateStruct.month) {\n if (inputDateStruct.day < currentDateStruct.day) {\n alert(\"day cannot be in past\")\n return false;\n }\n }\n }\n if (text === \"\") {\n alert(\"text cannot be empty\\nPlease enter some text in the text box\")\n return false;\n }\n\n const [hour, minutes] = time.split(\":\");\n const [intHour, intMinutes] = [parseInt(hour), parseInt(minutes)];\n if (time === \"\") {\n\n } else {\n\n if (currentHour > intHour) {\n alert(`invalid hour\\nhour cannot be in past\\n${text}`)\n return false;\n } else if (currentHour == intHour) {\n if (currentMinutes > intMinutes) {\n alert(\"invalid minute \\nminute cannot be in past\")\n return false;\n }\n }\n }\n console.log(\"Validation succeeded \")\n return true;\n}",
"function validTime() {\r\n // todo: write logic\r\n curTime = moment().tz('America/Los_Angeles')\r\n hourOfDay = parseInt(curTime.format('HH'))\r\n startHour = 19\r\n if (curTime.days() == 6 || curTime.days() == 7) {\r\n startHour = 15\r\n }\r\n return !(hourOfDay>=12 && hourOfDay<startHour)\r\n}",
"function isValidInput3 () {\n const today = new Date();\n const dueDate = new Date(input3.value);\n\n// Due date is the same as today's date\n if (\n today.getFullYear() === dueDate.getFullYear() &&\n today.getMonth() === dueDate.getMonth() &&\n today.getDate() === dueDate.getDate()\n ){\n console.log('date is today');\n input3.classList.add('is-valid');\n input3.classList.remove('is-invalid');\n }\n// Due date is in future\n else if (dueDate.getTime() > today.getTime()) {\n console.log('due date is in the future');\n input3.classList.add('is-valid');\n input3.classList.remove('is-invalid');\n\n// Due date is in past\n } else {\n console.log('due date is in the past');\n input3.classList.add('is-invalid');\n input3.classList.remove('is-valid');\n }\n }",
"function isAfterNow(time) {\n //empty time is considered future time\n if (!time || !time.format) {\n return false;\n }\n\n //remove timezone info before compare\n if (time) {\n var time = time.format(\"YYYY-MM-DD HH:mm:ss\");\n var currentTime = now().format(\"YYYY-MM-DD HH:mm:ss\");\n return moment(currentTime).isAfter(time);\n }\n }",
"function checkTime() {\n var numberToDay = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\n // create a time\n var d = new Date();\n var today = d.getDay();\n var hms = ('0' + d.getHours()).slice(-2)+\":\"+('0' + d.getMinutes()).slice(-2); // 0 + ... slice(-2) ensures leading zero\n // iterate through the array for today and return true if current time is in range of condition test\n if( timeDb[numberToDay[today]].some(function(t){ return hms >= t.start && hms <= t.end; }) ) {\n ajax_post(ajaxVars); // returned true\n } \n else {\n document.getElementById(\"status\").innerHTML = \"Data not scheduled to be posted to the server yet\"; // returned false\n }\n}",
"function TimeAfterCurrent(date,time){\n \n\ttry{\n\n\t\tvar dateNow = DateToday(); // date today\n\t\tvar today = new Date();\n\t\tvar timeNow = today.getHours() + ':' + today.getMinutes(); // time now\n\t\t\n\t\tdateNow = new Date(dateNow.split('.')[2] + '-' + dateNow.split('.')[1] + '-' + dateNow.split('.')[0] + ' ' + timeNow + ':00');\n\t\t\n\t\treturn dateNow < new Date(date.split('.')[2] + '-' + date.split('.')[1] + '-' + date.split('.')[0] + ' ' + time+ ':00')\n\t}\n\tcatch(err){\n\t\treturn false;\n\t}\n}",
"function ifInFuture(someTime) {\r\n const currentTime = new Date().getTime();\r\n\r\n const givenHours = someTime.split(\":\")[0];\r\n const givenMinutes = someTime.split(\":\")[1];\r\n const givenTime = new Date().setHours(givenHours, givenMinutes, 0, 0)\r\n\r\n if (givenTime>currentTime) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all members to a zero(0) score. Returns a list off all members nulled. To remove all members, see empty. | function zero() {
return client
.zrevrangeAsync([board, 0, -1])
.then(function(list) {
var multi = client.multi();
// When we have a list of all members set their scores
// to zero(0) and return the list of members
//
list.forEach(function(mem) {
multi.zadd(board, 0, mem);
})
return multi
.execAsync()
.then(function() {
return Promise.resolve(list);
});
});
} | [
"function SetNullScoresToZero(){\n for(let key in Scores){\n let score = GetScoreByName(key);\n if(score === null || score === undefined){\n SetScoreByName(key, 0);\n }\n }\n}",
"function clearAbilityScores() {\n for (item of abilitiesArray) {\n item.score = 0;\n item.mod = 0;\n }\n}",
"setZero() {\n const e = this.elements;\n e[0] = 0;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = 0;\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n }",
"setZero() {\n const e = this.elements\n e[0] = 0\n e[1] = 0\n e[2] = 0\n e[3] = 0\n e[4] = 0\n e[5] = 0\n e[6] = 0\n e[7] = 0\n e[8] = 0\n }",
"function clearScore() {\n players.map(player => player.winningRounds = 0);\n $('[data-score-marker-player]').html('0');\n}",
"function emptyStats() {\n return [ 0, \"\", \"\", 0, 0, 0, 0, 0 ];\n}",
"cull() {\n this.members = this.members.slice(0, this.populationSize);\n }",
"function clearScores() {\n playerScore = 0;\n computerScore = 0;\n}",
"function zeroArray(arr) {\n\tarr.forEach(function(v) {\n\t\tv = 0;\n\t});\n}",
"function setZeroScore() {\n playerScore = 0;\n computerScore = 0;\n drawScore = 0;\n}",
"static getEmptyScore(scoreDefaults) {\n const score = new SmoScore(scoreDefaults);\n score.addStaff();\n return score;\n }",
"function zero_aus(to_zero, t) {\n for (a in to_zero) {\n au(to_zero[a], 0)\n }\n move_face(t)\n}",
"function clearScore() {\n score = 0;\n }",
"_reset() {\n this.scores = {}\n Object.keys(this.lobby.players).forEach( p => {\n this.scores[p] = 0\n })\n }",
"function resetScore() {\n scoreValues = _getEmptyScore();\n _saveScoreValues();\n }",
"function resetAll() {\n for (var i = 0; i < users.length; i++) {\n users[i].infected = false;\n }\n tick();\n }",
"static getEmptyScore(scoreDefaults) {\n const score = new SmoScore(scoreDefaults);\n score.addStaff(systemStaff_1.SmoSystemStaff.defaults);\n return score;\n }",
"empty() {\n var emptySquares = []\n for (let i=0; i<this.squares.length; i++) {\n if (!this.squares[i]) emptySquares.push(i);\n }\n return emptySquares;\n }",
"reset() {\n for (let i = 0, l = this.matrix.length; i !== l; i++) {\n this.matrix[i] = 0\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to handle audio end event | function sound_ended() {
if (context !== null) {
sound_end_time = context.currentTime * 1000;
} else {
sound_end_time = Date.now();
}
if (trial.ignore_responses_during_audio) {
$(':button').prop('disabled',false);
}
if (trial.trial_ends_after_audio) {
end_trial();
}
} | [
"on_audio_end(evt){\n\n\t}",
"onAudioEnd() {\n if (this.loop) {\n this.play();\n }\n else {\n this._listenerPool.invoke('onTrackEnd', { track: this });\n }\n }",
"function handleEndAudio(mediaElement) {\r\n\t\t_playsStatus = \"notplaying\";\r\n\t\tshowPlay();\r\n\t}",
"onAudioEnd(e) {\n //Determine if the user has stopped the AudioBufferSourceNode rather than the source simply ending.\n const userStopped = (e && e.currentTarget && e.currentTarget._userStopped) || false;\n if (this._playingState === AUDIO_STATES.PLAYING && !userStopped && !this.loop) {\n this._playingState = AUDIO_STATES.STOPPED;\n this.audioListenerDelegate && this.audioListenerDelegate.onAudioEnd && this.audioListenerDelegate.onAudioEnd();\n }\n }",
"function audioEnded()\n {\n stopAudioTimeout();\n\n _Playing.off();\n _Playing = null;\n playNextEntry();\n }",
"function endGameAudio() {\n audioEnd.play();\n}",
"endedListener() {\n this._audio.addEventListener('ended', () => {\n this.nextTrack();\n return;\n })\n }",
"_onSongDone() {\n this.log.info(\"AudioOut._onSongDone()\");\n this.stop();\n }",
"end() {\n if (this._closed) {\n log.error(`Speaker already closed`);\n return;\n }\n\n if ((this._totalBufferLen % this._frameSize) !== 0) {\n this._done(\n new Error(`Buffer not a multiple of frame size of ${this._frameSize}`)\n );\n return;\n }\n\n const numFrames = this._totalBufferLen / this._frameSize;\n if (numFrames <= 0) {\n log.warn(`Trying to play an empty file?`);\n this._done(null);\n return;\n }\n if (!this._speaker.setNotificationMarkerPosition(numFrames)) {\n this._done(new Error(`Failed to set marker for eos`));\n return;\n }\n\n this._speaker.setPlaybackPositionUpdateListener((err) => {\n // Done playback\n this._done(err);\n });\n }",
"function audioCompleted() {\n\tendPresentation();\n}",
"async handleEndRecording() {\n // Capture audio into variable\n let audio;\n\n try {\n audio = await this.audioRecorder.stopRecording();\n } catch (e) {\n dispatchErrorToast(\n this,\n `Could not record successfully; ${e.name}: ${e.message}`\n );\n }\n\n // Do auto qc checks\n const qualityCheck = new QualityControl(this.context, audio.blob);\n const qualityResult = await qualityCheck.isQualitySound();\n if (!qualityResult.success) {\n this.qcError = qualityResult.errorMessage;\n this.dispatchCollectionState(CollectionStates.QC_ERROR);\n return;\n }\n\n this.finishedAudio = audio;\n this.dispatchAudioUrl(this.finishedAudio.recordingUrl);\n\n // Checks finished; transition to before_upload state\n this.dispatchCollectionState(CollectionStates.BEFORE_UPLOAD);\n }",
"function audioEventListener(){\n\tvar oAudio = document.getElementById('myPod');\n\toAudio.addEventListener('ended', endAudio);\t\n}",
"function onSoundEnd() {\n\n // look in the play vector to see which beat we need to play next\n sndIndex = sndIndex + 1;\n\n var toplay = playvector[sndIndex].beat + 1;\n\n // play that beat and reset the play timer\n id = sound.play(String(toplay));\n\n timerPlaybackID = setTimeout(onSoundEnd, beatmap[toplay - 1].duration);\n\n}",
"endStream() {\n if (this.audioDispatcher) {\n this.audioDispatcher.destroy();\n this.audioDispatcher = null;\n }\n }",
"function endAnimation() {\n let endAnimationText = getEndAnimation();\n endAnimationText.innerHTML = \"Finished!\";\n endAnimationText.style.fontSize = \"50px\";\n const finishedSound = audioFiles.finishedSound;\n if(audioOn && inhaleHold > 0) {\n finishedSound.load();\n finishedSound.play();\n }\n endEarlyDetails();\n}",
"onStop() {\n this.mediaRecorder.addEventListener(\"stop\", e => {\n const audioBlob = new Blob(this.audioChunks);\n\n const audioUrl = URL.createObjectURL(audioBlob);\n\n let onRecordEvent = this.inputs.getEvent('record');\n\n this.recordingSource = audioUrl;\n\n if (onRecordEvent) {\n let audioOptions = {\n blob: audioBlob,\n url: audioUrl,\n duration: this.recorderDuration,\n };\n onRecordEvent(audioOptions);\n }\n });\n }",
"onEnded() {\n if (!this._isPaused) {\n this._seekPosition = this._start;\n }\n this._isPlaying = false;\n this.disposeBufferSourceNode();\n this.trigger('ended');\n }",
"function onAudioProgressEvent(){\r\n\t\t\taudioObject.removeEventListener(\"ended\", onAudioProgressEvent);\r\n\t\t\tif(increment<$scope.audioArray.length-1){\r\n\t\t\t\taudioLoadingCompleted();\r\n\r\n\t\t\t}else{\r\n\t\t\t\tsharedService.broadcastItem('triggerAudioPlayer');\r\n\t\t\t\tsharedService.broadcastItem('audioCompleted')\r\n\t\t\t\tsharedService.isPlaying=false;\r\n\t\t\t}\r\n\r\n\t\t}",
"function handleMediaEnd(app) {\n playMedia(app, findSong(), true);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates and returns adapteraware SMART api. Not that while the shape of the returned object is well known, the arguments to this function are not. Those who override this method are free to require any environmentspecific arguments. For example in node we will need a request, a response and optionally a storage or storage factory function. | getSmartApi() {
return {
ready: (...args) => (0, smart_1.ready)(this, ...args),
authorize: options => (0, smart_1.authorize)(this, options),
init: options => (0, smart_1.init)(this, options),
client: state => new Client_1.default(this, state),
options: this.options,
utils: {
security
}
};
} | [
"getSmartApi() {\n return {\n ready: (...args) => smart_1.ready(this, ...args),\n authorize: options => smart_1.authorize(this, options),\n init: options => smart_1.init(this, options),\n client: state => new Client_1.default(this, state),\n options: this.options\n };\n }",
"generateGetApexWireAdapter(namespace,classname,method,isContinuation){const wireAdapter=generateWireAdapter((config,metaConfig)=>{return this._serviceGetApex(namespace,classname,method,isContinuation,config,metaConfig);});return wireAdapter;}",
"function Api() {}",
"function factory(opts){\n opts = opts || {}\n\n if(typeof(opts.model) != 'string') throw new Error('storage proxy needs opts.model==string')\n\n function getURL(path, query){\n query = query ? '?' + querystring.stringify(query) : ''\n path = path || ''\n return tools.storageUrl('/api/v1/' + opts.model + path + query)\n }\n\n function resHandler(done){\n return function(err, resp){\n if(err) return done(err)\n if(resp.statusCode >= 400){\n return done(JSON.stringify(resp.body))\n }\n done(null, resp.body)\n }\n }\n \n return {\n loadModels:function(query, done){\n bhttp.get(getURL('', query), {\n decodeJSON:true\n }, resHandler(done))\n },\n loadModel:function(id, done){\n bhttp.get(getURL('/' + id), {\n decodeJSON:true\n }, resHandler(done))\n },\n addModel:function(data, done){\n bhttp.post(getURL(), data, {\n encodeJSON:true,\n decodeJSON:true\n }, resHandler(done))\n },\n saveModel:function(id, data, done){\n bhttp.patch(getURL('/' + id), data, {\n encodeJSON:true,\n decodeJSON:true\n }, resHandler(done))\n },\n deleteModel:function(id, done){\n bhttp.delete(getURL('/' + id), {\n \n }, resHandler(done))\n }\n }\n}",
"static create() {\n switch (adapterConfig) {\n case ADAPTER.MS: // MSAdapter\n return new MSAdapter();\n case ADAPTER.MOCK: // MSAdapter\n return new MOCKAdapter();\n default:\n throw new Error(`cannot create ${adapterConfig} adapter, please check.`);\n }\n }",
"createAPI(data) {\n return null;\n }",
"function API(opts) {\n if (! (this instanceof API)) {\n return new API(opts);\n }\n\n // use joi to assert types\n this.types = Joi;\n\n // create the router\n this.router = bee.route();\n\n // initialise the model definitions\n this.models = {};\n\n // initialise the store\n this.store = store(opts);\n}",
"_createRequestObj(resource = '', options) {\n return new Request(resource, options);\n }",
"generateGetApexWireAdapter(namespace,classname,method){const wireAdapter=generateWireAdapter(this._serviceGetApex.bind(this,namespace,classname,method));return wireAdapter;}",
"function HttpAdapter()\n{\n var _this = this;\n this.getHttpOptions = function(path, method, additionalOptions) {\n var urlParts = url.parse(globalOptions.getApiUrl());\n\n var httpOptions = {\n \"url\" : globalOptions.getApiUrl() + path,\n \"hostname\": urlParts.hostname,\n \"port\": urlParts.port,\n \"path\": path,\n \"method\" : method\n };\n\n if (_this.isHttps() && globalOptions.isAllowSelfSignedCertificates()) {\n httpOptions['rejectUnauthorized'] = false;\n }\n\n httpOptions = this.extendByAdditionalOptions(httpOptions, additionalOptions);\n\n return httpOptions;\n };\n \n this.extendJsonParameters = function(httpOptions) {\n if (!('headers' in httpOptions)) {\n httpOptions['headers'] = {};\n }\n\n httpOptions['headers']['Content-Type'] = 'application/json; charset=utf-8';\n\n return httpOptions;\n };\n \n this.extendByAdditionalOptions = function(httpOptions, additionalOptions) {\n var authorizationToken = additionalOptions.authorizationToken || undefined;\n var contentType = additionalOptions.contentType || undefined;\n\n if (!('headers' in httpOptions)) {\n httpOptions['headers'] = {};\n }\n\n // append Basic authorization token if given\n if (undefined !== authorizationToken) {\n httpOptions['headers']['Authorization'] = 'Basic ' + authorizationToken;\n }\n\n // append Content type if given\n if (undefined !== contentType) {\n httpOptions['headers']['Content-Type'] = contentType;\n }\n\n return httpOptions;\n };\n \n this.handleNoApiConnectionError = function(req, onErrorCallback) {\n req.on('error', function(error) {\n errorHandler.newMessageAndLogError(onErrorCallback, messages.no_api_connection, \"Could not connect to API.\");\n });\n };\n}",
"prepareApi(){\n Api = new Api(App, this.server);\n App.Api = Api;\n }",
"generateGetRecordWireAdapter(){const wireAdapter=generateWireAdapter(this.serviceGetRecord.bind(this));return wireAdapter;}",
"function AdapterService() {\n ObjectStorageService.call(this);\n this.REQUIRED_FUNCTIONS.push('find');\n this.OPTIONAL_FUNCTIONS.push('count');\n this.OPTIONAL_FUNCTIONS.push('info');\n }",
"setupAPI() {\n const api = new API({\n token: getAccessToken()\n });\n return api;\n }",
"function AdapterFactory() {\n }",
"api() {\n return {\n /**\n * Fetches a resource from the network. Returns a Promise which resolves once\n * the response is available.\n */\n fetch: async (url, options) => this.fetch(url, options),\n\n Body,\n Headers,\n Request,\n Response,\n AbortController,\n AbortSignal,\n FormData,\n\n // extensions\n\n FetchBaseError,\n FetchError,\n AbortError,\n\n /**\n * This function returns an object which looks like the public API,\n * i.e. it will have the functions `fetch`, `context`, `reset`, etc. and provide its\n * own isolated caches and specific behavior according to `options`.\n *\n * @param {Object} options\n */\n context: (options = {}) => new FetchContext(options).api(),\n\n /**\n * Resets the current context, i.e. disconnects all open/pending sessions, clears caches etc..\n */\n reset: async () => this.context.reset(),\n\n ALPN_HTTP2: this.context.ALPN_HTTP2,\n ALPN_HTTP2C: this.context.ALPN_HTTP2C,\n ALPN_HTTP1_1: this.context.ALPN_HTTP1_1,\n ALPN_HTTP1_0: this.context.ALPN_HTTP1_0,\n };\n }",
"static get(name, id, opts) {\n return new ApiManagementService(name, undefined, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"function ApiDataAdapter() {\n \"use strict\";\n\n DataAdapter.call(this);\n}",
"static get(name, id, state, opts) {\n return new RestApi(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a l0r0 (That's how Menus align to their owning MenuItem) slign spec. | function parseAlign(alignSpec) {
const parts = alignSpecRe.exec(alignSpec),
myOffset = parseInt(parts[2] || 50),
targetOffset = parseInt(parts[4] || 50);
// Comments assume the Menu's alignSpec of l0-r0 is used.
return {
myAlignmentPoint: parts[1] + myOffset, // l0
myEdge: parts[1], // l
myOffset, // 0
targetAlignmentPoint: parts[3] + targetOffset, // r0
targetEdge: parts[3], // r
targetOffset, // 0
startZone: edgeIndices[parts[3]] // 1 - start trying zone 1 in TRBL order
};
} | [
"function parseAlign(alignSpec) {\n const parts = alignSpecRe.exec(alignSpec),\n myOffset = parseInt(parts[2] || 50),\n targetOffset = parseInt(parts[4] || 50); // Comments assume the Menu's alignSpec of l0-r0 is used.\n\n return {\n myAlignmentPoint: parts[1] + myOffset,\n // l0\n myEdge: parts[1],\n // l\n myOffset,\n // 0\n targetAlignmentPoint: parts[3] + targetOffset,\n // r0\n targetEdge: parts[3],\n // r\n targetOffset,\n // 0\n startZone: edgeIndices[parts[3]] // 1 - start trying zone 1 in TRBL order\n\n };\n} // Takes a result from the above function and flips edges for the axisLock config",
"function SpatialLevelSpecificationParser() {\n\tthis.constCharacterNewLine = \"\\n\";\n\tthis.constCharacterCarriageReturn = \"\\r\";\n\tthis.constCharacterSpace = \" \";\n\t\n\tthis.constLevelDataStartSequenceStr = \"@@@:::@@@\";\n\t\n\t// Array used as a look-up table to convert parsed\n\t// symbols within the source data to a numeric\n\t// index.\n\tthis.tileSymbolToNumericIdDictionary = {};\n\t\n\t// Collection of tile attributes, keyed by\n\t// the assigned numeric index.\n\tthis.tileSymbolAttributeCollection = [];\n\t\n\t// Will contain a collection of tile rows upon successful\n\t// parsing. Each tile within a row is represented by a\n\t// numeric specifier. All tiles are assumed to have\n\t// equivalent dimensions.\n\tthis.levelTileRowCollection = [];\n\t\n\tthis.initializeTileSymbolToNumericIdDict();\n}",
"function parseNavFromText(s) {\n let mapNav = s.match(/#[a-z_]+/);\n if (mapNav != null) {\n mapNav = mapNav[0].substr(1);\n if (!(mapNav in available_maps)) mapNav = null;\n }\n else return null;\n let pinNav = s.match(/#[0-9]+/)\n if (pinNav != null) {\n pinNav = pinNav[0].substr(1);\n pinNav = parseInt(pinNav)\n if (pinNav == NaN) pinNav = null;\n }\n return [mapNav, pinNav];\n}",
"function formatMarkingMenuData(data) {\r\n\tvar records = data.split(\"\\n\");\r\n\tvar numRecords = records.length;\r\n\tvar menuItems = {}\r\n\r\n\t// Parse through the records and create individual menu items\r\n\tfor (var i = 1; i < numRecords; i++) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar label = items[2].trim();\r\n\t\tmenuItems[id] = {\r\n\t\t\t'name': label,\r\n\t\t\t'children': []\r\n\t\t};\r\n\t}\r\n\r\n\tfor (var i = numRecords - 1; i >= 1; i--) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar parent = items[1].trim();\r\n\t\tif (parent === '0') {\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tvar children = menuItems[parent]['children'];\r\n\t\t\tchildren.push(menuItems[id]);\r\n\t\t\tdelete menuItems[id]\r\n\t\t\tmenuItems[parent]['children'] = children;\r\n\t\t}\r\n\t}\r\n\r\n\tvar menuItemsList = [];\r\n\tfor (var key in menuItems) {\r\n\t\tmenuItemsList.push(menuItems[key]);\r\n\t}\r\n\treturn menuItemsList;\r\n}",
"function formatMarkingMenuData(data) {\r\n\tvar records = data.split(\"\\n\");\r\n\tvar numRecords = records.length;\r\n\tvar menuItems = {}\r\n\r\n\t// Parse through the records and create individual menu items\r\n\tfor (var i = 1; i < numRecords; i++) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar label = items[2].trim();\r\n\t\tmenuItems[id] = {\r\n\t\t\t'name': label,\r\n\t\t\t'children': []\r\n\t\t};\r\n\t}\r\n\r\n\tfor (var i = numRecords - 1; i >= 1; i--) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar parent = items[1].trim();\r\n\t\tif (parent === '0') {\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tvar children = menuItems[parent]['children'];\r\n\t\t\tchildren.push(menuItems[id]);\r\n\t\t\tdelete menuItems[id]\r\n\t\t\tmenuItems[parent]['children'] = children;\r\n\t\t}\r\n\t}\r\n\r\n\tvar menuItemsList = [];\r\n\tfor (var key in menuItems) {\r\n\t\tmenuItemsList.push(menuItems[key]);\r\n\t}\r\n\r\n\treturn menuItemsList;\r\n}",
"function formatMarkingMenuData(data) {\r\n\t\tvar records = data.split(\"\\n\");\r\n\t\tvar numRecords = records.length;\r\n\t\tvar menuItems = {}\r\n\r\n\t\t// Parse through the records and create individual menu items\r\n\t\tfor (var i = 1; i < numRecords; i++) {\r\n\t\t\t\tvar items = records[i].split(',');\r\n\t\t\t\tvar id = items[0].trim();\r\n\t\t\t\tvar label = items[2].trim();\r\n\t\t\t\tmenuItems[id] = {\r\n\t\t\t\t\t\t'name': label,\r\n\t\t\t\t\t\t'children': []\r\n\t\t\t\t};\r\n\t\t}\r\n\r\n\t\tfor (var i = numRecords - 1; i >= 1; i--) {\r\n\t\t\t\tvar items = records[i].split(',');\r\n\t\t\t\tvar id = items[0].trim();\r\n\t\t\t\tvar parent = items[1].trim();\r\n\t\t\t\tif (parent === '0') {\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t} else {\r\n\t\t\t\t\t\tvar children = menuItems[parent]['children'];\r\n\t\t\t\t\t\tchildren.push(menuItems[id]);\r\n\t\t\t\t\t\tdelete menuItems[id]\r\n\t\t\t\t\t\tmenuItems[parent]['children'] = children;\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar menuItemsList = [];\r\n\t\tfor (var key in menuItems) {\r\n\t\t\t\tmenuItemsList.push(menuItems[key]);\r\n\t\t}\r\n\r\n\t\treturn menuItemsList;\r\n}",
"function menu(blockspec){\n var title = blockspec.name.replace(/\\W/g, '');\n var specs = blockspec.blocks;\n var help = blockspec.help !== undefined ? blockspec.help : '';\n return edit_menu(title, specs, help);\n}",
"function getMenuFormat( formatstr )\n{\n // formatstr = 'format' or 'displaystr|format'\n let barpos = formatstr.indexOf(\"|\");\n if (barpos === -1)\n {\n // Normal - menu entry is the format\n // NB: we strip menu-shortcut '&'s here; if you have a URL that legitimately contains\n // an ampersand, and this would be before a menu shortcut (‽), to stop it being stripped\n // you just have to give a label. Or double && I guess.\n return removeAccess( formatstr );\n }\n else\n {\n // Custom - format comes after the vertical bar\n return formatstr.substr( barpos+1 );\n }\n}",
"function parseMenu(navdoc) {\n var menu = [];\n navdoc.getSliceZone('nav.items').slices.forEach(function(item) {\n switch (item.sliceType) {\n case 'top-level':\n var label = item.value.getFirstTitle().text;\n var link = item.value.value[0].getLink('link');\n menu.push({\n label: label,\n url: configuration.linkResolver(link)\n });\n break;\n default:\n var subitems = item.value.toArray().map(function(item) {\n var label = item.getFirstTitle().text;\n var link = item.getLink('link');\n return {\n label: label,\n url: configuration.linkResolver(link)\n };\n });\n var last = menu.pop() || {};\n menu.push(Object.assign(last, {\n dropdown: true,\n subitems: subitems\n }));\n };\n });\n console.log(\"Got: \" + JSON.stringify(menu));\n return menu;\n}",
"function doseqparsing(seqdata) {\n\tvar lines = seqdata.split('\\n');\n\tfor (var i = 0; i < lines.length; i += 0) {\n\t\tif (!lines[i].startsWith(\">\") || lines[i].length === 0) { i++; }\n\t\telse {\n\t\t\tvar seqID = lines[i].substr(1).trim(/(\\r\\n|\\n|\\r)/gm);\n\t\t\tvar seq = lines[i+1].split(\"\");\n\t\t\twhile (seq[seq.length-1].charCodeAt(0) < 32) { seq.pop(); }\n\t\t\tseqID_lookup[seqID].sequence = seq;\n\t\t\tsequences_raw.push(seq);\n\t\t\tif (seqID_lookup[seqID].vaccine) {\n\t\t\t\tsequences.vaccine.push(seq);\n\t\t\t\tnumvac++;\n\t\t\t} else {\n\t\t\t\tsequences.placebo.push(seq);\n\t\t\t\tnumplac++;\n\t\t\t}\n\t\t\ti += 2;\n\t\t}\n\t}\n}",
"function formatMarkingMenuData(data) {\r\n\r\n\tvar records = data.split(\"\\n\");\r\n\tvar numRecords = records.length;\r\n\tvar menuItems = {} // { {Animals,children[{Mammals, children[]}]},...}\r\n\r\n\t// Parse through the records and create individual menu items\r\n\tfor (var i = 1; i < numRecords; i++) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar label = items[2].trim();\r\n\t\tmenuItems[id] = {\r\n\t\t\t'name': label,\r\n\t\t\t'children': [] \r\n\t\t};\r\n\t}\r\n\r\n\tfor (var i = numRecords - 1; i >= 1; i--) {\r\n\t\tvar items = records[i].split(',');\r\n\t\tvar id = items[0].trim();\r\n\t\tvar parent = items[1].trim();\r\n\t\tif (parent === '0') { // no parent with id '0'\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tvar children = menuItems[parent]['children']; //[]\r\n\t\t\tchildren.push(menuItems[id]);\r\n\t\t\tdelete menuItems[id]\r\n\t\t\tmenuItems[parent]['children'] = children;\r\n\t\t}\r\n\t}\r\n\r\n\tvar menuItemsList = [];\r\n\tfor (var key in menuItems) {\r\n\t\tmenuItemsList.push(menuItems[key]);\r\n\t}\r\n\treturn menuItemsList;\r\n}",
"function parseMenuInput(e) {\n\tmenu.children[menu.children.indexOf(e.target)].action();\n}",
"function menuFromData(data,menu,newItemList,prefix){\r\n\t\tnewItemList=(newItemList||[]);\r\n\t\tfor (var m=0,len=data.length; m<len; m++){\r\n\t\t\tvar material = (data[m][\"id\"]||data[m][\"name\"]).noSpaces().toLowerCase();\r\n\t\t\tvar accText = data[m][\"name\"].upperWords();\r\n\t\t\tvar event = (data[m][\"event\"]||\"Unsorted\").upperWords();\r\n\r\n\t\t\tvar thisMenu;\r\n\t\t\tif ( !(thisMenu=(menu[\"optblock\"+event]||null) ) ) {\r\n\t\t\t\t//create this option block\r\n\t\t\t\tthisMenu=(menu[\"optblock\"+event]={type:\"optionblock\",label:event,kids:{} });\r\n\t\t\t}\r\n\t\t\t//create this material element\r\n\t\t\tthisMenu.kids[prefix+material]={type:\"checkbox\",label:accText,newitem:newItemList.inArray(prefix+material)};\r\n\t\t}\r\n\t}",
"function parseloopspec(p){\n \t\tvar m = p.match( /^(\\w+)\\s*<-\\s*(\\S+)?$/ );\n \t\tif(m === null){\n \t\t\terror('bad loop spec: \"' + p + '\"');\n \t\t}\n \t\tif(m[1] === 'item'){\n \t\t\terror('\"item<-...\" is a reserved word for the current running iteration.\\n\\nPlease choose another name for your loop.');\n \t\t}\n \t\tif( !m[2] || (m[2] && (/context/i).test(m[2]))){ //undefined or space(IE) \n \t\t\tm[2] = function(ctxt){return ctxt.context;};\n \t\t}\n \t\treturn {name: m[1], sel: m[2]};\n \t}",
"function ParseSpellMenu() {\n\t//define a function for creating the full set of spells-by-level menu for a class\n\tvar createMenu = function(menu, className, fullArray) {\n\t\tvar nameArray = [\n\t\t\t\"All spells\",\n\t\t\t\"Cantrips\",\n\t\t\t\"1st-level\",\n\t\t\t\"2nd-level\",\n\t\t\t\"3rd-level\",\n\t\t\t\"4th-level\",\n\t\t\t\"5th-level\",\n\t\t\t\"6th-level\",\n\t\t\t\"7th-level\",\n\t\t\t\"8th-level\",\n\t\t\t\"9th-level\"\n\t\t];\n\t\tvar classTemp = {cName : className, oSubMenu : []};\n\t\tfor (var y = 0; y < fullArray.length; y++) {\n\t\t\tvar spellsArray = fullArray[y];\n\t\t\tif (spellsArray.length > 0) {\n\t\t\t\tvar spellsTemp = {cName : nameArray[y], oSubMenu : []};\n\t\t\t\tfor (var i = 0; i < spellsArray.length; i++) {\n\t\t\t\t\tspellsTemp.oSubMenu.push({\n\t\t\t\t\t\tcName : SpellsList[spellsArray[i]].name + (SpellsList[spellsArray[i]].ritual ? \" (R)\" : \"\"),\n\t\t\t\t\t\tcReturn : \"spell\" + \"#\" + spellsArray[i] + \"#\"\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tclassTemp.oSubMenu.push(spellsTemp);\n\t\t\t}\n\t\t}\n\t\tmenu.oSubMenu.push(classTemp);\n\t}\n\t\n\tvar amendMenu = function(theMenu, nameChange, extraReturn) {\n\t\ttheMenu.cName = nameChange;\n\t\tfor (var a = 0; a < theMenu.oSubMenu.length; a++) {\n\t\t\tif (theMenu.oSubMenu[a].cName === \"-\") continue;\n\t\t\tfor (var b = 0; b < theMenu.oSubMenu[a].oSubMenu.length; b++) {\n\t\t\t\tif (theMenu.oSubMenu[a].oSubMenu[b].cName === \"-\") continue;\n\t\t\t\tfor (var c = 0; c < theMenu.oSubMenu[a].oSubMenu[b].oSubMenu.length; c++) {\n\t\t\t\t\tif (theMenu.oSubMenu[a].oSubMenu[b].oSubMenu[c].cName === \"-\") continue;\n\t\t\t\t\ttheMenu.oSubMenu[a].oSubMenu[b].oSubMenu[c].cReturn += extraReturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvar allSpellCasters = [\n\t\t\"any\",\n\t\t\"-\",\n\t\t\"bard\",\n\t\t\"cleric\",\n\t\t\"druid\",\n\t\t\"paladin\",\n\t\t\"ranger\",\n\t\t\"sorcerer\",\n\t\t\"warlock\",\n\t\t\"wizard\",\n\t\t\"-\"\n\t];\n\t\n\tvar moreSpellCasters = [];\n\tfor (var aClass in ClassList) {\n\t\tif (aClass === \"rangerua\") continue;\n\t\tif (ClassList[aClass].spellcastingFactor && !(/psionic/i).test(ClassList[aClass].spellcastingFactor)) {\n\t\t\tif (allSpellCasters.indexOf(aClass) === -1 && moreSpellCasters.indexOf(aClass) === -1 && !testSource(aClass, ClassList[aClass], \"classExcl\")) moreSpellCasters.push(aClass);\n\t\t} else {\n\t\t\tvar subClasses = ClassList[aClass].subclasses[1];\n\t\t\tfor (var SC = 0; SC < subClasses.length; SC++) {\n\t\t\t\tvar aSubClass = subClasses[SC];\n\t\t\t\tif (ClassSubList[aSubClass].spellcastingFactor && !(/psionic/i).test(ClassSubList[aSubClass].spellcastingFactor) && allSpellCasters.indexOf(aSubClass) === -1 && moreSpellCasters.indexOf(aSubClass) === -1 && !testSource(aSubClass, ClassSubList[aSubClass], \"classExcl\")) moreSpellCasters.push(aSubClass);\n\t\t\t}\n\t\t}\n\t};\n\t\n\tmoreSpellCasters.sort();\n\tallSpellCasters = allSpellCasters.concat(moreSpellCasters);\n\t\n\t//now see if this newly created list matches the known caster classes\n\tif (AllCasterClasses && AllCasterClasses.toSource() === allSpellCasters.toSource()) {\n\t\treturn AddSpellsMenu;\n\t} else {\n\t\tAllCasterClasses = allSpellCasters;\n\t};\n\t\n\tvar AllSpellsMenu = {cName : \"without first column\", oSubMenu : []};\n\tfor (var s = 0; s < allSpellCasters.length; s++) {\n\t\tvar aCast = allSpellCasters[s];\n\t\tvar aObj = ClassList[aCast] ? ClassList[aCast] : (ClassSubList[aCast] ? ClassSubList[aCast] : false);\n\t\tif (aCast === \"-\") {\n\t\t\tAllSpellsMenu.oSubMenu.push({cName : \"-\"});\n\t\t\tcontinue;\n\t\t}\n\t\tvar aCastClass = aObj && aObj.spellcastingList ? aObj.spellcastingList : {class : aCast, psionic : false};\n\t\tvar aCastName = aCast === \"any\" ? \"All spells\" : (aObj.fullname ? aObj.fullname : aObj.subname ? aObj.subname : aObj.name) + \" spells\";\n\t\t\n\t\t//get a list of all the spells in the class' spell list and sort it\n\t\tvar allSpells = CreateSpellList(aCastClass, false);\n\t\tallSpells.sort();\n\t\t\n\t\t//now make an array with one array for each spell level\n\t\tvar spellsByLvl = OrderSpells(allSpells, \"multi\");\n\t\t//and add the complete list to as the first of the by level array\n\t\tspellsByLvl.unshift(allSpells);\n\t\t\n\t\t//now create amenu for this class and add it to the submenu array of AllSpellsMenu\n\t\tcreateMenu(AllSpellsMenu, aCastName, spellsByLvl);\n\t};\n\t\n\t//start an array of the different menus\n\tvar spellsMenuArray = [AllSpellsMenu];\n\t\n\t//now to do something that makes it possible to copy this object multiple times\n\tvar menuString = AllSpellsMenu.toSource();\n\t\n\tvar menuExtraTypes = [\n\t\t[\"with a Checkbox\", \"checkbox\"],\n\t\t[\"with an 'Always Prepared' Checkbox\", \"markedbox\"],\n\t\t[\"with 'At Will'\", \"atwill\"],\n\t\t[\"with '1\\u00D7 Long Rest'\", \"oncelr\"],\n\t\t[\"with '1\\u00D7 Short Rest'\", \"oncesr\"],\n\t\t[\"Ask me for the first column\", \"askuserinput\"]\n\t]\n\t//add a menu with a changed name \n\tfor (var e = 0; e < menuExtraTypes.length; e++) {\n\t\tvar aMenu = eval(menuString);\n\t\tamendMenu(aMenu, menuExtraTypes[e][0], menuExtraTypes[e][1]);\n\t\tspellsMenuArray.push(aMenu);\n\t}\n\t\n\t//return the newly formed array\n\treturn spellsMenuArray;\n}",
"function parseLocation(loc2parse) {\n var dot = dotStringLoc2ObjectLoc(loc2parse);\n var bknum = findBookNum(dot.shortName);\n if (bknum !== null) {\n // loc2parse started with something like Gen. so we assume it's a valid osisRef\n return dot;\n }\n \n loc2parse = loc2parse.replace(/[“|”|\\(|\\)|\\[|\\]|,]/g,\" \");\n loc2parse = loc2parse.replace(/^\\s+/,\"\");\n loc2parse = loc2parse.replace(/\\s+$/,\"\");\n loc2parse = iString(loc2parse);\n//jsdump(\"reference:\\\"\" + loc2parse + \"\\\"\\n\");\n if (loc2parse==\"\" || loc2parse==null) {return null;}\n var location = {shortName: null, version: null, chapter: null, verse: null, lastVerse: null}\n var m; //used for debugging only\n var has1chap;\n var shft; // book=1, chap=2, verse=3, lastVerse=4 \n var parsed = loc2parse.match(/([^:-]+)\\s+(\\d+)\\s*:\\s*(\\d+)\\s*-\\s*(\\d+)/); shft=0; m=0; has1chap=false; // book 1:2-3\n if (parsed==null) {parsed = loc2parse.match(/([^:-]+)\\s+(\\d+)\\s*:\\s*(\\d+)/); shft=0; m=1; has1chap=false;} // book 4:5\n if (parsed==null) {parsed = loc2parse.match(/([^:-]+)\\s+(\\d+)/); shft=0; m=2; has1chap=false;} // book 6\n if (parsed==null) {parsed = loc2parse.match(/([^:-]+)\\s+[v|V].*(\\d+)/); shft=0; m=3; has1chap=true;} // book v6 THIS VARIES WITH LOCALE!!!\n if (parsed==null) {parsed = loc2parse.match(/^(\\d+)$/); shft=2; m=4; has1chap=false;} // 6\n if (parsed==null) {parsed = loc2parse.match(/(\\d+)\\s*:\\s*(\\d+)\\s*-\\s*(\\d+)/); shft=1; m=5; has1chap=false;} // 1:2-3\n if (parsed==null) {parsed = loc2parse.match(/(\\d+)\\s*:\\s*(\\d+)/); shft=1; m=6; has1chap=false;} // 4:5\n if (parsed==null) {parsed = loc2parse.match(/(\\d+)\\s*-\\s*(\\d+)/); shft=2; m=7; has1chap=false;} // 4-5\n if (parsed==null) {parsed = loc2parse.match(/^(.*?)$/); shft=0; m=8; has1chap=false;} // book\n//jsdump(\"parsed:\" + parsed + \" match type:\" + m + \"\\n\");\n \n if (parsed) {\n while (shft--) {parsed.splice(1,0,null);}\n if (has1chap) parsed.splice(2,0,1); // insert chapter=1 if book has only one chapter\n if (parsed[1]) {\n var book=identifyBook(parsed[1].replace(/[\"'«»“”\\.\\?]/g,\"\"));\n if (book==null || book.shortName==null) {return null;}\n location.shortName = book.shortName;\n location.version = book.version;\n if (location.version.indexOf(\",\")>-1) {\n var vs = location.version.split(\",\");\nLOOP1:\n for (var v=0; v<vs.length; v++) {\n vs[v] = vs[v].replace(/\\s/g, \"\");\n location.version = vs[v];\n var bs = getAvailableBooks(vs[v]);\n for (var b=0; b<bs.length; b++) if (bs[b] == location.shortName) break LOOP1;\n }\n }\n }\n if (parsed[2]) {location.chapter = (Number(parsed[2])>0) ? Number(parsed[2]):1;}\n if (parsed[3]) {location.verse = (Number(parsed[3])>0) ? Number(parsed[3]):1;}\n if (parsed[4]) {location.lastVerse = (Number(parsed[4])>0) ? Number(parsed[4]):1;}\n }\n else {return null;}\n \n//jsdump(uneval(location));\n return location;\n}",
"function astSectionName(state, chars, phraseIndex, phraseLength, data) {\n const ret = id.SEM_OK;\n if (state === id.SEM_PRE) {\n const name = apgLib.utils.charsToString(chars, phraseIndex, phraseLength);\n currentSection = findSection(name, data);\n if (currentSection === undefined) {\n currentSection = {};\n data[name] = currentSection;\n }\n }\n return ret;\n }",
"function parseLocaTable(data,start,numGlyphs,shortVersion){var p=new parse.Parser(data,start);var parseFn=shortVersion?p.parseUShort:p.parseULong;// There is an extra entry after the last index element to compute the length of the last glyph.\n// That's why we use numGlyphs + 1.\nvar glyphOffsets=[];for(var i=0;i<numGlyphs+1;i+=1){var glyphOffset=parseFn.call(p);if(shortVersion){// The short table version stores the actual offset divided by 2.\nglyphOffset*=2;}glyphOffsets.push(glyphOffset);}return glyphOffsets;}",
"function parseMenus() {\n console.log(\"Finding contents of menus...\");\n let menus = document.getElementsByClassName(\"v-select__slot\");\n\n // make menus show up\n document.getElementsByClassName(\"s80-filter\")[0].getElementsByTagName(\"button\")[0].click();\n\n for (var m = 0; m < menus.length; m++ ) {\n let label = menus[m].getElementsByTagName(\"label\")[0];\n let listId = label.attributes[\"for\"].value.match(\"input-(.*)\")[1];\n let listName = label.innerText;\n\n parseEntries( listName, \"list-\" + listId );\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
f() : TOGGLELEFTMENU Animate the toggle apparition of the left menu | function toggleLeftMenu()
{
// Get ID of the left menu
// ---------------------------------------------------------------------------
var menu_Left = document.getElementById("leftMenu");
// Show / hide the left menu
// ---------------------------------------------------------------------------
if (menu_Left.style.opacity == "0")
{
$(function()
{
$("#leftMenu").animate({width: '170px', opacity: 1.0}, 200);
$("#content").animate({width: '73%', marginLeft: '210px'}, 200);
});
}
else
{
$(function()
{
$("#leftMenu").animate({width: '0px', opacity: 0.0}, 200);
$("#content").animate({width: '87%', marginLeft: '27px'}, 200);
});
}
} | [
"function toggleLeftMenu() {\n $mdSidenav('left').toggle();\n }",
"function menuStuff() {\n if (toggle === 1) {\n menu.css('display', 'table');\n setTimeout(function() {\n // menu.css('opacity', 1);\n menu.stop().animate({opacity: 1}, 200);\n // menuLi.css('left', '0');\n menuLi.stop().animate({left: 0}, 200);\n toggle = 0;\n }, 100);\n }\n if (toggle === 0) {\n // menu.css('opacity', 0);\n menu.stop().animate({opacity: 0}, 200);\n // menuLi.css('left', '-40px');\n menuLi.stop().animate({left: '-40px'}, 200);\n setTimeout(function() {\n menu.css('display', 'none');\n }, 600);\n toggle = 1;\n }\n }",
"function showSideMenu() {\n if (sideMenuToggle == 0) {\n $(\"#mainpane\").animate({\n left: \"300\"\n }, 500);\n sideMenuToggle = 1;\n }\n else {$(\"#mainpane\").animate({\n left: \"0\"\n }, 500);\n sideMenuToggle = 0;\n }\n}",
"onClickLeftMenuToggle(flag) {\n\n if (flag)\n this.props.dispatch(Action.getAction(sharedActionTypes.SET_LEFT_MENU_SMALL_SCREEN_TOGGLED, {}));\n else\n this.props.dispatch(Action.getAction(sharedActionTypes.SET_RIGHT_MENU_SMALL_SCREEN_TOGGLED, {}));\n\n }",
"static ToggleLeft() {}",
"function toggle_menu(e){\r\n\t var top\r\n\t\tif ( isMobile() == false )\r\n\t\t{\r\n\t\t\ttop = $('#toolTitle').offset().top + 'px'\r\n\t\t\t$(\"#side_nav\").css(\"right\", 0);\r\n\t\t\t$(\"#side_nav\").css(\"margin\", 0);\r\n\t\t} else {\r\n\t\t\ttop = $('#toolTitle').position().top + 'px'\r\n\t\t\t$(\"#side_nav\").css(\"margin-top\",0)\r\n\t\t}\r\n\r\n\t\t$(\"#side_nav\").css(\"position\", \"absolute\");\r\n\t\t$(\"#side_nav\").css(\"top\", top)\r\n\r\n\r\n if($(\"#side_nav\").width()>0){\r\n $(\"#side_nav\").show().animate({ width: \"0%\" },{ duration: 300, complete: function() {\r\n $('#side_nav .glyphicon-menu-hamburger').css('display', 'none');\r\n $(\"#form-steps\").css(\"z-index\",\"1\");\r\n }\r\n });\r\n\r\n } else {\r\n\t\t$(\"header\").css(\"z-index\",\"200\")\r\n\t\t$(\"#side_nav\").stop(true,true).show().animate({width: \"70%\"},{ complete: function() {\r\n\t\t $('#side_nav .glyphicon-menu-hamburger').css('display', 'inline-block');\r\n\t\t }\r\n\t\t }\r\n\t\t);\r\n }\r\n}",
"onShowMenu(){\n\t\tif(!this.menu_shown){\n\t\t\tactions.toggleMenu();\n\t\t}\n\t}",
"function openMenu() {\n document.getElementsByClassName('so-section')[0].style.left = '0';\n document.getElementsByClassName('navigator-links')[0].style.left = '-100%';\n setMenuIsOpen(true);\n }",
"toggleMenu () {\n const menuHeight = getHeight(this.menu);\n const slideContainer = (val, done) => {\n this.isOpen = null;\n return translateY(this.container, val, done, TRANS_DURATION);\n };\n\n if (this.isOpen) {\n slideContainer(menuHeight * -1, () => {\n this.isOpen = false;\n this.menu.classList.remove(OPEN_CLASS);\n setTranslateStyle(this.container, 0);\n });\n } else {\n setTranslateStyle(this.container, menuHeight * -1);\n this.menu.classList.add(OPEN_CLASS);\n slideContainer(0, () => {\n this.isOpen = true;\n });\n }\n }",
"toggleLeftSliderMenu() {\n this.setState({\n leftSliderMenuVisible: !this.state.leftSliderMenuVisible\n });\n this.setState({\n backDropVisible: !this.state.backDropVisible\n });\n }",
"function menuToggle() {\n\n if (menuStatus == false) {\n\n document.getElementById(\"menu\").style.marginLeft = \"300px\";\n\n document.getElementById(\"menu\").style.transition = \"1s\";\n\n menuStatus = true;\n\n } else {\n\n document.getElementById(\"menu\").style.marginLeft = \"0\";\n\n menuStatus = false;\n\n }\n\n}",
"toggleMenu() {\n let currentWidth = Dimensions.get('window').width;\n width = currentWidth;\n\n this.setState({\n expanded : !this.state.expanded\n });\n\n let toggledState = toggleStarter(this.state.expanded, this.state.initialValues, width),\n toggledFinal = toggleFinal(this.state.expanded, width);\n\n animateAll(toggledState, toggledFinal);\n\n\n }",
"function menuOnClick(){\n\n\tvar nav = $(\"nav\");\n\tif(!buttonPressed){\n\t\tnav.animate({left: '15px'});\n\t\tnav.animate({left: '-700px'});\n\t\tbuttonPressed = true;\n\t}\n\telse{\n\t\tnav.animate({left: '0'});\n\t\tbuttonPressed = false;\n\t}\n}",
"function menuSlide(){\n $('.nav-menu').toggleClass('nav-menu-is-showing');\n if($('.nav-menu').hasClass('nav-menu-is-showing')) {\n navMenu.inert = false;\n }\n else {\n navMenu.inert = true;\n }\n }",
"function toggleMenuState() {\n\n if (isVisible(menu)) {\n hideMenu ();\n }\n else {\n // show\n menu.style.display = 'block';\n }\n\n }",
"function menuAnimation() {\n if (!menuOpen) {\n menuOpen = true;\n headerTl.play();\n }\n else {\n menuOpen = false;\n headerTl.reverse();\n }\n}",
"function sidemenuToggle() {\n if(isSideMenuOpen) {\n sidemenuClose();\n } else {\n sidemenuOpen();\n }\n}",
"toggle() {\n if (this.hasMenu()) {\n this.isMenuOpen() ? this.closeMenu() : this.openMenu();\n }\n }",
"function flipMenu(){\n if (menu_open)\n closeMenu();\n else\n openMenu();\n menu_open = !menu_open;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
console.log(count(null, 1), 0) console.log(count(node1, 9), 1) console.log(count(node2, 17), 0) console.log(count(node2, 2), 2) / Find average of a list of integers | function average(node){
if(!node) return 0;
let length = 0;
let sum = 0;
function helper(node):void{
if(!node) return;
sum += node.value;
length++;
return helper(node.next);
}
return sum / length;
} | [
"function aggregate_counts(node) {\n}",
"average() {\n const length = this.length();\n let sum = 0;\n // this.traverse(function (node) {\n // sum += node.value;\n // });\n this.traverse(node => sum += node.value);\n\n return this.isEmpty() ? null : sum / length;\n }",
"function sumNodeValues(nodes) {\n\n return nodes.reduce((accum, node) => {\n accum += node.count;\n return accum;\n }, 0);\n}",
"average() {\n if (!this.head) {\n return 0;\n }\n\n let currNode = this.head;\n let sum = currNode.val;\n for (let i = 0; i < this.length - 1; i++) {\n currNode = currNode.next;\n sum += currNode.val;\n }\n\n return sum / this.length;\n }",
"function SllAverage (node) {\n let cnt = 0;\n let sum = 0;\n\n while(node) {\n sum += node.value;\n cnt++;\n node = node.next;\n }\n\n return sum/cnt;\n}",
"function mean(head){\n if(!head) return 0;\n // let total = 0\n // let count = 0 \n function sumAndCount(head){\n if(!head) return [0, 0];\n\n\n const [sum, count] = sumAndCount(head.next)\n\n return [head.value + sum, count+1]\n \n }\n const [sum, count] = sumAndCount(head)\n\n return sum / count\n\n}",
"countEvens() {\n return this.sumValues(0, \"node.val%2===0\");\n }",
"function averageOfLevels(node) {\n if (!node) return null;\n let results = [];\n\n getNodesAndLevels(node, results, 0);\n\n return results.map(level => {\n return level.reduce((a, b) => a + b) / level.length;\n })\n}",
"size() {\n let count = 1;\n\n if (this.left) {\n console.log(`counting left of node ${this.value}`);\n count += this.left.size();\n }\n\n if (this.right) {\n console.log(`counting right of node ${this.value}`);\n\n count += this.right.size();\n }\n\n return count;\n }",
"size() {\n let count = 1;\n \n if (this.left) {\n console.log(`counting left of node ${this.value}`);\n count += this.left.size();\n }\n \n if (this.right) {\n console.log(`counting right of node ${this.value}`);\n \n count += this.right.size();\n }\n \n return count;\n }",
"static toAverage(list)\n\t{\t\t\n\t\tlet node = list.begin();\n\t\tlet\tmean = 0;\n\t\tlet\tsum = 0;\n\t\t\t\n\t\tif (!list.isEmpty) {\n\t\t\twhile ( node !== null) {\n\t\t\t\tsum += node.value;\n\t\t\t\tnode = node.next;\n\t\t\t}\n\t\t}\t\t\n\t\tmean = sum / list.size;\t\t\n\t\treturn mean;\n\t}",
"average() {\n // what is the average value in my list?\n var runner = this.head;\n var sum = 0;\n var count = 0;\n while (runner != null) {\n sum += runner.val;\n count++;\n runner = runner.next;\n }\n return sum/count;\n }",
"get nodeCount() {\n let count = 0\n for (let x in this.app.state.aspects) {\n let nodes = cloneDeep(this.app.state.aspects[x].nodes)\n nodes.reverse()\n let countNulls = false\n\n for (let z in nodes) {\n if (nodes[z] != null) // on the first non-null subnode we find, start counting\n countNulls = true\n if (nodes[z] != null || countNulls) {\n count++\n }\n }\n }\n\n // add core nodes\n for (let node in this.app.state.coreNodes) {\n count += (this.app.state.coreNodes[node]) ? 1 : 0\n }\n\n return count\n }",
"nodeAverages() {\n const node = this.root;\n const result = {};\n const depthAverages = [];\n\n const traverse = ( node, depth ) => {\n if ( !node ) {\n return null;\n }\n if ( node ) {\n if ( !result[depth] ) {\n result[depth] = [node.value];\n } else {\n result[depth].push( node.value );\n }\n }\n // check to see if node is a leaf, depth stays the same if it is\n // otherwise increment depth for possible right and left nodes\n if ( node.right || node.left ) {\n traverse(node.left, depth + 1);\n traverse(node.right, depth + 1);\n }\n };\n traverse(node, 0);\n\n // get averages and breadthFirst\n for ( let key in result ) {\n const len = result[key].length;\n let depthAvg = 0;\n for ( let i = 0; i < len; i++ ) {\n depthAvg += result[key][i];\n }\n depthAverages.push( Number( ( depthAvg / len ).toFixed( 2 ) ) );\n }\n return depthAverages;\n }",
"function nodeStats(head){\n var curr = head\n if(curr.value){\n var stats = {\"max\": curr.value,\"min\":curr.value,\"avg\": 0}\n var sum = head.value\n var count = 1\n curr = curr.next\n }\n else{\n return \"initial node has null value\"\n }\n\n while(curr){\n if(curr.value > stats[\"max\"]){\n stats[\"max\"] = curr.value\n }\n if(curr.value < stats[\"min\"]){\n stats[\"min\"] = curr.value\n }\n sum += curr.value\n count++\n curr = curr.next\n }\n stats[\"avg\"] = sum/count\n return stats\n}",
"countEvens() {\n if (this.root == null) {\n return 0;\n }\n let toVisitNode = this.root.children;\n let isRootEven = this.root.val % 2 == 0 ? 1 : 0;\n let total = recurseCountEvenValues(toVisitNode, isRootEven);\n function recurseCountEvenValues(node, sum) {\n for (let child of node) {\n sum += child.val % 2 == 0 ? 1 : 0;\n if (child.children.length > 0) {\n return recurseCountEvenValues(child.children, sum);\n }\n }\n return sum;\n }\n return total;\n }",
"function getallNodesScore(nodes) {\r\n let allNodesScore = 0;\r\n\r\n nodes.forEach((node) => {\r\n allNodesScore += getNodeScore(node);\r\n });\r\n\r\n return allNodesScore;\r\n }",
"calculateFP3() {\n let nodeCount = 0,\n countedNodes = [];\n /**\n * Process only cluster heads\n */\n this.genes.forEach((geneValue, index) => {\n if (geneValue) {\n // Find number of nodes in the vicinity of corresponding node to this gene value.\n this.network.distanceMatrix[index].forEach((d, d_index) => {\n if (d < VICINITY && !countedNodes.includes(d_index)) {\n nodeCount++;\n countedNodes.push(d_index);\n }\n });\n }\n });\n return nodeCount;\n }",
"countNodes() {\n let count = 1;\n let current = this.head;\n if (current) {\n while (current.next) {\n current = current.next;\n count++;\n }\n return count;\n }\n return 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configures conversion pipelines to support upcasting and downcasting image captions. | _setupConversion() {
const editor = this.editor;
const view = editor.editing.view;
const imageUtils = editor.plugins.get( 'ImageUtils' );
const t = editor.t;
// View -> model converter for the data pipeline.
editor.conversion.for( 'upcast' ).elementToElement( {
view: element => matchImageCaptionViewElement( imageUtils, element ),
model: 'caption'
} );
// Model -> view converter for the data pipeline.
editor.conversion.for( 'dataDowncast' ).elementToElement( {
model: 'caption',
view: ( modelElement, { writer } ) => {
if ( !imageUtils.isBlockImage( modelElement.parent ) ) {
return null;
}
return writer.createContainerElement( 'figcaption' );
}
} );
// Model -> view converter for the editing pipeline.
editor.conversion.for( 'editingDowncast' ).elementToElement( {
model: 'caption',
view: ( modelElement, { writer } ) => {
if ( !imageUtils.isBlockImage( modelElement.parent ) ) {
return null;
}
const figcaptionElement = writer.createEditableElement( 'figcaption' );
writer.setCustomProperty( 'imageCaption', true, figcaptionElement );
enablePlaceholder( {
view,
element: figcaptionElement,
text: t( 'Enter image caption' ),
keepOnFocus: true
} );
const widgetEditable = toWidgetEditable( figcaptionElement, writer );
setHighlightHandling(
widgetEditable,
writer,
( element, descriptor, writer ) => writer.addClass( toArray( descriptor.classes ), element ),
( element, descriptor, writer ) => writer.removeClass( toArray( descriptor.classes ), element )
);
return widgetEditable;
}
} );
editor.editing.mapper.on( 'modelToViewPosition', mapModelPositionToView( view ) );
editor.data.mapper.on( 'modelToViewPosition', mapModelPositionToView( view ) );
} | [
"_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst conversion = editor.conversion;\n\t\tconst imageUtils = editor.plugins.get( 'ImageUtils' );\n\n\t\tconversion.for( 'upcast' ).add( upcastPicture( imageUtils ) );\n\t\tconversion.for( 'downcast' ).add( downcastSourcesAttribute( imageUtils ) );\n\t}",
"_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst t = editor.t;\n\t\tconst conversion = editor.conversion;\n\t\tconst imageUtils = editor.plugins.get( 'ImageUtils' );\n\n\t\tconversion.for( 'dataDowncast' )\n\t\t\t.elementToStructure( {\n\t\t\t\tmodel: 'imageBlock',\n\t\t\t\tview: ( modelElement, { writer } ) => (0,_image_utils__WEBPACK_IMPORTED_MODULE_7__.createBlockImageViewElement)( writer )\n\t\t\t} );\n\n\t\tconversion.for( 'editingDowncast' )\n\t\t\t.elementToStructure( {\n\t\t\t\tmodel: 'imageBlock',\n\t\t\t\tview: ( modelElement, { writer } ) => imageUtils.toImageWidget(\n\t\t\t\t\t(0,_image_utils__WEBPACK_IMPORTED_MODULE_7__.createBlockImageViewElement)( writer ), writer, t( 'image widget' )\n\t\t\t\t)\n\t\t\t} );\n\n\t\tconversion.for( 'downcast' )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)( imageUtils, 'imageBlock', 'src' ) )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)( imageUtils, 'imageBlock', 'alt' ) )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastSrcsetAttribute)( imageUtils, 'imageBlock' ) );\n\n\t\t// More image related upcasts are in 'ImageEditing' plugin.\n\t\tconversion.for( 'upcast' )\n\t\t\t.elementToElement( {\n\t\t\t\tview: (0,_image_utils__WEBPACK_IMPORTED_MODULE_7__.getImgViewElementMatcher)( editor, 'imageBlock' ),\n\t\t\t\tmodel: ( viewImage, { writer } ) => writer.createElement(\n\t\t\t\t\t'imageBlock',\n\t\t\t\t\tviewImage.hasAttribute( 'src' ) ? { src: viewImage.getAttribute( 'src' ) } : null\n\t\t\t\t)\n\t\t\t} )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.upcastImageFigure)( imageUtils ) );\n\t}",
"_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst t = editor.t;\n\t\tconst conversion = editor.conversion;\n\t\tconst imageUtils = editor.plugins.get( 'ImageUtils' );\n\n\t\tconversion.for( 'dataDowncast' )\n\t\t\t.elementToElement( {\n\t\t\t\tmodel: 'imageInline',\n\t\t\t\tview: ( modelElement, { writer } ) => writer.createEmptyElement( 'img' )\n\t\t\t} );\n\n\t\tconversion.for( 'editingDowncast' )\n\t\t\t.elementToElement( {\n\t\t\t\tmodel: 'imageInline',\n\t\t\t\tview: ( modelElement, { writer } ) => imageUtils.toImageWidget(\n\t\t\t\t\tcreateImageViewElement( writer, 'imageInline' ), writer, t( 'image widget' )\n\t\t\t\t)\n\t\t\t} );\n\n\t\tconversion.for( 'downcast' )\n\t\t\t.add( downcastImageAttribute( imageUtils, 'imageInline', 'src' ) )\n\t\t\t.add( downcastImageAttribute( imageUtils, 'imageInline', 'alt' ) )\n\t\t\t.add( downcastSrcsetAttribute( imageUtils, 'imageInline' ) );\n\n\t\t// More image related upcasts are in 'ImageEditing' plugin.\n\t\tconversion.for( 'upcast' )\n\t\t\t.elementToElement( {\n\t\t\t\tview: getImgViewElementMatcher( editor, 'imageInline' ),\n\t\t\t\tmodel: ( viewImage, { writer } ) => writer.createElement( 'imageInline', { src: viewImage.getAttribute( 'src' ) } )\n\t\t\t} );\n\t}",
"_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst t = editor.t;\n\t\tconst conversion = editor.conversion;\n\t\tconst imageUtils = editor.plugins.get( 'ImageUtils' );\n\n\t\tconversion.for( 'dataDowncast' )\n\t\t\t.elementToElement( {\n\t\t\t\tmodel: 'imageInline',\n\t\t\t\tview: ( modelElement, { writer } ) => writer.createEmptyElement( 'img' )\n\t\t\t} );\n\n\t\tconversion.for( 'editingDowncast' )\n\t\t\t.elementToStructure( {\n\t\t\t\tmodel: 'imageInline',\n\t\t\t\tview: ( modelElement, { writer } ) => imageUtils.toImageWidget(\n\t\t\t\t\t(0,_image_utils__WEBPACK_IMPORTED_MODULE_7__.createInlineImageViewElement)( writer ), writer, t( 'image widget' )\n\t\t\t\t)\n\t\t\t} );\n\n\t\tconversion.for( 'downcast' )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)( imageUtils, 'imageInline', 'src' ) )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)( imageUtils, 'imageInline', 'alt' ) )\n\t\t\t.add( (0,_converters__WEBPACK_IMPORTED_MODULE_3__.downcastSrcsetAttribute)( imageUtils, 'imageInline' ) );\n\n\t\t// More image related upcasts are in 'ImageEditing' plugin.\n\t\tconversion.for( 'upcast' )\n\t\t\t.elementToElement( {\n\t\t\t\tview: (0,_image_utils__WEBPACK_IMPORTED_MODULE_7__.getImgViewElementMatcher)( editor, 'imageInline' ),\n\t\t\t\tmodel: ( viewImage, { writer } ) => writer.createElement(\n\t\t\t\t\t'imageInline',\n\t\t\t\t\tviewImage.hasAttribute( 'src' ) ? { src: viewImage.getAttribute( 'src' ) } : null\n\t\t\t\t)\n\t\t\t} );\n\t}",
"_setupConversion() {\n const editor = this.editor;\n const t = editor.t;\n const conversion = editor.conversion;\n const imageUtils = editor.plugins.get('ImageUtils');\n\n conversion.for('dataDowncast').elementToElement({\n model: 'imageInline',\n view: (modelElement, { writer }) =>\n writer.createEmptyElement('img')\n });\n\n conversion.for('editingDowncast').elementToStructure({\n model: 'imageInline',\n view: (modelElement, { writer }) =>\n imageUtils.toImageWidget(\n (0,\n _image_utils__WEBPACK_IMPORTED_MODULE_7__.createInlineImageViewElement)(\n writer\n ),\n writer,\n t('image widget')\n )\n });\n\n conversion\n .for('downcast')\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)(\n imageUtils,\n 'imageInline',\n 'src'\n )\n )\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)(\n imageUtils,\n 'imageInline',\n 'alt'\n )\n )\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastSrcsetAttribute)(\n imageUtils,\n 'imageInline'\n )\n );\n\n // More image related upcasts are in 'ImageEditing' plugin.\n conversion.for('upcast').elementToElement({\n view: (0,\n _image_utils__WEBPACK_IMPORTED_MODULE_7__.getImgViewElementMatcher)(\n editor,\n 'imageInline'\n ),\n model: (viewImage, { writer }) =>\n writer.createElement(\n 'imageInline',\n viewImage.hasAttribute('src')\n ? { src: viewImage.getAttribute('src') }\n : null\n )\n });\n }",
"_setupConversion() {\n const editor = this.editor;\n const t = editor.t;\n const conversion = editor.conversion;\n const imageUtils = editor.plugins.get('ImageUtils');\n\n conversion.for('dataDowncast').elementToStructure({\n model: 'imageBlock',\n view: (modelElement, { writer }) =>\n (0,\n _image_utils__WEBPACK_IMPORTED_MODULE_7__.createBlockImageViewElement)(\n writer\n )\n });\n\n conversion.for('editingDowncast').elementToStructure({\n model: 'imageBlock',\n view: (modelElement, { writer }) =>\n imageUtils.toImageWidget(\n (0,\n _image_utils__WEBPACK_IMPORTED_MODULE_7__.createBlockImageViewElement)(\n writer\n ),\n writer,\n t('image widget')\n )\n });\n\n conversion\n .for('downcast')\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)(\n imageUtils,\n 'imageBlock',\n 'src'\n )\n )\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastImageAttribute)(\n imageUtils,\n 'imageBlock',\n 'alt'\n )\n )\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.downcastSrcsetAttribute)(\n imageUtils,\n 'imageBlock'\n )\n );\n\n // More image related upcasts are in 'ImageEditing' plugin.\n conversion\n .for('upcast')\n .elementToElement({\n view: (0,\n _image_utils__WEBPACK_IMPORTED_MODULE_7__.getImgViewElementMatcher)(\n editor,\n 'imageBlock'\n ),\n model: (viewImage, { writer }) =>\n writer.createElement(\n 'imageBlock',\n viewImage.hasAttribute('src')\n ? { src: viewImage.getAttribute('src') }\n : null\n )\n })\n .add(\n (0,\n _converters__WEBPACK_IMPORTED_MODULE_3__.upcastImageFigure)(\n imageUtils\n )\n );\n }",
"_setupConversion() {\n\t\tconst editor = this.editor;\n\t\tconst conversion = editor.conversion;\n\n\t\tconversion.for( 'upcast' ).attributeToAttribute( {\n\t\t\tview: {\n\t\t\t\tname: 'figure',\n\t\t\t\tkey: 'style',\n\t\t\t\tvalue: {\n\t\t\t\t\twidth: /[\\s\\S]+/\n\t\t\t\t}\n\t\t\t},\n\t\t\tmodel: {\n\t\t\t\tname: 'table',\n\t\t\t\tkey: 'tableWidth',\n\t\t\t\tvalue: viewElement => viewElement.getStyle( 'width' )\n\t\t\t}\n\t\t} );\n\n\t\tconversion.for( 'downcast' ).attributeToAttribute( {\n\t\t\tmodel: {\n\t\t\t\tname: 'table',\n\t\t\t\tkey: 'tableWidth'\n\t\t\t},\n\t\t\tview: width => ( {\n\t\t\t\tname: 'figure',\n\t\t\t\tkey: 'style',\n\t\t\t\tvalue: {\n\t\t\t\t\twidth\n\t\t\t\t}\n\t\t\t} )\n\t\t} );\n\n\t\tconversion.for( 'upcast' ).add( (0,_converters__WEBPACK_IMPORTED_MODULE_5__.upcastColgroupElement)( editor ) );\n\t\tconversion.for( 'downcast' ).add( (0,_converters__WEBPACK_IMPORTED_MODULE_5__.downcastTableColumnWidthsAttribute)() );\n\t}",
"_registerConverters() {\n const editor = this.editor;\n\n // Dedicated ckeditor5-converter to propagate media's attribute to the img tag.\n editor.conversion.for('downcast').add(dispatcher =>\n dispatcher.on('attribute:width:media', (evt, data, conversionApi) => {\n if (!conversionApi.consumable.consume(data.item, evt.name)) {\n return;\n }\n\n const viewWriter = conversionApi.writer;\n const figure = conversionApi.mapper.toViewElement(data.item);\n\n if (data.attributeNewValue !== null) {\n viewWriter.setStyle('width', data.attributeNewValue, figure);\n viewWriter.addClass('media_resized', figure);\n } else {\n viewWriter.removeStyle('width', figure);\n viewWriter.removeClass('media_resized', figure);\n }\n })\n );\n\n editor.conversion.for('upcast')\n .attributeToAttribute({\n view: {\n name: 'figure',\n styles: {\n width: /.+/\n }\n },\n model: {\n key: 'width',\n value: viewElement => viewElement.getStyle('width')\n }\n });\n }",
"_registerConverters() {\n const editor = this.editor;\n\n // Dedicated ckeditor5-converter to propagate media's attribute to the img tag.\n editor.conversion.for('downcast').add(dispatcher =>\n dispatcher.on('attribute:ratio:media', (evt, data, conversionApi) => {\n if (!conversionApi.consumable.consume(data.item, evt.name)) {\n return;\n }\n\n const viewWriter = conversionApi.writer;\n const figure = conversionApi.mapper.toViewElement(data.item);\n // if(_isStrNotEmpty(data.attributeNewValue)){\n // viewWriter.setAttribute(data.attributeKey, data.attributeNewValue, figure);\n // }else {\n // viewWriter.removeAttribute(data.attributeKey, figure);\n // }\n viewWriter.removeAttribute(data.attributeKey, figure);\n evt.stop();\n }, {priority : 'lowest'})\n );\n\n editor.conversion.for('upcast')\n .attributeToAttribute({\n view: {\n name: 'figure',\n key : 'class',\n value : /ratio-[\\S]+/\n },\n model: {\n key: 'ratio',\n value: viewElement => {\n const regexp = /ratio-[\\S]+/;\n const match = viewElement.getAttribute( 'class' ).match( regexp );\n return match[ 0 ];\n }\n }\n });\n }",
"defineConverter() {\n\t\tif (this.props.typeConverter === \"binToDec\") {\n\t\t\tthis.convertToBinary();\n\t\t} else {\n\t\t\tthis.convertToDecimal();\n\t\t}\n\t}",
"addOutputOptions() {\n const { conf, creator } = this;\n const outputOptions = [];\n // default\n const defaultOpts = this.getDefaultOutputOptions(conf);\n FFmpegUtil.concatOpts(outputOptions, defaultOpts);\n\n // audio\n const audio = conf.getVal('audio');\n if (!isEmpty(audio)) {\n let apro = '';\n if (ScenesUtil.hasTransition(creator)) {\n const index = ScenesUtil.getLength(creator);\n apro += `-map ${index}:a `;\n }\n\n FFmpegUtil.concatOpts(outputOptions, `${apro}-c:a aac -shortest`.split(' '));\n }\n this.command.outputOptions(outputOptions);\n }",
"afterInit() {\n const editor = this.editor;\n\n // Define on which elements the CSS classes should be preserved:\n setupCustomClassConversion( 'img', 'imageBlock', editor );\n // setupCustomClassConversion( 'img', 'imageInline', editor );\n // setupCustomClassConversion( 'iframe', 'media', editor );\n setupCustomClassConversion( 'table', 'table', editor );\n\n // editor.conversion.for( 'upcast' ).add( upcastCustomClasses( 'figure' ), { priority: 'low' } );\n\n // Define custom attributes that should be preserved.\n // setupCustomAttributeConversion( 'img', 'imageBlock', 'id', editor );\n // setupCustomAttributeConversion( 'img', 'imageInline', 'id', editor );\n // setupCustomAttributeConversion( 'table', 'table', 'id', editor );\n }",
"addImagePreFilter() {\n this.addPreFilter('format=yuv420p');\n }",
"function renderPipelineFromConf(confs, cb) {\n\t _d2.default.json(confs, function (conf) {\n\t getPipelines(conf, function (pipelines) {\n\t renderPipeline(pipelines, cb);\n\t });\n\t });\n\t}",
"prepareTransformations() {\n\n let shouldTransform = (key) => {\n return typeof this.options.transformers[key] !== 'undefined' && this.options.transformers[key];\n };\n\n let doTransform = (key, transformation) => {\n if(shouldTransform(key)) {\n this.transformations.push(transformation);\n }\n };\n\n doTransform('classes', classTransformation);\n doTransform('stringTemplates', templateStringTransformation);\n doTransform('arrowFunctions', arrowFunctionTransformation);\n doTransform('let', letTransformation);\n doTransform('defaultArguments', defaultArgsTransformation);\n doTransform('objectMethods', objectMethodsTransformation);\n }",
"function ImageTransformer()\n{\n\t\n}",
"createPipe(presets) {\n const pipe = new Pipe({ config: this._config, presets, isUdp: this._transport === 'udp' });\n pipe.on('broadcast', this.onBroadcast.bind(this)); // if no action were caught by presets\n pipe.on(`pre_${PIPE_DECODE}`, this.onPreDecode);\n pipe.on(`post_${PIPE_ENCODE}`, this.onEncoded);\n pipe.on(`post_${PIPE_DECODE}`, this.onDecoded);\n return pipe;\n }",
"_setupAttachmentOptions() {\n for (var i = 0; i < this._keys.length; i++) {\n var k = this._keys[i];\n this._textures[k] = [];\n Object.assign(this._attachments[i],\n (({ format, type, target }) => ({format, type, target}))(this._textureOptions[k]));\n\n this._attachments[i].format = this._attachments[i].format || gl.RGBA;\n this._attachments[i].internalFormat = this._attachments[i].format || gl.RGBA;\n }\n }",
"registerDefaultConverters() {\n this.registerConverter('string', new ArgumentConverter(this.client));\n this.registerConverter('boolean', new BooleanConverter(this.client));\n this.registerConverter('integer', new NumberConverter(this.client, { isInteger: true }));\n this.registerConverter('number', new NumberConverter(this.client, { isInteger: false }));\n this.registerConverter('member', new UserConverter(this.client, { isMember: true }));\n this.registerConverter('user', new UserConverter(this.client, { isMember: false }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
vResult = ConvertFontFormat(vFont, nInType, nRetType); Arguments: vFont pointer to LOGFONTW structure, handle to font, or array [sFontName, nFontStyle, nFontSize] nInType vFont type, nRetType vResult type: 1 pointer to LOGFONTW structure 2 handle to font 3 array [sFontName, nFontStyle, nFontSize] | function ConvertFontFormat(vFont, nInType, nRetType)
{
var nLFSize = 28 + 32 * 2; //sizeof(LOGFONTW)
var lpLF = AkelPad.MemAlloc(nLFSize);
var hFont;
var hDC;
var nHeight;
var nWeight;
var bItalic;
var vRetVal;
var i;
if (nInType == 1)
{
for (i = 0; i < nLFSize; ++i)
AkelPad.MemCopy(lpLF + i, AkelPad.MemRead(vFont + i, 5 /*DT_BYTE*/), 5 /*DT_BYTE*/);
}
else if (nInType == 2)
{
if (! vFont)
vFont = AkelPad.SystemFunction().Call("Gdi32::GetStockObject", 13 /*SYSTEM_FONT*/);
AkelPad.SystemFunction().Call("Gdi32::GetObjectW", vFont, nLFSize, lpLF);
}
else if (nInType == 3)
{
hDC = AkelPad.SystemFunction().Call("User32::GetDC", AkelPad.GetMainWnd());
nHeight = -AkelPad.SystemFunction().Call("Kernel32::MulDiv", vFont[2], AkelPad.SystemFunction().Call("Gdi32::GetDeviceCaps", hDC, 90 /*LOGPIXELSY*/), 72);
AkelPad.SystemFunction().Call("User32::ReleaseDC", AkelPad.GetMainWnd(), hDC);
nWeight = 400;
bItalic = 0;
if ((vFont[1] == 2) || (vFont[1] == 4))
nWeight = 700;
if (vFont[1] > 2)
bItalic = 1;
AkelPad.MemCopy(lpLF, nHeight, 3 /*DT_DWORD*/); //lfHeight
AkelPad.MemCopy(lpLF + 16, nWeight, 3 /*DT_DWORD*/); //lfWeight
AkelPad.MemCopy(lpLF + 20, bItalic, 5 /*DT_BYTE*/); //lfItalic
AkelPad.MemCopy(lpLF + 28, vFont[0], 1 /*DT_UNICODE*/); //lfFaceName
}
if (nRetType == 1)
vRetVal = lpLF;
else if (nRetType == 2)
{
vRetVal = AkelPad.SystemFunction().Call("Gdi32::CreateFontIndirectW", lpLF);
AkelPad.MemFree(lpLF);
}
else if (nRetType == 3)
{
vRetVal = [];
vRetVal[0] = AkelPad.MemRead(lpLF + 28, 1 /*DT_UNICODE*/); //lfFaceName
nWeight = AkelPad.MemRead(lpLF + 16, 3 /*DT_DWORD*/); //lfWeight
bItalic = AkelPad.MemRead(lpLF + 20, 5 /*DT_BYTE*/); //lfItalic
if (nWeight < 600)
vRetVal[1] = 1;
else
vRetVal[1] = 2;
if (bItalic)
vRetVal[1] += 2;
hDC = AkelPad.SystemFunction().Call("User32::GetDC", AkelPad.GetMainWnd());
nHeight = AkelPad.MemRead(lpLF, 3 /*DT_DWORD*/); //lfHeight
vRetVal[2] = -AkelPad.SystemFunction().Call("Kernel32::MulDiv", nHeight, 72, AkelPad.SystemFunction().Call("Gdi32::GetDeviceCaps", hDC, 90 /*LOGPIXELSY*/));
AkelPad.SystemFunction().Call("User32::ReleaseDC", AkelPad.GetMainWnd(), hDC);
AkelPad.MemFree(lpLF);
}
return vRetVal;
} | [
"function ConvertFontFormat(vFont, nInType, nRetType)\n{\n var nLFSize = 28 + 32 * 2; //sizeof(LOGFONTW)\n var lpLF = AkelPad.MemAlloc(nLFSize);\n var hFont;\n var hDC;\n var nHeight;\n var nWeight;\n var bItalic;\n var vRetVal;\n var i;\n\n if (nInType == 1)\n {\n for (i = 0; i < nLFSize; ++i)\n AkelPad.MemCopy(lpLF + i, AkelPad.MemRead(vFont + i, DT_BYTE), DT_BYTE);\n }\n else if (nInType == 2)\n {\n if (! vFont)\n vFont = oSys.Call(\"Gdi32::GetStockObject\", 13 /*SYSTEM_FONT*/);\n\n oSys.Call(\"Gdi32::GetObjectW\", vFont, nLFSize, lpLF);\n }\n else if (nInType == 3)\n {\n hDC = oSys.Call(\"User32::GetDC\", hMainWnd);\n nHeight = -oSys.Call(\"Kernel32::MulDiv\", vFont[2], oSys.Call(\"Gdi32::GetDeviceCaps\", hDC, 90 /*LOGPIXELSY*/), 72);\n oSys.Call(\"User32::ReleaseDC\", hMainWnd, hDC);\n\n nWeight = 400;\n bItalic = 0;\n if ((vFont[1] == 2) || (vFont[1] == 4))\n nWeight = 700;\n if (vFont[1] > 2)\n bItalic = 1;\n\n AkelPad.MemCopy(lpLF , nHeight, DT_DWORD); //lfHeight\n AkelPad.MemCopy(lpLF + 16, nWeight, DT_DWORD); //lfWeight\n AkelPad.MemCopy(lpLF + 20, bItalic, DT_BYTE); //lfItalic\n AkelPad.MemCopy(lpLF + 28, vFont[0], DT_UNICODE); //lfFaceName\n }\n\n if (nRetType == 1)\n vRetVal = lpLF;\n else if (nRetType == 2)\n {\n vRetVal = oSys.Call(\"Gdi32::CreateFontIndirectW\", lpLF);\n AkelPad.MemFree(lpLF);\n }\n else if (nRetType == 3)\n {\n vRetVal = [];\n vRetVal[0] = AkelPad.MemRead(lpLF + 28, DT_UNICODE); //lfFaceName\n\n nWeight = AkelPad.MemRead(lpLF + 16, DT_DWORD); //lfWeight\n bItalic = AkelPad.MemRead(lpLF + 20, DT_BYTE); //lfItalic\n\n if (nWeight < 600)\n vRetVal[1] = 1;\n else\n vRetVal[1] = 2;\n\n if (bItalic)\n vRetVal[1] += 2;\n\n hDC = oSys.Call(\"User32::GetDC\", hMainWnd);\n nHeight = AkelPad.MemRead(lpLF, DT_DWORD); //lfHeight\n vRetVal[2] = -oSys.Call(\"Kernel32::MulDiv\", nHeight, 72, oSys.Call(\"Gdi32::GetDeviceCaps\", hDC, 90 /*LOGPIXELSY*/));\n oSys.Call(\"User32::ReleaseDC\", hMainWnd, hDC); \n AkelPad.MemFree(lpLF);\n }\n\n return vRetVal;\n}",
"function ChooseFont(hWndOwn, nIniType, vIniVal, bEffects, bFixedPitchOnly, nResultType)\n{\n var CF_EFFECTS = 0x00000100;\n var CF_ENABLEHOOK = 0x00000008;\n var CF_FIXEDPITCHONLY = 0x00004000;\n var CF_FORCEFONTEXIST = 0x00010000;\n var CF_INITTOLOGFONTSTRUCT = 0x00000040;\n var CF_SCREENFONTS = 0x00000001;\n\n var hWndDesk = AkelPad.SystemFunction().Call(\"User32::GetDesktopWindow\");\n var lpCallback = AkelPad.SystemFunction().RegisterCallback(0, CFCallback, 4);\n var nFlags = CF_ENABLEHOOK | CF_FORCEFONTEXIST | CF_SCREENFONTS;\n var nCFSize = _X64 ? 104 : 60; //sizeof(CHOOSEFONT)\n var lpCF = AkelPad.MemAlloc(nCFSize);\n var lpLF;\n var vResult;\n var i;\n\n if (! AkelPad.SystemFunction().Call(\"User32::IsWindow\", hWndOwn))\n hWndOwn = hWndDesk;\n\n if (nIniType && vIniVal)\n {\n if (nIniType == 4) //handle to window\n lpLF = ConvertFontFormat(AkelPad.SystemFunction().Call(\"User32::SendMessageW\", vIniVal, 0x0031 /*WM_GETFONT*/, 0, 0), 2, 1);\n else\n lpLF = ConvertFontFormat(vIniVal, nIniType, 1);\n }\n\n if (lpLF)\n nFlags |= CF_INITTOLOGFONTSTRUCT;\n else\n lpLF = AkelPad.MemAlloc(28 + 32 * 2 /*sizeof(LOGFONTW)*/);\n\n if (bEffects)\n nFlags |= CF_EFFECTS;\n\n if (bFixedPitchOnly)\n nFlags |= CF_FIXEDPITCHONLY;\n\n AkelPad.MemCopy(lpCF, nCFSize, 3 /*DT_DWORD*/); //lStructSize\n AkelPad.MemCopy(lpCF + (_X64 ? 8 : 4), hWndOwn, 2 /*DT_QWORD*/); //hwndOwner\n AkelPad.MemCopy(lpCF + (_X64 ? 24 : 12), lpLF, 2 /*DT_QWORD*/); //lpLogFont\n AkelPad.MemCopy(lpCF + (_X64 ? 36 : 20), nFlags, 3 /*DT_DWORD*/); //Flags\n AkelPad.MemCopy(lpCF + (_X64 ? 56 : 32), lpCallback, 2 /*DT_QWORD*/); //lpfnHook\n\n if (AkelPad.SystemFunction().Call(\"Comdlg32::ChooseFontW\", lpCF))\n {\n if (nResultType == 1) //pointer to LOGFONTW\n vResult = lpLF;\n else //handle to font or array\n {\n vResult = ConvertFontFormat(lpLF, 1, nResultType);\n AkelPad.MemFree(lpLF);\n }\n }\n else\n {\n vResult = 0;\n AkelPad.MemFree(lpLF);\n }\n\n AkelPad.SystemFunction().UnregisterCallback(lpCallback);\n AkelPad.MemFree(lpCF);\n\n return vResult;\n\n function CFCallback(hWnd, uMsg, wParam, lParam)\n {\n if (uMsg == 272 /*WM_INITDIALOG*/)\n {\n var lpRect = AkelPad.MemAlloc(16); //sizeof(RECT)\n var sTitle;\n var nTextLen;\n var lpText;\n var nWndX, nWndY, nWndW, nWndH;\n var nOwnX, nOwnY, nOwnW, nOwnH;\n var nDeskW, nDeskH;\n\n //dialog title\n if (bFixedPitchOnly)\n {\n nTextLen = AkelPad.SystemFunction().Call(\"User32::SendMessageW\", hWnd, 0x000E /*WM_GETTEXTLENGTH*/, 0, 0);\n sTitle = \" [Monospace]\";\n lpText = AkelPad.MemAlloc((nTextLen + sTitle.length + 1) * 2);\n\n AkelPad.SystemFunction().Call(\"User32::SendMessageW\", hWnd, 0x000D /*WM_GETTEXT*/, nTextLen + 1, lpText);\n AkelPad.MemCopy(lpText + nTextLen * 2, sTitle, 1 /*DT_UNICODE*/);\n AkelPad.SystemFunction().Call(\"User32::SendMessageW\", hWnd, 0x000C /*WM_SETTEXT*/, 0, lpText);\n AkelPad.MemFree(lpText);\n }\n\n //center dialog\n AkelPad.SystemFunction().Call(\"User32::GetWindowRect\", hWnd, lpRect);\n nWndX = AkelPad.MemRead(lpRect, 3 /*DT_DWORD*/);\n nWndY = AkelPad.MemRead(lpRect + 4, 3 /*DT_DWORD*/);\n nWndW = AkelPad.MemRead(lpRect + 8, 3 /*DT_DWORD*/) - nWndX;\n nWndH = AkelPad.MemRead(lpRect + 12, 3 /*DT_DWORD*/) - nWndY;\n\n AkelPad.SystemFunction().Call(\"User32::GetWindowRect\", hWndOwn, lpRect);\n nOwnX = AkelPad.MemRead(lpRect, 3 /*DT_DWORD*/);\n nOwnY = AkelPad.MemRead(lpRect + 4, 3 /*DT_DWORD*/);\n nOwnW = AkelPad.MemRead(lpRect + 8, 3 /*DT_DWORD*/) - nOwnX;\n nOwnH = AkelPad.MemRead(lpRect + 12, 3 /*DT_DWORD*/) - nOwnY;\n\n AkelPad.SystemFunction().Call(\"User32::GetWindowRect\", hWndDesk, lpRect);\n nDeskW = AkelPad.MemRead(lpRect + 8, 3 /*DT_DWORD*/);\n nDeskH = AkelPad.MemRead(lpRect + 12, 3 /*DT_DWORD*/);\n AkelPad.MemFree(lpRect);\n\n nWndX = nOwnX + (nOwnW - nWndW) / 2;\n nWndY = nOwnY + (nOwnH - nWndH) / 2;\n\n if ((nWndX + nWndW) > nDeskW)\n nWndX = nDeskW - nWndW;\n if (nWndX < 0)\n nWndX = 0;\n if ((nWndY + nWndH) > nDeskH)\n nWndY = nDeskH - nWndH;\n if (nWndY < 0)\n nWndY = 0;\n\n AkelPad.SystemFunction().Call(\"User32::MoveWindow\", hWnd, nWndX, nWndY, nWndW, nWndH, 0);\n }\n\n return 0;\n }\n}",
"function parse_BrtFont(data,length,opts){var out={};out.sz=data.read_shift(2)/20;var grbit=parse_FontFlags(data,2,opts);if(grbit.fItalic)out.italic=1;if(grbit.fCondense)out.condense=1;if(grbit.fExtend)out.extend=1;if(grbit.fShadow)out.shadow=1;if(grbit.fOutline)out.outline=1;if(grbit.fStrikeout)out.strike=1;var bls=data.read_shift(2);if(bls===0x02BC)out.bold=1;switch(data.read_shift(2)){/* case 0: out.vertAlign = \"baseline\"; break; */case 1:out.vertAlign=\"superscript\";break;case 2:out.vertAlign=\"subscript\";break;}var underline=data.read_shift(1);if(underline!=0)out.underline=underline;var family=data.read_shift(1);if(family>0)out.family=family;var bCharSet=data.read_shift(1);if(bCharSet>0)out.charset=bCharSet;data.l++;out.color=parse_BrtColor(data,8);switch(data.read_shift(1)){/* case 0: out.scheme = \"none\": break; */case 1:out.scheme=\"major\";break;case 2:out.scheme=\"minor\";break;}out.name=parse_XLWideString(data,length-21);return out;}",
"function converter(inputFontFile,outPutFontFile,format){\n console.log('input file path',inputFontFile);\n console.log('output file path',outPutFontFile);\n if(process.platform=='darwin'){\n console.log('Mac platform')\n shelljs.exec(`${process.env.PWD}/lib/osx/subset -i ${inputFontFile} -o ${outPutFontFile} ${format}`)\n }else if(process.platform=='linux'){\n console.log('Linux platform')\n shelljs.exec(`${process.env.PWD}/lib/linux/x64//subset -i ${inputFontFile} -o ${outPutFontFile} ${format}`)\n }\n}",
"toFontArray(font) {\n\t\t\n\t\tvar initFontArr = ['normal', '10px', 'sans-serif'];\n\t\tDFS(font, initFontArr, 0);\n\t\treturn initFontArr;\n\t\tfunction DFS(font, fontArr, cnt){\n\t\t\tif (font === \"\" || cnt > 2) return;\n\t\t\tvar rhb = font.indexOf(' ');\n\t\t\trhb = (rhb !== -1) ? rhb : font.length;\n\t\t\t\tlet curr =\tfont.substring(0,rhb);\n\t\t\t\tlet idx = isWhichPartOfFont (curr)\n\t\t\t\tfontArr[idx] = curr;\n\t\t\t\tDFS (font.substring(rhb+1), fontArr, cnt++);\n\t\t\t\n\t\t}\n\t\t\n\t\tfunction isWhichPartOfFont (part) {\n\t\t\tlet fontWeightArr = ['normal', 'bold'];\n\t\t\tif (part.indexOf('px') > 0 ) {\n\t\t\t\treturn 1;\n\t\t\t} else if (fontWeightArr.indexOf(part.toLowerCase()) > -1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t}",
"function ui_getFont(font, fontsize)\n{\n var base_10 = 10;\n return fontsize.toString(base_10) + \"px\" + \" \" + font;\n}",
"function fontToSfntTable(font) {\n var xMins = [];\n var yMins = [];\n var xMaxs = [];\n var yMaxs = [];\n var advanceWidths = [];\n var leftSideBearings = [];\n var rightSideBearings = [];\n var firstCharIndex;\n var lastCharIndex = 0;\n var ulUnicodeRange1 = 0;\n var ulUnicodeRange2 = 0;\n var ulUnicodeRange3 = 0;\n var ulUnicodeRange4 = 0;\n\n for (var i = 0; i < font.glyphs.length; i += 1) {\n var glyph = font.glyphs.get(i);\n var unicode = glyph.unicode | 0;\n\n if (isNaN(glyph.advanceWidth)) {\n throw new Error(\n 'Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'\n );\n }\n\n if (firstCharIndex > unicode || firstCharIndex === undefined) {\n // ignore .notdef char\n if (unicode > 0) {\n firstCharIndex = unicode;\n }\n }\n\n if (lastCharIndex < unicode) {\n lastCharIndex = unicode;\n }\n\n var position = os2.getUnicodeRange(unicode);\n if (position < 32) {\n ulUnicodeRange1 |= 1 << position;\n } else if (position < 64) {\n ulUnicodeRange2 |= 1 << (position - 32);\n } else if (position < 96) {\n ulUnicodeRange3 |= 1 << (position - 64);\n } else if (position < 123) {\n ulUnicodeRange4 |= 1 << (position - 96);\n } else {\n throw new Error(\n 'Unicode ranges bits > 123 are reserved for internal usage'\n );\n }\n // Skip non-important characters.\n if (glyph.name === '.notdef') {\n continue;\n }\n var metrics = glyph.getMetrics();\n xMins.push(metrics.xMin);\n yMins.push(metrics.yMin);\n xMaxs.push(metrics.xMax);\n yMaxs.push(metrics.yMax);\n leftSideBearings.push(metrics.leftSideBearing);\n rightSideBearings.push(metrics.rightSideBearing);\n advanceWidths.push(glyph.advanceWidth);\n }\n\n var globals = {\n xMin: Math.min.apply(null, xMins),\n yMin: Math.min.apply(null, yMins),\n xMax: Math.max.apply(null, xMaxs),\n yMax: Math.max.apply(null, yMaxs),\n advanceWidthMax: Math.max.apply(null, advanceWidths),\n advanceWidthAvg: average(advanceWidths),\n minLeftSideBearing: Math.min.apply(null, leftSideBearings),\n maxLeftSideBearing: Math.max.apply(null, leftSideBearings),\n minRightSideBearing: Math.min.apply(null, rightSideBearings)\n };\n globals.ascender = font.ascender;\n globals.descender = font.descender;\n\n var headTable = head.make({\n flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)\n unitsPerEm: font.unitsPerEm,\n xMin: globals.xMin,\n yMin: globals.yMin,\n xMax: globals.xMax,\n yMax: globals.yMax,\n lowestRecPPEM: 3,\n createdTimestamp: font.createdTimestamp\n });\n\n var hheaTable = hhea.make({\n ascender: globals.ascender,\n descender: globals.descender,\n advanceWidthMax: globals.advanceWidthMax,\n minLeftSideBearing: globals.minLeftSideBearing,\n minRightSideBearing: globals.minRightSideBearing,\n xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),\n numberOfHMetrics: font.glyphs.length\n });\n\n var maxpTable = maxp.make(font.glyphs.length);\n\n var os2Table = os2.make({\n xAvgCharWidth: Math.round(globals.advanceWidthAvg),\n usWeightClass: font.tables.os2.usWeightClass,\n usWidthClass: font.tables.os2.usWidthClass,\n usFirstCharIndex: firstCharIndex,\n usLastCharIndex: lastCharIndex,\n ulUnicodeRange1: ulUnicodeRange1,\n ulUnicodeRange2: ulUnicodeRange2,\n ulUnicodeRange3: ulUnicodeRange3,\n ulUnicodeRange4: ulUnicodeRange4,\n fsSelection: font.tables.os2.fsSelection, // REGULAR\n // See http://typophile.com/node/13081 for more info on vertical metrics.\n // We get metrics for typical characters (such as \"x\" for xHeight).\n // We provide some fallback characters if characters are unavailable: their\n // ordering was chosen experimentally.\n sTypoAscender: globals.ascender,\n sTypoDescender: globals.descender,\n sTypoLineGap: 0,\n usWinAscent: globals.yMax,\n usWinDescent: Math.abs(globals.yMin),\n ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now\n sxHeight: metricsForChar(font, 'xyvw', {\n yMax: Math.round(globals.ascender / 2)\n }).yMax,\n sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals)\n .yMax,\n usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.\n usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available.\n });\n\n var hmtxTable = hmtx.make(font.glyphs);\n var cmapTable = cmap.make(font.glyphs);\n\n var englishFamilyName = font.getEnglishName('fontFamily');\n var englishStyleName = font.getEnglishName('fontSubfamily');\n var englishFullName = englishFamilyName + ' ' + englishStyleName;\n var postScriptName = font.getEnglishName('postScriptName');\n if (!postScriptName) {\n postScriptName =\n englishFamilyName.replace(/\\s/g, '') + '-' + englishStyleName;\n }\n\n var names = {};\n for (var n in font.names) {\n names[n] = font.names[n];\n }\n\n if (!names.uniqueID) {\n names.uniqueID = {\n en: font.getEnglishName('manufacturer') + ':' + englishFullName\n };\n }\n\n if (!names.postScriptName) {\n names.postScriptName = { en: postScriptName };\n }\n\n if (!names.preferredFamily) {\n names.preferredFamily = font.names.fontFamily;\n }\n\n if (!names.preferredSubfamily) {\n names.preferredSubfamily = font.names.fontSubfamily;\n }\n\n var languageTags = [];\n var nameTable = _name.make(names, languageTags);\n var ltagTable =\n languageTags.length > 0 ? ltag.make(languageTags) : undefined;\n\n var postTable = post.make();\n var cffTable = cff.make(font.glyphs, {\n version: font.getEnglishName('version'),\n fullName: englishFullName,\n familyName: englishFamilyName,\n weightName: englishStyleName,\n postScriptName: postScriptName,\n unitsPerEm: font.unitsPerEm,\n fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]\n });\n\n var metaTable =\n font.metas && Object.keys(font.metas).length > 0\n ? meta.make(font.metas)\n : undefined;\n\n // The order does not matter because makeSfntTable() will sort them.\n var tables = [\n headTable,\n hheaTable,\n maxpTable,\n os2Table,\n nameTable,\n cmapTable,\n postTable,\n cffTable,\n hmtxTable\n ];\n if (ltagTable) {\n tables.push(ltagTable);\n }\n // Optional tables\n if (font.tables.gsub) {\n tables.push(gsub.make(font.tables.gsub));\n }\n if (metaTable) {\n tables.push(metaTable);\n }\n\n var sfntTable = makeSfntTable(tables);\n\n // Compute the font's checkSum and store it in head.checkSumAdjustment.\n var bytes = sfntTable.encode();\n var checkSum = computeCheckSum(bytes);\n var tableFields = sfntTable.fields;\n var checkSumAdjusted = false;\n for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) {\n if (tableFields[i$1].name === 'head table') {\n tableFields[i$1].value.checkSumAdjustment = 0xb1b0afba - checkSum;\n checkSumAdjusted = true;\n break;\n }\n }\n\n if (!checkSumAdjusted) {\n throw new Error('Could not find head table with checkSum to adjust.');\n }\n\n return sfntTable;\n }",
"get font() {}",
"function modifyFontFamily(fontStyle)\n{\n\tvar f = fontStyle.split(\",\");\n\tvar ret = \"\";\n\tfor (x in f)\n\t{\n\t\tif (f[x].toLowerCase().trim() == \"helvetica\" || f[x].toLowerCase().trim() == \"\\\"lucida grande\\\"\")\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tret = ret.concat(f[x].trim() + \",\");\n\t\t}\n\t}\n\t\n\t// strip trailing ','\n\tret = ret.substring(0, ret.length - 1);\n\treturn ret;\n}",
"static getTextFontFromVexFontData(fd) {\n let i = 0;\n let selectedFont = null;\n const fallback = TextFont.fontRegistry[0];\n let candidates = [];\n const families = fd.family.split(',');\n for (i = 0; i < families.length; ++i) {\n const famliy = families[i];\n candidates = TextFont.fontRegistry.filter((font) => font.family === famliy);\n if (candidates.length) {\n break;\n }\n }\n if (candidates.length === 0) {\n selectedFont = new TextFont(fallback);\n } else if (candidates.length === 1) {\n selectedFont = new TextFont(candidates[0]);\n } else {\n const bold = TextFont.fontWeightToBold(fd.weight);\n const italic = TextFont.fontStyleToItalic(fd.style);\n const perfect = candidates.find((font) => font.bold === bold && font.italic === italic);\n if (perfect) {\n selectedFont = new TextFont(perfect);\n } else {\n const ok = candidates.find((font) => font.italic === italic || font.bold === bold);\n if (ok) {\n selectedFont = new TextFont(ok);\n } else {\n selectedFont = new TextFont(candidates[0]);\n }\n }\n }\n if (typeof fd.size === 'number' && fd.size > 0) {\n selectedFont.setFontSize(fd.size);\n }\n return selectedFont;\n }",
"function parseBuffer(buffer){var indexToLocFormat;var hmtxOffset;var glyfOffset;var locaOffset;var cffOffset;var kernOffset;var gposOffset;// OpenType fonts use big endian byte ordering.\n// We can't rely on typed array view types, because they operate with the endianness of the host computer.\n// Instead we use DataViews where we can specify endianness.\nvar font=new _font.Font();var data=new DataView(buffer,0);var version=parse.getFixed(data,0);if(version===1.0){font.outlinesFormat='truetype';}else{version=parse.getTag(data,0);if(version==='OTTO'){font.outlinesFormat='cff';}else{throw new Error('Unsupported OpenType version '+version);}}var numTables=parse.getUShort(data,4);// Offset into the table records.\nvar p=12;for(var i=0;i<numTables;i+=1){var tag=parse.getTag(data,p);var offset=parse.getULong(data,p+8);switch(tag){case'cmap':font.tables.cmap=cmap.parse(data,offset);font.encoding=new encoding.CmapEncoding(font.tables.cmap);if(!font.encoding){font.supported=false;}break;case'head':font.tables.head=head.parse(data,offset);font.unitsPerEm=font.tables.head.unitsPerEm;indexToLocFormat=font.tables.head.indexToLocFormat;break;case'hhea':font.tables.hhea=hhea.parse(data,offset);font.ascender=font.tables.hhea.ascender;font.descender=font.tables.hhea.descender;font.numberOfHMetrics=font.tables.hhea.numberOfHMetrics;break;case'hmtx':hmtxOffset=offset;break;case'maxp':font.tables.maxp=maxp.parse(data,offset);font.numGlyphs=font.tables.maxp.numGlyphs;break;case'name':font.tables.name=_name.parse(data,offset);font.familyName=font.tables.name.fontFamily;font.styleName=font.tables.name.fontSubfamily;break;case'OS/2':font.tables.os2=os2.parse(data,offset);break;case'post':font.tables.post=post.parse(data,offset);font.glyphNames=new encoding.GlyphNames(font.tables.post);break;case'glyf':glyfOffset=offset;break;case'loca':locaOffset=offset;break;case'CFF ':cffOffset=offset;break;case'kern':kernOffset=offset;break;case'GPOS':gposOffset=offset;break;}p+=16;}if(glyfOffset&&locaOffset){var shortVersion=indexToLocFormat===0;var locaTable=loca.parse(data,locaOffset,font.numGlyphs,shortVersion);font.glyphs=glyf.parse(data,glyfOffset,locaTable,font);hmtx.parse(data,hmtxOffset,font.numberOfHMetrics,font.numGlyphs,font.glyphs);encoding.addGlyphNames(font);}else if(cffOffset){cff.parse(data,cffOffset,font);encoding.addGlyphNames(font);}else{font.supported=false;}if(font.supported){if(kernOffset){font.kerningPairs=kern.parse(data,kernOffset);}else{font.kerningPairs={};}if(gposOffset){gpos.parse(data,gposOffset,font);}}return font;}// Asynchronously load the font from a URL or a filesystem. When done, call the callback",
"function stbtt_InitFont(font, data, offset) {\n return stbtt_InitFont_internal(font, data, offset);\n}",
"static processFontStyle(element,valueNew){return TcHmi.System.Services.styleManager.processFontStyle(element,valueNew)}",
"get fontStyle() {}",
"function font(style) {\n\t return draw(function () {\n\t if (exports.DEBUG)\n\t console.log(\"font: attach\");\n\t var arg1_next = Parameter.from(style).init();\n\t return function (tick) {\n\t var arg1 = arg1_next(tick.clock);\n\t if (exports.DEBUG)\n\t console.log(\"font: font\", arg1);\n\t tick.ctx.font = arg1;\n\t };\n\t });\n\t}",
"static processFontFamily(element,valueNew){return TcHmi.System.Services.styleManager.processFontFamily(element,valueNew)}",
"function parse_BrtFont(data, length) {\n\tvar out = {flags:{}};\n\tout.dyHeight = data.read_shift(2);\n\tout.grbit = parse_FontFlags(data, 2);\n\tout.bls = data.read_shift(2);\n\tout.sss = data.read_shift(2);\n\tout.uls = data.read_shift(1);\n\tout.bFamily = data.read_shift(1);\n\tout.bCharSet = data.read_shift(1);\n\tdata.l++;\n\tout.brtColor = parse_BrtColor(data, 8);\n\tout.bFontScheme = data.read_shift(1);\n\tout.name = parse_XLWideString(data, length - 21);\n\n\tout.flags.Bold = out.bls === 0x02BC;\n\tout.flags.Italic = out.grbit.fItalic;\n\tout.flags.Strikeout = out.grbit.fStrikeout;\n\tout.flags.Outline = out.grbit.fOutline;\n\tout.flags.Shadow = out.grbit.fShadow;\n\tout.flags.Condense = out.grbit.fCondense;\n\tout.flags.Extend = out.grbit.fExtend;\n\tout.flags.Sub = out.sss & 0x2;\n\tout.flags.Sup = out.sss & 0x1;\n\treturn out;\n}",
"buildfont( fontParams ){\n let font = fontParams.fontSize + 'px';\n font += ' ' + fontParams.font;\n fontParams.italic ? font = 'italic ' + font : null;\n fontParams.bold ? font = 'bold ' + font : null;\n return font;\n }",
"function font(style) {\n return draw(function () {\n if (exports.DEBUG)\n console.log(\"font: attach\");\n var arg1_next = Parameter.from(style).init();\n return function (tick) {\n var arg1 = arg1_next(tick.clock);\n if (exports.DEBUG)\n console.log(\"font: font\", arg1);\n tick.ctx.font = arg1;\n };\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run fungsi imgInfo fungsi untuk validasi + meneruskan submit ke fungsi selanjutnya | function imgInfo(){
var jumImg = $('.imgTR:visible','#imgTB').length; //hitung jumlah gambar bkeg bukeg dalam form
if(jumImg==0){// ksong
$('#imgInfo').fadeIn(function(){
$('#imgInfo').html('minimal unggah 1 bukti kegiatan(scan/gambar)'); //notif eror =>harus browse gambar
});
//efek untuk menghilangkan notif secara perlahan dalam interval 3000 milisecond = 3 detik
setTimeout(function(){
$('#imgInfo').fadeOut(1000,function(){
$('#imgInfo').html('');
});
},3000);
}else{ // ada gambar
$('#imgInfo').html('');
//tipe submit (add or edit )
var iddtk = $('#idformTB').val();
if(iddtk>0){ //edit data
if(jumDel==0 && jumAdd==0){ // 0 0
uploadFiles('edit','','',iddtk); //panggil fungsi uploadFiles
console.log('edit : 0 0');
}else if (jumAdd>0 && jumDel==0){ // + 0
uploadFiles('edit',filesAdd,'',iddtk);
console.log('edit : + 0');
}else if(jumAdd==0 && jumDel>0){ // 0 -
uploadFiles('edit','',filesDel,iddtk);
console.log('edit : 0 -');
}else{ // + -
uploadFiles('edit',filesAdd,filesDel,iddtk);
console.log('edit : + -');
}
}else{ // add data
uploadFiles('add',filesAdd,'','');
console.log('add : + 0'); // + 0
}
}
} | [
"async checkImageUpload () {\n I.waitForElement(this.form.frmPinBuilderDraft);\n const responseCode = await I.grabNumberOfVisibleElements(this.form.frmPinImage);\n if (responseCode < '1') {\n I.say('Image retrieved from coolImages library not found');\n I.click(this.button.btnCancel);\n I.attachFile(this.button.btnAttachImage, '/helpers/data/image/valletta-image.jpg')\n }\n else {\n I.waitForVisible(this.form.frmPinImage);\n I.click(this.form.frmPinImage);\n I.click(this.button.btnAddToPin);\n }\n }",
"function onOk() {\n\t\tform.validateFields()\n\t\t\t.then((values) => {\n\t\t\t\tparams.changeLoading(true);\n\t\t\t\tvalues.image = params.fileList[0].originFileObj;\n\t\t\t\tparams.onCreate(values);\n\t\t\t})\n\t\t\t.catch((info) => {\n\t\t\t\tconsole.log(\"Validate Failed:\", info);\n\t\t\t});\n\t}",
"function checkImage(input) {\n\n}",
"function imageValidationAndPreview(imageThis,imageFieldId,imageDisplayClass,isImageTag,isImageSizeCheck,imageWidthValid,imageHeightValid){\r\n\t\r\n\tvar imageValidationFlag\t\t=\timageValidation(imageThis,imageFieldId,imageDisplayClass,isImageTag);\r\n\tif(imageValidationFlag == 1){\r\n\t\treadURL(imageThis,imageFieldId,imageDisplayClass,isImageTag,isImageSizeCheck,imageWidthValid,imageHeightValid);\r\n\t}\r\n}",
"function submitImage() {\n let image = document.querySelector('input[type=file]').files[0];\n if (image) {\n encodeImageFileAsURL(image);\n } else {\n errorMessage(\"No Selected File\");\n }\n }",
"function submit() {\n var imageCount = $$(\"input.uploadBtn\")[0].files.length;\n if ((imageCount != null) && (imageCount > 0)) {\n console.log(\"saveImagesAndPost\");\n saveImagesAndPost(data);\n } else {\n // now user must post things with a photo!\n // console.log(\"saveOnlyPost\");\n // savePost(data);\n myApp.hideIndicator();\n myApp.alert('You need to pick a photo for this post. :(', 'Error');\n }\n }",
"validationImage(){\n let imagesValue = this.listImages.innerHTML;\n \n let text = document.querySelector('input[type=\"file\"]').value;\n let res = text.slice(12,300);\n let pos = imagesValue.indexOf(res);\n \n //!!! c'est juste une recommandation pas une obligation d'avoir la meme image\n if (pos < 0) {\n this.imagePossibleValidate.style.display = \"block\";\n this.imagePossibleValidateP.innerHTML = \"Cette image n'a jamais été utilisé, c'est parfait\"\n this.imagePossibleValidateButton.style.display = \"block\";\n this.imageValidate = true;\n } else {\n this.imagePossibleValidate.style.display = \"block\";\n this.imagePossibleValidateP.innerHTML = \" cette image a deja été utilsé , faites attention\"\n this.imagePossibleValidateButton.style.display = \"block\";\n this.imageValidate = true;\n }\n }",
"function submitURL() {\n let urlInput = document.getElementById(\"urlInput\");\n let url = urlInput.value;\n let urlRegex = /^.+\\.(png|jpg)$/;\n let regexResults = url.match(urlRegex);\n if (regexResults.length == 1) {\n toDataURL(url, sendImageAsString);\n } else {\n urlInput.value = \"\";\n errorMessage(\"Invalid URL \" + regexResults);\n }\n }",
"imageProcessed(img, eventname) {\n\t\tthis.allpictures.insert(img);\n\t\tconsole.log('image processed ' + this.allpictures.stuff.length + eventname);\n\t\tif (this.allpictures.stuff.length === this.num_Images * this.categories.length) {\n\t\t\talert('fim do processamento');\n\t\t\tthis.createXMLColordatabaseLS();\n\t\t\tthis.createXMLIExampledatabaseLS();\n\t\t}\n\t}",
"function wifxAddImageInfo()\n{\n var wifx = WebImageFX.instances[0].editor;\n var name = \"uploadfilephoto\";\n wifxAddFormField(name + \"_height\", wifx.GetImageInformation(\"height\"), false);\n wifxAddFormField(name + \"_width\", wifx.GetImageInformation(\"width\"), false);\n}",
"function cameraSuccess(imgData) {\n myApp.modal({\n title: 'Submit a photo',\n // text: 'Check and make sure this is the correct image you want to submit. Then type a message you want to go along with this image (250 Characters):',\n afterText: //'<form action=\"\">' +\n \"<center>\" + '<img height=\"150\" style=\"display:block;verticle-align:middle;\"'\n + 'id=\"img_ph\" src=\"\" alt=\"FAILURE\" />' + \"</center>\" +\n '<input type=\"text\" name=\"message\" placeholder=\"Description\" class=\"myText\" maxlength=\"250\"><br>',\n // '<input type=\"submit\" value \"Send\">' +\n //'</form>',\n buttons: [\n {\n text: 'Cancel',\n onClick: function() { }\n },\n {\n text: 'Submit', id: '#submitImg',\n onClick: function() {\n\n }\n }\n ],\n \n})\n// Changes the img 'img_ph' src tag to the image selected so that it is displayed \n// in the modal for submission.\n var image = document.getElementById('img_ph');\n img_ph.style.display = 'block';\n image.src = \"data:image/jpeg;base64,\" + imgData;\n}",
"function submitURL() {\n let urlInput = document.getElementById(\"urlInput\");\n let url = urlInput.value;\n let urlRegex = /^.+\\.(png|jpg)$/;\n let regexResults = url.match(urlRegex);\n if (regexResults.length > 0) {\n let currentImg = document.getElementById(\"currentImg\");\n currentImg.src = url;\n queryExternalImg(url);\n } else {\n urlInput.value = \"\";\n errorMessage(\"Invalid URL \" + regexResults);\n }\n }",
"function useImageUpload(){\n\n $('#actionArea').empty().append(\n 'Select a picture from your device<br>'+\n '<input id=\"selectImg\" type=\"file\"/><br>'+\n '<img src=\"\"><br>'+\n '<button class=\"submit-btn\" style=\"display: none\">Send picture</button>'\n );\n\n var selectImg = document.querySelector(\"input\");\n var img = document.querySelector(\"img\");\n var submitBtn = document.querySelector('.submit-btn');\n var fr = new FileReader();\n\n submitBtn.addEventListener('click', sendToServer, false);\n\n fr.onload = function(e){\n img.src = this.result; \n $(submitBtn).css('display','');\n };\n\n selectImg.addEventListener(\"change\", function(){\n hideBanana();\n fr.readAsDataURL(selectImg.files[0]);\n });\n\n function sendToServer(){\n var imgData = img.src;\n $.post('./verify',{ img: imgData }, function(data){\n if(data){\n showBanana(img, data);\n }\n });\n }\n }",
"function check_image() {\n var im = document.getElementById(\"image_form\").elements.namedItem(\"image_src\").value;\n\n var image = new Image();\n image.src = im;\n\n image.onload = function() {\n if (this.width > 0) {\n alert(\"IMAGE SRC OK - CLICK 'ADD IMAGE' TO SUBMIT\"); }};\n\n image.onerror = function() {\n alert(\"IMAGE SRC INCORRECT - CHECK URL AND RE-ENTER\"); }; \n}",
"function submit(evt) {\n evt.preventDefault( );\n \n var locationName = $( \"#location\" ).val();\n var i = 0;\n var coordinates;\n \n for(var i = 0; i <locationsArray.length; i++) { \n if (locationName == locationsArray[i].loc){ \n coordinates = locationsArray[i].coord; \n image1 = locationsArray[i].image1;\n image2 = locationsArray[i].image2;\n }\n }\n \n setLocation(coordinates, locationName);\n buildImages(image1, image2);\n}",
"processImage(image) {\n // TODO:\n }",
"function capturarSuccessFachada(imageCaminho) { \n // capturando o valor base64 da imagem\n convertFileToDataURLviaFileReader(imageCaminho, function(dataUri) {\n imagemURL_app_fachada = dataUri;\n });\n \n imagemURL_fachada = imageCaminho;\n // verificando se está editando o imovel\n if (editandoImovel){\n img = document.getElementById('imgEdit_fachada');\n } else if (novaUnidadeImovel){\n img = document.getElementById('imgNew_fachada');\n } else {\n img = document.getElementById('img_fachada');\n }\n img.innerHTML = '<span>Fachada:</span><br/><img src=\"' + imageCaminho + '\" />';\n}",
"function onsubmit(e){\n //preventDefault cancela el evento que se dispara por defecto para poder modificarlo \n //en este caso onsubmit busca el action y method pero con preventDefault cancenla esto \n e.preventDefault();\n //this hace referencia al formulario en si ya que el evento onsubmit es lanzado hacia en el formulario\n var data = new FormData(this);\n //Esta utilizando la libreria superagent para subir a las imagenes\n request\n //es para enviarle data a api/pictures\n .post('/api/pictures')\n //atravez de send enviamos la data\n .send(data)\n //cuando tengamos la respuesta se hara un console.lo\n .end(function (err, res){\n //argments es un array con todos los parametros que recibe \n console.log(arguments);\n })\n\n}",
"function checkImageExists() {\n add_form.image.className = \"valid\"\n document.getElementById('image-validation').innerHTML = \"\";\n var file_path = add_form.image.value;\n var img = document.createElement('img');\n img.setAttribute('src', file_path);\n img.onerror = function() {\n\n document.getElementById('image-validation').innerHTML = \"The image address is incorrect.\";\n add_form.image.className = \"notvalid\"\n return false\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2 Write a function `everyThird` that takes an array as an argument and returns a new array that contains every third element of the original array. everyThird(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']); returns ['c','f','i'] everyThird([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) returns [ 3, 6, 9, 12 ] | function everyThird(array){
newArray= []
for (var i = 2; i<array.length ; i+=3){
newArray.push(array[i])
}
return newArray
} | [
"function everyThird (arr) {\n var newArr = []\n for (var i = 2; i < arr.length; i+= 3) {\n newArr.push(arr[i]) \n }\n return newArr\n}",
"function everyThirdItem(arr) {\n let newArr = [];\n for (let i = 0; i < arr.length; i += 3) {\n newArr.push(arr[i]);\n }\n return newArr;\n}",
"function extractEveryThird(arr) {\n\tvar newArr = [];\n\tfor (var i = 0; i < arr. length; i++) {\n\t\tnewArr.push(arr[i]);\n\t}\n\treturn newArr;\n}",
"function extractEveryThird(arr){\n var newArr = [];\n for(var i = 2; i < arr.length; i += 3){\n newArr.push(arr[i]);\n }\n return newArr;\n}",
"function extractEveryThird (arr) {\n var newArr = [];\n // // Another way to write the for loop.\n // for (let e of arr) {\n // if ((arr.indexOf(e) + 1) % 3 === 0) {\n // newArr.push(e);\n // }\n // }\n for (let i = 2; i < arr.length; i += 3) {\n newArr.push(arr[i]);\n }\n return newArr;\n}",
"function extractEveryThird (arr) {\n let newArr = [];\n for (let i = 2; i < arr.length; i += 3) {\n newArr.push(arr[i]);\n \n }\n return newArr;\n}",
"function extractEveryThird (array) {\n let newArr = [];\n for ( let i=2; i< array.length; i+=3) {\n newArr.push(array[i]);\n }\n console.log (newArr);\n}",
"function extractEveryThird(arr) {\n let newArr = [];\n for (let i = 2; i < arr.length; i += 3) {\n newArr.push(arr[i]); \n }\n return console.log(newArr);\n}",
"function extractEveryThird(arraypara) {\n let newArr = [];\n for (let i = 2; i < arraypara.length; i += 3) {\n newArr.push(arraypara[i]);\n }\n console.log(newArr);\n}",
"function multiplesOfThree(arr) {\n let result = [];\n each(arr, function(num) {\n num % 3 === 0 ? result.push(num) : undefined;\n });\n return result;\n}",
"function numbersTimesThree(array) {\n var outputArray = [];\n array.forEach(function (value) {\n outputArray.push(value * 3);\n });\n return outputArray;\n}",
"function getMultiplesOfThree() {\n var A = [10, 5, 13, 18, 51];\n return A.filter(el => el % 3 == 0);\n}",
"function sumEveryThird(arr){\n var sum = 0;\n for(var i = 2; i < arr.length; i+=3){\n sum += arr[i];\n }\n return sum\n}",
"function largerThanThree(array) {\n let newArray = [];\n\n for (const number of array) {\n if (number > 3) {\n newArray.push(number);\n }\n }\n\n return newArray;\n}",
"function multiplesOfThree(array) {\n \n return filter(array, function(element) {\n\n return ( (element != 0) && (element % 3 === 0) );\n });\n}",
"function allElementsExceptFirstThree(array) {\n for (var i = 0; i < 3; i++) {\n array.shift();\n }\n return array;\n}",
"function divisibleBy3(arr){\n return arr.filter((value) => value % 3 === 0);\n}",
"function allElementsExceptFirstThree (array) {\n var result = [];\n for (var i = 3; i < array.length; i++) {\n result.push(array[i]);\n }\n return result;\n}",
"function allElementsExceptFirstThree(arr){\n\tfor(var i=0;i<3;i++){\n\t\tarr.shift();\n\t}\n\treturn arr;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete all posts from cloud storage for postId NOTE: ALTERNATE METHOD TO RETURN PROMISE DONGT USE FOR NOPW No way to get post in there but not ne | function destroyAllPostPhotosFromGCS(uid, postId) {
// You do not have to use Promise constructor here, just return async function
// return new Promise((resolve, reject) => {
return (async (resolve, reject) => {
const bucket = admin.storage().bucket();
let folderRef = `/users/${uid}/posts/${postId}/`;
// List all the files under the bucket
let files = await bucket.getFiles({
prefix: folderRef
});
// Delete each one
let response;
for (let i in files) {
try {
response = await files[i].delete();
} catch(err) {
reject(err);
}
}
resolve(response);
});
} | [
"async delete() {\n // Removing feeds and getting all posts, we'll be assigning all the Posts we get back to posts\n let [, posts] = await Promise.all([removeFeed(this.id), getPosts(0, 0)]);\n\n // Filter out all posts which do not contain feed id of feed being removed\n posts = await Promise.all(posts.map((id) => getPost(id)));\n posts = posts.filter((post) => post.feed === this.id);\n\n // Remove the post from Redis + ElasticSearch\n await Promise.all(\n [].concat(\n posts.map((post) => removePost(post.id)),\n posts.map((post) => deletePost(post.id))\n )\n );\n }",
"function deletePost(postId) {\n // TODO : Implement this\n}",
"function deletePost() {\n\tvar snippet = {\n\t\tquery : {\n\t\t\t// published: false,\n\t\t\tid: \"-K_WonIe_j7iSm-WeyC8\"\n\t\t}\n\t}\n\n\trimer.post.delete(snippet, function(error, value) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t}\n\t\telse {\n\t\t\tconsole.log(value)\n\t\t}\n\t})\n}",
"function deletePostImageByPostId(post_id) {\n return db.query(\"delete from post_images where post_id = $1 returning *;\", [post_id]);\n}",
"deleteFromFeed(uri, postId) {\n return this.database.ref(`${uri}/${postId}`).remove();\n }",
"deletePostDetials(post) {\n this.db.collection(collections_conse_1.cols.posts).updateOne({ _id: new mongodb_1.ObjectId(post._id), userId: new mongodb_1.ObjectId(this.loggedUser._id) }, {\n $set: {\n isDeleted: true\n },\n $unset: {\n content: true,\n languageCode: true,\n photoPath: true,\n seo: true,\n urls: true,\n userLoveIds: true,\n userNotLoveIds: true,\n userFavoriteIds: true,\n pureContent: true\n }\n }).then(res => {\n if (!res.modifiedCount)\n this.end_failed(this.resource.iCantDeleteThePost);\n //In user document in postsids with this post id i will update \"isDeleted\" property to ture\n this.db.collection(collections_conse_1.cols.users).updateOne({ _id: new mongodb_1.ObjectId(this.loggedUser._id) }, {\n $set: { \"posts.$[v].isDeleted\": true }\n }, { arrayFilters: [{ \"v._id\": new mongodb_1.ObjectId(post._id) }] });\n //Delete post id from array love or nolove or favorite from all users\n this.db.collection(collections_conse_1.cols.users).updateOne({}, {\n $pull: { \"postsLoveIds\": new mongodb_1.ObjectId(post._id), \"postsNotLoveIds\": new mongodb_1.ObjectId(post._id), \"postsFavoriteIds\": new mongodb_1.ObjectId(post._id) }\n });\n //Remove Post Image From Server Now\n file_services_1.FileService.removeFiles(post.photoPath);\n return this.end_successfully(this.resource.deleted);\n }).catch(err => this.catchError2(err, this));\n }",
"deletePostDocument(post) {\n //Delete post document from collection\n this.db.collection(collections_conse_1.cols.posts).deleteOne({ _id: new mongodb_1.ObjectId(post._id), userId: new mongodb_1.ObjectId(this.loggedUser._id) }).then(res => {\n if (!res.deletedCount)\n return this.end_failed(this.resource.iCantDeleteThePost);\n //Delete post id from user postsids in post document\n this.db.collection(collections_conse_1.cols.users).updateOne({ _id: new mongodb_1.ObjectId(this.loggedUser._id) }, {\n $pull: { \"posts._id\": new mongodb_1.ObjectId(post._id) }\n });\n //Delete post id from array love or nolove or favorite from all users\n this.db.collection(collections_conse_1.cols.users).updateOne({}, {\n $pull: { \"postsLoveIds\": new mongodb_1.ObjectId(post._id), \"postsNotLoveIds\": new mongodb_1.ObjectId(post._id), \"postsFavoriteIds\": new mongodb_1.ObjectId(post._id) }\n });\n //Remove Post Image From Server Now\n file_services_1.FileService.removeFiles(post.photoPath);\n return this.end_successfully(this.resource.deleted);\n }).catch(err => this.catchError2(err, this));\n }",
"async deletePost(context, id) {\n // delete in db\n await fetch(url + id, {\n method: \"DELETE\",\n headers: {\n authorization: process.env.VUE_APP_TOKEN,\n },\n });\n\n // retrieve ths good position of the deleted postIt in the store\n const pos = context.state.poste.findIndex((p) => p.id === id);\n if (pos > -1) {\n // remove from the store\n context.state.poste.splice(pos, 1);\n }\n context.commit(\"setPoste\", context.state.poste);\n }",
"[DELETE_POST](state, {id}) {\n state.posts.splice(state.posts.indexOf(id), 1)\n }",
"function deleteCommentsByPost(postId) {\n return CommentModel.deleteMany({postId: postId})\n .then(function() {console.log(\"All comments deleted\");})\n .catch(function(error){console.log(error);});\n}",
"deletePost(post) {\n // grab that specific post's reference in firebase\n var postRef = firebase.database().ref(\"Users/\" + firebase.auth().currentUser.uid + \"/saved/\" + post.key);\n\n // remove it from firebase\n postRef.remove();\n }",
"deletePost(parent, args, { db, pubsub }, info){\n const postIndex = db.posts.findIndex((post) => post.id === args.id)\n if (postIndex === -1) {\n throw new Error('post not found')\n }\n const [post] = db.posts.splice(postIndex, 1)\n\n\n //I tried including the following if statement? Why? I thought this was resetting \n //our posts array and doing the actual deleting. Instructor did not include this.\n //what would it actually do? My mistake was trying to copy steps from the delete\n //user down into the deletePosts step, above this if statement was needed to find\n //posts that were created by a now deletedUser - so a case of blind hoop jumping I guess\n // posts = posts.filter((post) => {\n // const match = post.id === args.id\n // if (match) {\n // posts = posts.filter((post) => args.id !== post.id)\n // }\n\n // return !match\n\n // })\n\n\n\n //remove all comments this user created\n\n db.comments = db.comments.filter((comment) => comment.post !== args.id)\n\n //condition for subscriptions\n if (post.published){\n pubsub.publish('post',{\n post:{\n mutation: 'DELETED',\n data: post\n }\n })\n }\n\n //I did fail to include [0] in the following line which defines an \n //array for the deletedPosts to land in\n return post\n\n }",
"async function deletePost ({post}){\n try{\n await axios.delete(`${process.env.NEXT_PUBLIC_BACKEND_URL}/${post.id}`);\n }\n catch(err){\n console.error(err)\n }\n\n refreshData();\n\n }",
"function deletePost(dbPostId){\n // deletes post from parent event container\n Post.findById(dbPostId).exec(function(err,post){\n if(err){\n console.log(err);\n } else {\n Event.findByFbId(post.fbEventId).exec(function(err,event){\n if(err) {\n console.log(err);\n } else {\n var index = event[0].posts.indexOf(dbPostId);\n event[0].posts.splice(index, 1);\n event[0].save();\n }\n });\n }\n });\n // deletes the post object from the database\n Post.findByIdAndRemove(dbPostId,function(err, postObj){\n if(err){\n console.log(err);\n // if postObj exists \n } if(postObj){\n //console.log(dbPostId + \" post removed successfully\");\n } else {\n console.log(dbPostId + \" POST DOES NOT EXIST\");\n }\n });\n}",
"function deleteThisPost(){\n handleDelete(post)\n }",
"removePost(context, id){\n return deletePost(id, localStorage.getItem('token'))\n }",
"async function deletePostsByUserId(id) {\n const [ posts ] = await mysqlPool.query(\n 'SELECT * FROM posts WHERE userId = ?',\n [ id ]\n );\n \n console.log(posts);\n\n if( posts ) {\n for(var i = 0; i < posts.length; i++){\n console.log(posts[i].postId);\n posts.comments = await deleteCommentsByPostId(posts[i].postId);\n posts.likes = await deleteLikesByPostId(posts[i].postId);\n }\n }\n\n const [ results ] = await mysqlPool.query(\n 'DELETE FROM posts WHERE userId = ?',\n [ id ]\n );\n return results.affectedRows > 0;\n }",
"function deletePost(id){\n return $http.delete(protocol+Base64.decode($rootScope.globals.currentUser.authdata)+'@'+host+'/posts/'+id+'/destroy');\n }",
"async function deletePost() {\n try {\n history.push('/home');\n\n // delete image in storage\n const imageRef = storage.ref(`images/${post.image.imageName}`);\n await imageRef.delete();\n\n // delete post in firestore\n await postRef.delete();\n\n toast.success('Tweet deleted successfully', options);\n } catch (err) {\n console.error(err.message);\n toast.error('Error deleting tweet', options);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a message and returns a promise which resolves to an Array of a new MessageBO Object. | createMessage(is_singlechat, thread_id, person, content) {
return this.#fetchAdvanced(this.#createMessageURL(is_singlechat, thread_id, person, content), {
method: 'POST',
}).then((responseJSON) => {
let responseMessageBO = MessageBO.fromJSON(responseJSON);
return new Promise(function (resolve) {
resolve(responseMessageBO);
})
})
} | [
"function createMessage(message) {\n\n\n var deferred = q.defer();\n\n MessageModel.create(message, function (err, dbMessage) {\n\n if(err){\n logger.error('Unable to create message.' + err);\n deferred.reject(err);\n } else {\n deferred.resolve(dbMessage);\n }\n\n });\n\n return deferred.promise;\n }",
"createMessage(message){\n this.pendingMessage = message;\n }",
"function createMsg(data) {\n return db.Message\n .create(data)\n .then(msg => {\n msg = msg.toObject();\n return db.User\n .findById(msg.from)\n .select('_id name avatar')\n .exec()\n .then(user => {\n msg.from = user\n return msg\n })\n })\n}",
"static createMessage(message) {\n let messageObj;\n repository.write(() => {\n message.surrogateKey = ++userService.messageSurrogateKey;\n messageObj = repository.create('Messages', message);\n\n });\n return messageObj;\n }",
"async get_messages() { \n let response_messages = [];\n return new Promise((resolve, reject) => {\n this.db().serialize(() => {\n this.db().each(\"SELECT * FROM messages;\", (error, message) => {\n if(!error) {\n response_messages.push(message);\n } else {\n // Provide feedback for the error\n console.log(error);\n }\n }, () => {\n resolve(response_messages);\n });\n });\n });\n }",
"function getMessages(){\n\treturn new Promise(function(resolve,reject){\n\n\t})\n}",
"function createNewMessage() {\n var message = {};\n message.webId = Util.getUniqueId();\n message.dateUpdate = Util.getISOCurrentTime();\n message.dateSent = \"\";\n message.value = \"\";\n message.type = 0;\n message.entityType = \"\";\n message.entityId = null;\n message.to = [];\n // FIXME: This should be initialized with the technician's ID\n message.from = \"\";\n return message;\n }",
"getMessages(is_singlechat, thread_id) {\n return this.#fetchAdvanced(this.#getMessagesURL(is_singlechat, thread_id))\n .then((responseJSON) => {\n let messageBOs = MessageBO.fromJSON(responseJSON);\n return new Promise(function(resolve){\n resolve(messageBOs);\n })\n })\n }",
"function doGetMessages() {\n var msgs = JSON.stringify(msg_queue);\n var buffer = _malloc(msgs.length + 1);\n writeStringToMemory(msgs, buffer);\n msg_queue = [];\n return buffer;\n}",
"function createMessage(requestId) {\n const params = {\n TableName: 'Message',\n Item: {\n 'messageId' : requestId,\n 'message' : 'Hello from lambda'\n }\n }\n return ddb.put(params).promise();\n}",
"function createStandardMessageBuffer(messageId,messageType,message){\n\tvar buffer = new Buffer(7+message.length)\n\tbuffer[0] = 0\n\tbuffer.writeUInt16BE(messageId,1)\n\tbuffer.writeInt16BE(messageType,3)\n\tbuffer.writeUInt16BE(message.length,5)\n\tfor (var i=7;i<buffer.length;i++) {\n\t\tbuffer[i] = message[i-7]\n\t}\n\treturn buffer\n}",
"function createMessage(double, callback) {\n Message.create(double, function(id, error) {\n if (id && !error) {\n getMessage(id, function(message){\n callback(message, error);\n });\n } else {\n callback(null, error);\n }\n });\n}",
"function createMessage(sender, message, convo) {\n User.findOne({username:sender}).exec()\n .then(function(user) {\n //mock convo\n sender=user;\n return Conversation.findOne().exec();\n })\n .then(function(conversation) {\n convo=conversation;\n return Message.createMessage({message:message, sender:sender, conversation:convo});\n })\n .then(function(message) {\n console.log(\"WEEWQE\");\n console.log(convo);\n console.log(message);\n }).catch(function(err) {\n console.log(err);\n });\n \n }",
"async createMsgPacked (context) {\n return this.getMessageBytes(context, await this.createMsg(context))\n }",
"function createMessage(myId, name, message, date, status) \n{\n this.myId = myId;\n this.name = name;\n this.message = message;\n this.date = date;\n this.status = status;\n}",
"function addMessage(username, msg, room){\n let time = moment().format('h:mm a');\n let message = {user:username, text:msg, time, room};\n // Check array message length\n // console.log(messagesArr.length)\n if(messagesArr.length > 1000){\n messagesArr.length = 0;\n messagesArr.push(message);\n return messagesArr\n }\n messagesArr.push(message);\n // console.log(messagesArr)\n return messagesArr\n}",
"function createMessage(msg) {\n return {\n \"payload\" : Buffer.from(msg).toString('base64'), // Pulsar requires payload to be hex or base64 encoding\n \"properties\": {\n \"key1\" : \"value1\",\n },\n \"context\" : \"1\"\n };\n}",
"getMessages() {\n\t\tMessage.find().then((res) => {\n\t\t\tlet messages = res;\n\t\t\tlet promises = [];\n\n\t\t\tfor(let i=0;i < messages.length;i++) {\n\t\t\t\tpromises.push(User.findOne({ _id : messages[i].userId }));\n\t\t\t}\n\n\t\t\tQ.all(promises).then((res) => {\n\t\t\t\tfor(let i=0;i<messages.length;i++) {\n\t\t\t\t\tmessages[i].user = res[i];\n\t\t\t\t}\n\n\t\t\t\tthis.socket.emit('message', messages);\n\t\t\t});\n\t\t});\n\t}",
"sendNewMessages () {\n if (this.socket) {\n const serializeJobs = this.messages.map(message => message.toTransferObject())\n Promise.all(serializeJobs)\n .then(serializedMessages => {\n this.socket.emit('messages', {\n hasMessages: this.hasMessages(),\n messages: serializedMessages\n })\n })\n .catch(e => console.error('Failed to send new messages: ', e))\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start Display Functions Restyles the page | function restylePage() {
logoToTrans();
allStyles();
} | [
"function displayToScreen() {\n\n\n\t}",
"updateDisplay() {\n \n }",
"display() {\n let currentTheme = this.gameOrchestrator.getCurrentTheme();\n currentTheme.displayScene();\n this.displayGameboard(currentTheme);\n }",
"display() {\n this.gameOrchestrator.scene.getCurrentTheme().displayScene();\n this.displayGameboard(this.gameOrchestrator.scene.getCurrentTheme());\n }",
"function stylePage(){\n styleBody(document.getElementById(\"body\"));\n styleNav(document.getElementById(\"nav1\"));\n styleStyleMenu(document.getElementById(\"drops\"));\n styleSection(document.getElementById(\"section\"), \"25vw\", \"40px\");\n styleSection(document.getElementById(\"section2\"), \"25vw\", \"40px\");\n styleSection(document.getElementById(\"section3\"), \"25vw\", \"40px\");\n styleDiv(document.getElementById(\"mainDiv\"));\n styleTitle(document.getElementById(\"pageTitle\"));\n /////////////////////////////////////////////////////////////////////////////\n styleElement(document.getElementById(\"titletext\"), \"gold\", \"0%\", \"70%\", \"200%\");\n styleElement(document.getElementById(\"authortext\"), \"gold\", \"0%\", \"40px\", \"75%\");\n /////////////////////////////////////////////////////////////////////////////////////////////////\n styleElement(document.getElementById(\"astart\"), \"gold\", \"0%\", \"20%\", \"200%\");\n styleElement(document.getElementById(\"a0\"), \"gold\", \"0%\", \"0%\", \"50%\");\n ////////////////////////////////////////////////////////////////////////////////////////////////\n styleElement(document.getElementById(\"title2text\"), \"gold\", \"0%\", \"70%\", \"200%\");\n styleElement(document.getElementById(\"author2text\"), \"gold\", \"0%\", \"40px\", \"75%\");\n ////////////////////////////////////////////////////////////////////////////////////////////////\n styleElement(document.getElementById(\"pstart\"), \"gold\", \"0%\", \"14%\", \"200%\");\n styleElement(document.getElementById(\"p0\"), \"gold\", \"0%\", \"0%\", \"50%\");\n ////////////////////////////////////////////////////////////////////////////////////////////////\n styleElement(document.getElementById(\"title3text\"), \"gold\", \"0%\", \"70%\", \"200%\");\n styleElement(document.getElementById(\"author3text\"), \"gold\", \"0%\", \"40px\", \"75%\");\n /////////////////////////////////////////////////////////////////////////////////////////\n}",
"function WSDisplay() {}",
"function drawHomeScreen() {\n homebutton.style('display', 'none');\n writingscrheading.style('display', 'none');\n startoverbutton.style('display', 'none');\n createCanvas(windowWidth, windowHeight);\n //pagebody.style('display', 'flex');\n ul.style('display', 'flex');\n button1.style('display', 'inline-block');\n button2.style('display', 'inline-block');\n button3.style('display', 'inline-block');\n button4.style('display', 'inline-block');\n titletext.style('display', 'block');\n about.style('display', 'block');\n}",
"function displayNewScene() {\n\t\n\t//first Start of Page\n\tif (!particleSystem) {\n\t\tupdateArticleDiv(startText);\n\t\tinitParticles();\n\t\tupdateSkyBoxColor(bgColor);\n\t\tfadeIn(cssObject, true);\n\t\tfillScene();\n\t\treturn;\n\t}\n\n\t\n\t\n\tif (lastBgColor != bgColor) {\n\t\tchangeBgColor();\n\t}\n\t\n\tconsole.log(\"cssObject \" + cssObject);\n\t\n\t\n\tfadeOutIn(cssObject);\n\t\n\tfillScene();\n\t\n}",
"function refreshDisplay(){\n env.disp.render() ;\n}",
"function resetDisplay(){\r\t\t\r\t}",
"function render()\n {\n modReadline.cursorTo(process.stdout, 0, 0);\n\n switch (m_displayMode)\n {\n case \"epg\":\n renderEpg();\n break;\n case \"info\":\n renderInfo();\n break;\n }\n\n modReadline.clearScreenDown(process.stdout);\n }",
"function initalizePage(){\n\n $(\"#name\").focus();\n resetThemeSelection();\n $(\"#colors-js-puns\").css('display','none');\n $(\"#other-title\").css('display','none');\n $(\"#paypal\").css('display','none');\n $(\"#bitcoin\").css('display','none');\n\n}",
"function initiatedDisplay(){\n $('header').addClass('position-top');\n $('.form-section').html('');\n $('.options').delay(1000).fadeIn(1000);\n $('header p, .description-prompt, footer').fadeOut();\n $('header h1').html(`<span style=\"font-size:.7em;\">${state.ajax.near}</span><br /><span class=\"js-search\">Search New Location</span>`);\n $('header h1').addClass('point');\n }",
"function LDisplay () {\n}",
"function setup_start() {\n display.start.css('display', 'block');\n display.start.on('click', function(e){\n start();\n e.preventDefault();\n });\n }",
"function alterDisplay()\n{\n\t$('.uploadArea').addClass(\"hide\"); // remove upload button **fix later to adjust to the top\n\t\n\tif($('#analysisArea').hasClass('hide'))\n\t{\n\t\t$('#analysisArea').removeClass('hide');\n\t\t\n\t\tprintDuration();\n\t\tprintOverview();\n\t\tprintMessageAnalysis();\n\t\tprintTimeAnalysis();\n\t\tprintEmojiAnalysis();\n\t\t//printWordsAnalysis()\n\t\tgoogleApi();\n\n\t}\n}",
"function onDisplayReady() {\n exports.startFromIndex(sozi.location.getFrameIndex());\n\n // Hack to fix the blank screen bug in Chrome/Chromium\n // See https://github.com/senshu/Sozi/issues/109\n window.setTimeout(display.update, 1);\n }",
"function compsciNewsDisplay() {\r\n\trefreshDisplayScreen();\r\n\tdocument.getElementById(\"computersciHeading\").innerHTML = \"Computer Science Department News\"; /*this display the heading of the page*/\r\n\tdocument.getElementById(\"news\").style.display = \"block\";\r\n\tgetCompsciNewsFeed(\"news\");\r\n}",
"function loadWrapsAndSandwichesPage() {\n display301();\n display302();\n display303();\n display304();\n display305();\n display306();\n display307();\n display308();\n display309();\n display310();\n display311();\n display312();\n display313();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new EventHubSender instance. | constructor(context, partitionId) {
super(context, {
name: context.config.getSenderAddress(partitionId),
partitionId: partitionId
});
/**
* The unique lock name per connection that is used to acquire the
* lock for establishing a sender link by an entity on that connection.
* @readonly
*/
this.senderLock = `sender-${uuid()}`;
this.address = context.config.getSenderAddress(partitionId);
this.audience = context.config.getSenderAudience(partitionId);
this._onAmqpError = (eventContext) => {
const senderError = eventContext.sender && eventContext.sender.error;
logger.verbose("[%s] 'sender_error' event occurred on the sender '%s' with address '%s'. " +
"The associated error is: %O", this._context.connectionId, this.name, this.address, senderError);
// TODO: Consider rejecting promise in trySendBatch() or createBatch()
};
this._onSessionError = (eventContext) => {
const sessionError = eventContext.session && eventContext.session.error;
logger.verbose("[%s] 'session_error' event occurred on the session of sender '%s' with address '%s'. " +
"The associated error is: %O", this._context.connectionId, this.name, this.address, sessionError);
// TODO: Consider rejecting promise in trySendBatch() or createBatch()
};
this._onAmqpClose = async (eventContext) => {
const sender = this._sender || eventContext.sender;
logger.verbose("[%s] 'sender_close' event occurred on the sender '%s' with address '%s'. " +
"Value for isItselfClosed on the receiver is: '%s' " +
"Value for isConnecting on the session is: '%s'.", this._context.connectionId, this.name, this.address, sender ? sender.isItselfClosed().toString() : undefined, this.isConnecting);
if (sender && !this.isConnecting) {
// Call close to clean up timers & other resources
await sender.close().catch((err) => {
logger.verbose("[%s] Error when closing sender [%s] after 'sender_close' event: %O", this._context.connectionId, this.name, err);
});
}
};
this._onSessionClose = async (eventContext) => {
const sender = this._sender || eventContext.sender;
logger.verbose("[%s] 'session_close' event occurred on the session of sender '%s' with address '%s'. " +
"Value for isSessionItselfClosed on the session is: '%s' " +
"Value for isConnecting on the session is: '%s'.", this._context.connectionId, this.name, this.address, sender ? sender.isSessionItselfClosed().toString() : undefined, this.isConnecting);
if (sender && !this.isConnecting) {
// Call close to clean up timers & other resources
await sender.close().catch((err) => {
logger.verbose("[%s] Error when closing sender [%s] after 'session_close' event: %O", this._context.connectionId, this.name, err);
});
}
};
} | [
"static create(context, partitionId) {\n const ehSender = new EventHubSender(context, partitionId);\n if (!context.senders[ehSender.name]) {\n context.senders[ehSender.name] = ehSender;\n }\n return context.senders[ehSender.name];\n }",
"function EventHubSender(amqpSenderLink) {\n var self = this;\n self._senderLink = amqpSenderLink;\n\n EventEmitter.call(self);\n\n var onErrorReceived = function (err) {\n self.emit('errorReceived', errors.translate(err));\n };\n\n self.on('newListener', function (event) {\n if (event === 'errorReceived') {\n self._senderLink.on('errorReceived', onErrorReceived);\n }\n });\n\n self.on('removeListener', function (event) {\n if (event === 'errorReceived') {\n self._senderLink.removeListener('errorReceived', onErrorReceived);\n }\n });\n}",
"createSender(host, port, request) {\n return new Sender(host, port, request);\n }",
"function EventHub() {\n\t\tthis.emitters = {};\n\t\tthis.emitters[generalPurpose] = new EventEmitter();\n\t}",
"function createHubType() {\n log.info(\"create hub\");\n // [ -Events- ]\n // error - emitted when received messages are poorly formatted\n // listen - emitted when listening\n // close - emitted when the hub is closed\n // status - various hub status updates\n // [ -Constructor- ]\n function Hub() {\n log.info(\"instantiate hub\");\n // get non-ambiguous this\n var self = this;\n // Call parent constructor\n Hub.super_.call(self);\n // Internal structures\n self._subscribers = {};\n // subsribers is { source._id: {'source': source, patterns: [pattern*]}}\n self._transport = undefined;\n self._closed = false;\n // state listeners\n self.once('close', function handleClosed() {\n self._closed = true;\n });\n // Constructor. Return undefined.\n return undefined;\n }\n // [ -Inheritance- ]\n util.inherits(Hub, events.EventEmitter);\n // [ -Private API- ]\n // disconnect a client\n Hub.prototype._disconnectClient = function hubDisconnectClient(client, error, cb) {\n client.close(cb);\n setImmediate(this.emit.bind(this), 'status', \"closed client connection\", error);\n this.emit('error', error);\n // allow chaining\n return this;\n };\n // handle publication request\n Hub.prototype._handlePublication = function hubHandlePublication(source, messageObj) {\n log.info(\"hub on publication\");\n // get a non-ambiguous \"this\"\n var self = this;\n var error = validateProperties(\n messageObj,\n \"publication message from transport layer\",\n ['type', 'message', 'channel', 'transactionID'],\n []\n );\n if (error) { self._disconnectClient(source, error); return null; }\n // FIXME message should be JSON\n // FIXME channel should be regex\n self._distribute(messageObj.message, messageObj.channel, function distributeCB(numPublished) {\n // notify source of publication and number published\n source.send({\n type: 'published',\n 'message': messageObj.message,\n channel: messageObj.channel,\n number: numPublished,\n transactionID: messageObj.transactionID,\n }, function onError(error) {\n if (error) { self._disconnectClient(source, error); }\n });\n });\n // allow chaining\n return this;\n };\n // handle subscription request\n Hub.prototype._handleSubscription = function hubHandleSubscription(source, messageObj) {\n log.info(\"hub on subscription\");\n // get a non-ambiguous \"this\"\n var self = this;\n var error = validateProperties(\n messageObj,\n \"subscription message from transport layer\",\n ['type', 'pattern', 'transactionID'],\n []\n );\n if (error) { self._disconnectClient(source, error); return null; }\n // FIXME - pattern should be a regex\n var subscriber = self._subscribers[source._id];\n if (subscriber === undefined) {\n subscriber = {\n patterns: [],\n connection: source,\n };\n log.debug(\"number of unique subscribers: \", _.keys(self._subscribers).length + 1);\n }\n if (!_.contains(subscriber.patterns, messageObj.pattern)) {\n subscriber.patterns.push(messageObj.pattern);\n }\n self._subscribers[source._id] = subscriber;\n // notify source that subscription is in place\n source.send({\n type: 'subscribed',\n pattern: messageObj.pattern,\n number: subscriber.patterns.length,\n transactionID: messageObj.transactionID,\n }, function onError(error) {\n if (error) { self._disconnectClient(source, error); }\n });\n // allow chaining\n return this;\n };\n // handle unsubscription request\n Hub.prototype._handleUnsubscription = function hubHandleUnsubscription(source, messageObj) {\n log.info(\"hub on unsubscription\");\n // get a non-ambiguous \"this\"\n var self = this;\n var error = validateProperties(\n messageObj,\n \"unsubscription message from transport layer\",\n ['type', 'pattern', 'transactionID'],\n []\n );\n if (error) { self._disconnectClient(source, error); return null; }\n // FIXME - pattern should be a regex\n var subscriber = self._subscribers[source._id];\n var numPatterns = 0;\n if (subscriber && _.contains(subscriber.patterns, messageObj.pattern)) {\n subscriber.patterns = _.without(subscriber.patterns, messageObj.pattern);\n if (subscriber.patterns.length === 0) {\n delete self._subscribers[source._id];\n log.debug(\"number of unique subscribers: \", _.keys(self._subscribers).length);\n } else {\n numPatterns = subscriber.patterns.length;\n }\n }\n // notify source that unsubscription occurred\n source.send({\n type: 'unsubscribed',\n pattern: messageObj.pattern,\n number: numPatterns,\n transactionID: messageObj.transactionID,\n }, function onError(error) {\n if (error) { self._disconnectClient(source, error); }\n });\n // allow chaining\n return this;\n };\n // unsubscribe a dead client\n Hub.prototype._unsubscribeFromAll = function hubUnsubscribeFromAll(source) {\n log.info(\"hub _unsubscribeFromAll\", source);\n if (_.contains(_.keys(this._subscribers)), source._id) {\n delete this._subscribers[source._id];\n this.emit('status', \"client disconnected\", source._id);\n }\n // allow chaining\n return this;\n };\n // handle messages from clients\n Hub.prototype._handleMessage = function hubHandleMessage(source, messageObj) {\n log.info(\"hub handle message\", messageObj);\n // parse the message type and respond accordingly\n if (!messageObj.type) {\n var noTypeError = new VError(\"Message from transport layer has no type (%j)\", messageObj);\n this._disconnectClient(source, noTypeError);\n } else if (messageObj.type == \"publication\") {\n this._handlePublication(source, messageObj);\n } else if (messageObj.type == \"subscription\") {\n this._handleSubscription(source, messageObj);\n } else if (messageObj.type == \"unsubscription\") {\n this._handleUnsubscription(source, messageObj);\n } else {\n var badTypeError = new VError(\"Unrecognized message type from transport layer: %s. (%j)\", messageObj.type, messageObj);\n this._disconnectClient(source, badTypeError);\n }\n // allow chaining\n return this;\n };\n // distribute a message to subscribers\n Hub.prototype._distribute = function hubDistribute(message, channel, cb) {\n // distribute a message on a channel to subscribers\n // get a non-ambiguous \"this\"\n var self = this;\n // new message object for distribution to clients\n var newMessageObj = {\n type: 'distribution',\n 'message': message,\n 'channel': channel,\n };\n // send to each subscriber\n var numPublished = 0;\n var match;\n var matchPattern = function matchPattern(pattern) {\n // closure for match.\n // returns true/false for match test, and also sets\n // the matching pattern\n match = pattern;\n return channel.match(pattern);\n };\n async.eachSeries(_.keys(self._subscribers), function distribute(subscriberId, eachCB) {\n // error response\n var subscriber = self._subscribers[subscriberId];\n if (_.any(subscriber.patterns, matchPattern)) {\n newMessageObj.match = match;\n subscriber.connection.send(newMessageObj, function sendError(error) {\n log.debug('hub sent to client (%j)', newMessageObj);\n // close the client conn on error.\n if (error) {\n self._disconnectClient(subscriber.connection, error, eachCB);\n } else {\n numPublished++;\n eachCB();\n }\n return null;\n });\n } else {\n eachCB();\n }\n return null;\n }, function eachFinal() {\n // errors here would come from disconnectClient, which calls\n // the cb when the client is closed.\n // Client.close does not report an error on close.\n callback(cb)(numPublished);\n return null;\n });\n return this;\n };\n // [ -Public API- ]\n // close a transport object\n Hub.prototype.close = function hubClose(cb) {\n log.info(\"hub close\");\n if (this._closed) {\n throw new VError(\"Hub has already been closed\");\n }\n // add cb to listeners\n if (cb) {\n this.on('close', cb);\n }\n this._transport.close();\n // it doesn't make sense to do anything with the object after this,\n // so return null\n return null;\n };\n // listen for connections\n Hub.prototype.listen = function hubListen(options, cb) {\n log.info(\"hub listen\");\n // non-ambiguous self\n var self = this;\n // FIXME - deal with options better - ask for url/http explicitly?\n // only allow this to be called once on the object\n if (self._transport) {\n // throw immediately - this is programmer error\n throw new VError(\"'listen' has already been called on this hub.\");\n }\n // add cb to listeners\n if (cb) {\n self.on('listening', cb);\n }\n // set transport\n self._transport = new ActualTransportServer();\n // proxy events\n self._transport.on('listening', self.emit.bind(self, 'listening'));\n self._transport.on('close', self.emit.bind(self, 'close'));\n // handle client actions\n self._transport.on('client closed', self._unsubscribeFromAll.bind(self));\n self._transport.on('message', self._handleMessage.bind(self));\n // handle transport actions\n self._transport.on('error', function handleTransportError() {\n // FIXME need a test for this\n // FIXME need some notice - either a propagated error event or a reason for the close\n self.close();\n });\n // listen\n self._transport.listen(options);\n // it doesn't make sense to do anything with the object until listen\n // calls back, so return null\n return null;\n };\n // return a new Hub\n return Hub;\n}",
"function Hub() {\n EventEmitter.call(this);\n\n if (appConfig.env === 'test') {\n // during test, there is no browser. thus we cannot instantiate socket.io!\n return;\n }\n\n this.io = (appConfig.wsUrl) ? socketIo(appConfig.wsUrl) : socketIo();\n\n this.io.on('connect', () => log.info('socket to server connected'));\n this.io.on('disconnect', () => log.info('socket from server disconnected'));\n this.io.on('event', this.emit.bind(this, 'event'));\n}",
"createSender(queueOrTopicName) {\n validateEntityPath(this._connectionContext.config, queueOrTopicName);\n return new ServiceBusSenderImpl(this._connectionContext, queueOrTopicName, this._clientOptions.retryOptions);\n }",
"establishEventHub() {\n hyperUtil.eventHub.registerEvent('blockEvent', this.peerName, this.orgAdmin, (block) => {\n var self = this\n var actionBlock = hyperUtil.helper.processBlockToReadAbleJson(block)\n let channelName = actionBlock[0].channelName\n if (!self.channelObjs.hasOwnProperty(channelName)) {\n logger.info('new a channel object ' + channelName)\n self.channelObjs[channelName] = new channel(self.peerName, channelName, this.io)\n self.channelObjs[channelName].start()\n }\n this.channelObjs[channelName].eventBlock(block)\n })\n }",
"getEventHubManager(): EventHub {\n return this.eventHub\n }",
"async function createEventHubEventSource() {\n const subscriptionId = process.env[\"TIMESERIESINSIGHTS_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"TIMESERIESINSIGHTS_RESOURCE_GROUP\"] || \"rg1\";\n const environmentName = \"env1\";\n const eventSourceName = \"es1\";\n const parameters = {\n type: \"EarliestAvailable\",\n consumerGroupName: \"cgn\",\n eventHubName: \"ehn\",\n eventSourceResourceId: \"somePathInArm\",\n keyName: \"managementKey\",\n kind: \"Microsoft.EventHub\",\n localTimestampPropertiesLocalTimestamp: {\n format: \"TimeSpan\",\n timeZoneOffset: { propertyName: \"someEventPropertyName\" },\n },\n location: \"West US\",\n serviceBusNamespace: \"sbn\",\n sharedAccessKey: \"someSecretvalue\",\n timestampPropertyName: \"someTimestampProperty\",\n };\n const credential = new DefaultAzureCredential();\n const client = new TimeSeriesInsightsClient(credential, subscriptionId);\n const result = await client.eventSources.createOrUpdate(\n resourceGroupName,\n environmentName,\n eventSourceName,\n parameters\n );\n console.log(result);\n}",
"* getSender(username) {\n if (!this.senders[username]) {\n this.senders[username] = {\n instance: ILP.createSender(yield this.factory.create({ username }))\n }\n\n debug('created a sender object')\n }\n\n // Destroy the sender if it hasn't been used for 15 seconds\n this.scheduleSenderDestroy(username)\n\n return this.senders[username].instance\n }",
"function InputAzureEventhub (config, eventEmitter) {\n this.config = config\n this.eventEmitter = eventEmitter\n if (!this.config.bodyField) {\n this.config.bodyField = 'body'\n }\n if (!this.config.consumerGroup) {\n this.config.consumerGroup = '$Default'\n }\n this.client = new EventHubConsumerClient(\n this.config.consumerGroup || '$Default',\n config.endpoint,\n config.name\n )\n}",
"constructor() {\n this.bus = document.createElement('event-bus-singleton');\n }",
"function EventHubController(timeout) {\n this.timeout = timeout || 125;\n this.queue = [];\n this.ready = true;\n}",
"function EventSource() {\n throw new TypeError(\"Type is not creatable\");\n \n // NOTE: Should EventSource be creatable?\n /*\n if (!(this instanceof EventSource) || this === EventSource.prototype) throw new TypeError(\"'this' is not an EventSource object\");\n \n // private storage object\n var data = new EventData();\n __EventSourceData__.set(this, data);\n \n // initialize the stream\n var stream = _create(EventStream.prototype);\n this.stream = stream;\n __EventStreamData__.set(stream, data);\n \n // brand the event stream\n __EventStreamBrand__.set(stream);\n \n // convenience, bind the source functions\n this.send = _bind(this.send, this);\n this.reject = _bind(this.reject, this);\n this.close = _bind(this.close, this); \n */ \n }",
"function Hub() {\r\n }",
"function EventBus() {\n _classCallCheck(this, EventBus);\n\n this.registry = {};\n }",
"async _init(options) {\n try {\n if (!this.isOpen() || !this._sender) {\n // Wait for the connectionContext to be ready to open the link.\n await this._context.readyToOpenLink();\n await this._negotiateClaim({\n setTokenRenewal: false,\n abortSignal: options.abortSignal,\n timeoutInMs: options.timeoutInMs\n });\n logger.verbose(\"[%s] Trying to create sender '%s'...\", this._context.connectionId, this.name);\n const sender = await this._context.connection.createAwaitableSender(options);\n this._sender = sender;\n logger.verbose(\"[%s] Sender '%s' created with sender options: %O\", this._context.connectionId, this.name, options);\n sender.setMaxListeners(1000);\n // It is possible for someone to close the sender and then start it again.\n // Thus make sure that the sender is present in the client cache.\n if (!this._context.senders[this.name])\n this._context.senders[this.name] = this;\n this._ensureTokenRenewal();\n return sender;\n }\n else {\n logger.verbose(\"[%s] The sender '%s' with address '%s' is open -> %s. Hence not reconnecting.\", this._context.connectionId, this.name, this.address, this.isOpen());\n return this._sender;\n }\n }\n catch (err) {\n const translatedError = translate(err);\n logger.warning(\"[%s] An error occurred while creating the sender %s: %s\", this._context.connectionId, this.name, `${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }",
"function setupEvents(){\r\n\ttry{\r\n\tvar eh = chain.getEventHub();\r\n\tvar cid = config['chaincode']['id'];\r\n\tvar regid = eh.registerChaincodeEvent(cid, \"^eventHub$\", function(event) {\r\n\t\tconsole.log(event);\r\n\t\tvar buffer = new Buffer(event.payload);\r\n\t\tconsole.log(buffer.toString());\r\n });\r\n\tconsole.log(\"EVENT SETUP DONE\");\r\n}\r\ncatch(err){\r\n\tconsole.log(err);\r\n\tconsole.log(\"Could not setup events\");\r\n}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
leaderboard fetch function based on tour id | function loadLeaderboard(a) {
setfetching("fetching");
fetch(`https://jason-11.herokuapp.com/pga-leaderboard?tourId=${a}`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "",
},
method: "get",
mode: "cors",
})
.then((response) => {
return response.json();
})
.then((data) => {
setleaderboardData(data);
setfetching("not-fetching");
})
.catch((err) => {
console.error(err);
});
} | [
"fetchInfo(id) {\n\t\tclient.db.query('SELECT id, title, msg, winners, guild_id, channel_id, message_id, winner_amount, ending FROM discord.lola_giveaway_info WHERE id = ?;', [id], function (err, res) {\n\t\t\tif(err) return console.log(err);\n\n\t\t\tfor (let i = 0; i < res.length; i++) {\n\t\t\t\tconst server = await this.getServerName(client, data[4]);\n\t\t\t\tthis.chooseWinners(res[i])\n\t\t\t}\n\t\t});\n\t}",
"searchID(leaderboard, id){\n var data = leaderboard.find( (obj => {\n return obj.id == id\n }))\n\n if (data !== undefined){ // make sure the value actually exists in the leaderboard first.\n var index = leaderboard.findIndex( (obj => {\n return obj.id == id\n }))\n\n return data, index\n }\n else{\n return undefined, undefined\n }\n }",
"function getLeaderBoard() {\n // clear the past leaderboard\n document.getElementById(\"leaderboard\").innerHTML = \"\";\n\n // pull from a database somewhere.\n fetch(\"https://word-scapes.herokuapp.com/scores?limit=5\")\n .then((res) => res.json())\n .then((data) =>\n document\n .getElementById(\"leaderboard\")\n .appendChild(createLeaderboardElement(data))\n );\n}",
"function fetchNearby(id) {\n fetch(surfline.nearby + id)\n .then( function (response) {\n return response.json();\n })\n .then( function (api) {\n renderNearby(api);\n \n })\n}",
"static getLeaderboards() {\r\n fetch(SCORES_URL)\r\n .then( response => response.json() )\r\n .then( function(scores_obj) {\r\n const scores_arr = scores_obj['data'];\r\n const s_arr = [];\r\n\r\n for(const elem of scores_arr) {\r\n const s_obj = {\r\n 'score': elem['attributes']['score'],\r\n 'username': elem['attributes']['user']['username'],\r\n 'difficulty': elem['attributes']['difficulty']['level']\r\n }\r\n \r\n s_arr.push(s_obj);\r\n }\r\n\r\n const ordered_scores = s_arr.sort(function(a, b) {\r\n return b['score'] - a['score'];\r\n })\r\n\r\n Game.renderScoreBoard(ordered_scores)\r\n })\r\n }",
"function getLeaderDetails(url,root){\n var xhr = new XMLHttpRequest();\n xhr.onload=function(e){\n _renderBoard(JSON.parse(e.target.responseText),root);\n };\n xhr.open('GET',url,true);\n xhr.send();\n }",
"static async getLeaderboard() {\n\t\tconst result = await axios.get('/favours/get-leaderboard', config);\n\t\treturn result.data;\n\t}",
"function fetchData(){\n Trello.get('boards/' + boardId, function(board){\n var boardData = board;\n Trello.get('boards/' + boardId + '/lists', function(lists){\n boardData.lists = lists;\n Trello.get('boards/' + boardId + '/cards', function(cards){\n boardData.cards = cards;\n showData(eatData(boardData));\n })\n });\n\n })\n \n }",
"function getLeaderboard() {\n var user = \"\";\n send(json_get_leaderboard_message(user));\n}",
"function getBoards() {\n leaderBoardList.innerHTML = \"\";\n console.log(\"getBoards\");\n fetch(`https://tic-tac-word-backend.herokuapp.com/api/v1/boards`)\n .then(response => response.json())\n .then(boards => reduceToTopTenBoards(boards));\n}",
"function getLeaders(){\n fetch(urlAPI.leaderboards)\n .then(function(response) {\n return response.json()\n }).then(function(json) {\n jsonLeaders= json;\n listarLeaders();\n })\n}",
"_showLeaderboard(message){\n var query = {karma: {$exists: true}};\n var fields = {karma: 1, _id: 1};\n var options = {limit: 5, sort: [['karma','desc']]}\n var self = this;\n\n this.dbClient.query(\"user-data\", query, fields, options, function(results) {\n var channel = self._getChannelById(message.channel);\n var response = \"The current standings are:\\n\";\n\n for (var i = 0; i < results.length; i++) {\n var rank = (i + 1) + \". \";\n var usr = \"<@\" + results[i]._id + \"> \";\n var karma = \" (\" + results[i].karma + \" CondorKarma :tm:)\\n\";\n response += rank + usr + karma;\n }\n\n self.giphy.sendMessageWithGiphy(self, response, 'w00t', channel.name);\n });\n }",
"function showMembers(source){\n let tour_id = $(source).closest(\"tr\").prop(\"id\");\n let tour = $.grep(tournamentsData, function(tour){\n return tour._id === tour_id;\n });\n $(\"#show-data-body\").empty();\n\n // match ID's with names in users collection\n if (tour[0].teams.length > 0) {\n $.each(tour[0].teams, function (key, data) {\n $(\"#show-data-body\").append(\"Hold: <b>\" + data.t_name + \"</b>\").append(\"<br>\");\n\n for (i = 0; i < data.members.length; i++) {\n let user = $.grep(usersData, function (usersData) {\n return usersData._id === data.members[i];\n });\n $(\"#show-data-body\").append(findUserName(data.leaderID)+\" (leder)\").append(\"<br>\");\n $(\"#show-data-body\").append(user[0].username).append(\"<br>\");\n }\n $(\"#show-data-body\").append(\"<br>\");\n });\n $(\"#show-data-header\").empty().append(\"Hold for turnering: \"+tour[0].name);\n $('#modal-edit').modal('show');\n } else {\n window.alert(\"Ingen deltagere på nuværende tidspunkt\")\n }\n}",
"function fetchGameTurns(){\n\tadapter.getGameTurns(gameId)\n\t\t.then(gameTurns => retrieveGameTurns(gameTurns))\n}",
"function fetchPlayerTurns(){\n\tadapter.getPlayerTurns()\n\t\t.then(playerTurns => retrievePlayerTurns(playerTurns))\n}",
"async function getTour(tournamentName, tournamentUrl) {\n\n var res = {};\n\n try {\n var page = await browser.browser(tournamentUrl + 'archive/');\n const linkYears = await page.evaluate(ftour.linkYears);\n await page.close();\n\n // While on each tournament archive per year\n for (let j in linkYears) {\n if (linkYears[j]) {\n var year = linkYears[j][1];\n var linkTour = linkYears[j][0];\n\n // Get Resultat table only\n var page = await browser.browser(linkTour + 'results/');\n tourYear = await page.evaluate(ftour.tourYears);\n await page.close();\n\n // Scrap all data on each match ID\n for (let k in tourYear) {\n // loop on match by competition on tournament (ex: qualification or not)\n for (let kk in tourYear[k].match) {\n var flashscoreId = tourYear[k].match[kk].id;\n var matchUrl = config.match + flashscoreId;\n // create new line Table HEAD and flashscore\n // All the data is available at this point\n\n try {\n var db_head = await models.head.findOne({\n where: {\n flashscoreId: flashscoreId\n }\n });\n\n if (db_head == null || db_head.dataValues.stateFlashscore != \"ok\") {\n try {\n // scraping match\n //var page = await browser.browser(\"about:blank\");\n var jsonMatch = await match.getMatch(null, flashscoreId);\n\n if (jsonMatch.state == \"ERROR\") {\n throw \"JsonMatch is unvalid : \" + jsonMatch.error;\n }\n\n var idHome = jsonMatch.player.home.playerID;\n var UrlHome = config.rootUrl + jsonMatch.player.home.playerURL;\n var home = await player.getPlayer(null, UrlHome, idHome, jsonMatch.player.home.playerCountry);\n var idAway = jsonMatch.player.away.playerID;\n var UrlAway = config.rootUrl + jsonMatch.player.away.playerURL;\n var away = await player.getPlayer(null, UrlAway, idAway, jsonMatch.player.away.playerCountry);\n if (home.state != \"ok\") {\n throw \"getPlayer Home is unvalid :\" + idHome + \": \" + home.error\n } else if (away.state != \"ok\") {\n throw \"getPlayer Away is unvalid :\" + idAway + \": \" + away.error\n }\n\n //await page.close();\n\n var date = Date.UTC(year, tourYear[k].match[kk].month,\n tourYear[k].match[kk].day,\n tourYear[k].match[kk].hour,\n tourYear[k].match[kk].min);\n\n var jsonWeather = await weather.setWeather(tournamentName,\n tourYear[k].country, date);\n if (jsonWeather.state == \"ERROR\") {\n throw \"setWeather is unvalid \" + weather.error;\n }\n\n //Update or Create in flashscore table\n await dbTools.upsert(\"flashscore\", {\n state: \"ok\",\n matchUrl: matchUrl,\n tournamentUrl: tournamentUrl,\n flashscoreId: flashscoreId,\n tournamentName: tournamentName,\n round: tourYear[k].match[kk].round,\n qualification: tourYear[k].qualification,\n indoor: tourYear[k].indoor,\n country: tourYear[k].country,\n surface: tourYear[k].surface,\n year: year,\n dateTime: date,\n data: jsonMatch,\n }, {\n flashscoreId: flashscoreId\n });\n } catch(e) {\n try {\n await page.close();\n } catch(e) {}\n res[flashscoreId] = e;\n console.error(\"ERROR tour.js\", e);\n continue;\n }\n //Update or Create in head table\n await dbTools.upsert(\"head\", {\n flashscoreId: flashscoreId,\n homeId: idHome,\n stateHome: \"ok\",\n awayId: idAway,\n stateAway: \"ok\",\n stateFlashscore: \"ok\",\n weatherId: jsonWeather.hash,\n stateWeather: \"ok\"\n }, {\n flashscoreId: flashscoreId\n })\n } // IF db_head doesn't exist\n } catch(e) {\n\n res[flashscoreId] = e;\n console.error(\"ERROR tour.js\", e);\n }\n }\n }\n } // while years\n } // while years\n } catch(e) {\n res.error = e;\n console.error(\"ERROR tour.js in\", tournamentName, e);\n }\n\n //await browser.close();\n //await models.sequelize.close();\n\n return res;\n}",
"function showTournament(data, tourid) {\n\tvar t;\n\tfor (var i = 0; i < data.tournaments.length; i++) {\n\t\tif (data.tournaments[i].tid == tourid\n\t\t || data.tournaments[i].shortcode == tourid) {\n\t\t\tt = data.tournaments[i];\n\t\t}\n\t}\n\tif (!t) {\n\t\treturn;\n\t}\n\tvar src = genTournament(t, true);\n\tif (session) {\n\t\tsrc += '<div id=\"tournamentDetails\"><h2>Loading Players List…</h2></div>';\n\t\tsrc += '<h2 class=\"dis\">Discussion</h2><iframe id=\"disqusFrame\" src=\"${ROOT}/disqus?tid='\n\t\t + t.tid + '\"></iframe>';\n\t} else {\n\t\tsrc += '<h2>Login to view players lists and discussions</h2>'\n\t\t + '<ul><li><a href=\"${ROOT}/login\">Login to Players Portal</a></li></ul>';\n\t}\n\t\n\tdocument.title = titlebase + ' - Tournament: ' + t.name;\n\t$('#header1').html('Tournament: ' + t.name);\n\t$('#tournamentContent').show();\n\t$('#tournamentsListContent').hide();\n\tif (gtourid != tourid) {\n\t\t$(document).scrollTop(0);\n\t\t$('#tournamentDynContent').html(src);\n\t}\n\tgetTournamentDetails(t);\n\tgtourid = tourid;\n}",
"function displayLeaderboardPage(tx) {\n\ttx.executeSql('SELECT Name, Score FROM Leaderboard WHERE Course = \"'+ leaderboardCourse.code +'\" ORDER BY Score', [],\n\t\tfunction(tx, result) {\n\t\t\tfor (var i = 0, len = result.rows.length, prevScore = 0, place = 1, currentScore; i < len; ++i) {\n\t\t\n\t\t\t\t// Make placing correct (two players with the same score are placed the same)\n\t\t\t\tcurrentScore = result.rows.item(i).Score;\n\t\t\t\tif (currentScore !== prevScore) {\n\t\t\t\t\tplace = i+1;\n\t\t\t\t}\n\t\t\t\tprevScore = currentScore;\n\t\n\t\t\t\t$('#leaderboardTbl tbody').append('<tr><td>' +\n\t\t\t\t\t\tplace +\n\t\t\t\t\t\t'</td><td>' +\n\t\t\t\t\t\tresult.rows.item(i).Name +\n\t\t\t\t\t\t'</td><td>' +\n\t\t\t\t\t\tcurrentScore +\n\t\t\t\t\t\t'</td></tr>');\n\t\t}\n\t}, errorCB);\n}",
"function fetchTopIDs() {\n return fetch('newstories');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the nav element has the class "opennav" or if the window is at a width of greater than 768px. If either condition applies, the nav links are placed in the tab index. If not, the links are removed from the tab order. | function setNavTabIndex() {
const $navList = $(".nav-list").find("a");
if ($("nav").hasClass("open-nav") || window.innerWidth > 768) {
$navList.attr("tabindex", "0");
} else {
removeNav();
$navList.attr("tabindex", "-1");
}
} | [
"function checkNav() {\n\t\tif(docWidth >= breakPoint) {\n\t\t\tnavControl.hide();\n\n\t\t\t//if nav is hidden, open it\n\t\t\tif(!nav.hasClass(\"open\")) {\n\t\t\t\tnav.find(\"ul\").first().css(\"display\", \"block\");\n\t\t\t\tnav.addClass(\"open\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tnavControl.show();\n\n\t\t\t//if nav is open, hide it\n\t\t\tif(nav.hasClass(\"open\")) {\n\t\t\t\tnav.find(\"ul\").first().css(\"display\", \"none\");\n\t\t\t\tnav.removeClass(\"open\");\n\t\t\t}\n\t\t}\n\t}",
"function hoverOnNav() {\n if ($(window).width() >= 768 && cssua.ua.desktop && !cssua.ua.tablet_pc) {\n //hover nav event\n $('.nav-icon, .left-menu').hover(function () {\n activeNav = $(this);\n openSubNav($(this));\n }, function () {\n closeSubNav();\n });\n //hover on sub nav\n $('.sub-nav-list').hover(function (event) {\n if(!$(event.target).hasClass('search-input')) {\n activeNav.addClass('active');\n $(this).stop(true,true).show();\n }\n\t\t\t\t\n\t\t\t\thoverOnSubNav();\n\t\t\t\t\n }, function () {\n closeSubNav();\n });\n } else {\n //small window size\n $('.nav-icon, .left-menu, .sub-nav-list').unbind('mouseenter mouseleave');\n }\n }",
"function isMobileNav() {\n return window.innerWidth < 1200;\n }",
"function showLargeNav() {\n\tif (window.innerWidth >= windowBreakpoint) {\n\t\t$(\".nav__collapse\").show();\n\t}\n\telse {\n\t\t$(\".nav__collapse\").hide();\n\t}\n}",
"function showNav() {\n $('.mobile-nav-button').removeClass('active');\n $('.mobile-search-button').removeClass('active');\n //if (($(window).width() >= MIN_NON_TABLET_SIZE && !Modernizr.ipad) || ($(window).width()<MIN_NON_TABLET_SIZE && $('header.ot, header.campaign').length==0)) {\n //if ($(window).width() > MIN_NON_TABLET_SIZE && !Modernizr.ipad) {\n if ($(window).width() > MIN_NON_MOBILE_SIZE) {\n $('.main-header-nav').show().css({'height':'', 'right':''});\n }\n else {\n $('.main-header-nav').hide().find('.active').removeClass('active');\n $('.main-header-nav > ul').css('left', '0px');\n }\n showDisplayName();\n}",
"function checkIfNavToggle() {\n\n const mediaQuery = window.matchMedia('(min-width: 990px)').matches;\n\n if(!mediaQuery && !navInitialised) {\n initializeMobileNav();\n }\n\n if(mediaQuery && navInitialised) {\n uninitializeMobileNav();\n }\n\n return false;\n}",
"function addClassForSmallNav() {\r\n var windowWidth = window.innerWidth,\r\n mainNav = $(\"#navbar > ul\");\r\n \r\n if (windowWidth < 992) {\r\n mainNav.addClass(\"small-nav\");\r\n } else {\r\n mainNav.removeClass(\"small-nav\");\r\n }\r\n }",
"function checkNavSize(width){\n\t\tvar isHome=$('header').hasClass('home');\n\t\tif(!isHome){\n\t\t\tif(width<1200){\n\t\t\t\t$('ul#menu').hide();\n\t\t\t\t$('ul#usermenu').hide();\n\t\t\t\t$('ul#minimenu').show();\n\t\t\t}else{\n\t\t\t\t$('ul#menu').show();\n\t\t\t\t$('ul#usermenu').show();\n\t\t\t\t$('ul#minimenu').show();\t\t\t\n\t\t\t}\n\t\t}else{\n\t\t\t$('ul#menu').hide();\n\t\t\t$('ul#usermenu').hide();\n\t\t\t$('ul#minimenu').show();\t\t\t\n\t\t}\n\t}",
"function addClassForSmallNav() {\n var windowWidth = window.innerWidth,\n mainNav = $(\"#navbar > ul\");\n \n if (windowWidth < 992) {\n mainNav.addClass(\"small-nav\");\n } else {\n mainNav.removeClass(\"small-nav\");\n }\n }",
"function resizeNav() {\n // If the window is scaled to mobile, use the hamburger navbar\n if ($(window).width() <= 640) {\n $(\".nav-large\").hide();\n $(\".nav-smol\").show();\n }\n // Otherwise, use the default nav bar with page tabs\n else {\n $(\".nav-large\").show();\n $(\".nav-smol\").hide();\n }\n}",
"function hoverOnNav() {\n\t\t\n\t\tif ($(window).width() >= 600 && cssua.ua.desktop && !cssua.ua.trident) {\n\t\t\t//hover nav event\n\t\t\t$('.nav-icon, .left-menu').hover(function(){\n\t\t\t\tactiveNav = $(this);\n\t\t\t\topenSubNav($(this));\n\t\t\t}, function(){\n\t\t\t\tcloseSubNav();\n\t\t\t});\n\t\t\t\n\t\t\t//hover on sub nav\n\t\t\t$('.sub-nav-list').hover(function(){\n\t\t\t\tactiveNav.addClass('active');\n\t\t\t\t$(this).stop().show();\n\t\t\t}, function(){\n\t\t\t\tcloseSubNav();\n\t\t\t});\n\t\t} else {\n\t\t\t//small window size\n\t\t\t$('.nav-icon, .left-menu, .sub-nav-list').unbind('mouseenter mouseleave');\n\t\t}\n\t}",
"function showNav(){\n if($(window).width() < 1200){\n $('#nav-links').hide();\n $('#hamburger-nav').show();\n } else {\n $('#nav-links').show();\n $('#hamburger-nav').hide();\n }\n }",
"function subnavRelocate() {\n var windowSize = jq(window).width();\n if (windowSize <= 768) {\n jq('#SubNav').insertBefore('.main-content');\n } else if (windowSize > 768) {\n jq('#SubNav').insertAfter('.main-content');\n }\n}",
"function navChange() {\n if ($(window).width() < 993) {\n $('#nav-icons').appendTo('#nav-mobile');\n }\n else {\n $('#nav-icons').appendTo('#nav-desktop');\n }\n $(window).resize(function() {\n if ($(window).width() < 993) {\n $('#nav-icons').appendTo('#nav-mobile');\n }\n else {\n $('#nav-icons').appendTo('#nav-desktop');\n }\n });\n if ($('title:first-of-type').text() == 'iCE - Accueil') {\n }\n\n\n}",
"function updateNav() {\n if (window.innerWidth < 991) {\n $('.navbar').addClass('bg-light');\n return;\n }\n\n checkNav();\n\n $(window).on('scroll', function(event) {\n checkNav();\n });\n }",
"function showHideNav(){\n\t\tif ( !mobileNav.classList.contains(\"nav--extend\") ){\n\t\t\tshowNav();\n\t\t}\n\t\telse {\n\t\t\thideNav();\n\t\t}\n\t}",
"function navItemWindth(){\n var windowWidth = $(window).width();\n var navItemCount = 5;// or $(.nav-item).length\n var atTop = false;\n\n atTop = $('nav').hasClass('nav-to-top') ? true : false;\n\n if(!atTop) {\n $('.nav-item').each(function(){\n $(this).css('width', windowWidth/navItemCount +'px');\n $(this).css('transform', 'translateX(0)');\n $(this).removeClass('nav-item-top');\n });\n } else {\n $('.nav-item').each(function(){\n //80 logo width, 20 left\n $(this).css('width', (windowWidth-100)/navItemCount +'px');\n $(this).css('transform', 'translateX(100px)');\n $(this).addClass('nav-item-top');\n });\n }\n }",
"function collapse_nav() {\n if (windowWidth < 992) {\n $('.navbar-collapse').addClass('collapse');\n } else {\n $('.navbar-collapse').removeClass('collapse');\n }\n }",
"function scrollFunction() {\n var width = $(window).width();\n var navBar = $('.nav-bar ');\n if (width > 768) {\n if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {\n navBar.addClass('desktop-shrink');\n } else {\n navBar.removeClass('desktop-shrink');\n }\n } else {\n // if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {\n // navBar.addClass('mobile-shrink');\n // } else {\n // navBar.removeClass('mobile-shrink');\n // }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates the icicles in the room. parameters (x,y,z,radius,height,segments, rotation) icicles are in order from left to right. | function initIcicles(){
// outer ring bottom
createIcicle(0, 9, 90, 2, 18, 0);
createIcicle(-24, 5, 72, 2, 10, 0);
createIcicle(-25, 13, 70, 2, 26, 0);
createIcicle(-27, 8, 68.5, 2, 16, 0);
createIcicle(-63, 15, 55, 3, 30, 0);
createIcicle(-70, 9, 35, 2, 18, 0);
createIcicle(-80, 9, 25, 2, 18, 0);
createIcicle(-82, 5, 23, 2, 10, 0);
createIcicle(-72, 20, -5, 3.5, 40, 0);
createIcicle(-70, 7, -25, 2, 14, 0);
createIcicle(-50, 11, -65, 2, 21, 0);
createIcicle(-50, 4, -70, 2, 8, 0);
createIcicle(-27, 17, -75, 2, 34, 0);
// inner ring bottom
createIcicle(0, 5, 25, 2, 10, 0);
createIcicle(-5, 2.5, -22, 2, 5, 0);
createIcicle(-23, 6, -5, 2, 12, 0);
createIcicle(-15, 2.5, 15, 2, 5, 0);
createIcicle(-15, 1.5, -15, 1.5, 3, 0);
// top
createIcicle(0, 83.2, 25, 2, 10, 180);
createIcicle(-15, 89, 15, 2, 5, 180);
createIcicle(-23, 83.3, -5, 2, 12, 180);
createIcicle(-15, 87.8, -15, 1.5, 6, 180);
createIcicle(-5, 86.8, -22, 2, 7, 180);
} | [
"function pipeCircle(pos, width, w, h, beg, rot, itner,r,l){\r\n\tvar lines = new Array();\r\n\tfor(p=0;p<=itner;p++){\r\n\t\t\tlines = connectShapes(lines,pipe(\r\n\t\t\t[pos[0]+w*Math.cos(beg+rot/itner*p),pos[1]+h*Math.sin(beg+rot/itner*p),pos[2]],\r\n\t\t\t[pos[0]+w*Math.cos(beg+rot/itner*(p+1)),pos[1]+h*Math.sin(beg+rot/itner*(p+1)),\r\n\t\t\tpos[2]],\r\n\t\t\twidth,r,l));\r\n\t\t}\r\n\t\treturn lines;\r\n}",
"function drawObsticles(){ \n for (var _ = 0; _ < 1; _++){ //x, y, width, height, speed\n var obsticle = new Obsticle(/*x = */ Math.random()*canvas.width, /*y = */ Math.floor((Math.random() * canvas.height/2) + 70), /*width = */ Math.floor((Math.random() * 60) + 30), /*height = */ Math.floor((Math.random() * 15) + 8), /*speed = */ Math.floor(Math.random() * 3.5) + 1);\n _obsticles.push(obsticle);\n }\n}",
"function calorimeter_object(name, type, ri, ro, z_start, z_end, nl, nseg, nsec, padding_xy, padding_z, rgb_plane, rgb_line){\n this.name = name ;\n this.type = type ;\n this.rgb_plane = rgb_plane ;\n this.rgb_line = rgb_line ;\n this.inner_radius = ri ;\n this.outer_radius = ro ;\n this.z_start = z_start ;\n this.z_end = z_end ;\n this.z_length = this.z_end-this.z_start ;\n this.n_layers = nl ;\n this.n_segments = nseg ;\n this.n_sectors = nsec ;\n this.padding_xy = padding_xy ;\n this.padding_z = padding_z ;\n this.spatial_resolution = 0.1 ;\n this.ri2 = pow(this.inner_radius,2) ;\n this.ro2 = pow(this.outer_radius,2) ;\n this.cells = [] ;\n this.blocks = [] ;\n \n this.z_from_index = function(index){\n if(index<0) return null ;\n if(index>=this.n_segments) return null ;\n return this.z_start + (this.z_end-this.z_start)*index/this.n_segments ;\n }\n \n // (u,v,w) are the indices in the (r,phi,z) directions\n this.u_from_r = function(r){\n if(isNaN(r)) return null ;\n if(r<this.inner_radius) return null ;\n if(r>this.outer_radius) return null ;\n var u = floor(this.n_layers*(r-this.inner_radius)/(this.outer_radius-this.inner_radius)) ;\n if(u<0) return null ;\n if(u>=this.n_layers) return null ;\n return u ;\n }\n this.v_from_phi = function(phi){\n phi = (phi+2*pi)%(2*pi) ;\n return floor((phi)/(2*pi)*this.n_sectors) ;\n }\n this.w_from_z = function(z){\n if(z<this.z_start) return null ;\n if(z>this.z_end ) return null ;\n var w = floor(this.n_segments*(z-this.z_start)/(this.z_end-this.z_start)) ;\n return w ;\n }\n \n // Stopping powers, for electron, muon, tau, photon, neutrino, charged_hardon, neutral_hadron, ephemeral_hadron\n this.stopping_powers = [] ;\n \n // Make polygons for drawing the calorimeter\n this.polygons = [] ;\n var ro = this.outer_radius ;\n var ri = this.inner_radius ;\n for(var u=0 ; u<this.n_layers ; u++){ // position in r\n this.blocks.push([]) ;\n var rho_1 = ri + (ro-ri)*(u+0)/this.n_layers ;\n var rho_2 = ri + (ro-ri)*(u+1)/this.n_layers ;\n var dxy = rho_2-rho_1 ;\n var rho_1_ = rho_1 + dxy*this.padding_xy ;\n var rho_2_ = rho_2 - dxy*this.padding_xy ;\n for(var v=0 ; v<this.n_sectors ; v++){ // position in phi\n this.blocks[u].push([]) ;\n var phi1 = 2*pi*(v-0.0)/this.n_sectors ;\n var phi2 = 2*pi*(v+1.0)/this.n_sectors ;\n for(var w=0 ; w<this.n_segments ; w++){ // position in z\n var z1 = this.z_start + this.z_length*(w+0)/this.n_segments - this.padding_z ;\n var z2 = this.z_start + this.z_length*(w+1)/this.n_segments + this.padding_z ;\n \n // Assemble all the points\n var x111 = rho_1_*cos(phi1) ; var y111 = rho_1_*sin(phi1) ; var z111 = z1 ;\n var x211 = rho_1_*cos(phi2) ; var y211 = rho_1_*sin(phi2) ; var z211 = z1 ;\n var x121 = rho_1_*cos(phi1) ; var y121 = rho_1_*sin(phi1) ; var z121 = z2 ;\n var x221 = rho_1_*cos(phi2) ; var y221 = rho_1_*sin(phi2) ; var z221 = z2 ;\n var x112 = rho_2_*cos(phi1) ; var y112 = rho_2_*sin(phi1) ; var z112 = z1 ;\n var x212 = rho_2_*cos(phi2) ; var y212 = rho_2_*sin(phi2) ; var z212 = z1 ;\n var x122 = rho_2_*cos(phi1) ; var y122 = rho_2_*sin(phi1) ; var z122 = z2 ;\n var x222 = rho_2_*cos(phi2) ; var y222 = rho_2_*sin(phi2) ; var z222 = z2 ;\n \n var points = [ [x111,y111,z111] , [x211,y211,z211] , [x121,y121,z121] , [x221,y221,z221] , [x112,y112,z112] , [x212,y212,z212] , [x122,y122,z122] , [x222,y222,z222] ] ;\n var calo_block = new calorimeter_block(points, rgb_plane, rgb_line) ;\n \n // Don't forget to store the coordinates!\n // i is a an id unique to the block in this detector component\n calo_block.u = u ;\n calo_block.v = v ;\n calo_block.w = w ;\n calo_block.i = u*this.n_layers + v*this.n_sectors + w ;\n \n // r_center is used for the tracker to find best point for a hit\n calo_block.r_center = 0.5*(rho_1_+rho_2_) ;\n \n // type is used when storing the block in the particle object\n calo_block.type = this.type ;\n this.blocks[u][v].push(calo_block) ;\n this.cells.push(calo_block.cell) ;\n }\n }\n }\n \n // Make getting a block very cheap so we can transform from (x,y,z) to (u,v,w) quickly\n this.get_block = function(xyz){\n var phi = atan2(xyz[1],xyz[0]) ;\n var r = sqrt(xyz[0]*xyz[0]+xyz[1]*xyz[1]) ;\n var u = this.u_from_r(r) ;\n var v = this.v_from_phi(phi) ;\n var w = this.w_from_z(xyz[2]) ;\n if(u==null) return null ;\n if(v==null) return null ;\n if(w==null) return null ;\n return this.blocks[u][v][w] ;\n }\n \n this.make_xml_node = function(){\n var element = xmlDoc.createElement('detector_component') ;\n element.setAttribute('name' , this.name ) ;\n element.setAttribute('type' , this.type ) ;\n element.setAttribute('rgb_plane' , this.rgb_plane ) ;\n element.setAttribute('rgb_line' , this.rgb_line ) ;\n element.setAttribute('inner_radius', this.inner_radius) ;\n element.setAttribute('outer_radius', this.outer_radius) ;\n element.setAttribute('z_start' , this.z_start ) ;\n element.setAttribute('z_end' , this.z_end ) ;\n element.setAttribute('n_layers' , this.n_layers ) ;\n element.setAttribute('n_segments' , this.n_segments ) ;\n element.setAttribute('n_sectors' , this.n_sectors ) ;\n element.setAttribute('padding_xy' , this.padding_xy ) ;\n element.setAttribute('padding_z' , this.padding_z ) ;\n \n var stopping_powers_element = xmlDoc.createElement('stopping_powers') ;\n for(var i=0 ; i<particle_species.length ; i++){\n stopping_powers_element.setAttribute(particle_species[i], this.stopping_powers[particle_species[i]]) ;\n }\n element.appendChild(stopping_powers_element) ;\n return element ;\n }\n}",
"function rectangles(lstBodyCoordinates, lstBodyPartsStr, element){\n if(lstBodyCoordinates == false){\n return false\n }\n else {\n for (var i = 0; i<lstBodyCoordinates.length; i++){\n var matrix = lstBodyCoordinates[i]\n\n // arms are defined by 2 points\n var newDiv = document.getElementById(lstBodyPartsStr[i])\n if (newDiv.id != \"bodyCore\"){\n var x0 = matrix[0][0]\n var x1 = matrix[1][0]\n var y0 = matrix[0][1]\n var y1 = matrix[1][1]\n\n var midpoint = [1/2 * (x0 + x1), 1/2 * (y0 + y1)]\n // need to define C\n const C = 1 \n var xDelta = x0 - x1\n var yDelta = y0 - y1\n\n if (xDelta == 0){\n if (yDelta > 0){\n var angle = 180\n }\n else {\n var angle = -180\n }\n }\n else {\n var angle = Math.atan(yDelta / xDelta) * 180 / Math.PI\n }\n\n var xDeltaSqr = Math.pow(xDelta, 2)\n var yDeltaSqr = Math.pow(yDelta, 2)\n var width = Math.sqrt(xDeltaSqr + yDeltaSqr)\n var height = C * width\n\n var widthScaled = width * scaleFactor\n var heightScaled = height * scaleFactor\n\n newDiv.style.width = widthScaled + 'px'\n newDiv.style.height = C * widthScaled + 'px'\n newDiv.style.transform = \"rotate(\" + angle.toString() + \"deg)\"\n newDiv.style.position = \"absolute\"\n newDiv.style.left = (midpoint[0] - 1/2*width) * scaleFactor + offset + 'px'\n newDiv.style.top = (midpoint[1] - 1/2*height) * scaleFactor + 'px'\n // var img = some image \n // newDiv.appendChild(img)\n }\n\n // here we got the bodyCore, defined by 4 points\n // 0 ----------- 1\n // | |\n // | |\n // | |\n // | |\n // 3 ----------- 2\n else {\n var x0 = matrix[0][0]\n var x1 = matrix[1][0]\n var x2 = matrix[2][0]\n var x3 = matrix[3][0]\n var y0 = matrix[0][1]\n var y1 = matrix[1][1]\n var y2 = matrix[2][1]\n var y3 = matrix[3][1]\n\n var midpointTop = [1/2*(x0+x1), 1/2*(y0+y1)]\n var midpointBot = [1/2*(x2+x3), 1/2*(y2+y3)]\n var midpointMid = [1/4*(x0+x1+x2+x3), 1/4*(y0+y1+y2+y3)]\n\n // assumption: width between shoulders > diameter of hip\n var xDeltaTop = x1 - x0\n var yDeltaTop = y1 - y0 \n\n if (xDeltaTop == 0){\n if (yDeltaTop > 0){\n var angle = 180\n }\n else {\n var angle = -180\n }\n }\n else {\n var angle = Math.atan(yDeltaTop / xDeltaTop) * 180 / Math.PI\n }\n\n var xDeltaSqrTop = Math.pow(xDeltaTop, 2)\n var yDeltaSqrTop = Math.pow(yDeltaTop, 2)\n\n var width = Math.sqrt(xDeltaSqrTop + yDeltaSqrTop)\n var widthScaled = width * scaleFactor + 80\n\n var height = Math.sqrt(\n Math.pow(midpointTop[0]-midpointBot[0], 2) + Math.pow(midpointTop[1]-midpointBot[1], 2)\n )\n var heightScaled = height * scaleFactor + 30\n\n newDiv.style.width = widthScaled + 'px'\n newDiv.style.height = heightScaled + 'px'\n newDiv.style.transform = \"rotate(\" + angle.toString() + \"deg)\"\n newDiv.style.position = \"absolute\"\n newDiv.style.left = (midpointMid[0] - 1/2 * width) * scaleFactor + offset + 'px'\n newDiv.style.top = (midpointMid[1] - 1/2 * height) * scaleFactor - 80 + 'px'\n \n }\n\n }\n }\n}",
"function addPoints(segments) {\n\t var theta = (2*Math.PI / segments); //Degrees = radians * (180 / π)\n\t \n \n\t\tcylinderPoints.push(vec3(0,0.5,0));\n cylinderNormal.push(vec3(0,1,0));\n\t\tcylinderPoints.push(vec3(0,-0.5,0));\n cylinderNormal.push(vec3(0,-1,0));\n \n \n\t for (i =0;i<=segments*2;i++){\n\t var x = 0.5*Math.cos(theta*i); \n\t var z = 0.5*Math.sin(theta*i);\n\t \n \n\n\t cylinderPoints.push(vec3(x,0.5,z));\t//Bottom Vertex\n\t cylinderPoints.push(vec3(x,-0.5,z));\t//Top Vertex\n\n\t\t /* if(i<segments){\n\t\t cylinderNormal.push(vec3(0,1,0));\n\t\t cylinderNormal.push(vec3(0,-1,0));\n\t\t }\n\t\t else{*/\n\t\t cylinderNormal.push(normalize(vec3(x,0.5,z)));\n\t\t cylinderNormal.push(normalize(vec3(x,-0.5,z)));\n\t\t //}\n\n\t \n\t /****************************************************************\n\t * *\n\t * NAO SEI SE É PRECISO MAS ADICIONA-SE CASO SEJA PRECISO DEPOIS*\n\t * *\n\t ****************************************************************/\n \n //alert(\"ola\");\n\n\t //Nao necessario, falar com o prof\n cylinderBotVertices.push(vec3(x,-0.5,z));\n\t cylinderTopVertices.push(vec3(x,0.5,z));\n }\n}",
"static genCorner(subdiv, irow) {\n const out = []; // Flat Array of Vertex Points\n const pi_h = Math.PI * 0.5; // Range of Arc being created\n const n = 2 ** subdiv;\n const a = new Vec3();\n const b = new Vec3();\n let cnt = 0;\n let rad, s, c;\n for (let i = 0; i < n; i++) {\n irow.push(cnt); // Starting Index of Each Row\n cnt += n - i + 1; // How Many points created for this row\n rad = pi_h * i / n; // Vertical Angle \n s = Math.sin(rad);\n c = Math.cos(rad);\n a.xyz(0, s, c); // Left Point\n b.xyz(c, s, 0); // Right Point\n a.pushTo(out); // Start of Row\n this.arcLerp(a, b, n - i, out); // in Between Verts\n b.pushTo(out); // End of Row\n }\n out.push(0, 1, 0); // Pole Point\n irow.push(cnt); // Pole Index\n return out;\n }",
"generateCircleVertices(radius, segments, centerX, centerY) {\n var degreePerFan = (2 * Math.PI)/ segments;\n vertexData = [centerX, centerY];\n for (var j = 0; j <= segments; j++) {\n var index = 2 * j+2;\n var angle = degreePerFan * (j+1);\n vertexData[index] = centerX + Math.cos(angle) * radius;\n vertexData[index+1] = centerY + Math.sin(angle) * radius;\n }\n circleVertices = new Float32Array(vertexData);\n }",
"constructor(i, x, y, width, height, mapParams) {\r\n this._i = i;\r\n this.x = x;\r\n this.y = y;\r\n this.width = width;\r\n this.height = height;\r\n this._params = mapParams;\r\n this.type = \"room\";\r\n \r\n this._corridors = new Map();\r\n }",
"CreateRegions( width, height ) {\n //index into the vector\n let idx = this.m_Regions.length - 1;\n\n for ( let col = 0; col < this.NumRegionsHorizontal; ++col ) {\n for ( let row = 0; row < this.NumRegionsVertical; ++row ) {\n this.m_Regions[ idx ] = new Region( this.PlayingArea().Left() + col * width,\n this.PlayingArea().Top() + row * height,\n this.PlayingArea().Left() + ( col + 1 ) * width,\n this.PlayingArea().Top() + ( row + 1 ) * height,\n idx );\n --idx;\n };\n };\n }",
"constructor(atoms/*:Atom[]*/, box_length/*:number*/,\n lower_bound/*:Num3*/, upper_bound/*:Num3*/) {\n this.boxes = [];\n this.box_length = box_length;\n this.lower_bound = lower_bound;\n this.upper_bound = upper_bound;\n this.xdim = Math.ceil((upper_bound[0] - lower_bound[0]) / box_length);\n this.ydim = Math.ceil((upper_bound[1] - lower_bound[1]) / box_length);\n this.zdim = Math.ceil((upper_bound[2] - lower_bound[2]) / box_length);\n //console.log(\"Cubicles: \" + this.xdim + \"x\" + this.ydim + \"x\" + this.zdim);\n const nxyz = this.xdim * this.ydim * this.zdim;\n for (let j = 0; j < nxyz; j++) {\n this.boxes.push([]);\n }\n for (let i = 0; i < atoms.length; i++) {\n const xyz = atoms[i].xyz;\n const box_id = this.find_box_id(xyz[0], xyz[1], xyz[2]);\n if (box_id === null) {\n throw Error('wrong cubicle');\n }\n this.boxes[box_id].push(i);\n }\n }",
"constructor({ numberOfSlices = 20, radius = 1.0, height = 1.0 }) {\n super();\n /* Points 0, 1, 2, ..., N-1 are on the base circle */\n for (let k = 0; k < numberOfSlices; k++) {\n const angle = (k / numberOfSlices) * 2 * Math.PI;\n const xVal = radius * Math.cos(angle);\n const yVal = radius * Math.sin(angle);\n this.vertices.push([xVal, yVal, 0.0]); // At z=0\n }\n /* Point N is the base center */\n this.vertices.push([0, 0, 0]); // center at base\n /* Point N+1 is the cone tip */\n this.vertices.push([0, 0, height]); // tip of the cone\n\n for (let k = 0; k < numberOfSlices; k++) {\n /* cells for the circle base are\n [N,0,1], [N,1,2], ..., [N,N-2,N-1], [N, N-1, 0]\n */\n this.triangles.push([numberOfSlices, k, (k + 1) % numberOfSlices]);\n /* cell for the cone top are\n [N+1,0,1], [N+1,1,2], ... [N+1,N-2,N-1], [N+1,N-1,0]\n */\n this.triangles.push([numberOfSlices + 1, k, (k + 1) % numberOfSlices]);\n }\n }",
"createRooms(){\n let walls = [\n [ 0, 0,40, 1], [39, 0,40,25], [ 0,24,40,25], [ 0, 0, 1,24], // outer walls\n [14,10,12, 5], // inner block\n [ 1,12, 6, 1], [ 8,12, 6, 1], [26,12, 6, 1], [33,12, 6, 1], // horizontal walls\n [14, 1, 1, 2], [14, 4, 1, 6], [25, 1, 1, 6], [25, 8, 1, 2], // vertical walls inkl.door\n [14,15, 1, 2], [14,18, 1, 6], [25,15, 1, 6], [25,22, 1, 2] // vertical walls inkl.door\n ];\n walls.map( (wallData) => {\n this.wallObjects.push( new Wall((wallData[0]).mx(),(wallData[1]).mx(),\n (wallData[2]).mx(),(wallData[3]).mx(),this.colorList[this.curColor],this.ctx));\n } );\n }",
"_positionsCircle(n, shift) {\n const rotation = () => {\n return random.double();\n };\n const positions = [];\n for (let i = 0; i < n; i++) {\n const angle = (360 / n) * i;\n const scale = 1 - 2 * shift;\n const x = shift + scale * (Math.sin(angle) + 1) / 2;\n const y = shift + scale * (Math.cos(angle) + 1) / 2;\n const r = rotation();\n positions.push({ x, y, r });\n }\n return positions;\n }",
"function buildWalls()\n{\n\t// 2 sides\n\tobsticleManager.addWall(new Block(width/2, height/2, 0, width,height,1, \"box\"));\t\n\tobsticleManager.addWall(new Block(width/2, height/2, zIndex, width,height,1, \"box\"));\t\n\t// 2 sides\n\tobsticleManager.addWall(new Block(width/2, 0, zIndex/2, width,1,zIndex, \"box\"));\t\n\tobsticleManager.addWall(new Block(width/2, height, zIndex/2, width,1,zIndex, \"box\"));\t\n\t// 2 sides\n\tobsticleManager.addWall(new Block(0, height/2, zIndex/2, 1,height,zIndex, \"box\"));\t\n\tobsticleManager.addWall(new Block(width, height/2, zIndex/2,1,height,zIndex, \"box\"));\t\n}",
"function createCircularStairs(params) {\n var cirStairs = new THREE.Object3D();\n\n // stair material\n var cirStairMat = marbleMaterials.whiteMarble;\n\n // bottom step\n var stepGeom1 = new THREE.CylinderGeometry(params.cirStairRad,\n params.cirStairRad,\n params.cirStairHeight,\n params.radialSeg,\n params.radialSeg,\n false,\n params.cirStairTS,\n params.cirStairTLFull);\n var stepMesh1 = new THREE.Mesh(stepGeom1,cirStairMat);\n\n // third step\n var stepGeom2 = new THREE.CylinderGeometry(params.cirStairRad * 0.8,\n params.cirStairRad* 0.8,\n params.cirStairHeight,\n params.radialSeg,\n params.radialSeg,\n false,\n params.cirStairTS,\n params.cirStairTLFull);\n var stepMesh2 = new THREE.Mesh(stepGeom2,cirStairMat);\n\n // second step\n var stepGeom3 = new THREE.CylinderGeometry(params.cirStairRad * 0.6,\n params.cirStairRad* 0.6,\n params.cirStairHeight,\n params.radialSeg,\n params.radialSeg,\n false,\n params.cirStairTS,\n params.cirStairTLFull);\n var stepMesh3 = new THREE.Mesh(stepGeom3,cirStairMat);\n\n // top step\n var stepGeom4 = new THREE.CylinderGeometry(params.cirStairRad * 0.4,\n params.cirStairRad* 0.4,\n params.cirStairHeight,\n params.radialSeg,\n params.radialSeg,\n false,\n params.cirStairTS,\n params.cirStairTLFull);\n var stepMesh4 = new THREE.Mesh(stepGeom4,cirStairMat);\n\n // position steps within cirStair object\n stepMesh1.position.y = params.cirStairHeight * 0.5;\n stepMesh2.position.y = params.cirStairHeight* 1.5;\n stepMesh3.position.y = params.cirStairHeight * 2.5;\n stepMesh4.position.y = params.cirStairHeight * 3.5;\n\n // add them to cirStair object\n cirStairs.add(stepMesh1);\n cirStairs.add(stepMesh2);\n cirStairs.add(stepMesh3);\n cirStairs.add(stepMesh4);\n\n return cirStairs;\n }",
"function createCone(radius, height, xpos, ypos, zpos, xrot, yrot, zrot)\n{\n var vertarray = [];\n var normarray = [];\n var indexarray = [];\n\n //center vertex\n vertarray.push(vec4(0.0, 0.0, 0.0,1.0));\n normarray.push(vec3(0.0, 0.0, 1.0));\n\n //top vertex\n vertarray.push(vec4(0.0, 0.0,-height,1.0));\n normarray.push(vec3(0.0, 0.0,-1.0));\n\n // create cone vertices (flat bottom)\n for (var longNumber = 0; longNumber <= _sphere_longitude_bands; longNumber++) {\n var phi = longNumber * 2 * Math.PI / _sphere_longitude_bands;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n\n var x = sinPhi;\n var y = cosPhi;\n var z = 0.0;\n //var u = 1 - (longNumber / _sphere_longitude_bands);\n //var v = 1 - (latNumber / _sphere_latitude_bands);\n\n normarray.push(vec3(x, y, z));\n\n //textureCoordData.push(u);\n //textureCoordData.push(v);\n\n vertarray.push(vec4(radius * x, radius * y, 0.0, 1.0));\n\n }\n\n var index_offset = _object_vertices.length;\n\n // create indices of cone\n for (var longNumber = 0; longNumber < _sphere_longitude_bands; longNumber++) {\n\n var first = (index_offset + 2) + longNumber;\n var top = index_offset + 1;\n\n indexarray.push(first);\n indexarray.push(first + 1);\n indexarray.push(top);\n\n }\n\n // create indices of flat bottom\n for (var longNumber = 0; longNumber < _sphere_longitude_bands; longNumber++) {\n\n var first = (index_offset + 2) + longNumber;\n var center = index_offset;\n\n indexarray.push(first);\n indexarray.push(first + 1);\n indexarray.push(center);\n\n }\n\n // transformation (translation + rotation)\n //+t/R/-t/T\n\n // rotation\n var trafo = mat4();\n\n trafo = translate(xpos, ypos, ypos);\n\n var trans1 = mat4();\n trans1 = translate(0,0,-height/2.0);\n\n var rot = mat4();\n rot = mult(rot, rotate( xrot, [1, 0, 0] ));\n rot = mult(rot, rotate( yrot, [0, 1, 0] ));\n rot = mult(rot, rotate( zrot, [0, 0, 1] ));\n\n var trans2 = mat4();\n trans2 = translate(0,0,height/2.0);\n\n trafo = mult(trafo, trans1);\n trafo = mult(trafo, rot);\n trafo = mult(trafo, trans2);\n\n for ( var i = 0; i < vertarray.length; i++ ){\n vertarray[i] = matVecMul(trafo, vertarray[i]); //matVecMul\n }\n\n return [vertarray, normarray, indexarray];\n}",
"function createSOR(){ \r\n for (var angle=10; angle<=360; angle+=10){\r\n var theta = ((angle * Math.PI) / 180);\r\n var currentLine = shape[0];\r\n polyLine = [];\r\n\r\n for (var i = 0; i < currentLine.length; i++) {\r\n var coordIterator = currentLine[i];\r\n var x = (Math.cos(theta) * coordIterator.x) - (Math.sin(theta) * coordIterator.z);\r\n var y = coordIterator.y;\r\n var z = (Math.cos(theta) * coordIterator.z) + (Math.sin(theta) * coordIterator.x);\r\n polyLine.push(new coord(x, y, z));\r\n }\r\n shape.push(polyLine);\r\n }\r\n}",
"createLines(lines) {\n let ic = this.icn3d,\n me = ic.icn3dui\n if (me.bNode) return\n\n if (lines !== undefined) {\n for (let name in lines) {\n let lineArray = lines[name]\n\n for (let i = 0, il = lineArray.length; i < il; ++i) {\n let line = lineArray[i]\n\n let p1 = line.position1\n let p2 = line.position2\n\n let dashed = line.dashed ? line.dashed : false\n let dashSize = 0.3\n\n let radius = ic.lineRadius\n\n let colorStr = '#' + line.color.replace(/\\#/g, '')\n\n let color = me.parasCls.thr(colorStr)\n\n if (!dashed) {\n if (name == 'stabilizer') {\n ic.brickCls.createBrick(p1, p2, radius, color)\n } else {\n ic.cylinderCls.createCylinder(p1, p2, radius, color)\n }\n } else {\n let distance = p1.distanceTo(p2)\n\n let nsteps = parseInt(distance / dashSize)\n let step = p2\n .clone()\n .sub(p1)\n .multiplyScalar(dashSize / distance)\n\n let start, end\n for (let j = 0; j < nsteps; ++j) {\n if (j % 2 == 1) {\n start = p1.clone().add(step.clone().multiplyScalar(j))\n end = p1.clone().add(step.clone().multiplyScalar(j + 1))\n\n if (name == 'stabilizer') {\n ic.brickCls.createBrick(start, end, radius, color)\n } else {\n ic.cylinderCls.createCylinder(start, end, radius, color)\n }\n }\n }\n }\n }\n }\n }\n\n // do not add the artificial lines to raycasting objects\n }",
"initCatmull()\n\t{\n\t\t//Initialisation of the arrays used to calculate catmull rom\n\t\tthis.points = [];\n\t\tthis.colorPoints = [];\n\t\tthis.indicesPoints = [];\n\t\t\n\t\tthis.angleMatrixTab = [];\n\t\t//Creation of the values to render the cattmull rom circle\n\t\tfor(var i = 0;i<360;i+=360/this._division)\n\t\t{\n\t\t\tthis.points.push(this.radius * Math.sin(glMatrix.toRadian(i)), this.radius * Math.cos(glMatrix.toRadian(i)) / 1.0,0.5);\n\t\t\tthis.colorPoints.push(this.color.r, this.color.g, this.color.b, 1.0);\n\t\t\tthis.indicesPoints.push(this.indicesPoints.length);\n\t\t}\n\t\t\n\t\t//Calculates the angle to rotate each slice\n\t\tvar angle = 360/this._verticalSlices;\n\t\t\n\t\t//Generation of each rotation matrix for the rendering\n\t\tfor(var i = 0;i<this._verticalSlices;i++)\n\t\t{\n\t\t\t//We rotate the object by the angle \n\t\t\tvar angleMatrix = mat4.create(); \n\t\t\tmat4.rotateY(angleMatrix, angleMatrix, glMatrix.toRadian(angle*i));\n\t\t\tthis.angleMatrixTab.push(angleMatrix)\n\t\t}\n\t\t\n\t\t//Push of the first index to complete the circle\n\t\tthis.indicesPoints.push(0);\n\t\t\n\t\t//Sets the alpha to 0.5 for catmullrom\n\t\tglContext.uniform1f(prg.alpha, 0.5);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tries to find the best matching locale. Locales should be given in the form "lang[COUNTRY]". If an exact match (i.e. both lang and country match) can be found, it is returned. Otherwise, a partial match based on the lang part is attempted. Partial matches without country are preferred over lang matches with nonmatching country. If no locale matches, null is returned. | function getBestLocaleMatch(aPreferred, aAvailable) {
aPreferred = aPreferred.toLowerCase();
var preferredLang = aPreferred.split("-")[0];
var langMatch = null;
var partialMatch = null;
for (var i = 0, current; current = aAvailable[i]; i++) {
// Both lang and country match
if (current.toLowerCase() == aPreferred)
return current;
if (current.toLowerCase() == preferredLang) {
// Only lang matches, no country
langMatch = current;
} else if (current.split("-")[0].toLowerCase() == preferredLang) {
// Only lang matches, non-matching country
partialMatch = current;
}
}
return langMatch || partialMatch;
} | [
"matchLocale(req) {\n const hostname = req.hostname;\n const locales = self.filterPrivateLocales(req, self.locales);\n let best = false;\n for (const [ name, options ] of Object.entries(locales)) {\n const matchedHostname = options.hostname\n ? (hostname === options.hostname.split(':')[0]) : null;\n const matchedPrefix = options.prefix\n ? ((req.path === options.prefix) || req.path.startsWith(options.prefix + '/'))\n : null;\n if (options.hostname && options.prefix) {\n if (matchedHostname && matchedPrefix) {\n // Best possible match\n return name;\n }\n } else if (options.hostname) {\n if (matchedHostname) {\n if (!best) {\n best = name;\n }\n }\n } else if (options.prefix) {\n if (matchedPrefix) {\n if (!best) {\n best = name;\n }\n }\n }\n }\n return best || self.defaultLocale;\n }",
"function getMatchedSupportedLocale(locale) {\n var partialLocale = locale.replace(/^([a-z]{2}).*/i, '$1');\n var matchedLocale;\n for (var i = 0; i < supportedLocales.length; i++) {\n var supportedLocale = supportedLocales[i];\n if (locale === supportedLocale) {\n matchedLocale = locale;\n break;\n }\n if (partialLocale === supportedLocale) {\n matchedLocale = partialLocale;\n }\n }\n return matchedLocale;\n }",
"function /* 9.2.2 */BestAvailableLocale(availableLocales, locale) {\n // 1. Let candidate be locale\n var candidate = locale;\n\n // 2. Repeat\n while (candidate) {\n // a. If availableLocales contains an element equal to candidate, then return\n // candidate.\n if (arrIndexOf.call(availableLocales, candidate) > -1) return candidate;\n\n // b. Let pos be the character index of the last occurrence of \"-\"\n // (U+002D) within candidate. If that character does not occur, return\n // undefined.\n var pos = candidate.lastIndexOf('-');\n\n if (pos < 0) return;\n\n // c. If pos ≥ 2 and the character \"-\" occurs at index pos-2 of candidate,\n // then decrease pos by 2.\n if (pos >= 2 && candidate.charAt(pos - 2) === '-') pos -= 2;\n\n // d. Let candidate be the substring of candidate from position 0, inclusive,\n // to position pos, exclusive.\n candidate = candidate.substring(0, pos);\n }\n}",
"normalize(locales, locale) {\n if (!locale) {\n return null;\n }\n\n // Transform Language-Country => Language_Country\n locale = locale.replace('-', '_');\n\n let search;\n\n if (api.collections.isArray(locales)) {\n search = isArrayElement;\n } else {\n search = isObjectKey;\n }\n\n if (search(locales, locale)) {\n return locale;\n }\n\n // Try to search by the language\n const parts = locale.split('_');\n const language = parts[0];\n if (search(locales, language)) {\n return language;\n }\n\n return null;\n }",
"function chooseLocale(names) {\n let next;\n let locale;\n let i = 0;\n while (i < names.length) {\n const split = normalizeLocale(names[i]).split('-');\n let j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n // the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return null;\n}",
"function /* 9.2.2 */BestAvailableLocale(availableLocales, locale) {\n\t // 1. Let candidate be locale\n\t var candidate = locale;\n\t\n\t // 2. Repeat\n\t while (candidate) {\n\t // a. If availableLocales contains an element equal to candidate, then return\n\t // candidate.\n\t if (arrIndexOf.call(availableLocales, candidate) > -1) return candidate;\n\t\n\t // b. Let pos be the character index of the last occurrence of \"-\"\n\t // (U+002D) within candidate. If that character does not occur, return\n\t // undefined.\n\t var pos = candidate.lastIndexOf('-');\n\t\n\t if (pos < 0) return;\n\t\n\t // c. If pos ≥ 2 and the character \"-\" occurs at index pos-2 of candidate,\n\t // then decrease pos by 2.\n\t if (pos >= 2 && candidate.charAt(pos - 2) === '-') pos -= 2;\n\t\n\t // d. Let candidate be the substring of candidate from position 0, inclusive,\n\t // to position pos, exclusive.\n\t candidate = candidate.substring(0, pos);\n\t }\n\t}",
"function findFallbackLocale(locale) {\n const locales = getAvailableLocales();\n\n for (let i = locale.length - 1; i > 1; i -= 1) {\n const key = locale.substring(0, i);\n\n if (locales.includes(key)) {\n return key;\n }\n }\n\n return null;\n}",
"function chooseLocale(names) {\n var i = 0, j, next, locale, split;\n while (i < names.length) {\n split = normalizeLocale(names[i]).split('-');\n j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n //the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return null;\n }",
"function getLocale(allowedLocales, longLocale) {\n longLocale = (typeof longLocale !== 'undefined') ? longLocale : false\n var i = 0;\n var localeName = Qt.locale().name;\n // qtLocale is sometimes just C\n var qtLocale;\n if (localeName == 'C') {\n qtLocale = longLocale ? 'en_GB' : 'en';\n }\n else {\n qtLocale = localeName.substring(0, (longLocale ? 5 : 2))\n }\n\n if (allowedLocales == '*') {\n return qtLocale;\n }\n\n var langCandidate = \"\";\n\n // Array.includes() would be cleaner, but didn't work for me.\n while (i < allowedLocales.length) {\n if (allowedLocales[i] == qtLocale) {\n return qtLocale;\n }\n // It wasn't an exact match, but if the language is same, save the first one\n // (ie. the most preferable by allowed order) as a fallback candidate.\n else if (allowedLocales[i].substring(0, 2) == qtLocale.substring(0, 2) && langCandidate == \"\") {\n langCandidate = allowedLocales[i];\n }\n i++\n }\n return langCandidate == \"\" ? allowedLocales[0] : langCandidate;\n}",
"function chooseLocale(names) {\n var i = 0, j, next, locale, split;\n \n while (i < names.length) {\n split = normalizeLocale(names[i]).split('-');\n j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n //the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return null;\n }",
"function chooseLocale(names) { // 1733\n var i = 0, j, next, locale, split; // 1734\n // 1735\n while (i < names.length) { // 1736\n split = normalizeLocale(names[i]).split('-'); // 1737\n j = split.length; // 1738\n next = normalizeLocale(names[i + 1]); // 1739\n next = next ? next.split('-') : null; // 1740\n while (j > 0) { // 1741\n locale = loadLocale(split.slice(0, j).join('-')); // 1742\n if (locale) { // 1743\n return locale; // 1744\n } // 1745\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { // 1746\n //the next array item is better than a shallower substring of this one // 1747\n break; // 1748\n } // 1749\n j--; // 1750\n } // 1751\n i++; // 1752\n } // 1753\n return null; // 1754\n } // 1755",
"function chooseLocale(names) {\n\t\tvar i = 0, j, next, locale, split;\n\n\t\twhile (i < names.length) {\n\t\t\tsplit = normalizeLocale(names[i]).split('-');\n\t\t\tj = split.length;\n\t\t\tnext = normalizeLocale(names[i + 1]);\n\t\t\tnext = next ? next.split('-') : null;\n\t\t\twhile (j > 0) {\n\t\t\t\tlocale = loadLocale(split.slice(0, j).join('-'));\n\t\t\t\tif (locale) {\n\t\t\t\t\treturn locale;\n\t\t\t\t}\n\t\t\t\tif (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n\t\t\t\t\t//the next array item is better than a shallower substring of this one\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tj--;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\treturn globalLocale;\n\t}",
"function chooseLocale(names) {\n var i = 0, j, next, locale, split;\n\n while (i < names.length) {\n split = normalizeLocale(names[i]).split('-');\n j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n //the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return null;\n}",
"function chooseLocale(names) {\n var i = 0, j, next, locale, split;\n \n while (i < names.length) {\n split = normalizeLocale(names[i]).split('-');\n j = split.length;\n next = normalizeLocale(names[i + 1]);\n next = next ? next.split('-') : null;\n while (j > 0) {\n locale = loadLocale(split.slice(0, j).join('-'));\n if (locale) {\n return locale;\n }\n if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {\n //the next array item is better than a shallower substring of this one\n break;\n }\n j--;\n }\n i++;\n }\n return null;\n }",
"function loadBestMatchingStrings(locale) {\n\n try {\n // Firstly try for an exact match for the supplied locale.\n strings = require(`./locales/${locale}/strings.json`)\n } catch (e) {\n // Then try for a partial match.\n strings = require(`./locales/${osLanguage(locale)}/strings.json`)\n }\n}",
"static fallbackLocale(locale, optionalLocales) {\n if (optionalLocales === undefined) {\n throw new TypeError('Invalid Arguments');\n }\n if (optionalLocales.includes(locale.toLowerCase())) {\n return locale;\n }\n const languagePolicy = new languagePolicy_1.LanguagePolicy();\n if (languagePolicy.has(locale)) {\n const fallbackLocales = languagePolicy.get(locale);\n for (const i in fallbackLocales) {\n const fallbackLocale = fallbackLocales[i];\n if (optionalLocales.includes(fallbackLocale)) {\n return fallbackLocale;\n }\n }\n }\n else if (optionalLocales.includes('')) {\n return '';\n }\n throw new Error(`there is no locale fallback for ${locale}`);\n }",
"function findSupportedLanguage(language, suppportedLanguages) {\r\n \r\n // English is the default if the language passed in is unsupported \r\n var defaultLanguage = 'en';\r\n \r\n if (language == null || language == 'ERROR') {\r\n return defaultLanguage;\r\n }\r\n \r\n var lang = language;\r\n \r\n var indexOfUnderscore = lang.indexOf('_');\r\n var languageCode = '';\r\n var countryCode = '';\r\n \r\n // Normalize language so languageCode is lowercase and countryCode is\r\n // uppercase (ex: en_US).\r\n if ( indexOfUnderscore > -1) {\r\n languageCode = lang.substring(0, indexOfUnderscore).toLowerCase();\r\n countryCode = lang.substring(indexOfUnderscore+1).toUpperCase();\r\n lang = languageCode + '_' + countryCode;\r\n } else {\r\n lang = lang.toLowerCase();\r\n }\r\n \r\n if (suppportedLanguages.indexOf(lang) > -1) {\r\n return lang;\r\n }\r\n \r\n if (indexOfUnderscore > -1) {\r\n if (suppportedLanguages.indexOf(languageCode) > -1) {\r\n return languageCode;\r\n }\r\n }\r\n\r\n return defaultLanguage;\r\n}",
"function chooseLocale(names){var i=0,j,next,locale,split;while(i<names.length){split=normalizeLocale(names[i]).split(\"-\");j=split.length;next=normalizeLocale(names[i+1]);next=next?next.split(\"-\"):null;while(j>0){locale=loadLocale(split.slice(0,j).join(\"-\"));if(locale){return locale}if(next&&next.length>=j&&compareArrays(split,next,true)>=j-1){\n//the next array item is better than a shallower substring of this one\nbreak}j--}i++}return globalLocale}",
"function findLocalisedRoute(pathName, route, language) {\n let exists = false;\n\n if (language) {\n return { exists: route.lang && route.lang[language] && route.lang[language].includes(pathName), language }\n }\n\n exists = compareRoutes(pathName, route.name);\n\n if (!exists && route.lang && typeof route.lang === 'object') {\n for (const [key, value] of Object.entries(route.lang)) {\n if (compareRoutes(pathName, value)) {\n exists = true;\n language = key;\n }\n }\n }\n\n return { exists, language }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion para mostrar los eventos del dia seleccionado | function showEvent(day,month,year){
dia_ult = day;
mes_ult = month;
ano_ult = year;
showListCalen(4,day,month,year);
} | [
"function date_click(event) {\n $(\".events-container\").show(250);\n $(\"#dialog\").hide(250);\n $(\".active-date\").removeClass(\"active-date\");\n $(this).addClass(\"active-date\");\n show_events(event.data.events, event.data.month, event.data.day);\n }",
"showEvents() {\n this.showEventTimespans();\n this.showRaterTimelines();\n }",
"function date_click(event) {\n $(\".events-container\").show(250);\n $(\"#dialog\").hide(250);\n $(\".active-date\").removeClass(\"active-date\");\n $(this).addClass(\"active-date\");\n show_events(event.data.events, event.data.month, event.data.day);\n }",
"function date_click(event) {\n $(\".events-container\").show(250);\n $(\"#dialog\").hide(250);\n $(\".active-date\").removeClass(\"active-date\");\n $(this).addClass(\"active-date\");\n // show_events(event.data.events, event.data.month, event.data.day);\n show_events_from_db(event.data.events, event.data.year, event.data.month, event.data.day);\n }",
"function date_click(event) {\n $(\".events-container\").show(250);\n $(\"#dialog\").hide(250);\n $(\".active-date\").removeClass(\"active-date\");\n $(this).addClass(\"active-date\");\n show_events(event.data.events, event.data.month, event.data.day);\n}",
"function calendario3() {\n var calendarEl = document.getElementById(\"calendar3\");\n calendarEl.innerHTML = \"\";\n\n var fecha = new Date();\n var ano = fecha.getFullYear();\n var id;\n\n var configuracionCalendario = {\n locale: \"es\",\n defaultDate: fecha,\n height: 400,\n fixedWeekCount: false,\n plugins: [\"dayGrid\", \"interaction\", \"timeGrid\"],\n\n selectable: true,\n selectMirror: true,\n /* select: function (arg) {\n $('#pruebaEnd').val(moment(arg.end).format('YYYY-MM-DD HH:mm:ss'));\n $('#pruebaStar').val(moment(arg.start).format('YYYY-MM-DD HH:mm:ss'));\n\n $('#horarioAsignar').modal('show');\n }, */\n eventClick: function (info) { },\n editable: false,\n eventLimit: true,\n header: {\n left: \"prev,next today\",\n center: \"title\",\n right: \"\",\n },\n eventRender: function (info) {\n $('.tooltip').remove();\n /* CUANNDO NO ES HORARIO */\n if (info.event.extendedProps.laborable != 1) {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Incidencia: ' + info.event.title +\n '<br> Código: ' + info.event.extendedProps.horaI +\n '<br> Tipo de Incidencia: ' + info.event.extendedProps.horaAdic +\n ' <br> Se paga: ' +info.event.extendedProps.horaF\n });\n } else {\n /* HORARIO CUANDO TIENE PAUSAS*/\n if (info.event.extendedProps.pausas != '') {\n var cadenaPausas = [];\n $.each(info.event.extendedProps.pausas, function (index, value2) {\n\n variableResult1 = ' <br> ' + value2.pausH_descripcion + ': ' + value2.pausH_Inicio + '-' + value2.pausH_Fin + ' ';\n cadenaPausas.push(variableResult1);\n })\n if (info.event.borderColor == '#5369f8') {\n if (info.event.extendedProps.horaAdic == 1) {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF +\n '<br> Horas adicionales:' + info.event.extendedProps.nHoraAdic + ' horas' +\n '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga +\n ' <br> Trabaja fuera de horario' +\n ' <br> Pausas programadas: ' + cadenaPausas\n });\n } else {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF +\n '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga +\n ' <br> Trabaja fuera de horario' +\n ' <br> Pausas programadas: ' + cadenaPausas\n });\n }\n }\n else {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF +\n '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga +\n '<br> Pausas programadas: ' + cadenaPausas\n });\n }\n }\n else {\n /* HORARIO CUANDO NO TIENE PAUSAS */\n if (info.event.borderColor == '#5369f8') {\n if (info.event.extendedProps.horaAdic == 1) {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF +\n ' <br> Horas adicionales:' + info.event.extendedProps.nHoraAdic + ' horas' +\n '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga +\n ' <br> Trabaja fuera de horario'\n });\n } else {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF + '<br> Trabaja fuera de horario' + '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga\n });\n }\n }\n else {\n $(info.el).tooltip({\n template: '<div class=\"tooltip\" role=\"tooltip\"><div class=\"tooltip-arrow\"></div><div class=\"tooltip-inner large\"></div></div>',\n html: true, title: 'Horario ' + info.event.title + ' : ' + info.event.extendedProps.horaI + '-' + info.event.extendedProps.horaF +\n '<br> Horas obligadas: ' + info.event.extendedProps.horasObliga\n });\n }\n }\n\n\n }\n },\n events: function (info, successCallback, failureCallback) {\n var idempleado = $(\"#idempleado\").val();\n var datoscal;\n $.ajax({\n type: \"POST\",\n url: \"/empleado/calendarioEmpleado\",\n data: {\n idempleado,\n },\n headers: {\n \"X-CSRF-TOKEN\": $('meta[name=\"csrf-token\"]').attr(\n \"content\"\n ),\n },\n statusCode: {\n 419: function () {\n location.reload();\n },\n },\n success: function (data) {\n successCallback(data);\n },\n error: function () { },\n });\n },\n\n /* events: \"calendario/show\", */\n };\n calendar3 = new FullCalendar.Calendar(calendarEl, configuracionCalendario);\n calendar3.setOption(\"locale\", \"Es\");\n\n calendar3.render();\n}",
"static displayEvents() {\n //for-loop der kører igennem alle events\n for (let i=0; i<listOfEvents.length; i++) {\n //node med html-tag P skabes og får tilknyttet string (eventnavn[i])\n let eventName = document.createElement(\"p\");\n eventName.innerHTML = listOfEvents[i].eventName;\n //Klasse tilføjes for at kunne bruge CSS\n eventName.classList.add(\"eventDisplay\");\n //Tilknytter (appendChild) alle eventnavne (noder som <p>) til div'en eventName\n document.getElementById(\"eventName\").appendChild(eventName);\n\n //samme fremgangsmåde\n let eventLocation = document.createElement(\"p\");\n eventLocation.innerHTML = listOfEvents[i].eventLocation;\n eventLocation.classList.add(\"eventDisplay\");\n document.getElementById(\"eventLocation\").appendChild(eventLocation);\n\n //samme fremgangsmåde\n let eventKategori = document.createElement(\"p\");\n eventKategori.innerHTML = listOfEvents[i].Category;\n eventKategori.classList.add(\"eventDisplay\");\n document.getElementById(\"eventKategori\").appendChild(eventKategori);\n\n //Skal laves drastisk om, ved implementering af tidskoder\n //samme fremgangsmåde\n let eventTid = document.createElement(\"p\");\n eventTid.innerHTML = listOfEvents[i].eventTime;\n eventTid.classList.add(\"eventDisplay\");\n document.getElementById(\"eventTid\").appendChild(eventTid);\n\n //samme fremgangsmåde\n let eventHost = document.createElement(\"p\");\n eventHost.innerHTML = listOfEvents[i].eventHost;\n eventHost.classList.add(\"eventDisplay\");\n document.getElementById(\"eventVært\").appendChild(eventHost);\n\n //samme fremgangsmåde\n let eventBeskrivelse = document.createElement(\"p\");\n eventBeskrivelse.innerHTML = listOfEvents[i].eventDescription;\n eventBeskrivelse.classList.add(\"eventDisplay\");\n document.getElementById(\"eventBeskrivelse\").appendChild(eventBeskrivelse);\n\n //samme fremgangsmåde\n let eventKapacitet = document.createElement(\"p\");\n\n //Metode der skal beregne om et event har kapacitet\n //Variabel der tager det valgte index af listOfEvents\n events = listOfEvents[i];\n //Variabel der bestemmer antal pladser tilbage i et event, ved at trække længden af array'et eventParticipants fra eventCapacity som er et nummer\n remainingCapacity = events.eventCapacity - events.eventParticipants.length;\n eventKapacitet.innerHTML = remainingCapacity;\n eventKapacitet.classList.add(\"eventDisplay\");\n document.getElementById(\"eventKapacitet\").appendChild(eventKapacitet);\n\n //Tilmeldningsknap (join-metode)\n let tilmeldEvent = document.createElement(\"p\");\n tilmeldEvent.innerHTML = \"Tilmeld\";\n tilmeldEvent.classList.add(\"eventDisplay\");\n //Jeg kunne ikke få værdien af index i loop ud af loop'et uden at funktionen kørte sammen med loop'et, hvorfor funktionen er skrevet herinde\n //addeventlistener der tjekker om der bliver klikket på noden. Hvis der klikkes køres funktionen nedenfor.\n tilmeldEvent.addEventListener('click', function () {\n //variabel der tager det event der bliver klikket på\n subscribedEvent = listOfEvents[i];\n EventUtility.subscribe();\n });\n document.getElementById(\"tilmeldEvent\").appendChild(tilmeldEvent);\n }\n }",
"function show_events(events, month, day) {\n // Clear the dates container\n $(\".events-container\").empty();\n $(\".events-container\").show(250);\n // If there are no events for this date, notify the user\n if (events.length === 0) {\n var event_card = $(\"<div class='event-card'></div>\");\n var event_name = $(\"<div class='event-name'>There are no events planned for \" + month + \" \" + day + \".</div>\");\n $(event_card).css({\"color\": \"#FF1744\"});\n $(event_card).append(event_name);\n $(\".events-container\").append(event_card);\n } else {\n // Go through and add each event as a card to the events container\n for (var i = 0; i < events.length; i++) {\n var jour = events[i].day; var mois= events[i].month;\n if((events[i].day).toString().length === 1){\n jour = \"0\"+events[i].day;\n }\n if((events[i].month).toString().length === 1){\n mois = \"0\"+events[i].month;\n }\n var dateDebut = events[i].year + \"-\" + mois + \"-\" + jour;\n var dateFin = events[i].dateFin;\n var event_card = $('<div class=\"event-card\"></div>');\n var event_name = $(\"<div class='event-name'>Essai n°\" + events[i][\"essai\"] + \":</div>\");\n var event_essai = $(\"<div class='event-count'>Projet n°\" + events[i][\"projet\"] + \"</div>\");\n var event_Config = $(\"<div class='event-count'>\" + events[i][\"plateforme\"] + \": \" + events[i][\"config\"] + \"</div>\");\n var modif_date = $('<span class=\"datepicker-toggle\"> <span class=\"datepicker-toggle-button\"><input type=\"date\" id=\"' + events[i][\"essai\"] + '\"class=\"datepicker-input\" onchange=\"updateDate(this.id,this.value)\">📅</span></span>');\n var print_dateFin;\n if(dateDebut !== dateFin){\n print_dateFin = $(\"<br><div class='event-count'> date de fin de l'essai: \" + dateFin + \"</div>\");\n }\n var valid_essai = $(\"<div class='event-count'><a id='\"+events[i].essai+\"' onclick='validationEssai(this.id)' style='cursor: pointer;'>🚩 </a></div>\");\n if (events[i][\"cancelled\"] === true) {\n $(event_card).css({\n \"border-left\": \"10px solid #FF1744\"\n });\n event_count = $(\"<div class='event-cancelled'>Cancelled</div>\");\n }\n\n $(event_card).append(event_name).append(event_essai).append(modif_date).append(event_Config).append(print_dateFin).append(valid_essai);\n $(event_name).css({\n \"color\": events[i][\"couleur\"]\n });\n $(\".events-container\").append(event_card);\n }\n }\n }",
"function date_click(event) {\n $(\".events-container\").show(250);\n $(\"#dialog\").hide(250);\n $(\".active-date\").removeClass(\"active-date\");\n $(this).addClass(\"active-date\");\n //!!!! this is where we want to create function for when date is clicked\n // !!!! figure out date -> year collection\n var date = event.data.date;\n var year = document.getElementById(\"label\").innerHTML;\n console.log(year + \" testing year parameter\");\n \n show_events(event.data.events, event.data.month, event.data.day, year);\n \n }",
"function constroiEventos(){}",
"function show_events(events, month, day) {\n // Clear the dates container\n $(\".events-container\").empty();\n $(\".events-container\").show(250);\n console.log(event_data[\"events\"]);\n // If there are no events for this date, notify the user\n if (events.length === 0) {\n var event_card = $(\"<div class='event-card'></div>\");\n var event_name = $(\"<div class='event-name' style='color: black'>Chưa có hoạt động nào trong \" + month + \" \" + day + \".</div>\");\n $(event_card).css({\"border-left\": \"10px solid #FF1744\"});\n $(event_card).append(event_name);\n $(\".events-container\").append(event_card);\n } else {\n // Go through and add each event as a card to the events container\n for (var i = 0; i < events.length; i++) {\n var event_card = $(\"<div class='event-card'></div>\");\n var event_name = $(\"<div class='event-name'>\" + events[i][\"name\"] + \":</div>\");\n var event_count = $(\"<div class='event-count'>\" + events[i][\"money_amount\"] + \"</div>\");\n $(event_card).append(event_name).append(event_count);\n $(\".events-container\").append(event_card);\n }\n }\n }",
"function event_select(){\n let events = elements_array[_g('#elements').selectedIndex].events;\n let select_event = _g('#select_subproperties');\n select_event.innerHTML = \"\";\n if (\n elements_count(events) > 0\n ){\n select_event.style = \"visibility: visible;\";\n for (event_id in events){\n let node = document.createElement(\"option\"); // Create a <option> node\n let textnode = document.createTextNode(event_id); // Create a text node\n node.id = event_id;\n node.appendChild(textnode);\n select_event.appendChild(node);\n }\n select_event.selectedIndex = 0;\n }else{\n select_event.style = \"visibility: hidden;\";\n }\n}",
"function dayClicked(event){\n var selectedCell = this.id;\n selectedDate = getCellDate(selectedCell);\n var eventlist = getCellEventData(selectedCell);\n eventEditorContent.innerHTML = eventlist;\n eventEditor.style.display = \"block\";\n}",
"function showSelectedDays() {\r\n var selectedDates = data.selectedDates;\r\n for (var index in selectedDates) {\r\n var day = selectedDates[index][\"day\"];\r\n var month = selectedDates[index][\"month\"];\r\n var year = selectedDates[index][\"year\"];\r\n showAsSelected(day, month, year);\r\n }\r\n }",
"function showEvent(event) {\n let day_name = getDayName(event['day'] - 1);\n let cur_day = document.querySelector('#'+day_name + ' .day_body');\n let event_div = document.createElement('div');\n event_div.classList.add('event');\n event_div.id = event['id'];\n\n let ev_title = document.createElement('h5');\n let ev_body = document.createElement('p');\n ev_title.innerHTML = event.title;\n ev_body.innerHTML = event.body;\n event_div.appendChild(ev_title);\n event_div.appendChild(ev_body);\n let type = event.type.toLowerCase();\n\n event_div.classList.add(type);\n\n if(event.type != 'Wait') cur_day.appendChild(event_div);\n\n // done event\n if(event.done == 1) {\n event_div.classList.add('done');\n }\n}",
"function show_events(events, month, day) {\n // Clear the dates container\n $(\".events-container\").empty();\n $(\".events-container\").show(250);\n console.log(event_data[\"events\"]);\n // If there are no events for this date, notify the user\n if (events.length === 0) {\n var event_card = $(\"<div class='event-card'></div>\");\n var event_name = $(\"<div class='event-name'>Não há doações agendadas para o dia \" + day + \" \" + month + \".</div>\");\n $(event_card).css({ \"border-left\": \"10px solid #FF1744\" });\n $(event_card).append(event_name);\n $(\".events-container\").append(event_card);\n }\n else {\n // Go through and add each event as a card to the events container\n for (var i = 0; i < events.length; i++) {\n var event_card = $(\"<div class='event-card'></div>\");\n var event_count = $(\"<div class='event-count'>Hora: \" + events[i][\"invited_count\"] + \"</div>\");\n var event_name = $(\"<div class='event-name'>Doador: \" + events[i][\"occasion\"] + \"</div>\");\n if (events[i][\"cancelled\"] === true) {\n $(event_card).css({\n \"border-left\": \"10px solid #FF1744\"\n });\n event_count = $(\"<div class='event-cancelled'>Cancelled</div>\");\n }\n $(event_card).append(event_count).append(event_name);\n $(\".events-container\").append(event_card);\n }\n }\n }",
"function setDate(button, date){\n debugger;\n button.addEventListener('click', function(){\n var cards = document.getElementsByClassName(date);\n var noEvents = document.getElementById('empty');\n var eventCards = document.getElementsByClassName('events');\n if(cards.length != 0){\n //hide the no events card\n noEvents.style.display = 'none';\n for(i=0;i<eventCards.length;i++){\n eventCards[i].style.display = 'none';\n }\n for(i=0;i<cards.length;i++){\n cards[i].style.display = 'block';\n }\n }\n else{\n for(i=0;i<eventCards.length;i++){\n eventCards[i].style.display = 'none';\n }\n var noEvents = document.getElementById('empty');\n noEvents.style.display = 'block';\n }\n });\n}",
"function seleccionarDia () {\n \n var fecha = $('#fechas_seleccionadas_cita').val();\n globalFecha = fecha;\n var idMedico = $('#idMedico').text();\n\n if (fecha) {\n var date = new Date(fecha);\n //alert(date, idMedico);\n var obj_dates_idMedico = _dates_idMedico(fecha, date.getDay(), idMedico);\n tramosDisponibles(obj_dates_idMedico);\n\n } else { \n alert(\"Selecione una fecha\");\n }\n}",
"function showEvents() {\r\n /** check if organizer is switched on */\r\n if (!switchOrganizer) {\r\n switchedOffOrganizerMessage();\r\n return;\r\n }\r\n\r\n /** check if there are any events in the localStorage */\r\n if (checkAvailability('events') === false) {\r\n console.log(noEventsAvailable);\r\n return;\r\n }\r\n\r\n let archieve = arguments[0];\r\n console.log('Events list: ');\r\n getEvents().forEach(function (item) {\r\n /** check which events to show */\r\n if (archieve === undefined || archieve === '') {\r\n /** shows all events */\r\n printEvents(item);\r\n } else {\r\n /** shows only active/archieved events */\r\n if (item.archieve === archieve) {\r\n printEvents(item);\r\n }\r\n }\r\n });\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create single row of the go link table, with the given key and url. Args: key go shortcut url target of go shortcut. | function generateMapTableRow(key, url) {
var line = $("<tr key='"+key+"'>");
line.append("<td>"+key+"</td>");
line.append("<td><a href='"+url+"'>"+url+"</a></td>");
var delete_btn = $("<button type='button'"+
" class='btn btn-xs btn-danger'>"+
"<span class='glyphicon glyphicon-remove'></span>"+
"</button>");
var btn_td = $("<td class='text-center'>");
btn_td.append(delete_btn);
line.append(btn_td);
delete_btn.click(function(e) {
var row = $(e.target).parents("tr");
var key = row.children("td").first().text();
bgPage.clearMapping(key);
row.remove();
setAlertMessage("Successfully removed mapping for \""+key+"\"",
"success");
});
return line;
} | [
"function addLinksTableRow(table, key, value, index) {\n\tvar tr = document.createElement('tr');\n\n\tvar keyTd = document.createElement('td');\n\tkeyTd.appendChild(document.createTextNode(key));\n\ttr.appendChild(keyTd);\n\n\tvar valueTd = document.createElement('td');\n\tvalueTd.appendChild(document.createTextNode(value))\n\ttr.appendChild(valueTd);\n\n\tvar deleteTd = document.createElement('td');\n\tvar deleteBttn = document.createElement('button');\n\tdeleteBttn.innerHTML = \"delete\";\n\tdeleteBttn.onclick = function() { deleteGoLink(key, value, tr); }\n\tdeleteTd.appendChild(deleteBttn);\n\ttr.appendChild(deleteBttn);\n\t\n\ttable.appendChild(tr);\n}",
"function add_row(email, key, link) {\n\n var $row = $key_table.find('tr[data-template]').clone();\n\n $row.removeAttr('data-template');\n $row.attr('data-email', email);\n $row.find('[data-user-email]').text(email);\n $row.find('[data-user-link]').text(link).attr('href', link);\n $row.find('[data-user-key-delete]').attr('data-email', email);\n\n if (!$key_table.find('tbody tr:not([data-template])').length) {\n $user_keys_container.fadeIn();\n }\n\n $key_table.find('tbody').append($row);\n\n $row.fadeIn();\n }",
"function makeItemLink(key, linkLi) {\n\t\tvar editLink = document.createElement('a');\n\t\teditLink.href = \"#editRide\";\n\t\teditLink.key = key;\n\t\t// assigns the variable that was passed\n\t\tvar editText = \"Edit trail\";\n\t\t//editLink.addEventListener(\"click\", editTrail);\n\t\teditLink.innerHTML = editText;\n\t\tlinkLi.setAttribute(\"class\", \"modLinks\");\n\t\tlinkLi.appendChild(editLink);\n\n\t\t// add a line break \n\t\tvar breakTag = document.createElement('br');\n\t\tlinkLi.appendChild(breakTag);\n\n\t\tvar deleteLink = document.createElement('a');\n\t\tdeleteLink.href = \"#\";\n\t\tdeleteLink.key = key;\n\t\tvar deleteText = \"Delete trail\";\n\t\t//deleteLink.addEventListener(\"click\", deleteTrail);\n\t\tdeleteLink.innerHTML = deleteText;\n\t\tlinkLi.appendChild(deleteLink);\n\t}",
"function makeTableRow(data, item, key) {\n var row = document.createElement(\"tr\");\n\n var cell = document.createElement(\"td\");\n cell.innerHTML = item;\n row.appendChild(cell);\n\n cell = document.createElement(\"td\");\n cell.innerHTML = data;\n row.appendChild(cell);\n\n return row;\n}",
"addUrl(gameKey) {\n\t\tconst url = `${window.location.href}${gameKey}`;\n\t\tconst msg = `invite yOur friends:\\n\\n${url}`;\n\t\tconst link = this.add.text(100, 100, msg);\n\t\tlink.setInteractive();\n\t\tlink.on(\"pointerdown\", () => {\n\t\t\tnavigator.clipboard.writeText(url);\n\t\t\tlink.setText(\"cOpied!\");\n\t\t});\n\t\treturn link;\n\t}",
"function createEditLink (key, eLink) {\n var linkEdit = makeTag('a');\n linkEdit.href = '#';\n linkEdit.id = 'editS';\n linkEdit.key = key;\n var textEdit = \"Edit Schedule\";\n linkEdit.addEventListener(\"click\", editSchedule);\n linkEdit.innerHTML = textEdit;\n eLink.appendChild(linkEdit);\n }",
"static addTableRow(table, keyValue, labelValue)\n {\n var rowIdx = table.rows.length\n\n var row = table.insertRow(rowIdx);\n var key = row.insertCell(0);\n var value = row.insertCell(1);\n // table data\n key.classList.add(\"pkg_content-td\");\n key.classList.add(\"pkg_content-key\");\n\n value.classList.add(\"pkg_content-td\");\n value.classList.add(\"pkg_content-value\");\n\n key.innerHTML = keyValue\n value.innerHTML = labelValue\n }",
"function add_link_row(table_id)\n{\n\t//Get the table element\n\tvar table = document.getElementById(table_id);\n\t\n\tvar link_num = parseInt(table.rows.length - 1);\n\t\n\t//Create a new row\n\tvar row = table.insertRow(table.rows.length - 1);\n\t\n\t//Insert the cells\n\tvar cell1 = row.insertCell(0);\n\tvar cell2 = row.insertCell(1);\n\tvar cell3 = row.insertCell(2);\n\t\n\t//Add the contents to the cells\n\tcell1.innerHTML = link_num;\n\t\n\tcell2.innerHTML = '<input type=\"number\" value=\"0\" name=\"global_link_' + link_num + '_loss\" id=\"global_link_' + link_num + '_loss\" max=\"100\" min=\"0\" maxlength=\"3\" size=\"3\"/></label>%';\n\t\n\tcell3.innerHTML = '<input type=\"button\" value=\"Remove Link\" class=\"rowRemoveButton\";\\'/>';\n\t\n\t\n\t\n\t\n}",
"function createPollLinks(key) {\n\n var pollURL = \"/poll/\";\n var resultURL = \"/result/\";\n var result1 = pollURL + key;\n var result2 = resultURL + key;\n\n var link1 = $(\"<a>Link to Poll</a>\").attr('href', result1);\n $('#links').append(link1).append('<br>');\n\n // var link2 = $(\"<a>Link to Results</a>\").attr('href', result2);\n // $('#links').append(link2).append('<br>');\n\n }",
"getLink(key) {\n return this.links.get(key);\n }",
"createLinkBetweenTargetAndSource(row, target, source){\n\t\tlet link = {};\n\t\tlink.source = source;\n\t\tlink.target = target;\n\t\tlink.correlation = row[target];\n\t\treturn link;\n\t}",
"function createTrashRowElement(key) {\n let trashRowElement = document.createElement(\"th\");\n trashRowElement.setAttribute(\"scope\",\"row\");\n let trashLink = createHtmlElement(\"a\",\"trash-link\");\n trashLink.setAttribute(\"value\", key);\n let trashIcon = createHtmlElement(\"i\",\"fas fa-trash-alt\");\n trashLink.appendChild(trashIcon);\n trashRowElement.appendChild(trashLink);\n return trashRowElement;\n}",
"function linkcell(thing) {\n\t\tif(thing !== undefined) {\n\t\t\tvar content = $(\"<a>\");\n\t\t\tif (thing.url !== undefined)\n\t\t\t\tcontent.attr(\"href\", thing.url);\n\t\t\tvar name = thing.name;\n\t\t\tif (name === undefined)\n\t\t\t\tname = \"UNDEFINED\";\n\t\t\treturn cell().append(content.text(name));\n\t\t}\n\t\treturn cell();\n\t}",
"function makeItemLinks (key, linksLi) {\n\t\t// add edit single item link\n\t\tvar editLink = document.createElement(\"a\");\n\t\teditLink.href = \"#\";\n\t\teditLink.key = key;\n\t\tvar editText = \"Edit Beer Info\";\n\t\teditLink.addEventListener(\"click\", editItem);\n\t\teditLink.innerHTML = editText;\n\t\tlinksLi.appendChild(editLink);\n\t\t\n\t\t\n\t\t//add line break\n\t\tvar breakTag = document.createElement(\"br\");\n\t\tlinksLi.appendChild(breakTag);\n\t\t\n\t\t\n\t\t// add delete single item link\n\t\tvar deleteLink = document.createElement(\"a\");\n\t\tdeleteLink.href = \"#\";\n\t\tdeleteLink.key = key;\n\t\tvar deleteText = \"Delete Beer Info\";\n\t\tdeleteLink.addEventListener(\"click\", deleteItem);\n\t\tdeleteLink.innerHTML = deleteText;\n\t\tlinksLi.appendChild(deleteLink);\n\t\t\n\t}",
"function add_link(index1, index2, row) {\n var id = index1 + '\\t' + index2\n if (id in link_index)\n links[link_index[id]].rows.push(row)\n else {\n link_index[id] = links.length\n links.push({\n source: nodes[index1],\n target: nodes[index2],\n id: id,\n rows: [row]\n })\n }\n }",
"function createItemLinks(key, linkLi){\n var editLink = document.createElement('a');\n editLink.href = \"#\";\n editLink.key = key;\n var editTxt = \"Edit Order\";\n editLink.addEventListener(\"click\", editItem);\n editLink.innerHTML = editTxt;\n linkLi.appendChild(editLink);\n \n var delLink = document.createElement('a');\n delLink.href = \"#\";\n delLink.key = key;\n var delTxt = \"Delete Order\";\n delLink.addEventListener(\"click\", delItem)\n delLink.innerHTML = delTxt;\n linkLi.appendChild(delLink);\n \n \n }",
"function makeItemLinks(key, linksLi){\n\t\t// Edit single item link\n\t\tvar editLink = document.createElement('a');\n\t\teditLink.href = \"#\";\n\t\teditLink.key = key;\n\t\tvar editText = \"Edit Relative\";\n\t\teditLink.addEventListener(\"click\", editItem);\n\t\teditLink.innerHTML = editText;\n\t\tlinksLi.appendChild(editLink);\n\t\t\n\t\t// Line Break Tag\n\t\tvar breakTag = document.createElement('br');\n\t\tlinksLi.appendChild(breakTag);\n\t\t\n\t\t// Delete single item link\n\t\tvar deleteLink = document.createElement('a');\n\t\tdeleteLink.href = \"#\";\n\t\tdeleteLink.key = key;\n\t\tvar deleteText = \"Delete Relative\";\n\t\tdeleteLink.addEventListener(\"click\", deleteItem);\n\t\tdeleteLink.innerHTML = deleteText;\n\t\tlinksLi.appendChild(deleteLink);\n\t}",
"function makeItemLinks (key, linksLi){\n\t\t//add edit single item link\n\t\tvar editLink = document.createElement('a');\n\t\teditLink.href = \"#\";\n\t\teditLink.key = key;\n\t\tvar editText = \"Edit Task\";\n\t\teditLink.addEventListener(\"click\", editItem);\n\t\teditLink.innerHTML = editText;\n\t\tlinksLi.appendChild(editLink);\n\t\t\n\t\t//add delete single item link\n\t\tvar deleteLink = document.createElement('a');\n\t\tdeleteLink.href = \"#\";\n\t\tdeleteLink.key = key;\n\t\tvar deleteText = \"Delete Task\";\n\t\t//deleteLink.addEventListener(\"click\", deleteItem);\n\t\tdeleteLink.innerHTML = deleteText;\n\t\tlinksLi.appendChild(deleteLink);\n\t}",
"function openLink(table, index, isCommandPressed) {\n var rows = table.find(\"tr\");\n var row_index = index * 3;\n\n var url;\n if (index === NUMBER_ROWS_PER_PAGE) {\n var more = rows[index * 3 + 1];\n url = $(more).find(\"a\")[0].href;\n } else {\n var row = $(rows[row_index]);\n var title = $(row.find(\"td:nth-of-type(3)\"));\n var link = title.children(\"a\");\n url = link[0].href;\n }\n\n var window_name = isCommandPressed ? \"_blank\" : \"_self\";\n\n window.open(url, window_name);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cookie structure description1+price1+image1&description2+price2+image2&... The "&" simbol separe products and the "+" sign separe info. | function setCookie(description, price, image) {
var cookie = description + "+" + price + "+" + image;
var previousCookie = getCookie();
if (previousCookie == "") {
// If cookie is empty just add the info.
document.cookie = "products" + "=" + cookie + ";path=/";
}
else {
// If cookie is not empty append an "&" sign.
document.cookie = "products" + "=" + previousCookie + "&" + cookie + ";path=/";
}
} | [
"function ppcUrlCookiePart1() {\r\n //setup list/array of parameters desired. names on right should match querystring names\r\n var param_names = new Array(\r\n 'ppcSource;utm_source',\r\n 'ppcMedium;utm_medium',\r\n 'ppcCampaign;utm_campaign',\r\n 'ppcKeyword;utm_term',\r\n );\r\n\r\n\r\n //loop through all params and create cookie\r\n for (i = 0; i < param_names.length; i++) {\r\n var param_object = param_names[i].split(\";\");//split out the cookie name and url name\r\n var param_name = param_object[0];\r\n var param_url_name = param_object[1];\r\n //start the cookie creation\r\n checkCookie(param_name, param_url_name);\r\n }\r\n}",
"function parseAndStoreRawCookie(tabId, url, cookieRaw){\r\n if(DEBUG) {\r\n\t//console.log(\"Attempting to parse raw cookie string: \" + cookieRaw);\r\n }\r\n var cookieObj = {};\r\n cookieObj.url = url;\r\n \r\n var cKey = getKeyfromPId(getPseudoId(tabId, url).split(\"&\")[0]);\r\n \r\n var cookieParts = cookieRaw.split(';');\r\n\r\n if(DEBUG) {\r\n\t//console.log(cookieParts);\r\n }\r\n\r\n for( var i=0; i<cookieParts.length; i++){\r\n if(cookieParts[i].length == 0)\r\n continue;\r\n \r\n //remove the whitespace\r\n var cString = cookieParts[i].replace(/^\\s+|\\s+$/g,\"\");\r\n \r\n var splitIndex = cString.indexOf(\"=\");\r\n \r\n var namePart = cString.substring(0, splitIndex);\r\n var valuePart = cString.substring(splitIndex+1, cString.length);\r\n \r\n \r\n //first part is the name value pair\r\n if( i == 0 ){\r\n cookieObj.name = cKey + namePart;\r\n cookieObj.value = valuePart;\r\n }\r\n else if( namePart.toLowerCase() == \"path\" ){\r\n cookieObj.path = valuePart;\r\n }\r\n else if( namePart.toLowerCase() == \"domain\" ){\r\n cookieObj.domain = valuePart;\r\n }\r\n //else if( partSplit[0].toLowerCase() == \"max-age\" ){\r\n //not sure what to do here....\r\n //}\r\n else if( namePart.toLowerCase() == \"expires\" ){\r\n //convert the gmt string to seconds since the unix epoch\r\n var date = new Date(valuePart);\r\n cookieObj.expirationDate = date.getTime() / 1000;\r\n if(cookieObj.expirationDate == NaN){\r\n console.log(\"reserve here to catch bug\");\r\n //console.log(\"valuePart:\" + valuePart);\r\n }\r\n }\r\n else if( cString == \"secure\" ){\r\n //attention! secure property is not a key-value pair\r\n cookieObj.secure = true;\r\n }\r\n else{\r\n console.log(\"set Raw Unknown part!!!! cookie: \" + cString); \r\n }\r\n }\r\n if(DEBUG) {\r\n\t//console.log(cookieObj);\r\n }\r\n chrome.cookies.set(cookieObj);\r\n}",
"function cookie(context) {\n var split, layer, valeur, debut, fin;\n\n split = '|';\n layer = context+split;\n valeur = '';\n\n if(document.cookie.indexOf('carbone_cookie_backoffice=')!=-1) {\n debut = document.cookie.indexOf('carbone_cookie_backoffice=')+26;\n fin = document.cookie.indexOf(';',debut);\n if (fin < 0) fin = document.cookie.length;\n valeur=unescape(document.cookie.substring(debut,fin));\n }\n\n if(valeur.indexOf(layer)!=-1)\n valeur = valeur.replace(layer, '');\n else\n valeur = valeur+layer;\n\n return valeur;\n\n }",
"function ReadShopCartCookie(){\nvar allcookies = document.cookie;\n//alert(allcookies);\nvar pos = allcookies.indexOf(\"ACXShopCart=\");\n\tif (pos != -1){\n\t\tvar start = pos+12;\n\t\tvar end = allcookies.indexOf(\";\",start);\n\t\tif (end == -1) {end=allcookies.length;}\n\t\tvar ShopCartString = allcookies.substring(start,end);\n\t\tShopCartString = unescape(ShopCartString);\n\t}\n\telse{ShopCartString= \"\";}\n//alert(\"Read cookie:\\n \" + ShopCartString);\nreturn ShopCartString;\n}",
"function AddcurrencyCookies() {\n\tcurrencyCookies = currencyCookies + cookieIncome/10;\n\tclickBonus = cookieIncome;\n\tclickPower = clickPowerBase + clickBonus;\n}",
"function embedCookie(realCookieName, virtualCookieName, virtualCookieValue) { // returns nbr embedded cookies\n \n //alert(\"embedCookie(\" + realCookieName + \", \" + virtualCookieName + \", \" + virtualCookieValue + \"')\");\n virtualCookieName = escape(virtualCookieName);\n if (virtualCookieValue && virtualCookieValue != \"\")\n virtualCookieValue = escape(virtualCookieValue);\n \n var realCookie = getCookie(realCookieName);\n if (!realCookie) {\n if (virtualCookieValue) {\n var realCookieValue = virtualCookieName + embeddedAttrValSep + virtualCookieValue;\n //alert(\"No realCookie\\nCalling setCookie() with realCookieValue:\\n\" + realCookieValue);\n setCookie(realCookieName, realCookieValue);\n //alert(\"embedCookie()\\nAfter setCookie()\\ngetCookie()=\" + getCookie(realCookieName));\n return 1;\n }\n else {\n //alert(\"embedCookie()\\nrealCookie is null and virtualCookieValue is null.\\nReturning 0\");\n return 0;\n }\n }\n /*\n if (!virtualCookieValue)\n alert(\"embedCookie()\\nrealCookie=\" + realCookie);\n */\n var embeddedCookies = realCookie.split(embeddedCookieSep);\n /*\n str = \"embeddedCookies:\\n\";\n for (var i = 0; i < embeddedCookies.length; i++) \n str += embeddedCookies[i] + \"\\n\";\n alert(str);\n */\n \n var newCookie = \"\";\n if (virtualCookieValue)\n newCookie = virtualCookieName + embeddedAttrValSep + virtualCookieValue; // updated virtual cookie - head of list\n for (var i = 0; i < embeddedCookies.length; i++) {\n var attrValue = embeddedCookies[i].split(embeddedAttrValSep);\n //alert(\"realCookieName=\" + realCookieName + \"\\n\\nembeddedCookies[\" + i + \"]=\" + embeddedCookies[i]);\n if (attrValue[0] != \"\" && attrValue[0] != virtualCookieName) {\n if (!virtualCookieValue)\n ; //alert(\"attrValue[0]=\" + attrValue[0] + \"\\nvirtualCookieName=\" + virtualCookieName);\n if (realCookie.length + newCookie.length + embeddedCookies[i].length < 4090) { // 4K max cookie size\n if (newCookie != \"\")\n newCookie += embeddedCookieSep + embeddedCookies[i];\n else\n newCookie = embeddedCookies[i];\n //alert(\"attrValue[0]=\" + attrValue[0] + \"\\nnewCookie=\" + newCookie);\n }\n }\n else {\n if (!virtualCookieValue)\n ; //alert(\"Skipping\\nattrValue[0]=\" + attrValue[0] + \"\\nvirtualCookieName=\" + virtualCookieName + \"\\nnewCookie=\" + newCookie);\n }\n }\n if (newCookie != \"\")\n setCookie(realCookieName, newCookie);\n else\n clearCookie(realCookieName, false);\n //alert(\"embedCokie()\\nAfter setCookie()\\ngetCookie()=\" + getCookie(realCookie));\n return embeddedCookie.length;\n}",
"function splitCookieString(cookie) {\r\n if(cookie.indexOf('###') != -1)\r\n console.error(\"PID might not be striped from cookie: \" + cookie);\r\n\r\n var index = cookie.indexOf('=');\r\n \r\n var name = cookie.substring(0, index);\r\n //Add the +1 to skip the '='\r\n var value = cookie.substring(index+1, cookie.length);\r\n \r\n return {'name':name, 'value':value};\r\n}",
"function storeLickFormValues(form){\n for (let i = 0; i < 16; i++){\n let chord = 'chord_'+(i+1).toString()\n setCookie('f_'+chord, form.elements[chord].value);\n }\n\n\n // only remember instrument if it is not 'other'\n if (form.elements['id_instrument'].value != '5'){\n setCookie(\"id_instrument\", form.elements['id_instrument'].value);\n } else {\n setCookie(\"id_instrument\", '');\n }\n // remember tags\n setCookie(\"tags\", tags);\n\n // remember ts\n\n if (form.elements['id_time_signature_2'].checked){\n setCookie(\"newlick_ts\", \"34\");\n } else {\n setCookie(\"newlick_ts\", \"44\");\n }\n\n\n}",
"function getcookiedata() {\n var cookie = document.cookie;\n \n cookie = cookie.split(\"; \");\n \n var len = cookie.length;\n var data = {};\n\n for (var i = 0; i < len; i++) {\n cookie[i] = cookie[i].split(\"=\");\n data[cookie[i][0]] = cookie[i][1];\n }\n return data;\n }",
"function submitPizza(){\n \n \n setCookie(\"pizza_size\", pizza_size, 2, \"order_contact.html\");\n setCookie(\"pizza_crust\", pizza_crust, 2, \"order_contact.html\");\n setCookie(\"pizza_type\", pizza_type, 2, \"order_contact.html\");\n setCookie(\"pizza_toppings\", toppingsString, 2, \"order_contact.html\");\n setCookie(\"price\", price, 2, \"order_contact.html\");\n setCookie(\"tax\", tax, 2, \"order_contact.html\");\n setCookie(\"total\", total, 2, \"order_contact.html\");\n}",
"function putKeyWordsInCookies(j)\n{\n\tvar i = encodeURIComponent(j);\n\tif(getCookie(\"kws\") == null)\n\t{\n\t\tkws += i + \"@\";\n\t\tsetCookie(\"kws\",kws);\n\t}\n\telse\n\t{\n\t\tvar ky = getCookie(\"kws\");\n\t\tif(ky.indexOf(i) < 0)\n\t\t{\n\t\t\tky += i + \"@\";\n\t\t\tsetCookie(\"kws\",ky);\n\t\t}\n\t\tconsole.log(\"ky=\"+ky);\n\t}\n\tconsole.log(\"putKeyWordsInCookies.i=\"+i);\n}",
"function cookieForms(formName, mode) \n{ \n mfrm = eval(\"document.\" + formName);\n len = mfrm.elements.length;\n var cookieValue = '';\n if(mode == 'load') {\t\t\n //alert(\" MOAD IS LOAD...\");\n if(getCookie(\"NoOfFormParts\") != \"\"){ \n //alert(\"NoOfFormParts = \"+getCookie(\"NoOfFormParts\"));\n // if cookie max value exceed its limit get remaing value from \"saved_formName1\"\t\t\t\n for(var i=1; i<= getCookie(\"NoOfFormParts\"); i=i+1)\n\tcookieValue += getCookie('saved_'+formName + i);\n\t}\n\telse\n\t{\n\t cookieValue = getCookie('saved_'+formName);\n\t}\t\t\n\n\tif(cookieValue != null) {\n var cookieArray = cookieValue.split('#cf#');\n\tif(cookieArray.length == mfrm.elements.length) {\n\tfor(i=0; i<mfrm.elements.length; i++) {\n if(cookieArray[i].substring(0,6) == 'select') {\n mfrm.elements[i].options.selectedIndex = parseInt(cookieArray[i].substring(6, cookieArray[i].length),10); \n }\n else if(cookieArray[i].substring(0,6) == 'selmul') {\n cookieArray[i] = cookieArray[i].substring(6,cookieArray[i].length); \n if(cookieArray[i].substring(cookieArray[i].length,cookieArray[i].length-1)==\"*\")\n {\n cookieArray[i] = cookieArray[i].substring(0,cookieArray[i].length-1); \n for(var j=0;j<cookieArray[i].split('*').length;j++)\n {\n /*\n if(j<=mfrm.elements[i].options.length)\n {\n break;\n }\n */\n var x =parseInt(cookieArray[i].split('*')[j],10); \n if(mfrm.elements[i].options[x])\n mfrm.elements[i].options[x].selected = true; \n } \n } \n } \n else if((cookieArray[i] == 'cbtrue') || (cookieArray[i] == 'rbtrue')) { mfrm.elements[i].checked = true; }\n\n else if((cookieArray[i] == 'cbfalse') || (cookieArray[i] == 'rbfalse')) { mfrm.elements[i].checked = false; }\n\t\t\t\t\t\n\telse { if(mfrm.elements[i].type != \"file\") { mfrm.elements[i].value = (cookieArray[i]) ? cookieArray[i] : ''; } }\n\n }\n }\n }\n} // load\n\n if(mode == 'save') {\t\n cookieValue = '';\t\n for(i=0; i<mfrm.elements.length; i++) {\n\t fieldType = mfrm.elements[i].type;\n if(fieldType == 'password') { passValue = ''; }\n\n else if(fieldType == 'checkbox') { passValue = 'cb'+mfrm.elements[i].checked; }\n\n else if(fieldType == 'radio') { passValue = 'rb'+mfrm.elements[i].checked; }\n\n else if(fieldType == 'select-one') { passValue = 'select'+mfrm.elements[i].options.selectedIndex; }\n \n else if(fieldType == 'select-multiple'){\n passValue='selmul';\n for(var k=0;k<mfrm.elements[i].options.length;k++){ \n if(mfrm.elements[i].options[k].selected)\n {\n passValue+=k+'*';\n }\n } \n } \n else { passValue = mfrm.elements[i].value; }\n\n\t\tcookieValue = cookieValue + passValue + '#cf#';\n } // for\n\n cookieValue = cookieValue.substring(0, cookieValue.length-4); // Remove last delimiter\n setCookie('saved_'+formName, cookieValue, 0);\t\t\n } // save\n\n}",
"function ibp_getCookie(name)\n{ // DEFINE THE PATTERN TO SEARCH FOR IN THE COOKIE LIST WHICH IS THE COOKIE NAME\n arg = name + \"=\";\n\n // DETERMINE HOW LONG THE PATTERN IS\n alen = arg.length;\n\n // DETERMINE HOW LONG THE COOKIE LIST IS\n clen = document.cookie.length;\n\n // DEFINE A COOKIE LIST CHARACTER INDEX TRACKER\n i = 0;\n\n // LOOP WHILE THE CURRENT INDEX IS LESS THAN THE LENGTH OF THE COOKIE LIST\n while (i < clen)\n { // SET A TEMPORARY LENGTH WITHIN THE COOKIE LIST BASED ON THE COOKIE NAME LENGTH\n j = i + alen;\n\n // DETERMINE IF THE COOKIE NAME HAS BEEN FOUND\n if (document.cookie.substring(i, j) == arg)\n { // GRAB THE NEXT AVAILABLE INDEX OF A SEMI-COLON TO KNOW WHERE THE END OF THE COOKIE VALUE IS\n endstr = document.cookie.indexOf(\";\", j);\n\n // DETERMINE IF A SEMI-COLON WAS FOUND\n if (endstr == -1)\n { // USE THE LENGTH OF THE COOKIE LIST AS THE ENDING POINT\n endstr = document.cookie.length;\n }\n\n // RETURN THE UNESCAPED COOKIE VALUE\n return unescape(document.cookie.substring(j, endstr));\n }\n\n // GRAB THE NEXT AVAILABLE SPACE THAT SEPARATES COOKIES\n i = document.cookie.indexOf(\" \", i) + 1;\n\n // DETERMINE IF THERE ARE MORE COOKIE TO PROCESS\n if (i === 0)\n { //THERE ARE NO MORE COOKIES TO PROCESS\n break;\n }\n }\n\n // COOKIE NOT FOUND\n return false;\n}",
"function parseCookies(rawCookie) {\n rawCookie && rawCookie.split(';').forEach(function( cookie ) {\n var parts = cookie.split('=');\n cookies[parts.shift().trim()] = decodeURI(parts.join('='));\n });\n}",
"function getCookieMultiValue(cookiename,cookiekey) {\n var cookievalue=getCookie(cookiename);\n if ( cookievalue == \"\")\n return \"\";\n cookievaluesep=cookievalue.split(\"&\");\n for (c=0;c<cookievaluesep.length;c++) {\n cookienamevalue=cookievaluesep[c].split(\"=\");\n if (cookienamevalue.length > 1) {\n if ( cookienamevalue[0] == cookiekey )\n return cookienamevalue[1].toString();\n }\n else\n return \"\";\n }\n\n return \"\";\n}",
"createCookies() {\n let pageID = this.getPageID();\n crumbs.set(\"Frequency-\" + pageID, this.getFrequency()); // Create session cookie\n crumbs.set(\"Amount-\" + pageID, this.getAmount()); // Create session cookie\n crumbs.set(\"Fee-\" + pageID, this.getFee()); // Create session cookie\n }",
"function getArmoryCookies(type) \n{ \tvar modelCookies = {}\n\tvar armory_cookies = document.cookie.toString().split(\";\") \n\tfor(xi=0;xi<armory_cookies.length;xi++){ \n\t\t\tif(armory_cookies[xi].indexOf(\"armory.cookie\"+type) > -1)\n\t\t\t{ \tvar tempck = armory_cookies[xi].split(\"=\"); \n\t\t\t\tmodelCookies[tempck[0].split(\"cookie3d\")[1].toLowerCase()] = tempck[1];\t\t\t\t\n\t\t\t} \n\t}\n\treturn modelCookies\n}",
"function bp_get_cookies() {\n // get all cookies and split into an array\n var allCookies = document.cookie.split(\";\");\n\n var bpCookies = {};\n var cookiePrefix = 'bp-';\n\n // loop through cookies\n for (var i = 0; i < allCookies.length; i++) {\n var cookie = allCookies[i];\n var delimiter = cookie.indexOf(\"=\");\n var name = jq.trim(unescape(cookie.slice(0, delimiter)));\n var value = unescape(cookie.slice(delimiter + 1));\n\n // if BP cookie, store it\n if (name.indexOf(cookiePrefix) == 0) {\n bpCookies[name] = value;\n }\n }\n\n // returns BP cookies as querystring\n return encodeURIComponent(jq.param(bpCookies));\n}",
"function getcoklist(){\n\tvar text2=\"\";\n\tvar cuadro01=document.getElementById(\"ifr002\").contentDocument;\n\tvar decodedCookie = decodeURIComponent(document.cookie);\n\tvar ca = decodedCookie.split(';');\n\t\tfor(var i = 0; i <ca.length ; i++) {\n\t\t\t\tvar c = ca[i];\n\t\t\t\t\twhile (c.charAt(0) == ' ') {\n\t\t\t\t\t\tc = c.substring(1);\n\t\t\t\t\t}\n // if (c.indexOf(name) == 0) {\n\t\t\nvar split02=(c.substring(name.length, c.length)).split('=');\t\t\n //alert(split02[0]);\n ///for(var i = 0; i <split02.length; i++) {\n\t // var c2 = split02[i];\n // while (c2.charAt(0) == ' ') {\n // c2 = c2.substring(1);\n\t text2 += \" <style>.fakeimg {height: auto; background: #aaa;padding: 5px;border:solid 1px blue;border-radius:10px;}</style><p class='fakeimg'><a class='nav-link btn btn-primary' href=' javascript:void(0) ' onclick='javascript:parent.uno(this.innerHTML)'>\" + split02[0] +\"</a></p>\";\n\n\t// cuadro01.body.innerHTML=cuadro01.body.innerHTML + split02[0] + \"<br>\";\t\n\n // }\n\t\t\n // return c.substring(name.length, c.length);\n\n }\n // cuadro01.body.innerHTML=text2 + \"<br>\";\t\n document.getElementById(\"ifr002\").contentDocument.body.innerHTML= (\"<base href='/webspace/' target='ifr001'><script src='/webspace/js/jsc01.js'></script><link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css'>\" + text2) ;\n return \"\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets connection from the connection manager. If connection name wasn't specified, then "default" connection will be retrieved. | function getConnection(connectionName) {
if (connectionName === void 0) { connectionName = "default"; }
return getConnectionManager().get(connectionName);
} | [
"function getConnection(connectionName) {\n if (connectionName === void 0) { connectionName = \"default\"; }\n return getConnectionManager().get(connectionName);\n }",
"get(name = \"default\") {\n const connection = this.connections.find(connection => connection.name === name);\n if (!connection)\n throw new ConnectionNotFoundError(name);\n return connection;\n }",
"get(connectionName) {\n return this.connections.get(connectionName);\n }",
"function getManager(connectionName) {\n if (connectionName === void 0) { connectionName = \"default\"; }\n return getConnectionManager().get(connectionName).manager;\n}",
"function getManager(connectionName) {\n if (connectionName === void 0) { connectionName = \"default\"; }\n return getConnectionManager().get(connectionName).manager;\n }",
"function getConnection() {\n const nameSpace = getNamespace('unique context');\n const conn = nameSpace.get('connection');\n \n if (!conn) {\n throw 'Connection is not set for any tenant database.';\n }\n \n return conn;\n }",
"get connection () {}",
"function getDatabaseConnection()\n{\n\tvar dbConn;\n\tif(conPool.isConnPool === true)\n\t{\n\t\tif(getPoolSize() <= 0)\n\t\t{\n\t\t\tdbConn = \"empty\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tdbConn = getConnection();\n\t\t}\n\t}\n\telse\n\t{\n\t\tdbConn = databaseConnect();\n\t}\n return dbConn;\n}",
"function getConnectionManager() {\n return container_1.getFromContainer(ConnectionManager_1.ConnectionManager);\n}",
"static async getConnection() {\n const conn = new MGConnection();\n await conn.openConnection();\n return { conn, db: conn.getDefaultDb() };\n }",
"getConnection() {\n errors.throwNotImplemented(\"getting a connection from the pool\");\n }",
"function getConnection() {\n if (!connection) {\n connection = new web3.Connection(\n web3.clusterApiUrl(nodeType),\n commitment,\n );\n }\n return connection;\n}",
"function getMongoManager(connectionName) {\n if (connectionName === void 0) { connectionName = \"default\"; }\n return getConnectionManager().get(connectionName).manager;\n}",
"defaultConnection () {\n return Config.get('database.default')\n }",
"async getDatabaseConnection() {\n debug('Attempt to get database connection from %s', this.hostName);\n }",
"function getConnectionObject() {\n return __credentials[\"conn\"];\n }",
"function getConnection(options) {\n debug('getConnection','start',options);\n\n let key = null;\n let promise = null;\n try {\n //clone options\n options = clone(options);\n\n //serialize the options as a key for pools\n key = stringify(options || {});\n\n //if there's already a promise for the given connection, return it\n if (promises[key]) return promises[key];\n\n //create a new promise for the given connection options\n promise = promises[key] = createConnectionPromise(key, options);\n\n debug('getConnection','success')\n return promise;\n } catch(err) {\n debug('getConnection','error',err);\n return Promise.reject(err);\n }\n}",
"async getConnection() {\n this.showPoolStatus()\n const conn = this.connections.find(x => x.free || x.broken)\n if (!conn && this.size < this.config.connectionLimit) {\n this.size += 1\n return await this.getNewConnection()\n } else {\n return await this.getOldConnection()\n }\n }",
"get connectionManager() {\n return this._connectionMgr;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns deadline of Project object | getDeadline() {
return this.deadline;
} | [
"get deadline(){\n\t\treturn this.deadline;\n\t}",
"getNextDeadline() {\n return Math.min(this.newLayoutTime, this.newModuleTime);\n }",
"function getFormDeadline (formName, term, referenceDate) {\n const formDates = getFormDatesForAllTerms(referenceDate);\n\n formName = formName.toLowerCase();\n term = term.toLowerCase();\n\n let deadline;\n eval(`deadline = formDates.${formName}.${term}_latestDate;`);\n\n return deadline;\n}",
"function getRelativeTimeout(deadline) {\n const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline;\n const now = new Date().getTime();\n const timeout = deadlineMs - now;\n if (timeout < 0) {\n return 0;\n }\n else if (timeout > MAX_TIMEOUT_TIME) {\n return Infinity;\n }\n else {\n return timeout;\n }\n}",
"function CalculateDeadlineInDays(task) {\r\n var days;\r\n if (task.deadline) {\r\n task.deadline = new Date(task.deadline);\r\n var timeDiff = task.deadline.getTime() - Date.now();\r\n var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));\r\n task.deadlineInDays = diffDays;\r\n }\r\n }",
"function getRemainingTime(deadline)\n{\n\tif(typeof(deadline.date) !== \"undefined\")\n\t{\n\t\t// gson returns the LocalDateTime as date and time\n\t\t// -1 is necessary since Date represents month with indices from 0 to 11\n\t\tvar deadlineDate = new Date(deadline.date.year, deadline.date.month - 1, deadline.date.day, deadline.time.hour, deadline.time.minute);\n\t}\n\telse\n\t{\n\t\t// Case in which the user has submitted the form to create\n\t\t// a new auction and the deadline is being checked\n\t\t// to see if it's valid\n\t\tvar deadlineDate = new Date(deadline);\n\t}\n\n \t// Gets the current date and time\n \tvar currDate = new Date();\n\n\t// Since the auctions' deadlines are truncated to the minutes\n\t// but dates are not, the currentDate should be truncated too\n\tcurrDate.setSeconds(0);\n\tcurrDate.setMilliseconds(0);\n\n \t// Finds the milliseconds between the current date and the deadline\n \tvar millisecondsDiff = deadlineDate - currDate;\n\n\t// If the auction is expired, these are the returned values\n\tvar days = 0, hours = 0, minutes = 0;\n\t\n\t// Checks if the auction is expired\n\tif(millisecondsDiff > 0)\n\t{\t\t\n\t\tvar millisecondsInADay = 1000 * 60 * 60 * 24;\n\t\tvar millisecondsInAnHour = 1000 * 60 * 60;\n\t\tvar millisecondsInAMinute = 1000 * 60;\n\t\t// Calculates the remaining days, hours and minutes\n\t \tdays = Math.floor(millisecondsDiff / millisecondsInADay);\n\t \thours = Math.floor((millisecondsDiff % millisecondsInADay) / millisecondsInAnHour);\n\t \tminutes = Math.floor((millisecondsDiff % millisecondsInAnHour) / millisecondsInAMinute);\n\t}\n\t\t\t\n\t// Returns a diffDAte object in order to set the remaining time for each auction\n\treturn new DiffDAte(days, hours, minutes);\n}",
"function deadlineCouter(\n\tworkingHours\n) {\n\tif (workingHours > 0) {\n\t\tlet orderDate = moment().locale(\"ua\");\n\t\tlet startTime = moment().startOf(\"day\").add(10, \"hours\");\n\t\tlet endTime = moment(startTime).add(9, \"hours\");\n\t\tconst dateFormat = \"DD.MM\";\n\t\tconst timeFormat = \"HH:mm\";\n\t\tlet completionDate = orderDate;\n\n\t\tfor (let i = 0; i < workingHours; i++) {\n\t\t\twhile (completionDate.day() === 6 || completionDate.day() === 0) {\n\t\t\t\tcompletionDate.add(1, \"day\");\n\t\t\t\tcompletionDate.hours(10).minutes(0);\n\t\t\t}\n\t\t\tif (completionDate.hours() < startTime.hours()) {\n\t\t\t\tcompletionDate.hours(10).minutes(0);\n\t\t\t}\n\t\t\tif (completionDate.hours() > endTime.hours() - 1) {\n\t\t\t\tcompletionDate.add(1, \"days\");\n\t\t\t\tcompletionDate.hours(10).minutes(0);\n\t\t\t}\n\t\t\tcompletionDate.add(1, \"hours\");\n\t\t}\n\t\treturn (\n\t\t\tcompletionDate.format(dateFormat) + \" о \" + completionDate.format(timeFormat)\n\t\t);\n\t} else {\n\t\treturn '';\n\t}\n}",
"function __getNextDeadline(testInterval = -1) {\n if (testInterval >= 0) return testInterval;\n const now = moment();\n const deadLine = moment().add(1, 'd').set({ hour: 0, minute: 0, second: 0, millisecond: 0 })\n const interval = deadLine.valueOf() - now.valueOf();\n return interval;\n}",
"addDeadline(newDeadline){\n\t\tthis.deadline = newDeadline;\n\t}",
"lastPastMilestone() {\n const { milestones } = this.props;\n const dateNow = Date.now();\n return milestones.takeUntil(milestone => Date.parse(milestone.get('start_at')) > dateNow).last();\n }",
"removeDeadline(){\n\t\tthis.deadline = null;\n\t}",
"hasDeadline(){\n\t\tif (this.deadline === null){\n\t\t\treturn false;\n\t\t} else{\n\t\t\treturn true;\n\t\t}\n\t}",
"@computed('tab', 'dcpLupteammemberrole', 'project.milestones')\n get upcomingMilestonePlannedStartDate() {\n const participantMilestoneId = REFERRAL_MILESTONEID_BY_ACRONYM_LOOKUP[this.dcpLupteammemberrole];\n const participantReviewMilestone = this.project.get('milestones').find(milestone => milestone.dcpMilestone === participantMilestoneId);\n\n return participantReviewMilestone ? participantReviewMilestone.dcpPlannedstartdate : null;\n }",
"get timeRemaining() {\n \n // compute time left since start of judging\n return Math.max(this.time_limit - (new Date() - this.time_start), 1);\n \n }",
"function getEndDate() {\n\tlet lastEndDate = Date.now();\n\tif (tasks.length > 0) {\n\t\tlastEndDate = tasks[tasks.length - 1].endDate;\n\t}\n\treturn lastEndDate;\n}",
"function ProjectDealine(props) {\n\n const [deadline, setDeadline] = useState(0);\n const isPocatek = useRef(true);\n const endDate = useSelector(state => state.deadline);\n\n /**\n * Vypocet poctu dnu dokonce\n * */\n function countDeadline(endDate) {\n let date = parseISO(endDate);\n let today = new Date();\n\n if(isValid(date)) {\n let dead = differenceInCalendarDays(date, today);\n if (dead < 0)\n return 0;\n else\n return dead;\n }\n else\n return 0;\n\n }\n\n useEffect(() => {\n let dead = countDeadline(props.konec);\n setDeadline(dead);\n }, [props]);\n\n\n useEffect(() => {\n if (isPocatek.current)\n isPocatek.current = false;\n else {\n let dead = countDeadline(endDate);\n setDeadline(dead);\n }\n }, [endDate, isPocatek]);\n\n return(\n <ProjectStatsInfo title=\"Dnů do ukončení\" data={deadline}/>\n );\n}",
"get completedAt() {\n return this.getStringAttribute('completed_at');\n }",
"function getDueDateText(todo) {\n if (todo.isComplete) {\n return 'Done!';\n }\n else if (isOverdue(todo)) {\n return `Overdue! Was due ${moment(todo.due).fromNow()}`;\n }\n else {\n return `Due ${moment(todo.due).fromNow()}`\n }\n}",
"async fetchLastProcessTime() {\n\t \tconst oThis = this;\n\t \treturn Promise.resolve(oThis.model.getLastCronRunTime());\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get index of assignment with given id | function assignmentsGetIdxForId(id) {
for (var i=0; i<assignments.length; i++)
if (assignments[i].id == id)
return i;
return -1;
} | [
"function assignmentsGetCurrentIdx() {\n\tvar asgnSelect = document.getElementById('assignment_select');\n\tif (asgnSelect.selectedIndex == -1) return -1;\n\tvar currentId = asgnSelect.options[asgnSelect.selectedIndex].value;\n\tfor (var i=0; i<assignments.length; i++)\n\t\tif (assignments[i].id == currentId)\n\t\t\treturn i;\n\treturn -1;\n}",
"getAnalysisIndex(id) {\n if (!id) return undefined;\n\n for (let i = 0; i < this.analyses.length; i++) {\n let analysis = this.analyses[i];\n if (analysis.id === id) return i;\n }\n\n return undefined;\n }",
"function getIndexForId(id) {\n\n\tvar index = -1;\n\tfor (var c in courses) {\n\t\tif (courses[c].id == id) {\n\t\t\tindex = c;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn index;\n}",
"function indexFromId(id){\n var index\n switch(id){\n case 'cell-0':\n index = 0\n break;\n case 'cell-1':\n index = 1\n break;\n case 'cell-2':\n index = 2\n break;\n case 'cell-3':\n index = 3\n break;\n case 'cell-4':\n index = 4\n break;\n case 'cell-5':\n index = 5\n break;\n case 'cell-6':\n index = 6\n break;\n case 'cell-7':\n index = 7\n break;\n case 'cell-8':\n index = 8\n break;\n }\n return index\n }",
"function _findIndexFromID(id) \n{\n var len=this.rsList.length, i=0;\n\n for(i=0; i<len; i++) {\n\tif(id == this.rsList[i].ruleID)\n\t break;\n }\n if(i == len)\n\treturn -1;\n else\n\treturn i;\n}",
"function getIndex(id){\r\n\t\t\tfor( var i = 0; i < $scope.people.length; i++){\r\n\t\t\t\tif($scope.people[i].id === id){\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}",
"getIndex (id, array) {\n for (let i = 0; i < array.length; ++i)\n if (array[i].id === id) return i;\n return -1;\n }",
"function getIDIndex(id) {\n return parseInt(id.slice(2));\n}",
"function getIndex(id){\n for(var i = 0; i < self.length; ++i)\n if(self.fields[i].id == id)\n return i;\n return -1;\n }",
"function getIndex(id){\n for(var i = 0; i<playerRoster.length; i++){\n if (id === playerRoster[i].id){\n return i;\n }\n } return -1;\n}",
"function idToIndex(id) {\n for (var idx = 0, len = nodes.length; idx < len; idx++) {\n if (nodes[idx].id === id) {\n return idx\n }\n }\n return -1\n}",
"function getIndexFromID(id) {\n\tvar counter = 0;\n\tvar result = -1;\n\tconnections.forEach(function(e) {\n\t\tif (e.id == id) {\n\t\t\tresult = counter;\n\t\t}\n\t\tcounter++;\n\t});\n\treturn result;\n}",
"function getCellarIndex(id) {\n id = parseInt(id);\n for (var i = 0; i < cellars.length; i++) {\n if (cellars[i].id === id) {\n return i;\n }\n }\n return -1;\n}",
"getItemIndexByValue(id, obj){\n var idFilter = (element) => element.id == id;\n var x = obj.findIndex(idFilter);\n return obj.findIndex(idFilter);\n }",
"function getOpsGroupIndex(id) {\n var i = 0;\n for (i = 0; i < $scope.opsGroups.length; i++) {\n if ($scope.opsGroups[i]._id === id) {\n return i + 1;\n }\n }\n return null;\n }",
"function alertArrayIndexByID(id) {\n for (var i=0; i < alertRulesArray.length; i++) {\n if (alertRulesArray[i].alert_id == id) {\n return i;\n }\n };\n }",
"function getIdIndex(src, id, verbose = false) {\n var ast = esprima.parse(src, {range: true});\n var index = -1;\n\n estraverse.traverse(ast, {\n enter: function(node, parent) {\n if (node.type == 'Identifier' && node.name === id) {\n if(verbose) console.log(\"Found! \" + node.range[0]);\n index = node.range[0];\n // The break function seems to be broken\n // estraverse.VisitorOption.Break;\n }\n },\n leave: function(node, parent) {\n // This might not be needed at all?\n }\n });\n\n return index;\n}",
"findIndexById(id){\n for (var i = 0; i < this.buses.length; i++) {\n if(this.buses[i]._id === id) {\n return i;\n }\n }\n return -1;\n }",
"function getIndex(dataIndex, id) {\n\n // get the array of Ids\n var idNames = getIdNames(dataIndex);\n\n // get the index value for id of interest\n var idIndex = idNames.indexOf(id);\n\n // return the index value of selected id\n return idIndex;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
drawYlabels is a function called by drawBarChart to draw the Y axis labels for a bar chart. The function takes in three parameters: data: object with four properties: values, labels, scale, and title (as defined for drawBarChart) chartHeight: positive integer representing the height of the chart area (excluding titles, labels, etc.) in pixels element: jQuery element that the chart is rendered into | function drawYlabels(data, chartHeight, element) {
// extracts scale from data
var scale = data.scale;
// determines the maximum value to be displayed on the Y axis of the chart
var maxY = findMaxY(data.values, scale);
// creates the label area that the labels are rendered to
var labelArea = $("<div>").attr("id", "yArea");
$(labelArea).css({height: chartHeight + "px"});
$(element).append(labelArea);
var labelHeight;
var i;
for (i = 0; i <= maxY / scale; i++) {
// creates a label for each multiple of scale less than or equal to maxY
var label = $("<div>").addClass("yLabel");
// determines the label height
labelHeight = ((i * scale) / maxY) * chartHeight;
// updates the position and text displayed for the label
$(label).css({marginBottom: (labelHeight - 13) + "px"});
$(label).text((i * scale) + " -");
// appends the label to the label area
$(labelArea).append(label);
}
} | [
"function drawYAxis(barchart, height) {\n\n barchart.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(d3.axisLeft(y).tickFormat(function(n) { return n + \"%\"}))\n .append(\"text\")\n .attr(\"fill\", \"#000\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", -60)\n .attr(\"x\", - (height / 2))\n .attr(\"dy\", \"0.71em\")\n .style(\"font-weight\", \"bold\")\n .text(\"Inwoners\");\n}",
"function drawYAxis(data) {\n $(\".chartContainer\").append(\"<div class='yAxis'></div>\");\n let maximum = maxScale(tallestBar(data));\n let order = Math.floor(Math.log(maximum) / Math.LN10\n + 0.000000001);\n for (let i = 1; i > 0; i = i - 0.2) {\n if (order < 0) {\n $(\".yAxis\").append(\"<div class='yAxisLabel'>\" + (maximum * i).toFixed(Math.abs(order-1)) + \"</div>\");\n } else {\n $(\".yAxis\").append(\"<div class='yAxisLabel'>\" + (maximum * i).toFixed(0) + \"</div>\");\n }\n }\n }",
"function createYLabels() {\n var i;\n for ( i = 0; i < $yLabels.length; i++) {\n $yLabels[i].remove();\n }\n $yLabels = [];\n\n for ( i = 0; i < seriesArray.length; i++) {\n $yLabels[i] = jQuery('<div />').attr('id', 'ylabel' + i);\n $yLabels[i].appendTo('body').hide().css({\n 'position' : 'absolute',\n 'display' : 'none',\n 'border' : '1px solid #000000',\n 'background-color' : '#ffffcc',\n 'opacity' : 0.0,\n 'z-index' : '20000',\n 'padding' : '0.0em 0.3em',\n 'border-radius' : '0.5em',\n 'font-size' : '0.8em',\n 'pointer-events' : 'none'\n });\n $yLabels[i].html(\"0.00\").css({\n left : 0,\n top : 0\n }).show();\n }\n }",
"function placeYLabels(){\n // removes all previously found y-labels\n svg.selectAll(\".heatYLabel\")\n .exit()\n .remove();\n // places the y-labels\n var yLabels = svg.selectAll(\".heatYLabel\")\n .data(yList)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"heatYLabel\")\n .text(function(d){return d;})\n .attr(\"x\", pad.left * 0.9)\n .attr(\"y\", function(d,i){\n var yCoor = yScaleHeat(i * 1.2 + 1.1)\n return yCoor\n })\n .style(\"font-size\", \"15px\")\n .style(\"text-anchor\", \"end\");\n }",
"function createYAxis(options) {\n // Amount to decrease for each tick\n const decrementAmount = Math.round(options[7]/options[8]);\n // Dynamically calculated height percentage to use for formatting of ticks\n const tickHeight = (1/options[8] *100);\n let currentTick = options[7];\n // Iterate the the requested number of y labels (options[8]) and create a label for each\n for (let yLabelCount = 1; yLabelCount <= options[8]; yLabelCount++) {\n $(\".yAxisLabels\").append(\"<span class=\\\"label\\\"></span\");\n $(\".yAxisLabels span:last-of-type\").append(\"<p>\" + currentTick + options[9] + \"</p>\");\n currentTick -= decrementAmount;\n }\n $(\".label p, .xAxisLabelContainer p\").css(\"color\", options[5]);\n $(\".label\").css(\"height\", tickHeight + \"%\")\n }",
"function drawYAxis() {\n paper.leonardo.vLine(plotArea.x, plotArea.y, plotArea.height);\n\n // TODO: Get rid of magic number. Base text on font size instead.\n var valueX = plotArea.x - opts.tickSize,\n valueTextX = plotArea.x - (3 * opts.tickSize);\n\n plot(scaleValues, function (x, y, value) {\n paper.leonardo.hLine(valueX, y, opts.tickSize);\n paper.text(valueTextX, y, value);\n });\n }",
"function transformDataToYLabels(CHART_ELEMENT, data, timestamps, maxFromYAxis) {\n\n var biggestYAxisElem = maxFromYAxis.maxY1 >= maxFromYAxis.maxY2 ? maxFromYAxis.maxY1 : maxFromYAxis.maxY2;\n var yAxisStamps = [], yLabelCounts = [], counter = -1;\n while(counter++ < biggestYAxisElem) {\n if (Number.isSafeInteger(counter / Y_AXIS_COUNT)) {\n yLabelCounts.push(counter);\n }\n if (Number.isSafeInteger(counter / Y_AXIS_LABEL_HEIGHT)) {\n yAxisStamps.push(counter);\n }\n }\n data.columns[1].splice(0, 1);\n data.columns[2].splice(0, 1);\n yLabelCounts.push(yLabelCounts[yLabelCounts.length - 1] + Y_AXIS_COUNT);\n\n var columnsX1 = data.columns[1],\n columnsX2 = data.columns[2];\n var xStrokeWidth = 0, yLineHeight = 0;\n\n CHART_ELEMENT.fillStyle = \"black\";\n xStrokeWidth = 0;\n columnsX1.forEach((columnX1) => {\n CHART_ELEMENT.fillText(columnX1, xStrokeWidth += Y_AXIS_LABEL_WIDTH, columnX1 + Y_AXIS_LABEL_HEIGHT);\n });\n xStrokeWidth = 0;\n columnsX2.forEach((columnY2) => {\n CHART_ELEMENT.fillText(columnY2, xStrokeWidth += Y_AXIS_LABEL_WIDTH, columnY2 + Y_AXIS_LABEL_HEIGHT);\n });\n return {\n yAxisHeight: yAxisStamps.length * Y_AXIS_LABEL_HEIGHT,\n yAxisStamps: yAxisStamps,\n yLabels: yLabelCounts\n };\n }",
"renderLabelY(){\n const labelGroup = this.chartGroup.append(\"g\");\n\n this.yAxisList.forEach((axis, index) => {\n const label = labelGroup.append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 0 - this.margin.left + (index * this.offset))\n .attr(\"x\", 0 - (this.chartHeight / 2))\n .attr(\"dy\", \"1em\")\n .attr(\"value\", index)\n .text(axis.label);\n\n if(index == this.selectAxisY){\n label.classed(\"active\", true);\n label.classed(\"inactive\", false);\n }\n else{\n label.classed(\"active\", false);\n label.classed(\"inactive\", true);\n }\n\n label.on(\"click\", (_d, i, nodes) =>{\n const label = d3.select(nodes[i]);\n const value = label.attr(\"value\");\n \n if(value != this.selectAxisY)\n {\n this.updateAxisY(value, true);\n }\n });\n });\n\n this.yLabelGroup = labelGroup;\n }",
"function drawYAxisLabel(barData, yAxis, font){\n for (var i=0; i<yAxis; i++) {\n\n var yAxisItem = barData.data[i];\n let l = yAxisItem.label;\n if (yAxisItem.label.includes('-') && yAxisItem.label.includes('|')){\n l = yAxisItem.label.split('|')[1];\n }\n var geometry = new THREE.TextGeometry( l, {\n font: font,\n size: yAxisLabelSize,\n height: 0.0001\n });\n var material = new THREE.MeshPhongMaterial( { color: yAxisLabelColor } );\n var text = new THREE.Mesh(geometry, material);\n text.rotateX(-Math.PI/2);\n var box = new THREE.Box3().setFromObject( text );\n var size = new THREE.Vector3();\n\n text.position.y = -maxHeight/2;\n let distance = (endOfGridHelperIsEnabled)\n ? ((maxWidth > maxLength) ? maxWidth : maxLength)\n : maxLength;\n text.position.x = distance/2 + padding;\n text.position.z = -1 * (- maxWidth/2 + padding + i * (barWidth + 2 * padding) + barWidth/2) + box.getSize(size).z/2;\n scene.add(text);\n }\n }",
"function BarChart_YPos(chart, y)\r\n{\r\n return chart.YRange - (y * chart.PixelsToY);\r\n}",
"function extractYLabels(){\n for(var i=0;i<data.length;i++){\n if(data[i][0].yLabel){\n yLabels.push(data[i][0].yLabel);\n }\n }\n yLabels = unique(yLabels);\n extractZLabels();\n }",
"function updateYlabel() {\n if (options.ylabel && ylabel) {\n ylabel.text(options.ylabel);\n } else {\n ylabel.style(\"display\", \"none\");\n }\n renderGraph();\n }",
"function drawBarChart(data, options, element){\n\n //The Functions\n function drawXYBox(element) {\n $(element).prepend(\"<div class=xyData></div>\");\n $(\".xyData\").css({\n \"height\" : \"auto\",\n \"width\" : \"auto\",\n \"float\" : \"left\",\n \"display\" : \"inline-block\"\n });\n }\n\n function drawYLabel(element, options) {\n $(element).prepend(\"<div class=yLabel></div>\");\n $(\".yLabel\").css({\n \"display\" : \"inline-block\",\n \"float\" : \"left\",\n \"margin-top\" : \"-9.5px\"\n });\n $(element).prepend('<div class=yTitle contenteditable=true>' + options[3] + '</div>');\n $(\".yTitle\").css({\n \"display\" : \"inline-block\",\n \"float\" : \"left\",\n \"writing-mode\" : \"tb-rl\",\n \"text-align\" : \"center\",\n \"margin-right\" : \"10px\",\n \"height\" : options[21],\n \"color\" : options[4],\n \"font-size\" : options[5]\n });\n }\n\n function drawXLabel(options, chartWidth, element){\n $(element).prepend(\"<div class=xTitle contenteditable=true>\" + options[6] + \"</div>\");\n $(\".xTitle\").css({\n \"text-align\" : \"center\",\n \"padding-left\" : \"60px\",\n \"width\" : chartWidth,\n \"margin-top\" : \"10px\",\n \"margin-bottom\" : \"20px\",\n \"color\" : options[7],\n \"font-size\" : options[8]\n })\n }\n\n function drawMainTitle(options, chartWidth, element) {\n $(element).prepend(\"<div class=title contenteditable=true>\" + options[0] + \"</div>\");\n $(\".title\").css({\n \"width\" : chartWidth,\n \"padding-left\" : \"60px\",\n \"text-align\" : \"center\",\n \"color\": options[1],\n \"font-size\" : options[2],\n \"margin-bottom\" : \"15px\"\n }); \n }\n\n //Functions to draw the BARS\n function drawBars(ID, maxVal, options, data) {\n //Append a container to the allData div for the bar being drawn\n $(\".allData\").append(\"<div class=data\" + ID + \"></div>\");\n //Set the bar to be displayed inline-block as the bars must be side by side\n $(\".data\" + ID).css({\n \"display\" : \"inline-block\",\n \"background-color\" : options[14]\n });\n\n function makeBottomBar(ID, i, data, options){\n $(\".dataBar\" + ID + i).css({\n \"border-top\" : \"1px solid black\",\n \"border-left\" : \"1px solid black\",\n \"border-right\" : \"1px solid black\"\n })\n if(options[23] === \"valDepend\"){\n $(\".dataBar\" + ID + i).css({\n \"width\" : (data[ID][i]), //Width based on the numeric value of bar\n })\n }else{\n $(\".dataBar\" + ID + i).css({\n //Determine the width of each bar based on the width of the chart area\n \"width\": (options[22] / (data.length + 1)) \n })\n }\n $(\".dataBar\" + ID + i).css({ \n \"position\" : \"relative\",\n \"background-color\" : options[15] // Change later in the options\n });\n\n // Getting the data points styled\n $(\".dataPoint\" + i).css({\n \"position\" : \"absolute\",\n \"left\" : \"50%\",\n \"color\" : options[17],\n \"font-size\" : options[18]\n });\n }\n\n function makeTopBar(ID, i, data, options){\n if(options[23] === \"valDepend\"){\n $(\".dataBar\" + ID + i).css({\n \"width\" : (data[ID][i]), //Width based on the numeric value of bar\n })\n }else{\n $(\".dataBar\" + ID + i).css({\n //Determine the width of each bar based on the width of the chart area\n \"width\": (options[22] / (data.length + 1)), \n })\n }\n $(\".dataBar\" + ID + i).css({ \n \"border\" : \"1px solid black\",\n \"position\" : \"relative\",\n \"background-color\" : options[16] // Change later in the options\n });\n\n $(\".dataPoint\" + i).css({\n \"position\" : \"absolute\",\n \"left\" : \"50%\",\n \"color\" : options[17],\n \"font-size\" : options[18]\n });\n }\n \n //for each datapoint in the bar, draw the bar (data for a single bar must be sorted from lowest-highest)\n for (var i = 1; i < data[ID].length; i++) {\n $(\".data\" + ID).prepend(\"<div class=dataBar\" + ID + i + \"><div class=dataPoint\" + i + \">\" + data[ID][i] + \"</div></div>\");\n if(i % 2 !== 0){ // BOTTOM BAR MAKING FUNCTION RUNNING\n makeBottomBar(ID, i, data, options)\n }else{ // TOP BAR MAKING FUNCTION RUNNING\n makeTopBar(ID, i, data, options)\n }\n\n //Set the dataPoint to display at either the top, middle or bottom of the bar\n if (options[19] === \"top\") {\n $(\".dataPoint\" + i).css(\"top\", \"5%\");\n $(\".dataPoint\" + i).css(\"transform\", \"translate(-50%, 0%)\");\n } else if (options[19] === \"middle\") {\n $(\".dataPoint\" + i).css(\"top\", \"50%\");\n $(\".dataPoint\" + i).css(\"transform\", \"translate(-50%, -50%)\");\n } else {\n $(\".dataPoint\" + i).css(\"bottom\", \"0%\");\n $(\".dataPoint\" + i).css(\"transform\", \"translate(-50%, -10%)\");\n }\n //For multiple values, we calculate the remaining height needed to add above the currently drawn values to get the correct height of the bar\n var heightVal = (data[ID][i] / maxVal) * options[21];\n //console.log(heightVal + \" outside\");\n for (var j = 1; j < i; j++) {\n //heightVal = (((data[ID][j] / maxVal) * options[21]) - heightVal) * (-1);\n //console.log(heightVal);\n }\n $(\".dataBar\" + ID + i).css(\"height\", heightVal);\n }\n $(\".data\" + ID).css(\"border-bottom\", \"1px solid black\");\n //add the space between each bar\n $(\".allData\").append(\"<div class=barSpace></div>\");\n } // END OF DRAW BARS FUNCTION\n\n //Function to create the bars using the data given\n function drawData(data, options) {\n $(\".xyData\").append(\"<div class=allData></div>\");\n $(\".allData\").css(\"border-left\", \"1px solid black\");\n \n //Find the max value contained in the data. It will be used to set the max height\n if(!isNaN(data[0][2])){\n var maxVal = data[0][1] + data[0][2];\n }else{\n var maxVal = data[0][1];console.log(maxVal)\n }\n for(let i = 0; i<data.length; i++){\n var arr = [], sum = 0;\n for(let j=1; j<data[i].length; j++){\n arr.push(data[i][j])\n }\n if(arr.length > 1){\n sum = arr.reduce((total, current)=>(total+current));\n }else{\n sum = arr[0];\n }\n if(maxVal < sum){maxVal = sum}\n }\n\n //Get the largest y-axis value, which will be the closest multiple of 5 to the max value rounded up.\n var maxValAxis = Math.ceil(maxVal / 5) * 5;\n //calls the drawBars function for each bar that needs to be drawn\n for (var i = 0; i < data.length; i++) {\n drawBars(i, maxValAxis, options, data);\n }\n\n //Sets the spacing between the bars to the value input in the options parameter\n $(\".barSpace\").css({\n \"width\" : options[20],\n \"display\" : \"inline-block\",\n \"border-bottom\" : \"1px solid black\"\n });\n return maxValAxis;\n }\n\n //The function that draws the axis marks of the x-axis and y-axis\n function drawAxisMarks(data, options, maxValAxis) {\n\n $(\".xyData\").append(\"<div class=xLabel></div>\");\n $(\".xLabel\").css(\"display\", \"flex\");\n $(\".xLabel\").css(\"flex-wrap\", \"nowrap\");\n \n //Each y-axis will have 10 axis-marks \n var increment = parseInt(options[13]); // Can be changed using the options value\n var yAxisSegments = Math.ceil(maxAxisVal / increment);\n //Every odd value of i, we draw an axis mark with a label (ie] -10), every even value we just draw an axis mark (ie] -).\n for (var i = (yAxisSegments -1); i >= -1; i--) {\n if (i % 2 != 0) { //i.e.- Odd value\n $(\".yLabel\").append(\"<div class=dashY\" + i + \">\" + maxValAxis + \"-</div>\");\n $(\".dashY\" + i).css(\"height\", (options[21] / yAxisSegments));\n } else {\n $(\".yLabel\").append(\"<div class=dashY\" + i + \">-</div>\");\n $(\".dashY\" + i).css(\"height\", (options[21] / yAxisSegments));\n }\n maxValAxis -= increment;\n $(\".dashY\" + i).css(\"text-align\", \"right\");\n }\n \n\n //for each bar, draw an x-axis label\n for (var i = 0; i < data.length; i++) {\n $(\".xLabel\").append(\"<div class=tick\" + i + \">\" + data[i][0] + \"</div>\");\n $(\".tick\" + i).css({\n \"display\" : \"inline-block\",\n //\"text-align\" : \"center\",\n //Translate the x-axis labels so they are written vertically\n \"writing-mode\" : \"tb-rl\",\n \"flex-grow\" : \"1\",\n \"top\" : \"50%\",\n \"padding-right\" : \"10px\",\n \"position\" : \"relative\",\n \"transform\" : \"translateX(-40%)\",\n });\n }\n\n //Color of the labels and add a margin\n $(\".xLabel\").css({\n \"margin\" : \"auto\",\n \"color\" : options[11],\n \"font-size\" : options[12]\n });\n $(\".yLabel\").css({\n \"color\" : options[9],\n \"font-size\" : options[10]\n });\n}\n\n//EXECUTING THE drawBarChart FUNCTION when BEING RUN IN THE SCRIPT FILE\n\n drawXYBox(element);\n drawYLabel(element, options);\n var maxAxisVal = drawData(data, options);\n drawAxisMarks(data, options, maxAxisVal);\n var chartWidth = $(\".xyData\").width();\n drawXLabel(options, chartWidth, element);\n drawMainTitle(options, chartWidth, element);\n\n //THE CLICK EVENTS\n // Main title, X-Title and Y-Title editable on CLICK\n $(\".title, .xTitle, .yTitle\").click((event) => {\n if($(event.target).attr('class') === 'title'){\n var input = window.prompt(\"Enter name of chart\", \"\");\n $(event.target).closest('div').text(input)\n }else if($(event.target).attr('class') === 'xTitle'){\n var input = window.prompt(\"Enter name for x-axis\", \"\");\n $(event.target).closest('div').text(input)\n }else if($(event.target).attr('class') === 'yTitle'){\n var input = window.prompt(\"Enter value for y-axis\", \"\");\n $(event.target).closest('div').text(input)\n }\n });\n\n //Changes color of individual xLabel colors ON CLICK\n $(\".xLabel\").click((event) => {\n var input = window.prompt(\"Enter a color\", \"\");\n $(event.target).closest('div').css(\"color\", input);\n });\n\n //Changes color of individual YLabel colors ON CLICK\n $(\".yLabel\").click((event) => {\n var input = window.prompt(\"Enter a color\", \"\");\n $(event.target).closest('div').css(\"color\", input);\n });\n\n}",
"function setYAxis() {\n const Y_LABEL_X_OFFSET = -height / 2;\n const Y_LABEL_Y_OFFSET = -80;\n const TICK_COUNT = 10;\n const Y_AXIS_CALL = d3.axisLeft(yScale)\n .ticks(TICK_COUNT)\n .tickFormat(data => {\n return data + '%';\n });\n\n // Y Axis Label\n d3Chart.append('text')\n .attr('class', 'y axis-label')\n .attr('x', Y_LABEL_X_OFFSET)\n .attr('y', Y_LABEL_Y_OFFSET)\n .attr('font-size', '24px')\n .attr('text-anchor', 'middle')\n .attr('transform', 'rotate(-90)')\n .text('Percent of Lyrics Unique (%)');\n\n // Y Axis Setup\n d3Chart.append('g')\n .attr('class', 'y-axis')\n .call(Y_AXIS_CALL)\n .selectAll('text')\n .attr('font-size', '16px');\n }",
"function renderLabelsVertical() {\n var i, origin;\n\n // Y Labels\n for (i = 0; i < this.range.max - this.range.min + 1; i++) {\n origin = getInnerChartPoint([\n 0,\n 100 - (i * 100) / (this.range.max - this.range.min)\n ]);\n\n origin[0] -= LABEL_MARGIN;\n\n this.svg.add('text', origin, String(i + this.range.min), { class: 'chart-label chart-label-y' });\n }\n}",
"function renderLabelsY(circlesLabels, yLinearScale, chosenY) {\n circlesLabels.transition()\n .duration(1000)\n .attr(\"y\", d => yLinearScale(d[chosenY]));\n return circlesLabels;\n}",
"function updateYlabel() {\n if (options.ylabel && ylabel) {\n ylabel.text(options.ylabel);\n } else {\n ylabel.style(\"display\", \"none\");\n }\n }",
"_drawYAxis(ctx, area) {\n ctx.strokeStyle = LABEL_COLOR;\n ctx.fillStyle = LABEL_COLOR;\n ctx.font = this.LABEL_FONT;\n ctx.textBaseline = 'middle';\n ctx.lineWidth = AXIS_LINE_WIDTH;\n ctx.textAlign = 'right';\n ctx.stroke(area.yaxis.path);\n const labelWidth = (3 * this.LEFT_MARGIN) / 4;\n area.yaxis.labels.forEach((label) => {\n ctx.fillText(label.text, label.x + labelWidth, label.y, labelWidth);\n });\n }",
"function drawYAxis(yScale){\n\tvar yAxis = d3.svg.axis()\n\t \t\t.scale(yScale)\n\t \t\t.orient(\"left\");\n\n\ttest_viz.append(\"g\")\n\t\t\t.attr(\"class\", \"axis\")\n\t\t\t.attr(\"id\", \"y-axis\")\n\t\t\t.attr(\"transform\", \"translate(\"+padding.left+\",0)\")\n\t\t\t.call(yAxis);\n\n\td3.select(\"#y-axis\")\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"transform\", \"rotate(-90)\")\n\t\t\t.attr(\"x\", -(scatterplot_height / 2))\n\t\t\t.attr(\"y\", -45)\n\t\t\t.style(\"text-anchor\", \"middle\")\n\t\t\t.text(y_axis_label);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply changes to set with given `setId`. | updateSet(setId, title, description, isDeleted) {
const edits = [
title,
description,
isDeleted,
setId
]
return this.db.one(`
UPDATE
study_sets
SET
title = COALESCE($1, title),
description = COALESCE($2, description),
is_deleted = COALESCE($3, is_deleted)
WHERE
set_id = $4
RETURNING
set_id AS id,
title,
description,
creator_id,
created,
changed,
is_deleted
`, edits);
} | [
"updateSetReps(reps, id) {\r\n const sets = this.state.sets;\r\n sets[sets.findIndex(set => set.id === id)].reps = reps;\r\n\r\n this.setState({\r\n sets: sets\r\n });\r\n }",
"updateSetWeight(weight, id) {\r\n const sets = this.state.sets;\r\n sets[sets.findIndex(set => set.id === id)].weight = weight;\r\n\r\n this.setState({\r\n sets: sets\r\n });\r\n }",
"function toggleId(id, selectionChange) {\n var newSet;\n if (selectionSet().has(id)) {\n newSet = immutable.Set()\n } else {\n newSet = immutable.Set.of(id)\n }\n selectionChange(selectionSet(), newSet)\n return selectionSet(newSet)\n }",
"update_sets(set) {\n\n if (this.set == set) { return; }\n this.set = set;\n if (this.edges != undefined) {\n this.edges.forEach(element => element.update_sets(set));\n }\n }",
"setID(id){\n let layer = this.parent.layer;\n this.id = id;\n _.each(SELECT_MAP, (selector, key) => {\n _.each(this.node.querySelectorAll(selector), el => __updateAttribute(el, id, layer, key));\n });\n // change to self\n __updateAttribute(this.node, id, layer, 'id');\n }",
"async handleRemoveSet(e, setId) {\r\n e.preventDefault();\r\n const workoutId = this.props.match.params.workoutId;\r\n deleteSets(setId);\r\n\r\n await this.setState({\r\n sets: this.state.sets.filter(set => set.id !== setId)\r\n });\r\n\r\n const sets = this.state.sets;\r\n\r\n this.context.addSet(sets, workoutId);\r\n }",
"set(id, data){\n if(this.datas[id]){\n if(data.id){\n delete data.id;\n }\n this.datas[id] = data;\n }\n }",
"function oldSet(id, data, name, num){\n set(id, name, data, num);\n}",
"set(_id, _data) {\n this.values[_id].set(_data);\n }",
"setId(id) {\n this.id = id;\n }",
"function toggleAddId(id, selectionChange) {\n var newSet;\n if (selectionSet().has(id)) {\n newSet = selectionSet().delete(id)\n } else {\n newSet = selectionSet().add(id)\n }\n selectionChange(selectionSet(), newSet)\n return selectionSet(newSet)\n }",
"_set (context, id) {\n this.special.set(context, id)\n }",
"updateIds() {\n let adapts = this.getAdaptationSets();\n let cpt = 0;\n for (let i = 0; i < adapts.length; i++) {\n let atapt = adapts[i];\n atapt.$.id = i;\n\n for (let j = 0; j < atapt.Representation.length; j++) {\n let repr = atapt.Representation[j];\n repr.$.id = cpt++;\n }\n }\n }",
"function setAssociatedID(id) {\n\t\tif (!_activeID) {\n\t\t\tthrow 'Cannot call setAssociatedID() with no history transaction set in progress';\n\t\t}\n\n\t\tvar sql = \"UPDATE transactionSets SET id=\";\n\t\tif (!id) {\n\t\t\tsql += '0';\n\t\t}\n\t\t// If array, insert hyphen-delimited string\n\t\telse if (typeof id == 'object') {\n\t\t\t\tsql += \"'\" + id.join('-') + \"'\";\n\t\t\t} else\n\t\t\t{\n\t\t\t\tsql += id;\n\t\t\t}\n\t\tsql += \" WHERE transactionSetID=\" + _activeID;\n\t\tZotero.DB.query(sql);\n\t}",
"function setId(elem, id) {\n id = toLogeeString(id);\n while (getById(id)) {\n id = id + Math.floor(Math.random() * 10);\n }\n return elem.id = id;\n}",
"setDataSet(id){\n this.setState({data_set:id, data:[], hasMoreData:true});\n ReactGA.event({\n category: 'Data',\n action: 'Chose a data set to view',\n label: DATA_SETS[id].name\n });\n\n DATA_SETS[id].fetchData(id, this.setData, this.state.data.length)\n }",
"update(id, permissionSet) {\n let url_ = this.baseUrl + \"/v1/ContentPermissionSets/{id}\";\n if (id === undefined || id === null)\n throw new Error(\"The parameter 'id' must be defined.\");\n url_ = url_.replace(\"{id}\", encodeURIComponent(\"\" + id));\n url_ = url_.replace(/[?&]$/, \"\");\n const content_ = JSON.stringify(permissionSet);\n let options_ = {\n body: content_,\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n };\n return this.transformOptions(options_).then(transformedOptions_ => {\n return this.http.fetch(url_, transformedOptions_);\n }).then((_response) => {\n return this.processUpdate(_response);\n });\n }",
"set(id, fields) {\n let version = this._versions.get(id);\n\n let isNew = false;\n\n if (version) {\n Object.assign(version, fields);\n } else {\n version = _objectSpread({\n _id: id\n }, fields);\n isNew = true;\n\n this._versions.set(id, version);\n }\n\n this._watchCallbacks.forEach((_ref2) => {\n let {\n fn,\n filter\n } = _ref2;\n\n if (!filter || filter === version._id) {\n fn(version, isNew);\n }\n });\n }",
"UPDATE_CURRENT_SET(state, set) {\n state.currentSet = set;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Entry point for the script. This script will attempt to iterate over all un processed accounts and check them for any disapproved ads. A Drive folder is created each day in which to store Ads accountspecific spreadsheets containing any information on disapproved ads. The script will process as many accounts as possible within the 30 minute Ads Scripts execution time limits. | function main() {
var managerAccount = AdsApp.currentAccount();
var centralSpreadsheet = validateAndGetSpreadsheet(CONFIG.CENTRAL_SPREADSHEET_URL);
validateEmailAddresses(CONFIG.RECIPIENT_EMAILS);
var timeZone = AdsApp.currentAccount().getTimeZone();
var now = new Date();
centralSpreadsheet.setSpreadsheetTimeZone(timeZone);
var processStatus = centralSpreadsheet.getRangeByName(CONFIG.PROCESS_STATUS_RANGE).getValue();
var runDateString = centralSpreadsheet.getRangeByName(CONFIG.RUN_DATE_RANGE).getValue();
var runDate = getDateStringInTimeZone('M/d/y', runDateString);
var dateString = getDateStringInTimeZone('M/d/y', now);
var folderName = "Disapproved Ads : " + dateString;
var folder = createDriveFolder(folderName);
// This is the first execution today, so reset status to PROCESS_NOT_STARTED
// and clear any old data.
if (runDate != dateString) {
processStatus = CONFIG.PROCESS_NOT_STARTED;
setProcessStatus(centralSpreadsheet, processStatus);
clearSheetData(centralSpreadsheet);
}
centralSpreadsheet.getRangeByName(CONFIG.RUN_DATE_RANGE).setValue(dateString);
if (processStatus != CONFIG.PROCESS_COMPLETED) {
ensureAccountLabels([CONFIG.LABEL]);
} else {
removeLabelsInAccounts();
removeAccountLabels([CONFIG.LABEL]);
Logger.log("All accounts had already been processed.");
return;
}
// Fetch the managed accounts that have not been checked and process them.
var accountSelector = getAccounts(false);
processStatus = processAccounts(centralSpreadsheet, accountSelector, folder);
if (processStatus == CONFIG.PROCESS_COMPLETED) {
setProcessStatus(centralSpreadsheet, processStatus);
removeLabelsInAccounts();
AdsManagerApp.select(managerAccount);
removeAccountLabels([CONFIG.LABEL]);
Logger.log("Process Completed without any errors");
sendEmailNotification(centralSpreadsheet);
}
} | [
"function main() {\n var missingCount = 0;\n\n // Selector for all active campaigns\n var campaignIterator = AdsApp.campaigns()\n .withCondition(\"Status = ENABLED\")\n .withCondition(\"AdvertisingChannelType = SEARCH\")\n .get();\n\n // Iterate through all active campaigns\n while (campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n\n // Selector for all active ad groups in the current campaign\n var adGroupIterator = campaign.adGroups()\n .withCondition(\"Status = ENABLED\")\n .get();\n\n // Iterate through all active ad groups\n while (adGroupIterator.hasNext()) {\n var adGroup = adGroupIterator.next();\n\n // Selector for all responsive search ads in the current ad group\n var rsaIterator = adGroup.ads()\n .withCondition(\"Type = RESPONSIVE_SEARCH_AD\")\n .withCondition(\"Status = ENABLED\")\n .get();\n\n // Check if RSA is missing in the current ad group\n if (!rsaIterator.hasNext()) {\n missingCount++;\n }\n }\n }\n\n Logger.log(\"Number of active ad groups missing RSA: \" + missingCount);\n}",
"function main() {\n // select the current account\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n \n var conversionVariable = 0;\n\n // Selector for the current enabled campaign\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\");\n // Get all the enabled campaigns\n var campaignIterator = campaignSelector.get();\n // Loop over the enabled campaigns - log out the data needed - add stats to the spreadsheet\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n\n Logger.log(\"Campaign Name: \" + campaign.getName());\n // Get the bidding strategy to make sure the campaign is Max Clicks (\"TARGET_SPEND\")\n var currentBiddingStrategy = campaign.getBiddingStrategyType();\n Logger.log(\"Current Bidding Strategy: \" + currentBiddingStrategy);\n // Get the current conversion and conversion rate stats\n var currentStats = campaign.getStatsFor(\"THIS_MONTH\");\n var currentClicks = currentStats.getClicks();\n var currentCost = currentStats.getCost();\n var currentConversions = currentStats.getConversions();\n var currentConversionRate = currentStats.getConversionRate();\n\n Logger.log(\"Campaign Stats: \" + \"Conversions: \" + currentConversions + \"ConversionRate: \" + currentConversionRate +\n \"Cost: \" + currentCost + \"currentClicks: \" + currentClicks);\n }\n\n if(currentConversions <= 0 && currentBiddingStrategy === \"TARGET_SPEND\") {\n Logger.log(\"Campaign currently has no conversions\");\n }\n else if(currentConversions > conversionVariable) {\n Logger.log(\"Campaign is tracking above Conversion Variable\");\n }\n else if(currentConversions < conversionVariable) {\n Logger.log(\"Campaign conversions is not tracking above Conversion Variable\");\n }\n else {\n Logger.log(\"An error has occured, please look into this account\");\n }\n\n if(currentConversionRate < conversionRateVariable) {\n Logger.log(\"Conversion Rate is below conversion rate variable\");\n }\n else if(currentConversionRate > conversionRateVariable) {\n Logger.log(\"Conversion Rate is tracking above conversion rate variable\");\n }\n else {\n Logger.log(\"Campaign conversion rate has thrown an error - please look into this account\");\n }\n}",
"function main() {\n // Init Spreadsheet\n var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/13MvQ2dXsekZP3ZBXZSoYOCyPsZfVJBTMGIdPAGWw7Zc/edit?usp=sharing');\n var sheetName = spreadsheet.getSheetName();\n // Format report to print on correct sheet - IMPORTANT!!\n var sheet = spreadsheet.getSheets()[1];\n \n // Select accounts at the manager level - format for desired output \n var accountSelector = MccApp\n .accounts()\n .withCondition(\"Impressions > 5000\")\n .withCondition(\"LabelNames CONTAINS 'iHeart'\")\n .forDateRange(\"LAST_7_DAYS\")\n .orderBy(\"Cost DESC\")\n .withLimit(50);\n \n var accountIterator = accountSelector.get();\n // Iterate over the accounts that match the conditions\n while (accountIterator.hasNext()) {\n \n var account = accountIterator.next();\n MccApp.select(account);\n // AQL query string to select metrics needed for report\n var myString = \"SELECT AccountDescriptiveName, Cost, Clicks, Impressions, Ctr, AverageCpm FROM ACCOUNT_PERFORMANCE_REPORT DURING LAST_7_DAYS\";\n var myAccount = AdWordsApp.currentAccount();\n Logger.log(myAccount.getCustomerId());\n Logger.log(myString);\n \n // Init report with query string - iterate account data per row into spreadsheet\n var report = AdWordsApp.report(myString);\n var iter = report.rows();\n while (iter.hasNext()) {\n var reportRow = iter.next();\n sheet.appendRow([\n reportRow[\"AccountDescriptiveName\"], \n reportRow[\"Cost\"],\n reportRow[\"Clicks\"],\n reportRow[\"Impressions\"], \n reportRow[\"Ctr\"], \n reportRow[\"AverageCpm\"]]);\n }\n }\n }",
"function main() {\n\n // Init Variables\n var maxCpm = parseFloat(1.25);\n var maxCpc = parseFloat(2.00);\n var ctrCheck = parseFloat(.005);\n\n var maxClicksLabel = 'iHeart_MaxClicks';\n\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n Logger.log(\"Account - \" + accountName);\n\n var labelSelector = AdWordsApp.labels();\n\n var labelIterator = labelSelector.get();\n\n while (labelIterator.hasNext()) {\n var label = labelIterator.next();\n var labelName = label.getName();\n Logger.log(\"Account Label - \" + labelName);\n }\n \n\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\");\n\n var campaignIterator = campaignSelector.get();\n\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n var campaignName = campaign.getName();\n\n var biddingStrategy = campaign.getBiddingStrategyType();\n\n var currentBudget = campaign.getBudget();\n\n Logger.log(\"Campaign Name - \" + campaignName + \" Bidding Strategy - \" + biddingStrategy + \" Campaign Budget - \" + currentBudget);\n var stats = campaign.getStatsFor(\"ALL_TIME\");\n\n var cpc = stats.getAverageCpc();\n var cpm = stats.getAverageCpm();\n var ctr = stats.getCtr();\n\n Logger.log(\"Campaign Stats - \" + \" cpc: \" + cpc + \" cpm: \" + cpm + \" ctr: \" + ctr);\n\n }\n\n if(cpc <= maxCpc && ctr <= ctrCheck) {\n Logger.log(\"Current Cost per Click is below Target of $2.00 - Recommended Bidding Strategy is Max Clicks\");\n // campaign.bidding().setStrategy(\"TARGET_SPEND\");\n // Apply Account Label - iHeart_MaxClicks\n // account.applyLabel(maxClicksLabel);\n }\n else if(cpm >= maxCpm) {\n Logger.log(\"Cpm is above $5 - Recommended bidding strategy is VCPM\");\n // campaign.bidding().setStrategy(\"MANUAL_CPM\");\n // account.removeLabel(maxClicksLabel);\n }\n else {\n Logger.log(\"Campaign stats are holding, no adjustment necessary\");\n }\n}",
"function main() {\n // Init Spreadsheet\n var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1mRbD0jN-i1Jy7HVIySBvKnxfLc7ADKwzpn5nfXOdalg/edit?usp=sharing');\n var sheet = spreadsheet.getSheets()[0];\n\n\n // Select accounts with label\n var accountSelector = MccApp\n .accounts()\n .withCondition(\"LabelNames CONTAINS 'CMS-CTC'\")\n .withLimit(50);\n\n var accountIterator = accountSelector.get();\n\n while(accountIterator.hasNext()) {\n // Iterate over the accounts and access them\n var account = accountIterator.next();\n MccApp.select(account);\n // Generate a AQL Query string with desired metrics\n var reportString = \"SELECT AccountDescriptiveName, CampaignName, StartDate, Clicks, Impressions, AverageCpc, CostPerConversion, Ctr FROM CAMPAIGN_PERFORMANCE_REPORT WHERE CampaignStatus = ENABLED DURING LAST_7_DAYS\";\n \n // Init report with query string - iterate account data into rows\n var report = AdWordsApp.report(reportString);\n var iter = report.rows();\n while(iter.hasNext()) {\n var reportRow = iter.next();\n\n sheet.appendRow([\n reportRow[\"AccountDescriptiveName\"],\n reportRow[\"CampaignName\"],\n reportRow[\"StartDate\"],\n reportRow[\"Clicks\"],\n reportRow[\"Impressions\"],\n reportRow[\"AverageCpc\"],\n reportRow[\"CostPerConversion\"],\n reportRow[\"Ctr\"]\n ]);\n }\n }\n}",
"function main() {\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n \n Logger.log(\"Account: \" + accountName);\n \n var spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1yCToteUPvD6xwBFX_Xorj09tW5Fav-DCxWllG5EqlhE/edit?usp=sharing';\n var spreadsheet = SpreadsheetApp.openByUrl(spreadsheet_url);\n var sheet = spreadsheet.getSheets()[0];\n \n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Impressions > 100\")\n .forDateRange(\"LAST_MONTH\")\n .orderBy(\"Clicks DESC\");\n\n var campaignIterator = campaignSelector.get();\n while (campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n Logger.log(\"Campaign: \" + campaign.getName());\n }\n \n // Init variables\n var maxCpm = parseFloat(5);\n var targetCpc = parseFloat(1);\n var targetCpm = parseFloat(1.25);\n var cpmCheck = parseFloat(2);\n\n var campaignSelector = AdWordsApp\n .campaigns()\n .forDateRange(\"LAST_7_DAYS\");\n\n var campaignIterator = campaignSelector.get();\n while (campaignIterator.hasNext()) {\n // Get campaign stats\n var campaign = campaignIterator.next();\n var campaignName = campaign.getName();\n Logger.log(\"Campaign Name:\" + campaignName);\n\n var currentBiddingStrategy = campaign.getBiddingStrategyType();\n Logger.log(\"Current Bidding Strategy: \" + currentBiddingStrategy);\n\n var currentDailyBudget = campaign.getBudget().getAmount();\n Logger.log(\"Current daily budget: \" + currentDailyBudget);\n\n var stats = campaign.getStatsFor(\"LAST_7_DAYS\");\n var currentCpc = stats.getAverageCpc();\n Logger.log(\"Current CPC: \" + currentCpc);\n var currentCpm = stats.getAverageCpm();\n Logger.log(\"Current CPM: \" + currentCpm);\n \n // Generate a report on placements\n var report = AdWordsApp.report(\n \"SELECT DisplayName, Cost, AverageCpm, Ctr, Clicks, Impressions FROM PLACEMENT_PERFORMANCE_REPORT WHERE Impressions > 100 DURING LAST_7_DAYS\");\n var rows = report.rows();\n while(rows.hasNext()) {\n var row = rows.next();\n sheet.appendRow([row[\"DisplayName\"], row[\"Cost\"], row[\"AverageCpm\"], row[\"Ctr\"], row[\"Clicks\"], row[\"Impressions\"]]);\n Logger.log(\"Printed 7 Day Row\");\n }\n var allString = \"SELECT DisplayName, Cost, AverageCpm, Ctr, Clicks, Impressions FROM PLACEMENT_PERFORMANCE_REPORT WHERE Impressions > 100 DURING LAST_30_DAYS\";\n Logger.log(allString);\n var allReport = AdWordsApp.report(allString);\n \n var iter = report.rows();\n \n while(iter.hasNext()) {\n var allReportRow = iter.next();\n sheet.appendRow([\n allReportRow[\"DisplayName\"],\n allReportRow[\"Cost\"],\n allReportRow[\"AverageCpm\"],\n allReportRow[\"Ctr\"],\n allReportRow[\"Clicks\"],\n allReportRow[\"Impressions\"]]);\n Logger.log(\"Printed 30 Day Row\");\n }\n }\n\n if(currentCpc < targetCpc) {\n Logger.log(\"Current Cost per Click is below Target of $1.00 - Setting bid strategy to Max Clicks\");\n // campaign.bidding().setStrategy(\"TARGET_SPEND\");\n }\n else if(currentCpm > maxCpm) {\n Logger.log(\"Cpm is above $5 - setting bidding strategy to VCPM\");\n // campaign.bidding().setStrategy(\"MANUAL_CPM\");\n }\n else {\n Logger.log(\"Campaign stats are holding, no adjustment necessary\");\n }\n}",
"function main() {\n\n var spreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1Z-l1kE6qMWSHKjfCCUISCAoxCuZDwg1T4mPfLzE9hwc/edit?usp=sharing';\n \n var columns = {\n id: 1,\n name: 2,\n endDate: 4,\n orderedImp: 6,\n dailyImp: 7,\n below: 8\n };\n \n var startRow = 2;\n \n \n Logger.log('Using spreadsheet - %s.', spreadsheetUrl);\n var spreadsheet = SpreadsheetApp.openByUrl(spreadsheetUrl);\n var sheet = spreadsheet.getSheets()[0];\n \n var endRow = sheet.getLastRow();\n \n // var accountName = sheet.getRange(ROW, COLUMN.accountName).getValue();\n\n // var budgetRange = sheet.getRange(13, 2);\n // var budgetArray = [[currentDailyBudget]]\n // budgetRange.setValues(budgetArray);\n \n var currentAccount = AdWordsApp.currentAccount();\n var currentAccountName = currentAccount.getName();\n var accountNameRange = sheet.getRange(2,2);\n var accountNameArray = [[currentAccountName]];\n accountNameRange.setValues(accountNameArray);\n var currentAccountId = currentAccount.getCustomerId();\n var accountIdRange = sheet.getRange(2,1);\n var accountIdArray = [[currentAccountId]];\n accountIdRange.setValues(accountIdArray);\n Logger.log(\"Current Account Processed: \" + currentAccountName)\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\")\n .forDateRange(\"THIS_MONTH\")\n var campaignIterator = campaignSelector.get();\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next()\n var currentCampaign = campaign.getName();\n var campaignStats = campaign.getStatsFor(\"THIS_MONTH\");\n var currentCampaignImpressions = campaignStats.getImpressions();\n Logger.log(\"current impressions: \" + currentCampaignImpressions);\n var orderedImpressions = sheet.getRange(2,6).getValue();\n Logger.log(\"ordered impressions: \" + orderedImpressions);\n var daysRemaining = sheet.getRange(2, 5).getValue();\n var impressionsRemaining = orderedImpressions - currentCampaignImpressions;\n Logger.log(\"impressions remaining: \" + impressionsRemaining);\n var dailyImpressions = impressionsRemaining / daysRemaining;\n dailyImpressions = dailyImpressions.toFixed(0);\n Logger.log(\"daily imp: \" + dailyImpressions);\n var dailyImpRange = sheet.getRange(2, 7);\n var dailyImpArray = [[dailyImpressions]];\n dailyImpRange.setValues(dailyImpArray);\n var belowFifty = dailyImpressions * .50;\n Logger.log(\"Below 50 calculation: \" + belowFifty);\n \n if(dailyImpressions < belowFifty) {\n // ALERT EMPLOYEE = Notify Function\n Logger.log(\"=======================================\");\n Logger.log(\"Account Flagged: \" + currentAccountName);\n var belowFiftyRange = sheet.getRange(2, 8);\n var yesArray = [[\"Yes\"]];\n belowFiftyRange.setValue(yesArray);\n } else {\n Logger.log(\"Not below 50% - That's Good!\");\n var okayRange = sheet.getRange(2, 8);\n var noArray = [[\"No\"]];\n \tokayRange.setValue(noArray);\n }\n } \n}",
"function main() {\n // Init Variables\n var emailForNotify = \"eric.king@comporium.com\";\n\n // Grab Ordered Impressions\n var orderedImpressions = sheet.getRange(2,3);\n\n // Grab Days Remaining\n var daysRemaining = sheet.getRange(5,2);\n\n // Email function to pass string and send through to email provided\n function notify(string) {\n // Construct email template for notifications\n // Must have to, subject, htmlBody\n var emailTemplate = {\n to: emailForNotify,\n subject: accountName,\n htmlBody: \"<h1>Comporium Media Services Automation Scripts</h1>\" + \"<br>\" + \"<p>This account has encountered has been flagged</p>\" + accountName +\n \"<br>\" + \"<p>This campaign is a candidate for VCPM: </p>\" + campaignName + \"<br>\" + \"<p>Additional Information - </p>\" + \"<br>\"\n + string + \"<p>Average CPM For Last 7 Days: \" + avgCpm + \"<br>\" +\"<p>If something is incorrect with this notification please reach out to eric.king@comporium.com. Thanks!</p>\"\n }\n MailApp.sendEmail(emailTemplate);\n }\n\n // select current account - get account name and return it\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n Logger.log(\"Account - \" + accountName);\n\n // Select current Campaign - ENABLED\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\");\n\n var campaignIterator = campaignSelector.get();\n\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n var campaignName = campaign.getName();\n Logger.log(campaignName);\n\n var currentDailyBudget = campaign.getBudget().getAmount();\n Logger.log(\"current daily budget: \" + currentDailyBudget);\n \n var currentBiddingStrategy = campaign.getBiddingStrategyType();\n Logger.log(\"current bidding strategy: \" + currentBiddingStrategy);\n var campaignBidding = AdWordsApp.campaignBidding();\n\n var sevenStats = campaign.getStatsFor(\"LAST_7_DAYS\");\n var avgCpm = sevenStats.getAverageCpm();\n Logger.log(\"Average Cpm Last 7 Days: \" + avgCpm);\n\n var allStats = campaign.getStatsFor(\"ALL_TIME\");\n var currentImpressions = allStats.getImpressions();\n Logger.log(\"Total Impressions: \" + currentImpressions);\n\n var impressionsRemaining = orderedImpressions - allImpressions;\n\n var dailyImpressions = impressionsRemaining / daysRemaining;\n Logger.log(\"Daily Impressions: \" + dailyImpressions);\n\n var dailyBudget = dailyImpressions / 1000 * avgCpm;\n Logger.log(\"Daily Budget Calculation: \" + dailyBudget);\n\n\n if(avgCpm > 2) {\n Logger.log(\"Cpm has gone above $2 on this max clicks campaign - available to switch Bidding Strategy\");\n notify(\"Cpm has gone above $2 on this max clicks campaign - available to switch Bidding Strategy\");\n }\n else if(avgCpm > 3) {\n Logger.log(\"CPM has gone above $3 on this max clicks campaign - adjusting budget to - \" + dailyBudget);\n notify(\"Cpm has gone above $3 on this max clicks campaign - adjusting budget to the calculated daily budget\");\n campaignBidding.setStrategy(\"MANUAL_CPM\");\n } else {\n Logger.log(\"This Max Clicks campaign should continue using this bidding strategy\");\n }\n }\n}",
"function main() {\n var currentAccount = AdWordsApp.currentAccount();\n var currentAccountName = currentAccount.getName();\n var cpmCheck = 1.25;\n var bidDownOnce = currentCpm - .50;\n var bidDownTwice = currentCpm - 1.00;\n var cpmAboveAverage = 3.00;\n var maxCpm = 5.00;\n \n var campaignIterator = AdWordsApp.campaigns().get();\n\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n Logger.log(\"Account - \" + currentAccountName);\n Logger.log(\"Campaign Name: \" + campaign.getName());\n\n var cpmStats = campaign.getStatsFor(\"LAST_14_DAYS\");\n var currentCpm = cpmStats.getAverageCpm();\n Logger.log(\"Average CPM for last 14 days: \" + currentCpm);\n\n var currentBiddingStrategy = campaign.getBiddingStrategyType();\n Logger.log(\"Current bidding strategy: \" + currentBiddingStrategy);\n\n //Ad Groups selector\n var adGroupSelector = AdWordsApp\n .adGroups()\n .forDateRange(\"LAST_14_DAYS\");\n var adGroupIterator = adGroupSelector.get();\n while(adGroupIterator.hasNext()) {\n var adGroup = adGroupIterator.next();\n Logger.log(\"Ad Group Name: \" + adGroup.getName());\n }\n }\n\n if(currentBiddingStrategy === \"MANUAL_CPM\") {\n if(currentCpm >= cpmCheck && currentCpm < cpmAboveAverage) {\n Logger.log(\"CPM is greater than $1.25 and under the max\");\n setCpm() - adGroup.setCpm(bidDownOnce);\n } else if(currentCpm > cpmAboveAverage && currentCpm < maxCpm) {\n Logger.log(\"CPM is above average - bidding down by $1.00\");\n setCpm() - adGroup.setCpm(bidDownTwice);\n }\n else if(currentCpm > maxCpm) {\n // NOTIFY\n Logger.log(\"CPM IS ABOVE $5\");\n }\n else {\n Logger.log(\"Current CPM is lower than $1.25\");\n }\n }\n\n\n}",
"function main() {\n const spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);\n const sheet = spreadsheet.getSheetByName(RSA_SHEET_NAME);;\n\n const range = sheet.getDataRange();\n const responsiveAdRows = range.getValues();\n\n // Start with 2nd row and skip the header.\n for (var rowIndex = 1; rowIndex < responsiveAdRows.length; rowIndex++) {\n var updateColValue = responsiveAdRows[rowIndex][AdColumnIndex.UPDATE];\n if (updateColValue === UPDATE_STATUS_YES) {\n var accountId = responsiveAdRows[rowIndex][AdColumnIndex.ACCOUNT];\n var accountIterator = AdsManagerApp.accounts()\n .withIds([accountId])\n .get();\n\n while (accountIterator.hasNext()) {\n var account = accountIterator.next();\n AdsManagerApp.select(account);\n addResponsiveAd(responsiveAdRows[rowIndex], sheet, rowIndex + 1);\n }\n }\n }\n}",
"function main() {\n \n Logger.log('Using template spreadsheet - %s.', SPREADSHEET_URL);\n\n //open the template spreadsheet \n var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);\n \n Logger.log(spreadsheet.getName());\n \n var sheet = spreadsheet.getSheets()[0];\n sheet.getRange(1, 2, 1, 1).setValue(new Date());\n //make a copy of the template and rename it \n var report = spreadsheet.copy('monthly ad report');\n \n // Logger.log(report.getName());\n \n //empty object for holding all values together\n var segmentMap = {};\n \n var row = 4;\n \n //retrieve the campaigns that you want to work with\n \n var campaignSelector = AdWordsApp.campaigns()\n .withCondition(\"Name CONTAINS_IGNORE_CASE 'campaign'\");\n \n var campaignIterator = campaignSelector.get();\n \n //iterate over campaigns\n while (campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n //retrieve the ads\n var adSelector = campaign.ads()\n .withCondition(\"Status = ENABLED\");\n \n var adIterator = adSelector.get();\n Logger.log(adIterator.totalNumEntities());\n \n //iterate over the ads\n while (adIterator.hasNext() || row < adIterator.totalNumEntities()) {\n \n \n var ad = adIterator.next();\n //print ad headlines to column 2\n var headline = ad.getHeadline();\n var id = ad.getId();\n sheet.getRange(row, 2).setValue(headline);\n sheet.getRange(row, 3).setValue(id);\n //move down a row\n row++;\n \n }\n \n } \n \n\n\n \n \n \n}",
"function getAllCampaigns(sheet) { \n var campaignIterator = AdWordsApp.campaigns().get();\n\n var today = new Date();\n\n // due to data gathering limitations, these variables are the metrics \n // for the last two full days. \n var dayPrevious = getDataFromPast(1); \n var prevPrev = getDataFromPast(2);\n\n while (campaignIterator.hasNext()) { \n var campaign = campaignIterator.next(); \n var campaignName = campaign.getName() ? campaign.getName() : '--';\n\n //intialize variables to 0 \n var totalCost = 0; \n var totalCost2 = 0; \n var totalConversions = 0; \n var totalConversions2 = 0; \n var cpa = 0; \n var cpa2 = 0; \n var changeCPA = 0; \n var changeSpend = 0;\n\n var stats = campaign.getStatsFor(dayPrevious, dayPrevious); \n var stats2 = campaign.getStatsFor(prevPrev, prevPrev);\n\n //day 1 stats \n totalCost += stats.getCost(); \n totalConversions += stats.getConversions();\n\n //check if yesterdays conversions were zero \n //if so make cpa in spreadsheet zero to avoid error read out. \n if (totalConversions == 0) { \n cpa = 0; \n } else { \n cpa = totalCost / totalConversions; \n }\n\n //day 2 stats \n totalCost2 += stats2.getCost(); \n totalConversions2 += stats2.getConversions();\n\n //check if conversions two days ago were zero \n //if so make cpa in spread zero to avoid error read out. \n if (totalConversions2 == 0) { \n cpa = 0; \n } else { \n cpa2 += totalCost2 / totalConversions2; \n }\n\n //change in cpa \n if ((totalConversions == 0) || (totalConversions2 == 0)) { \n changeCPA = 0; \n } else { \n changeCPA = ((cpa - cpa2) / cpa2) * 100; \n }\n\n //change in spend \n if ((totalCost == 0) && (totalCost2 == 0)) { \n changeSpend = 0; \n } else { \n changeSpend = ((totalCost - totalCost2) / totalCost2) * 100; \n }\n\n //fill in row with campaign data \n var row = [ \n campaignName, \n changeCPA + \"%\", \n changeSpend + \"%\", \n \"$\" + cpa, \n \"$\" + cpa2, \n \"$\" + totalCost, \n \"$\" + totalCost2, \n totalConversions, \n totalConversions2 \n ];\n\n sheet.appendRow(row); \n } \n}",
"function main() {\n // Select the current account\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n Logger.log(\"Account: \" + accountName);\n\n // Init Spreadsheet\n var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1mPtQWBuk-Kk15K-OlqRA96HvR-lAX6mcm8TkgAZCqwU/edit?usp=sharing');\n var sheet = spreadsheet.getSheets()[0];\n\n var callString = \"SELECT CampaignName, AdGroupName, Date, Month, CallStartTime, CallDuration, CallStatus, CallTrackingDisplayLocation, CallerCountryCallingCode FROM CALL_METRICS_CALL_DETAILS_REPORT DURING THIS_MONTH\";\n\n\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\");\n\n var campaignIterator = campaignSelector.get();\n\n while(campaignIterator.hasNext()) {\n // Iterate over the number of campaigns\n var campaign = campaignIterator.next();\n // Get the campaign name\n var campaignName = campaign.getName();\n Logger.log(\"Campaign Name: \" + campaignName);\n\n // Init report with query string\n var report = AdWordsApp.report(callString);\n var iter = report.rows();\n // Print Report to spreadsheet with results data\n while(iter.hasNext()) {\n var reportRow = iter.next();\n sheet.appendRow([\n reportRow[\"CampaignName\"],\n reportRow[\"AdGroupName\"],\n reportRow[\"Date\"],\n reportRow[\"CallStartTime\"],\n reportRow[\"CallDuration\"],\n reportRow[\"CallStatus\"],\n reportRow[\"CallTrackingDisplayLocation\"],\n reportRow[\"CallerCountryCallingCode\"]\n ]);\n }\n }\n}",
"function main() {\n // select the current account\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n\n // spreadsheet init\n // add spreadsheet link here\n var spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1tVgxuqdEaVoaSGMbu-8q2d9Ck8taShzGMzkus9JMzqk/edit?usp=sharing';\n // Log spreadsheet url\n Logger.log('Using spreadsheet - %s.', spreadsheet_url);\n // open ss\n var spreadsheet = SpreadsheetApp.openByUrl(spreadsheet_url);\n // init sheet - update for the sheet number\n var sheet = spreadsheet.getSheets()[0];\n \n var emailForNotify = sheet.getRange(2,5);\n // Email function to pass string and send through to email provided\n function notify(string) {\n MailApp.sendEmail(emailForNotify, accountName, string);\n };\n\n // Grab Spreadsheet Data from the google spreadsheet\n var account = sheet.getRange(2,2);\n // Spreadsheet variable to apply for tracking (Conversion amount you want to be above)\n var conversionVariable = sheet.getRange(2,3);\n\n // Selector for the current enabled campaign\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"Status = ENABLED\");\n // Get all the enabled campaigns\n var campaignIterator = campaignSelector.get();\n // Loop over the enabled campaigns - log out the data needed - add stats to the spreadsheet\n while(campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n\n Logger.log(\"Campaign Name: \" + campaign.getName());\n // Get the bidding strategy to make sure the campaign is Max Clicks (\"TARGET_SPEND\")\n var currentBiddingStrategy = campaign.getBiddingStrategyType();\n Logger.log(\"Current Bidding Strategy: \" + currentBiddingStrategy);\n // Get the current conversion and conversion rate stats\n var currentStats = campaign.getStatsFor(\"THIS_MONTH\");\n var currentClicks = currentStats.getClicks();\n var currentCost = currentStats.getCost();\n var currentConversions = currentStats.getConversions();\n var currentConversionRate = currentStats.getConversionRate();\n\n // Get the range to input the stats data into the spreadsheet (array, range, setvalues)\n var statsArray = [[currentClicks, currentCost, currentConversions, currentConversionRate]];\n var statsRange = sheet.getRange('B4:E4');\n statsRange.setValues(statsArray);\n }\n\n // Grab the cells from the spreadsheet to input tracking information\n var conversionCell = sheet.getRange(6,3);\n var conversionRateCell = sheet.getRange(6,4);\n\n if(currentConversions <= 0 && currentBiddingStrategy === \"TARGET_SPEND\") {\n Logger.log(\"Campaign currently has no conversions\");\n // notify(\"Campaign currently has no conversions\");\n }\n else if(currentConversions > conversionVariable) {\n Logger.log(\"Campaign is tracking above Conversion Variable\");\n // notify(\"Campaign conversions currently tracking above the Conversion Variable\");\n conversionCell.setValues(\"GOOD\");\n }\n else if(currentConversions < conversionVariable) {\n Logger.log(\"Campaign conversions is not tracking above Conversion Variable\");\n // notify(\"Campaign conversions currently tracking below Conversion Variable for this account\");\n conversionCell.setValues(\"BAD\");\n }\n else {\n Logger.log(\"An error has occured, please look into this account\");\n // notify(\"Campaign conversions currently has an error with Conversion Tracking\");\n }\n\n if(currentConversionRate < conversionRateVariable) {\n Logger.log(\"Conversion Rate is below conversion rate variable\");\n // notify(\"Campaign conversion rate currently tracking below conversion rate tracking variable\");\n conversionRateCell.setValues(\"BAD\");\n }\n else if(currentConversionRate > conversionRateVariable) {\n Logger.log(\"Conversion Rate is tracking above conversion rate variable\");\n // notify(\"Campaign conversion rate currently tracking above conversion rate tracking variable\");\n conversionRateCell.setValues(\"GOOD\");\n }\n else {\n Logger.log(\"Campaign conversion rate has thrown an error - please look into this account\");\n // notify(\"Campaign conversion rate currently has thrown an error on this account - please look into this.\")\n }\n}",
"function checkCtrPerformance() {\n\n\n\t/// select accounts which fullfill your criteria(conditions)\n var accountIterator = MccApp.accounts()\n .withCondition(\"LabelNames CONTAINS 'check_performance'\")\n .withCondition('Ctr < 0.05')\n .forDateRange(\"LAST_7_DAYS\")\n .get();\n \n \n\t// iterate over selected accounts\n while(accountIterator.hasNext()){\n var account = accountIterator.next();\n var stats = account.getStatsFor('LAST_7_DAYS');\n var accountName = account.getName();\n \n\t//create a labelIterator with ONLY asanaBoard E-Mails in it\n var lblItr= account.labels()\n .withCondition(\"Name CONTAINS 'asana'\")\n .get();\n \n while(lblItr.hasNext()){\n var accountLabel = lblItr.next();\n var asanaBoardMail = accountLabel.getName();\n \n \t//create E-Mail Text\n \tvar CtrMail = \"\\n Account: \" + accountName\n \t\t\t+ \"\\n Klicks: \" + stats.getClicks().toFixed(0) \n \t\t\t+ \"\\n CTR: \" + stats.getCtr()\n \t\t\t+ \"\\n Label: \" + asanaBoardMail;\n \n \n //send E-Mail to Asana\n //uncomment when testing in Preview and use Loggers, it will also send E-Mails in Preview Mode\n \n /*\n MailApp.sendEmail({\n to: asanaBoardMail, \n subject: 'CTR verbessern, liegt tiefer als 5%', \n body: 'Der CTR dieses Accounts ist ungenügend. Schau dir folgende Zahlen an und versuche den CTR zu steigern: ' + CtrMail\n \t});\n */\n \n \n /* \n * Logger checks - Use these to test when in Preview Mode\n */\t \n Logger.log(CtrMail);\n Logger.log(\"The Account is \" + accountName);\n Logger.log(\"E-Mail was sent to \" + asanaBoardMail);\n \n }\n }\n}",
"function main() {\n // Set up SS\n // Init Spreadsheet\n // Create cell for ordered impressions\n // Grab that data and save it - Make sure the url is for the correct SS\n var spreadsheet = SpreadsheetApp.openByUrl(\"https://docs.google.com/spreadsheets/d/1psxrVyBP8s90FCoxVnLO-shkrCoKzTRXzjb0c-0377Q/edit?usp=sharing\");\n var sheet = spreadsheet.getSheets()[0]; // Set correct sheet number in budget spreadsheet\n\n // Init globals (ordered impressions, budget adjustment value) *** Set correct ranges for budget script\n var emailForNotify = sheet.getRange(2,2).getValue();\n var orderedImpressions = sheet.getRange(2,1).getValue();\n Logger.log(\"Ordered Impressions from SS: \" + orderedImpressions);\n var setTo = .50;\n\n // Select Account with condition enabled\n var currentAccount = AdWordsApp.currentAccount();\n var accountName = currentAccount.getName();\n Logger.log(\"Processing on the following account: \" + accountName);\n\n // This function takes a campaign budget - logs the current budget and sets the new amount of the given budget parameter\n\n function adjustBudget(budgetToAdjust) {\n var currentCampaigns = AdWordsApp.campaigns().get();\n if(currentCampaigns.hasNext()) {\n var currentBudgetToAdjust = campaign.getBudget();\n Logger.log(\"current budget: \" + currentBudgetToAdjust);\n var getAllBudgetToAdjust = currentBudgetToAdjust.campaigns().get();\n \n while (getAllBudgetToAdjust.hasNext()) {\n var allCampaignsCurrentBudgets = getAllBudgetToAdjust.next();\n allCampaignsCurrentBudgets.getBudget().setAmount(budgetToAdjust);\n Logger.log(allCampaignsCurrentBudgets.getName());\n }\n }\n }\n\n // Select Campaign with condition enabled\n // With condition impressions > 0 to make sure it is running\n var campaignSelector = AdWordsApp\n .campaigns()\n .withCondition(\"CampaignStatus = ENABLED\")\n .withCondition(\"Impressions > 0\")\n .forDateRange(\"LAST_7_DAYS\");\n\n var campaignIterator = campaignSelector.get();\n\n while (campaignIterator.hasNext()) {\n var campaign = campaignIterator.next();\n var campaignName = campaign.getName();\n var currentDailyBudget = campaign.getBudget().getAmount();\n Logger.log(\"current daily budget: \" + currentDailyBudget);\n var stats = campaign.getStatsFor(\"ALL_TIME\");\n // Get the impression stats for the running campaign - ALL_TIME\n var impressions = stats.getImpressions();\n \tLogger.log(\"Impressions: \" + impressions);\n // Write a conditional check to set the daily budget to .50 if over-delivering\n if(impressions > orderedImpressions) {\n Logger.log(\"Campaign is over-delivering - budget set to .50\");\n adjustBudget(setTo);\n notify(\"The campaign is over-delivering and the budget has been adjusted down to .50 - please check into this campaign.\")\n } else {\n Logger.log(\"Campaign is pacing below ordered impressions\"); \n }\n }\n\n // Email function to pass string and send through to email provided\n function notify(string) {\n // Construct email template for notifications\n // Must have to, subject, htmlBody\n var emailTemplate = {\n to: emailForNotify,\n subject: accountName,\n htmlBody: \"<h1>Comporium Media Services Automation Scripts</h1>\" + \"<br>\" + \"<p>This account has encountered an issue</p>\" + accountName +\n \"<br>\" + \"<p>The issue is with this campaign: </p>\" + campaignName + \"<br>\" + \"<p>This is what is wrong - </p>\" + \"<br>\"\n + string + \"<br>\" +\"<p>If something is incorrect with this notification please reply to this email. Thanks!</p>\"\n }\n MailApp.sendEmail(emailTemplate);\n }\n\n}",
"function bulkCreateAdvertisers() {\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(ADV_SHEET);\n\n // This represents ALL the data\n var range = sheet.getDataRange();\n var values = range.getValues();\n\n const profile_id = _fetchProfileId();\n\n // build request body resources\n for (var i = 1; i < values.length; ++i) {\n var currentRow = i + 1;\n var currentAdvertiser = values[i];\n var adv_name = currentAdvertiser[0];\n var adv_subaccount_id = currentAdvertiser[1];\n var adv_group_id = currentAdvertiser[2]; // optional field\n\n var advertiserResource = {\n \"kind\": \"dfareporting#advertiser\",\n \"name\": adv_name\n };\n\n // advertiser group is optional\n if (adv_group_id !== \"\") {\n advertiserResource.advertiserGroupId = adv_group_id;\n }\n\n // subaccount is optional\n if (adv_subaccount_id !== \"\") {\n advertiserResource.subaccountId = adv_subaccount_id;\n }\n\n var newAdvertiser = DoubleClickCampaigns.Advertisers\n .insert(advertiserResource,\n profile_id);\n sheet.getRange(\"D\" + currentRow)\n .setValue(newAdvertiser.id).setBackground(AUTO_POP_CELL_COLOR);\n }\n}",
"function main() {\n // Get adverts from results page\n var ads = extractAds(); // HTMLCollection\n /**/console.log(ads.length + \" ads found:\\n\\n\");\n // Extract advert text, remove stop words and stem words\n var ads_proc = processAds(ads);\n /**/for(ad of ads_proc)console.log(ad);console.log(\"---------------\\n\");\n var [row_probs, col_probs] = getProbs();\n \n // Add a border to the adverts according to their classifications\n highlightAds(ads, ads_proc, row_probs, col_probs);\n}",
"function main() {\n // After first run this can throw an error as the labels already exists, but we can ignore.\n for( var n = LABELS_NAME.length-1; n >= 0; n-- ) {\n try {\n MccApp.createAccountLabel( LABELS_NAME[n] );\n } catch (e) {} // Nothing to do about this error\n } \n \n // Get the list of accounts not yet processed \n // Maximum 50 due to the parallel execution limit\n var notProcessedAccounts = [];\n var parallelExecutionLimit = 50;\n var accountIterator = MccApp.accounts() \n .withCondition(\"LabelNames DOES_NOT_CONTAIN '\" + LABELS_NAME[0] + \"'\")\n .get();\n \n var i = 0;\n while (accountIterator.hasNext() && i < parallelExecutionLimit) {\n var account = accountIterator.next();\n notProcessedAccounts.push( account.getCustomerId() );\n i++;\n }\n \n // If there are no accounts to process, we can clean up\n if( notProcessedAccounts.length == 0) {\n /**\n * This section unlabels all accounts \n * And deletes the label from the MCC\n * Uncomment this section once all the accounts\n * are labeled and run one last time the script\n **/\n /*\n for( var n = LABELS_NAME.length-1; n >= 0; n-- ) {\n var accountIterator = MccApp.accounts()\n .withCondition(\"LabelNames CONTAINS '\" + LABELS_NAME[n] + \"'\")\n .get();\n \n while (accountIterator.hasNext()) {\n var account = accountIterator.next();\n account.removeLabel(LABELS_NAME[n]);\n }\n \n // We delete the label from the MCC\n var labelIterator = MccApp.accountLabels()\n .withCondition(\"Name ='\" + LABELS_NAME[n] + \"'\")\n .get();\n\n while (labelIterator.hasNext()) {\n var label = labelIterator.next();\n label.remove();\n }\n }\n */\n // Send an email to STATUS_EMAIL_RECEIVER with STATUS_EMAIL_CC in cc\n // to indicate the keyword deletion is over\n var body = 'Hello there,'\n +'\\n\\nAll the accounts have been processed and all the necessary keywords have been deleted.\\n\\n';\n + '\\n\\nFor additionnal information, check the logs in the MCC.';\n MailApp.sendEmail({to: STATUS_EMAIL_RECEIVER,\n cc: STATUS_EMAIL_CC,\n subject: 'MCC Keyword deletion status report',\n body: body,\n noReply: true});\n Logger.log(\"All the accounts have been processed and all the necessary keywords have been deleted.\");\n\n } else {\n \n // Otherwise, we can process the accounts\n Logger.log('Starting parallel processing on ' + i + ' accounts');\n Logger.log('Accounts in this batch: ' + notProcessedAccounts);\n var accountSelector = MccApp.accounts().withIds(notProcessedAccounts);\n accountSelector.executeInParallel('accountKeywordDeletion', 'batchFinished');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all actions that are pushed after marked positions (using `setMark()`) | clearFromMark() {
if (mark !== null) {
stack.splice(mark);
mark = null;
}
} | [
"function undoLastMark() {\r\n\tnewPaddockCoords.pop();\r\n\tmarkersArray.getAt(markersArray.getLength() - 1).setMap(null);\r\n\tmarkersArray.pop();\r\n}",
"function clearNextMovesMarkers() {\n mapSquares(square => square.canBeNextMove = false);\n}",
"unMarkAll() {\r\n\r\n for ( var i = 0; i < this.marked.length; i++) {\r\n this.marked[i].originalColor();\r\n }\r\n\r\n this.marked = [];\r\n }",
"undo() {\n // ˅\n if (this.pastCommands.length !== 0) {\n this.pastCommands.pop();\n }\n // ˄\n }",
"function eliminateMark(ev, ignore, hard) {\n var next = nextMark(ignore);\n if (next.m && next.m.e === ev) {\n /* The purpose of keeping this mark is so that if we want to back\n * out, our mark has something to abut to. That's pointless if the\n * next mark is at the same time. This avoids clutter particularly\n * when we created the other mark in the first place. */\n var follow = marks[next.i+1];\n if (follow && follow.t === next.m.t)\n marks.splice(next.i, 1);\n else\n next.m.e = \"x\" + ev;\n }\n }",
"function unmarker() {\n unmark = 1;\n\t\tmark = 0;\n }",
"function unmarkMark(next) {\n var moveASpan = function (i) {\n return document.querySelector('#' + movesId + i + '> a');\n };\n\n removeClass(document.querySelector('#' + movesId + \" a.yellow\"), 'yellow');\n addClass(moveASpan(next), 'yellow');\n }",
"function clearMarks() {\n var codeMirror = getCodeMirror();\n\n // Clear any text we've marked\n clearLineHighlight();\n\n // Get rid of multiple selections in the editor\n var doc = codeMirror.getDoc();\n var pos = doc.getCursor(\"start\");\n codeMirror.setCursor(pos);\n }",
"function unmarkMark(next) {\n var moveASpan = function(i) {\n return $('#' + movesId + i + \"> a\");\n };\n\n $(\"div#\" + movesId + \" a.yellow\").removeClass('yellow');\n moveASpan(next).addClass('yellow');\n }",
"removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }",
"closeMark(mark) {\n this.marks = mark.removeFromSet(this.marks)\n }",
"function removeMarkers()\n {\n var next;\n while (markerHead)\n {\n next = markerHead[marker].prev;\n delete markerHead[marker];\n markerHead = next;\n }\n }",
"prune() {\n if(this._pointer === undefined) {\n // clear the stack\n while(this._stack.length) {\n this._stack.pop();\n }\n } else {\n // remove all events above the pointer\n while(this._pointer < (this._stack.length-1)) {\n this._stack.pop();\n }\n }\n }",
"function removeLastMarker() {\n myMarkers.pop();\n}",
"clearToLastMarker() {\n const markerIdx = this.entries.indexOf(MARKER);\n if (markerIdx >= 0) {\n this.entries.splice(0, markerIdx + 1);\n }\n else {\n this.entries.length = 0;\n }\n }",
"function clearAction() {\n debug('clearAction')\n last.diff = null\n last.domNode = null\n }",
"forgetState() {\n if (this.mPreservedPos.length) {\n this.mPreservedPos.pop();\n }\n }",
"function removeMarkedStations(){\n for(let i = 0; i < markedStations.length; i++){\n let stationID = markedStations[i]._popup._content.lastChild.id;\n let button = markedStations[i]._popup._content.lastChild;\n const station = stationsData.find(x => x.id === stationID);\n removeStation(station, markedStations[i], button);\n }\n markedStations = [];\n}",
"function undomaker() {\n // clear board\n tool.clearRect(0, 0, canvas.width, canvas.height);\n // pop last point\n // undoStack.pop();\n while (undoStack.length > 0) {\n let curObj = undoStack[undoStack.length - 1];\n if (curObj.desc == \"md\") {\n redoStack.push(undoStack.pop());\n break;\n } else if (curObj.desc == \"mm\") {\n redoStack.push(undoStack.pop());\n }\n }\n // redraw\n redraw();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the events with type: empty | updateEmptyEvents() {
if (this.isEmpty()) {
this.updateEventsContainer('empty');
}
} | [
"function clearEvents() {\n\t\tevents = [];\n\t\teventsById = {};\n\t\tduration = undefined;\n\t}",
"function clearEvents(plot, type){\n\n\tfor (var i in this.events){\n\t\tvar ev = this.events[i];\n\t\tif (ev.plot == plot && ev.event == type){\n\t\t\tdelete this.events[i];\n\t\t}\n\t}\n\n\tthis.stateChange();\n}",
"function clear() {\r\n __onfireEvents = {};\r\n }",
"function clearEvents() {\n for (var m = 0; m < timeBlocks.length; m++) {\n timeBlocks[m].eventName = \"\";\n }\n}",
"function reset() {\r\n for (var eventName in unboundEvents) {\r\n EventBus._events[eventName] = unboundEvents[eventName];\r\n }\r\n }",
"clear(type = '') {\r\n if (type) {\r\n delete (this._events[type]);\r\n }\r\n else {\r\n this._events = {};\r\n }\r\n return this;\r\n }",
"clear() {\n this._events = [];\n this._eventTimes = [];\n }",
"clearAllEvents() {\n this.apiEvents.splice(0, this.apiEvents.length);\n }",
"clearAllEvents() {\n\t\tthis._events.clear();\n\t}",
"function eventsReset() {\n for (var i = 0; i < gameEventArray.length; i++) {\n if (gameEventArray[i].persistent === false) {\n gameEventArray[i].state = false;\n }\n gameEventArray[i].changed = false;\n }\n}",
"clear() {\n this._eventsStash = [];\n }",
"clearListeners() {\n const vals = Object.values(EVENT_TYPES);\n vals.forEach((val) => {\n this.callbacks[val] = [];\n });\n }",
"updateFullEvents() {\n if (this.isFull()) {\n this.updateEventsContainer('full');\n }\n }",
"resetStoryEvents() {\n\t\tthis.eventFlags = {};\n\t\tthis.eventDict = {};\n\t\tfor(const eventId in this.eventCount) {\n\t\t\tthis.eventCount[eventId] = 0;\n\t\t}\n\t}",
"function removeAllEvents() {\n instance.removeEvent();\n}",
"clear() {\n debug('Clearing all previously stashed events.');\n this._eventsStash = [];\n }",
"function flushEvents() {\n if (_eventBatch.length && _isEventCollectorOn) {\n uploadEventBatch(_eventBatch);\n _eventBatch.length = 0;\n }\n}",
"function resetEventQueue(){\n\tlocal_events = get_local_events();\n\tif(local_events !== null){\n\t\tlocal_events.eventQueue = [];\n\t\tputinStorage( 'localevents', JSON.stringify(local_events) );\n\t}else{\n\t\tconsole.log(\"Local events not found!\");\n\t}\n}",
"function clearSet(event) {\n if(event) {\n delete setEvents[event];\n } else {\n setEvents = {};\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns HTML string for eBay results | function getEbayHTML(results) {
var items = results.searchResult.item;
var html = "<tr class='ebayResults'><td colspan='5'><h3>eBay results</h3><table><tbody>";
$(items).each(function(i){
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var price = parseFloat(items[i].sellingStatus.convertedCurrentPrice);
if (null != title && null != viewitem) {
html += ("<tr><td>" + "<img src='" + pic + "' border='0'>" + "</td>" +
"<td><a href='" + viewitem + "' target='_blank'>" + title + "</a></td><td>£" + price.toFixed(2) + "</td></tr>");
}
});
html += "</tbody></table></td></tr>";
return html;
} | [
"function showWebResult(item)\n {\n var p = document.createElement('p');\n var a = document.createElement('a');\n a.href = item.Url;\n $(a).append(item.Title);\n $(p).append(item.Description);\n // Append the anchor tag and paragraph with the description to the results div.\n $('#results').append(a, p);\n }",
"function solrGetPlainResultHtml(result,highlight,metatags,index) {\nvar html=\"\";\nhtml+=\"<li>\";\nif (metatags != null && metatags != undefined && metatags.resultthumb != \"\" && metatags.resultthumb != null) {\nhtml+=\" <div class='thumb'>\";\nhtml+=\" <img class='photo' width='138' height='78' border='0' alt='thumbnail' src='\"+metatags.resultthumb+\"'>\";\nhtml+=\" </div>\";\n}\nhtml+=\"\t<div class='title'><a href='\"+result.url+\"'>\"+result.htsearch+\"</a>\"+getSearchWeight(result.score,index)+\"</div>\";\nhtml+=\"\t<div class='summary'>\";\nhtml+=\" <span class='date'>\"+solrGetDate(result)+\"</span>\";\nhtml+=\" \" + highlight.noindexcontent + \" ...\";\nhtml+=\" </div>\";\nhtml+=\"</li>\";\nreturn html;\n}",
"function generateHtml(payload, html) {\r\n // Check if the user has select artist or album\r\n payload = payload.artists || payload.albums;\r\n // Check if there's a next url\r\n if (payload.next) {\r\n nextUrl = payload.next.replace(\r\n \"https://api.spotify.com/v1/search\",\r\n baseUrl\r\n );\r\n } else {\r\n moreBtn.style.visibility = \"hidden\";\r\n }\r\n\r\n // Check if there's a result\r\n var items = payload.items;\r\n if (items.length === 0) {\r\n html = `<div class=\"no-result\">No result</div>`;\r\n } else {\r\n // Loop through each item\r\n for (var i = 0; i < items.length; i++) {\r\n if (\r\n items[i].name &&\r\n items[i].external_urls.spotify &&\r\n items[i].images\r\n ) {\r\n var name = items[i].name; // returns name of artist/album as string\r\n var images = items[i].images;\r\n var image;\r\n if (images.length > 0) {\r\n for (var j = 0; j < images.length; j++) {\r\n if (images[j][\"url\"]) {\r\n image = images[j][\"url\"];\r\n break;\r\n }\r\n }\r\n } else {\r\n image = \"/assets/spotify-logo.png\";\r\n }\r\n var extUrl = items[i].external_urls.spotify; // returns an object with external_urls\r\n if (!extUrl) {\r\n extUrl = \"https://spotify.com/404\";\r\n }\r\n }\r\n\r\n html += `<a href=\"${extUrl}\">\r\n <div class=\"item\">\r\n <div class=\"image-container\">\r\n <img src=\"${image}\" alt=\"${name}\" />\r\n </div>\r\n <div class=\"name\">\r\n <p>${name}</p>\r\n </div>\r\n </div>\r\n </a>`;\r\n }\r\n }\r\n\r\n return html;\r\n }",
"function renderResult(result) {\n\n if (result.summary == \"inactive\") {\n return `<div class=\"domain\">${result.domain}<span class=\"buyButton\"><a href=\"https://www.namecheap.com/domains/registration/results.aspx?domain=${result.domain}\" target=\"_blank\">Buy it!</a></span></div>`;\n } else if (result.summary == \"active\") {\n return `<div class=\"domainUnavail\"><a class=\"domainLink\" href=\"http://www.${result.domain}\" target=\"_blank\">${result.domain}</a><span class=\"sold\">Unavailable</span></div>`;\n } else {\n return `<div class=\"domainUnavail\"><a class=\"domainLink\" href=\"http://www.${result.domain}\" target=\"_blank\">${result.domain}</a><span class=\"sold\">Unavailable</span></div>`;\n }\n}",
"function getBooksHtml() {\n var url = new URL(\"http://www.gutenberg.org/cache/epub/feeds/today.rss\")\n var items = readRssFeed(url)\n\n var str = \"<ul>\"\n\n // Nashorn's string interpolation and heredoc\n // support is very handy in generating text content\n // that is filled with elements from runtime objects.\n // We insert title and link in <li> elements here.\n for each (i in items) {\n str += <<EOF\n<li>\n <a href=\"${i.link}\">${i.title}</a>\n</li>\nEOF\n }\n str += \"</ul>\"\n return str\n}",
"function filterPiratebayResults(rawText)\r\n\t{\r\n\t\tvar cleanData=\"\";\r\n\t\trawText = rawText.replace(/\\n|\\r/g, \"\");\r\n\t\trawText = rawText.replace(/.*?<table id=\\\"searchResult\\\">/,'<table id=\"searchResult\">');\r\n\t\trawText = rawText.replace(/<\\/table>.*/,'</table>');\r\n\t\trawText = rawText.replace(/href=\\\"\\//g,'href=\\\"http://thepiratebay.org/');\r\n\t\tcleanData = rawText.toString();\r\n\t\tGM_addStyle('table#searchResult {font-size:80%; width:98%;} '); \r\n\t\tGM_addStyle('table#searchResult > tbody > tr {background-color:#FFFFFF;} '); \r\n\t\tGM_addStyle('table#searchResult > tbody > tr > td {border-bottom:1px solid PaleGoldenrod;} '); \r\n\t\tGM_addStyle('table#searchResult > thead > tr.header {background:paleGoldenRod;font-size:12px;color:#805B4D;font-weight:normal;line-height:131%;} '); \r\n\t\tGM_addStyle('table#searchResult > thead > tr.header a:link {color:#805B4D;}'); \r\n\t\tGM_addStyle('table#searchResult > thead > tr.header a:visited {color:#805B4D;}'); \r\n\t\treturn cleanData;\r\n\t}",
"function resultString(){\n\t\tvar start = (current*pgSize)+1;\n\t\tvar end = (current+1)*pgSize;\n\t\tif(end > total){\n\t\t\tend = total;\n\t\t}\n\t\treturn `<p class=\"results ${divName}\">(Showing results ${start} through ${end} of ${total})</p>`;\n\t}",
"function generateResultHtml(result)\n\t{\n\n\t\tlet Html = \"\"\n\t\tresult.forEach(function(element) {\n\t\t\tlet difficulty = ''\n\t\t\tswitch(element.LevelOfDifficulty){\n\t\t\t\tcase 1:\n\t\t\t\t\tdifficulty = 'Green'\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdifficulty = 'Red'\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tdifficulty = 'Black'\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tHtml += `<div>\n <p>${element.Destination1} To ${element.Destination2}</p>\n <p>Length: ${element.Lenght/1000} Km</p>\n <p>Difficulty: ${difficulty}</p>\n <a href=\"${element.GPXLink}\">GpxLink</a>\n <hr>\n </div>`\n\t\t})\n\n\t\treturn Html\n\t}",
"function returnHtml(item){\n var output = `<div class=\"newsitem\"><div class=\"itemleft\"><div class=\"itemimg\"><img src=\"`+item.thumbnail+`\"></div></div>`\n + `<div class=\"itemright\"><div class=\"itemtitle\">`+item.title+`</div>`\n +`<div class=\"itemabstract\">`+item.abstract+`</div>`\n +`<div class=\"itemdate\">`+item.published_date+`</div>`\n +`<div class=\"itemlink\"><a target=\"_blank\" href=\"`+item.url+`\">Open in new tab</a></div></div></div>`\n ;\n return output;\n }",
"function buildWebPage(result){\n document.getElementById('article').innerHTML = result.description;\n document.getElementById('article-title').innerHTML = result.title;\n}",
"function renderItemsHtml(){\n\tlet itemsHtml =\tgetItems(generateAndDisplayArrayOfItems);\n}",
"function renderBreaches(breach, index){\n return `<div class =\"breach-results\">\n <h1>Company: ${breach.Name}</h1>\n <h2>Domain: ${breach.Domain}</h2>\n <h3>Breach Description: ${breach.Description}</h3>\n </div>`;}",
"function showResults(results){\n var result = \"\";\n // got through each array and get the value of the Title only\n $.each(results, function(index,value){\n result += '<p>' + value.Title + '</p>';\n });\n // append the information into search-results div.\n $('#search-results').append(result);\n }",
"function outPutHtml(bees){\n\t\tlet beeRows = \"\"\n\t\tfor (let i = 0; i < bees.length; i++) {\t\t\n\t\t\tbeeRows +=`<tr><td>${bees[i].type}</td><td>${bees[i].health}</td><td>${bees[i].status}</td><tr>`\n\t\t}\n\t\tdocument.getElementById(\"js-bee-rows\").innerHTML = beeRows\n\t}",
"function ebayAPI(searchTerm) {\n var key = \"StephenC-SecretSa-PRD-6132041a0-943144c9\";\n var url = \"https://svcs.ebay.com/services/search/FindingService/v1\";\n \n $.ajax({\n url: url, \n method: \"GET\",\n dataType: \"jsonp\",\n data: {\n \"OPERATION-NAME\": \"findItemsByKeywords\",\n \"SERVICE-VERSION\": \"1.0.0\",\n \"SECURITY-APPNAME\": \"StephenC-SecretSa-PRD-6132041a0-943144c9\",\n \"RESPONSE-DATA-FORMAT\": \"JSON\",\n \"paginationInput.entriesPerPage\": \"10\",\n keywords: searchTerm\n }\n \n }).done(function(result) {\n console.log(result);\n\n var short = result.findItemsByKeywordsResponse[0].searchResult[0];\n try{\n short.item[0];\n }\n catch(err){\n if(err) { \n console.log(err)\n $(\"#productDisplay\").html(\"<h3>No goods found</h3>\");\n return 1;\n }\n } \n for (var i = 0; i < 10; i++) {\n var newImg = $(\"<img>\");\n newImg.attr(\"src\", short.item[i].galleryURL[0]);\n var Paragraph = $(\"<p class='truncate'>\");\n Paragraph.text(short.item[i].title[0]);\n var Paragraph2 = $(\"<p>\");\n Paragraph2.text(\"$\" + short.item[i].sellingStatus[0].currentPrice[0].__value__);\n var caruItem = $(\"<a id=img\" + i + \">\");\n caruItem.attr(\"class\", 'carousel-item center-align');\n caruItem.attr(\"target\", \"_blank\");\n caruItem.attr(\"href\", short.item[i].viewItemURL[0]);\n caruItem.append(newImg);\n caruItem.append(Paragraph);\n caruItem.append(Paragraph2);\n $(\"#productDisplay\").append(caruItem);\n $(\"#img\" + i).hammer();\n $(\"#img\" + i).on(\"tap\", function() {\n window.open($(this).attr(\"href\"), '_blank');\n });\n }\n $('.carousel').carousel();\n });\n }",
"function renderItemsHtml() {\n let itemsHtml = getItems(generateAndDisplayArrayOfItems);\n}",
"function displayWebsite() {\n\t$('.results').append(`<a target=\"_blank\" href=\"${website}\"class=\"website\">${website}</a>`);\n}",
"function openNewPageWithRawResults(result) {\n alert(result)\n }",
"function showResultsFromApi(result) {\n\n //create an empty variable to store one LI for each one the results\n let buildTheHtmlOutput = \"\";\n\n $.each(result, function (resultKey, resultValue) {\n //create and populate one LI for each of the results ( \"+=\" means concatenate to the previous one)\n buildTheHtmlOutput += '<article role=\"listbox\" class=\"one-half\">';\n buildTheHtmlOutput += '<h3>' + resultValue.show.name + '</h3>';\n\n if (resultValue.show.rating.average == null) {\n buildTheHtmlOutput += '<h4>' + 'Ratings not found' + '</h4>';\n } else {\n buildTheHtmlOutput += '<h4>' + 'Rating ' + resultValue.show.rating.average + '</h4>';\n }\n\n if (resultValue.show.image == null) {\n buildTheHtmlOutput += '<img src=\"no-img.png\" alt=\"Television show poster\">';\n } else {\n buildTheHtmlOutput += '<img src=\"' + resultValue.show.image.original + '\" alt=\"Television show poster\">';\n }\n\n buildTheHtmlOutput += '<p>' + resultValue.show.summary + '</p>';\n buildTheHtmlOutput += '</article>';\n });\n //use the HTML output to show it in the index.html\n $(\".result-section\").html(buildTheHtmlOutput);\n $('.result-section').show();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initiate account settings modal | function initAccountSettingsModal() {
const template = require('./user-accounts-modal-settings.html');
$uibModal
.open({
template,
windowTopClass: 'uib-modal',
ariaLabelledBy: 'dialog_label',
controllerAs: 'modalCtrl',
controller: function() {
const lockoutMethod = mapLockoutMethod(
$scope.accountSettings.AccountLockoutDuration);
this.settings = {};
this.settings.maxLogin =
$scope.accountSettings.AccountLockoutThreshold;
this.settings.lockoutMethod = lockoutMethod;
this.settings.timeoutDuration = !lockoutMethod ?
null :
$scope.accountSettings.AccountLockoutDuration;
}
})
.result
.then((form) => {
if (form.$valid) {
const lockoutDuration = form.lockoutMethod.$modelValue ?
form.timeoutDuration.$modelValue :
0;
const lockoutThreshold = form.maxLogin.$modelValue;
updateAccountSettings(lockoutDuration, lockoutThreshold);
}
})
.catch(
() => {
// do nothing
})
} | [
"function initSettings() {\n\n\tvar settingsButton = document.getElementById('settings-button');\n\tvar settingsDialog = document.getElementById('settings-dialog');\n\n\tsettingsButton.addEventListener('click', function() {\n\t\topenDialog(settingsDialog, settingsButton);\n\t});\n\n}",
"function showSettings(){\r\n\t\tshowModal('settingsScreen');\r\n\t\tesc = closeSettings;\r\n\t}",
"function showConfigUser() {\n\n\tdocument.getElementById('sel_interface_font_size').value = v_font_size;\n\tdocument.getElementById('sel_editor_theme').value = v_theme;\n\n\tdocument.getElementById('txt_confirm_new_pwd').value = '';\n\tdocument.getElementById('txt_new_pwd').value = '';\n\n\tdocument.getElementById('sel_csv_encoding').value = v_csv_encoding;\n\tdocument.getElementById('txt_csv_delimiter').value = v_csv_delimiter;\n\n\t$('#modal_config').modal({ backdrop: 'static', keyboard: false });\n\n}",
"function showButtonClicked(args) {\n\n Windows.UI.ApplicationSettings.AccountsSettingsPane.show();\n }",
"function openSettingsEditModal() {\n accountSettingsEditModal.style.display = 'block';\n sidebarSettings.style.display = 'none'\n}",
"function settingsModal(fname, sname, email) {\n $('.modal-body #settingsFName').val(fname);\n $('.modal-body #settingsSName').val(sname);\n $('.modal-body #settingsEmail').val(email);\n $('#settingsModal').modal('show');\n\n}",
"function openSettings(){\n var settingsModal = document.getElementById('settingsModal');\n var gameinstall = document.getElementById('settings-installloc');\n var settingsPreRelease = document.getElementById('settingsPreRelease');\n if(settingsModal.classList.contains('fadedout')){\n settingsModal.classList.remove('fadedout');\n }\n settingsPreRelease.checked = config.preRelease;\n settingsModal.style.display = \"block\";\n gameinstall.textContent = config.gameInstallLoc;\n}",
"function onOpenSettings() {\n populateSettingsInputs(settings)\n // Show\n showHideSettings(true)\n}",
"function openUserPrefsModal() {\n var modalTitle = $('.modal-title');\n modalTitle.text('Enter Your Preferences');\n\n $('#myModal').modal('show');\n}",
"function InitUserSettings() {\n UserSettingsCtrl.ePage.Masters.UserSetting = {};\n UserSettingsCtrl.ePage.Masters.UserSetting.Cancel = Cancel;\n UserSettingsCtrl.ePage.Masters.UserSetting.Save = Save;\n UserSettingsCtrl.ePage.Masters.UserSetting.Edit = Edit;\n UserSettingsCtrl.ePage.Masters.UserSetting.DeleteConfirmation = DeleteConfirmation;\n UserSettingsCtrl.ePage.Masters.UserSetting.OnUserSettingsClick = OnUserSettingsClick;\n UserSettingsCtrl.ePage.Masters.UserSetting.OpenJsonModal = OpenJsonModal;\n UserSettingsCtrl.ePage.Masters.UserSetting.AddNew = AddNew;\n\n UserSettingsCtrl.ePage.Masters.UserSetting.SaveBtnText = \"OK\";\n UserSettingsCtrl.ePage.Masters.UserSetting.IsDisableSaveBtn = false;\n\n UserSettingsCtrl.ePage.Masters.UserSetting.DeleteBtnText = \"Delete\";\n UserSettingsCtrl.ePage.Masters.UserSetting.IsDisableDeleteBtn = false;\n }",
"showSettingsModal() {\n return Modals.contentSettings(this);\n }",
"function settings(e) {\n e.detail.applicationcommands = {\n \"divAccount\": { href: \"accountSettings.html\", title: \"Account\" },\n \"divPrivacy\": { href: \"privacySettings.html\", title: \"Privacy\" },\n };\n WinJS.UI.SettingsFlyout.populateSettings(e);\n }",
"function createAccountClick() {\n $(\"#modal\").modal({backdrop: 'static', keyboard: true});\n $(\"#modal\").modal(\"show\");\n }",
"function showModal() {\n setVisible(true);\n setSignUp(false);\n }",
"function openSettings() {\n settingsPopup.style.display = \"block\";\n }",
"function openSettings() {\n pomodoroSettingsModal.classList.remove('hide-modal');\n document.querySelector('body').style.overflowY = 'hidden';\n setTimeout(() => pomodoroSettingsModal.style.opacity = 1, 0);\n }",
"openSettingsMenu() {\n\t\tif(this.menuSettings.hasGameStarted) {\n\t\t\tthis.settings_save.style.display = 'none';\n\t\t\tthis.settings_cancel.style.display = 'inline-block';\n\t\t\tthis.player_number.style.display = 'none';\n\t\t}\n\t\telse {\n\t\t\tthis.settings_save.style.display = 'inline-block';\n\t\t\tthis.settings_cancel.style.display = 'none';\n\t\t\tthis.player_number.style.display = 'inline-block';\n\t\t}\n\t\tthis.settings_menu.showModal();\n\t}",
"function backToAccountSettings() {\n accountSettingsEditModal.style.display = 'none';\n sidebarSettings.style.display = 'block'\n}",
"function showSettingsDialog() {\n var html = getSettings();\n\n html.setWidth(400);\n html.setHeight(300);\n\n SpreadsheetApp.getUi()\n .showModalDialog(html, 'Fuzzy.ai Settings');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a group that will contain proxy elements. The group order is automatically updated according to the last group order keys. Returns the added group. | addGroup(groupKey, groupType, attributes) {
const existingGroup = this.groups[groupKey];
if (existingGroup) {
return existingGroup.groupElement;
}
const proxyContainer = this.domElementProvider.createElement(groupType);
// If we want to add a role to the group, and still use e.g.
// a list group, we need a wrapper div.
let groupElement;
if (attributes && attributes.role && groupType !== 'div') {
groupElement = this.domElementProvider.createElement('div');
groupElement.appendChild(proxyContainer);
}
else {
groupElement = proxyContainer;
}
groupElement.className = 'highcharts-a11y-proxy-group highcharts-a11y-proxy-group-' +
groupKey.replace(/\W/g, '-');
this.groups[groupKey] = {
proxyContainerElement: proxyContainer,
groupElement,
type: groupType,
proxyElements: []
};
attr(groupElement, attributes || {});
if (groupType === 'ul') {
proxyContainer.setAttribute('role', 'list'); // Needed for webkit
}
// Add the group to the end by default, and perhaps then we
// won't have to reorder the whole set of groups.
this.afterChartProxyPosContainer.appendChild(groupElement);
this.updateGroupOrder(this.groupOrder);
return groupElement;
} | [
"addProxyElement(groupKey, target, attributes) {\n const group = this.groups[groupKey];\n if (!group) {\n throw new Error('ProxyProvider.addProxyElement: Invalid group key ' + groupKey);\n }\n const proxy = new ProxyElement(this.chart, target, group.type, attributes);\n group.proxyContainerElement.appendChild(proxy.element);\n group.proxyElements.push(proxy);\n return proxy;\n }",
"groupChildren(){\n const newGroup = this.constructor.CreateGroup();\n const childList = this.getChildrenList();\n this.addChild(newGroup);\n for(let c of childList){\n c.reparent(newGroup);\n }\n newGroup.recenterAnchorInSubtree();\n return newGroup;\n }",
"createGroup(groupName) {\n if (this.groups.hasOwnProperty(groupName))\n console.error(`Pulse Collection: Group ${groupName} already exists`);\n let group = new group_1.default(() => this);\n group.name = groupName;\n this.groups[groupName] = group;\n return group;\n }",
"function group( layer, items, isDuplicate) {\n\n\t\t// create new group\n\t\tvar gg = layer.groupItems.add();\n\n\t\t// add to group\n\t\t// reverse count, because items length is reduced as items are moved to new group\n\t\tfor(var i=items.length-1; i>=0; i--) {\n\n\t\t\tif (items[i]!=gg) { // don't group the group itself\n\t\t\t\tif (isDuplicate) {\n\t\t\t\t\tnewItem = items[i].duplicate (gg, ElementPlacement.PLACEATBEGINNING);\n\t\t\t\t} else {\n\t\t\t\t\titems[i].move( gg, ElementPlacement.PLACEATBEGINNING );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn gg;\n\t}",
"function addToGroup(curr){\r\n\t\tgroup.appendChild(curr.cloneNode(true));\r\n\t}",
"function createLocalGroup() {\n tm && tm.record(Web.TelemetryEvent.GroupCreate);\n var dfd = new Task(), group = createGroup(dfd.promise);\n pendingHrefs.push(dfd);\n pendingGroups.push(group);\n return group;\n }",
"clone() {\n let group = new Group();\n for (let i = 0, len = this.length; i < len; i++) {\n group.push(this[i].clone());\n }\n return group;\n }",
"_insertIntoNewGroup(details) {\n const that = this,\n tab = details.tab,\n tabLabelContainer = details.tabLabelContainer,\n group = details.group,\n groupContainers = that._addGroupContainer(group),\n groupLabel = groupContainers.label,\n groupDropDown = groupContainers.dropDown;\n\n groupDropDown.appendChild(tabLabelContainer);\n\n that._groups.push(group);\n\n let index = Math.max(0, Math.min(details.index, that.$.tabStrip.childElementCount)),\n tabStripIndex = index;\n\n if (that._addNewTab && tabStripIndex === that.$.tabStrip.childElementCount) {\n tabStripIndex--;\n }\n\n that.$.tabStrip.insertBefore(groupLabel, that.$.tabStrip.children[tabStripIndex] || null);\n\n that._groupLabels.push(groupLabel);\n\n const newJqxTabItemsGroup = document.createElement('jqx-tab-items-group');\n\n newJqxTabItemsGroup.appendChild(tab);\n that.$.tabContentSection.insertBefore(newJqxTabItemsGroup, that.$.tabContentSection.children[index]);\n newJqxTabItemsGroup.label = group;\n\n const previousSibling = newJqxTabItemsGroup.previousElementSibling;\n let overallIndex = 0;\n\n if (previousSibling) {\n if (previousSibling instanceof JQX.TabItem) {\n overallIndex = previousSibling.index + 1;\n }\n else if (previousSibling) {\n overallIndex = previousSibling.lastElementChild.index + 1;\n }\n }\n\n that._tabLabelContainers.splice(overallIndex, 0, tabLabelContainer);\n that.$.dropDownButtonDropDown.insertBefore(details.dropDownLabelContainer, that.$.dropDownButtonDropDown.children[overallIndex] || null);\n that._tabs.splice(overallIndex, 0, tab);\n\n index = overallIndex;\n\n tab.group = group;\n\n that._updateIndexes(index);\n }",
"add(x) {\n if(!this.has(x)) return new p_group(this.group.concat(x));\n }",
"createGroup() {\n\t\t\tW.accelerators.Groups[this.group] = [];\n\t\t\tW.accelerators.Groups[this.group].members = [];\n\n\t\t\tif(this.title && !I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group]){\n\t\t\t\tI18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group] = [];\n\t\t\t\tI18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].description = this.title;\n\t\t\t\tI18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].members = [];\n\t\t\t}\n\t\t}",
"group(n,s,g=[]){\n this.o.groups.push({n,s,g});\n return this;\n }",
"updateGroupOrder(groupKeys) {\n // Store so that we can update order when a new group is created\n this.groupOrder = groupKeys.slice();\n // Don't unnecessarily reorder, because keyboard focus is lost\n if (this.isDOMOrderGroupOrder()) {\n return;\n }\n const seriesIx = groupKeys.indexOf('series');\n const beforeKeys = seriesIx > -1 ? groupKeys.slice(0, seriesIx) : groupKeys;\n const afterKeys = seriesIx > -1 ? groupKeys.slice(seriesIx + 1) : [];\n // Store focused element since it will be lost when reordering\n const activeElement = doc.activeElement;\n // Add groups to correct container\n ['before', 'after'].forEach((pos) => {\n const posContainer = this[pos === 'before' ?\n 'beforeChartProxyPosContainer' :\n 'afterChartProxyPosContainer'];\n const keys = pos === 'before' ? beforeKeys : afterKeys;\n removeChildNodes(posContainer);\n keys.forEach((groupKey) => {\n const group = this.groups[groupKey];\n if (group) {\n posContainer.appendChild(group.groupElement);\n }\n });\n });\n // Attempt to restore focus after reordering, but note that this may\n // cause screen readers re-announcing the button.\n if ((this.beforeChartProxyPosContainer.contains(activeElement) ||\n this.afterChartProxyPosContainer.contains(activeElement)) &&\n activeElement && activeElement.focus) {\n activeElement.focus();\n }\n }",
"createGroup(existingGroups, group) {\n\t const existingGroup = _.find(existingGroups, { name: group.name });\n\t if (existingGroup) {\n\t return Promise.resolve(true);\n\t }\n\n\t const payload = {\n\t name: group.name,\n\t description: group.description\n\t };\n\n\t return request.post({ uri: process.env.AUTHZ_API_URL + '/groups', json: payload, headers: { 'Authorization': 'Bearer ' + this.accessToken } })\n\t .then((createdGroup) => {\n\t existingGroups.push(createdGroup);\n\t log(chalk.green.bold('Group:'), `Created ${group.name}`);\n\t return group;\n\t });\n\t}",
"function duplicateGroupToDoc(layer) \n{\n createNewDoc();\n\n var x = docRef.layerSets.length;\n \n app.activeDocument = docRef;//set active document\n activeDocument.activeLayer = layer;\n\n newLayerSetRef = layer.duplicate(app.documents[\"Clipped Group\"], ElementPlacement.PLACEATBEGINNING); \n\n app.activeDocument = newDocRef; \n newDocRef.activeLayer = newLayerSetRef;\n newLayerSetRef.name = layer.name;\n}",
"function createGroups(accumulated, item) {\n var last = accumulated[accumulated.length - 1];\n\n if (last && last.type === 'group-start') {\n if (item.type === 'group-end') {\n last.type = 'group';\n } else {\n last.entries.push(item);\n }\n } else if (item.type === 'group-start') {\n item.entries = [];\n accumulated.push(item);\n } else {\n accumulated.push(item);\n }\n return accumulated;\n}",
"function makeWallGroup() {\n var $ = go.GraphObject.make;\n return $(go.Group, \"Spot\",\n {\n contextMenu: makeContextMenu(),\n toolTip: makeGroupToolTip(),\n selectionObjectName: \"SHAPE\",\n rotateObjectName: \"SHAPE\",\n locationSpot: go.Spot.Center,\n reshapable: true,\n minSize: new go.Size(1, 1),\n dragComputation: snapWalls,\n selectionAdorned: false,\n mouseDrop: addWallPart,\n mouseDragEnter: wallPartDragOver,\n mouseDragLeave: wallPartDragAway,\n doubleClick: function (e) { if (e.diagram.floorplanUI) e.diagram.floorplanUI.hideShow(\"selectionInfoWindow\"); }\n },\n $(go.Shape,\n {\n name: \"SHAPE\",\n fill: \"black\",\n },\n new go.Binding(\"strokeWidth\", \"thickness\"),\n new go.Binding(\"stroke\", \"isSelected\", function (s, obj) {\n if (obj.part.containingGroup != null) {\n var group = obj.part.containingGroup;\n if (s) { group.data.isSelected = true; }\n }\n return s ? \"dodgerblue\" : \"black\";\n }).ofObject()\n ))\n}",
"function createGroup(x, y, z) {\n\tlet group = new THREE.Group();\n\tgroup.position.set(x, y, z);\n\treturn group;\n}",
"AddGroup(w, h, position) {\n let self = this;\n this.Group = new Konva.Group({\n id: \"gondola_group_\" + self.ID,\n name: \"gondola_group\",\n x: position.x,\n y: position.y,\n width: w,\n height: h\n });\n\n this.Layer.add(this.Group);\n }",
"function groups() {\n\tvar result = new EventEmitter();\n\tprocess.nextTick(function() {\n\t\tstore.groups.forEach(function(g) {\n\t\t\tresult.emit('group', g);\n\t\t})\n\t\tresult.emit('end');\n\t})\n\treturn result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The interface for an adapter is simply a function that takes a [Socket.IO]( socket. When test events `testsstart`, `testresult`, `alltestresults` come in, the adapter is responsible for sending these events to the socket. | function customTestFrameworkAdapter(socket) {
// Store all the tests in an array for simplicity of running.
var tests = []
var started = false
window.test = function test(name, fn){
tests.push([name, fn])
// assume all tests are added synchronously
// so after the setTimeout, we should have all the
// tests we have to run available in `tests` variable.
if (!started){
setTimeout(runTests, 1)
started = true
}
}
// simple assert function
window.assert = function assert(bool, message) {
if (!bool) {
throw new Error(message)
}
}
function runTests(){
var results = { // Summary of all test results
failed: 0
, passed: 0
, total: 0
, tests: []
}
var id = 1 // A counter that IDs each test
// Send `tests-start` to indicate to the Testem UI
// that tests have started running.
socket.emit("tests-start")
// Loop through the tests and run them
for (var i = 0, numTests = tests.length; i < numTests; i++){
var test = tests[i]
, name = test[0] // test name
, fn = test[1] // test function
, passed = false
var result = { // the result object to report for this test
passed: 0
, failed: 0
, total: 1
, id: id++
, name: name
, items: []
}
try {
fn() // run it!
passed = true // we passed!
} catch (err) {
// On failure, we want to recored the
// error message and, if available - the stack
// and add to `result.items` to be reported back
result.items.push({
passed: false
, message: err.message
, stack: err.stack ? err.stack : undefined
})
}
// update the passed and failed count for this test
// and the overall summary
if (passed) {
results.passed++
result.passed++
} else {
results.failed++
result.failed++
}
// Now actually report back this test result
socket.emit("test-result", result)
// update the total tally and add to the collection of
// overall results
results.total++
results.tests.push(result)
}
// Report back all test results and the fact that
// we are done running them.
socket.emit("all-test-results")
}
} | [
"function qunitAdapter(socket) {\n var currentTest, currentModule;\n\n var id = 1;\n\n var results = {\n failed: 0,\n passed: 0,\n total: 0,\n tests: []\n };\n\n QUnit.log(function(details) {\n var item = {\n passed: details.result,\n message: details.message\n }\n\n if (!details.result) {\n item.actual = details.actual;\n item.expected = details.expected;\n }\n\n currentTest.items.push(item);\n });\n\n QUnit.testStart(function(details) {\n currentTest = {\n id: id++,\n name: (currentModule ? currentModule + ': ' : '') + details.name,\n items: []\n };\n socket.emit('tests-start');\n });\n\n QUnit.testDone(function(details) {\n currentTest.failed = details.failed;\n currentTest.passed = details.passed;\n currentTest.total = details.total;\n\n results.total++;\n\n if (currentTest.failed > 0) {\n results.failed++;\n } else {\n results.passed++;\n }\n\n results.tests.push(currentTest);\n socket.emit('test-result', currentTest);\n });\n\n QUnit.moduleStart(function(details) {\n currentModule = details.name;\n });\n\n QUnit.done(function(details) {\n results.runDuration = details.runtime;\n socket.emit('all-test-results', results);\n });\n }",
"listen_test() {\n this.socket.on('Test', (data, callback) => {\n console.log('Test Successful');\n callback(data);\n });\n }",
"function TestemSocket() {}",
"function MockSocket() {\n this._dataListeners = [];\n}",
"function SocketInterface() {\n queue(this, 'on');\n queue(this, 'send');\n}",
"setupSocketIO() {\n\n }",
"function run(tests, socket, cb) {\n\n // Generate list of tests to be run, in order.\n // If given a string, import it as a module.\n // If given a non-function object, run any test-like methods on it.\n\n var testNames = [];\n var testsToRun = {};\n\n if (typeof tests === 'string') {\n tests = require(tests);\n }\n if (typeof tests === 'function') {\n testNames.push(tests.name || \"test_default\");\n testsToRun[testNames[testNames.length - 1]] = tests;\n } else if (typeof tests === 'object') {\n Object.keys(tests).forEach(function(testname) {\n if (typeof tests[testname] === 'function') {\n // Match array indices, or method names with \"test\" in them.\n if (typeof testname === 'number' || (/.*test.*/i).exec(testname)) {\n testNames.push(testname);\n testsToRun[testname] = tests[testname].bind(tests);\n }\n }\n });\n }\n\n // Loop through doing runs of the tests until we've exceeded the\n // specified duration, or the specified number of hits.\n\n var duration = socket.runStatus.duration || 0;\n var startTime = currentTime();\n\n async.doWhilst(\n\n // Loop body - do a single run through the tests.\n function doTestRun(cb) {\n\n // Iterate over the tests, doing each in turn.\n async.eachSeries(testNames, function(testname, cb) {\n\n // Each test expects to be called with a single callback argument,\n // which provides the LoadsSocket object as special property 'socket'.\n var testcb = function(err) {\n if (err) {\n var exc_info = [\"JSError\", JSON.stringify(err), \"\"];\n socket.send('addFailure', {test: testname, exc_info: exc_info});\n } else {\n socket.send('addSuccess', {test: testname});\n }\n socket.send('stopTest', {test: testname});\n process.nextTick(function() {\n return cb(null);\n });\n };\n socket.send('startTest', {test: testname});\n testcb.socket = socket;\n\n // Do the test, being sure to catch any exceptions so that\n // we can report them properly.\n try {\n testsToRun[testname](testcb);\n } catch (err) {\n testcb(err);\n }\n }, cb);\n\n },\n\n // Loop condition - stop once hits and duration have been met.\n function checkForTermination() {\n socket.runStatus.currentHit++;\n if (socket.runStatus.currentHit <= socket.runStatus.totalHits) {\n return true;\n }\n if (duration) {\n if (startTime + duration > currentTime()) {\n return true;\n }\n }\n },\n\n // Exit handler - just invoke the original callback.\n cb\n );\n}",
"function MockSocketIO() {\n this.function_calls = {};\n this.volatile = new MockVolatile();\n this._sockets = [];\n this.length = 0;\n}",
"setUpSocketEventListeners() {}",
"function onTest(data) {\r\n console.log('Received: \"' + data + '\" from client: ' + client.id);\r\n client.emit('test', \"Cheers, \" + client.id);\r\n }",
"function MockSocket (id) {\n\n\treturn {\n\t\tid: id,\n\t\temit: function () {}\n\t};\n\n}",
"function onTest(data) {\n console.log('Received: \"' + data + '\" from client: ' + client.id);\n client.emit('test', \"Cheers, \" + client.id);\n }",
"static registerSocketTest () {\n // Test de l'absence de socket\n runner('deepEqual', WebSocketServer.registeredWebsocket, new Map())\n\n // Test de l'enregistrement d'un socket\n WebSocketServerTest.object.registerSocket(socket, acceptKey)\n runner('equal', WebSocketServer.registeredWebsocket.size, 1)\n runner('deepEqual', WebSocketServer.registeredWebsocket.get(acceptKey), socket)\n\n // Test de la présence des eventLisentners\n runner('equal', typeof socket.listeners.get('timeout'), 'function')\n runner('equal', typeof socket.listeners.get('data'), 'function')\n }",
"function MockServer() {\n EventEmitter.call(this);\n\n this.clients = [];\n\n this.write = function(data) {\n this.emit('write', data);\n };\n\n this.connect = function(client) {\n this.addListener('write', function(data) {\n client.emit('data', data);\n });\n client.connect(this);\n this.clients.push(client);\n return this;\n };\n}",
"listen() {\n this.io.on('connection', (socket) => {\n this.events.forEach((event, key) => {\n socket.on(key, event.execute(this.io, socket));\n });\n });\n this.io.listen(this.port);\n this.onReady();\n }",
"function callSockets(io, message){\r\n io.sockets.emit('data', message);\r\n}",
"sockets() {\r\n this.io.on('connection', ( socket ) => socketController( socket , this.io) ); \r\n\r\n }",
"_applyOnAdapters(t) {\n this.adapters.forEach((e) => {\n t(e);\n });\n }",
"function Hub() {\n EventEmitter.call(this);\n\n if (appConfig.env === 'test') {\n // during test, there is no browser. thus we cannot instantiate socket.io!\n return;\n }\n\n this.io = (appConfig.wsUrl) ? socketIo(appConfig.wsUrl) : socketIo();\n\n this.io.on('connect', () => log.info('socket to server connected'));\n this.io.on('disconnect', () => log.info('socket from server disconnected'));\n this.io.on('event', this.emit.bind(this, 'event'));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a modal according to the current portfolio item | function addPortfolioModal(element, number) {
var modal = $("<div>", {
id : 'portfolioModal' + number,
class: 'portfolio-modal modal fade',
tabindex : "-1",
role : "dialog"
}).attr( 'aria-hidden', 'true');
var modalContent = $('<div>', { class: 'modal-content'});
var lr = $('<div>', { class: 'lr' }).append("<div class='rl'></div>")
var closeModal = $('<div>', { class: 'close-modal' }).attr('data-dismiss','modal').append(lr);
var container = $('<div>', { class: 'container' });
var row = $('<div>', { class: 'row' });
var col = $('<div>', { class: 'col-lg-8 col-lg-offset-2' });
var modalBody = $('<div>', { class: 'modal-body'});
var title = $('<h2>', { html: element.title });
var hr = $("<hr>", { class: 'star-primary' });
var img = $('<img>', {
class: 'img-responsive img-centered',
src: element.miniature,
alt: ''
});
var description = $("<p>", { html: element.description });
// Projects details
var list = $('<ul>', { class: 'list-unstyled item-details'});
var liAuthor = $('<li>', { html: 'Auteur(s)' })
.append($('<strong>').append($('<p>', { html: element.authors })));
var liDate = $('<li>', { html: 'Date' })
.append($('<strong>').append($('<p>', { html: element.year })));
var liPlatform = $('<li>', { html: 'Plateformes' })
.append($('<strong>').append($("<p>", { html: element.platform })));
var button = $('<button>', {
class: 'btn btn-danger',
type : 'button'
}).attr('data-dismiss', 'modal')
.append("<i class='fa fa-times'>Close</i>");
list.append(liAuthor).append(liDate).append(liPlatform);
modalBody.append(title).append(hr).append(img)
.append(description).append(list).append(button);
container.append(row).append(col).append(modalBody);
modalContent.append(closeModal).append(container);
modal.append(modalContent);
modal.insertAfter("#portfolio");
} | [
"function portfolioModal(projectID) {\n for (let i=0; i<portfolio.length; i++) {\n if (parseInt(projectID) === parseInt(portfolio[i].projectID)) {\n var project = portfolio[i];\n\n // update project title\n $(\"p.modalTitle\").text(project.projectName);\n\n // update project image\n $(\"img.projectImage\").attr('src', project.descriptionImage);\n\n // update the description\n $(\".projectInfo .projectDescription\").text(project.description);\n\n // update the project features\n addProductFeatures(project);\n\n // update project links\n $(\".links a#link1\").attr('href', project.link1)\n $(\".links a#link2\").attr('href', project.link2) \n }\n }\n }",
"function MilestoneDeliverableItemModal() {}",
"function setPortfolioTabModalData(){\n const portfolioModal = $('#portfolio-modal');\n const listItem = $('.portfolio-tab-container .list-item');\n\n $('.portfolio-tab-container .list-item').on(\"click\", function(){\n $('#portfolio-modal .modal-title').text( $(this).find('span').html() );\n $('#portfolio-modal .modal-body img').attr( 'src', $(this).find('img').attr('src') );\n });\n }",
"function MilestoneNoteItemModal() {}",
"function addContent (){\n var selectedProject;\n projects.forEach( function(cV){\n if(selectedId == cV.id){ selectedProject = cV; }\n });\n selectedProject.content();\n portfolioObj.center( $('body'), $modalWindow);\n }",
"function createItemModal(elem, title, desc, currentColour, isComplete, allColours) {\n // If modal exists then do no create a new one\n if (!$(\"#modalId\").length) {\n modalDiv = document.createElement(\"DIV\");\n modalDiv.id = \"modalId\";\n $(modalDiv).addClass(\"modal\");\n\n // Remove modal if clicking outside main div\n $(modalDiv).click(function(event) {\n if (event.target == modalDiv) {\n modalDiv.remove();\n blur();\n elem.focus();\n }\n });\n\n main2ColumnDiv = document.createElement(\"DIV\");\n $(main2ColumnDiv).addClass(\"list-modal-content-2-columns\");\n\n itemModalHeaderDiv = document.createElement(\"DIV\");\n $(itemModalHeaderDiv).addClass(\"list-modal-header\");\n\n itemModalHeaderSpan = document.createElement(\"SPAN\");\n $(itemModalHeaderSpan).addClass(\"list-modal-header-span\");\n $(itemModalHeaderSpan).html(\"<i class=\\\"fas fa-edit icon-space\\\"></i>Edit Item\");\n\n itemModalHeaderBtn = document.createElement(\"BUTTON\");\n $(itemModalHeaderBtn).addClass(\"list-modal-close\");\n $(itemModalHeaderBtn).html(\"<i class=\\\"fas fa-times\\\"></i>\");\n $(itemModalHeaderBtn).click(function(event) {\n if ($(\"#modalId\").length) {\n $(\"#modalId\").remove();\n blur();\n elem.focus();\n }\n });\n\n itemModalMainForm = document.createElement(\"FORM\");\n itemModalMainForm.id = \"itemModalForm\";\n $(itemModalMainForm).addClass(\"list-modal-form\");\n\n itemModalMainColumnDiv = document.createElement(\"DIV\");\n $(itemModalMainColumnDiv).addClass(\"modal-main-column-div\");\n\n itemModalLeftDiv = document.createElement(\"DIV\");\n $(itemModalLeftDiv).addClass(\"modal-left-div\");\n\n itemModalTitleLabel = document.createElement(\"LABEL\");\n $(itemModalTitleLabel).addClass(\"form-label\");\n $(itemModalTitleLabel).attr(\"for\", \"itemModalInput\");\n $(itemModalTitleLabel).html(\"Item Name\");\n\n itemModalTitleInput = document.createElement(\"INPUT\");\n $(itemModalTitleInput).addClass(\"form-input\");\n itemModalTitleInput.id = \"itemModalInput\";\n $(itemModalTitleInput).attr(\"type\", \"text\");\n $(itemModalTitleInput).attr(\"name\", \"itemModalInput\");\n $(itemModalTitleInput).attr(\"value\", title);\n\n itemModalDescLabel = document.createElement(\"LABEL\");\n $(itemModalDescLabel).addClass(\"form-label\");\n $(itemModalDescLabel).attr(\"for\", \"modalItemDescription\");\n $(itemModalDescLabel).html(\"Description\");\n\n itemModalDescTextarea = document.createElement(\"TEXTAREA\");\n $(itemModalDescTextarea).addClass(\"form-textarea\");\n itemModalDescTextarea.id = \"modalItemDescription\"\n $(itemModalDescTextarea).attr(\"type\", \"text\");\n $(itemModalDescTextarea).attr(\"name\", \"modalItemDescription\");\n $(itemModalDescTextarea).html(desc);\n\n itemModalRightDiv = document.createElement(\"DIV\");\n $(itemModalRightDiv).addClass(\"modal-right-div\");\n\n itemModalColourLabel = document.createElement(\"LABEL\");\n $(itemModalColourLabel).addClass(\"form-label\");\n $(itemModalColourLabel).attr(\"for\", \"modalColourDropdown\");\n $(itemModalColourLabel).html(\"Colour\");\n\n itemModalColourDiv = document.createElement(\"DIV\");\n $(itemModalColourDiv).addClass(\"modal-colour-div\");\n\n itemModalColourTypeInput = document.createElement(\"INPUT\");\n $(itemModalColourTypeInput).attr(\"type\", \"color\");\n $(itemModalColourTypeInput).addClass(\"modal-colour-input\");\n itemModalColourTypeInput.id = \"modalColourInput\";\n $(itemModalColourTypeInput).attr(\"name\", \"modalColourInput\");\n $(itemModalColourTypeInput).attr(\"list\", \"presetColours\");\n $(itemModalColourTypeInput).attr(\"value\", \"#\" + currentColour);\n\n preset_colours = [\"ffffff\", \"ce2d4f\", \"f08a4b\", \"ffc145\", \"55c1ff\", \"81c14b\", \"bfc0c0\"];\n\n for (c of allColours) {\n if (!preset_colours.includes(c.toLowerCase())) {\n preset_colours.push(c.toLowerCase());\n }\n }\n\n itemModalColourDatalist = document.createElement(\"DATALIST\");\n itemModalColourDatalist.id = \"presetColours\";\n\n for (c of preset_colours) {\n optionColour = document.createElement(\"OPTION\");\n $(optionColour).html(\"#\" + c.toLowerCase());\n $(itemModalColourDatalist).append(optionColour);\n }\n\n itemModalColourTextDiv = document.createElement(\"DIV\");\n $(itemModalColourTextDiv).addClass(\"colour-text-div\");\n\n itemModalHashSpan = document.createElement(\"SPAN\");\n $(itemModalHashSpan).addClass(\"hash-span\");\n $(itemModalHashSpan).html(\"#\");\n\n itemModalColourTextInput = document.createElement(\"INPUT\");\n $(itemModalColourTextInput).addClass(\"form-input-colour\");\n itemModalColourTextInput.id = \"formTextColour\";\n $(itemModalColourTextInput).attr(\"type\", \"text\");\n $(itemModalColourTextInput).attr(\"value\", currentColour.toLowerCase());\n $(itemModalColourTextInput).attr(\"maxlength\", 6);\n $(itemModalColourTextInput).attr(\"oninput\", \"updateColourInput(this.value)\");\n\n $(itemModalColourTypeInput).change(function() {\n itemModalColourTextInput.value = itemModalColourTypeInput.value.substring(1);\n });\n\n itemModalCompleteLabel = document.createElement(\"LABEL\");\n $(itemModalCompleteLabel).addClass(\"form-label modal-checkmark-container\");\n $(itemModalCompleteLabel).attr(\"for\", \"modalCheckBox\");\n $(itemModalCompleteLabel).html(\"Complete?\");\n\n itemModalCompleteInput = document.createElement(\"INPUT\");\n $(itemModalCompleteInput).attr(\"type\", \"checkbox\");\n itemModalCompleteInput.id = \"modalCheckBox\";\n $(itemModalCompleteInput).attr(\"name\", \"modalCheckBox\");\n // If checked then check the checkbox\n if (isComplete == 1) {\n $(itemModalCompleteInput).attr(\"checked\", \"checked\");\n }\n\n itemModalCompleteSpan = document.createElement(\"SPAN\");\n $(itemModalCompleteSpan).addClass(\"modal-checkmark-span\");\n\n itemModalControlsDiv = document.createElement(\"DIV\");\n $(itemModalControlsDiv).addClass(\"list-modal-controls\");\n\n itemModalSaveCancelDiv = document.createElement(\"DIV\");\n $(itemModalSaveCancelDiv).addClass(\"list-modal-save-cancel\");\n\n itemModelSaveBtn = document.createElement(\"BUTTON\");\n $(itemModelSaveBtn).addClass(\"list-modal-btn list-modal-save-btn create-btn\");\n $(itemModelSaveBtn).attr(\"type\", \"submit\");\n $(itemModelSaveBtn).html(\"Save\");\n\n itemModelCancelBtn = document.createElement(\"BUTTON\");\n $(itemModelCancelBtn).addClass(\"list-modal-btn list-modal-cancel-btn\");\n $(itemModelCancelBtn).attr(\"type\", \"button\");\n $(itemModelCancelBtn).html(\"Cancel\");\n\n $(itemModelCancelBtn).click(function(event) {\n if ($(\"#modalId\").length) {\n $(\"#modalId\").remove();\n blur();\n elem.focus();\n }\n });\n\n itemModalDeleteBtn = document.createElement(\"BUTTON\");\n $(itemModalDeleteBtn).addClass(\"list-modal-btn cancel-btn\");\n $(itemModalDeleteBtn).attr(\"type\", \"button\");\n $(itemModalDeleteBtn).html(\"<i class=\\\"fas fa-trash icon-space\\\"></i> Delete Item\");\n\n // -------------------------- MODAL CONSTRUCTION -------------------------- //\n\n $(modalDiv).append(main2ColumnDiv);\n $(main2ColumnDiv).append(itemModalHeaderDiv);\n $(itemModalHeaderDiv).append(itemModalHeaderSpan);\n $(itemModalHeaderDiv).append(itemModalHeaderBtn);\n\n $(main2ColumnDiv).append(itemModalMainForm);\n $(itemModalMainForm).append(itemModalMainColumnDiv);\n $(itemModalMainForm).append(itemModalControlsDiv);\n $(itemModalMainColumnDiv).append(itemModalLeftDiv);\n $(itemModalMainColumnDiv).append(itemModalRightDiv);\n\n $(itemModalLeftDiv).append(itemModalTitleLabel);\n $(itemModalLeftDiv).append(itemModalTitleInput);\n $(itemModalLeftDiv).append(itemModalDescLabel);\n $(itemModalLeftDiv).append(itemModalDescTextarea);\n\n $(itemModalRightDiv).append(itemModalColourLabel);\n $(itemModalRightDiv).append(itemModalColourDiv);\n $(itemModalRightDiv).append(itemModalCompleteLabel);\n\n $(itemModalColourDiv).append(itemModalColourTypeInput);\n $(itemModalColourDiv).append(itemModalColourDatalist);\n $(itemModalColourDiv).append(itemModalColourTextDiv);\n\n $(itemModalColourTextDiv).append(itemModalHashSpan);\n $(itemModalColourTextDiv).append(itemModalColourTextInput);\n\n $(itemModalCompleteLabel).append(itemModalCompleteInput);\n $(itemModalCompleteLabel).append(itemModalCompleteSpan);\n\n $(itemModalControlsDiv).append(itemModalSaveCancelDiv);\n $(itemModalSaveCancelDiv).append(itemModelSaveBtn);\n $(itemModalSaveCancelDiv).append(itemModelCancelBtn);\n $(itemModalControlsDiv).append(itemModalDeleteBtn);\n\n $(modalDiv).insertAfter(\"#mainBodyDiv\");\n\n // Variable to hold request\n var request;\n // Bind to the submit event of our form\n $(itemModalMainForm).submit(function(event) {\n // Prevent default posting of form - put here to work in case of errors\n event.preventDefault();\n\n // Remove undo button if it exists\n if ($(\"#undoBtnId\")) {\n $(\"#undoBtnId\").remove();\n }\n\n itemModalInput = $(itemModalMainForm).find(\"input[name=\\\"itemModalInput\\\"]\").val();\n modalItemDescription = $(itemModalMainForm).find(\"textarea[name=\\\"modalItemDescription\\\"]\").val();\n modalColourInput = $(itemModalMainForm).find(\"input[name=\\\"modalColourInput\\\"]\").val().substring(1);\n modalCheckBox = $(itemModalMainForm).find(\"input[name=\\\"modalCheckBox\\\"]\").is(\":checked\");\n\n itemModalInputError = itemModalInput.length == 0 ? \"Please enter a list name.\" : (itemModalInput.length > 255 ? \"The name is too long.\" : \"\");\n modalItemDescriptionError = modalItemDescription.length > 21844 ? \"The description is too long.\" : \"\";\n\n // if (itemModalInputError.length == 0 && modalItemDescriptionError.length == 0) {\n // Check if the input and current values are the same\n // Abort any pending request\n if (request) {\n request.abort();\n }\n // Setup some local variables\n var $form = $(this);\n\n // Let's select and cache all the fields\n var $inputs = $form.find(\"input, select, button, textarea\");\n\n listItem = $(elem).parent().parent()[0];\n\n // Serialize the data in the form\n var serializedData = \"itemId=\" + $(elem).attr(\"data-id\") + \"&itemModalInput=\" + itemModalInput + \"&modalItemDescription=\" + modalItemDescription + \"&modalColourInput=\" + modalColourInput + \"&modalCheckBox=\" + modalCheckBox + \"&listId=\" + $(listItem).attr(\"data-id\");\n\n // Let's disable the inputs for the duration of the Ajax request.\n // Note: we disable elements AFTER the form data has been serialized.\n // Disabled form elements will not be serialized.\n $inputs.prop(\"disabled\", true);\n\n // Fire off the request to /form.php\n request = $.ajax({\n url: \"save_item_data.php\",\n type: \"post\",\n dataType: \"json\",\n data: serializedData\n });\n\n // Callback handler that will be called on success\n request.done(function (response, textStatus, jqXHR){\n // If error is returned\n if (response[\"error\"]) {\n if (response[\"error\"][\"itemTitle\"]) {\n if ($(\"#itemModalInput\").next().hasClass(\"new-item-error-p\")) {\n $(\"#itemModalInput\").next().html(response[\"error\"][\"itemTitle\"]);\n } else {\n p = document.createElement(\"P\");\n p.innerHTML = response[\"error\"][\"itemTitle\"];\n p.classList.add(\"new-item-error-p\");\n\n $(p).insertAfter(\"#itemModalInput\");\n }\n }\n\n if (response[\"error\"][\"itemDesc\"]) {\n if ($(\"#modalItemDescription\").next().hasClass(\"new-item-error-p\")) {\n $(\"#modalItemDescription\").next().html(response[\"error\"][\"itemDesc\"]);\n } else {\n p = document.createElement(\"P\");\n p.innerHTML = response[\"error\"][\"itemDesc\"];\n p.classList.add(\"new-item-error-p\");\n\n $(p).insertAfter(\"#modalItemDescription\");\n }\n }\n // If successfully added to the database\n } else {\n if ($(\"#itemModalInput\").next().hasClass(\"new-item-error-p\")) {\n $(\"#itemModalInput\").next().remove();\n }\n\n if ($(\"#modalItemDescription\").next().hasClass(\"new-item-error-p\")) {\n $(\"#modalItemDescription\").next().remove();\n }\n\n $(elem).html(response[\"success\"][\"title\"]);\n $(elem).css(\"border-left-color\", \"#\" + response[\"success\"][\"colour\"]);\n $(modalDiv).remove();\n\n if (response[\"success\"][\"is_complete\"] == \"true\") {\n $(elem.parentNode).remove();\n }\n }\n });\n\n // Callback handler that will be called on failure\n request.fail(function (jqXHR, textStatus, errorThrown){\n console.error(\n \"The following error occurred: \"+\n textStatus, errorThrown\n );\n });\n\n // Callback handler that will be called regardless\n request.always(function () {\n // Reenable the inputs\n $inputs.prop(\"disabled\", false);\n });\n // }\n });\n\n $(itemModalDeleteBtn).click(function() {\n // Prevent default posting of form - put here to work in case of errors\n event.preventDefault();\n\n // Remove undo button if it exists\n if ($(\"#undoBtnId\")) {\n $(\"#undoBtnId\").remove();\n }\n\n // Abort any pending request\n if (request) {\n request.abort();\n }\n // Setup some local variables\n var $form = $(this);\n\n // Let's select and cache all the fields\n var $inputs = $form.find(\"input, select, button, textarea\");\n\n listItem = $(elem).parent().parent()[0];\n\n // Serialize the data in the form\n var serializedData = \"itemId=\" + $(elem).attr(\"data-id\") + \"&listId=\" + $(listItem).attr(\"data-id\");\n\n // Let's disable the inputs for the duration of the Ajax request.\n // Note: we disable elements AFTER the form data has been serialized.\n // Disabled form elements will not be serialized.\n $inputs.prop(\"disabled\", true);\n\n // Fire off the request to /form.php\n request = $.ajax({\n url: \"delete_item.php\",\n type: \"post\",\n dataType: \"json\",\n data: serializedData\n });\n\n // Callback handler that will be called on success\n request.done(function (response, textStatus, jqXHR) {\n // If error is returned\n if (response[\"error\"]) {\n if ($(\"#itemModalInput\").next().hasClass(\"new-item-error-p\")) {\n $(\"#itemModalInput\").next().html(response[\"error\"]);\n } else {\n p = document.createElement(\"P\");\n p.innerHTML = response[\"error\"];\n p.classList.add(\"new-item-error-p\");\n\n $(p).insertAfter(\"#itemModalInput\");\n }\n // If successfully remove from database\n } else {\n if ($(\"#itemModalInput\").next().hasClass(\"new-item-error-p\")) {\n $(\"#itemModalInput\").next().remove();\n }\n\n $(modalDiv).remove();\n listItem = $(elem).parent().parent()[0];\n $(elem.parentNode).remove();\n\n // Create an undo button\n undoBtn = document.createElement(\"BUTTON\");\n $(undoBtn).addClass(\"undo-btn\");\n undoBtn.id = \"undoBtnId\";\n $(undoBtn).html(\"<i class=\\\"fas fa-undo icon-space\\\"></i>Undo\");\n $(undoBtn).insertAfter(\"#mainBodyDiv\");\n undoBtn.style.animation = \"buttonFromBotttom 0.2s forwards\";\n $(undoBtn).click(function() {\n var request;\n\n // Prevent default posting of form - put here to work in case of errors\n event.preventDefault();\n\n // Abort any pending request\n if (request) {\n request.abort();\n }\n\n // Serialize the data in the form\n var serializedData = \"itemId=\" + $(elem).attr(\"data-id\") + \"&listId=\" + $(listItem).attr(\"data-id\");\n\n // Fire off the request to /form.php\n request = $.ajax({\n url: \"undo_delete_item.php\",\n type: \"post\",\n dataType: \"json\",\n data: serializedData\n });\n\n // Callback handler that will be called on success\n request.done(function (response, textStatus, jqXHR){\n // If error is returned\n if (response[\"error\"]) {\n console.log(response[\"error\"]);\n // If re-add the list\n } else {\n location.reload();\n }\n });\n\n // Callback handler that will be called on failure\n request.fail(function (jqXHR, textStatus, errorThrown){\n console.error(\n \"The following error occurred: \"+\n textStatus, errorThrown\n );\n });\n\n // Callback handler that will be called regardless\n request.always(function () {\n // Reenable the inputs\n $inputs.prop(\"disabled\", false);\n });\n });\n }\n });\n });\n }\n}",
"function clickProject(project) {\n console.log(project);\n var modalName = \"#portfolioModal\";\n\n $(modalName + \" .project-title\").html(project.title);\n $(modalName + \" .project-content\").html(project.description);\n $(modalName + \" .img-responsive\").attr('src', project.miniature);\n $(modalName + \" .project-link\").attr('href', project.link);\n}",
"function openPortfolioModal(number) {\n const modal = document.getElementById(\"portfolioModal\" + number);\n modal.style.display = \"block\";\n window.onclick = function(event) {\n if (event.target == modal) {\n modal.style.display = \"none\";\n }\n }\n}",
"function addSectionToPortfolio(element) {\n var item = $('<div>', {\n class: 'col-sm-3 portfolio-item'\n });\n\n var link = $('<a>', {\n class: 'portfolio-link',\n href: '#portfolioModal',\n }).attr(\"data-toggle\", 'modal');\n\n var caption = $('<div>', {\n class: 'caption'\n });\n\n var captionContent = $('<div>', {\n class: 'caption-content'\n });\n\n var information = $('<i>', {\n class: 'fa fa-search-plus fa-3x'\n });\n\n var img = $('<img>', {\n class: 'img-responsive img-projects',\n src : element.preview,\n alt: ''\n });\n\n caption.append(captionContent.append(information));\n item.append(link.append(caption).append(img));\n item.appendTo(\"#portfolio .container .items\");\n\n item.click(function () {\n clickProject(element);\n });\n}",
"add(itemName, componentName, props) {\n self.modals.push({\n itemName,\n componentName,\n props\n });\n }",
"function initPortfolio() {\n var container = $('.portfolio-gallery');\n\n $('.navigation li').click(function() {\n $(this).addClass('active');\n $('.navigation li').not($(this)).removeClass('active');\n });\n\n var mixed = mixitup($('.portfolio-gallery .elements'), {\n animation: {\n duration: 400,\n //feffects: 'fade translateZ(-360px) stagger(34ms)',\n easing: 'ease'\n }\n });\n\n // When a Portfolio Item is clicked, then the equivalent modal is open\n $('.portfolio-item', container).click(function() {\n $('#' + $(this).data('item')).parent().css('display', 'flex');\n $('body').addClass('modal-open'); // Turn off the scroll page\n $('#' + $(this).data('item')).css('display', 'flex').animateCss('fadeIn', function() {\n revealModal();\n });\n\n // Force the click event to reset the slider\n $('#' + $(this).data('item') + ' .navigation label:first-child').trigger('click');\n \n });\n\n // When the close button is clicked, then close the modal and turn on the page scroll\n $('.close-button a').click(function() {\n $('body').removeClass('modal-open');\n $(this).parent().parent().animateCss('fadeOut', function() {\n $('.modal').css('display', 'none');\n $('.portfolio-modal-container').css('display', 'none');\n });\n });\n }",
"choose() {\n const { i18next } = this;\n const modal = Modals.newModal();\n modal.setContent(`<h3>${i18next.t('modals.choose.title')}</h3><p>${i18next.t('modals.choose.text')}</p>`);\n modal.addFooterBtn(i18next.t('modals.buttons.downloadViewingActivity'), 'tingle-btn tingle-btn--primary tingle-btn--pull-right', async () => {\n modal.close();\n await this.download(ViewingActivityDownloader);\n });\n modal.addFooterBtn(i18next.t('modals.buttons.downloadRatingHistory'), 'tingle-btn tingle-btn--primary tingle-btn--pull-right', async () => {\n modal.close();\n await this.download(RatingHistoryDownloader);\n });\n modal.open();\n }",
"function ventanaModal()\n {\n \n }",
"function showModal() {\n\t$('#modalBody').empty(); // clear modal\n\tcurrencyQueue.map((item, idx) => {\n\t\tconst currenct = $(\n\t\t\t`<div class=\"modalItem p-2 d-flex align-items-center justify-content-between\">\n\t\t\t\t<div>${item.data.name}</div>\n\t\t\t\t<div>\n\t\t\t\t\t<label class=\"switch\">\n\t\t\t\t\t\t<input id=\"checked-${idx}\" class=\"checkbox-modal\" type=\"checkbox\" checked>\n\t\t\t\t\t\t<span class=\"slider\"></span>\n\t\t\t\t\t</label>\n\t\t\t\t</div>\n\t\t\t</div>`\n\t\t).appendTo('#modalBody');\n\n\t\tcurrenct.data('data', item); // append data to the element\n\t});\n\t$('#modalComponent').modal('show'); // show modal\n}",
"function showDeclineItemModal(itemObj) {\r\n\t$(\".decline-item-id\").val(itemObj.itemId);\r\n\tconsole.log(itemObj);\r\n\t$(\".decline-item-modal\").modal(\"open\");\r\n}",
"function showProject(id) {\r\n \r\n // To hold values for each different element in the modal\r\n var title;\r\n var img;\r\n var subheading;\r\n var description;\r\n var link;\r\n \r\n switch(id) {\r\n case 'project-transit':\r\n title='Lost in Transit';\r\n img='transit-modal.png';\r\n subheading='Video-game published on Steam. Developed using Gamemaker Studio 2.';\r\n description='As a solo video-game developer. I designed, programmed, and marketed Lost in Transit. I self-published the title in January 2020 on Steam.';\r\n link='https://store.steampowered.com/app/1165600/Lost_in_Transit/';\r\n break;\r\n case 'project-turntabler':\r\n title='Turntabler';\r\n img='turntabler-modal.png';\r\n subheading='Interactive website developed using Javascript, node.js, and the Spotify Web API.';\r\n description='A node.js website that dynamically creates virtual vinyl records based off what Spotify artist the user searches for. Utilized the Spotify Web API endpoints to return the data about all artists/albums.';\r\n link='http://turntabler.com/';\r\n break;\r\n case 'project-memjars':\r\n title='Memjars';\r\n img='memjars-modal.png';\r\n subheading='Social media website developed using Firebase and Javascript';\r\n description='Memjars is a social media platform used for the sole purpose to share and reminisce memories between friends, colleagues, and family. Users create <em>memory jars</em>, share them with their friends, and start filling the jars with memories, together.';\r\n link='https://github.com/sethpoly/memjars';\r\n break;\r\n }\r\n \r\n // Append the newly created HTML to the modal to view\r\n modal.innerHTML = '<div class=\"modal-content\"><div class=\"modal-header\"><span id=\"btn-close-modal\" onclick=\"closeModal()\"class=\"close\">×</span><img class=\"modal-img\" src=\"'+img+'\"></div><div class=\"modal-body\"><h3 class=\"modal-heading\">'+title+'</h3><p class=\"modal-subheading\">'+subheading+'</p><hr><p class=\"modal-description\">'+description+'</p><a href=\"'+link+'\" target=\"_blank\"><button class=\"btn-viewproject\">View project</button></a></div></div>';\r\n \r\n // Display modal\r\n setTimeout(displayModal(modal), 1);\r\n}",
"async function presentEditFeedModal( $item, langs_data ) {\n // create the modal with the `modal-page` component\n $doc.trigger('open-modal', [\n await modalController.create({\n component: 'modal-update-feed',\n componentProps: {\n 'langs' : langs_data,\n 'lang' : $item.data('lang'),\n 'id' : $item.data('id'),\n 'url' : $item.data('url'),\n 'title' : $item.find('ion-label h3 span').text(),\n 'allow_duplicates' : $item.data('allow-duplicates'),\n },\n }),\n function() {\n setTimeout(function() {\n $('#feed_title')[0].setFocus();\n }, 500);\n }\n ]);\n }",
"function initProductModal(){\n\t\tconsole.log(\"-- init my script modal --\");\n\t\t$('.catalogue-item').click(function(){\n\n\t\t\tcurrItemDataVO = $(this).data('dataVO');\n\t\t\tconsole.log(\"-- click -- \" + currItemDataVO.name);\n\t\t\t$('.modal-title').text(currItemDataVO.name);\n\t\t\t$('.modal-body .itemImage').attr(\"src\", currItemDataVO.image);\n\t\t\t$('.modal-body .itemModalDescription').text(currItemDataVO.details);\n\t\t\t$('.modal-body .itemPrice').text(currItemDataVO.price);\n\t\t\t\n\t\t\t$(\".productModal\").modal('show');\n\t\t});\n\n\t\t$('.productModal').on('show.bs.modal', function (event) {\n\t\t\t//var modal = $(this);\n\t\t\t//modal.find('.modal-title').text(\"Product Title\");\n\t\t});\n\t}",
"function openNewProjectModal() {\n\tvar $modal = $('#projectModal');\n\t$('#projectModal').modal();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detects the API version that's been requested, either from the NApiVersion header or the URL parameters. | function detectApiVersionMiddleware(req, res, next) {
const version = parseInt(req.headers["n-api-version"], 10) || parseInt(req.params.apiVersion, 10) || 0;
req.apiVersion = res.apiVersion = version;
next();
} | [
"function handleVersion(req, res, next) {\n\tvar version = req.params.version;\n\tif (validator.isValid(version, 'ApiVersion')) {\n\t\treq.api_version = version;\n\t\tnext();\n\t} else {\n\t\tvar error = {};\n\t\terror.msg = \"Bad ApiVersion: \" + req.originalUrl;\n\t\tnext(new ClientError(error));\n\t}\n}",
"function isVersionRequest(req) {\n var url = new URL(req.url);\n\n return req.method === 'GET'\n && url.pathname === '/version';\n }",
"function getAPIVersion() {\n return util.env.api ? util.env.api : defaultApi;\n}",
"function getVersion(req) {\n let version;\n if (req) {\n if (!req.version) {\n if (req.headers && req.headers['accept-version']) {\n version = req.headers['accept-version'];\n }\n } else {\n version = String(req.version);\n }\n }\n\n return version;\n}",
"function getVersion (req, header) {\n let version;\n if (!req.version) {\n if (req.headers && req.headers[header]) {\n version = req.headers[header];\n }\n } else {\n version = req.version;\n }\n return version;\n}",
"getVersion(api_url, options) {\n return this.request(api_url, 'apiinfo.version', [], options);\n }",
"isAPIVersionCompatibleWith(version) {\n let apiVersion = this._apiVersion;\n apiVersion = apiVersion.split('.').map(s => s.padStart(10)).join('.');\n version = version.split('.').map(s => s.padStart(10)).join('.');\n return version <= apiVersion;\n }",
"function versionOf(url) {\n var results = restUrlVersionMatch.exec(url);\n return results && results.length === 2 ? results[1] : false;\n }",
"function getVersion(a) {\n var secondBracket = a.url.indexOf('/', 1);\n return a.url.substring(1, secondBracket) || \"v1\";\n}",
"async handleVersionCompatibility () {\n\t\tconst versionInfo = {};\n\t\tObject.keys(this.request.query).forEach(key => {\n\t\t\tversionInfo[key] = decodeURIComponent(this.request.query[key]);\n\t\t});\n\t\tversionInfo.readFromDatabase = this.request.headers['x-cs-read-version-from-db'];\n\t\tthis.responseData = await this.module.versionInfo.handleVersionCompatibility(versionInfo);\n\t}",
"function getVersion() {\n\n var url = window.location.href.split('/');\n if (url.length === 4) {\n // no version in url, first version\n return 1;\n } else {\n return parseInt(url[url.length - 1], 10) || 1;\n }\n\n}",
"function getVersion(a) {\n return a.url.substring(1, 3) || \"v1\";\n}",
"function checkVersionParam(targetVal) {\n const { paths } = targetVal;\n const errors = [];\n if (paths && typeof paths === 'object') {\n Object.keys(paths).forEach((path) => {\n // Parameters can be defined at the path level.\n if (paths[path].parameters && Array.isArray(paths[path].parameters)) {\n const versionParam = findVersionParam(paths[path].parameters);\n if (versionParam) {\n const index = paths[path].parameters.indexOf(versionParam);\n errors.push(...validateVersionParam(versionParam, ['paths', path, 'parameters', index.toString()]));\n return;\n }\n }\n\n ['get', 'post', 'put', 'patch', 'delete'].forEach((method) => {\n if (paths[path][method]) {\n const versionParam = findVersionParam(paths[path][method].parameters);\n if (versionParam) {\n const index = paths[path][method].parameters.indexOf(versionParam);\n errors.push(...validateVersionParam(versionParam, ['paths', path, method, 'parameters', index]));\n } else {\n errors.push({\n message: 'Operation does not define an \"api-version\" query parameter.',\n path: ['paths', path, method, 'parameters'],\n });\n }\n }\n });\n });\n }\n\n return errors;\n}",
"apiVersion() {\n return this.options.apiVersion || 3;\n }",
"function getVersionFromRequest(req, param) {\r\n var result = req.params[param];\r\n result = JSCR.version({\r\n versionId : result\r\n });\r\n return result;\r\n}",
"getServerVersion() {\n const query_params = {\n key: this.apiKey\n }\n\n return fetch(BASE_URL + DOTA_VERSION + 'GetServerVersion/v1/?' + handleQueryParams(query_params))\n .then(response => responseHandler(response))\n .catch(e => e)\n }",
"static InitByAccept() {\n var removeWhitespaces = (str) => { if (typeof str === 'string') { return str.replace(/\\s/g, '') } else return '' };\n\n return (req, res, next) => {\n\n if (!req.requested_version && req && req.headers && req.headers.accept) {\n const acceptHeader = String(req.headers.accept);\n\n // First try and use method 1\n const params = acceptHeader.split(';')[1]\n const paramMap = {}\n if (params) {\n for (let i of params.split(',')) {\n const keyValue = i.split('=')\n if (typeof keyValue === 'object' && keyValue[0] && keyValue[1]) {\n paramMap[removeWhitespaces(keyValue[0]).toLowerCase()] = removeWhitespaces(keyValue[1]);\n }\n }\n req.requested_version = this.formatVersion(paramMap.version)\n }\n\n // if method 1 did not yeild results try method 2\n if (req.requested_version === undefined) {\n const header = removeWhitespaces(acceptHeader);\n let start = header.indexOf('-v');\n if (start === -1) {\n start = header.indexOf('.v');\n }\n const end = header.indexOf('+');\n if (start !== -1 && end !== -1) {\n req.requested_version = this.formatVersion(header.slice(start + 2, end));\n }\n } \n } else {\n req.requested_version = undefined;\n }\n\n next();\n }\n }",
"function validateVersionParam(param, path) {\n const errors = [];\n if (!param.required) {\n errors.push({\n message: '\"api-version\" should be a required parameter',\n path,\n });\n }\n if (param.default && !param.default.match(/^\\d\\d\\d\\d-\\d\\d-\\d\\d(-preview)?$/)) {\n errors.push({\n message: 'Default value for \"api-version\" should be a date in YYYY-MM-DD format, optionally suffixed with \\'-preview\\'.',\n path: [...path, 'default'],\n });\n }\n return errors;\n}",
"function validateHttpVersion(req){\n var versionFormat = /^HTTP\\/(\\d+.\\d+)$/;\n var versionNumberAsStr = versionFormat.exec(req.versionStr);\n if (versionNumberAsStr === null){\n throw new ValidateException(\"HTTP version must be in the format 'HTTP/x' whereas x\" +\n \" is an integer or a float number.\");\n }\n // index0 is the whole phase, index1 is the whole version number (with float if exists),\n // index2 is the floating point of the version including the \".\".\n var httpVer = parseFloat(versionNumberAsStr[1]);\n if (SUPPORTED_VERSIONS.indexOf(httpVer)=== -1){\n var supporded = '';\n for (var j=0;j<SUPPORTED_METHODS.length-1; j++){\n supporded += (SUPPORTED_METHODS[j]+', ');\n }\n supporded += SUPPORTED_METHODS[j];\n throw new ValidateException(\"HTTP version is unsupported. The server supports only: \"+supporded);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
;; camRemoveDuplicates(array) ;; ;; Remove duplicate items from an array. ;; | function camRemoveDuplicates(array)
{
var prims = {"boolean":{}, "number":{}, "string":{}};
var objs = [];
return array.filter(function(item) {
var type = typeof item;
if (type in prims)
{
return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
}
else
{
return objs.indexOf(item) >= 0 ? false : objs.push(item);
}
});
} | [
"function removeDuplicate(array) {\n\n}",
"function removeDuplicateItems(arr) {}",
"function removeDuplicates(array) {\n return array.filter((arr, index) => array.indexOf(arr) === index);\n }",
"function removeDuplicates (array) {\n\treturn array.filter( (item, index) => \n\t\tarray.indexOf(item) === index && item !== undefined );\n}",
"function removeDuplicates(array) {\n var seen = {};\n return array.filter(function(item) {\n return seen.hasOwnProperty(item) ? false : (seen[item] = true);\n });\n }",
"function unique (array) {\n\n}",
"function removeDuplicates(array) {\n var hash = {};\n var results = [];\n for(var i = 0; i < array.length; i++) {\n if(!hash[array[i]]) {\n hash[array[i]] = 1;\n results.push(array[i]);\n }\n \n }\n return results;\n \n }",
"function removeDuplicates(arr) {\n\n// ****or could do below to write it out\n// const set = new Set (arr);\n// return [...set];\n\n return [...new Set(arr)];\n}",
"function dedup(array) {\n const uniqueSet = new Set(array);\n const backToArray = [...uniqueSet];\n return backToArray;\n}",
"function dedup(array) {\n var dedupList = [...new Set(array)];\n return dedupList;\n}",
"function removeDuplicate(arr){\nvar exists = {};\nvar outArr = [];\nvar elm;\n\nfor (var i = 0; i < arr.length; i++){\n elm = arr[i];\n if (!exists[elm]){\n outArr.push(elm);\n exists[elm] = true;\n }\n}\nreturn outArr;\n}",
"function removeDupes(array){\n\tvar map ={};\n\tvar output =[];\n\n\n\tfor(var i = 0; i < array.length; i++){\n\n\t\tvar item = array[i];\n\t\tif(!map[item]){\n\t\t\tmap[item] = true;\n\t\t\toutput.push(item);\n\t\t}\n\t}\t\n\n\treturn output.sort();\n}",
"function remove_duplicates(arr) {\n+ //console.log(arr.length);\n+ arr.sort();\n+\n+ for(j=0;j<5;j++){\n+ for(i=0;i<arr.length;i++){\n+ if(arr[i]==arr[i+1]){\n+ arr.splice(i,1);\n+ }\n+ }\n+ }\n \n- console.log(\"Duplicates removed from array\");\n+ console.log(arr);\n }",
"function dedupe(array) {\n // initialize an array that holds all the non duplicate\n // iterate thru the arr\n const output = array.filter((el, idx) => idx === array.indexOf(el));\n // check if the idx of the el is equal to the output of using the indexof method with that el\n // push the el into the output array\n // return the arr\n return output;\n}",
"function dedup(array) {\n for (var i = 0; i < array.length; i++) {\n for (var j = i + 1; j < array.length; j++) {\n while (array[i] === array[j]) {\n array.splice(j, 1);\n }\n }\n }\n return array;\n}",
"function removeDuplicates(arr) {\n return new Set(arr.sort())\n}",
"function findDuplicate(array) {\n\n}",
"function dedup(array) {\n// create empty array to push to\nvar noDoops = []\n//using for loop\n for (var i = 0; i < array.length; i ++){\n // if not included in noDoops array, push to noDoops \n if(noDoops.includes(array[i]) === false){\n \n noDoops.push(array[i])\n }\n }\n//return array \nreturn noDoops\n}",
"function removeDuplicatesAndSort(array) {\n let result = array.filter((element, index, arr) => {\n return index === arr.indexOf(element)\n })\n result.sort();\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Injects socket id from the received request. | function SocketId() {
return function (object, methodName, index) {
var format = Reflect.getMetadata("design:paramtypes", object, methodName)[index];
var metadata = {
target: object.constructor,
method: methodName,
index: index,
type: ParamTypes_1.ParamTypes.SOCKET_ID,
reflectedType: format
};
index_1.defaultMetadataArgsStorage().params.push(metadata);
};
} | [
"function getSocketId() {\n const socketId = socket ? socket.id : 'none';\n\n return socketId || 'none';\n}",
"get id() {\n return this.socket.id\n }",
"registerVueRequestInterceptor() {\n Vue.http.interceptors.push((request, next) => {\n if (this.socketId()) {\n request.headers.set('X-Socket-ID', this.socketId());\n }\n next();\n });\n }",
"setSocketId(socketId)\n {\n this.socketId = socketId;\n }",
"registerSocket() {\n const { pid } = this;\n if (!pid) {\n throw new Error('The server process id is not set. Call the init() function first.');\n }\n if (this[eventSourceValue]) {\n return;\n }\n this[registerSocket](pid);\n }",
"SET_SOCKET( state, id ) {\n\n state.socket = id\n\n }",
"function connectionID(socket) {\n return socket.client.conn.id;\n}",
"registerEndpoint(request, fn : any, socket : SocketIO.Socket) {\n if (! request.endpoint_id) {\n debug('register endpoint: endpoint_id not specified');\n fn({ error: \"endpoint_id not specified\"});\n return;\n }\n\n debug(`endpoint ${request.endpoint_id} registered on socket ${socket.id}`);\n socket[\"endpoint_id\"] = request.endpoint_id;\n }",
"socketId() {\n return this.socket.id;\n }",
"setRequestId(req) {\n\n req.headers = req.headers || {};\n if (req.headers['x-request-id']) {\n return;\n }\n req.headers['x-request-id'] = this.reqId;\n\n }",
"socketId() {\n return this.connector.socketId();\n }",
"function getHostId(){\n\t\tsocket.emit('get host_id');\n\t}",
"setSocketId(socketId)\n {\n this.mapResources(resource => resource.setSocketId(socketId));\n }",
"acceptCall(socket){\r\n console.log(\"Got new connection from: \" + socket.id);\r\n id = socket.id;\r\n this.connections.push({id : socket});\r\n io.sockets[id] = socket;\r\n }",
"function RequestIdHeader(proxy) {\n /**\n * A response is about to be send to an user,\n * it's our change to add some headers :-)\n */\n proxy.on('response', function(conn) {\n conn.headers['X-Request-ID'] = conn.reqid;\n conn.headers['X-Slot-Id'] = conn.slotid || 0xff;\n conn.headers['X-Request-Time'] = (new Date - conn.started) + 'ms';\n });\n}",
"function connectionID() {\n socket.emit(\"start-game\", socket.id);\n console.log(\"connected to \" + URI);\n}",
"function makeId(collection, socket) {\n var text;\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n\n do {\n text = \"\";\n for(var i = 0; i < ID_LENGTH; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n } while (text in collection); //keep going if the id exists\n\n collection[text] = socket; //keep track of it\n if (socket) {\n socket.id = text;\n }\n return text;\n}",
"function addSocket(socket)\n\t\t{\n\t\t\tsockets[socket.getId()] = socket;\n\t\t}",
"registerAxiosRequestInterceptor() {\n axios.interceptors.request.use((config) => {\n if (this.socketId()) {\n config.headers['X-Socket-Id'] = this.socketId();\n }\n return config;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to send GCODE line in terminal | function sendGCodeLine() {
let value = state.gCodeLine;
if (!value) {
return;
}
printerInterface.sendGCodeLine({ code: value }, function (err, res) {
if (err) {
setError(err);
return;
}
state.gCodeResult = "";
if (res) {
switch (typeof res) {
case "string":
state.gCodeResult = res;
break;
case "boolean":
state.gCodeResult = res;
case "number":
state.gCodeResult = res;
case "object":
state.gCodeResult = JSON.stringify(res);
break;
default:
state.gCodeResult = "";
}
}
});
} | [
"function sendGCodeLine(event) {\n var value = _terminalInputValue;\n if (!value) {\n return;\n }\n _printerDialog.sendGCodeLine({ code: value }, function (err, res) {\n if (err) {\n setError(err);\n return;\n }\n _gcodeResult = \"\";\n if (res) {\n switch (typeof res) {\n case \"string\":\n _gcodeResult = res;\n break;\n case \"boolean\":\n case \"number\":\n //gcodeResult = res;\n case \"object\":\n _gcodeResult = JSON.stringify(res);\n break;\n default:\n _gcodeResult = \"\";\n }\n }\n\n _confirmationTerminalResults.push({\n request: value,\n response: _gcodeResult,\n date: Date()\n });\n _terminalInputValue = \"\";\n component.forceUpdate();\n });\n }",
"send(code, callback){\n this.ghci.stdin.write(code + \"\\n\", callback);\n }",
"executeCode(code){\n IpcRequester.send(GHCI, {str: code});\n }",
"function shellcode() {\n\n}",
"function sendAuthCodeCommand() {\n console.log('===', 'Send authcode command');\n client.emit('authcode', '123456');\n}",
"function sendGCode(gcode, fromInput) {\n\t\tif (gcode == \"\") {\n\t\t\treturn;\n\t\t}\n\t\tlastSentGCode = gcode;\n\n\t\t// Although rr_gcode gives us a JSON response, it doesn't provide any useful values for DWC.\n\t\t// We only need to worry about an AJAX error event, which is handled by the global AJAX error callback.\n\t\t$.ajax(ajaxPrefix + \"rr_gcode?gcode=\" + encodeURIComponent(gcode), {\n\t\t\tdataType: \"json\"\n\t\t});\n\t}",
"function sendGCode(gcode, fromInput) {\n\tlastSendGCode = gcode;\n\tlastGCodeFromInput = (fromInput != undefined && fromInput);\n\t\n\t// Although rr_gcode gives us a JSON response, it doesn't provide any results.\n\t// We only need to worry about an AJAX error event.\n\t$.ajax(\"rr_gcode?gcode=\" + encodeURIComponent(gcode), {\n\t\tdataType: \"json\"\n\t});\n}",
"sendIRCode(code) {\n this._sendTiVoCommand('IRCODE', code);\n }",
"async function sendRfCode(code) {\n\tif (isLibNode433) {\n\t\tconsole.log('Using lib rpi-433-v3...');\n\t\treturn rfEmitter.sendCode(code);\n\t}\n\n\tconsole.log('Using python...');\n\tconst cmd = `/home/pi/rf-modules/rpi-rf/rpi-rf_send -r 7 ${code}`;\n\tconst { stdout, stderr } = await exec(cmd);\n\n\tif (stderr) {\n\t\tconsole.error(`error: ${stderr}`);\n\t\treturn stderr;\n\t}\n\tconsole.log(`stdout ${stdout}`);\n\treturn stdout;\n}",
"function writeCode() {}",
"function enter() {\n process.stdout.write('\\x1b[90mpress enter to continue:\\x1b[0m ');\n}",
"function SEND_CODE(c, tree) {\n\t\tsend_bits(tree[c].fc, tree[c].dl);\n\t}",
"function keyPress(code, char) { }",
"function EfwServerBarcode() {\n}",
"function SEND_CODE(c, tree) {\n send_bits(tree[c].fc, tree[c].dl);\n }",
"function stream(){\n if (!streaming) return;\n while (true) {\n if (i == gcode.length) {\n listener.streaming(i);\n end();\n return;\n }\n if (gcode[i].trim().length == 0) i++;\n else break;\n }\n port.write(gcode[i] + '\\n', function(err) {\n console.log('line:', gcode[i]);\n if (err) {\n return console.log('Error on write: ', err.message);\n }\n });\n i++;\n listener.streaming(i);\n}",
"async sendCode(code) { throw new NotImplementedError('sendCode'); }",
"function SEND_CODE(c, tree) {\n \t\tsend_bits(tree[c].fc, tree[c].dl);\n \t}",
"sendKeyboardCode(code) {\n this._sendTiVoCommand('KEYBOARD', code);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
> DONE Return an array of Collection Objects for User requesting it | getUserCollections() {
return axios.get(`/collections`);
} | [
"function getCollection() {\n return datastore.getCollection(\"users\");\n}",
"get users() {\n return this.collection;\n }",
"async getCollectionItems(name) {\n const { fields, entries } = await this.cockpit.collectionGet(name);\n return { fields, entries, name };\n }",
"getAll() {\n return this.collection.find({}).toArray();\n }",
"getCollection() {\n return null;\n }",
"function buildCollection() {\n\n var collection = [];\n\n // Add some friends.\n [\"Sarah\", \"Tricia\", \"Joanna\", \"Kit\", \"Lisa\"].forEach(\n function iterator(name) {\n\n collection.push({\n id: ++pkey,\n name: name,\n isFriend: true,\n isEnemy: false\n });\n\n }\n );\n\n // Add some enemies.\n [\"Sam\", \"Turner\", \"Jenkins\", \"Ken\", \"Lenard\"].forEach(\n function iterator(name) {\n\n collection.push({\n id: ++pkey,\n name: name,\n isFriend: false,\n isEnemy: true\n });\n\n }\n );\n\n return ( collection );\n }",
"get collections() {\n return this._collections.custom;\n }",
"function get_collection(callback) {\n\n TRANSFER_INGEST.get_collection(sip_uuid, function (result) {\n\n if (result === null || result === undefined) {\n get_collection(callback);\n return false;\n }\n\n let obj = {};\n obj.pid = sip_uuid;\n obj.sip_uuid = sip_uuid;\n obj.is_member_of_collection = result;\n callback(null, obj);\n });\n }",
"getCollection(collection) {\n return this.connection.get(collection);\n }",
"async getUsersRequest(){\n if (!this.oid)\n await this.getOID() \n \n let usersRequest = []\n let requestOnDatabase = await db.collection('organizations').doc(this.oid).collection('userRequest').get()\n requestOnDatabase.forEach( request => { \n let userRequest = {}\n userRequest.uid = request.id\n usersRequest.push(userRequest)\n })\n return usersRequest\n }",
"get collections() { return new Promise((resolve, reject) => {\n require('./skyblock/base.js').collections().then((collections) => {\n resolve(collections)\n })\n })}",
"collect () {\n return this.getCollection()\n }",
"function createCollections() {\n return {};\n}",
"getCollection(name) {\n return this.collections.get(name);\n }",
"model() {\n return this.get('store').findAll('collection')\n .then(collections =>{\n if (collections.get('length') > 0) {\n return collections;\n } else {\n return this.get('_seedIntialCollection').perform()\n .then(() =>{\n return collections;\n });\n }\n });\n }",
"getCollection (collectionName) {\n return this.collections[ collectionName ]\n }",
"async getAllCollections() {\n try {\n const collectionsData = await this.client.getCollections();\n // Directus API doesn't support filtering collections on requests\n // so this will do\n const collections = collectionsData.data.filter(\n collection => !collection.collection.startsWith('directus_'),\n );\n return collections;\n } catch (e) {\n console.error('Error fetching Collections: ', e);\n return [];\n }\n }",
"async getCockpitCollections() {\n const collections = await this.getCollectionNames();\n return Promise.all(collections.map(name => this.getCollectionItems(name)));\n }",
"static getAll() {\n return firestore.collection(collectionPath).get();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
external fits_int64: t > bool Provides: ml_z_fits_int64 Requires: bigInt | function ml_z_fits_int64(z1) {
z1 = bigInt(z1)
if (z1.compare(bigInt("9223372036854775807")) <= 0 && z1.compare(bigInt("-9223372036854775808")) >= 0)
return 1
else
return 0
} | [
"function ml_z_fits_int32(z1) {\n return ml_z_fits_int(z1);\n}",
"function ml_z_fits_int(z1) {\n if(z1 == (z1 | 0)) return 1;\n else return 0;\n}",
"function ml_z_fits_nativeint(z1) {\n return ml_z_fits_int(z1);\n}",
"function ml_z_of_int32(i32) {\n return bigInt(i32);\n}",
"function ml_z_testbit(z,pos){\n z = bigInt(z);\n return (z.shiftRight(pos).and(bigInt(1)).toJSNumber())|0;\n}",
"function ml_z_of_int64(i64) {\n return bigInt(i64[3]).shiftLeft(48).add(bigInt(i64[2]).shiftLeft(24)).add(bigInt(i64[1]));\n}",
"function ml_z_of_int32(i32) {\n return ml_z_of_int(i32);\n}",
"function ml_z_of_int64(i64) {\n var neg = false;\n if(caml_int64_compare(i64, caml_int64_create_lo_hi(0,0)) < 0) {\n neg = true;\n i64 = caml_int64_neg(i64)\n }\n var lo = caml_int64_lo32(i64) >>> 0;\n var hi = caml_int64_hi32(i64) >>> 0;\n var x = bigInt(lo).add(bigInt(hi).shiftLeft(32));\n if(neg) { x = x.negate() };\n return ml_z_normalize(x)\n}",
"function ml_z_of_nativeint(z) {\n return ml_z_of_int(z)\n}",
"function ml_z_equal(z1, z2) {\n return bigInt(z1).equals(bigInt(z2));\n}",
"function ml_z_of_bits(z1, z2) {\n\n}",
"function ml_z_of_nativeint(z1, z2) {\n\n}",
"function ml_z_to_int64(z1) {\n z1 = bigInt(z1)\n if(!ml_z_fits_int64(z1)) {\n caml_raise_constant(caml_named_value(\"ml_z_overflow\"));\n }\n var mask = bigInt(0xffffffff)\n var lo = z1.and(mask).toJSNumber();\n var hi = z1.shiftRight(32).and(mask).toJSNumber();\n var x = caml_int64_create_lo_hi(lo, hi);\n return x;\n}",
"function ml_z_numbits(z1) {\n z1 = bigInt(z1).abs();\n var n = 0;\n var upperBound = bigInt.one;\n while (upperBound.leq(z1)) {\n n += 1;\n upperBound = upperBound.multiply(2);\n }\n return n; // 2^{n-1} <= |x| < 2^n\n}",
"function ml_z_size(z1) {\n // Claim to be a 32-bit architecture.\n return bigInt(z1).toArray(Math.pow(2, 32)).value.length;\n}",
"function ml_z_of_int(i) {\n return i | 0;\n}",
"function ml_z_perfect_square(z) {\n z = bigInt(z);\n if (z.lt(bigInt(0))) {\n return 0;\n }\n var root = bigInt(ml_z_root(z, 2));\n if (root.multiply(root).eq(z)) {\n return 1;\n }\n else {\n return 0\n };\n}",
"function ml_z_sign(z1) {\n return bigInt(z1).compare(bigInt.zero);\n}",
"function ml_z_of_bits(z1) {\n var r = bigInt.zero\n var base1 = bigInt(256);\n var base = bigInt.one;\n for(var i = 0; i < caml_ml_string_length(z1); i++){\n var d = caml_string_unsafe_get(z1,i);\n r = bigInt(base).multiply(d).add(r);\n base = bigInt(base).multiply(base1);\n }\n return ml_z_normalize(r);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get polar coordinates of each spiral point. Do this once. Based on ideal formulas. Important: theta output in degrees from base function. Convert back to radians prior to storing, to be consistent with original Pullman papers. Input: none using existing userSpiral. Return: none stored in spiralPoint. | function toPolarCoordinates(inpt) {
//Find origin point.
var xorig=(inpt[0].xpos+inpt[1].xpos)/2;
var yorig=(inpt[0].ypos+inpt[1].ypos)/2;
//First reset the original point. We have done all of the reference spiral calculations at this point, so safe.
inpt[0].r=Math.sqrt(Math.pow(inpt[0].xpos-xorig,2)+Math.pow(inpt[0].ypos-yorig,2));
//Compute theta, but adjust for the preceding point so that theta is always positively increasing.
inpt[0].theta=atanRotate(inpt[0].ypos-yorig,inpt[0].xpos-xorig);
//Now do this for all spiral points.
var pre=inpt[0].theta;
var zeroCrossing = 0;
for (var i=1; i<inpt.length;i++) {
inpt[i].r=Math.sqrt(Math.pow(inpt[i].xpos-xorig,2)+Math.pow(inpt[i].ypos-yorig,2));
var tmp=atanRotate(inpt[i].xpos-xorig,inpt[i].ypos-yorig)+360*(zeroCrossing-1);
if (tmp<pre) {
//Hit a point where we cross back over x=1,y=0. Need to add 360 degrees.
zeroCrossing++;
}
inpt[i].theta = tmp;
pre=tmp;
}
//Now convert back to radians.
for (var i=0; i<inpt.length; i++) {
inpt[i].theta=toRadian(inpt[i].theta);
}
} | [
"function calculate_interspiral(decs) {\n\t//Set up a map of arrays to keep all unique degree values.\n\tvar degreeR = new Map();\n\tfor (var i=0; i<=360; i++) {\n\t\tdegreeR[i]=[];\n\t}\n\t//Now loop through every point and put it into its group.\n\tfor (var i=0; i<userSpiral.length;i++) {\n\t\t//Convert theta from radian to degree.\n\t\tvar res=0; \n\t\t//Fix it so that anything in the quadrants below x-axis are + PI.\n\t\tif (userSpiral[i].theta<0) {\n\t\t\tres=(Math.PI+userSpiral[i].theta)+Math.PI; \n\t\t}\n\t\telse { \n\t\t\tres=userSpiral[i].theta;\n\t\t}\n\t\t//Because this is a linear transform, mod theta so we can convert back to 0 to 360 degrees. \n\t\tres = Math.round(((Math.abs(res) %(Math.PI*2)) * 180 / Math.PI));\n\t\tdegreeR[res].push(userSpiral[i].r);\t\n\t}\n\t\n\t//Now loop through entire map and gather interspiral interval values;\n\t//Implement this value as std dev / mean per Louis 2012. \n\tuserSpiral.interspiralMeans = []; \n\tfor (var k in degreeR) {\n\t\tvar mean=0; var stdev=0; var count=0; \n\t\tif (degreeR[k].length>0) {\n\t\t\tmean=(degreeR[k].reduce((a, b) => a + b) / degreeR[k].length);\n\t\t\tstdev = Math.sqrt(degreeR[k].reduce((a, b) => a + Math.pow(b-mean,2)) / degreeR[k].length);\n\t\t\tif (mean!=0) { userSpiral.interspiralMeans.push(stdev/mean); } \n\t\t}\n\t}\n\t\n\t//Now get the mean of means.\n\tmm=((userSpiral.interspiralMeans.reduce((a, b) => a + b) / userSpiral.interspiralMeans.length).toFixed(decs));\n\t//Now calculate the standard deviation. \n\tsd=Math.sqrt(userSpiral.interspiralMeans.reduce((a,b) => a + Math.pow(b-mm,2)) / userSpiral.interspiralMeans.length).toFixed(decs);\n\t//console.log(mm+\" \"+sd);\n\treturn([mm,sd]);\n}",
"function calcWigglySpiral(start_x, start_y, start_r, start_theta, distance_between_turns, wiggle_amplitude, wiggle_frequency) {\n\n // Set initial values\n var x;\n var y;\n var r = start_r;\n var theta = start_theta;\n\n // Calculate the maximum radius\n var max_r = min(max_x/2, max_y/2);\n\n // Initialize shape path array\n // This stores the x,y coordinates for each step\n var path = new Array();\n\n // Iteration counter.\n var step = 0;\n\n // Increase the denominator to get finer resolution (more instructions/longer time to plot)\n var theta_per_step = 1/300;\n\n // Continue as long as the design stays within bounds of the plotter\n // This isn't quite right yet. I need to look into the coordinate translations\n // while (r < max_r && x > width/2-max_x/2 && x < width/2+max_x/2 && y > height/2-max_y/2 && y < height/2-max_y/2) {\n while (r > 0) {\n // while (theta < 100 * TWO_PI) {\n\n // Rotational Angle (steps per rotation in the denominator)\n theta = step * theta_per_step * TWO_PI;\n\n // Decrement the radius by a set amount per rotation\n // Every full rotation the radius is reduced by the offset (distance_between_turns)\n r = start_r - distance_between_turns * (step * theta_per_step);\n\n // Optional: Decay Frequency and Amplitude\n // wiggle_frequency = 0.9999 * wiggle_frequency;\n // wiggle_amplitude = 0.99999 * wiggle_amplitude;\n\n // Add a wiggle with a constant amplitude\n // Subtract from radius so that drawing area will not be exceeded\n r = r - wiggle_amplitude * sin(wiggle_frequency * theta);\n\n // Convert polar position to rectangular coordinates\n x = start_x + (r * cos(theta));\n y = start_y + (r * sin(theta));\n\n // Add coordinates to shape array\n path[step] = [x,y];\n\n // Increment iteration counter\n step++;\n }\n\n return path;\n}",
"function makeSpiral(x1, y1, r1, r2, a1, a2, pCount = 100) {\n const points = [];\n for (let i = 0; i < pCount; i++) {\n const a = lerp(a1, a2, i / pCount);\n const r = lerp(r1, r2, i / pCount);\n const x = x1 + cos(a) * r;\n const y = y1 + sin(a) * r;\n points.push({ x, y });\n }\n console.log(points);\n return points;\n}",
"displaySpiral() {\n // Sets x and y positons of the shape so that it is displayed in spiral\n this.x = cos(this.angle) * this.spiralRadius;\n this.y = sin(this.angle) * this.spiralRadius;\n // Fills the ellipse with variabes, without stroke and displays it from the center\n fill(this.red, this.green, this.blue);\n noStroke();\n ellipseMode(CENTER);\n // Sets the width and height according to the mouse position\n this.shapeWidth = map(mouseX, 0, width, 2, 50);\n this.shapeHeight = map(mouseY, 0, height, 2, 50);\n // Display the ellipse\n ellipse(this.x, this.y, this.shapeWidth, this.shapeHeight);\n // Add speed to the angle and the spiral radius so that the shapes are displayed in spiral\n this.angle += this.speed;\n this.spiralRadius += this.speed;\n }",
"function pointOnShericalSpiral( t ) {\n\n const c = Math.atan( a * t );\n const cosC = Math.cos( c );\n\n const x = Math.cos( t ) * cosC;\n const y = Math.sin( t ) * cosC;\n const z = -Math.sin( c );\n\n\n return vec.set( x, y, z );\n\n}",
"function cartesian2Polar(point){\n var x = point[0];\n var y = point[1];\n var theta = rad2deg(Math.atan(y/x));\n \n // Q1: Use theta\n // Q2, Q3: Use theta + 180\n // Q4: Use theta + 360\n if(x < 0) theta += 180; // Handles Q2, Q3\n if(x > 0 && y < 0) theta += 360; // Handles Q4 \n \n if(x == 0){\n if(y > 0) theta = 90;\n else if(y < 0) theta = 270;\n else theta = 0;\n }\n \n return [magnitude(x,y), theta];\n}",
"function spiralGenerator(centerX, centerY, radius, coils, rotation) {\n var thetaMax = coils * 2 * Math.PI;\n\n // How far to step away from center for each side.\n var awayStep = radius / thetaMax;\n\n // distance between points to plot\n var chord = 10;\n\n // For every side, step around and away from center.\n // start at the angle corresponding to a distance of chord\n // away from centre.\n for ( var theta = chord / awayStep; theta <= thetaMax; ) {\n //\n // How far away from center\n var away = awayStep * theta;\n //\n // How far around the center.\n var around = theta + rotation;\n //\n // Convert 'around' and 'away' to X and Y.\n var x = centerX + Math.cos ( around ) * away;\n var y = centerY + Math.sin ( around ) * away;\n //\n // Now that you know it, do it.\n plotPoint( x, y );\n\n // to a first approximation, the points are on a circle\n // so the angle between them is chord/radius\n //theta += chord / away;\n\n var delta = ( -2 * away + Math.sqrt ( 4 * away * away + 8 * awayStep * chord ) ) / ( 2 * awayStep );\n\n theta += delta;\n\n chord = _.random(6, 12);\n }\n}",
"function get_angle_on_spiral(small_spiral, big_spiral) {\n // find the end points of this small spiral\n let theta = recursive_search(true, projection_formula, big_spiral, small_spiral, 0);\n let theta2 = recursive_search(false, projection_formula, big_spiral, small_spiral, Math.PI * 2);\n return Math.abs(theta) + Math.abs(theta2);\n }",
"toPolarCoords() {\n return ({\n r: Math.sqrt(this.x ** 2 + this.y ** 2),\n a: Point.angle(this),\n });\n }",
"function spiral( v ) {\n\t\t\treturn {\n\t\t\t\tx: +( Math.exp(v.x) * Math.cos(v.y) ),\n\t\t\t\ty: +( Math.exp(v.x) * Math.sin(v.y) )}\n\t\t}",
"function psi2thetaRo(psi){\n //var shift = Math.PI*2*0.3;\n var shift = 0;\n\tx = (R-r)*sin(psi+shift) \n + r2 * sin( (R-r)*psi/r - shift - pi );\n\ty = -(R-r)*cos(psi+shift)\n\t\t + r2 * cos( (R-r)*psi/r - shift - pi );\n var theta = Math.atan2(x,y);\n theta = pi - theta;\n if (theta<0){\n theta = theta + 2*pi;\n }\n var ro = Math.sqrt(x*x+y*y);\n return [theta, ro];\n}",
"function polar(rFunctionOfTheta){\n return function(parameter){\n var theta = parameter;\n var radius = rFunctionOfTheta(theta);\n return [radius * Math.cos(theta), radius * Math.sin(theta)];\n }\n}",
"function update_rotating_inspirals(big_spiral) {\n // one main spiral\n const spirals = big_spiral.children;\n if (!big_spiral.ccw)\n big_spiral.obj.rotate -= Math.PI / 200;\n else\n big_spiral.obj.rotate += Math.PI / 200;\n // let starting_u = (big_spiral.n - 2) / big_spiral.n;\n // let increment = big_spiral.increment_u;\n // for (let i = 0; i < spirals.length; i++) {\n // let u = starting_u + i * increment;\n // const small_spiral = get_spiral_in_spiral(big_spiral, u, big_spiral.obj.rotate);\n // spirals[i] = small_spiral;\n // }\n return spirals;\n\n}",
"function spiralStep(circ) {\n\ttheta = parseFloat(circ.getAttribute(\"theta\"));\n\txPos = parseFloat(circ.getAttribute(\"cx\"));\n\tyPos = parseFloat(circ.getAttribute(\"cy\"));\n\tdTheta = 0.1\n\trad = 7\n\n\tif(theta > 2 * Math.PI) {\n\t\tcirc.setAttribute(\"theta\", 0);\n\t}\n\telse {\n\t\tcirc.setAttribute(\"theta\", theta + dTheta);\n\t}\n\n\tdisplayCircle(circ, xPos + rad * Math.cos(theta), yPos + rad * Math.sin(theta));\n}",
"function computeSpiralArc(u, v, uv) {\n // Multiples of v^(1/8) as points on the spiral from 1 to v.\n var h4 = roughSqrt(v);\n var h2 = roughSqrt(h4);\n var h1 = roughSqrt(h2);\n var h3 = mul(h2, h1);\n var h5 = mul(h4, h1);\n var h6 = mul(h4, h2);\n var h7 = mul(h4, h3);\n\n return [u,\n mul(u, h1),\n mul(u, h2),\n mul(u, h3),\n mul(u, h4),\n mul(u, h5),\n mul(u, h6),\n mul(u, h7),\n uv];\n}",
"function polarToCartesian(r, theta) {\n return [r * Math.cos(theta), r * Math.sin(theta)];\n }",
"function calculateSpiralCircle(r, interp, freq) {\n var sx = 0.2 * freq * Math.cos(freq); \n var sy = 0.2 * freq * Math.sin(freq); \n\n var rev = 1024 - freq;\n var rx = 0.3 * rev * Math.cos(rev);\n var ry = 0.3 * rev * Math.sin(rev);\n \n var x = (1 - interp) * sx + interp * rx;\n var y = (1 - interp) * sy + interp * ry;\n\n return new Circle(x, y, r);\n }",
"function spiral(width) {\n this.width = width;\n \n this.x = function(t) {\n return t/(this.width) * Math.cos(t); \n };\n \n this.y = function(t) {\n return t/(this.width) * Math.sin(t) / 3;\n };\n \n this.z = function(t) {\n return -t/(this.width) * Math.sin(t)/2 + .75;\n };\n}",
"function findSpiral(real, imaginary, maxNodes, maxDistance) {\n /* returns a function that just spews out the next complex number to\n * use for the straight line walk. */\n function makeTurnLeft(d) {\n var n=[\n C.create(1, 0),\n C.create(0, 1),\n C.create(-1, 0),\n C.create(0, -1)\n ];\n\n return function() {\n return n[d++%4];\n };\n };\n\n /* Walk in the direction specified by the complex number \"direction\"\n * until you find a gaussian prime, then return that prime. */\n function walk(location, direction, maxDistance) {\n while (maxDistance--) {\n location=C.add(location, direction);\n\n if (P.isGaussianPrime(location.real, location.imaginary))\n\treturn location;\n }\n\n return false;\n }\n\n /* Some array handling stuff */\n function last(a) {\n return a[a.length-1];\n }\n\n function lastTwo(a) {\n return [a[a.length-2],\n\t a[a.length-1]];\n }\n\n function firstTwo(a) {\n return [a[0], a[1]];\n }\n\n /* This is to check whether the last two nodes in the walk match the\n * first two. If they do then we have a cycle. */\n function comparePairs(a, b) {\n return C.eq(a[0], b[0]) && C.eq(a[1], b[1]);\n }\n\n maxNodes=(typeof maxNodes === \"number\") ? maxNodes : 1000000;\n maxDistance=(typeof maxDistance === \"number\") ? maxDistance : 1000000;\n var nodeList=[];\n\n var turnLeft=makeTurnLeft(0);\n\n /* If the user's entered a non-prime starting location find the\n * first prime on the walk and pretend that's our starting\n * location. This is done purely to make detecting a cycle\n * easier. */\n if (P.isGaussianPrime(real, imaginary)) {\n nodeList.push(C.create(real, imaginary));\n }\n else {\n nodeList.push(walk(C.create(real, imaginary),\n\t\t turnLeft(),\n\t\t maxDistance));\n }\n\n /* Perform the random walk. */\n while (maxNodes--) {\n nodeList.push(walk(last(nodeList),\n\t\t turnLeft(),\n\t\t maxDistance));\n\n if (last(nodeList) === false)\n return false;\n\n if (nodeList.length > 2 &&\n\tcomparePairs(firstTwo(nodeList), lastTwo(nodeList)))\n return nodeList.slice(0, -2);\n }\n\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getCurrentBoardRowScores Find the current board scores to decide which row to go for returns: [Array] Array with the sum of row values | function getCurrentBoardRowScores() {
var winningCombination = getCurrentBoardValues();
return winningCombination.map(combination => combination.reduce(add, 0));
} | [
"function getCurrentBoardValues() {\n var board = getCurrentBoardTokenPositions();\n var winningCombinationBoardValues = [];\n\n for (var boardRow = 0; boardRow < winningCombinationIndexes.length; boardRow++) {\n var valuesBoardRow = [];\n\n for (var boardSpaceIndex = 0; boardSpaceIndex < winningCombinationIndexes[boardRow].length; boardSpaceIndex++) {\n var index = winningCombinationIndexes[boardRow][boardSpaceIndex];\n\n if (board[index] === players[0].symbol) {\n valuesBoardRow.push(players[0].scorePoints);\n } else if (board[index] === players[1].symbol) {\n valuesBoardRow.push(players[1].scorePoints);\n } else {\n valuesBoardRow.push(Number(board[index]));\n }\n\n if (boardSpaceIndex === winningCombinationIndexes[boardRow].length - 1) {\n winningCombinationBoardValues.push(valuesBoardRow);\n }\n }\n\n if (boardRow === winningCombinationIndexes.length - 1) {\n return winningCombinationBoardValues;\n }\n }\n}",
"function computeCurrentTurnScore(board) {\r\n // initialize the boundary of the board in order to compute score easily\r\n // so we need not to consider the boundary condition of the board\r\n var boardWithBoundary = [];\r\n var currentTurnScore = 0;\r\n for (var i = 0; i < gameLogic.ROWS + 2; i++) {\r\n boardWithBoundary[i] = [];\r\n for (var j = 0; j < gameLogic.COLS + 2; j++) {\r\n boardWithBoundary[i][j] = '';\r\n }\r\n }\r\n // copy board to boardWithBoundary\r\n for (var i = 0; i < board.length; i++) {\r\n for (var j = 0; j < board[i].length; j++) {\r\n boardWithBoundary[i + 1][j + 1] = board[i][j];\r\n }\r\n }\r\n // compute the score for this turn\r\n for (var i = 0; i < board.length; i++) {\r\n for (var j = 0; j < board[i].length; j++) {\r\n if (boardWithBoundary[i + 1][j + 1] !== '') {\r\n var res = computeScoreBFS(boardWithBoundary, { row: i + 1, col: j + 1, color: boardWithBoundary[i + 1][j + 1] });\r\n boardWithBoundary = res.board;\r\n currentTurnScore += res.score;\r\n }\r\n }\r\n }\r\n // clear the color in the original board\r\n for (var i = 0; i < board.length; i++) {\r\n for (var j = 0; j < board.length; j++) {\r\n board[i][j] = boardWithBoundary[i + 1][j + 1];\r\n }\r\n }\r\n return { board: board, score: currentTurnScore };\r\n }",
"function calcScore(scores) {\n\tvar sumscore = 0;\n\tfor (var i = 0; i < boardsize + 1; ++i) {\n\t\tswitch(scores[i]) {\n\t\t\tcase 2:\n\t\t\t\t// 10x the value of this card\n\t\t\t\tsumscore += 10 * i;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t// Value of the card\n\t\t\t\tsumscore += i;\n\t\t\tdefault:\n\t\t\t\t// If it's 3 or more, add in a flat 100\n\t\t\t\t// Otherwise, do nothin'\n\t\t\t\tif (scores[i] > 2) sumscore += 100;\n\t\t\t\tbreak;\n\t\t} // switch(curscore[i])\n\t} // for (var i = 0; i < boardsize + 1; ++i)\n\treturn sumscore;\n} // function calcScore(scores)",
"getBoardValue() {\n let totalValue = 0;\n //go through each square on board\n for (let column of this.grid) {\n for (let piece of column) {\n if (!piece) {\n continue;\n }\n //if square contains piece, get value\n let value = piece.getValue();\n //if piece belongs to ai, make value negative\n if (piece.color === this.aiColor) {\n value *= -1;\n }\n //add everything up\n totalValue += value;\n }\n }\n return totalValue;\n }",
"getScore({ currentPlayer, currentPlayerIsMaxPlayer }) {\n let gridScore = 0;\n let c, r;\n // Use native for loops instead of forEach because the function will need to\n // return immediately if a winning connection is found (there is no clean way\n // to break out of forEach)\n for (c = 0; c < this.columnCount; c += 1) {\n for (r = 0; r < this.rowCount; r += 1) {\n // If grid slot is empty\n if (this.columns[c][r] === undefined) {\n // Calculate the score normally assuming neither player has won yet\n gridScore += this.getIntermediateScore({ currentPlayer, currentPlayerIsMaxPlayer, c, r });\n } else {\n // Give player the maximum/minimum score if a connection of four or more\n // is found\n let winningScore = this.getWinningScore({ currentPlayer, currentPlayerIsMaxPlayer, c, r });\n if (winningScore) {\n return winningScore;\n }\n }\n }\n }\n return gridScore;\n }",
"getRowScore(boardState,row){\n let score = 0;\n let count = 0;\n for (let i = 0; i < 3; i++) {\n score+=boardState[row][i];\n count+=boardState[row][i]*boardState[row][i];\n }\n return {score:score,count:count};\n }",
"updatePlayerScore() {\n // Is there a way to avoid referencing the game object here?\n const playersRows = game.board.getPlayersRows(this);\n for (let row of playersRows) {\n row.calculateScore();\n }\n const playersScore = playersRows.reduce(function(acc, curr, index) {\n return acc + curr.score;\n }, 0);\n this.currentScore = playersScore;\n }",
"function getScores() {\n let sum = 0;\n let sub = getScore(document.getElementById('section1-subscore').innerText);\n sum += sub;\n scores.push(sub);\n sub = getScore(document.getElementById('section2-subscore').innerText);\n sum += sub;\n scores.push(sub);\n sub = getScore(document.getElementById('section3-subscore').innerText);\n sum += sub;\n scores.push(sub);\n sub = getScore(document.getElementById('section4-subscore').innerText);\n sum += sub;\n scores.push(sub);\n sub = getScore(document.getElementById('section5-subscore').innerText);\n sum += sub;\n scores.push(sub);\n scores.push(sum.toString());\n const color = colorMappings[document.getElementById('risk-level').innerText.split(' ')[0]];\n document.getElementById('risk-color').style.borderColor = color;\n}",
"computeScore() {\n const all_scores = [];\n\n GameTree.walkTree(\n this.state.gameTree,\n (node) => {\n if ('cost' in node.data.board) {\n all_scores.push(node.data.board.cost);\n }\n }\n );\n\n return all_scores.reduce((a, b) => (a + b), 0);\n }",
"function evaluateBoard(game, player)\n{\n let board = game.board()\n if(game.in_checkmate())\n {\n if (game.turn() === player)\n {\n return -1000000;\n }\n else\n {\n return 1000000;\n }\n }\n let totalScore = 0;\n // Evaluate 8*8 position on board:\n for(var i = 0; i < 8; i++)\n {\n for(var j = 0; j <8; j ++)\n {\n let piece = board[i][j];\n if (piece !== null)\n {\n let pieceValue = getPieceVal(piece);\n if(piece.color === player)\n {\n totalScore = totalScore + pieceValue;\n totalScore = totalScore + getPositionValue(piece,i,j, player);\n }\n else{\n totalScore = totalScore - pieceValue;\n totalScore = totalScore - getPositionValue(piece,i,j, player);\n }\n }\n }\n }\n return totalScore;\n}",
"addScore(rows) {\n this.score += Game.PER_SQUARE_SCORE * Game.COLUMNS * rows.length;\n this.refreshScore();\n }",
"function countScores(board) {\n var scores = {\"BLACK\":0,\"WHITE\":0};\n var maxSize = board.length;\n for (var y = 0; y < board.length; y++) {\n for (var x = 0; x < board[y].length; x++) {\n var score = 1;\n if(y == 0 || x == 0 || y == maxSize || x == maxSize){\n score = 2;\n }\n\n if(x == 0 && y == 0 || x == maxSize && y == maxSize || x == 0 && y == maxSize || x == maxSize && y == 0){\n score = 3;\n }\n\n if (board[y][x].pawn == \"WHITE\") {\n scores[\"WHITE\"] = scores[\"WHITE\"]+score;\n }else if (board[y][x].pawn == \"BLACK\") {\n scores[\"BLACK\"] = scores[\"BLACK\"]+score;\n }\n }\n }\n\n return scores;\n}",
"function getScores(boards) {\n var scores = [];\n for (var i = 0; i < boards.length; i++) {\n scores.push(boards[i] ? boards[i].getScore() : -1);\n }\n return scores;\n}",
"calScore()\n\t{\n\n\t\tfor(var v = 0; v < this._boardSize; v++)\n\t\t{\n\t\t\tif(this._Graph[v][4] === 1)\n\t\t\t\tthis._playerBlack.score += 1;\n\t\t\telse if(this._Graph[v][4] === 2)\n\t\t\t\tthis._playerWhite.score += 1;\n\t\t\telse {\n\t\t\t\tif (this._Graph[v][5] === 1)\n\t\t\t\t\tthis._playerBlack.score += 1;\n\t\t\t\telse if (this._Graph[v][5] === 2)\n\t\t\t\t\tthis._playerWhite.score += 1;\n\t\t\t}\n\t\t}\n\t\tthis._playerBlack.score -= this._playerBlack.captured;\n\t\tthis._playerWhite.score -= this._playerWhite.captured;\n\t}",
"function getScoringArray() {\n\tvar scores = Array();\n\tfor (var i = 0; i < boardsize + 1; ++i) {\n\t\tscores.push(0);\n\t} // for (var i = 0; i < boardsize + 1; ++i)\n\treturn scores;\n} // function getScoringArray()",
"function newScore(board) {\n var o_counts = counts(board, \"O\");\n var x_counts = counts(board, \"X\"); \n var score=0; \t\n for (var k=0; k<2*size+2; k++) {\n score +=newLineScore(x_counts[k], o_counts[k]);\n }\n return score;\n }",
"function getScoreValue(col, row) {\n // Value for a non-core space is just how far it is from the center row.\n // Rows above that row (with lower index) score for the bottom player,\n // and rows below it (with higher index) score for the top player.\n let score = row - MID_ROW;\n // Core spaces score more points, especially the uppermost and lowermost peaks of the board,\n // so let's figure out if it's a core space.\n if (row === 0 || row === NUM_ROWS - 1) {\n // The only spaces in these rows are the extreme tips of the board\n score += (SPAN + 2) * (score > 0 ? 1 : -1);\n } else {\n // Other core spaces are those for which the horizontal distance from the column is equal to\n // the vertical distance from the top or bottom row.\n let laterality = Math.abs(col - SPAN);\n if (laterality === row || laterality === NUM_ROWS - 1 - row) {\n score += (SPAN + 1 - laterality) * (score > 0 ? 1 : -1);\n }\n }\n return score;\n}",
"function calcGameboard() {\n\tgameboard = [];\n\t$('.gameboard .row').each(function(){\n\t\trow = [];\n\t\t$(this).find('.cell').each(function(){\n\t\t\trow.push($(this).data('cell'));\n\t\t})\n\t\tgameboard.push(row);\n\t})\n\n\treturn gameboard;\n}",
"function getScore(board) {\n var pieces = Board.getPiecesFromBoard(board);\n var startEndRows = Board.getStartEndRows(board);\n var white = getColorScore(startEndRows.white, pieces.white);\n var black = getColorScore(startEndRows.black, pieces.black);\n return {\n ended: white.won || black.won,\n white: white,\n black: black\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Vertical Timeline by CodyHouse.co | function VerticalTimeline( element ) {
this.element = element;
this.blocks = this.element.getElementsByClassName("cd-timeline__block");
this.images = this.element.getElementsByClassName("cd-timeline__img");
this.contents = this.element.getElementsByClassName("cd-timeline__content");
this.offset = 0.8;
this.hideBlocks();
} | [
"function VerticalTimeline( element ) {\r\n\t\tthis.element = element;\r\n\t\tthis.blocks = this.element.getElementsByClassName(\"cd-timeline__block\");\r\n\t\tthis.images = this.element.getElementsByClassName(\"cd-timeline__img\");\r\n\t\tthis.contents = this.element.getElementsByClassName(\"cd-timeline__content\");\r\n\t\tthis.offset = 0.8;\r\n\t\tthis.hideBlocks();\r\n\t}",
"function VerticalTimeline( element ) {\n\t\tthis.element = element;\n\t\tthis.blocks = this.element.getElementsByClassName(\"cd-timeline__block\");\n\t\tthis.images = this.element.getElementsByClassName(\"cd-timeline__img\");\n\t\tthis.contents = this.element.getElementsByClassName(\"cd-timeline__content\");\n\t\tthis.offset = 0.8;\n\t\tthis.hideBlocks();\n\t}",
"function dvTimeline (st) {\n if (st.view === \"Dvtimeline\") {\n timeline(document.querySelectorAll('.timeline'), {\n verticalStartPosition: 'right',\n verticalTrigger: '150px'\n });\n\n }\n}",
"function BMTimeline() {}",
"function showTimelineView(){\n\n syncAllChanges()\n w2ui.main_layout.content('main', '<div stlye=\"padding:10px;padding-top:30px;margin:10px\" id=\"graph\"></div>');\n var container = document.getElementById('graph');\n // Configuration for the Timeline\n var options = {};\n\n data = timeline2vis(case_data.timeline)\n if(data.length==0){\n $('#graph').html(\"No Timestamps to display. Add Timestamps to the timeline first and mark them as Visualizable\")\n }\n var dataset = new vis.DataSet(data)\n\n // Create a Timeline\n var timeline = new vis.Timeline(container , dataset, options);\n\n\n}",
"updateVerticalTimeline() {\n var self = this; // 'this' will change when we enter forEach\n this.events.forEach(function(e) {\n var prefix = e.event_type == 'release' ? 'release' : 'event';\n if (self.shouldDrawEvent(e)) {\n $(`#${prefix}_block_${e.id}`).fadeIn();\n $(`#${prefix}_block_${e.id}`).addClass(\"show-block\");\n } else {\n $(`#${prefix}_block_${e.id}`).fadeOut();\n $(`#${prefix}_block_${e.id}`).removeClass(\"show-block\");\n }\n });\n const showBlocks = document.querySelectorAll(\".show-block\");\n showBlocks.forEach((block,i)=>{\n $(block).removeClass(\"block-right\");\n if (i % 2 !== 0) {\n $(block).addClass(\"block-right\");\n }\n })\n }",
"function setUpVerticalTimeline(tl) {\n let lastVisibleIndex = 0;\n tl.items.forEach((item, i) => {\n item.classList.remove('animated', 'fadeIn');\n if (!isElementInViewport(item, tl.settings.verticalTrigger) && i > 0) {\n item.classList.add('animated');\n } else {\n lastVisibleIndex = i;\n }\n const divider = tl.settings.verticalStartPosition === 'left' ? 1 : 0;\n if (i % 2 === divider && window.innerWidth > tl.settings.forceVerticalMode) {\n item.classList.add('timeline__item--right');\n } else {\n item.classList.add('timeline__item--left');\n }\n });\n for (let i = 0; i < lastVisibleIndex; i += 1) {\n tl.items[i].classList.remove('animated', 'fadeIn');\n }\n // Bring elements into view as the page is scrolled\n window.addEventListener('scroll', () => {\n tl.items.forEach((item) => {\n if (isElementInViewport(item, tl.settings.verticalTrigger)) {\n item.classList.add('fadeIn');\n }\n });\n });\n }",
"styleTimeline() {\n this.timeline.style.position = 'absolute';\n\n if (this.props.type === 'horizontal') {\n const timelineHeight = this.timeline.offsetHeight;\n const containerHeight = this.container.offsetHeight;\n const timelineTop = ((containerHeight - timelineHeight) / containerHeight) / 2;\n this.timeline.style.top = `${timelineTop * 100}%`;\n this.timeline.style.left = 0;\n this.timeline.style.height = `${timelineHeight}px`;\n this.timeline.style.marginTop = `-${timelineHeight / 2}px`;\n } else if (this.props.type === 'vertical') {\n const timelineWidth = this.timeline.offsetWidth;\n const containerWidth = this.container.offsetWidth;\n const timelineLeft = ((containerWidth - timelineWidth) / containerWidth) / 2;\n this.timeline.style.left = `${timelineLeft * 100}%`;\n this.timeline.style.top = 0;\n this.timeline.style.width = `${timelineWidth}px`;\n this.timeline.style.marginTop = `-${timelineWidth / 2}px`;\n }\n }",
"function constructTimeLineForGivenData(items)\r\n{\r\n\t var container = document.getElementById('visualization');\r\n\t // Configuration for the Timeline\r\n\t var options = {};\r\n\t // Create a Timeline\r\n\t var timeline = new vis.Timeline(container, items, options);\r\n}",
"function Timeline() {\r\n\t/*\r\n\tImplementation Details:\r\n\r\n\tFor each piece of functionality, decide whether it belongs in setup, draw, resizeHandler,\r\n\tsliderChangedHandler or a combination of the aforementioned.\r\n\t*/\r\n\r\n\t// constants\r\n\t/*\r\n\t\tThe border on each side of the timeline. We'll need this value later when\r\n\t\tcalculating back's top offset.\r\n\t*/\r\n\tTimeline._BORDER_SIDES = 20;\r\n\tTimeline._OFFSET_LEFT = '8px';\r\n\tTimeline._OFFSET_TOP = '8px'; // top border, 8px seems to be chrome default\r\n\tTimeline._BUTTON_WIDTH = 17; // The length of the back and forward buttons\r\n\tTimeline._WIDTH_FACTOR = 2 / 3; // How much height timeline should take up\r\n\tTimeline._MAGIC_DISTANCE = '6px'; // I don't know why this number works for\r\n\t// all sizes, but it does. Maybe it has something to do with the margin\r\n\t// of eight\r\n\tTimeline._BODY_MARGINS = 8;\r\n\tTimeline._SCALE_MARGIN = 5;\r\n\r\n\r\n\t// window.height * this value is used to calculate the canvas height.\r\n\tTimeline._HEIGHT_FACTOR = 3 / 5; \r\n\r\n\t// The following constants are used in the sliderChangedHandler\r\n\t// use integers to aid in calculating latestFullHour\r\n\tTimeline._MS_PER_MINUTE = 60 * 1000;\r\n\tTimeline._MS_PER_HOUR = Timeline._MS_PER_MINUTE * 60;\r\n\tTimeline._MS_PER_DAY = Timeline._MS_PER_HOUR * 24;\r\n\tTimeline._MS_PER_WEEK = Timeline._MS_PER_DAY * 7;\r\n\tTimeline._MS_PER_MONTH = Timeline._MS_PER_WEEK * 4;\r\n\tTimeline._MS_PER_YEAR = Timeline._MS_PER_MONTH * 12;\r\n\r\n\t// How long should the length of the now tickmark be?\r\n\tTimeline._NOW_TICKMARK_HALF_LENGTH = 15;\r\n\r\n\tTimeline._MINUTE_TICKMARK_HALF_LENGTH = 5;\r\n\tTimeline._HOUR_TICKMARK_HALF_LENGTH = 10;\r\n\tTimeline._DAY_TICKMARK_HALF_LENGTH = 15;\r\n\tTimeline._WEEK_TICKMARK_HALF_LENGTH = 20;\r\n\r\n\tTimeline._START_END_BORDER = 40;\r\n\r\n\t// variables\r\n\tTimeline._id = 0; // An id wich is unique for each instance of Timeline\r\n\r\n\t// methods\r\n\tTimeline._showSettings = function (id) {\r\n\t\t$('#settings' + id).show(500).children().show();\r\n\t\t$('#showHideSettings' + id).attr('href', 'javascript:Timeline._hideSettings(' + id + ');');\r\n\t};\r\n\r\n\tTimeline._hideSettings = function (id) {\r\n\t\t$('#settings' + id).hide(500);\r\n\t\t$('#showHideSettings' + id).attr('href', 'javascript:Timeline._showSettings(' + id + ');');\r\n\t};\r\n\r\n\tTimeline._SLIDER_MIN = 0;\r\n\tTimeline._SLIDER_MAX = 100;\r\n\tTimeline._SLIDER_STEP = 1;\r\n\tTimeline._SLIDER_DEFAULT = 50;\r\n\r\n\tTimeline._BEYOND_SLIDER_MAX = 80; // this value lets us actually get past years\r\n\r\n\tTimeline._scale = function (value) {\r\n\t\tvar minIn = Timeline._SLIDER_MIN;\r\n\t\tvar maxIn = Timeline._SLIDER_MAX;\r\n\r\n\t\tvar minOut = Math.log(Timeline._MS_PER_MINUTE);\r\n\t\tvar maxOut = Math.log(Timeline._MS_PER_YEAR);\r\n\r\n\t\tvar scale = (maxOut - minOut) / (maxIn - minIn);\r\n\r\n\t\treturn Math.exp(minOut + scale * (value - minIn));\r\n\t};\r\n\r\n\t/* Here's how the timeline slider works: \r\n\tThe sliderChangedHandler detects what range the current value fits in, and adjusts the step accordingly, to allow\r\n\tfor an easier transition. The slider determines how many minutes pass between startX and endX\r\n\t*/\r\n\tTimeline._DEFAULT_RANGE_DESCRIPTION = \"Seconds\";\r\n\tTimeline._sliderChangedHandler = function (id) {\r\n\t\t// get the value from scale_slider and scale it.\r\n\t\tvar val = Timeline._scale($('#scale_slider' + id).val());\r\n\t\tvar rangeDescription = Timeline._DEFAULT_RANGE_DESCRIPTION;\r\n\r\n\t\tif (Timeline._MS_PER_MINUTE <= val && val < Timeline._MS_PER_HOUR) {\r\n\t\t\trangeDescription = 'Minutes';\r\n\t\t} else if (Timeline._MS_PER_HOUR <= val && val < Timeline._MS_PER_DAY) {\r\n\t\t\trangeDescription = 'Hours';\r\n\t\t} else if (Timeline._MS_PER_DAY <= val && val < Timeline._MS_PER_WEEK) {\r\n\t\t\trangeDescription = \"Days\";\r\n\t\t} else if (Timeline._MS_PER_WEEK <= val && val < Timeline._MS_PER_MONTH) {\r\n\t\t\trangeDescription = 'Weeks';\r\n\t\t} else if (Timeline._MS_PER_MONTH <= val) {\r\n\t\t\trangeDescription = 'Months';\r\n\t\t} \r\n\r\n\t\t// display the current range to the user\r\n\t\t$('#zoom_range' + id).text(rangeDescription);\r\n\r\n\t\tTimeline._timelines[id]._rangeInMilliseconds = val;\r\n\r\n\t\tTimeline._timelines[id]._pixelsPerMs = (Timeline._timelines[id]._endX - Timeline._timelines[id]._startX) / Timeline._timelines[id]._rangeInMilliseconds;\r\n\t};\r\n\r\n\tTimeline._msToMin = function (ms) {\r\n\t\treturn ms / (60 * 1000);\r\n\t};\r\n\r\n\tTimeline._minToMs = function (min) {\r\n\t\treturn min * (60 * 1000);\r\n\t};\r\n\r\n\tTimeline._drawTick = function (timeline, x, halflength) {\r\n\t\ttimeline._context.beginPath();\r\n\r\n\t\ttimeline._context.moveTo(x, timeline._timelineY - halflength);\r\n\t\ttimeline._context.lineTo(x, timeline._timelineY + halflength);\r\n\r\n\t\ttimeline._context.closePath();\r\n\t\ttimeline._context.stroke();\r\n\t};\r\n\r\n\tthis._labelId = 0;\r\n\tTimeline._label = function(text, x, y, callback){\r\n\t\t$('#timeline_wrapper' + this._id).append('<div id=\"label' + this._id + '_' + this._labelId + '\">' + text + '</div>');\r\n\t\t$('#label' + this._id + '_' + this._labelId)\r\n\t\t\t.css({\r\n\t\t\t\t'position': 'absolute',\r\n\t\t\t\t'left': x,\r\n\t\t\t\t'top': y,\r\n\t\t\t\t'z-index': 1\r\n\t\t\t})\r\n\t\t\t.click(callback)\r\n\t};\r\n\r\n\t// member functions\r\n\r\n\t/*\r\n\ttimeline.setup()\r\n\tCreate canvas, back and forward button, as well as slider for scale.\r\n\ttimeline_wrapper_id is the id of an element which is to contain this\r\n\tspecific timeline. \r\n\t*/\r\n\tTimeline._timelines = [];\r\n\tthis.setup = function (timeline_wrapper_id) {\r\n\r\n\t\t// add canvas\r\n\t\tthis._id = Timeline._id++; // get id, create next id for next instance\r\n\t\tthis._timeline_wrapper_id = timeline_wrapper_id;\r\n\t\t$('#' + timeline_wrapper_id).css('position', 'relative');\r\n\t\t// Thanks to css-tricks.com/absolute-positioning-inside-relative-positioning\r\n\r\n\t\t// add this to collection of timelines, so it is retrievable by id, in cases where\r\n\t\t// an event handler turns this from an instance of Timeline to an instance of event\r\n\t\t// details.\r\n\t\tTimeline._timelines[this._id] = this;\r\n\r\n\t\tthis._canvas = document.createElement('canvas');\r\n\t\tthis._canvas.setAttribute('id', 'canvas' + this._id);\r\n\t\tthis._canvas.setAttribute('width', $(window).width() - Timeline._BODY_MARGINS * 2);\r\n\t\tthis._canvas.setAttribute('height', $(window).height() - Timeline._BODY_MARGINS * 2);\r\n\t\t$('#' + timeline_wrapper_id).append(this._canvas);\r\n\r\n\t\t// add back button\r\n\t\tthis._back = document.createElement('div');\r\n\t\tthis._back.setAttribute('id', 'back' + this._id);\r\n\t\t// id's help us jquery stuff, ensuring their unique across instances\r\n\t\t// lets us potentially put several instance on the same page.\r\n\r\n\t\t$('#' + timeline_wrapper_id).append(this._back);\r\n\r\n\r\n\t\t// add forward button\r\n\t\tthis._forward = document.createElement('div');\r\n\t\tthis._forward.setAttribute('id', 'forward' + this._id);\r\n\t\t$('#' + timeline_wrapper_id).append(this._forward);\r\n\r\n\r\n\t\t// Add a settings panel\r\n\t\t/*\r\n\t\tthis._settings = document.createElement('div');\r\n\t\tthis._settings.setAttribute('id', 'settings' + this._id);\r\n\t\tthis._settings.innerText = 'Settings\\n';\r\n\t\t*/\r\n\t\t$('#' + timeline_wrapper_id).append($('<div id=\"settings_wrapper' + this._id + '\"><center><a id=\"showHideSettings' + this._id + '\" href=\"javascript:Timeline._showSettings(' + this._id + ');\">Settings</a></center></div>'));\r\n\t\t// Add some settings to the settings panel\r\n\t\t$('#settings_wrapper' + this._id).append($('<div id=\"settings' + this._id + '\"></div>'));\r\n\t\t$('#settings' + this._id).hide();\r\n\r\n\t\t// If lock_scale is set, the scale feature should disable\r\n\t\t$('#settings' + this._id).append($('<input type=\"checkbox\" id=\"lock_scale' + this._id + '\">'));\r\n\t\t// label the checkbox\r\n\t\t$('#settings' + this._id).append($('<label for=\"#lock_scale' + this._id + '\">Lock Time Zoom</label>'));\r\n\r\n\t\t$('#settings' + this._id).append($('<hr>'));\r\n\r\n\t\t// Issue 3: Add user-mechanism for changing scale\r\n\t\t/* This will be implemented using the html slider */\r\n\t\t$('#timeline_wrapper').append($('<div id=\"scale_wrapper' + this._id + '\"></div>'));\r\n\t\t$('#scale_wrapper' + this._id).text('Time Zoom: ').append(\r\n\t\t\t'<span id=\"zoom_range' + this._id + '\">' + Timeline._DEFAULT_RANGE_DESCRIPTION + '</span>'\r\n\t\t);\r\n\t\t// use SLIDER_MIN, SLIDER_MAX and SLIDER_STEP above to modify the following line of code!!!\r\n\t\t$('#scale_wrapper' + this._id).append(\r\n\t\t\t$('<input type=\"range\" id=\"scale_slider' + this._id + '\" min=\"' + Timeline._SLIDER_MIN + '\" max=\"' + (Timeline._SLIDER_MAX + Timeline._BEYOND_SLIDER_MAX) + '\" step=\"' + Timeline._SLIDER_STEP + '\" value=\"' + Timeline._SLIDER_DEFAULT + '\" onchange=\"Timeline._sliderChangedHandler(' + this._id + ');\" />')\r\n\t\t);\r\n\r\n\t\t// debug\r\n\t\t//\t\t$('#scale_wrapper' + this._id).append($('<div id=\"range\r\n\r\n\t\t/* The _resizeHandler is called to fit the Timeline on the screen.\r\n\t\tIt sets the canvas dimensions, as well as those of the back and \r\n\t\tforward buttons. General rule of thumb: If a values should change with resize,\r\n\t\tit should be calculated as part of this function.\r\n\t\t*/\r\n\t\tthis._resizeHandler = function (self) {\r\n\t\t\t// First, we clear all style so as to prevent duplicates\r\n\t\t\t$('#canvas' + self._id).removeAttr('style');\r\n\t\t\t$('#back' + self._id).removeAttr('style');\r\n\t\t\t// later we'll insert an empty style before modifying the style.\r\n\r\n\r\n\t\t\t// set canvas attributes\r\n\r\n\t\t\t// Width of canvas is window width, with space for borders either \r\n\t\t\t// side.\r\n\t\t\tvar canvas_width = $(window).width() - Timeline._BORDER_SIDES;\r\n\t\t\tvar canvas_height = $(window).height() * Timeline._HEIGHT_FACTOR;\r\n\r\n\r\n\t\t\t/* The core feature of this block is the z-index. Everything else \r\n\t\t\tis there because otherwise I can't determine the z-index. At \r\n\t\t\tleast that's what I read somewhere.\r\n\t \r\n\t\t\tThe z-index determines how overlapping elements are drawn.\r\n\t\t\tThe higher the z-index, the \"closer to the user\" the element is.\r\n\t \r\n\t\t\tIn this case, we want to draw everything on top of the canvas,\r\n\t\t\thence the lowest z-index in our application: 0.\r\n\t\t\t*/\r\n\t\t\t$('#canvas' + self._id).attr('style', '');\r\n\t\t\t// this undoes our removeAttr('style') from earlier\r\n\r\n\t\t\tself._canvas.setAttribute('width', canvas_width);\r\n\t\t\tself._canvas.setAttribute('height', canvas_height);\r\n\t\t\t$('#canvas' + self._id).css({\r\n\t\t\t\t//width: canvas_width,\r\n\t\t\t\t//height: canvas_height,\r\n\t\t\t\tborder: '1px solid', // to see what's going on\r\n\t\t\t\tposition: 'relative', // \"take canvas out of flow\"-rough quote\r\n\t\t\t\ttop: Timeline._BORDER_TOP, // seems to be the chrome default\r\n\t\t\t\tleft: Timeline._BORDER_LEFT, // ditto\r\n\t\t\t\t'z-index': 0\r\n\t\t\t});\r\n\r\n\t\t\t/* Here we define the back button's visual properties. \r\n\t\t\tWhere possible, we calculate them in terms of canvas attributes,\r\n\t\t\tto achieve a consistent layout as the browser is resized.\r\n\t\t\t*/\r\n\t\t\tvar back_left = $('#canvas' + self._id).css('left') + 'px';\r\n\t\t\t// same distance from left timeline_wrapper as canvas\r\n\r\n\t\t\t// This one is a little more difficult: An explanation will follow\r\n\t\t\t// as soon as I've figured it out myself.\r\n\t\t\tvar back_top = ((-1) * $('#canvas' + self._id).height() - 6) + 'px';\r\n\r\n\t\t\t$('#back' + self._id).attr('style', '');\r\n\t\t\t$('#back' + self._id).css({\r\n\t\t\t\t'background-color': '#336699',\r\n\t\t\t\twidth: Timeline._BUTTON_WIDTH,\r\n\t\t\t\theight: $('#canvas' + self._id).height(), // fill canvas height\r\n\t\t\t\tposition: 'absolute', // same reason as for canvas\r\n\t\t\t\tbottom: Timeline._MAGIC_DISTANCE,\r\n\t\t\t\tleft: '0px',\r\n\t\t\t\t'z-index': 1\r\n\t\t\t});\r\n\r\n\t\t\t// Now, let's define the forward code.\r\n\t\t\t// forward_left is defined by the space to the left of canvas,\r\n\t\t\t// plus the width of the canvas, minus the width of the button.\r\n\t\t\tvar forward_left = ($('#canvas' + self._id).css('left') +\r\n\t\t\t\t$('#canvas').width() -\r\n\t\t\t\tTimeline._BUTTON_WIDTH) + 'px';\r\n\t\t\tvar forward_top = back_top;\r\n\r\n\t\t\t$('#forward' + self._id).attr('style', '');\r\n\t\t\t$('#forward' + self._id).css({\r\n\t\t\t\t'background-color': '#336699',\r\n\t\t\t\twidth: Timeline._BUTTON_WIDTH,\r\n\t\t\t\theight: $('#canvas' + self._id).height(),\r\n\t\t\t\tposition: 'absolute',\r\n\t\t\t\tbottom: Timeline._MAGIC_DISTANCE,\r\n\t\t\t\tright: '2px',\r\n\t\t\t\t'z-index': 1\r\n\t\t\t});\r\n\r\n\t\t\t/* The settings panel should be centered at the top of the \r\n\t\t\ttimeline.\r\n\t\t\t*/\r\n\t\t\t$('#settings_wrapper' + self._id).css({\r\n\t\t\t\tposition: 'absolute',\r\n\t\t\t\twidth: '200px',\r\n\t\t\t\tleft: ($('#canvas' + self._id).width() - 200) / 2 + 'px',\r\n\t\t\t\ttop: '1px', // canvas border thickness, or was it timeline_wrapper?\r\n\t\t\t\t'background-color': '#99ccff',\r\n\t\t\t\t'z-index': 1\r\n\t\t\t});\r\n\r\n\t\t\t// where to draw the now tickmark\r\n\t\t\tself._initialNowX = self._canvas.width / 8;\r\n\t\t\tself._timelineY = self._canvas.height * 4 / 5 + 0.5;\r\n\r\n\t\t\t// this.draw()\r\n\r\n\t\t\tself._startX = Timeline._START_END_BORDER;\r\n\t\t\tself._endX = self._canvas.width - Timeline._START_END_BORDER;\r\n\r\n\t\t\t// call resizeHandler to sliderChangedHandler to define rangeMin and minPerPixel\r\n\t\t\tTimeline._sliderChangedHandler(self._id);\r\n\t\t};\r\n\r\n\r\n\t\tthis._resizeHandler(this);\r\n\r\n\t\tvar thisTimeline = this; // todo make this safe for multiple timelines\r\n\t\t$(window).resize(function () {\r\n\t\t\tthisTimeline._resizeHandler(thisTimeline);\r\n\t\t});\r\n\r\n\t\t// and now, finally, the timeline\r\n\t\tthis._context = this._canvas.getContext('2d'); // we'll use the context\r\n\t\t// to draw on the canvas in the draw() function.\r\n\r\n\t\t// the offset will determine the visible range of time\r\n\t\tthis._offsetT = 0; // it begins with 0\r\n\r\n\t\t// establish the startDate, endDate, so it may be used in draw\r\n\t\tthis._startDate = new Date();\r\n\t\tthis._endDate = new Date();\r\n\r\n\t\t$('#range_slider' + self._id).change(function () {\r\n\t\t\tTimeline._sliderChangedHandler(self._id);\r\n\t\t});\r\n\r\n\t\t//\t\t// use jquery.mousewheel to scroll the time zoom\r\n\t\t//\t\t$('#canvas' + self._id).mousewheel(function (event, delta) {\r\n\t\t//\t\t\talert('test');\r\n\t\t//\t\t\t$('#range_slider' + self._id).val(parseInt($('#range_slider' + self._id).val()) + delta);\r\n\t\t//\t\t});\r\n\r\n\t\t// Issue 11: Scroll nowx and recalculate startDate and endDate when back or forward are clicked\r\n\t\tthis._offset = 0;\r\n\t\tself = this;\r\n\t\t$('#back' + self._id).mouseout(function () {\r\n\t\t\tclearInterval(self._incOffsetInterval);\r\n\t\t}).mouseup(function () {\r\n\t\t\tclearInterval(self._incOffsetInterval);\r\n\t\t}).mousedown(function () {\r\n\t\t\tself._incOffsetInterval = setInterval('self._offset++;', 30);\r\n\t\t});\r\n\r\n\t\t$('#forward' + self._id).mouseout(function () {\r\n\t\t\tclearInterval(self._decOffsetInterval);\r\n\t\t}).mouseup(function () {\r\n\t\t\tclearInterval(self._decOffsetInterval);\r\n\t\t}).mousedown(function () {\r\n\t\t\tself._decOffsetInterval = setInterval('self._offset--;', 30);\r\n\t\t});\r\n\r\n\t\t\r\n\t}; // end of setup\r\n\r\n\t/*\r\n\ttimeline.draw()\r\n\tUpdate (or set for the first time) the styles of back and forward button,\r\n\tas well as the canvas.\r\n\tAssumes setup has been called.\r\n\r\n\tImplementation: \r\n\tAll times are calculated as an offset from NOW before being displayed on the timeline.\r\n\t*/\r\n\tthis.draw = function () {\r\n\t\t// calculate nowX as a function of initialNowX\r\n\t\tthis._nowX = this._initialNowX + this._offset;\r\n\r\n\t\t// let's find out what time it is.\r\n\t\tthis._nowDate = new Date();\r\n\r\n\t\tthis._context.clearRect(0, 0, this._canvas.width, this._canvas.height);\r\n\r\n\t\tvar gradient = this._context.createLinearGradient(0, 0, this._canvas.width, 0);\r\n\t\tgradient.addColorStop(0, 'orange');\r\n\t\tgradient.addColorStop(1, 'white');\r\n\t\tthis._context.fillStyle = gradient;\r\n\t\tthis._context.fillRect(0, 0, this._canvas.width, this._canvas.height);\r\n\r\n\t\tthis._context.lineWidth = 1;\r\n\t\t// draw timeline\r\n\t\tthis._context.beginPath();\r\n\t\tthis._context.moveTo(0, this._timelineY);\r\n\t\tthis._context.lineTo(this._canvas.width, this._timelineY);\r\n\t\tthis._context.closePath();\r\n\t\tthis._context.stroke();\r\n\r\n\t\t// draw tickmark for now\r\n\t\tTimeline._drawTick(this, this._nowX, Timeline._NOW_TICKMARK_HALF_LENGTH);\r\n\r\n\r\n\t\t// draw Tickmarks for start and end\r\n\t\t// start\r\n\t\tTimeline._drawTick(this, this._startX, Timeline._NOW_TICKMARK_HALF_LENGTH);\r\n\r\n\t\t// end\r\n\t\tTimeline._drawTick(this, this._endX, Timeline._NOW_TICKMARK_HALF_LENGTH);\r\n\r\n\t\t// calculate the time of startX\r\n\t\t/*\r\n\t\t* segmentTime = (segmentPixels / totalPixels) * totalTime\r\n\t\t* startTime = nowTime - segmentTime\r\n\t\t* startTime = nowTime - (segmentPixels / totalpixels * totalTime)\r\n\t\t*/\r\n\t\tvar totalPixels = this._endX - this._startX;\r\n\t\tvar segmentPixels = this._nowX - this._startX;\r\n\t\tvar startTime = this._nowDate.getTime() - Math.floor(segmentPixels / totalPixels * this._rangeInMilliseconds);\r\n\t\tthis._startDate.setTime(startTime);\r\n\r\n\t\t// calculate the time of endX\r\n\t\tvar endTime = this._nowDate.getTime() + Math.floor((this._rangeInMilliseconds / totalPixels) * (this._endX - this._nowX));\r\n\t\tthis._endDate.setTime(endTime);\r\n\t\t// Issue 7: Label startx, nowX and endx\r\n\t\tfunction drawText(text, x, y, timeline) {\r\n\t\t\ttimeline._context.beginPath();\r\n\t\t\ttimeline._context.font = '14px mono sans serif';\r\n\t\t\ttimeline._context.strokeText(text, Math.floor(x) + 0.5, Math.floor(y) + 0.5);\r\n\t\t\ttimeline._context.closePath();\r\n\t\t\ttimeline._context.stroke();\r\n\t\t}\r\n\r\n\t\tfunction formatDate(date) {\r\n\t\t\tstr = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();\r\n\t\t\treturn str;\r\n\t\t}\r\n\r\n\t\tfunction formatTime(date) {\r\n\t\t\tstr = date.getHours() + ':' + (date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes());\r\n\t\t\treturn str;\r\n\t\t}\r\n\r\n\t\tvar fontSize = 14;\r\n\t\tvar padding = 1;\r\n\t\t// startx\r\n\t\tdrawText(formatDate(this._startDate), this._startX, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH, this);\r\n\t\tdrawText(formatTime(this._startDate), this._startX, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH + fontSize, this);\r\n\t\tdrawText('past', this._startX, this._timelineY - Timeline._DAY_TICKMARK_HALF_LENGTH - padding, this);\r\n\r\n\t\t// nowX\r\n\t\tdrawText(formatDate(this._nowDate), this._nowX, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH, this);\r\n\t\tdrawText(formatTime(this._nowDate), this._nowX, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH + fontSize, this);\r\n\t\tdrawText('now', this._nowX, this._timelineY - Timeline._DAY_TICKMARK_HALF_LENGTH - padding, this);\r\n\r\n\t\t// endX\r\n\t\tvar endXtext = this._endX - this._context.measureText(formatDate(this._endDate)).width;\r\n\t\tdrawText(formatDate(this._endDate), endXtext, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH, this);\r\n\t\tdrawText(formatTime(this._endDate), endXtext, this._timelineY + Timeline._DAY_TICKMARK_HALF_LENGTH + fontSize, this);\r\n\t\tdrawText('future', endXtext, this._timelineY - Timeline._DAY_TICKMARK_HALF_LENGTH - padding, this);\r\n\r\n\t\t// Todo 9: Add tickmarks for hours, days, etc\r\n\t\t// begin by calculating the position of the latest full hour\r\n\r\n\r\n\t\tTimeline._timeToX = function (timeline, pixelsPerMs, time) {\r\n\t\t\t// calculate how many minutes are in a pixel\r\n\t\t\tvar x = timeline._nowX + (time - timeline._nowDate.getTime()) * pixelsPerMs;\r\n\t\t\treturn x;\r\n\t\t}\r\n\r\n\t\tvar latestFullHour = Math.floor(this._endDate.getTime() / Timeline._MS_PER_HOUR) * Timeline._MS_PER_HOUR;\r\n\t\tvar latestFullHourX = Timeline._timeToX(this, this._nowX, this._pixelsPerMs, latestFullHour);\r\n\r\n\t\t\r\n\t\t// calculate all hours between end and start\r\n\t\tTimeline._drawHoursRecursive = function (timeline, lastDrawnHour) {\r\n\t\t\tif (lastDrawnHour <= timeline._startDate.getTime()) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tTimeline._drawTick(timeline, Timeline._timeToX(timeline, timeline._pixelsPerMs, lastDrawnHour), Timeline._HOUR_TICKMARK_HALF_LENGTH);\r\n\r\n\t\t\tTimeline._drawHoursRecursive(timeline, lastDrawnHour - Timeline._MS_PER_HOUR);\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tTimeline._drawHoursIterative = function(timeline, latestDrawnHour){\r\n\t\t\tvar startTime = timeline._startDate.getTime();\r\n\t\t\tvar times = [];\r\n\r\n\t\t\tfor(i = latestDrawnHour; \r\n\t\t\t\ti >= startTime;\r\n\t\t\t\ti = i - Timeline._MS_PER_HOUR)\r\n\t\t\t{\r\n\t\t\t\ttimes.push(i);\r\n\t\t\t\tTimeline._drawTick(timeline, Timeline._timeToX(timeline, timeline._PIXELS_PER_MS, i), timeline._HOUR_TICKMARK_HALF_LENGTH);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tthrow new Error(\"start: \" + startTime + \" \" + times + \" \");\r\n\t\t}\r\n\r\n\t\tTimeline._drawHoursRecursive(this, latestFullHour);\r\n\t};\r\n}",
"function Timeline(x, y, width, height, start, end) {\n\tthis.posX = x;\n\tthis.posY = y;\n\tthis.width = width;\n\tthis.height = height;\n\tthis.startYear = start;\n\tthis.endYear = end;\n\tthis.segments = [];\n\tthis.pins = [];\t\t// Let's call the objects on the timeline 'pins'.\n\tthis.activePin = null;\n\tthis.plusButton = new Button(\"+\", 0, 0, 20, 20, false);\n\tthis.minusButton = new Button(\"-\", 0, 0, 20, 20, false);\n\tthis.doneButton = new Button (\"CONFIRM\", 0, 0, 50, 15, false);\n}",
"createTimeline() {\n const scenes = this.getScenes();\n const fps = this.rootConf('fps');\n const timeline = new Timeline(fps);\n timeline.annotate(scenes);\n this.timeline = timeline;\n }",
"function displayTimeline(){\n items = new vis.DataSet(dataSet);\n // Create a Timeline\n timeline = new vis.Timeline(container, items, options);\n\n timeline.on(\"doubleClick\", function(prop){\n setModalValues(prop);\n });\n\n timeline.on(\"select\", function(prop){\n displayEventInfo(prop.items[0]);\n timeline.focus(prop.items[0]);\n });\n\n timeline.on(\"click\", function(prop){\n if(prop.item == null && currentEventDisplayedId){\n displayEventInfo(false);\n }\n });\n\n timeline.on(\"rangechange\", function(prop){\n timeline.off(\"click\");\n });\n\n timeline.on(\"rangechanged\", function(prop){\n setTimeout(function(){\n timeline.on(\"click\", function(prop){\n if(prop.item == null && currentEventDisplayedId){\n displayEventInfo(false);\n }\n });\n }, 100);\n });\n\n bindTimelineButtons();\n focusNow();\n }",
"_initTimelines() {\n const overviewContainer = document.getElementById('overview');\n\n this._timeline =\n new vis.Timeline(this._timelineContainer, this._bookmarks, this._timelineOptions);\n this._centerTime = this._timeline.getCurrentTime();\n this._timeline.moveTo(this._centerTime, {\n animation: false,\n });\n\n this._timeline.addCustomTime(this._centerTime, this._timeId);\n this._timeline.on('mouseUp', this._onMouseUp.bind(this));\n this._timeline.on('mouseDown', () => this._dragDistance = 0);\n this._timeline.on('mouseMove', (e) => {this._dragDistance += Math.abs(e.event.movementX)});\n this._timeline.on('rangechange', this._timelineDragCallback.bind(this));\n this._timeline.on('rangechanged', this._timelineDragEndCallback.bind(this));\n this._timeline.on('itemover', this._itemOverCallback.bind(this));\n this._timeline.on('itemout', this._itemOutCallback.bind(this));\n\n // create overview timeline\n this._overviewTimeline =\n new vis.Timeline(overviewContainer, this._bookmarksOverview, this._overviewTimelineOptions);\n this._overviewTimeline.addCustomTime(this._timeline.getWindow().end, this._rightTimeId);\n this._overviewTimeline.addCustomTime(this._timeline.getWindow().start, this._leftTimeId);\n this._overviewTimeline.on('rangechange', this._overviewDragCallback.bind(this));\n this._overviewTimeline.on('mouseUp', this._onMouseUp.bind(this));\n this._overviewTimeline.on('mouseDown', () => this._dragDistance = 0);\n this._overviewTimeline.on(\n 'mouseMove', (e) => this._dragDistance += Math.abs(e.event.movementX));\n this._overviewTimeline.on('itemover', this._itemOverCallback.bind(this));\n this._overviewTimeline.on('itemout', this._itemOutCallback.bind(this));\n this._initialOverviewWindow(new Date(1950, 1), new Date(2030, 12));\n }",
"animateTimelines() {\n\n //master timeline\n new TimelineMax()\n .add(this.loadAnimations());\n // .add(this.landAnimations())\n }",
"function extendTimeline() {\n // node_top_offset = first_node.offsetTop - first_flexbox.offsetTop + 32\n parent_height = document.getElementsByClassName(\"timeline-container\")[0].scrollHeight - 32\n timeline.style.height = parent_height + \"px\";\n // timeline.style.marginTop = node_top_offset + \"px\"\n}",
"function createTimeline() {\n var gSportTimeLineContainer = $('<div id=\"timeline-container\"></div>')\n var homeLine = $('<div id=\"home-line\"></div>')\n var timeline = $('<div id=\"timeline\"></div>')\n var awayLine = $('<div id=\"away-line\"></div>')\n var timelineBox = $('<div id=\"timelineBox\"></div>')\n\n timelineBox.append(homeLine);\n timelineBox.append(timeline);\n timelineBox.append(awayLine);\n gSportTimeLineContainer.append(timelineBox);\n $('body').append(gSportTimeLineContainer);\n for (var i = 0; i < 9; i++) {\n var boxId = 'index-' + i;\n var indexBox = $('<div class=\"box\" id=\"' + boxId + '\"></div>')\n $('#timeline').append(indexBox);\n }\n}",
"function setUpTimelines() {\n timelines.forEach((tl) => {\n tl.timelineEl.style.opacity = 0;\n if (!tl.timelineEl.classList.contains('timeline--loaded')) {\n wrapElements(tl.items);\n }\n resetTimelines(tl);\n if (window.innerWidth <= tl.settings.forceVerticalMode) {\n tl.timelineEl.classList.add('timeline--mobile');\n }\n if (tl.settings.mode === 'horizontal' && window.innerWidth > tl.settings.forceVerticalMode) {\n setUpHorinzontalTimeline(tl);\n } else {\n setUpVerticalTimeline(tl);\n }\n tl.timelineEl.classList.add('timeline--loaded');\n setTimeout(() => {\n tl.timelineEl.style.opacity = 1;\n }, 500);\n });\n }",
"function timelineCount() {\n const containerStops = [mainProjectsContainer.offsetTop, mainContactContainer.offsetTop];\n const bodyHeight = Math.abs(document.body.getBoundingClientRect().y) +300;\n\n if (bodyHeight > containerStops[0] && bodyHeight < containerStops[1]) {\n timeline.firstElementChild.textContent = '2';\n } else if (bodyHeight > containerStops[1]) {\n timeline.firstElementChild.textContent = '3';\n } else {\n timeline.firstElementChild.textContent = '1';\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle when the list of tasks changes locally. | handleTaskListChange(tasks) {
this.saveTasks(tasks);
this.setState({tasks: tasks});
} | [
"onListContentsChanged() {\n this.generateListContents();\n this.saveTasksData();\n }",
"function changeStatus(){\n if(list){\n activeTasksCounter = 0;\n tasksStatus = !tasksStatus;\n for(let i = 0 ; i < list.length; i++){\n tasksStatus == true ? changeTaskToCompleted(list[i]) : changeTaskToActive(list[i]);\n }\n }\n updateActiveTasksCounter(); \n localStorage.setItem('tasksList', JSON.stringify(list));\n}",
"function onStatusChange(event, taskId) {\n changeTaskStatus(event.target.value, taskId);\n renderTaskList();\n}",
"onChangeStatusTaskOnServer(taskData) {\r\n console.log('Status changed');\r\n let result = this.tasks.find((a) => a.key == taskData.taskId);\r\n let position = this.tasks.indexOf(result);\r\n this.tasks[position].enableTask();\r\n this.changeStatus(position, taskData.isDone);\r\n this.tasks[position].isWaiting = false;\r\n }",
"updateTaskList() {\n if (this.taskList.selectedTask) {\n this.taskList.updateSelectedTaskSessionCount();\n this.taskList.updateStorage();\n }\n }",
"function trackTasks() {\n trackTasksFn(react);\n }",
"onTaskUpdated(task, updatedData) {\n const tasks = this.tasks.slice();\n tasks.splice(tasks.indexOf(task), 1, Object.assign({}, task, updatedData));\n this.tasksUpdated.next(tasks);\n }",
"function updateTaskList(key, ref, old, nw, page) {\n const tasks = page.getViewById(\"tasks\");\n\n tasks.items = db.tasks();\n}",
"function doStatusChangeInLocalstorage(task){\n\n \n let dataList = JSON.parse(localStorage.getItem(\"allData\"));\n\n\n for(let i = 0;i < dataList.length ; ++i){\n\n \n taskObject = dataList[i] ;\n\n if(taskObject.task == task){\n\n\n \tif(taskObject.status == \"active\")\n \t\t taskObject.status = \"completed\" ;\n else if(taskObject.status == \"completed\")\n \t taskObject.status = \"active\" ;\n\n\n dataList[i] = taskObject ;\n localStorage.setItem(\"allData\" , JSON.stringify(dataList));\n decideToShowOrHide(taskObject);\n break;\t\n }\n\n }\n\n }",
"function handleStatusChange() {\n var newProjectStatus = $(this).val();\n getJobs(newProjectStatus);\n }",
"function updateList() {\n\t\t$('#tasks').empty();\n\n\t\tvar records = taskTable.query();\n\n\t\t// Sort by creation time.\n\t\trecords.sort(function (taskA, taskB) {\n\t\t\tif (taskA.get('created') < taskB.get('created')) return -1;\n\t\t\tif (taskA.get('created') > taskB.get('created')) return 1;\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Add an item to the list for each task.\n\t\tfor (var i = 0; i < records.length; i++) {\n\t\t\tvar record = records[i];\n\t\t\t$('#tasks').append(\n\t\t\t\trenderTask(record.getId(),\n\t\t\t\t\trecord.get('completed'),\n\t\t\t\t\trecord.get('taskname')));\n\t\t}\n\n\t\t//addListeners();\n\t\t//$('#newTask').focus();\n\t}",
"handleTaskStatusChange(taskId) {\r\n const tasks = this.state.tasks.map(task => {\r\n if (task.id === taskId) {\r\n task.done = !task.done;\r\n }\r\n return task;\r\n });\r\n this.setState({\r\n tasks: tasks\r\n });\r\n }",
"refreshList() {\n\t\taxios.get('http://localhost:8080/').then(res => {\n\n\t\t\tlet doneArray = [];\n\n\t\t\tfor(let n=0; n<res.data.length; n++) {\n\t\t\t\tif(res.data[n].done === true) {\n\t\t\t\t\tdoneArray.push(res.data[n].short);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.setState({\n\t\t\t\tdoneArray: doneArray,\n\t\t\t\tnewTask: '',\n\t\t\t\ttasks: res.data\n\t\t\t});\n\t\t});\n\t}",
"function informAboutTasksChanges() {\n console.log(\"Something changed in tasks, inform categories\");\n updateInfoAfterTasksChanges();\n}",
"function updateTasks() {\n /**\n * @param {TaskDate} date \n */\n function getTasksFrom(date) {\n return allTasks.filter(task => task.day === date.getTime());\n }\n\n tasks = getTasksFrom(current);\n render();\n }",
"onTaskWasUpdated (newTask) {\n // Edit the task in the database?\n TaskActions.editTask(newTask)\n }",
"function check_if_synced(){\n if(notion_synced && todoist_synced){\n for(var title in notion_task_dict){\n if (!todoist_task_arr.includes(title)){\n if (notion_task_dict[title][0] == 0){\n todoist_synced = false;\n console.log(\"New notion page found running add_task\")\n add_task(title, notion_task_dict[title][2]);\n notion_task_dict[title][0] = 1;\n } else if (notion_task_dict[title][0] == 1){\n notion_synced = false;\n change_status_notion(notion_task_dict[title][1]);\n }\n }\n }\n }\n}",
"function updateTodo() {\n console.log(\"updating todo list in todo-tab\");\n\n panel.port.emit(\"todo-update\", USER.todoList);\n}",
"__selectedTasklistChanged(selectedTasklist, tasklists) {\n if (selectedTasklist === undefined || tasklists === undefined) {\n return;\n }\n this.set('openedTasklist', tasklists[selectedTasklist]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add new document with user information and FILE in Firestore 'requests' collection | function pushToDatabaseWithFile(name, email, message, fileURL) {
let date = getDate();
db.collection("requests")
.add({
to: "gsw2@lehigh.edu",
message: {
subject: "New CSB Capstone Request",
html:
"<div class=”body”><b>Name:</b> " +
name +
"<br><b>Email:</b> " +
email +
"<br><b>Message:</b> " +
message +
"<br><b>File Upload:</b> " +
fileURL +
"<br><b>Date:</b> " +
date +
"</div>",
},
})
.then(function (docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function (error) {
console.error("Error adding document: ", error);
});
// console.log("Successfully updated database.");
} | [
"function addPhoto(file) {\n console.log(\n \"Adding photo: %s, for user: %s\",\n file.name,\n firebase.auth().currentUser.displayName\n );\n\n var userDocRef = firebase\n .firestore()\n .collection(\"users\")\n .doc(firebase.auth().currentUser.uid);\n\n // 1. add or update user doc\n userDocRef\n .set({\n name: firebase.auth().currentUser.displayName,\n timestamp: firebase.firestore.FieldValue.serverTimestamp()\n })\n .then(function() {\n // 2. add new doc to photo collection of user\n console.log(\"User docoument set, adding photo\");\n return userDocRef\n .collection(\"photos\")\n .add({\n text: input.value,\n timestamp: firebase.firestore.FieldValue.serverTimestamp()\n })\n .then(function(photoDocRef) {\n console.log(\"Photo added, doc ID: \", photoDocRef.id);\n return photoDocRef;\n })\n .catch(function(error) {\n console.error(\"Error writing photo to database\", error);\n });\n })\n .then(function(photoDocRef) {\n // 3. add photo to cloud storage\n var metadata = {\n customMetadata: {\n photoDocId: photoDocRef.id // used by cloud storage function to udate photo with sentiment\n }\n };\n\n var extention = file.type.split(\"/\").pop();\n var filePath =\n firebase.auth().currentUser.uid +\n \"/\" +\n photoDocRef.id +\n \".\" +\n extention;\n return firebase\n .storage()\n .ref(filePath)\n .put(file, metadata)\n .then(function(fileSnapshot) {\n console.log(\"Photo uploaded to cloud storage\");\n // generate a public URL for the file\n return fileSnapshot.ref.getDownloadURL().then(url => {\n // update the photo doc with the image's URL\n console.log(\"Updating photo doc: \", photoDocRef.id);\n return photoDocRef.update({\n imageUrl: url,\n storageUri: fileSnapshot.metadata.fullPath\n });\n });\n })\n .catch(function(error) {\n console.error(\"Error uploading photo\", error);\n });\n })\n .catch(function(error) {\n console.error(\"Error writing user document to database\", error);\n })\n .then(function() {\n input.value = \"\";\n input.file = \"\";\n });\n }",
"function upload() {\n db.collection('starfish').add(starfish)\n .then((docRef) => {\n console.log('Document written with ID: ', docRef.id);\n })\n .catch((error) => {\n console.error('Error adding document: ', error);\n });\n}",
"async function addFriend(uid) {\n const currentUserData = await getCurrentUserDataAsync();\n\n db.collection('users').doc(currentUserData.id).collection('Friends').doc('sent' + uid)\n .set({\n isConfirmed: false,\n friendID: uid,\n })\n .then(() => {\n console.log(\"Document successfully written!\");\n })\n .catch((error) => {\n console.error(\"Error writing document: \", error);\n });\n const friendRef = db.collection('users').doc(uid);\n\n friendRef.set({\n newRequestsNo: firestore.FieldValue.increment(1)\n }, { merge: true });\n\n friendRef.collection('Friends').doc('received' + currentUserData.id)\n .set({\n isPending: true,\n friendID: currentUserData.id\n })\n .then(() => {\n console.log(\"Document successfully written!\");\n })\n .catch((error) => {\n console.error(\"Error writing document: \", error);\n });\n}",
"async addToAttachments(\n user: User,\n file: File,\n downloadUrl: string,\n reference: string\n ) {\n let newAttachment = new Attachment(\n \"\",\n user.uid,\n user.ra,\n \"uploaded\",\n new Date(),\n {\n name: file.name,\n size: file.size,\n type: file.format,\n originalName: file.originalName\n },\n {\n downloadUrl,\n storageReference: reference\n },\n false\n );\n\n await firestore.collection(\"attachments\").add({ ...newAttachment });\n }",
"async add() {\n /* validate data */\n if (!this.uid) throw new Error('uid was not provided');\n if (!this.username) throw new Error('username was not provided');\n if (!this.email) throw new Error('email was not provided');\n\n const newRecord = {\n email: this.email,\n username: this.username,\n profileImg: this.profileImg,\n dateadded: admin.firestore.Timestamp.now(),\n };\n\n return await User.collection.doc(this.uid).set(newRecord);\n }",
"addFileToDocument(api_id, docId, fileToDocument) {\n const promised_addFileToDocument = this.client.then((client) => {\n const payload = {\n apiId: api_id,\n documentId: docId,\n file: fileToDocument,\n 'Content-Type': 'application/json',\n };\n return client.apis['Document (Individual)'].post_apis__apiId__documents__documentId__content(\n payload,\n this._requestMetaData({\n 'Content-Type': 'multipart/form-data'\n }),\n );\n });\n\n return promised_addFileToDocument;\n }",
"addFileRef(user_id, file_info) {\n logger.log('info', 'add file', {\n user_id: user_id,\n file_info: file_info\n });\n\n return FileReference.create({\n UserID: user_id,\n Info: file_info,\n LastUpdated: new Date(),\n }).then(function (file_ref) {\n logger.log('debug', 'file reference added', file_ref.toJSON());\n return file_ref;\n }).catch(function (err) {\n logger.log('error', 'add file reference failed', err);\n return err;\n });\n }",
"function addToDb(doc) {\n var myobj = doc;\n var clientCollection = database.collection(\"clients\");\n clientCollection.insertOne(myobj, function (err, res) {\n if (err) throw err;\n console.log(\"Created new user: \" + myobj['identifier'] + doc);\n });\n}",
"addFileToDocument(api_id, docId, fileToDocument) {\n const promised_addFileToDocument = this.client.then(client => {\n const payload = {\n apiId: api_id,\n documentId: docId,\n 'Content-Type': 'application/json',\n };\n return client.apis['API Documents'].addAPIDocumentContent(\n payload,\n {\n requestBody: {\n file: fileToDocument\n }\n },\n this._requestMetaData({\n 'Content-Type': 'multipart/form-data',\n }),\n );\n });\n\n return promised_addFileToDocument;\n }",
"registerMood(rating, comment){\n this.db.collection(this.auth.currentUser.email).add({\n Date: Date.now(),\n Rate: rating,\n Comment: comment,\n \n })\n .then(function(docRef) {\n console.log(\"Document written with ID: \", docRef.id); // Get generated id for the new document\n }) \n .catch(function(error) {\n console.error(\"Error adding document: \", error);\n });\n }",
"function addItemToFirestore(data) {\n userRef.collection('items').add(data);\n}",
"function Add_Doc_WithAutoID() {\n // Collection is the table or collection of\n cloudDB\n .collection(\"Students\")\n .add({\n // This is creating a new entry in the DB\n NameOfStd: nameV,\n RollNo: Number(rollV),\n Section: secV,\n Gender: genV,\n })\n .then(function (docRef) {\n console.log(\"Document writeen with ID\", docRef.id);\n })\n .catch(function (error) {\n console.eroor(\"Error adding document\", error);\n });\n}",
"async function addUserFile(userIdIn, displayNameIn, locationIn) {\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n await db.collection('files').insertOne({\n userId: new ObjectID(userIdIn),\n displayName: displayNameIn,\n location: locationIn\n });\n await db.close();\n}",
"static addUser(user) {\n if (user.id) {\n return firestore().collection(\"users\").doc(user.id).set(user)\n .then(() => {\n console.log(\"Document successfully written!\");\n })\n .catch(error => {\n console.error(\"Error writing document: \", error);\n });\n } else {\n console.error(\"need to pass an object with existing id property\");\n }\n }",
"async function createDocument(req, res) {\n req.body = JSON.parse(JSON.stringify(req.body));\n if (!req.body.hasOwnProperty(\"userEmail\") ||\n !req.body.hasOwnProperty(\"documentName\") ||\n !req.body.hasOwnProperty(\"documentDescription\")) {\n return res.status(404).json({ success: false, message: \"user email, name or description, or document is missing.\" })\n }\n\n const userEmail = req.body.userEmail\n const documentName = req.body.documentName\n const documentDescription = req.body.documentDescription\n // Check if the userEmail is empty \n if (userEmail.trim() === '') {\n res.status(404).json({ success: false, message: 'userEmail must not be empty' });\n return\n }\n // Check if the documentName is empty \n if (documentName.trim() === '') {\n res.status(404).json({ success: false, message: 'documentName must not be empty' });\n return\n }\n // Check if the documentDescription is empty \n if (documentDescription.trim() === '') {\n res.status(404).json({ success: false, message: 'documentDescription must not be empty' });\n return\n }\n // Check if the documentId is empty \n if (req.file.id === '') {\n res.status(404).json({ success: false, message: 'initialFileId must not be empty' });\n return\n }\n\n try {\n // Check if there is an existing user.\n const user = await User.findOne({ email: userEmail })\n if (!user) return res.status(404).json({ success: false, error: \"Email is invalid\" });\n\n // Check if user already has created document with same name.\n const document = await Document.find({ documentName: documentName, email: userEmail })\n if (document.length > 0) {\n return res.status(404).json({ success: false, error: 'User already has a document with same name\\n Please create a document with unique name' });\n } else {\n // User doesn't have another document with the same name\n // Save the document entry.\n const newDocument = new Document({\n userEmail: userEmail,\n documentName: documentName,\n documentDescription: documentDescription,\n initialFileId: req.file.id,\n createdAt: new Date().toISOString(),\n user: user._id,\n lastVersionId: req.file.id\n })\n await newDocument.save();\n user.documents.push(newDocument._id)\n await user.save()\n res.status(200).json({ success: true, id: newDocument._id, message: \"Document is created successfully.\" })\n return\n }\n } catch (err) {\n res.status(404).json({ success: false, message: 'Your Document is not valid/cannot be saved. A technical error occurred. Please try again later.' })\n console.log(\"Error occurred during document creation\", err)\n return\n }\n\n}",
"function addLog(points, user_from, user_to) {\n firebase.firestore().collection('logfile').doc().set(\n {from: user_from, points: points, to: user_to, \n createdAt: firebase.firestore.FieldValue.serverTimestamp()}\n ).then(() => console.log('Log file added'))\n .catch((error) => console.error(error)) \n}",
"function addReview(store) {\n db.collection(\"Stores\").doc(store).collection(\"Reviews\").doc(firebase.auth().currentUser.displayName).set({\n id: firebase.auth().currentUser.displayName,\n Reviewer_Name: firebase.auth().currentUser.displayName,\n Reviewer_Email: firebase.auth().currentUser.email,\n Reviewer_Rating: parseInt(rating),\n Reviewer_Comment: document.getElementById(\"comment_box\").value,\n Date_Time: firebase.firestore.FieldValue.serverTimestamp()\n })\n .then(() => {\n console.log(\"Document successfully written!\");\n })\n .catch((error) => {\n console.error(\"Error adding document: \", error);\n });\n}",
"function _uploadDocument() {\r\n vm.authorizationFile = $scope.content;\r\n vm.authorizationName = vm.myFile.name;\r\n vm.myFile = { authorizationFile: vm.authorizationFile, authorizationName: vm.authorizationName };\r\n\r\n restApi.uploadDocument(vm)\r\n .success(function (data, status, headers, config) {\r\n vm.myFile.authorizationID = data;\r\n vm.documentsList.push(vm.myFile);\r\n vm.myFile = null;\r\n })\r\n\r\n .error(function (error) {\r\n // alert(\"Something went wrong. Please try again.\");\r\n vm.toggleModal(\"error\");\r\n });\r\n }",
"function insertarEntrenamiento(){\n db.collection(\"entrenamiento\").add({\n idUsuario: usuario.uid,\n nombre: \"GoogleUser\",\n equipo: \"Google Zaragoza\",\n km: 13,\n minkm: 4.45,\n dia: new Date(\"December 10, 2019\")\n })\n .then(function (docRef) {\n console.log(\"Document written with ID: \", docRef.id);\n })\n .catch(function (error) {\n console.error(\"Error adding document: \", error);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a function which adds a "lane" to the board in the given position. This lane is just a reference to the worklist used to represent it. | function addLaneDetails(position) {
return function(lane) {
$scope.board.lanes.push({
board_id: $scope.board.id,
list_id: lane.id,
position: position
});
};
} | [
"function addLaneEvent(lane) {\n myDiagram.startTransaction(\"addLane\");\n if (lane != null && lane.data.category === \"Lane\") {\n // create a new lane data object\n var shape = lane.findObject(\"SHAPE\");\n var size = new go.Size(shape.width, MINBREADTH);\n //size.height = MINBREADTH;\n var newlanedata = {\n category: \"Lane\",\n text: \"New Lane\",\n color: \"white\",\n isGroup: true,\n loc: go.Point.stringify(new go.Point(lane.location.x, lane.location.y + 1)), // place below selection\n size: go.Size.stringify(size),\n group: lane.data.group\n };\n // and add it to the model\n myDiagram.model.addNodeData(newlanedata);\n }\n myDiagram.commitTransaction(\"addLane\");\n }",
"function addShip (ship, boardCoord, board) {\n\n}",
"function createLane(name: string): IAction {\n return {\n type: actionTypes.CREATE_LANE,\n payload: {\n id: uuid.v4(),\n name,\n notes: [],\n },\n };\n}",
"function addBoard(board, position) {\n var move = turnPlayer(board);\n var newBoard = [];\n for (var i = 0; i < board.length; i++) {\n if (i === position) {\n newBoard.push(move);\n }\n else {\n newBoard.push(board[i]);\n }\n }\n return newBoard;\n}",
"function createLane(laneNumber) {\n // Create a DOM node for the lane\n let laneNode = document.createElement('div');\n // Set the lane properties\n laneNode.classList.add('lane');\n laneNode.setAttribute('lane-number', laneNumber);\n laneNode.setAttribute('lane-type', lanes[laneNumber].laneType || 'RACE');\n // Set interval nodes in the lane\n createIntervalsOnNode(laneNode);\n // Duplicate lane for starting area\n let startingLaneNode = laneNode.cloneNode();\n // Create start gate in start lane\n createStartGate(startingLaneNode);\n // Insert the lane in the DOM\n startContainer.appendChild(startingLaneNode);\n lanesContainer.appendChild(laneNode);\n}",
"function addToBoard(cssclass, position, clickHandler) {\n var container = $(\"#pieces\").get(0);\n var square = addPiece(container, position, cssclass, PIECE_MARGIN);\n square.onclick = clickHandler;\n }",
"function CreateLane()\n{\n\t// If we have a victory lane and we passed the needed number of lanes, create the victory lane.\n\tif ( victoryLane && lanesToVictory > 0 && lanesCreated >= lanesToVictory )\n\t{\n\t\tInstantiate( victoryLane, Vector3(nextLanePosition,0,0), Quaternion.identity);\n\t}\n\telse //Othewise, create a random lane from the list of available lanes\n\t{\n\t\t//Choose a random lane from the list\n\t\tvar randomLane:int = Mathf.Floor(Random.Range(0, lanesList.Length));\n\t\t\n\t\t//Create a random lane from the list of available lanes\n\t\tvar newLane = Instantiate( lanesList[randomLane].laneObject, Vector3(nextLanePosition,0,0), Quaternion.identity);\n\t\t\n\t\tif ( Random.value < lanesList[randomLane].itemChance )\n\t\t{ \n\t\t\tif ( dropInSequence == true ) \n\t\t\t{\n\t\t\t\tif ( currentDrop < objectDropList.Length - 1 ) currentDrop++;\n\t\t\t\telse currentDrop = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentDrop = Mathf.FloorToInt(Random.Range(0, objectDropList.Length));\n\t\t\t}\n\t\t\t\n\t\t\tvar newObject = Instantiate( objectDropList[currentDrop] );\n\t\t\t\n\t\t\tnewObject.position = newLane.position;\n\t\t\t\n\t\t\tnewObject.position.z += Mathf.Round(Random.Range(-objectDropOffset,objectDropOffset));\n\t\t}\n\t\t\n\t\t//Go to the next lane position, based on the width of the current lane\n\t\tnextLanePosition += lanesList[randomLane].laneWidth;\n\t}\n\t\n\tlanesCreated++;\n}",
"addTile(tile, wallSize) {\n this.currentGame.turn++;\n this.currentGame.wallSize = wallSize;\n this.tiles.push(tile);\n this.ai.tracker.gained(this.currentGame.position, tile);\n this.ai.updateStrategy();\n this.discardTile(true);\n }",
"appendCar(vehicle, lane){\n\n // add to the vehicle storage array\n Vehicle.tags.push(vehicle)\n\n let y_coord = this.BOTTOM_EDGE - lane.height*40 - 20\n let x_coord\n\n this.tag.appendChild(vehicle)\n\n if(lane.direction === \"east\"){\n x_coord = -60\n vehicle.style.transform = 'rotate(180deg)';\n }else{\n x_coord = this.WIDTH + 5\n }\n\n vehicle.style.left = `${x_coord}px`\n vehicle.style.top = `${y_coord}px`\n\n }",
"function createlane(y,x){\nif(lane4[y][x] == player){\n //Define playerposition as y,x where the value of y is y and the value of x is x.\n playerposition = {y:y,x:x};\n ctx4.fillStyle = \"brown\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}else if(lane4[y][x] == wall){\n ctx4.fillStyle =\"black\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}else if(lane4[y][x] == walk){\n ctx4.fillStyle = \"#C6F68D\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}else if(lane4[y][x] == goal){\n ctx4.fillStyle = \"orange\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}else if(lane4[y][x] == poison){\n ctx4.fillStyle = \"red\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}else if(lane4[y][x] == points){\n ctx4.fillStyle = \"yellow\";\n ctx4.fillRect(x*tilesize, y*tilesize, tilesize, tilesize);\n}\n}",
"function sendPlayerToLane(player,laneFrom, laneTo, callback){\n var playersOnThisLane = new Array();\n var laneCoords;\n var colors = ['red', 'blue'];\n\tfor (var a in colors){\n\t\tvar color = colors[a];\n if(color==player.team){ \n for(var i in players[color]){\t\t\n if(players[color][i].lane==laneTo){\n\t\t\t\t\t//Get a list of player of your team already on the lane you are sending the player\n playersOnThisLane.push(players[color][i]); \n }\n }\n\t\t\t//Get position of the lane to go to\n if(laneTo=='base' && color==\"blue\"){laneCoords = baseBlueSideCoord;}\n else if(laneTo=='top' && color==\"blue\"){laneCoords = toplaneBlueSideCoord;}\n else if(laneTo=='mid' && color==\"blue\"){laneCoords = midlaneBlueSideCoord;}\n else if(laneTo=='bot' && color==\"blue\"){laneCoords = botlaneBlueSideCoord;}\n else if(laneTo=='base' && color==\"red\"){laneCoords = baseRedSideCoord;}\n else if(laneTo=='top' && color==\"red\"){laneCoords = toplaneRedSideCoord;}\n else if(laneTo=='mid' && color==\"red\"){laneCoords = midlaneRedSideCoord;}\n else if(laneTo=='bot' && color==\"red\"){laneCoords = botlaneRedSideCoord;}\n \n if(laneTo == 'base'){ \n\t\t\t //How to display them on the lane depending on the amount of players already on the lane\t\t\n switch (playersOnThisLane.length){ \n case 0: \n //moveElementToXY(player, laneCoords[0], laneCoords[1], 50, 50, 0, callback); \n player.DOMElement.style.marginLeft = laneCoords[0] + 'px';\n player.DOMElement.style.marginTop = laneCoords[1] + 'px';\n callback(player);\n break; \n case 1:\n //moveElementToXY(player, laneCoords[0]-25, laneCoords[1]-25, 50, 50, 0, callback);\n player.DOMElement.style.marginLeft = laneCoords[0]-25 + 'px';\n player.DOMElement.style.marginTop = laneCoords[1]-25 + 'px';\n callback(player); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]+25, laneCoords[1]+25, null, null, null, null); \n break; \n case 2: \n //moveElementToXY(player, laneCoords[0]-12, laneCoords[1]-25, 50, 50, 0, callback); \n player.DOMElement.style.marginLeft = laneCoords[0]-12 + 'px';\n player.DOMElement.style.marginTop = laneCoords[1]-25 + 'px';\n callback(player); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]+12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0], laneCoords[1]+25 ,null, null, null, null); \n break; \n case 3:\n //moveElementToXY(player, laneCoords[0]-25, laneCoords[1]-25, 50, 50, 0, callback); \n player.DOMElement.style.marginLeft = laneCoords[0]-25 + 'px';\n player.DOMElement.style.marginTop = laneCoords[1]-25 + 'px';\n callback(player); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-25, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+25, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0]+25, laneCoords[1]+25 ,null, null, null, null); \n break; \n case 4:\n //moveElementToXY(player, laneCoords[0], laneCoords[1], 50, 50, 0, callback); \n player.DOMElement.style.marginLeft = laneCoords[0] + 'px';\n player.DOMElement.style.marginTop = laneCoords[1] + 'px';\n callback(player); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0]-12, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[3], laneCoords[0]+12, laneCoords[1]+25 ,null, null, null, null); \n break; \n }\n } else {\n switch (playersOnThisLane.length){ \n case 0: \n moveElementToXY(player, laneCoords[0], laneCoords[1], null, null, null, callback); \n break; \n case 1: \n moveElementToXY(player, laneCoords[0]-25, laneCoords[1]-25, null, null, null, callback); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]+25, laneCoords[1]+25, null, null, null, null); \n break; \n case 2: \n moveElementToXY(player, laneCoords[0]-12, laneCoords[1]-25, null, null, null, callback); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]+12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0], laneCoords[1]+25 ,null, null, null, null); \n break; \n case 3:\n moveElementToXY(player, laneCoords[0]-25, laneCoords[1]-25, null, null, null, callback); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-25, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+25, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0]+25, laneCoords[1]+25 ,null, null, null, null); \n break; \n case 4:\n moveElementToXY(player, laneCoords[0], laneCoords[1], null, null, null, callback); \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0]-12, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[3], laneCoords[0]+12, laneCoords[1]+25 ,null, null, null, null); \n break; \n }\n } \n\t\t\t//Get a list of player of your team already on the lane the player is coming from\n playersOnThisLane = new Array();\n for(var i in players[color]){\t\t\n if(players[color][i].lane==laneFrom && players[color][i]!=player ){\n playersOnThisLane.push(players[color][i]) \n }\n }\n //Get position of the lane tthe player is from\n if(laneFrom=='base' && color==\"blue\"){laneCoords = baseBlueSideCoord;}\n else if(laneFrom=='top' && color==\"blue\"){laneCoords = toplaneBlueSideCoord;}\n else if(laneFrom=='mid' && color==\"blue\"){laneCoords = midlaneBlueSideCoord;}\n else if(laneFrom=='bot' && color==\"blue\"){laneCoords = botlaneBlueSideCoord; }\n else if(laneFrom=='base' && color==\"red\"){laneCoords = baseRedSideCoord;}\n else if(laneFrom=='top' && color==\"red\"){laneCoords = toplaneRedSideCoord;}\n else if(laneFrom=='mid' && color==\"red\"){laneCoords = midlaneRedSideCoord;}\n else if(laneFrom=='bot' && color==\"red\"){laneCoords = botlaneRedSideCoord; }\n \n //How to display them on the lane depending on the amount of players already on the lane\t\n switch (playersOnThisLane.length){\n case 0:\n break; \n case 1: \n moveElementToXY(playersOnThisLane[0], laneCoords[0], laneCoords[1] ,null, null, null, null); \n\t\t\t\t\t //console.log\t(playersOnThisLane[0].name + \" \" + laneCoords[0] + \" \" + laneCoords[1]);\n break; \n case 2: \n moveElementToXY(playersOnThisLane[0], laneCoords[0]+25, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]-25, laneCoords[1]-25 ,null, null, null, null); \n break; \n case 3: \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+12, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0], laneCoords[1]+25 ,null, null, null, null); \n break; \n case 4: \n moveElementToXY(playersOnThisLane[0], laneCoords[0]-25, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[1], laneCoords[0]+25, laneCoords[1]-25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[2], laneCoords[0]-25, laneCoords[1]+25 ,null, null, null, null); \n moveElementToXY(playersOnThisLane[3], laneCoords[0]+25, laneCoords[1]+25 ,null, null, null, null); \n break; \n } \n }\n }\n\t//Callback function\n player.lane=laneTo; \n //if (typeof callback === \"function\") { \n // callback(player);\n //}\n}",
"function mxLeanFifoLane(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}",
"placeNewPiece(algPos, type, set) {\n const arrPos = this.constructor.parseToArrPosition(algPos)\n this.board.placePiece(type, arrPos, set)\n }",
"function addToBoard(block, x, y, state) {\n blockPartsEach(block, x, y, state, function(x, y) {\n court[y] = court[y] || [];\n court[y][x] = block;\n });\n // get the next piece\n getNextPiece();\n }",
"addPositionedNode(position) {\n this.positions[this.numVertices] = position;\n return this.addNode();\n }",
"add(piece){\n this.stack[3 - piece.size] = piece;\n }",
"addPieceToTile(tile,piece){\n tile.setPieceOnTile(piece);\n }",
"function addManueversToPanel(route) {\n\t\tvar nodeOL = document.createElement('ol');\n\n\t\tnodeOL.style.fontSize = 'small';\n\t\tnodeOL.style.marginLeft = '5%';\n\t\tnodeOL.style.marginRight = '5%';\n\t\tnodeOL.className = 'directions';\n\n\t\troute.sections.forEach((section) => {\n\t\t\tsection.actions.forEach((action, idx) => {\n\t\t\t\tvar li = document.createElement('li'),\n\t\t\t\t\tspanInstruction = document.createElement('span');\n\n\t\t\t\tspanInstruction.innerHTML = section.actions[idx].instruction;\n\t\t\t\tli.appendChild(spanInstruction);\n\n\t\t\t\tnodeOL.appendChild(li);\n\t\t\t});\n\t\t});\n\n\t\t$('#outputDirections').append(nodeOL);\n\t}",
"function addWall(line) {\n sceneVisibleLines.push(line);\n sceneHitboxLines.push(line);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds 'buttons' based on array size divided by number of students to show | function buttonController(allStudents){
let colorLinks;
$('.pagination').children().remove();
for (let j = 0; j < allStudents.length / studentsPerPage ; j ++ ){
($('.pagination').append(`<li><a> ${(j + 1)} </a></li>`));
// Finds the current page number element
if (j == currentPage)
{
colorLinks = $('.pagination').children().children()[j]
};
//Colours the element
$(colorLinks).addClass('active')
}
} | [
"function loadStudents(x) {\nhideStudents();\nlet studentsPage = students.slice((x-1) * 10, x * 10);\n for (var i = 0; i < studentsPage.length; i++) {\n studentsPage[i].style.display='';\n }\n}",
"function displayNav() {\n var studentNames = [];\n for (var i = 0; i < roster.length; i++) {\n studentNames[i] = '<button class=\"student_buttons\" onclick=\"changeStudent(' + i + ')\">' +\n roster[i].first_name + ' ' + roster[i].last_name + '</button>';\n }\n if (debug) {\n console.log('Student names: ' + studentNames);\n }\n //event listeners for each button\n $('#studentButtons').html(studentNames);\n $('#back').click(back);\n $('#forward').click(forward);\n}",
"function renderButtons() {\n //delete dierctor buttons before adding new.//\n $(\"#director-view\").empty();\n //looping through the array.//\n for (var i = 0; i < director.length; i++) {//generate buttons for each director in array//\n var a = $('<button>');\n\n //add a class!\n a.addClass('director');\n\n //adding data-attribute with value of director index i//\n a.attr('data-name', director[i]);\n\n //button text w value of director at index i//\n a.text(director[i]);\n\n $(\"#director-view\").append(a);\n }\n\n s = $(\"#director-input\").focus();\n }",
"function appendPageLinks(totalPages) {\r\n\tlet parentDiv = document.querySelector(\".page\");\r\n\tfor(let i = 0; i<totalPages; i++) {\r\n\t\tlet button = document.createElement(\"button\");\r\n\t\tbutton.innerHTML = i+1;\r\n\t\tbutton.className = \"pageButton\"\r\n\t\t\r\n\t\tbutton.style.margin = \"10px\"\r\n\t\tbutton.addEventListener(\"click\", () => {\r\n\t\t\tcurrentPage = i+1\r\n\t\t\tshowPage(studentsList, i+1)\r\n\t\t\ttoggleButton()\r\n\t\t});\r\n\t\t\r\n\t\tparentDiv.appendChild(button);\r\n\t}\t\r\n}",
"function displayButtons() {\n \n // >> clears button-area and generates/re-generates\n $(\"#button-area\").empty();\n \n // a button for every item in the nameArray\n for (let i = 0; i < nameArray.length; i++) {\n var arr = nameArray[i];\n \n // creates the button element\n var mkBut = $(\"<button>\");\n \n // adds the name-button class to each\n mkBut.addClass(\"name-button\");\n \n // adds name attribute to each\n mkBut.attr(\"data-name\", arr);\n \n // adds text to each\n mkBut.text(arr);\n \n // adds the buttons to the button-area div\n $(\"#button-area\").append(mkBut);\n \n }\n }",
"function showFirstTen() {\n for (let i = 0; i < eachStudent.length; i++) {\n if (i < studentsPerPage) {\n eachStudent[i].style.display = '';\n } else {\n eachStudent[i].style.display = 'none';\n }\n }\n}",
"function renderButtons() {\n\n // Deleting the genres prior to adding new genres\n $(\"#buttons-view\").empty();\n \n // Looping through the array of movie genres\n for (var i = 0; i < topics.length; i++) {\n\n // Dynamicaly generating buttons for each movie genre in the array\n var a = $(\"<button>\");\n // Adding a class of genre-btn to our button\n a.addClass(\"genre-btn\");\n // Adding a data-attribute\n a.attr(\"data-name\", topics[i]);\n // Providing the initial button text\n a.text(topics[i]);\n // Adding the button to the buttons-view div\n $(\"#buttons-view\").append(a);\n }\n }",
"function buttonCreation () {\n\tfor (var j=1; j<=pagesNumber; j=j+1){\n \t\tif (j === 1) {\n\t\t\t$(\"h2\").append(\"<h4 class='groupNumber'><p>Choose a Button to Get Group of \"+ studentsPerPage +\" Students</p></h4><br>\")\n\t\t\t$(\"h4\").append(\"<br>\");\n\t\t\t$(\"h4\").append(\"<div class='one'></div>\");\n\t\t\t$(\"div.one\").append(\"<button class='grouping' value=\"+j+\">\"+\"1 to 10\"+\"</button>\");\n \t\t} else if (j !== pagesNumber) {\n\t\t\t$(\"div.one\").append(\"<button class='grouping' value=\"+j+\">\"+(1+(j-1)*10)+\" to \"+j*10+\"</button>\");\n \t\t} else {\n \t\t\t$(\"div.one\").append(\"<button class='grouping' value=\"+j+\">\"+(1+(j-1)*10)+\" to \"+j*10+\"</button>\");\n \t\t};\n\t};\n}",
"function showFirstTen() {\n for (let i = 0; i < perStudent.length; i++) {\n if (i < studentsPerPage) {\n perStudent[i].style.display = '';\n } else {\n perStudent[i].style.display = 'none';\n }\n }\n}",
"function renderButtons() {\n\n // Clearning the #buttons div prior to adding new items\n $(\"#buttons\").empty();\n\n // Looping through the summerArray\n for (var i = 0; i < summerArray.length; i++) {\n\n var newButton = $(\"<button>\");\n newButton.addClass(\"btn btn-info\");\n newButton.addClass(\"summerBtn\");\n newButton.attr(\"data-name\", summerArray[i]);\n newButton.text(summerArray[i]);\n $(\"#buttons\").append(newButton);\n }\n }",
"function renderButtons (){\n //first clear the topics div so that we dont get duplicates of buttons\n $(\"#topics-div\").empty();\n //For loop to run through full lenght of array\n for (var i = 0; i < topics.length; i++) {\n //create empty button var\n var button = $(\"<button class='btn'>\");\n //give it the class of topic\n button.addClass(\"topic\")\n //give it the value of relatid topic by attributing the title index of button\n button.attr(\"data-topic\", topics[i]);\n //set the text for button to be topic index\n button.text(topics[i]);\n //add it to the topic div in html\n $(\"#topics-div\").append(button);\n }\n\n}",
"function activateAll() {\r\n let lastIndex = currentPageNb * nbStudentsPerPage;\r\n let firstIndex = lastIndex - nbStudentsPerPage;\r\n\r\n for(i = 0; i < totalStudents; i++) {\r\n if (i >= firstIndex && i < lastIndex) {\r\n studentItemLI[i].style.display = '';\r\n } else {\r\n studentItemLI[i].style.display = 'none';\r\n }\r\n }\r\n}",
"function showPage(){\n\n let pageSelected = document.querySelector('.pagination'); \n pageSelected.addEventListener('click',(e) =>{\n document.querySelector('h2').textContent='STUDENTS';\n e.preventDefault();\n let selected = parseInt(e.target.textContent);\n const last = (selected * 10)-1;\n const first = (selected * 10) - numberStudents;\n\n for (let i = 0; i < students.length ; i++){\n\n if(i < first || i > last)\n {\n students[i].style.display = 'none';\n\n }else\n {\n students[i].style.display = 'block';\n } \n }\n });\n}",
"function display_students(current_page, students_to_display) {\n\n\tlet total_students = students_to_display.length;\n\n\tlet offset = (current_page - 1) * students_per_page;\n\toffset + students_per_page <= total_students ? numberOfStudentsToDisplay = students_per_page : numberOfStudentsToDisplay = total_students - offset ;\n\n\tfor(let i=offset; i < offset + numberOfStudentsToDisplay; i++){\n\t\tstudents_to_display[i].style.display = 'block';\n\t}\n}",
"function makeList() {\n numberOfRecPages = Math.ceil(rec_list.length / numberPerPage);\n numberOfRestPages = Math.ceil(rest_list.length / numberPerPage);\n \n //show up to first five buttons\n if (numberOfRestPages >= 5) {\n createNumberedRestButton(1, 5);\n } else {\n createNumberedRestButton(1, numberOfRestPages);\n }\n if (numberOfRecPages >= 5) {\n createNumberedRecButton(1, 5);\n } else {\n createNumberedRecButton(1, numberOfRestPages);\n }\n}",
"function showStudents(page) {\n\tlet start = page * 10;\n\tlet end = start + 10;\n\n\tfor (let i = start; i < end && i < students.length; i++) {\n\t\tstudents[i].style.display = \"inherit\";\n\t}\n}",
"function displayButtons(){\n\t//First Empty the section before recreating it\n\t$(\"#button-section\").empty();\n\n\t//Loop through the areay to recreate it\n\tfor (var i = 0; i < topics.length; i++){\n\n\t\t//create button for each click\n\t\tvar animalBtn = $(\"<button>\");\n\n\t\t//Animal class added is to be used later for each of the animal button clicks\n\t\tanimalBtn.addClass(\"btn btn-default animal\");\n\n\t\t//Store the value of the text in a variable\n\t\tanimalBtn.attr(\"data-attr\",topics[i]);\n\n\t\t//Write the value of the search on the text button\n\t\tanimalBtn.text(topics[i]);\n\n\t\t//Adding button to section\n\t\t$(\"#button-section\").append(animalBtn);\n\n\t\t//Clear the search\n\t\t$(\"#add-animal\").val(\"\");\n\t}\n}",
"function showButtons(){\n\n // for loop to go through the array and create the buttomns\n // need to add class and atributes and name\n // have to append the buttons in the webpage\n $(\"#button-list\").html(\"\"); // cleans the button list before a new buttom is added and showButtons function add back the buttons\n for (var i = 0; i < topics.length; i++) {\n var plugButton = $(\"<button>\");\n\n plugButton.addClass(\"mma\");\n plugButton.attr(\"data-name\", topics[i]);\n plugButton.text(topics[i]);\n $(\"#button-list\").append(plugButton);\n }\n }",
"function renderButtons() {\n\n // this prevents buttons from being repeated\n $(\"#snacks-view\").empty(); \n\n // this for loop will loop through the array of snacks and create a button for each\n for (let i= 0; i < snacks.length; i++) {\n // creates buttonf for each snack\n var snackButton = $(\"<button>\");\n // adds the class \"snack\" to each button\n snackButton.addClass(\"snack\");\n // adds the name of each snack to the data attribute data-name\n snackButton.attr(\"data-name\", snacks[i]);\n // shows the text of each snack name on the button\n snackButton.text(snacks[i]);\n // appends the newest snack button to the previous in the snacks-view div\n $(\"#snacks-view\").append(snackButton);\n \n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
toggle "last" class on selected column | function columnToggleLast(){
var column = '#constructColumn-' + containerPtr + '-' + columnPtrs[containerPtr];
$(column).toggleClass('last');
return false;
} | [
"function columnToggleLast(){\r\n $('#construct .container.selected .column.selected').toggleClass('last');\r\n \r\n return false;\r\n}",
"function addLastClass(dom_tree) {\n jQuery.jsComposer.checkColumnsIsEmpty();\n return jQuery.jsComposer.addLastClass(dom_tree);\n} // end jQuery.wpb_composer.addLastClass()",
"function removeLastColumn (){ \n mediaSection.removeClass(\"middleColumn\")\n}",
"function addLastClass( dom_tree ) {\n return jQuery.swift_page_builder.addLastClass( dom_tree );\n //jQuery(dom_tree).children(\".column:first\").addClass(\"first\");\n //jQuery(dom_tree).children(\".column:last\").addClass(\"last\");\n}",
"function lastColumn (){\n if (media.html() === \"\"){\n mediaSection.addClass(\"middleColumn\");\n }\n}",
"setLastColumn(columnHeader) {\n this.lastHeader = columnHeader;\n }",
"selectLastCell() {\n let lastRow = this.hotMenu.countRows() - 1;\n let cell = this.hotMenu.getCell(lastRow, 0);\n\n if (isSeparator(cell) || isDisabled(cell) || isSelectionDisabled(cell)) {\n this.selectPrevCell(lastRow, 0);\n } else {\n this.hotMenu.selectCell(lastRow, 0);\n }\n }",
"function toggleAddClass() {\n setRightColDisplay(\"addClass\");\n }",
"function deleteLastColumn() {\n game.editorMode.deleteLastColumn();\n displayNumCols();\n updateBackgroundTilesDetailUI();\n updateForegroundTilesDetailUI();\n updateEnemiesDetailUI();\n}",
"function addColoumnOfLastRow(){\n\t // selectedRowArray = null ;\t \n\t selectedColoumnArray = TAFFY( JSON.stringify( selectedRowArray[selectedRowArray.length-1].cols )).get();\n\t alert('selectedColoumnArray.length : ' + selectedColoumnArray.length ) ;\n\t showHtml( 'showcoloumnlisting' ) ;\n}",
"function lastCollaboratorIndicator() {\n if($(\"#version-menu\").is(\":visible\")){\n $(\".collab-name\").removeClass(\"col-active\")\n $(\".last_collaborator\").addClass(\"col-active\")\n }else{\n $(\".last_collaborator\").removeClass(\"col-active\")\n }\n}",
"Last() {\n if (this.CanLast()) {\n this.Position = this.fRows.length - 1;\n }\n }",
"function toggle_column(cls) {\n toggle_class($(\"motifs\"), cls);\n}",
"setLastCellActive() {\n const lastRowIndex = this._rows.length - 1;\n const lastRow = this._getRowsArray()[lastRowIndex];\n this._setActiveCellByIndex(lastRowIndex, lastRow.cells.length - 1);\n }",
"function getCurrentColumn() {\n return (parseInt($frogger.parent().attr('class').split('-')[1]));\n }",
"function isLastNextColumn(colModel, index) {\n var result;\n $.each(colModel, function (i, val) {\n if ((index + 1) < i) {\n if (colModel[i].hidden !== false) {\n result = true;\n } else {\n result = false;\n }\n }\n return (result);\n });\n return result;\n }",
"setPreviousColumnActive() {\n this._setActiveCellByDelta(0, -1);\n }",
"function setLast(allSheet)\n{\n for(let i=0;i<allSheet.length;i++)\n {\n allSheet[i].classList.remove(\"active\");\n }\n allSheet[allSheet.length-1].classList.add(\"active\");\n}",
"get lastColumnRightButton() {\n let list = $$('.move-right');\n return list[list.length - 1];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the ratio of the camera. Most likely to happen when the windows is resized. Depends if the cam is ortho of persp. | updateRatio(w, h){
if(this._isPerspective){
this._camera.aspect = w / h ;
this._camera.updateProjectionMatrix();
}else{
var wRatio = this._windowSize.width / window.innerWidth;
var hRatio = this._windowSize.height / window.innerHeight;
this._camera.left /= wRatio;
this._camera.right /= wRatio;
this._camera.top /= hRatio;
this._camera.bottom /= hRatio;
}
this._windowSize.width = window.innerWidth;
this._windowSize.height = window.innerHeight;
} | [
"recalculateAspect() {\n this.aspect = this.clientWidth / this.clientHeight;\n this.camera.aspect = this.aspect;\n this.camera.updateProjectionMatrix();\n }",
"resize() {\n var window = registry.components.window;\n this.camera.aspect = window.aspect;\n this.camera.updateProjectionMatrix();\n }",
"function update() {\n resize();\n self.camera.updateProjectionMatrix();\n self.controls.update();\n }",
"onWindowResize () {\n\t\tthis.camera.aspect = window.innerWidth / window.innerHeight;\n\t\tthis.camera.updateProjectionMatrix();\n\t\tthis.renderer.setSize(window.innerWidth, window.innerHeight);\n\t}",
"_updateOthoCamFrustrum(){\n var frustrumFactor = 1 / Math.pow(2, this._resolutionLevel);\n this._quadViews[0].updateOrthoCamFrustrum( frustrumFactor );\n this._quadViews[1].updateOrthoCamFrustrum( frustrumFactor );\n this._quadViews[2].updateOrthoCamFrustrum( frustrumFactor );\n }",
"function resize(){\r\n\t//var viewSize = 500;\r\n\r\n\trenderer.setSize( window.innerWidth, window.innerHeight );\r\n\r\n\tvar aspectRatio = window.innerWidth / window.innerHeight;\r\n\r\n\tif( window.innerHeight > 0 && window.innerWidth > 0 ){\r\n\t\t\r\n\t\tif ( aspectRatio < 1 )\r\n\t\t{\r\n\t\t\tcamera.left = -viewSizeHALF;\r\n camera.right = viewSizeHALF;\r\n camera.top = viewSizeHALF * (1 / aspectRatio);\r\n camera.bottom = -viewSizeHALF * (1 / aspectRatio);\r\n\t\t}\r\n\t\telse if ( aspectRatio > 1 )\r\n\t\t{\r\n\t\t\tcamera.left = -viewSizeHALF * aspectRatio;\r\n camera.right = viewSizeHALF * aspectRatio;\r\n camera.top = viewSizeHALF;\r\n camera.bottom = -viewSizeHALF;\r\n\t\t}\r\n\t\t//else ( aspectRatio == 1 )\r\n\t}\r\n\tcamera.aspect = aspectRatio; //keep the Perpective ratio\r\n camera.updateProjectionMatrix();\r\n}",
"updateAspectRatio() {\n if (\n this.skin\n && this.skin.props.skinConfig.responsive.aspectRatio\n && this.skin.props.skinConfig.responsive.aspectRatio !== 'auto'\n ) {\n if (this.skin.props.skinConfig.responsive.aspectRatio === 'fluid') {\n const container = this.state.mainVideoContainer[0].parentNode;\n const containerWidth = container.clientWidth;\n const containerHeight = container.clientHeight;\n this.state.mainVideoAspectRatio = this.calculateAspectRatio(containerWidth, containerHeight);\n } else {\n this.state.mainVideoAspectRatio = this.skin.props.skinConfig.responsive.aspectRatio;\n }\n this.setAspectRatio();\n }\n }",
"setCameraAspect(anAspectRatio){\n this.camera.aspect = anAspectRatio;\n this.camera.updateProjectionMatrix();\n }",
"function resize() {\n var width = container.offsetWidth;\n var height = container.offsetHeight;\n\n camera.aspect = width / height;\n // camera.updateProjectionMatrix();\n\n // renderer.setSize(width, height);\n // effect.setSize(width, height);\n }",
"function updateRendererSize(){\n renderer.setSize(width, height);\n camera.aspect = width / height;\n camera.updateProjectionMatrix();\n }",
"setCameraAspect (anAspectRatio) {\n this.camera.aspect = anAspectRatio;\n this.camera.updateProjectionMatrix();\n }",
"function handleResize() {\r camera.aspect = window.innerWidth / window.innerHeight;\r camera.updateProjectionMatrix();\r renderer.setSize(window.innerWidth, window.innerHeight);\r }",
"function handleResize() {\n camera.aspect = window.innerWidth / window.innerHeight;\n camera.updateProjectionMatrix();\n renderer.setSize(window.innerWidth, window.innerHeight);\n }",
"function handleResize() {\n camera.aspect = window.innerWidth / window.innerHeight;\n camera.updateProjectionMatrix();\n renderer.setSize(window.innerWidth, window.innerHeight);\n }",
"function handleResize() {\n\t\t camera.aspect = window.innerWidth / window.innerHeight;\n\t\t camera.updateProjectionMatrix();\n\t\t renderer.setSize(window.innerWidth, window.innerHeight);\n\t\t }",
"setRatio(val) {\n this.ratio = val;\n this.samplesIn.setDisplacePos((this.winSize * 0.5) / this.ratio);\n }",
"function windowResized() {\n\taction = true;\n\tresizeCanvas(windowWidth, windowHeight);\n\tW = windowWidth;\n\tH = windowHeight;\n\tcameras[camera].S = (22*sqrt(width*height/1000));\n\tresizeCanvas(windowWidth, windowHeight);\n}",
"function onWindowResize()\n{\n\tcamera.aspect = window.innerWidth / window.innerHeight;\n\tcamera.updateProjectionMatrix();\n\n \tif (vrMode)\n \tvrEffect.setSize(window.innerWidth, window.innerHeight);\n else\n \trenderer.setSize(window.innerWidth, window.innerHeight);\n}",
"function onWindowResize(){\r\n camera.aspect = parentWidth(document.getElementById(\"3Dcube\")) / parentHeight(document.getElementById(\"3Dcube\"));\r\n //camera.aspect = window.innerWidth / window.innerHeight;\r\n camera.updateProjectionMatrix();\r\n //renderer.setSize(window.innerWidth, window.innerHeight);\r\n renderer.setSize(parentWidth(document.getElementById(\"3Dcube\")), parentHeight(document.getElementById(\"3Dcube\")));\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function component for the Menu of Recipes | function RecipeMenu({ title, recipes }) {
return (
<article>
<header>
<h1>{title}</h1>
</header>
<div className="recipes">
{recipes.map((recipe, i) => (
<Recipe {...recipe} key={i} />
))}
</div>
</article>
);
} | [
"function PopulateMenuComponent(){\n\n}",
"function menuOptions() {}",
"function Venus() {}",
"addDishToMenu(dish) {\n //TODO Lab 1\n }",
"onAddRecipeClick() {\n window.location.assign('/recipe/add');\n this.onMenuClose();\n }",
"function AddRecipeToMenu() {\n console.log('add recipe to menu');\n let e = d.Config.enums;\n let menuTitle = u.ID(\"selectMenuForNewRecipe\").value;\n let mealID = parseInt(u.ID(\"selectMealForMenu\").value);\n let recipeTitle = u.ID(\"selectRecipeForMenu\").value;\n let morv = u.ID(\"selectMorvForMenu\").value;\n console.log(menuTitle);\n console.log(mealID);\n console.log(recipeTitle);\n console.log(morv);\n\n Dict.menus.addRecipe(menuTitle, mealID, recipeTitle, morv);\n u.WriteDict(3);\n RefreshEditMenu();\n u.SetValues([[\"selectMealForMenu\", \"Choose Meal\"], [\"selectRecipeForMenu\", \"Choose Recipe\"], [\"selectMorvForMenu\", \"Choose Morv\"]]);\n}",
"function makeMenus() { }",
"onMyRecipesClick() {\n window.location.assign('/my-recipes');\n this.onMenuClose();\n }",
"function editRecipe() {\n displayEditForm();\n }",
"clickedDisplayRecipe(event) {\n const id = parseInt(event.target.parentElement.dataset.id);\n this.displayRecipeCallback(id);\n }",
"function logick_menu_item(name,onclick)\n{\n return menubar_Item(name,onclick,\"element-aktions\");\n}",
"handleClick() {\n this.props.onRecipeSelect(this.props.recipe);\n }",
"function Recipe({ name, ingredients, steps }) {\n return (\n <section id={name.toLowerCase().replace(/ /g, \"-\")}>\n <h1>{name}</h1>\n <Ingredients ingredients={ingredients} />\n <Instructions steps={steps} title=\"Cooking instructions\" />\n <StarRating style={{ backgroundColor: \"lightblue\" }} />\n <Rating style={{ backgroundColor: \"lightblue\" }} />\n <p>RatingAsClass</p>\n <RatingAsClass totalStars=\"5\" />\n </section>\n );\n}",
"function DecisionMenu() {}",
"changeRecipe(e) {\n // Define buttonId as a constant with target property of the id interface \n const buttonId = e.target.id;\n // Define recipeId as a constant with a .split method so split strings\n const recipeId = buttonId.split('_')[0];\n // recipeToSelect has prop-types that correlates to recipeId function\n this.props.recipeToSelect(recipeId);\n }",
"function getSubChapterMenu(){\n\t\n}",
"function Estiliza_menu_itens()\n{\n //PARA CADA ITEM DO MENU, BASTA CHAMAR A FUNÇÃO ABAIXO, ESPECIFICANDO\n //SEU INDICE(NUMERO), SUA COR(STRING), SEU CONTEUDO(STRING), SEU LABEL(STRING)\n //Estiliza_item(Indice, Cor, Conteudo, Texto Lateral);\n Estiliza_item(0,\"blue\",\"+\",\"Adicionar\");\n Estiliza_item(1,\"red\",\"Botão\");\n}",
"renderItems() {\n return (\n <div className=\"foodMenu\">\n {this.props.menu.map(item => {\n return (\n <MenuItem\n key={item.name + item.type}\n name={item.name}\n price={item.price}\n // handleInputChange={this.handleInputChange}\n // menuState={this.state}\n />\n );\n })}\n </div>\n );\n }",
"static ExecuteMenuItem() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a modal and displays a random game in it | function randomModal() {
fetch(
`https://api.boardgameatlas.com/api/search?random=true&client_id=${bgAtlasApi}`
)
.then(function (data) {
return data.json();
})
.then(function (data) {
document.getElementById("ranName").textContent = data.games[0].name;
document
.getElementById("ranImg")
.setAttribute("src", `${data.games[0].image_url}`);
document.getElementById(`ranImg`).style.width = `70%`;
document.getElementById(`ranImg`).style.height = `70%`;
document
.getElementById(`ranLink`)
.setAttribute("href", `${data.games[0].url}`);
document.getElementById(`ranLink`).textContent = `${data.games[0].url}`;
});
} | [
"function showYouWin() {\n $(\"#modal-win\").modal(\"show\");\n win.play();\n GAMEOVER = true;\n }",
"function gameWin() {\r\n modal(\"Congratulations!\",\"fa-trophy\");\r\n}",
"function winGame() {\n stopMusic();\n win.play();\n modal.style.display = \"block\";\n modalContent.innerHTML = `<h1 class=\"centered\">Congratulation!</h1><h3 class=\"centered\">You have completed the game!</h3><h3 class=\"centered\">Points scored: ${player.score}</h3><h3 class=\"centered\">Lives saved: ${player.lives}</h3><h3 class=\"centered\">Final Score: ${player.score*player.lives}</h3><button class=\"restart button centered\">RESTART!</button>`;\n}",
"function loadGameModal() {\n this.lives = player.lives;\n if (this.lives === 3) {\n const r = confirm(`Welcome to arcade game. Please use your arrow keys to navigate the player through the bugs. When you reach the water, the player will be reset to the start. Every 3 passes, another bug is added to the screen. Click OK to begin and GOOD LUCK!`);\n if (r === true) {\n resetGame();\n } else {\n endGame();\n }\n }\n}",
"function gameWinPopup(){\n var modalGameWin = document.getElementById('modalGameWin');\n var rePlay = document.getElementById(\"replayBtnWin\");\n var img = document.querySelectorAll(\"img\")[0];\n\n modalGameWin.style.display = \"block\";\n $(\"#scoreWin\").html(\"Final score: \" + finalScore);\n // When the user clicks button replay, close it\n rePlay.onclick = function() {\n window.location.assign(\"../start.html\");\n }\n }",
"function winGame()\n{\n if(matchCounter == 8) \n {\n displayModal();\n }\n}",
"function showWinner() {\n let modal\n if (computerScore > playerScore) {\n modal = new Modal({ title: \"Game over\", body: \"You lost\" })\n } else if (playerScore > computerScore) {\n modal = new Modal({ title: \"Congratulations!\", body: \"You won\" })\n } else {\n modal = new Modal({ title: \"It's draw\", body: \"Play again?\" })\n }\n modal.show()\n}",
"function gameWin() {\n winModalDisplay$.text(currentLevel);\n winModal$.modal('show');\n playSound('win');\n}",
"modal(){\n timer.stop();\n setTimeout(function(){\n game.modal.show();\n game.modal.container_element.innerHTML = game.modal.result_message();\n },1000);\n \n }",
"function joinGameModal() {\n $(\"#enter-game-modal-text\").text(`${params.createdBy} has invited you to play! You can join their game or create your own and invite friends to play.`)\n $(\"#new-game\").hide();\n $(\"#enter-game-modal\").show();\n}",
"function showYouLose() {\n $(\"#modal-lose\").modal(\"show\");\n gameIsOver.play();\n }",
"function openSinglePlayerModalGameType() {\n modal.style.display = 'none';\n numPlayers = 1;\n singlePlayerModalGameType.style.display = 'block';\n}",
"function startGame() {\n let startModal = document.getElementById('startModal');\n startModal.style.display = \"none\";\n}",
"function renderGame() {\n initNotes(document.querySelector(\".keys:checked\").id, randomize);\n changeAnswerBtns();\n document.querySelectorAll(\".modal\").forEach(function (modal) {\n modal.style.display = \"none\";\n });\n document.querySelector(\"#contact\").style.display = \"none\";\n document.querySelector(\"#stats\").style.display = \"none\";\n document.querySelector(\"#game\").style.display = \"block\";\n}",
"gameWonMsg() {\n this.showModal(true, \"message\", \"You Won!\");\n }",
"function displayRandCharacter(){\n var opts = createRandOpts();\n character = createRandCharacter(opts);\n setCharacter(character);\n // show/hide right buttons on form\n $('#gameDel').hide();\n $('#playSaved').hide();\n $('#character').show();\n $('#customize').show();\n $('#play').show();\n $('#displayCharacter').modal('show');\n}",
"function openModal() {\n client.interface.trigger(\"showModal\", {\n title: \"Goals Set Board\",\n template: \"./modals/modal.html\",\n });\n}",
"function showModal() {\n\t\tlet finalMoves = moves.innerHTML;\n\t\tlet finalTime = timer.innerHTML;\n\t\tlet finalStarRating = document.querySelector('.stars').innerHTML;\n\t\tmodal.style.display = 'block';\n\t\tdocument.querySelector(\n\t\t\t'.playing-time'\n\t\t).innerHTML = `You finished the game in ${finalTime}`;\n\t\tdocument.querySelector(\n\t\t\t'.game-moves'\n\t\t).innerHTML = `You made ${finalMoves} moves`;\n\t\tdocument.querySelector(\n\t\t\t'.stars-won'\n\t\t).innerHTML = `You won ${finalStarRating} stars`;\n\t\tcloseModal();\n\t\tclearInterval(interval);\n\t}",
"function loseGame() {\n stopMusic();\n lose.play();\n modal.style.display = \"block\";\n modalContent.innerHTML = `<h1 class=\"centered\">Game Over!</h1><h3 class=\"centered\">You have lost all lives and collected ${player.score} points!</h3><button class=\"restart button centered\">RESTART!</button>`;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of all items that have a file in the docs folder. | function getDocFolderItems(docFolderPath) {
var result = {};
var items = fs.readdirSync(path.resolve(docFolderPath));
for (var i = 0; i < items.length; i++) {
if (items[i].endsWith('.md')) {
var nameNoSuffix = path.basename(items[i], '.md');
result[nameNoSuffix] = 1;
}
}
return result;
} | [
"function getFiles() {\n return fileList;\n}",
"function getDocs(){\n var fs = require('fs');\n var files = fs.readdirSync('docs');\n var list = document.getElementById(\"docList\");\n for(var i = 0; i < files.length; i++){\n //Each folder needs to contain an info.json to interpret, with the file name, description and the entry file for that piece of documentation\n var json = JSON.parse(fs.readFileSync('docs/'+files[i]+'/info.json', 'utf8'));\n list.innerHTML += \"<tr onclick=\\\"location.href='docs/\"+files[i]+\"/index.html'\\\" class='docListItem'><td style=\\\"width:20%\\\">\"+json.docName+\"</td><td><i>\"+json.description+\"</i></td></tr>\";\n }\n}",
"function findDocs(title) {\n return new Promise(function (resolve, reject) {\n var retrievePageOfFiles = function (promise, answer) {\n promise.then(function (response) {\n answer = answer.concat(response.result.files);\n var nextPageToken = response.result.nextPageToken;\n if (nextPageToken) {\n promise = gapi.client.drive.files.list({\n pageToken: nextPageToken,\n q: `name = '${title}' and trashed = false`,\n pageSize: 10,\n fields: 'nextPageToken, files(id, name)'\n });\n retrievePageOfFiles(promise, answer);\n } else {\n resolve(answer);\n }\n }), function (response) {\n appendPre('Error (list): ' + response.result.error.message);\n };\n }\n var initialPromise = gapi.client.drive.files.list({\n q: `name = '${title}' and trashed = false`,\n pageSize: 10,\n fields: 'nextPageToken, files(id, name)'\n });\n retrievePageOfFiles(initialPromise, []);\n });\n}",
"getFiles() {\n let files = this.state.cursor().get( 'files' )\n return files\n ? files.toList()\n : null\n }",
"getFiles() {\n return Resource.find({})\n }",
"function findFiles() {\r\n var files = DriveApp.searchFiles('title contains keyword and trashed=false');\r\n while (files.hasNext()) {\r\n var file = files.next();\r\n Logger.log(\"id=%s, name=%s\", file.getId(), file.getName())\r\n }\r\n }",
"function _getFileList(folder, callback) {\n var files = [];\n \n klaw(folder)\n .on('data', function(item) {\n if (item.stats.isFile() && isAllowed(item.path))\n files.push(item.path);\n })\n .on('end', function() {\n callback(files);\n });\n}",
"listDocuments() {\n return new Promise((resolve) => {\n let documentEntries = []\n forEach(this.documents, (html, documentId) => {\n let manifest = _getManifest(documentId)\n let entry = Object.assign({}, manifest, {id: documentId})\n documentEntries.push(entry)\n })\n resolve(documentEntries)\n })\n }",
"function getFiles () {\n return ProjectManager.getAllFiles(filter());\n }",
"function files_list(usage, gameid) {\n var ix;\n var ls = [];\n\n if (!Storage)\n return ls;\n\n var keyls = Storage.getKeys();\n for (ix=0; ix<keyls.length; ix++) {\n var key = keyls[ix];\n if (!key)\n continue;\n var dirent = file_decode_ref(key.toString());\n if (!dirent)\n continue;\n if (!file_ref_matches(dirent, usage, gameid))\n continue;\n var file = file_load_dirent(dirent);\n ls.push(file);\n }\n\n //GlkOte.log('### files_list found ' + ls.length + ' files.');\n return ls;\n}",
"async allFiles() {\r\n let keys = await this.allKeys();\r\n return keys.filter(k => k.startsWith(\"file:\")).map(k => k.substring(5));\r\n }",
"async function getFiles() {\n return await File.find({}, { path: 0, owner: 0 });\n}",
"function getFiles() {\n return files;\n }",
"function getDocList(req, res) {\n cloudinary.v2.api.resources(\n {\n type: 'upload',\n prefix: CLOUDINARY_DIR\n },\n (err, cloudResponse) => {\n if (err) {\n res.status(500).json(err);\n }\n res.status(200).json(cloudResponse);\n }\n );\n}",
"function getFiles(folder) {\n // Only gets Docs files.\n const files = folder.getFilesByType(MimeType.GOOGLE_DOCS);\n let docIDs = [];\n while (files.hasNext()) {\n let file = files.next();\n docIDs.push(file.getId());\n }\n return docIDs;\n}",
"static async getAllFiles() {\n try {\n return await database.File.findAll();\n } catch (error) {\n throw error;\n }\n }",
"async getAllFiles() {\n try {\n // Directus SDK doesn't yet support fetching files via a\n // dedicated method yet but this works just as well\n const filesData = await this.client.get('files', { limit: '-1' });\n return filesData.data;\n } catch (e) {\n error('gatsby-source-directus: Error while fetching files: ', e);\n return [];\n }\n }",
"_getFiles() {\n return fs.readdirSync(this.arkFilesDir);\n }",
"function getListFiles(dir){\n // Acces to system directory files\n var dir = Components.classes[\"@mozilla.org/file/local;1\"].\n createInstance(Components.interfaces.nsILocalFile);\n dir.initWithPath( bn );\n // read files of working directory\n var dlst = dir.directoryEntries;\n while(dlst.hasMoreElements()) {\n var file = dlst.getNext().QueryInterface(Components.interfaces.nsIFile);\n if (file.isFile() && file.leafName.substring(file.leafName.lastIndexOf('.')) === '.xul') {\n /* Create html list */\n var html_li = document.createElementNS(HTML_NS, 'li');\n var html_a = document.createElementNS(HTML_NS, 'a');\n html_a.href = base_chrome + file.leafName;\n html_a.innerHTML = file.leafName;\n html_li.appendChild(html_a);\n html_lst.appendChild(html_li);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert boolan values true/false (including 1/0 from MySQL) to strings 'true'/'false'. Any other values return undefined. | static boolToTrueFalse(value) {
if (value === undefined) return undefined;
if (value === null) return undefined;
return value ? 'true' : 'false';
} | [
"function booleanToString(b){\n return b ? \"true\" : \"false\"\n}",
"function booleanToString(b){\n // take input and convert to strings\n // return input as strings\n return b.toString()\n }",
"function booleanToString(b){\n return b ? 'true' : 'false';\n}",
"function booleanToString(b){\n return b === true ? 'true' : 'false'\n}",
"function booleanToString(b){\n return b.toString();\n}",
"function booleanToString(b) {\r\n\treturn \"\" + b;\r\n}",
"function boolsToString (k, v) {\n\t if (typeof v === 'boolean')\n\t return String(v)\n\t return v\n\t }",
"function boolsToString (k, v) {\n if (typeof v === 'boolean')\n return String(v)\n return v\n }",
"function booleanToString(b){\n if(b === true){\n return 'true'\n }else{\n return 'false'\n }\n}",
"function boolToStr(bool)\n{\n if (bool === undefined)\n return \"ברירת המחדל\";\n if (bool)\n return \"פעיל\";\n return \"כבוי\";\n}",
"function booleanToString(b){\n \n // initially I thought it was asking me to return either \"true\" or \"false\" + a corresponding sentence string (see var ans), so that's why that is there. It passed the tests without me cleaning that bit out though :P\n\n var booly;\n var ans;\n\n if (b === true){\n ans = 'When we pass in true, we want the string \"true\" as output';\n booly = \"true\";\n } else if (b === false){\n ans = 'When we pass in false, we want the string \"false\" as output';\n booly = \"false\";\n }\n\n return booly\n\n }",
"function boolToString(flag) \r\n{\r\n \r\n return flag.toString();\r\n}",
"function boolean2HexString(bool) {\n return bool ? \"01\" : \"00\";\n}",
"function get_boolean_string(boolean_input){\n if(boolean_input == 'true'){\n return 'Yes';\n } else{\n\t\t\treturn 'No';\n }\n}",
"function boolToActive(value) {\n return value ? 'Active' : 'Inactive';\n}",
"function boolToWord(bool) {\r\n\treturn bool ? \"Yes\" : \"No\";\r\n}",
"function convertBooleanToTorF(bool)\r\n{\r\n return (bool ? \"T\" : \"F\");\r\n}",
"function as_bool(v) {\r\n return setType(v, 'bool');\r\n}",
"function convertBool(bool) {\n if (bool) {\n return 1;\n } else {\n return 0;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates, or attempts to evaluate, a GetAccessorDeclaration, before setting it on the given parent | function evaluateGetAccessorDeclaration({ node, environment, evaluate, stack, reporting, typescript, statementTraversalStack }, parent) {
const nameResult = evaluate.nodeWithValue(node.name, environment, statementTraversalStack);
const isStatic = inStaticContext(node, typescript);
if (parent == null) {
let updatedParent;
if (typescript.isClassLike(node.parent)) {
evaluate.declaration(node.parent, environment, statementTraversalStack);
updatedParent = stack.pop();
}
else {
updatedParent = evaluate.expression(node.parent, environment, statementTraversalStack);
}
stack.push(isStatic ? updatedParent[nameResult] : updatedParent.prototype[nameResult]);
return;
}
/**
* An implementation of the get accessor
*/
function getAccessorDeclaration() {
// Prepare a lexical environment for the function context
const localLexicalEnvironment = cloneLexicalEnvironment(environment);
// Define a new binding for a return symbol within the environment
setInLexicalEnvironment({ env: localLexicalEnvironment, path: RETURN_SYMBOL, value: false, newBinding: true, reporting, node });
// Define a new binding for the arguments given to the function
// eslint-disable-next-line prefer-rest-params
setInLexicalEnvironment({ env: localLexicalEnvironment, path: "arguments", value: arguments, newBinding: true, reporting, node });
if (this != null) {
setInLexicalEnvironment({ env: localLexicalEnvironment, path: THIS_SYMBOL, value: this, newBinding: true, reporting, node });
// Set the 'super' binding, depending on whether or not we're inside a static context
setInLexicalEnvironment({
env: localLexicalEnvironment,
path: SUPER_SYMBOL,
value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype,
newBinding: true,
reporting,
node
});
}
// If the body is a block, evaluate it as a statement
if (node.body == null)
return;
evaluate.statement(node.body, localLexicalEnvironment);
// If a 'return' has occurred within the block, pop the Stack and return that value
if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) {
return stack.pop();
}
// Otherwise, return 'undefined'. Nothing is returned from the function
else
return undefined;
}
getAccessorDeclaration.toString = () => `[Get: ${nameResult}]`;
let currentPropertyDescriptor = Object.getOwnPropertyDescriptor(parent, nameResult);
if (currentPropertyDescriptor == null)
currentPropertyDescriptor = {};
Object.defineProperty(parent, nameResult, Object.assign(Object.assign({}, currentPropertyDescriptor), { configurable: true, get: getAccessorDeclaration }));
} | [
"function evaluateSetAccessorDeclaration(options, parent) {\n const { node, environment, evaluate, statementTraversalStack, reporting, typescript } = options;\n const nameResult = evaluate.nodeWithValue(node.name, environment, statementTraversalStack);\n const isStatic = inStaticContext(node, typescript);\n /**\n * An implementation of the set accessor\n */\n function setAccessorDeclaration(...args) {\n // Prepare a lexical environment for the function context\n const localLexicalEnvironment = cloneLexicalEnvironment(environment);\n // Define a new binding for a return symbol within the environment\n setInLexicalEnvironment({ env: localLexicalEnvironment, path: RETURN_SYMBOL, value: false, newBinding: true, reporting, node });\n // Define a new binding for the arguments given to the function\n // eslint-disable-next-line prefer-rest-params\n setInLexicalEnvironment({ env: localLexicalEnvironment, path: \"arguments\", value: arguments, newBinding: true, reporting, node });\n if (this != null) {\n setInLexicalEnvironment({ env: localLexicalEnvironment, path: THIS_SYMBOL, value: this, newBinding: true, reporting, node });\n // Set the 'super' binding, depending on whether or not we're inside a static context\n setInLexicalEnvironment({\n env: localLexicalEnvironment,\n path: SUPER_SYMBOL,\n value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype,\n newBinding: true,\n reporting,\n node\n });\n }\n // Evaluate the parameters based on the given arguments\n evaluateParameterDeclarations(Object.assign(Object.assign({}, options), { node: node.parameters, environment: localLexicalEnvironment }), args);\n // If the body is a block, evaluate it as a statement\n if (node.body == null)\n return;\n evaluate.statement(node.body, localLexicalEnvironment);\n }\n setAccessorDeclaration.toString = () => `[Set: ${nameResult}]`;\n let currentPropertyDescriptor = Object.getOwnPropertyDescriptor(parent, nameResult);\n if (currentPropertyDescriptor == null)\n currentPropertyDescriptor = {};\n Object.defineProperty(parent, nameResult, Object.assign(Object.assign({}, currentPropertyDescriptor), { configurable: true, set: setAccessorDeclaration }));\n}",
"function visitAccessorDeclaration(node) {\n ts.Debug.assert(!ts.isComputedPropertyName(node.name));\n var savedConvertedLoopState = convertedLoopState;\n convertedLoopState = undefined;\n var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);\n var updated;\n if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) {\n var parameters = ts.visitParameterList(node.parameters, visitor, context);\n var body = transformFunctionBody(node);\n if (node.kind === 154 /* GetAccessor */) {\n updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);\n }\n else {\n updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);\n }\n }\n else {\n updated = ts.visitEachChild(node, visitor, context);\n }\n exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);\n convertedLoopState = savedConvertedLoopState;\n return updated;\n }",
"function visitAccessorDeclaration(node) {\n ts.Debug.assert(!ts.isComputedPropertyName(node.name));\n var savedConvertedLoopState = convertedLoopState;\n convertedLoopState = undefined;\n var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);\n var updated;\n if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) {\n var parameters = ts.visitParameterList(node.parameters, visitor, context);\n var body = transformFunctionBody(node);\n if (node.kind === 154 /* GetAccessor */) {\n updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);\n } else {\n updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);\n }\n } else {\n updated = ts.visitEachChild(node, visitor, context);\n }\n exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);\n convertedLoopState = savedConvertedLoopState;\n return updated;\n }",
"function visitAccessorDeclaration(node) {\n ts.Debug.assert(!ts.isComputedPropertyName(node.name));\n var savedConvertedLoopState = convertedLoopState;\n convertedLoopState = undefined;\n var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);\n var updated = ts.visitEachChild(node, visitor, context);\n exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);\n convertedLoopState = savedConvertedLoopState;\n return updated;\n }",
"function visitAccessorDeclaration(node){ts.Debug.assert(!ts.isComputedPropertyName(node.name));var savedConvertedLoopState=convertedLoopState;convertedLoopState=undefined;var ancestorFacts=enterSubtree(16286/* FunctionExcludes */,65/* FunctionIncludes */);var updated;var parameters=ts.visitParameterList(node.parameters,visitor,context);var body=transformFunctionBody(node);if(node.kind===163/* GetAccessor */){updated=ts.updateGetAccessor(node,node.decorators,node.modifiers,node.name,parameters,node.type,body);}else{updated=ts.updateSetAccessor(node,node.decorators,node.modifiers,node.name,parameters,body);}exitSubtree(ancestorFacts,49152/* FunctionSubtreeExcludes */,0/* None */);convertedLoopState=savedConvertedLoopState;return updated;}",
"function visitAccessorDeclaration(node) {\n var savedInGeneratorFunctionBody = inGeneratorFunctionBody;\n var savedInStatementContainingYield = inStatementContainingYield;\n inGeneratorFunctionBody = false;\n inStatementContainingYield = false;\n node = ts.visitEachChild(node, visitor, context);\n inGeneratorFunctionBody = savedInGeneratorFunctionBody;\n inStatementContainingYield = savedInStatementContainingYield;\n return node;\n }",
"function visitAccessorDeclaration(node){var savedInGeneratorFunctionBody=inGeneratorFunctionBody;var savedInStatementContainingYield=inStatementContainingYield;inGeneratorFunctionBody=false;inStatementContainingYield=false;node=ts.visitEachChild(node,visitor,context);inGeneratorFunctionBody=savedInGeneratorFunctionBody;inStatementContainingYield=savedInStatementContainingYield;return node;}",
"function visitSetAccessorDeclaration(context, node) {\n var accessor = converter.createDeclaration(context, node, td.models.ReflectionKind.Accessor);\n context.withScope(accessor, function () {\n accessor.setSignature = converter.createSignature(context, node, '__set', td.models.ReflectionKind.SetSignature);\n });\n return accessor;\n }",
"static isSetAccessorDeclaration(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.SetAccessor;\r\n }",
"parseAccessors(node) {\n\t\tif (this.currentToken.value === TV.At) {\n\t\t\tthis.next();\n\t\t\tconst { line } = this.currentToken;\n\t\t\treturn new AccessorNode(node, this.parseSymbolOrConstant(), line);\n\t\t}\n\n\t\treturn node;\n\t}",
"function shouldEmitAccessorDeclaration(node) {\n return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));\n }",
"function visitGetAccessor(node) {\n if (!shouldEmitAccessorDeclaration(node)) {\n return undefined;\n }\n var updated = ts.updateGetAccessor(node,\n /*decorators*/undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context),\n /*type*/undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));\n if (updated !== node) {\n // While we emit the source map for the node after skipping decorators and modifiers,\n // we need to emit the comments for the original range.\n ts.setCommentRange(updated, node);\n ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));\n }\n return updated;\n }",
"static isGetAccessorDeclaration(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.GetAccessor;\r\n }",
"function evaluatePropertyDeclaration({ environment, node, evaluate, statementTraversalStack, typescript, stack }, parent) {\n // Compute the property name\n const propertyNameResult = evaluate.nodeWithValue(node.name, environment, statementTraversalStack);\n if (parent == null) {\n evaluate.declaration(node.parent, environment, statementTraversalStack);\n const updatedParent = stack.pop();\n const isStatic = inStaticContext(node, typescript);\n stack.push(isStatic ? updatedParent[propertyNameResult] : updatedParent.prototype[propertyNameResult]);\n return;\n }\n parent[propertyNameResult] = node.initializer == null ? undefined : evaluate.expression(node.initializer, environment, statementTraversalStack);\n if (node.decorators != null) {\n for (const decorator of node.decorators) {\n evaluate.nodeWithArgument(decorator, environment, [parent, propertyNameResult], statementTraversalStack);\n // Pop the stack. We don't need the value it has left on the Stack\n stack.pop();\n }\n }\n}",
"function shouldEmitAccessorDeclaration(node) {\n return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));\n }",
"getSetAccessor() {\r\n const parent = this.getParentIfKindOrThrow(typescript_1.SyntaxKind.ClassDeclaration);\r\n const thisName = this.getName();\r\n for (const prop of parent.getInstanceProperties()) {\r\n if (prop.getName() === thisName && prop.getKind() === typescript_1.SyntaxKind.SetAccessor)\r\n return prop;\r\n }\r\n return undefined;\r\n }",
"function visitSetAccessor(node) {\n if (!shouldEmitAccessorDeclaration(node)) {\n return undefined;\n }\n var updated = ts.updateSetAccessor(node,\n /*decorators*/undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));\n if (updated !== node) {\n // While we emit the source map for the node after skipping decorators and modifiers,\n // we need to emit the comments for the original range.\n ts.setCommentRange(updated, node);\n ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));\n }\n return updated;\n }",
"function getTopLevelAccessorsNotSupported() {\n throw new Error(\"getTopLevelAccessors() is not supported in CapeCode because each accessor is a separate JavaScript engine.\");\n}",
"async resolveAccessorForAll(path) {\n debug('resolve accessor (all):', this.value, path)\n let scope = this // eslint-disable-line consistent-this\n for (let i = 0; i < path.length; i++) {\n const operation = path[i]\n debug('resolve accessor: next op:', operation)\n switch (operation.op) {\n case 'parent':\n scope = scope.parent\n debug('resolve accessor: ^ =>', scope)\n break\n case 'attribute':\n if (scope.sourceId) {\n const source = (await scope.dataForSource(scope.sourceId)).documents // eslint-disable-line no-await-in-loop\n debug('resolve accessor: (source)', source)\n // Resolve the path to the source item for every document\n const sourceScopes = source.map(item => scope.clone({\n value: item\n }).resolveAccessor(scope.path))\n\n const flattenedSourceScopes = []\n\n // Flatten any arrays we might have seen\n sourceScopes.forEach(itemScope => {\n if (Array.isArray(itemScope.value)) {\n itemScope.value.forEach(itemValue => {\n flattenedSourceScopes.push(scope.clone({\n value: itemValue\n }))\n })\n } else {\n flattenedSourceScopes.push(itemScope)\n }\n })\n\n\n debug('resolve accessor: (expanded scopes)', source)\n // Now resolve the rest of the path for each item\n const subPath = path.slice(i)\n const result = []\n flattenedSourceScopes.forEach(itemScope => { // eslint-disable-line no-loop-func, no-await-in-loop\n // const itemScope = scope.clone({\n // value: item\n // })\n const resolvedScope = itemScope.resolveAccessor(subPath)\n if (resolvedScope.value !== null) {\n result.push(resolvedScope)\n }\n })\n return result\n }\n\n if (scope.value === null || scope.value === undefined) {\n return scope.clone({\n value: null\n })\n }\n\n scope = scope.child({\n parent: scope,\n value: scope.value[operation.name]\n })\n debug('resolve accessor:', operation.name, '=>', scope.value)\n break\n default:\n throw new Error(`Unkown accessor path element ${operation.op}`)\n }\n if (!scope.value) {\n break\n }\n }\n // Unresolved attributes should return null, not undefined?\n if (scope.value === undefined) {\n scope = scope.clone({\n value: null\n })\n }\n debug('resolve accessor (all, result):', this.value, path, scope)\n return [scope]\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the point in the user's environment that the anchor tracks from. The parameters passed in to this function correspond to the X, Y and Z coordinates (in camera space) of the point to track. Choosing a position with X and Y coordinates of zero, and a negative Z coordinate, will select a point on a surface directly in front of the center of the screen. | setAnchorPoseFromCameraOffset(x, y, z, orientation) {
this._z.instant_world_tracker_anchor_pose_set_from_camera_offset(this._impl, x, y, z, orientation || zappar_cv_1.instant_world_tracker_transform_orientation_t.MINUS_Z_AWAY_FROM_USER);
} | [
"function setupCamera(x, y, z) {\n camera.position.set(x, y, z)\n}",
"setInitialCameraPosition() {\n\n\t\tlet target = this.getOption('target') || [0,0,0];\n\t\tthis.camera.target.set(...target);\n\n\t\t// If we don't find a position, we'll calculate the bounding box of \n\t\t// the entire scene.\n\t\tlet pos = this.getOption('position');\n\t\tif (!pos) {\n\t\t\tif (this.scene.children.length === 0) {\n\t\t\t\tpos = [0,1,0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet bbox = new three.Box3().setFromObject(this.scene);\n\t\t\t\tthrow new Error('Calculating the position automatically not supported yet!');\n\t\t\t}\n\t\t}\n\t\tthis.camera.position.set(...pos);\n\n\t}",
"function setPos(params) {\n\tvar params = params || {};\n\tCamera.duration = 0;\n\tCamera.easing = platino.ANIMATION_CURVE_LINEAR;\n\tCamera.lookAt_eyeX = params.eyeX || params.centerX;\n\tCamera.lookAt_centerX = params.centerX;\n\tCamera.lookAt_eyeY = params.eyeY || params.centerY;\n\tCamera.lookAt_centerY = params.centerY;\n\tCamera.lookAt_eyeZ = params.eyeZ;\n\tCamera.skipOnComplete = params.skipOnCompleteListener || false;\n\tgame.moveCamera(Camera);\n}",
"setOrbitPoint(targetX, targetY, targetZ) {\n this._camera.updateMatrixWorld();\n _xColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 0);\n _yColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 1);\n _zColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 2);\n const position2 = _v3A.set(targetX, targetY, targetZ);\n const distance4 = position2.distanceTo(this._camera.position);\n const cameraToPoint = position2.sub(this._camera.position);\n _xColumn.multiplyScalar(cameraToPoint.x);\n _yColumn.multiplyScalar(cameraToPoint.y);\n _zColumn.multiplyScalar(cameraToPoint.z);\n _v3A.copy(_xColumn).add(_yColumn).add(_zColumn);\n _v3A.z = _v3A.z + distance4;\n this.dollyTo(distance4, false);\n this.setFocalOffset(-_v3A.x, _v3A.y, -_v3A.z, false);\n this.moveTo(targetX, targetY, targetZ, false);\n }",
"function fnCamSet (argX, argY, argZ) {\n oCamNext = {x:argX,y:argY,z:argZ};\n oLookAt = oCamNext; // FIX\n}",
"SetLookAtPosition() {}",
"function setPointPos(x,y,z) {\n gl.uniform3f(\n _pointPos,\n parseFloat(x),\n parseFloat(y),\n parseFloat(z)\n );\n}",
"function setCameraPosition(){\n if(position < 0){\n position = 0\n }\n if(position > 3){\n position = 3\n }\n let p = (position / 3);\n let positionCurve = pathCurve.getPointAt( p );\n \n return positionCurve;\n}",
"function xyzprySet2Home() {\n\tgl[gl.at].homeX = gl[gl.at].X ;\n\tgl[gl.at].homeY = gl[gl.at].Y ;\n\tgl[gl.at].homeZ = gl[gl.at].Z ;\n\tgl[gl.at].homePitch = gl[gl.at].pitch;\n\tgl[gl.at].homeRoll = gl[gl.at].roll ;\n\tgl[gl.at].homeYaw = gl[gl.at].yaw ;\n\t//AL(\"setting home as\");\n\t//xyzpryLogView();\n}",
"function xyzprySet2Home0() {\n\tgl[gl.at].homeX0 = gl[gl.at].X ;\n\tgl[gl.at].homeY0 = gl[gl.at].Y ;\n\tgl[gl.at].homeZ0 = gl[gl.at].Z ;\n\tgl[gl.at].homePitch0 = gl[gl.at].pitch;\n\tgl[gl.at].homeRoll0 = gl[gl.at].roll ;\n\tgl[gl.at].homeYaw0 = gl[gl.at].yaw ;\n\t//AL(\"setting home0 as\");\n\t//xyzpryLogView();\n}",
"setCameraToCenter() {\n let center_pos = (this.max_val - this.min_val) / 2;\n this.sigInst.camera.goTo({x:center_pos, y:center_pos, ratio:1});\n }",
"function setCamera() { \n camera.position.set(40, 120, 0);\n camera.lookAt(0, 0, 0);\n camera.up.set(0, 1, 0);\n camera.updateProjectionMatrix();\n\n}",
"function setPos(newX : float, newY : float)\n{\n // By default the target x and y coordinates of the camera are it's current x and y coordinates.\n var targetX : float = newX;\n var targetY : float = newY;\n // The target x and y coordinates should not be larger than the maximum or smaller than the minimum.\n targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);\n targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);\n // Set the camera's position to the target position with the same z component.\n transform.position = new Vector3(targetX, targetY, transform.position.z);\n}",
"function set_eye_position (x, y, z) {\r\n eye_x = x;\r\n eye_y = y;\r\n eye_z = z;\r\n}",
"setEarthPosition(x = 0.0, y = 0.0, z = 0.0){\n this.earth.position.set(x, y, z);\n }",
"function setupCamera() {\r\n //camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);\r\n camera = new PerspectiveCamera(85, window.innerWidth / window.innerHeight, 0.1, 1000);\r\n camera.position.x = 30;\r\n camera.position.y = 20;\r\n camera.position.z = 0;\r\n camera.lookAt(scene.position);\r\n console.log(\"Finished setting up Camera...\");\r\n}",
"setCameraCenter(x, y){\n if(this.config.DEBUG && this.config.DEBUG.render) console.log(\"set Camera BEFORE\", this.cameraX, this.cameraY);\n if(this.config.DEBUG && this.config.DEBUG.render) console.log(\"setCamera:\", x, y);\n let centerX = Math.floor(x - (this.viewWidth / 2));\n let centerY = Math.floor(y - (this.viewHeight / 2));\n this.cameraX = centerX;\n this.cameraY = centerY;\n if(this.config.DEBUG && this.config.DEBUG.render) console.log(\"set Camera AFTER\", this.cameraX, this.cameraY);\n }",
"function setCamera()\n{\n var v = 0.0025; // camera tool speed\n var r = 500.0; // camera to origin distance\n \n var alphaX = v * camRotationX * Math.PI;\n var alphaY = v * camRotationY * Math.PI;\n \n alphaX = Math.max(alphaX, -0.5 * Math.PI)\n alphaX = Math.min(alphaX, 0.5 * Math.PI)\n \n var sX = Math.sin(alphaX);\n var cX = Math.cos(alphaX);\n \n var sY = Math.sin(alphaY);\n var cY = Math.cos(alphaY);\n \n camera.position.x = r * cX * sY;\n camera.position.y = r * (-sX);\n camera.position.z = r * cX * cY;\n \n // aim the camera at the origin\n camera.lookAt(new Vector3(0,0,0));\n}",
"function setPosition(element, x, y, z) {\n var pos = element.transform.position.value;\n if(x !== false) pos[0] = x;\n if(y !== false) pos[1] = y;\n if(z !== false) pos[2] = z;\n element.transform.position.setValue(pos);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find game by gameid in games array | function getGame(gameid){
var i = 0;
do{
if(games[i].gameid == gameid){
return games[i];
}
i++;
}while(i < games.length);
return -1;
} | [
"function findGame(id) {\n for (var i = 0; i < games.length; i++) {\n if (games[i].id == id) {\n return games[i];\n }\n }\n return null;\n}",
"function searchingForGame(id){\n\tvar i;\n\tfor(i=0; i < games.length; i++){\n\t\tif(games[i].id === id){\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}",
"getGameFromID(_id) {\n for (var i = 0; i < this.games.length; i++) if (this.games[i].id == _id) return this.games[i];\n }",
"function findGameByID (id) {\n return activeGames.find(game => game.id === id);\n}",
"getGame(id) {\n let game = this.games.find((game) => game.id === id);\n return game;\n }",
"findGame(gameID) {\n let gameIdInt = parseInt(gameID);\n if (this.GameList.has(gameIdInt)) {\n return this.GameList.get(gameIdInt);\n } else {\n let e = new Error(\"Das Spiel wurde nicht gefunden\");\n e.name = \"GameNotFound\";\n throw e;\n }\n }",
"getGame(id) {\n if (id >= this._games.length) {\n return null;\n }\n return this._games[id];\n }",
"function getGamePublic(id) {\n for (let game of games) {\n if (game.publicId == id) {\n return game;\n }\n }\n\n return null;\n}",
"getGame(id) {\n if (!this._games.has(id)) {\n return null;\n }\n return this._games.get(id);\n }",
"function getGame(query) {\n for (let i=0; i<games.length; i++) {\n if (query === games[i].name || query === games[i].data_name) return games[i];\n }\n return null;\n}",
"function getGame(code) {\n for(let i = 0; i < games.length; i++) {\n if (games[i].code === code) {\n return games[i];\n }\n }\n}",
"function findGame(socket,data) {\r\n\t\r\n\t// search the games for the nearest to this position?\r\n\tvar id = data.id != -1 ? data.id.toLowerCase() : data.id;\r\n\tvar game = games.find(id)\r\n\t\r\n\treturn {\r\n\t\tdisconnect: function(){\r\n\t\t\tif(game)\r\n\t\t\t\tgame.disconnect(socket)\r\n\t\t},\r\n\t\tapply: function(){\r\n\t\t\tif(!game && id) // no game but a id\r\n\t\t\t\tgame = games.create(id)\r\n\t\t\tif(game)\t\r\n\t\t\t\tgame.apply(socket, data)\r\n\t\t}\r\n\t}\r\n}",
"function getGamePrivate(id) {\n for (let game of games) {\n if (game.privateId == id) {\n return game;\n }\n }\n\n return null;\n}",
"getGame(hostId) {\n let game = this.games.filter((game) => game.hostId === hostId)\n return game[0]\n }",
"function getGameFromGameUuid(gameUuid) {\n console.log(\"games length [\" + games.length + \"]\");\n var out = null;\n games.forEach(function(item,index) {\n if(item.uuid == gameUuid) {\n out = item;\n }\n });\n return out;\n }",
"function get_data_by_id(id){\n\treturn data.find(game => game.id === id)\n}",
"function getGame(sessionID)\n{\n for(let i=0; i<games.length; i++)\n {\n if(games[i].session.sessionID === sessionID) {\n return games[i];\n }\n }\n\n return null;\n}",
"function searchByID(array, id) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].id == id)\n return array[i];\n }\n}",
"function getGame(index) {\n\n var game;\n for (var i = 0; i < SHIPS.games.length; i++) {\n if (SHIPS.games[i] && SHIPS.games[i].gameIndex == index) {\n game = SHIPS.games[i];\n }\n }\n \n return game;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a synchronous request was a success or not Taken from jQuery 1.4 | function httpSuccess(xhr) {
try {
return !xhr.status && location.protocol === "file:" ||
xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304 || xhr.status === 1223;
} catch (e) {
}
return false;
} | [
"function successfulRequest(request) {\n return request.readyState === 4 && request.status == 200;\n}",
"function successfulRequest(request) {\r\n return request.readyState === 4 && request.status == 200;\r\n }",
"function IsRequestSuccessful (httpRequest) {\n // IE: sometimes 1223 instead of 204\n var success = (httpRequest.status == 0 || \n (httpRequest.status >= 200 && httpRequest.status < 300) || \n httpRequest.status == 304 || httpRequest.status == 1223);\n \n return success;\n}",
"function isSuccess(request) {\n if (request.kind === \"success\") {\n return request.result;\n }\n return null;\n}",
"function isRequestOk(request) {\n return request.status === 200 && request.readyState === 4;\n }",
"function httpSuccess(r) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// If no server status is provided, and we're actually\n\t\t\t\t\t\t// requesting a local file, then it was successful\n\t\t\t\t\t\treturn !r.status && location.protocol == 'file:' ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Any status in the 200 range is good\n\t\t\t\t\t\t( r.status >= 200 && r.status < 300 ) ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Successful if the document has not been modified\n\t\t\t\t\t\tr.status == 304 ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Safari returns an empty status if the file has not been modified\n\t\t\t\t\t\tnavigator.userAgent.indexOf('Safari') >= 0 && typeof r.status == 'undefined';\n\t\t\t\t\t} catch(e){\n\t\t\t\t\t\t// Throw a corresponding error\n\t\t\t\t\t\tthrow new Error(\"httpSuccess = \" + e);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// If checking the status failed, then assume that the request failed too\n\t\t\t\t\treturn false;\n\t\t\t\t}",
"function checkState(request) { return (request.readyState == 4); }",
"function httpSuccess(r) {\r\n try {\r\n\t //if no server status is provided and we're actually requesting a local file then it was successful;\r\n\t return !r.status && location.protocol == \"file:\" ||\r\n\t \r\n\t //any status in the 200 range is good;\r\n\t\t(r.status >= 200 && r.status < 300) ||\r\n\t\t\r\n\t\t//successful if the document has not been modified;\r\n\t\tr.status == 304 ||\r\n\t\t\r\n\t\t//Safari returns an empty status if the file has not been modified\r\n\t\tnavigator.userAgent.indexOf(\"Safari\") >= 0 && typeof r.status == \"undefined\";\r\n\t\t\r\n\t} catch(e) {}\r\n\t\r\n //if checking the status failed then assume that the request failed;\r\n return false;\r\n \r\n }",
"function AjaxCallback() { \r\n if( 4 == this.req.readyState ) {\r\n if( 200 != this.req.status ) {\r\n if (this.errorCall != null) {\r\n this.errorCall();\r\n }\r\n } else { \r\n if (this.successCall != null) { \r\n this.successCall(); \r\n }\r\n }\r\n }\r\n}",
"function httpSuccess(r) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// If no server status is provided, and we're actually\n\t\t\t\t\t\t// requesting a local file, then it was successful\n\t\t\t\t\t\treturn !r.status && location.protocol == 'file:' ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Any status in the 200 range is good\n\t\t\t\t\t\t( r.status >= 200 && r.status < 300 ) ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Successful if the document has not been modified\n\t\t\t\t\t\tr.status == 304 ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Safari returns an empty status if the file has not been modified\n\t\t\t\t\t\tnavigator.userAgent.indexOf('Safari') >= 0 && typeof r.status == 'undefined';\n\t\t\t\t\t} catch(e){\n\t\t\t\t\t\t// Throw a corresponding error\n\t\t\t\t\t\tthrow new Error(\"httpSuccess Error = \" + e);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// If checking the status failed, then assume that the request failed too\n\t\t\t\t\treturn false;\n\t\t\t\t}",
"function successful (xhr) {\n return xhr.status >= 200 && xhr.status <= 299\n }",
"function httpSuccess(r) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// If no server status is provided, and we're actually\n\t\t\t\t\t\t// requesting a local file, then it was successful\n\t\t\t\t\t\treturn !r.status && location.protocol == 'file:' ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Any status in the 200 range is good\n\t\t\t\t\t\t( r.status >= 200 && r.status < 300 ) ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Successful if the document has not been modified\n\t\t\t\t\t\tr.status == 304 ||\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Safari returns an empty status if the file has not been modified\n\t\t\t\t\t\tnavigator.userAgent.indexOf('Safari') >= 0 && typeof r.status == 'undefined';\n\t\t\t\t\t} catch(e){\n\t\t\t\t\t\t// Handle error\n\t\t\t\t\t\t__xhrl.errorHandler(config.url, 'httpSuccess function', e);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// If checking the status failed, then assume that the request failed too\n\t\t\t\t\treturn false;\n\t\t\t\t}",
"function checkState(request) { return (request.readyState == request.DONE); }",
"function IsAjaxResult(data) {\n return (data.Status && data.Message);\n}",
"function requestReady(resp){\n return (resp.readyState == 4 && resp.status == 200);\n}",
"function ajaxResponse() {\nif (ajaxreq.readyState !=4) return;\nif (ajaxreq.status==200) {\n// if the request succeeded...\nif (ajaxCallback) ajaxCallback();\n} else alert(\"Request failed: \" + ajaxreq.statusText);\nreturn true;\n}",
"function checkUrlExistence( url, success, failure ) {\n var settings = {\n 'type' : 'HEAD',\n 'async' : true,\n 'url' : url\n };\n if ( success )\n settings.success = success;\n if ( failure )\n settings.error = failure;\n $.ajax( settings );\n }",
"function isAjaxReturnOK(obj) {\n var ret = false;\n if (obj) {\n if (typeof (obj.response) == 'string') {\n if (obj.response.toLowerCase() == 'ok') {\n ret = true;\n }\n }\n }\n return ret;\n}",
"function isAjaxReturnOK(obj) {\r\n var ret = false;\r\n if (obj) {\r\n if (typeof (obj.response) == 'string') {\r\n if (obj.response.toLowerCase() == 'ok') {\r\n ret = true;\r\n }\r\n }\r\n }\r\n return ret;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[MSPPT] 2.5 Slide Types / [MSPPT] 2.5.1 SlideContainer | function parse_SlideContainer(blob, length, opts) {
var o = {};
recordhopper(blob, function rtslide(R, val) {
switch(R.n) {
case 'RT_SlideAtom': break;
case 'RT_Drawing': o.drawing = val; break;
case 'RT_ColorSchemeAtom': break;
case 'RT_ProgTags': break;
case 'RT_RoundTripContentMasterId12Atom': break;
case 'RT_RoundTripCompositeMasterId12Atom': break;
default: if(opts.WTF) throw R.n; break;
}
}, blob.l + length, opts);
return o;
} | [
"function generateSlides() {\n const parentEle = document.querySelector('#container');\n currentQContent = [dataVizPage[state.q_id], ...sharedContent]\n\n currentQContent.forEach((slide, i) => {\n const slideElement = document.createElement('div');\n //element position absolute\n slideElement.style.zIndex = `-${i}`;\n slideElement.style.position = 'absolute';\n slideElement.classList.add('slide');\n slideElement.setAttribute('id', `slide${state.q_id}-${i}`)\n if (i == 0) {\n slideElement.classList.add('center');\n } else {\n slideElement.classList.add('right');\n }\n slideElement.innerHTML = `${currentQContent[i].slide_text}`;\n parentEle.appendChild(slideElement);\n });\n\n}",
"function createPresentation(slides) {\n\n const slideContainer = document.getElementById(\"slides\");\n\n if (slides.length) {\n\n // create list using plain old vanilla JS\n const slideList = document.createElement(\"ul\");\n slideContainer.appendChild(slideList);\n slides.forEach(function(slide) {\n\n let slideElement = document.createElement(\"li\");\n slideElement.id = slide.id;\n slideElement.classList.add(\"slide\");\n let title = document.createElement(\"div\");\n title.innerHTML = slide.title.text;\n slideElement.appendChild(title);\n\n slideElement.addEventListener(\"click\", function() {\n // the slide is only used to zoom to a viewpoint (more like a bookmark)\n // because we don't want to modify the view in any other way\n // this also means that layers won't change their visibility with the slide, so make all layers visible from the beginning\n view.goTo(slide.viewpoint);\n }.bind(slide));\n\n slideList.appendChild(slideElement);\n });\n }\n\n }",
"function markupSlides(container) {\n // Machinery to create slide/subslide <section>s and give them IDs\n var slide_counter = -1, subslide_counter = -1;\n var slide_section, subslide_section;\n function new_slide() {\n slide_counter++;\n subslide_counter = -1;\n return $('<section>').appendTo(container);\n }\n function new_subslide() {\n subslide_counter++;\n return $('<section>').attr('id', 'slide-'+slide_counter+'-'+subslide_counter)\n .appendTo(slide_section);\n }\n\n // Containers for the first slide.\n slide_section = new_slide();\n subslide_section = new_subslide();\n var current_fragment = subslide_section;\n\n var selected_cell_idx = IPython.notebook.get_selected_index();\n var selected_cell_slide = [0, 0];\n\n // Special handling for the first slide: it will work even if the user\n // doesn't start with a 'Slide' cell. But if the user does explicitly\n // start with slide/subslide, we don't want a blank first slide. So we\n // don't create a new slide/subslide until there is visible content on\n // the first slide.\n var content_on_slide1 = false;\n\n var cells = IPython.notebook.get_cells();\n var i, cell, slide_type;\n\n for (i=0; i < cells.length; i++) {\n cell = cells[i];\n slide_type = (cell.metadata.slideshow || {}).slide_type;\n //~ console.log('cell ' + i + ' is: '+ slide_type);\n\n if (content_on_slide1) {\n if (slide_type === 'slide') {\n // Start new slide\n slide_section = new_slide();\n // In each subslide, we insert cells directly into the\n // <section> until we reach a fragment, when we create a div.\n current_fragment = subslide_section = new_subslide();\n } else if (slide_type === 'subslide') {\n // Start new subslide\n current_fragment = subslide_section = new_subslide();\n } else if (slide_type === 'fragment') {\n current_fragment = $('<div>').addClass('fragment')\n .appendTo(subslide_section);\n }\n } else if (slide_type !== 'notes' && slide_type !== 'skip') {\n // Subsequent cells should be able to start new slides\n content_on_slide1 = true;\n }\n\n // Record that this slide contains the selected cell\n if (i === selected_cell_idx) {\n selected_cell_slide = [slide_counter, subslide_counter];\n }\n\n // Move the cell element into the slide <section>\n // N.B. jQuery append takes the element out of the DOM where it was\n if (slide_type === 'notes') {\n // Notes are wrapped in an <aside> element\n subslide_section.append(\n $('<aside>').addClass('notes').append(cell.element)\n );\n } else {\n current_fragment.append(cell.element);\n }\n\n // Hide skipped cells\n if (slide_type === 'skip') {\n cell.element.addClass('reveal-skip');\n }\n }\n\n // Put .end_space back at the end after all the rearrangement\n $('.end_space').appendTo('div#notebook-container');\n return selected_cell_slide;\n}",
"function dockerSlides() {\n return ['01-docker_reminders/00-reminders.md'\n ];\n}",
"AddSlide(string, string, stSlideInfo) {\n\n }",
"function AddSlide(slide) {\r\n \r\n }",
"function addSlide() {\n\t/* create a new slide object */\n\tvar slide = new SlideSet(nextSlideType);\n\tslideSetArray[numSlide] = slide;\n\tnumSlide = numSlide + 1;\n}",
"function UnknownPersonSlide() {\n}",
"function createSlides( arr, container ) {\n\n var gal = container.querySelector(\".gallry > .slides\");\n\n // array has slides in it?\n if ( arr.length > 0 ) {\n for ( var i = 0; i < arr.length; i++ ) {\n\n var fig = document.createElement(\"FIGURE\"); // create figure element\n // create new element\n gal.appendChild( fig );\n }\n displaySlide( arr, container );\n }\n else {\n console.log(\"createSlides function needs an array to be passed in as param\");\n }\n }",
"function buildSlide(collection){\n var slideElem, slideImg, slideDesc, descTextNode, domFrag;\n domFrag = d.createDocumentFragment();\n\n collection.forEach(function(elem) {\n slideElem = d.createElement('div');\n slideImg = d.createElement('img');\n slideDesc = d.createElement('h3');\n descTextNode = d.createTextNode(elem.desc);\n slideDesc.appendChild(descTextNode);\n slideElem.appendChild(slideDesc);\n\n slideElem.className = 'slide';\n slideImg.setAttribute('src', elem.url);\n slideElem.appendChild(slideImg);\n domFrag.appendChild(slideElem);\n });\n slideContainer.appendChild(domFrag);\n }",
"function renderSlides(slidesContainer, slides, currentIndex, viewNum) {\n const slidesNum = viewNum + 2;\n const slidesToContainer = Array(slidesNum);\n const startIndex = currentIndex === 0 ? slides.length - 1 : currentIndex - 1;\n for (let i = 0; i < slidesNum; i += 1)\n slidesToContainer[i] = slides[(startIndex + i) % slides.length].cloneNode(true);\n slidesContainer.innerHTML = '';\n slidesContainer.append(...slidesToContainer);\n }",
"function buildHTMLTypePresentation(){\n\n\t\t\t\t//loop through presentation sections array\n\t\t\t\tdata.presentation.sections.forEach( function( sectiondata, sectionindex ) {\n\n\t\t\t\t\t//set section index conditionally - look for defined index in JSON data first\n\t\t\t\t\tsectiondata.index = sectiondata.index || sectionindex || 0;\n\n\t\t\t\t\t//set section attributes\n\t\t\t\t\tvar section = createNewSection( sectiondata );\n\n\t\t\t\t\t//iterate through slide objects to create each instance. attach to section array\n\t\t\t\t\tdata.presentation.sections[ sectionindex ].slides.forEach( function( slidedata, slideindex ){\n\n\t\t\t\t\t\t//push slide into SlideCarousel slide array\n\t\t\t\t\t\tsection.slides.push( createSlide( slidedata, slideindex ) );\n\n\t\t\t\t\t} );\n\n\t\t\t\t} );\n\n\t\t\t}",
"function currentSlide(n) { //aktuelle Seite\r\n showSlides(slideIndex= n);\r\n}",
"function Slideshow(slideContainer, options) {\n// private: input fields\n this.slideContainer = slideContainer;\n this.blurringPeriod = options.blurringPeriod; \n this.displayPeriod = options.displayPeriod; \n \n// private: internal variables \n this.slideIndex = 0;\n this.selectorExpression = \"#\"+slideContainer+\" > div\";\n this.slideCount = $(this.selectorExpression).length;\n \n// private: internal methods\n this.fadeIn = ___Slideshow_fadeIn;\n this.fadeOut = ___Slideshow_fadeOut;\n \n// public: exposed operations\n this.play = ___Slideshow_play;\n}",
"function tiSlideshow(container, options, id) {\n this.container = container;\n this.options = options;\n this.maskId = \"\";\n this.isOpen = false;\n this.imageList = [];\n this.currentImageIndex = 0;\n $.tiSlideshow.interfaces[id] = this;\n if (this.options.auto)\n this.open();\n }",
"function getFirstSlideImage(myJSON, container) {\n\t// creating new presentation (only for this displaying)\n\tlet myP = new Presentation(myJSON.presentation.name, container);\n\tmyP.setCurrentSlideIndex(0);\n\tmyP.addSlide(0);\n\tmyP.setTheme(myJSON.presentation.theme);\n\n\t// check for empty presentation\n\tif (myJSON.presentation.slides.length == 0) {\n\t\t// empty presentation\n\t} else {\t// non empty presentation\n\t\t// append every element (text, image, video, sound) to presentation\n\t\tfor (let j = 0; j < myJSON.presentation.slides[0].elements.length; j++){\n\t\t\tif (myJSON.presentation.slides[0].elements[j].typeElement === TEXT){\n\t\t\t\tmyP.getCurrentSlide().addText(myJSON.presentation.slides[0].elements[j].contentElement);\n\t\t\t}\n\t\t\telse if(myJSON.presentation.slides[0].elements[j].typeElement === IMAGE){\n\t\t\t\tmyP.getCurrentSlide().addImage(myJSON.presentation.slides[0].elements[j].contentElement);\n\t\t\t}\n\t\t\telse if(myJSON.presentation.slides[0].elements[j].typeElement === VIDEO){\n\t\t\t\tmyP.getCurrentSlide().addVideo(myJSON.presentation.slides[0].elements[j].contentElement);\n\t\t\t}\n\t\t\telse { // sound\n\t\t\t\tmyP.getCurrentSlide().addSound(myJSON.presentation.slides[0].elements[j].contentElement);\n\t\t\t}\n\n\t\t\t// set correct position of element\n\t\t\tmyP.getSlides()[0].getElements()[j].setAttribute('style', `left: ${myJSON.presentation.slides[0].elements[j].leftPercent}%;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t top: ${myJSON.presentation.slides[0].elements[j].topPercent}%`);\n\t\t\tmyP.getSlides()[0].getElements()[j].className = `${myJSON.presentation.slides[0].elements[j].classElement}` ;\n\t\t}\n\t}\n}",
"createSlides(array) {\r\n this._createSlides(array);\r\n }",
"function processSlide(slide) {\n var fSlide = '\\n';\n //console.log(slide);\n if('heading' in slide) {\n fSlide += '<!-- begin .slide-box ' + slide['heading']+' -->\\n' ;\n fSlide += '<a name=\"'+slide['heading']+'\"></a> \\n' ;\n }\n // everyone is a slide box\n fSlide += '<section class=\"slide-box\">\\n'\n if(slide['type']==='title') {\n \n return fSlide+=processTitle(slide);\n }\n // there is a heading\n if('heading' in slide) fSlide += '\\t<h2>'+ slide['heading']+'</h2>\\n';\n // then there is a slide type\n fSlide += '\\t<div class=\"slide-'+slide['type']+'\">\\n';\n \n // normally there is some content\n // treat codeBox as special case\n if('items' in slide) {\n if(slide['type']==='codebox') fSlide += processCode(slide['items'])\n else if(slide['type']==='blank') fSlide += processBlank(slide['items'])\n else fSlide += processItems(slide['items']);\n }\n \n fSlide += '\\t</div><!-- end div slide-'+slide['type']+' -->\\n'\n // special case for imag\n if(slide['type']=='imag' && 'image' in slide){\n fSlide += '\\t<img class=\"slide-image-only\" src=\"'+slide['image']+'\">\\n';\n }\n // special case for limg\n else if(slide['type']=='limg' && 'image' in slide){\n fSlide += '\\t<div class=\"slide-image\">' + '\\t\\t<img src=\"'+slide['image']+'\">\\n' + '\\t</div>\\n'\n }\n // end section\n fSlide += '</section><!-- end .slide-box -->\\n'\n return fSlide;\n }",
"addNewSlide () {\n const props = this.props\n const latestSettings = props.latestSettings\n const slides = latestSettings.slides || []\n props.dispatchEdition('slides', [...slides, {}])\n this.unactivateAllEditors()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize the fill filters. Generate a min and max div element that responds to mouse events that can slide within an area of 1/4th the width of the ctrldiv. Generate an interpolator to make and + values possible given the data in the fill column that we are filtering. Additional Limit closures are provided to specialize the div objects of the divMaker class to each of the min and max responsibilities. Also set closure on paneOb that enables setting values without mouse involvement. | init() {
// make a paragraph element that has the title of the fill col filter
let para = document.createElement("p")
para.id = "colfilterTitle"
para.innerHTML = "Fill Color Filter"
this.para = para
this.ctrlDiv.append(para)
// make a range slider that updates the self filter function which is called later on activity data
let rangeWidth = this.ctrlDiv.getBoundingClientRect()
// the holder for the min and max elements
let filterDiv = document.createElement("div")
filterDiv.className = "fillFilterDiv"
this.filterDiv = filterDiv
// add the background part of the slider
let backline = document.createElement("div")
backline.id = "backline"
this.backline = backline
filterDiv.append(backline)
this.ctrlDiv.append(filterDiv)
let min = new divMaker(rangeWidth.width / 4, filterDiv)
let max = new divMaker(rangeWidth.width / 4, filterDiv)
// establish the absmin and absmax of the column data
// raise hell if the data can't be sorted this way
this.setbounds(Math.min(...this.data), Math.max(...this.data))
// makes it easier to have the sliders present correct values even when negatives are involved
/** Interpolator instance to provide values in the fill column range given values 0 to 1 related to slider div placement on page */
this.interpolator = interpolator()
// values of v go in which range from 0 to 1
// the additional -1 and +1 make it so that we can still see all the data if the sliders are set to their extremes
this.interpolator.setup(0, this.absmin - 1, 1, this.absmax + 1)
/** This is the html element for the max fill slider */
this.maxel = max
/** This is the html element for the min fill slider */
this.minel = min
// make the draggable elements catch movement events and ensure that the filter method gets called when dragging stops
this.maxel.element.addEventListener("divmoved", this.filter.bind(this))
this.minel.element.addEventListener("divmoved", this.filter.bind(this))
// this si the amount of screen space that the filter div's can move, minus the width of the element
/** This is the static width of the fill slider area, 1/4 of the ctrldiv's width less 30 which is the width of a div slider */
this.width = (rangeWidth.width / 4) - 30
// create labels
/** The min slider value, this changes when the div moves */
this.minlabel = document.createElement("p")
this.minlabel.id = "minlabel"
this.minlabel.className = "filterLabel"
/** The max slider value, which changes due to user interaction with the div */
this.maxlabel = document.createElement("p")
this.maxlabel.id = "maxlabel"
this.maxlabel.className = "filterLabel"
let labelholder = document.createElement("div")
labelholder.id = "labelholder"
this.labelholder = labelholder
// prevent sliders from going over each other
min.additionalLimit = (v) => {
// stay below the max point
let maxleft = parseInt(max.element.style.left) - 10
if (v > maxleft) {
min.element.style.left = `${maxleft}px`
/** The minimum value. This is actually a measure in pixels from the side of the pane's bounding box. Not in the range of actual CSV data yet, will be set to zero if it is dragged beyond the pane's bounding box */
this.min = maxleft
// update min label
this.minlabel.innerHTML = this.interpolator.calc(maxleft / this.width).toFixed(3)
return true
}
// used at filter time
this.min = v
// update min label and account for the divslider width
this.minlabel.innerHTML = this.interpolator.calc(v / this.width).toFixed(3)
return false
}
max.additionalLimit = (v) => {
let minleft = parseInt(min.element.style.left) + 10
if (v < minleft) {
max.element.style.left = `${minleft}px`
/** The maximum value. Again, this is actually a measure in pixels from the side of the pane's bounding box. Not in the range of actual CSV data yet, will be set to zero if it is dragged beyond the pane's bounding box */
this.max = minleft
this.maxlabel.innerHTML = this.interpolator.calc(minleft / this.width).toFixed(3)
return true
}
this.maxlabel.innerHTML = this.interpolator.calc(v / this.width).toFixed(3)
// used at filter time
this.max = v
return false
}
labelholder.append(this.minlabel, this.maxlabel)
filterDiv.append(min.element)
filterDiv.append(max.element)
this.ctrlDiv.append(labelholder)
// once placed, set this to keep in correct spot, make them sit on same line
max.element.style.top = `-30px` // overlap the element with the other
max.element.style.left = "50px"
// provide a way to initialize values via styling from import
/** A function that allows creation of fill filter defaults at import time
* @alias updateFillFilter
* @memberof Pane
* @function
* @instance
* @param {*} importMin The min value that the slider should be set to
* @param {*} importMax the max value that the slider should be set to
*/
this.paneOb.updateFillFilter = (importMin, importMax) => {
// must calculate where the importMin and Max are in terms of width
// interpolate the value in min max to 0 to width
let valToLeftInterp = interpolator()
valToLeftInterp.setup(this.absmin - 1, 0, this.absmax + 1, min.width - 30)
let minConverted = valToLeftInterp.calc(importMin)
let maxConverted = valToLeftInterp.calc(importMax)
// check if within the width
if (minConverted > 0 && minConverted < maxConverted) {
min.element.style.left = minConverted + "px"
min.additionalLimit(minConverted)
} else {
min.element.style.left = "0px"
min.additionalLimit(this.absmin - 1)
}
if (maxConverted < min.width && minConverted < maxConverted) {
max.element.style.left = maxConverted + "px"
max.additionalLimit(maxConverted)
} else {
max.element.style.left = `${min.width - 30}px`
min.additionalLimit(this.absmin - 1)
}
let event = new Event("divmoved")
min.element.dispatchEvent(event)
max.element.dispatchEvent(event)
}
} | [
"filter() {\n // calculate the actual min activity value\n let fillmin = this.interpolator.calc(this.min / this.width).toFixed(3)\n let fillmax = this.interpolator.calc(this.max / this.width).toFixed(3)\n // give this information to the paneOb,useful for tooltips\n /** The min value in the fill data range used for filtering the fill column's data.\n * @alias fillmin\n * @memberof Pane\n * @instance\n */\n this.paneOb.valFilterMin = fillmin\n /** The max value in the fill data range used for filtering the fill column's data.\n * @alias fillmax\n * @memberof Pane\n * @instance\n */\n this.paneOb.valFilterMax = fillmax\n /** The data from the fill color column filtered by the min and max sliders, passed to the paneOb to be combined with the altColFilteredData at time of canvas setup and draws.\n * @alias filteredFillColData\n * @memberof Pane\n * @instance\n */\n this.paneOb.filteredFillColData = this.data.map(e => {\n // handle the three cases that one or the other (min or max) is set, or both\n if (!isNaN(fillmin) && !isNaN(fillmax)) {\n if (e >= fillmin && e <= fillmax) {\n return e\n }\n } else if (!isNaN(fillmin)) {\n if (e >= fillmin) {\n return e\n }\n } else {\n if (e <= fillmax) {\n return e\n }\n }\n\n return NaN\n })\n // emit an actual canvas filtered event \n let e = new Event(\"filterChange\")\n this.eTarget.dispatchEvent(e)\n\n }",
"createFilters() {\n if (this.fillFilter) {\n this.fillFilter.remove()\n }\n /** This is the filter allowing to only color fill regions greater than the min value and less than the max. Helpful for ascertaining which areas with similar coloration are actually higher or lower values. */\n this.fillFilter = new FillColFilter(this.ctrlDiv, this.paneOb.initialColData, this.eTarget, this.paneOb)\n this.fillFilter.init()\n // set them at default values\n // categorical filters\n if (this.altFilters) {\n this.altFilters.remove()\n }\n /** The alternate column filter. Allows for pairing down which regions are colored based on rules set on */\n this.altFilters = new AltHolder(this.ctrlDiv, this.paneOb)\n this.altFilters.init()\n\n\n }",
"setupCanvas() {\n // mingle the two filtered datasets \n /** This is a helper attribute that will hold the values that have passed all available filters */\n this.fillData = []\n // if both data filters aren't specified use whole initial range\n if (this.paneOb.filteredFillColData == undefined &&\n this.paneOb.filteredAltColData == undefined) {\n this.fillData = this.paneOb.initialColData\n } else if (this.paneOb.filteredFillColData == undefined && this.paneOb.filteredAltColData != undefined) {\n this.fillData = this.paneOb.filteredAltColData\n } else if (this.paneOb.filteredFillColData != undefined && this.paneOb.filteredAltColData == undefined) {\n this.fillData = this.paneOb.filteredFillColData\n } else {\n // if only the activity is specified\n // if both filters are around\n for (let i = 0; i < this.paneOb.initialColData.length; i++) {\n // if the two different filters have non NAN at that index add it to fill\n\n if (isNaN(this.paneOb.filteredAltColData[i]) || isNaN(this.paneOb.filteredFillColData[i])) {\n this.fillData.push(NaN)\n } else {\n this.fillData.push(this.paneOb.initialColData[i])\n\n }\n\n }\n }\n // will update the map used in the draw to determine the color of a region\n if (this.paneOb.csvData) {\n this.makeRegDataMap()\n }\n // initialize the color setting for the invisican\n let cc = color_collection(this.paneOb.sliceData.features.length)\n /** This is the map that has red,green,blue strings as keys to look up region names. an example pair would be \"15,22,180\":\"PL_Op_L\" */\n this.colToRegMap = {}\n /** This is the inverse of the colToRegMap */\n this.regToColMap = {}\n this.paneOb.sliceData.features.map((f, i) => {\n // this is for the fill on the invisible canvas\n this.regToColMap[f.properties.regionName] = cc.array[i]\n this.colToRegMap[JSON.stringify(cc.array[i])] = f.properties.regionName\n })\n // this will happen at the beginning before column selection\n if (this.fillData != undefined) {\n this.calcValueColMinMax()\n }\n // create the region data to screen space interpolators\n let xinterp = interpolator()\n let yinterp = interpolator()\n // use correct ratio\n if (this.canvasRatio > 1) {\n xinterp.setup(this.regionSizes[0], 0 + this.margin, this.regionSizes[2], this.can.width / this.canvasRatio - this.margin)\n yinterp.setup(this.regionSizes[1], (this.can.height - this.margin), this.regionSizes[3], this.margin)// extra 10is the margin split intwo\n\n } else {\n\n xinterp.setup(this.regionSizes[0], 0 + this.margin, this.regionSizes[2], this.can.width - this.margin)\n yinterp.setup(this.regionSizes[1], this.can.height * this.canvasRatio - this.margin, this.regionSizes[3], this.margin)// extra 10is the margin split intwo\n }\n /** This is the interpolator for converting region coordinate y values to the y axis of the canvas. Don't forget that 0 is the top of the canvas which is why in the setup code the full height minus the margin is mapped to the min value of the region size */\n this.yinterp = yinterp\n /** This is the interpolator for converting the x coordinates of a region's boundary to the x dimension of the canvas. */\n this.xinterp = xinterp\n }",
"function makeFiltersTab() {\n\n var slider, select;\n\n // it is required in order to set all the filter limits\n if (typeof _unique !== 'undefined') {\n\n // add tab and container\n var note = 'Use the inputs below to filter the plotted data.';\n note += '<br><span class=\"label label-default\">NOTE</span> ';\n note += 'each additional filter is combined as an <code>and</code> boolean operation.'; \n addTab(_filtersTab, 'Filters', note);\n\n // generate an input for each of the columns in the loaded dataset\n //for (var col in colTypes) {\n Object.keys(colTypes).forEach(function(col) {\n var colType = colTypes[col]\n var colVals = _unique[col];\n\n if (colType == 'int' || colType == 'float') { // if a number, render a slider\n colVals = d3.extent(_unique[col]);\n var sliderOptions = {\n start: [colVals[0], colVals[1]],\n connect: true,\n range: {\n min: colVals[0],\n max: colVals[1],\n }\n };\n\n var format;\n if (colType == 'int') {\n format = colTypes[col].format ? colTypes[col].format : function(d) { return '[' + parseInt(d[0]) + ',' + parseInt(d[1]) + ']' };\n } else if (colType == 'float') {\n format = colTypes[col].format ? colTypes[col].format : function(d) { return '[' + parseFloat(d[0]).toFixed(2) + ',' + parseFloat(d[1]).toFixed(2) + ']'; };\n }\n var opts = {id:col, label:col, domClass:'col-sm-4 filterInput', options:sliderOptions, format:format}\n slider = generateFormSlider(_filtersTab, opts);\n if (slider) { \n slider.noUiSlider.on('start',function() { \n showButton(_filtersResetBtn) // activate reset button\n })\n }\n\n } else if (colType == 'str') { // if categorical, render a select\n var opts = {\n values:colVals, \n id:col, \n label:col, \n domClass:'col-sm-4 filterInput', \n attributes:{\n multiple:true,\n 'data-actions-box':true\n },\n selectAll: true\n };\n select = generateFormSelect(_filtersTab, opts);\n select.on('change',function() { \n showButton(_filtersResetBtn) // activate reset button\n });\n } else if (colType == 'datetime' || colType == 'date') {\n var opts = {values:colVals, accessor:col, label:col, type:colType, range:true, domClass:'col-sm-8'};\n generateDateTimeInput(_filtersTab, opts);\n\n jQuery('#'+col).on('dp.change', function() { \n showButton(_filtersResetBtn) // activate reset button\n var picker1 = this.id;\n var picker2 = this.id + '2';\n })\n if (opts.range) jQuery('#'+col+'2').on('dp.change', function() { \n showButton(_filtersResetBtn) // activate reset button\n var picker1 = this.id.replace(/2$/,\"\");\n var picker2 = this.id;\n })\n }\n })\n\n // filter reset button\n // initially hide it\n d3.select('#'+_filtersTab)\n .append('div')\n .attr('class','note col-sm-2 col-sm-offset-10')\n .style('margin-bottom',0)\n .append('button')\n .attr('id',_filtersResetBtn)\n .attr('class','btn btn-warning btn-xs pull-right')\n .attr('disabled','disabled')\n .style('display','none')\n .on('click', function() { resetInputs(_filtersTab, _filtersResetBtn) })\n .text('Reset filters');\n \n }\n\n addClearFix(_filtersTab);\n }",
"calcValueColMinMax() {\n let noNan = this.fillData.reduce((acc, cur) => {\n if (!isNaN(cur)) {\n acc.push(cur)\n }\n return acc\n }, [])\n // if the panehas a filter min and max set, scan datamin and max should be equal\n if (!isNaN(this.paneOb.valFilterMin)) {\n this.scanDatamin = this.paneOb.valFilterMin\n } else {\n /** These values are the min of the entire fillData provided to the canvas. This is used in linearly interpolating the color of the fill for a region if it has data. This is the minimum value */\n this.scanDatamin = Math.min(...noNan).toFixed(3)\n }\n if (!isNaN(this.paneOb.valFilterMax)) {\n this.scanDatamax = this.paneOb.valFilterMax\n\n } else {\n /** This is the maximum value of the fillData for the canvas. */\n this.scanDatamax = Math.max(...noNan).toFixed(3)\n }\n // this normalizes the value from the scan data into the range 0 to 1 for color interpolation\n /** color interpolators for fill */\n this.colInterpolator = interpolator()\n this.colInterpolator.setup(this.scanDatamin, 0, this.scanDatamax, 1)\n // calculate the min and maxes of the scan data for each scan\n }",
"fill(fn, filter) {\n for (let y = 0; y < this.h; y++) {\n for (let x = 0; x < this.w; x++) {\n const fx = (x/this.w * 2) - 1\n const fy = (y/this.h * 2) - 1\n const v = limit(fn(fx, fy), -1, 1)\n\n this.map[y*this.w + x] = v\n this.fput(x, y, v, filter)\n }\n }\n return this\n }",
"filter() {\n\n\n /** This is the representation of the fill column after the alt column filters have been applied to it. This data will be combined with the fillColFilterData when it is time to draw to the canvas.\n * @alias filteredAltColData\n * @memberof Pane\n * @instance\n */\n this.paneOb.filteredAltColData = this.paneOb.initialColData.map((e, i) => {\n let isNa = false\n for (let altfilter of this.altfilters) {\n if (altfilter.boolMask[i] == 0) {\n isNa = true\n break\n }\n }\n if (isNa) {\n return NaN\n } else {\n return e\n }\n })\n let e = new Event(\"filterChange\")\n // get the canvas element\n this.paneOb.paneDiv.querySelector(\"canvas\").dispatchEvent(e)\n\n // extract filter name information to use in the tooltip\n\n /** This is the active alternate column filter information used for the creation of tooltips. \n * @alias altFilterInfo\n * @memberof Pane\n * @instance\n */\n this.paneOb.altFilterInfo = \"\"\n for (let altfilter of this.altfilters) {\n //\n this.paneOb.altFilterInfo += JSON.stringify(altfilter.expInfo)\n }\n }",
"function addControlListeners(map, attributes, data) {\n console.log(data);\n //month range slider\n $('#month-slider').click(function(){\n var index = $(this).val();\n var filterAmount = getRunFilter(document.getElementsByClassName('active')[0].innerText);\n\n $('#currentMonthText').text(getCurrentMonth(index));\n updatePopup(map, getCurrentMonth(index));\n updateFilter(data, map, attributes, filterAmount);\n });\n //next button\n $('#next').click(function(){\n var newIndex = $('#month-slider').val() < 11 ? parseInt($('#month-slider').val()) + 1 : 11;\n var filterAmount = getRunFilter(document.getElementsByClassName('active')[0].innerText);\n $('#month-slider').val(newIndex).slider;\n $('#currentMonthText').text(getCurrentMonth(newIndex));\n updatePopup(map, getCurrentMonth(newIndex));\n updateFilter(data, map, attributes, filterAmount);\n });\n //previous button\n $('#previous').click(function(){\n var newIndex = $('#month-slider').val() > 0 ? parseInt($('#month-slider').val()) - 1 : 0;\n var filterAmount = getRunFilter(document.getElementsByClassName('active')[0].innerText);\n $('#month-slider').val(newIndex).slider;\n $('#currentMonthText').text(getCurrentMonth(newIndex));\n updatePopup(map, getCurrentMonth(newIndex));\n updateFilter(data, map, attributes, filterAmount);\n });\n //filter menu controller\n $('.menu-ui a').click(function() {\n $(this).addClass('active').siblings().removeClass('active');\n });\n //greater than five filter controller\n $('.marathon').click(function(){\n updateFilter(data, map, attributes, \"type_mara\")\n });\n //greater than 10 filter controller\n $('.halfmarathon').click(function(){\n updateFilter(data, map, attributes, \"type_half\")\n });\n //greater than 20 filter controller\n $('.marathonrelay').click(function(){\n updateFilter(data, map, attributes, \"type_relay\")\n });\n $('.10k').click(function(){\n updateFilter(data, map, attributes, \"type_10k\")\n });\n $('.5k').click(function(){\n updateFilter(data, map, attributes, \"type_5k\")\n });\n}",
"createSelector() {\n\n // get rid of previous select dropdown if it exists\n if (this.paneOb.paneDiv.querySelector(\"#fillCol\")) {\n this.paneOb.paneDiv.querySelector(\"#fillCol\").remove()\n }\n // this is the selection element that is populated by the column names in the csv\n\n let valueColumnSelect = document.createElement(\"select\")\n valueColumnSelect.id = \"fillCol\"\n for (let key of Object.keys(this.paneOb.csvData)) {\n let option = document.createElement(\"option\")\n option.value = key\n option.innerHTML = key\n valueColumnSelect.append(option)\n }\n this.fillColDiv.append(valueColumnSelect)\n valueColumnSelect.onchange = () => {\n // make access to the selector possible\n\n /** This is the name of the column selected for use as the fill color of the regions drawn to the canvas.\n * @alias fillColValue\n * @memberof Pane\n * @instance\n */\n this.paneOb.fillColValue = valueColumnSelect.value\n // parse the data into numeric\n let numericData = this.paneOb.csvData[valueColumnSelect.value].map(e => parseFloat(e))\n\n /** This is a copy of the unfiltered numeric data in the fill column of the CSV.\n * @alias initialColData\n * @memberof Pane\n * @instance\n */\n this.paneOb.initialColData = numericData\n\n // establish filters for the selected column of data\n this.createFilters()\n\n // trigger a valcolchange event\n // this will make the filters update themselves, and make the canvas redraw the \n let e = new Event(\"valcolchange\")\n // update the canvas columdata somehow\n if (this.eTarget) {\n // send it to the canvas\n this.eTarget.dispatchEvent(e)\n }\n }\n }",
"function _initFilter() {\n $(\"#price-input\").slider({\n from: 100,\n to: 15000,\n step: 100,\n round: 1,\n format: { format: '##', locale: 'en' },\n dimension: ' $'\n });\n\n $(\"#km-input\").slider({\n from: 100,\n to: 100000,\n step: 100,\n round: 1,\n format: { format: '##', locale: 'en' },\n dimension: ' km'\n });\n\n}",
"static createFilter_Slider() {\n let filter = {\n type: 'slider',\n id: 'SLIDER'+UID++,\n active: true,\n delta: new Array(65536).fill(0),\n pixelsOut: null,\n imageData: null\n }\n return filter\n }",
"function setHeatmapControls(analysisID){\n\t\n\t//sets the slider used to resize the heatmap\n\tvar sliderID=\"#heatmapSlider_\" +analysisID;\n\tjQuery(sliderID).width('75');\n\tjQuery(sliderID).slider({\n\t\tmin:8,\n\t\tmax:25,\n\t\tvalue:15,\n\t\tstep: 1,\n\t \tstop: function(event, ui) { \n\t \t\tupdateHeatmap(analysisID);\t \t\t\n \t}\n\t});\n\t\n\t\n\t//sets the slider used to resize the heatmap\n\tvar colorSliderID=\"#heatmapColorSlider_\" +analysisID;\n\tjQuery(colorSliderID).width('75');\n\tjQuery(colorSliderID).slider({\n\t\trange: true,\n\t\tmin:-100,\n\t\tmax:100,\n\t\tvalues: [ -100, 100 ],\n\t \tslide: function(event, ui) { \n\n\t \t\t//prevent the min from being greater than 0, and the max less than 0\n/*\t \t\tif(ui.values[1] < 0.01 || ui.values[0] > -0.01){\n return false;// do not allow change\n }\n*/\t \t\t\n\t \t},\n\t \tstop: function(event, ui) { \n\t \t\tupdateHeatmap(analysisID);\t \t\t\n \t}\n\t});\n\t\n\tvar heatmapControlsDiv = \"#heatmapControls_\" +analysisID;\n\tjQuery('.heatmapControls_holder').mouseenter(function(){\n\t// clearTimeout(jQuery(this).data('timeoutId'));\n\t jQuery('body').data('heatmapControlsID', '');\n\t \n\t // jQuery(this).find(\".tooltip\").fadeIn(\"slow\");\n\t}).mouseleave(function(){\n\t //\t var timeoutId = setTimeout(function(){\n\t // \tjQuery(heatmapControlsDiv).fadeOut(\"fast\");\n\t// }, 800);\n\t //set the timeoutId, allowing us to clear this trigger if the mouse comes back over\n\t// jQuery(this).data('timeoutId', timeoutId); \n\t jQuery('body').data('heatmapControlsID', analysisID);\n\t});\n\t\n\t \n\n\t\n\t\n}",
"function setUniversalFilterDimensions() {\n\n filterCheckbox.css('transform', \"scale(\" + responsiveCalcs.filterUniversal.checkboxScale + \")\");\n\n var filterHeaders = $('h4.filter-header');\n filterHeaders.css('font-size', responsiveCalcs.filterUniversal.titleFontSize + \"px\")\n filterHeaders.css('line-height', responsiveCalcs.filterUniversal.titleLineHeight + \"px\")\n filterHeaders.css('margin-bottom', responsiveCalcs.filterUniversal.headerMarginBottom + \"px\");\n // filter options,14/20\n var filterLabels = $('label.filter-label');\n filterLabels.css('font-size', Math.min(14/683 * dashboardInnerHeight, 14/1380 * dashboardInnerWidth) + \"px\")\n filterLabels.css('min-height', Math.min(20/683 * dashboardInnerHeight, 20/1380 * dashboardInnerWidth) + \"px\")\n filterLabels.css('max-height', Math.min(20/683 * dashboardInnerHeight, 20/1380 * dashboardInnerWidth) + \"px\")\n\n\n }",
"function filterOnSliders(attr, values) {\n for (i = 0; i < attributes.length; i++){\n if (attr == attributes[i]){\n ranges[i] = values;\n }\n }\n\n // SCATTERPLOT\n var toVisualize = scatterData.filter(function(d) { return isInRange(d)});\n // filter on current checkbox selections\n if (!currDistricts[0][1]) {\n toVisualize = filterOnCurrDistricts(toVisualize, \"scatter\"); // filter based on the school districts\n }\n drawScatterplot(toVisualize);\n\n // TREEMAP\n var nTree = dataset.filter(function(d) { return isInRange(d) });\n nTree = filterOnCurrDistricts(nTree, \"tree\");\n\n var root = prepTree(nTree, currSizing);\n\n drawTree(root);\n}",
"function setLimits(){\n //max and min container movements\n var topCss = ($containerWidget.css(\"top\")>0) ? parseInt($containerWidget.css(\"top\")) : 0;\n var headerOffset = $('.top-bar').height() + /*padding of top-bar*/8 + /*bottom-margin*/10;\n var max_move = $configBlock.offset().top + $configBlock.height() - $containerWidget.height() - topCss - headerOffset;\n var min_move = $configBlock.offset().top - headerOffset;\n\n $containerWidget\n .data('min', min_move)\n .data('max', max_move);\n\n //window thresholds so the movement isn't called when its not needed!\n window_min = min_move - threshold_offset;\n window_max = max_move + $containerWidget.height() + threshold_offset;\n }",
"function createPanelFilter() {\n\t$(\"#wb-layerComboDiv\").append(\n\t\t$(\"<div>\").attr(\"class\", \"titleItem\").append(\n\t\t\t$(\"<div>\").attr(\"class\", \"filterDesc\").text(\"Layer\"),\n\t\t\t$(\"<div>\").attr(\"class\", \"filterValue\").text(\"\"),\n\t\t\t$(\"<div>\").attr(\"class\", \"filterImg\").append(\n\t\t\t\t$(\"<img>\").attr(\"src\", pathImageDown)\n\t\t\t)\n\t\t),\n\t\t$(\"<div>\").attr(\"class\", \"containerValuesCombo\").addClass(\"box-shadow-combo\")\n\t)\n\t\n\t$(\"#wb-fieldLayerComboDiv\").append(\n\t\t$(\"<div>\").attr(\"class\", \"titleItem\").append(\n\t\t\t$(\"<div>\").attr(\"class\", \"filterDesc\").text(\"Field\"),\n\t\t\t$(\"<div>\").attr(\"class\", \"filterValue\"),\n\t\t\t$(\"<input>\").attr(\"class\", \"valueFieldHidden\").attr(\"type\", \"hidden\"),\n\t\t\t$(\"<div>\").attr(\"class\", \"filterImg\").append(\n\t\t\t\t$(\"<img>\").attr(\"src\", pathImageDown)\n\t\t\t)\n\t\t),\n\t\t$(\"<div>\").attr(\"class\", \"containerValuesCombo\").addClass(\"box-shadow-combo\"),\n\t\t$(\"<div>\").attr(\"class\", \"warnignText\").text(\"You have to enable WFS request for the layer in qgs project\")\n\t)\n\t\n\t$(\"#wb-valueFieldLayerInputDiv\").append(\n\t\t$(\"<div>\").attr(\"class\", \"titleItem\").append(\n\t\t\t$(\"<div>\").attr(\"class\", \"filterDesc\").text(\"Value\"),\n\t\t\t$(\"<input>\").attr(\"class\", \"filterValue\").keyup(function(){\n\t\t\t\tenableDisableButtonFilter();\n\t\t\t})\n\t\t),\n\t $(\"<div>\").attr(\"id\", \"containerInfoInput\").append(\n\t \t$(\"<span>\").attr(\"id\", \"wb-infoInputValueFilter\").text(\"(case sensitive and exactly match)\")\n\t )\n\t)\n}",
"function constraint1ComboHandler(obj){\r\n\t\t\tif(obj.value === 'range'){\r\n\t\t\t\tExt.getCmp(\"FILTER_DATE2_PREF_FILTER\").setValue('');\r\n\t\t\t\tExt.getCmp(\"FILTER_DATE2_PREF_FILTER\").show();\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tExt.getCmp(\"FILTER_DATE2_PREF_FILTER\").setValue('');\r\n\t\t\t\tExt.getCmp(\"FILTER_DATE2_PREF_FILTER\").hide();\r\n\t\t\t}\r\n\t\t}",
"function initFilter(paramsObj) {\r\n\tselected = document.getElementById(paramsObj.id).getElementsByClassName('item');\r\n\tfilterable_content = document.getElementById(paramsObj.id);\r\n\r\n\tlet filtered = [];\r\n\tfor (var i = 0; i < selected.length; i++) {\r\n\t\tfiltered.push({\r\n\t\t\t'node': selected[i],\r\n\t\t\t'visible': true\r\n\t\t});\r\n\t}\r\n\r\n\tif (paramsObj.filterable.length > 0) {\r\n\t\tfor (var i = paramsObj.filterable.length - 1; i >= 0 ; i--) {\r\n\t\t\tcurrentFilter = paramsObj.filterable[i];\r\n\r\n\t\t\ttmpElements = [];\r\n\r\n\t\t\tif (currentFilter.type === 'str') {\r\n\t\t\t\ttmpElements.push({\r\n\t\t\t\t\t'element': createElementWAttr('input', {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'type': 'text',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'id': paramsObj.id + '_' + currentFilter.name,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'data-property-name': currentFilter.name,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'data-filter-id': paramsObj.id,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'placeholder': currentFilter.form_placeholder\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}),\r\n\t\t\t\t\t'dataToBeFiltered': filtered\r\n\t\t\t});\r\n\t\t\t\t\r\n\t\t\t} else if (currentFilter.type === 'num') {\r\n\t\t\t\ttmpElements.push({'element': createElementWAttr('input', {\r\n\t\t\t\t\t\t\t\t\t\t\t'type': 'number',\r\n\t\t\t\t\t\t\t\t\t\t\t'id': paramsObj.id + '_' + currentFilter.name + '_to',\r\n\t\t\t\t\t\t\t\t\t\t\t'data-property-name': currentFilter.name,\r\n\t\t\t\t\t\t\t\t\t\t\t'data-filter-id': paramsObj.id,\r\n\t\t\t\t\t\t\t\t\t\t\t'placeholder': currentFilter.form_placeholder[1]\r\n\t\t\t\t\t\t\t\t\t\t}),\r\n\t\t\t\t\t\t\t\t\t'dataToBeFiltered': filtered\r\n\r\n\t\t\t});\r\n\t\t\t\ttmpElements.push({'element': createElementWAttr('input', {\r\n\t\t\t\t\t\t\t\t\t\t\t'type': 'number',\r\n\t\t\t\t\t\t\t\t\t\t\t'id': paramsObj.id + '_' + currentFilter.name + '_from',\r\n\t\t\t\t\t\t\t\t\t\t\t'data-property-name': currentFilter.name,\r\n\t\t\t\t\t\t\t\t\t\t\t'data-filter-id': paramsObj.id,\r\n\t\t\t\t\t\t\t\t\t\t\t'data-from-value': 'true',\r\n\t\t\t\t\t\t\t\t\t\t\t'placeholder': currentFilter.form_placeholder[0]\r\n\t\t\t\t\t\t\t\t\t\t}),\r\n\t\t\t\t\t\t\t\t\t'dataToBeFiltered': filtered\r\n\r\n\t\t\t});\r\n\t\t\t} else if (currentFilter.type === 'enumeration') {\r\n\t\t\t\ttmpEl = createElementWAttr('select', {\r\n\t\t\t\t\t'multiple': 'true',\r\n\t\t\t\t\t'name': paramsObj.id + '_' + currentFilter.name + '[]',\r\n\t\t\t\t\t'id': paramsObj.id + '_' + currentFilter.name,\r\n\t\t\t\t\t'data-property-name': currentFilter.name,\r\n\t\t\t\t\t'data-filter-id': paramsObj.id,\r\n\t\t\t\t});\r\n\r\n\t\t\t\tselected = document.querySelectorAll(\"#\" + paramsObj.id + \" .item .\" + currentFilter.name);\r\n\t\t\t\tuniqueOptions = [];\r\n\t\t\t\tselected.forEach(function(currentValue, currentIndex, listObj) {\r\n\t\t\t\t\tif (!uniqueOptions.includes(currentValue.innerHTML)) {\r\n\t\t\t\t\t\ttmpOption = createElementWAttr('option', {\r\n\t\t\t\t\t\t\t'value': selected[currentIndex].innerHTML\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\ttmpOption.innerHTML = currentValue.innerHTML;\r\n\t\t\t\t\t\ttmpEl.append(tmpOption);\r\n\t\t\t\t\t\tuniqueOptions.push(currentValue.innerHTML);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\ttmpElements.push({\r\n\t\t\t\t\t'element': tmpEl,\r\n\t\t\t\t\t'dataToBeFiltered': filtered\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttmpElements.forEach(function(item) {\r\n\t\t\t\tfilterable_content.prepend(item.element);\r\n\t\t\t\t\r\n\t\t\t\tdocument.getElementById(item.element.id).addEventListener('input', (function(foo) {\r\n\t\t\t\t\treturn function(e) {\r\n\t\t\t\t\t\tglobalSearchHandler(e, foo.dataToBeFiltered);\r\n\t\t\t\t\t}\r\n\t\t\t\t}) (item));\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n}",
"prepRangeData() {\n let slicesByView = {\n \"sagittal\": [],\n \"axial\": [],\n \"coronal\": []\n }\n for (let n in this.paneOb.regionBoundaryData) {\n if (n.search(/cor/) == 0) {\n slicesByView[\"coronal\"].push(n)\n }\n if (n.search(/sag/) == 0) {\n slicesByView[\"sagittal\"].push(n)\n }\n if (n.search(/ax/) == 0) {\n slicesByView[\"axial\"].push(n)\n }\n }\n let sortfunc = (x, y) => {\n let xmm = parseInt(x.match(/(-?\\d+\\.?\\d*?)(mm)?/)[1])\n let ymm = parseInt(y.match(/(-?\\d+\\.?\\d*?)(mm)?/)[1])\n return xmm - ymm\n }\n slicesByView.axial.sort(sortfunc)\n slicesByView.sagittal.sort(sortfunc)\n slicesByView.coronal.sort(sortfunc)\n /** An object who's keys are the brain views, and values are lists of the slice files that match the paneOb.regionBoundaryData object. Used to figure out which slice's region boundaries are to be drawn on the canvas at any time */\n this.sliderSlices = slicesByView\n // get the array of values\n /** A similar collection to the sliderSlices, but to populate the label next to the slice slider element so users can tell which slice (in mm) they are looking at */\n this.sliderMeasurements = {}\n this.sliderMeasurements.axial = slicesByView.axial.map(sl => {\n return (sl.match(/(-?\\d+\\.?\\d*?mm)/)[1])\n })\n this.sliderMeasurements.sagittal = slicesByView.sagittal.map(sl => {\n return (sl.match(/(-?\\d+\\.?\\d*?mm)/)[1])\n })\n this.sliderMeasurements.coronal = slicesByView.coronal.map(sl => {\n return (sl.match(/(-?\\d+\\.?\\d*?mm)/)[1])\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a div for each limit in the format of "current / max" and applies CSS classes based on how close it is to the limit. | function applyLimitClassDiv(current, max) {
const remaining = max - current;
let elClass = '';
if(remaining <= 0) {
elClass = 'limit';
} else if(remaining <= char_limit_warning) {
elClass = 'warning';
}
return `<div class="${elClass}">${current} / ${max}</div>`;
} | [
"function _renderLimitBar() {\n\n // Get UI elements\n var leftTag = _dataUsageLimitView.querySelector('dt.start');\n var leftValue = _dataUsageLimitView.querySelector('dd.start');\n var rightTag = _dataUsageLimitView.querySelector('dt.end');\n var rightValue = _dataUsageLimitView.querySelector('dd.end');\n var progress = _dataUsageLimitView.querySelector('progress');\n\n // Get current total and limit\n var currentLimit = Service.dataLimitInBytes;\n var currentWarning = currentLimit * Service.getDataUsageWarning();\n\n var currentUsage = 0;\n var dataUsage = Service.settings.option('lastdatausage');\n if (dataUsage)\n currentUsage = dataUsage.mobile.total;\n\n // Determine mode\n _dataUsageLimitView.classList.remove('nearby-limit');\n _dataUsageLimitView.classList.remove('reached-limit');\n\n // Normal mode\n if (currentUsage <= currentLimit) {\n leftTag.textContent = _('used');\n rightTag.textContent = _('limit');\n leftValue.textContent = roundData(currentUsage).join(' ');\n rightValue.textContent = roundData(currentLimit).join(' ');\n progress.setAttribute('max', currentLimit);\n progress.setAttribute('value', currentUsage);\n\n // Warning mode\n if (currentUsage > currentWarning) {\n _dataUsageLimitView.classList.add('nearby-limit');\n }\n\n // Limit exceeded mode\n } else {\n leftTag.textContent = _('limit-passed');\n rightTag.textContent = _('used');\n leftValue.textContent = roundData(currentLimit).join(' ');\n rightValue.textContent = roundData(currentUsage).join(' ');\n progress.setAttribute('max', currentUsage);\n progress.setAttribute('value', currentLimit);\n\n _dataUsageLimitView.classList.add('reached-limit');\n }\n }",
"function renderLimit(model) {\n document.getElementById(\"max-current\").innerText = model.getLimit().toString();\n}",
"function setLimit(){\n var showList = param.target.find(\".search-show\");\n $(\".search-first,.search-last\").removeClass('search-first').removeClass('search-last');\n showList.first().addClass(\"search-first\");\n showList.last().addClass(\"search-last\");\n }",
"function renderBars() {\n bars = '';\n endpoint.bars.forEach(function (bar) {\n var barValue = (bar / endpoint.limit) * 100;\n if (bar > endpoint.limit) {\n bars += `<div class=\"progress\">\n <div class=\"progress-bar bg-danger\" role=\"progressbar\" style=\"width: ${barValue}%\"\n aria-valuenow=\"${barValue}\" aria-valuemin=\"0\" aria-valuemax=\"${endpoint.limit}\"></div>\n <span class=\"progress-indicator\">${bar}%</span>\n </div>`\n } else {\n bars += `<div class=\"progress\">\n <div class=\"progress-bar\" role=\"progressbar\" style=\"width: ${barValue}%\"\n aria-valuemin=\"0\" aria-valuemax=\"${endpoint.limit}\"></div>\n <span class=\"progress-indicator\">${bar}%</span>\n </div>`\n }\n });\n barGroup.innerHTML = bars;\n}",
"function getLimits() {\n\t\tvar limitMax = parseInt($(\"#limit\").val());\n\t\tvar limitMin = limitMax - (TITLE_LIMIT-1);\n\t\tvar limits = [limitMin, limitMax+1]; // add 1 to account for array 0 index\n\t\treturn limits;\n\t}",
"function updateLimits (current, limits) {\n if (current > limits.max) limits.max = current;\n if (current < limits.min) limits.min = current;\n}",
"function min_max(range_element) {\nvar current_limit = $(range_element).closest(\".limit_content.range_limit\").find(\".current\")\n\nvar min = max = BlacklightRangeLimit.parseNum(current_limit.find(\".single\").text())\nif ( isNaN(min)) {\nmin = BlacklightRangeLimit.parseNum(current_limit.find(\".from\").first().text());\nmax = BlacklightRangeLimit.parseNum(current_limit.find(\".to\").first().text());\n}\n\nif (isNaN(min) || isNaN(max)) {\n//no current limit, take from results min max included in spans\nmin = BlacklightRangeLimit.parseNum($(range_element).find(\".min\").first().text());\nmax = BlacklightRangeLimit.parseNum($(range_element).find(\".max\").first().text());\n}\n\nreturn [min, max]\n}",
"function load_max_range_preview(){\n $( \".max\" ).html( set_value_in_gigabyte(options.slider_max_value) + \" (GB)\"); \n }",
"function maxStyleIndicators() {\n $('.castle-indicator').each(function() {\n if ($(this).text().trim() == settings.values.maxCastle) {\n $(this).addClass('max-attribute');\n } else {\n $(this).removeClass('max-attribute');\n }\n });\n $('.shield-indicator').each(function() {\n if ($(this).text().trim() == settings.values.maxShield) {\n $(this).addClass('max-attribute');\n } else {\n $(this).removeClass('max-attribute');\n }\n });\n }",
"function load_max_range_preview(){\n\t\t$( \".max\" ).html( set_value_in_gigabyte(slider_max_value) + \" (GB)\");\t\n\t}",
"function _limits(limit) {\n return _.range(0, Math.ceil(limit / LIMIT)).map((val, idx) => {\n return Math.min(LIMIT, limit - (LIMIT * idx));\n });\n}",
"function calLimit(value, totalItens, itensPerPage) {\n let limitMin = 0;\n let limitMax = Math.ceil(totalItens / itensPerPage) - 1;\n let valueReturn = value;\n if (value < limitMin) {\n valueReturn = limitMin;\n }\n if (value > limitMax) {\n valueReturn = limitMax;\n }\n return valueReturn;\n}",
"function setMax() {\r\n dlMax = $('#dlcurrentmax-input').val().trim();\r\n ftsqMax = $('#ftsqcurrentmax-input').val().trim();\r\n per = 95;\r\n dlTrainingMax = (dlMax * per) / 100;\r\n frsqTrainingMax = (ftsqMax * per) / 100;\r\n var roundedNumberDl = Math.floor(dlTrainingMax);\r\n var roundedNumberSq = Math.floor(frsqTrainingMax);\r\n var newDiv = $('<div>');\r\n newDiv.addClass('workingmaxes');\r\n newDiv.html('<h2>10 Week Training Routine ' +\r\n '<br/><h3>Deadlift Training Max(95% of max): ' +\r\n roundedNumberDl + ' <br/>Front Squat Training Max(95% of max): ' + roundedNumberSq) ;\r\n $('#program').css({'color': 'rgb(255, 255, 255)',\r\n 'padding': '2rem 1rem' ,\r\n 'margin-bottom': '2rem',\r\n 'border-radius': '0.3rem',\r\n 'background': '#000064', \r\n 'background': '-webkit-linear-gradient(to right, #1BADD8, #00003E)', \r\n 'background': 'linear-gradient(to right, #1BADD8, #00003E)'});\r\n \r\n $('#program').append(newDiv); \r\n}",
"function limit(num, minNumber) {\n\n // check if value is outside of the limits\n if (!$.isNumeric(num.value) || num.value <= minNumber) {\n num.value = minNumber;\n } else if (num.id === \"override-curr-hp\") {\n if (num.value >= 100) {\n num.value = 100;\n } else if (Math.floor(num.value) !== num.value) {\n num.value = Math.floor(num.value);\n }\n } else if (num.value >= HIGHESTSTAT) {\n num.value = HIGHESTSTAT;\n } else if (Math.floor(num.value) !== num.value) {\n num.value = Math.floor(num.value);\n }\n }",
"function displayMaxCards() {\n var maxNum = getMaxNum();\n var categoryItems = $(\".category-page-filter\").find(\".category-items\").children(\".category-item\");\n \n var dblockCategoryItems = categoryItems.filter(function(i,item) {\n if($(item).hasClass(\"hiden-filter\")) {\n return false;\n }\n return true;\n });\n\n if(dblockCategoryItems.length > maxNum) {\n // hide others and add load more btn\n for(var index = 0; index < dblockCategoryItems.length; index ++) {\n \n if(index + 1 > maxNum) {\n $(dblockCategoryItems[index]).addClass(\"hiden-other\");\n }\n }\n \n displayLoadMoreBtn(parseInt(dblockCategoryItems.length - maxNum));\n\n } else {\n $(\".category-page-filter .more-btn\").addClass(\"d-none\")\n }\n }",
"handleMaximizeCounter() {\n this.template.querySelector('c-numerator').maximizeCounter();\n }",
"function getLimitCount() {\r\n\tvar resultLimit = $('#query-results-limit').val();\r\n\r\n\tif (resultLimit.match(/[a-z]/i)) {\r\n\t\t$('#query-results-limit-label').html('Invalid limit value').show();\r\n\t\treturn;\r\n\t}\r\n\tif (parseInt(resultLimit)) {\r\n\t\tif (resultLimit > 100) {\r\n\t\t\t$('#query-results-limit-label').html('Maximum limit: 100').show();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif ($('#query-results-limit-label').is(':visible')) $('#query-results-limit-label').hide();\r\n\t\treturn \"&limit=\" + resultLimit.toString();\r\n\t} else {\r\n\t\t$('#query-results-limit-label').html('Invalid limit value').show();\r\n\t\treturn;\r\n\t}\r\n}",
"function calculateLimits() {\r\n\r\n var $bottomControls = ($('.bottom_controls').length > 0) ? $('.bottom_controls').outerHeight(true) : 0;\r\n var $ascendComments = ($('.comment-wrap.full-width-section').length > 0) ? $('.comment-wrap.full-width-section').outerHeight(true) : 0;\r\n var $footerHeight = ($('body[data-footer-reveal=\"1\"]').length == 0) ? $('#footer-outer').height() : 0 ;\r\n\r\n return {\r\n limit: ($('#ajax-content-wrap').height() + $('#ajax-content-wrap').offset().top) - sticky.stickyHeight - $footerHeight -$headerHeight - $extraHeight - secondaryHeader - $bottomControls - $ascendComments,\r\n windowTop: sticky.win.scrollTop(),\r\n stickyTop: sticky.stickyTop2 - sticky.marg - $headerHeight - $extraHeight - secondaryHeader\r\n }\r\n\r\n\r\n }",
"function getLimitText() {\n var limitUrl = '&limit=';\n if (isFeelingLucky()) {\n feelingLuckyComponent.show();\n limitUrl += '1';\n } else {\n limitUrl += '10';\n }\n return limitUrl;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load all of the dust templates from a given directory, storing them either in the string of client template information, or by passing them directly to the dust engine | function load_dust_templates(path, prefix, both_prefix, prepend) {
var prefix_len = prefix.length;
var both_len = both_prefix.length;
prepend = prepend || '';
var files = fs.readdirSync(path);
var that = this;
_.each(files, function(v) {
// Skip temporary/swap files (helps for running the server while editing)
if (v[0] == '.')
return;
fs.stat(path+'/'+v, function(err, stats) {
if (stats.isDirectory()) {
that.load_dust_templates(path+'/'+v, prefix, both_prefix, prepend+v+'_');
}
else {
var contents = fs.readFileSync(path+'/'+v, 'utf8');
// Save client templates specially to serve them
if (v.substr(0, prefix_len) == prefix) {
logger.info('Loading dust template '+(prepend+v).cyan+'...', mod_name);
var template = dust.compile(contents, prepend+v.substr(prefix_len, v.length));
that.client_templates.push(template);
}
else if (v.substr(0, both_len) == both_prefix) {
logger.info('Loading dust template '+(prepend+v).magenta+'...', mod_name);
var name = v.substr(both_len, v.length);
// Client side
var template = dust.compile(contents, prepend+name);
that.client_templates.push(template);
// Server side
dust.loadSource(dust.compile(contents, prepend+name));
}
else {
// Server templates should be put into our dust engine though
logger.info('Loading dust template '+(prepend+v).green+'...', mod_name);
dust.loadSource(dust.compile(contents, prepend+v));
}
}
});
});
} | [
"function loadTemplates() {\n for (var template in templates) {\n templates[template] = fs.readFileSync(templatePath + template + '.html').toString();\n }\n }",
"function loadTemplates() {\n let templates = fs.readdirSync(options.templates);\n templates.forEach(function(template) {\n let templateName = template.split('.')[0];\n templateCache[templateName] = hbs.compile(fs.readFileSync(options.templates + '/' + template).toString());\n });\n}",
"loadTemplates(dir, name, templateDir) {\n // Load in and compile the templates in the view's dir using dust.\n let files\n try {\n files = fs.readdirSync(path.join(dir, templateDir))\n } catch (e) {\n return false\n }\n if (files) {\n for (\n let file of files) {\n let content = util.file.readIfFile(path.join(dir, templateDir, file))\n let templateName = path.join(name, file)\n viewEngine.compileMethod(content, templateName)\n }\n return true\n } else {\n console.log('No Partials Found')\n }\n }",
"function loadTemplates() {\n var templates = {};\n\n var templatesLoc = _path2[\"default\"].join(__dirname, \"transformation/templates\");\n if (!_pathExists2[\"default\"].sync(templatesLoc)) {\n throw new ReferenceError(messages.get(\"missingTemplatesDirectory\"));\n }\n\n var _arr3 = _fs2[\"default\"].readdirSync(templatesLoc);\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var name = _arr3[_i3];\n if (name[0] === \".\") return;\n\n var key = _path2[\"default\"].basename(name, _path2[\"default\"].extname(name));\n var loc = _path2[\"default\"].join(templatesLoc, name);\n var code = _fs2[\"default\"].readFileSync(loc, \"utf8\");\n\n templates[key] = parseTemplate(loc, code);\n }\n\n return templates;\n}",
"function loadTemplates() {\n\t var templates = {};\n\n\t var templatesLoc = _path2[\"default\"].join(__dirname, \"transformation/templates\");\n\t if (!_pathExists2[\"default\"].sync(templatesLoc)) {\n\t throw new ReferenceError(messages.get(\"missingTemplatesDirectory\"));\n\t }\n\n\t var _arr3 = _fs2[\"default\"].readdirSync(templatesLoc);\n\n\t for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n\t var name = _arr3[_i3];\n\t if (name[0] === \".\") return;\n\n\t var key = _path2[\"default\"].basename(name, _path2[\"default\"].extname(name));\n\t var loc = _path2[\"default\"].join(templatesLoc, name);\n\t var code = _fs2[\"default\"].readFileSync(loc, \"utf8\");\n\n\t templates[key] = parseTemplate(loc, code);\n\t }\n\n\t return templates;\n\t}",
"function preloadTemplates() {\n\ttemplateFiles = {};\n\tloadWholeDirectory('templates', templateFiles, function aDir(list) {\n\t\tmaybeServe(true, false);\n\t}, function cp() {\n\t\tcompletePreloads();\n\t});\n\t\n}",
"function Mustache(templateDirs = ['./templates']) {\n this.templates = {};\n for (const templateDir of templateDirs) {\n for (const fname of fs.readdirSync(templateDir)) {\n const m = fname.match(/^([\\w\\-]+)\\.ms$/);\n if (!m) continue;\n try {\n this.templates[m[1]] =\n String(fs.readFileSync(`${templateDir}/${fname}`));\n }\n catch (e) {\n console.error(`cannot read ${fname}: ${e}`);\n process.exit(1);\n }\n }\n }\n}",
"loadExternalTemplates() {\n const config = util_1.ProjectConfig.getConfig();\n const customTemplates = [];\n for (const entry of config.customTemplates) {\n let template;\n // tslint:disable-next-line:prefer-const\n let [protocol, value] = entry.split(/(^[^:]+):/).filter(x => x);\n switch (protocol) {\n default:\n // in case just path is passed:\n value = entry;\n case \"file\":\n case \"path\":\n value = value.replace(/template\\.json$/, \"\");\n if (util_1.Util.directoryExists(value)) {\n // try single template\n template = this.loadFromConfig(path.join(value, \"template.json\"));\n if (template !== null) {\n customTemplates.push(template);\n break;\n }\n // try folder of templates:\n for (const folder of util_1.Util.getDirectoryNames(value)) {\n template = this.loadFromConfig(path.join(value, folder, \"template.json\"));\n if (template !== null) {\n customTemplates.push(template);\n }\n }\n }\n else {\n // TODO: Util.log(`Ignored: Incorrect custom template path for \"${entry}\".`);\n }\n break;\n case \"ignored\":\n break;\n }\n }\n this.addTemplates(customTemplates);\n }",
"function loadTemplates() {\n // This loop will spit out all the template\n for (num = 0; num < templates.length; ++num) {\n var source = $(templates[num][\"templatesource\"] + \"\").html();\n var handlebarscompile = Handlebars.compile(source);\n \n // Determine if we are rendering the template at the beginning\n // Or the end of the DIV\n $(templates[num][\"templatehtml\"] + \"\").append(handlebarscompile(context));\n }\n}",
"loadTemplates() {\n this.peer.logger.debug(`${this.name} loading templates`)\n this.templates = {}\n return new Promise((resolve) => {\n if (this.peer.isHeadless) {\n let projectDir = this.peer.settings.headless.projectDir\n glob(path.join(projectDir, 'apps', '**', '{*.html,!browser_wrapper.html}'), {matchBase: true}, (err, filePaths) => {\n Promise.all(filePaths.map(r => fs.readFileAsync(r, 'utf8')))\n .then(htmlData => {\n htmlData.forEach((html, i) => {\n let fileInfo = filePaths[i].replace(projectDir + '/', '').split(path.sep)\n let templateName = fileInfo[1] + '-' + fileInfo[fileInfo.length - 1].replace('.html', '')\n this.templates[templateName] = Ractive.parse(html, {csp: true})\n })\n // Write the templates to file, so the browser can use them\n // as well. First set them to the global namespace.\n let templateFile = path.join('public', 'js', 'templates.js')\n let templateData = 'window.templates=' + JSON.stringify(this.templates)\n fs.readFileAsync(templateFile, 'utf8')\n .then((content) => {\n if (content !== templateData) {\n fs.writeFileAsync(templateFile, templateData)\n .then(() => {\n resolve(this.templates)\n })\n } else {\n resolve(this.templates)\n }\n })\n })\n })\n } else {\n this.templates = global.templates\n resolve(this.templates)\n }\n })\n }",
"function fetchTemplates() {\n\tprint(\"\\x1b[90m->\\x1b[0m gathering templates...\");\n\tlet [ temps, err ] = os.readdir(\"src/templates\").filter(x => x != \".\" && x != \"..\");\n\tif (err) return print(err);\n\ttemps = temps.filter(x => x != \".\" && x != \"..\");\n\n\tlet x = 0;\n\ttemps.forEach((filename) => new Promise((resolve, reject) => {\n\t\tlet _f = std.open(\"src/templates/\" + filename, \"r\");\n\t\tif (_f.error()) return reject(_f.error());\n\t\ttemplates[filename] = _f.readAsString().replace(/\\r/g, \"\"); // windows newline =[\n\t\t_f.close();\n\n\t\tif (++x == temps.length)\n\t\t\tfetchWiki();\n\t\tresolve();\n\t}).catch(print));\n}",
"static preloadTemplates() {\n let templates = [\n \"templates/partials/need-row.html\",\n \"templates/partials/needs-table.html\",\n ];\n\n templates = templates.map(t => `modules/FoundryPLANT/${t}`);\n loadTemplates(templates);\n }",
"resolveTemplates () {\n this.devTemplate = this.resolveCommonAgreementFilePath(\n 'devTemplate',\n {\n defaultValue: this.getLibFilePath('client/index.dev.html'),\n siteAgreement: 'templates/dev.html',\n themeAgreement: 'templates/dev.html'\n }\n )\n\n this.ssrTemplate = this.resolveCommonAgreementFilePath(\n 'ssrTemplate',\n {\n defaultValue: this.getLibFilePath('client/index.ssr.html'),\n siteAgreement: 'templates/ssr.html',\n themeAgreement: 'templates/ssr.html'\n }\n )\n\n logger.debug('SSR Template File: ' + chalk.gray(this.ssrTemplate))\n logger.debug('DEV Template File: ' + chalk.gray(this.devTemplate))\n }",
"function loadTemplate() {\n var templatePattern = /@[[a-zA-Z0-9]+]/g;\n\n templateContent = _fs.readFileSync(templatePath, fileEncoding);\n templatePlaceholders = templateContent.match(templatePattern);\n\n }",
"function renderStaticTemplates(){\n renderHandlebarsTemplate(proxyPrefix + 'kpcc-header.handlebars', '#kpcc-header');\n renderHandlebarsTemplate(proxyPrefix + 'kpcc-footer.handlebars', '#kpcc-footer');\n renderHandlebarsTemplate('static-files/templates/data-share.handlebars', '#data-share');\n renderHandlebarsTemplate('static-files/templates/data-details.handlebars', '#data-details');\n renderHandlebarsTemplate('static-files/templates/data-visuals.handlebars', '#data-visuals');\n renderHandlebarsTemplate('static-files/templates/data-footer.handlebars', '#data-footer');\n}",
"function loadTemplates() {\n plugin.loadTemplates(self.settings().templates, true);\n }",
"function setupTemplates(app, dir) {\n app.templates = {};\n for (let fname of fs.readdirSync(dir)) {\n const m = fname.match(/^([\\w\\-]+)\\.ms$/);\n if (!m) continue;\n try {\n app.templates[m[1]] =\n\tString(fs.readFileSync(`${TEMPLATES_DIR}/${fname}`));\n }\n catch (e) {\n console.error(`cannot read ${fname}: ${e}`);\n process.exit(1);\n }\n }\n}",
"function getTemplates() {\r\n $.ajax({\r\n url: opts.templateFileURL,\r\n success: opts.onTemplateLoaded || handleTemplateResponse\r\n });\r\n }",
"function setupTemplates(app, dir) {\n app.templates = {};\n for (let fname of fs.readdirSync(dir)) {\n console.log(\"field name -> \" + fname);\n const m = fname.match(/^([\\w\\-]+)\\.ms$/);\n if (!m) continue;\n try {\n app.templates[m[1]] =\n //String(fs.readFileSync(`${TEMPLATES_DIR}/create.ms`));\n //console.log(\"app.templates[m[1]] -> \"+app.templates[m[1]]);\n String(fs.readFileSync(`${TEMPLATES_DIR}/${fname}`));\n }\n catch (e) {\n console.error(`cannot read ${fname}: ${e}`);\n process.exit(1);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================================================================= loadData function Desc: Will request data from stream given a specific timeframe (start, end) ============================================================================= | function loadData(start, end){
var filter = $('#filter').val();
if ($.isNumeric(filter) == false){
filter = 1;
}
isNewData = true;
var rest_request_values = "/stream/getstreamdata?streamid="+streamId
+"&startdate="+start.format('YYYY-MM-DD')
+"&enddate="+end.format('YYYY-MM-DD')
+"&filter=" + filter;
console.log(start.format('YYYY-MM-DD'))
console.log(end.format('YYYY-MM-DD'))
var rest_request_info = "/stream/getstreaminfo?streamid="+streamId;
var rest_request_setting = "/streams/settings?streamid="+streamId+"&msgtype="+messageType;
queue()
.defer(d3.json, rest_request_values)
.defer(d3.json, rest_request_info)
.defer(d3.json, rest_request_setting)
.awaitAll(handleData);
} | [
"function getDataFromTimeRange(start, end, requestedUri, data) {\n if (!data || data.length === 0) {\n return null;\n }\n let startStrs = start.toString().split('-');\n let startDate = new Date(parseInt(startStrs[0]), parseInt(startStrs[1]) - 1, parseInt(startStrs[2]));\n let unixStart = startDate.getTime();\n let endStrs = end.toString().split('-');\n let endDate = new Date(parseInt(endStrs[0]), parseInt(endStrs[1]) - 1, parseInt(endStrs[2]));\n endDate.setDate(endDate.getDate() + 1);\n let unixEnd = endDate.getTime();\n let numDays = 0;\n\n let result = {};\n result.data = [];\n result.labels = [];\n result.unixTimeLabels = [];\n\n let current = new Date(parseInt(startStrs[0]), parseInt(startStrs[1]) - 1, parseInt(startStrs[2]));\n while (current <= endDate) {\n ++numDays;\n let label = `${current.getMonth() + 1}-${current.getDate()}`;\n result.labels.push(label);\n result.unixTimeLabels.push(current.getTime());\n current.setDate(current.getDate() + 1);\n }\n numDays -= 1;\n // console.log('num day == ' + numDays);\n\n let zeros = [];\n for (let i = 0; i < numDays; ++i)\n zeros.push(0);\n\n requestedUri.forEach(uri => {\n result.data.push({\n name: uri,\n traffic: [...zeros],\n });\n });\n\n let unixTimeRange = result.unixTimeLabels;\n\n for (let i = 0; i < data.length; ++i) {\n let unixTime = data[i].utime * 1000;\n if (unixTime < unixStart || unixTime >= unixEnd) {\n // out of range, skip to next data row.\n continue;\n }\n\n let uri = data[i].uri;\n // console.log('on i = ' + i + ' ' + uri);\n for (let j = 0; j < numDays; ++j) {\n let current = unixTimeRange[j];\n let next = unixTimeRange[j + 1];\n // console.log(`${current} ${unixTime} ${next}`);\n if (unixTime >= current && unixTime < next) {\n for (let k = 0; k < requestedUri.length; ++k) {\n if (uri === requestedUri[k]) {\n result.data[k].traffic[j] += 1;\n break;\n }\n }\n break;\n }\n }\n }\n result.labels.pop();\n result.unixTimeLabels.pop();\n console.log(result);\n return result;\n}",
"function loadDataSets(start, end){\n console.log(\"4. get data sets\");\n\n //Get data for all streams\n var q = queue();\n for(var i=0; i < metaData.streams.length; i++){\n var rest_request_values = \"/stream/getstreamdata?streamid=\"+metaData.streams[i].sid\n +\"&startdate=\"+moment(start).format('YYYY-MM-DD')\n +\"&enddate=\"+moment(end).format('YYYY-MM-DD')\n +\"&filter=\" + metaData.streams[i].filter;\n q = q.defer(d3.json, rest_request_values);\n }\n q.awaitAll(handleLoadedDataSets);\n}",
"function loadDates(){\n var rest_request_dates = \"/stream/getstreamdates?streamid=\"+streamId;\n queue()\n .defer(d3.json, rest_request_dates)\n .awaitAll(loadDateRangePicker);\n}",
"function getTrafficData (uaaToken, startTime, endTime, size) {\n var token = 'Bearer '+ uaaToken;\n // Your traffic api predix zone id.\n var trafficPredixZoneId = '7f6545e2-3a78-4ee8-9390-a6616de09050';\n\n // Traffic Events URL. This will be obtained from HATEOAS model.\n var trafficEventsUrl = 'https://ie-traffic.run.aws-usw02-pr.ice.predix.io/v1/assets/1000000018/events';\n\n var deferred = $q.defer();\n\n // Ajax call to traffic events api.\n $http({\n method: 'GET',\n url: trafficEventsUrl,\n params: {'event-types':'TFEVT', 'start-ts':startTime, 'end-ts':endTime, 'size':size},\n headers: {'Authorization': token, 'Predix-Zone-Id': trafficPredixZoneId},\n timeout: 30000,\n cache: false\n })\n .success(function(data){\n deferred.resolve(data);\n })\n .error(function(err){\n deferred.reject(err);\n });\n return deferred.promise;\n }",
"async _streamData() {\n this.currentChart = \"DISCO WORM\";\n let xVals = [];\n let yVals = [];\n\n let self = this;\n dataService.startStreaming(5, function(x, y) {\n xVals.push(x);\n yVals.push(y);\n self.graphPoints = self._convertGraphPoints(xVals, yVals);\n self._generateTable([\"x\", \"y\"]);\n });\n }",
"loadData(url, callback, extraheaders) {\n this.proxyUrl(\n url,\n dods => {\n let dds = \"\";\n while (!dds.match(/\\nData:\\n$/)) {\n let c = dods.splice(0, 1);\n if (c.length === 0) throw new Error(\"Error reading data, are you sur this is a .dods request ?\");\n dds += String.fromCharCode(c);\n }\n dds = dds.substr(0, dds.length - 7);\n\n let daplet = new ddsParser(dds).parse();\n let data = new dapUnpacker(dods, daplet).getValue();\n this._applydata(data, daplet);\n callback(daplet);\n },\n true,\n extraheaders\n );\n }",
"function getData() {\n sc.firstDataLoad = true;\n plotDataHttp.provider.get(sc.src)\n .success(function(data, status, headers, config) {\n if (headers(\"Content-Type\").indexOf('application/json') == 0)\n format = 'json';\n processData(data);\n })\n .error(function() {\n throw Error(\"failed to read data from \" + sc.src);\n });\n }",
"function loadData(){\n\td3.queue()\n\t\t.defer(d3.csv,\"public/locationsinter.csv\", parseLocations) //locations_nest\n .defer(d3.csv,\"public/res3.csv\", parseSamples)\n .await(callbackDataLoaded)\n}",
"function getNewTimeRangeData (p) {\n //console.log(formatDate(p.start));\n //console.log(formatDate(p.end));\n\n if (p.manual === undefined) {\n //Update timeline graph data too\n p.manual = true;\n getNewTimelineData(p);\n timeline.setWindow(p.start, p.end);\n }\n\n let timeMod = getTimeMod(p.start, p.end);\n let start = formatDate(p.start);\n let end = formatDate(p.end);\n\n /* sensor 1 fetch - fermenter temperature */\n let queryString = \"./sensor1?start=\" + start + \"&end=\" + end + \"&mod=\" + timeMod;\n jQuery.getJSON(queryString, function(sensor1_data, status) {\n if (status == \"success\") {\n let items = [];\n console.log(\"returned \" + sensor1_data.sensor1.length + \" sensor1 entries\");\n sensor1_data.sensor1.forEach(function(entry) {\n if (globals.sensor_cache[sensorEnum.FERMENTER_TEMP][entry.index] === undefined) {\n globals.sensor_cache[sensorEnum.FERMENTER_TEMP][entry.index] = 1;\n\n let item = {};\n //item['id'] = entry.index; --can't use with groups\n item['x'] = entry.timestamp;\n item['y'] = entry.temperature;\n item['group'] = sensorEnum.FERMENTER_TEMP;\n items.push(item);\n }\n });\n if (items.length > 0) {\n dataset.add(items);\n }\n items.length=0; //Tell javascript we are done with this?\n } else {\n console.log(\"Jquery failed to get sensor1 information\");\n }\n });\n\n /* sensor 2 fetch - ambient temperature */\n queryString = \"./sensor2?start=\" + start + \"&end=\" + end + \"&mod=\" + timeMod;\n jQuery.getJSON(queryString, function(sensor2_data, status) {\n if (status == \"success\") {\n let items = [];\n sensor2_data.sensor2.forEach(function(entry) {\n if (globals.sensor_cache[sensorEnum.AMBIENT_TEMP][entry.index] === undefined) {\n globals.sensor_cache[sensorEnum.AMBIENT_TEMP][entry.index] = 1;\n\n let item = {};\n //item['id'] = entry.index; --can't use with groups\n item['x'] = entry.timestamp;\n item['y'] = entry.temperature;\n item['group'] = sensorEnum.AMBIENT_TEMP; //Note different group\n items.push(item);\n }\n });\n if (items.length > 0) {\n dataset.add(items);\n }\n items.length=0; //Tell javascript we are done with this\n } else {\n console.log(\"Jquery failed to get sensor2 information\");\n }\n });\n}",
"function playSegment(range, url) {\n var xhr = new XMLHttpRequest();\n if (range || url) { // Make sure we've got incoming params\n xhr.open('GET', url);\n xhr.setRequestHeader(\"Range\", \"bytes=\" + range);\n xhr.send();\n xhr.responseType = 'arraybuffer';\n try {\n xhr.addEventListener(\"readystatechange\", function () {\n if (xhr.readyState === xhr.DONE) { //wait for video to load\n // Calculate when to get next segment based on time of current one\n segCheck = (timeToDownload(range) * 0.8).toFixed(3); // Use point eight as fudge factor\n // Add received content to the buffer\n try {\n videoSource.appendBuffer(new Uint8Array(xhr.response));\n } catch (e) {\n log('Exception while appending', e);\n }\n }\n }, false);\n } catch (e) {\n log(e);\n return; // No value for range\n }\n }\n }",
"function playSegment(range, url) {\n var xhr = new XMLHttpRequest();\n if (range || url) { // Make sure we've got incoming params\n xhr.open('GET', url);\n xhr.setRequestHeader(\"Range\", \"bytes=\" + range);\n xhr.send();\n xhr.responseType = 'arraybuffer';\n try {\n xhr.addEventListener(\"readystatechange\", function () {\n if (xhr.readyState == xhr.DONE) { //wait for video to load\n // Calculate when to get next segment based on time of current one\n segCheck = (timeToDownload(range) * .8).toFixed(3); // Use .8 as fudge factor\n segLength.textContent = segCheck;\n // Add received content to the buffer\n try {\n videoSource.appendBuffer(new Uint8Array(xhr.response));\n } catch (e) {\n log('Exception while appending', e);\n }\n }\n }, false);\n } catch (e) {\n log(e);\n return // No value for range\n }\n }\n}",
"function DataSource() {\n\n var loaded = {};\n\n function get(source, latmin, latmax, lonmin, lonmax, callback) {\n\n\tif( source.type == 'shape' ) {\n\n\t //async.nextTick(function() { callback('not rendering shapes'); });\n\t //return;\n\t \n\t var data = loaded[source.type + '#' + source.file];\n\t if( data == null )\n\t\tloaded[source.type + '#' + source.file] = { status: 'loading', waitlist: [ callback ], data: null };\n\t else if( data.status == 'loading' ) {\n\t\t//console.log('waiting for ' + source.file);\n\t\tdata.waitlist.push(callback);\n\t\treturn;\n\t } else if( data.status == 'error' ) {\n\t\tprocess.nextTick(function(){ callback('error'); });\n\t\treturn;\n\t } else {\n\t\t//console.log('returning loaded data for ' + source.file);\n\t\tprocess.nextTick(function(){ callback(null, data.data); });\n\t\treturn;\n\t }\n\t\n\t var chunks = [];\n\n\t var zipname = source.file.replace('.shp','.zip');\n\t console.log('reading ' + source.file);\n\t var instream = fs.createReadStream(zipname);\n\t if( instream == null )\n\t\tconsole.log('reading ' + zipname + ' failed');\n\t var shapestr = shp2json(instream);\n\t delete shapestr.chunks;\n\t instream.on('error', function(err) {\n\t\tconsole.log('ERROR READING SOURCE: ' + err);\n\t });\n\t shapestr.on('data', function(data) {\n\t\tchunks.push(data);\n\t });\n\t shapestr.on('error', function(err) {\n\t\tconsole.log('ERROR reading shape data: ' + err);\n\t });\n\t shapestr.on('end', function() {\n\t\tconsole.log('loaded ' + source.file);\n\t\ttry {\n\t\t var shapedata = chunks.join('');\n\t\t var shape = JSON.parse(shapedata);\n\t\t var obj = loaded['shape#' + source.file];\n\t\t obj.status = 'loaded';\n\t\t obj.data = shape;\n\t\t async.forEachSeries(obj.waitlist, function(cb, waitcallback) {\n\t\t\tcb(null, shape);\n\t\t\tasync.nextTick(waitcallback);\n\t\t }, function() {\n\t\t\t//console.log('returned loaded data to ' + obj.waitlist.length);\n\t\t\tobj.waitlist = [];\n\t\t });\n\t\t} catch(err) {\n\t\t var obj = loaded['shape#' + source.file];\n\t\t obj.status = 'error';\n\t\t async.forEachSeries(obj.waitlist, function(cb, waitcallback) {\n\t\t\tcb('error');\n\t\t\tasync.nextTick(waitcallback);\n\t\t }, function() {\n\t\t\t//console.log('returned error to ' + obj.waitlist.length);\n\t\t\tobj.waitlist = [];\n\t\t });\n\t\t console.log('error reading data: ' + err.stack);\n\t\t}\n\t });\n\t} else if( source.type == 'postgis' ) {\n\n\t function formatQuery(query) {\n\t\tif( query == null )\n\t\t return null;\n\t\treturn query.replace(/&/g, '&').\n\t\t replace(/#/g, '#').\n\t\t replace(/[\\n\\r\\u2028\\u2029]/g,'').\n\t\t replace(/'/g, '\\'').\n\t\t replace(/(/g, '(').\n\t\t replace(/)/g, ')').\n\t\t replace(/</g, '<').\n\t\t replace(/>/g, '>').\n\t\t replace(/"/g, '\"').\n\t\t replace(/AS/g, ' AS').\n\t\t replace(/WHERE/g, ' WHERE').\n\t\t replace(/ORDER/g, ' ORDER').\n\t\t replace(/ NULLS L AST/g, ' NULLS LAST').\n\t\t replace(/FROM/g, ' FROM');\n\t }\n\n\t var connectionString = 'pg://osmusername:osmpassword@localhost/osm';\n\t pg.connect(connectionString, function(err, dbclient) {\n\t\tif(err) {\n\t\t process.stdout.write('error connecting to postgis: ' + err + '\\n');\n\t\t callback(err);\n\t\t} else {\n\t\t \n\t\t var polytext = 'GeomFromText(\\'POLYGON((' + \n\t\t\tlonmin + ' ' + latmin + ', ' + lonmin + ' ' + latmax + ', ' + \n\t\t\tlonmax + ' ' + latmax + ', ' + lonmax + ' ' + latmin + ', ' +\n\t\t\tlonmin + ' ' + latmin + '))\\',4326)';\n\n\t\t //var query = 'select osm_id, landuse, ST_AsText(way) from planet_osm_polygon where ' + \n\t\t //\t'landuse is not null and way && ' + polytext + ';';\n\n\t\t var query = formatQuery(source.table);\n\n\t\t var parentheses = query.match(/^\\((.+)\\)\\s*AS\\s*data$/);\n\t\t if( parentheses )\n\t\t\tquery = parentheses[1];\n\n\t\t if( query == null ) {\n\t\t\tasync.nextTick(function() { callback('invalid query ' + source.table); });\n\t\t\treturn;\n\t\t }\n\n\t\t query = query.replace(/SELECT way/, 'SELECT ST_AsText(way)');\n\n\t\t var orderndx = query.indexOf('ORDER BY');\n\t\t var wherendx = query.indexOf('WHERE ');\n\t\t if( orderndx != -1 ) {\n\t\t\tquery = query.substring(0, orderndx) + \n\t\t\t ( wherendx == -1 ? ' WHERE ' : ' AND ') +\n\t\t\t source.geometry_field + ' && ' + polytext + ' ' + \n\t\t\t query.substring(orderndx);\n\t\t } else {\n\t\t\tquery = query + \n\t\t\t ( wherendx == -1 ? ' WHERE ' : ' AND ') +\n\t\t\t source.geometry_field + ' && ' + polytext;\n\t\t }\n\t\t console.log('postgis query ' + query);\n\t\t query = dbclient.query(query + ';');\n\t\t \n\t\t var numrows = 0, numpolygons = 0, numpolygons_clipped = 0;\n\t\t query.on('error', function(err) {\n\t\t\tconsole.log('postgis error ' + err);\n\t\t\tcallback(err);\n\t\t });\n\t\t var rows = { features: [] };\n\t\t query.on('row', function(row) {\n\n\t\t\t//if( rows.features.length >= 100 )\n\t\t\t// return;\n\t\t\t\n\t\t\tvar geomtext = row.st_astext;\n\t\t\tvar geomobj = { properties: {}, geometry: {} };\n\t\t\tif( geomtext.indexOf('POLYGON(') == 0 ) {\n\n\t\t\t geomobj.geometry.type = 'Polygon';\n\t\t\t geomobj.geometry.coordinates = [];\n\n\t\t\t geomtext = geomtext.substring(8, geomtext.length-1);\n\t\t\t var polygons = geomtext.split('),(');\n\t\t\t \n\t\t\t for( var ppi = 0; ppi < polygons.length; ppi++ ) {\n\t\t\t\tvar i1 = 0;\n\t\t\t\tif( polygons[ppi][0] == '(' )\n\t\t\t\t i1 = 1;\n\t\t\t\tvar i2 = polygons[ppi].length;\n\t\t\t\tif( polygons[ppi][polygons[ppi].length-1] == ')' )\n\t\t\t\t i2 = polygons[ppi].length-1;\n\t\t\t\tvar polytext = polygons[ppi].substring(i1, i2).split(',');\n\t\t\t\t\n\t\t\t\tvar geom = [];\n\t\t\t\tfor( var gi = 0; gi < polytext.length; gi++ ) {\n\t\t\t\t try {\n\t\t\t\t\tvar ctext = polytext[gi].split(' ');\n\t\t\t\t\tgeom.push([ parseFloat(ctext[0]), parseFloat(ctext[1]) ]);\n\t\t\t\t } catch( exc ) {\n\t\t\t\t\tconsole.log('exception: ' + exc + '\\n' + exc.stack);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\tif( geom.length == 0 )\n\t\t\t\t console.log('ERROR ZERO COORDINATES');\n\t\t\t\tgeomobj.geometry.coordinates.push(geom);\n\t\t\t }\n\t\t\t} else if( geomtext.indexOf('LINESTRING(') == 0 ) {\n\n\t\t\t geomobj.geometry.type = 'LineString';\n\t\t\t geomobj.geometry.coordinates = [];\n\t\t\t \n\t\t\t geomtext = geomtext.substring(11, geomtext.length-1);\n\t\t\t geomtext = geomtext.split(',');\n\t\t\t var geom = [];\n\t\t\t for( var gi = 0; gi < geomtext.length; gi++ ) {\n\t\t\t\ttry {\n\t\t\t\t var ctext = geomtext[gi].split(' ');\n\t\t\t\t geom.push([ parseFloat(ctext[0]), parseFloat(ctext[1]) ]);\n\t\t\t\t} catch( exc ) {}\n\t\t\t }\n\t\t\t geomobj.geometry.coordinates = geom;\n\t\t\t}\n\t\t\t\n\t\t\trows.features.push(geomobj);\n\t\t });\n\t\t query.on('end', function() {\n\t\t\tif( rows.length == 0 )\n\t\t\t callback('no postgis results');\n\t\t\telse\n\t\t\t callback(null, rows);\n\t\t });\n\t\t}\n\t }); \n\t} else {\n\t console.log('unknown data type ' + source.type);\n\t async.nextTick(function() {\n\t\tcallback('unknown data type ' + source.type);\n\t });\n\t}\n }\n\n return {\n\tget: get\n };\n}",
"function loadFromKiWIS(tsName, start, end, format, func, err) {\n\t\t\tif(err === undefined)\n\t\t\t\terr = function() {};\n\t\t\tif(end < start)\n\t\t\t\treturn this.loadFromKiWIS(tsName, end, start, format, func, err);\n\n\t\t\t/* \n\t\t\t * These 2 variables are combined with the timeseries id to form the KiWIS URL from which data is retrieved\n\t\t\t */\n\t\t\tvar prefix = \"http://waterdata.quinteconservation.ca/KiWIS/KiWIS?service=kisters&type=queryServices&request=getTimeseriesValues&datasource=0&format=\" + format + \"&ts_id=\";\n\t\t\tvar suffix = \"&header=true&metadata=true&md_returnfields=station_name,parametertype_name&dateformat=UNIX\";\n\t\t\tif(start !== null)\n\t\t\t\tsuffix += \"&from=\" + start;\n\t\t\tif(end !== null)\n\t\t\t\tsuffix += \"&to=\" + end;\n\n\t\t\tthis.numData++;//Keep track of how many times makeDataByYear is called in order to properly show/hide 'loading...' text\n\t\t\t$.ajax({\n\t\t\t\tdataType: (format === 'csv'? \"text\" : format),\n\t\t\t\turl: prefix + this.getId(tsName, start, end) + suffix,\n\t\t\t\tsuccess: $.proxy(function(res) {\n\t\t\t\t\tthis.numData--;//reduce numData now that the request has returned\n\t\t\t\t\t$.proxy(func, this)(res);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif(footerPos !== undefined)\n\t\t\t\t\t\t\tfooterPos();//reposition the footer once the request has finished\n\t\t\t\t\t} catch(ex) {}\n\t\t\t\t}, this),\n\t\t\t\terror: $.proxy(function(res) {\n\t\t\t\t\tthis.numData--;//reduce numData so as to not cause problems\n\t\t\t\t\terr(res, func);\n\t\t\t\t}, this)\n\t\t\t});\n\t\t}",
"function createDataSet(dataRecieved){\n\n\n}",
"function initActivityData() {\n\tcurrentTimeValue = 0;\n //read the first file\n var initUrl = getUrlForPageFromIndex(0);\n activitiesData = HLPR_readJSONfromFile(initUrl);\n if (activitiesData != undefined) {\n currentActivitiesFileLength = activitiesData.length * TIME_STEP;\n totalPassedActivitiesData = 0;\n }\n}",
"function YDataStream_initFromDataSet(dataset,encoded)\n {\n var val; // int;\n var i; // int;\n var iRaw; // int;\n var iRef; // int;\n var fRaw; // float;\n var fRef; // float;\n var duration_float; // float;\n var iCalib = []; // intArr;\n \n // decode sequence header to extract data\n this._runNo = encoded[0] + (((encoded[1]) << (16)));\n this._utcStamp = encoded[2] + (((encoded[3]) << (16)));\n val = encoded[4];\n this._isAvg = (((val) & (0x100)) == 0);\n this._samplesPerHour = ((val) & (0xff));\n if (((val) & (0x100)) != 0) {\n this._samplesPerHour = this._samplesPerHour * 3600;\n } else {\n if (((val) & (0x200)) != 0) {\n this._samplesPerHour = this._samplesPerHour * 60;\n }\n }\n \n val = encoded[5];\n if (val > 32767) {\n val = val - 65536;\n }\n this._decimals = val;\n this._offset = val;\n this._scale = encoded[6];\n this._isScal = (this._scale != 0);\n \n val = encoded[7];\n this._isClosed = (val != 0xffff);\n if (val == 0xffff) {\n val = 0;\n }\n this._nRows = val;\n duration_float = this._nRows * 3600 / this._samplesPerHour;\n this._duration = Math.round(duration_float);\n // precompute decoding parameters\n this._decexp = 1.0;\n if (this._scale == 0) {\n i = 0;\n while (i < this._decimals) {\n this._decexp = this._decexp * 10.0;\n i = i + 1;\n }\n }\n iCalib = dataset.get_calibration();\n this._caltyp = iCalib[0];\n if (this._caltyp != 0) {\n this._calhdl = YAPI._getCalibrationHandler(this._caltyp);\n this._calpar.length = 0;\n this._calraw.length = 0;\n this._calref.length = 0;\n i = 1;\n while (i + 1 < iCalib.length) {\n iRaw = iCalib[i];\n iRef = iCalib[i + 1];\n this._calpar.push(iRaw);\n this._calpar.push(iRef);\n if (this._isScal) {\n fRaw = iRaw;\n fRaw = (fRaw - this._offset) / this._scale;\n fRef = iRef;\n fRef = (fRef - this._offset) / this._scale;\n this._calraw.push(fRaw);\n this._calref.push(fRef);\n } else {\n this._calraw.push(YAPI._decimalToDouble(iRaw));\n this._calref.push(YAPI._decimalToDouble(iRef));\n }\n i = i + 2;\n }\n }\n // preload column names for backward-compatibility\n this._functionId = dataset.get_functionId();\n if (this._isAvg) {\n this._columnNames.length = 0;\n this._columnNames.push(\"\"+this._functionId+\"_min\");\n this._columnNames.push(\"\"+this._functionId+\"_avg\");\n this._columnNames.push(\"\"+this._functionId+\"_max\");\n this._nCols = 3;\n } else {\n this._columnNames.length = 0;\n this._columnNames.push(this._functionId);\n this._nCols = 1;\n }\n // decode min/avg/max values for the sequence\n if (this._nRows > 0) {\n this._minVal = this._decodeVal(encoded[8]);\n this._maxVal = this._decodeVal(encoded[9]);\n this._avgVal = this._decodeAvg(encoded[10] + (((encoded[11]) << (16))), this._nRows);\n }\n return 0;\n }",
"getEventData(range: GenomeRange) {\n var result = [];\n var xhttp = new XMLHttpRequest();\n\n xhttp.open(\"GET\", \"http://127.0.0.1:5000/getrange/start=\" + range.start + \"&end=\" + (range.stop+1) + \"&name=may15-dataset\", false);\n xhttp.onload = function() {\n result = JSON.parse(xhttp.responseText);\n\n };\n xhttp.send();\n return result;\n // event.preventDefault();\n }",
"function getPlotData(id, startTime, endTime, intervals) {\n\tvar reqTS = \"&requestTimestamp=\" + (new Date().getTime());\n return webRequest(apiRoot + \"/streams/\" + id + \"/plot?starttime=\" + startTime + \"&endtime=\" + endTime + \"&intervals=\" + intervals.toString() + \"&selectedfields=items.timestamp;items.value\" + reqTS);\n}",
"function loadData() {\n d3.queue()\n .defer(d3.json, \"eu_health_spending.json\")\n .defer(d3.json, \"eu_life_expect.json\")\n .defer(d3.json, \"geoMap.json\")\n .awaitAll(checkResponse);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getIgnoreKeywords_allNumberWords_remainingDigits(args) Get the remaining digits to ignore. For example: one thousand, fifty five hundred, seventy eight million, etc.. | function getIgnoreKeywords_allNumberWords_remainingDigits(args) {
var onehundred = args.onehundred;
var increments = getIgnoreKeywords_allNumberWords_remainingDigits_baseIncrements();
var allremainingnumbers = [];
for(var i = 0; i < increments.length; i++) {
var increment = increments[i];
for(var j = 0; j < onehundred.length; j++) {
var number = onehundred[j];
var numberword = number + ' ' + increment;
allremainingnumbers.push(numberword);
}
}
return allremainingnumbers;
} | [
"function getIgnoreKeywords_allNumberWords() {\n\t\tvar allnumberwords = [];\n\t\t\n\t\tvar onehundred = [];\n\t\tonehundred = onehundred.concat(getIgnoreKeywords_allNumberWords_firstDigit());\n\t\tonehundred = onehundred.concat(getIgnoreKeywords_allNumberWords_upToTwenty());\n\t\tonehundred = onehundred.concat(getIgnoreKeywords_allNumberWords_upToNinetyNine());\n\t\t\n\t\tfor(i = 0; i < onehundred.length; i++) {\n\t\t\tvar number = onehundred[i];\n\t\t\tallnumberwords.push(number);\n\t\t}\n\t\t\n\t\tallnumberwords = allnumberwords.concat(getIgnoreKeywords_allNumberWords_remainingDigits({'onehundred':onehundred}));\n\t\t\n\t\treturn allnumberwords;\n\t}",
"function getIgnoreKeywords_allNumberWords_remainingDigits_baseIncrements() {\n\t\treturn [\n\t\t\t'hundred',\n\t\t\t'thousand',\n\t\t\t'million',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberWords_upToNinetyNine_secondDigit() {\n\t\treturn [\n\t\t\t'twenty',\n\t\t\t'thirty',\n\t\t\t'forty',\n\t\t\t'fifty',\n\t\t\t'sixty',\n\t\t\t'seventy',\n\t\t\t'eighty',\n\t\t\t'ninety',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberWords_firstDigit() {\n\t\treturn [\n\t\t\t'one',\n\t\t\t'two',\n\t\t\t'three',\n\t\t\t'four',\n\t\t\t'five',\n\t\t\t'six',\n\t\t\t'seven',\n\t\t\t'eight',\n\t\t\t'nine',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberWords_upToNinetyNine() {\n\t\tvar firstdigits = getIgnoreKeywords_allNumberWords_firstDigit();\n\t\tvar seconddigits = getIgnoreKeywords_allNumberWords_upToNinetyNine_secondDigit();\n\t\t\n\t\tvar firstdigitcount = firstdigits.length;\n\t\tvar seconddigitcount = seconddigits.length;\n\t\t\n\t\tvar onehundredlist = [];\n\t\t\n\t\tfor(var i = 0; i < seconddigitcount; i++) {\n\t\t\tvar seconddigit = seconddigits[i];\n\t\t\t\n\t\t\tonehundredlist.push(seconddigit);\n\t\t\t\n\t\t\tfor(var j = 0; j < firstdigitcount; j++) {\n\t\t\t\tvar firstdigit = firstdigits[j];\n\t\t\t\t\n\t\t\t\tvar word = seconddigit + ' ' + firstdigit;\n\t\t\t\t\n\t\t\t\tonehundredlist.push(word);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn onehundredlist;\n\t}",
"function getIgnoreKeywords_allNumberWordths_upToTwenty() {\n\t\treturn [\n\t\t\t'tenth',\n\t\t\t'eleventh',\n\t\t\t'twelfth',\n\t\t\t'thirteenth',\n\t\t\t'fourteenth',\n\t\t\t'fifteenth',\n\t\t\t'sixteenth',\n\t\t\t'seventeeth',\n\t\t\t'eighteenth',\n\t\t\t'ninteenth',\n\t\t\t'twentieth',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberWordthlys() {\n\t\tvar allnumberwordths = getIgnoreKeywords_allNumberWordths();\n\t\t\n\t\tvar allnumberwordthlies = [];\n\t\t\n\t\tfor(var i = 0; i < allnumberwordths.length; i++) {\n\t\t\tvar numberwordth = allnumberwordths[i];\n\t\t\t\n\t\t\tallnumberwordthlies.push(numberwordth + 'ly');\n\t\t}\n\t\t\n\t\treturn allnumberwordthlies;\n\t}",
"function getIgnoreKeywords_allNumberWordths_firstDigit() {\n\t\treturn [\n\t\t\t'first',\n\t\t\t'second',\n\t\t\t'third',\n\t\t\t'fourth',\n\t\t\t'fifth',\n\t\t\t'sixth',\n\t\t\t'seventh',\n\t\t\t'eighth',\n\t\t\t'ninth',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberWords_upToTwenty() {\n\t\treturn [\n\t\t\t'ten',\n\t\t\t'eleven',\n\t\t\t'twelve',\n\t\t\t'thirteen',\n\t\t\t'fourteen',\n\t\t\t'fifteen',\n\t\t\t'sixteen',\n\t\t\t'seventeen',\n\t\t\t'eighteen',\n\t\t\t'nineteen',\n\t\t\t'twenty',\n\t\t];\n\t}",
"function getIgnoreKeywords_allNumberPlaces() {\n\t\tvar numbers = [];\n\t\t\n\t\tfor (var i = 0; i < 100; i++) {\n\t\t\tnumbers = numbers.concat(getIgnoreKeywords_allNumberPlaces_suffixes_common({'number':i.toString()}));\n\t\t}\n\t\t\n\t\tnumbers = numbers.concat(getIgnoreKeywords_allNumberPlaces_suffixes_uncommon());\n\t\t\n\t\treturn numbers;\n\t}",
"function getIgnoreKeywords_allNumberSymbols() {\n\t\tvar numbers = [];\n\t\t\n\t\tfor (var i = 0; i < 100; i++) {\n\t\t\tnumbers.push(i);\n\t\t}\n\t\t\n\t\treturn numbers;\n\t}",
"function getIgnoreKeywords_allNumberPlaces_appendSeparator(args) {\n\t\tvar suffix = args.suffix;\n\t\tvar number = args.number;\n\t\t\n\t\tvar separators = numberSuffixSeparators();\n\t\t\n\t\tvar suffixwords = [];\n\t\t\n\t\tfor(var i = 0; i < separators.length; i++) {\n\t\t\tvar separator = separators[i];\n\t\t\t\n\t\t\tsuffixwords.push(number + separator + suffix);\n\t\t}\n\t\t\n\t\treturn suffixwords;\n\t}",
"function unusedDigits(...args) {\n let completeNums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n let allNums = []\n \n args.forEach( num => {\n \n })\n\n let answer = completeNums.filter(num => allNums.indexOf(num) < 0).join('')\n return \n}",
"function unusedDigits(...args){\n return '0123456789'.replace(new RegExp('[' + args.join('') + ']', 'g'), '');\n}",
"function getIgnoreKeywords_allLeftNumberDecorations() {\n\t\treturn [\n\t\t\t'n',\n\t\t\t'no',\n\t\t\t'nos',\n\t\t\t'no\\'s',\n\t\t\t'num',\n\t\t\t'number',\n\t\t\t'pg',\n\t\t\t'pgs',\n\t\t\t'pp',\n\t\t\t'pps',\n\t\t];\n\t}",
"function getIgnoreKeywords_allWords() {\n\t\tvar ignorekeywords = [];\n\t\t\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_symbolWords());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_numberWords());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_A_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_B_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_C_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_D_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_E_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_F_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_G_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_H_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_I_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_J_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_K_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_L_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_M_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_N_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_O_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_P_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_Q_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_R_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_S_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_T_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_U_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_V_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_W_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_X_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_Y_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_Z_Words());\n\t\tignorekeywords = ignorekeywords.concat(getIgnoreKeywords_allWords_nonEnglishWords());\n\t\t\n\t\treturn ignorekeywords;\n\t}",
"function getIgnoreKeywords_allDecoratedNumberSymbols(args) {\n\t\tvar decorargs = {\n\t\t\t'allnumbersymbols':getIgnoreKeywords_zeroPadSymbols({'symbols':getIgnoreKeywords_allNumberSymbols()}),\n\t\t};\n\t\t\n\t\tvar decoratednumbersymbols = [];\n\t\t\n\t\tdecoratednumbersymbols = decoratednumbersymbols.concat(getIgnoreKeywords_allDecoratedNumberSymbols_rightDecorations(decorargs));\n\t\tdecoratednumbersymbols = decoratednumbersymbols.concat(getIgnoreKeywords_allDecoratedNumberSymbols_leftDecorations(decorargs));\n\t\t\n\t\tvar decorargs = {\n\t\t\t'allnumbersymbols':getIgnoreKeywords_romanNumerals(),\n\t\t};\n\t\t\n\t\tdecoratednumbersymbols = decoratednumbersymbols.concat(getIgnoreKeywords_allDecoratedNumberSymbols_rightDecorations(decorargs));\n\t\tdecoratednumbersymbols = decoratednumbersymbols.concat(getIgnoreKeywords_allDecoratedNumberSymbols_leftDecorations(decorargs));\n\t\t\n\t\treturn decoratednumbersymbols;\n\t}",
"function getIgnoreKeywords_romanNumerals_numbersOnly() {\n\t\tvar digit1 = getRomanNumerals_firstDigitValues();\n\t\tvar digit2 = getRomanNumerals_secondDigitValues();\n\t\tvar digit3 = getRomanNumerals_thirdDigitValues();\n\t\tvar digit4 = getRomanNumerals_fourthDigitValues();\n\t\t\n\t\tvar numerals = digit1;\n\t\t\n\t\tnumerals = getIgnoreKeywords_romanNumerals_mergeLists({'mainlist':digit2, 'mergedlist':numerals});\n\t\tnumerals = getIgnoreKeywords_romanNumerals_mergeLists({'mainlist':digit3, 'mergedlist':numerals});\n\t\tnumerals = getIgnoreKeywords_romanNumerals_mergeLists({'mainlist':digit4, 'mergedlist':numerals});\n\t\t\n\t\treturn numerals;\n\t}",
"function getIgnoreKeywords_allNumberPlaces_suffixes_common(args) {\n\t\tvar number = args.number;\n\t\t\n\t\tvar commonsuffixes = commonNumberSuffixes();\n\t\t\n\t\tvar commonsuffixnumbers = [];\n\t\t\n\t\tfor(var i = 0; i < commonsuffixes.length; i++) {\n\t\t\tvar commonsuffix = commonsuffixes[i];\n\t\t\t\n\t\t\tcommonsuffixnumbers = commonsuffixnumbers.concat(getIgnoreKeywords_allNumberPlaces_appendSeparator({\n\t\t\t\t'number':number,\n\t\t\t\t'suffix':commonsuffix,\n\t\t\t}));\n\t\t}\n\t\t\n\t\treturn commonsuffixnumbers;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changing background image as checklist | function checklist() {
document.body.style.backgroundImage = "url('checkl.jfif')";
} | [
"function setBackGround() {\n let el = $('.currency li');\n for (var i = 0; i < el.length; i++) {\n let clas = el[i].className;\n\n $(el[i]).css('background-image', 'url(' + './flag-icon/'+ clas + '.png' +')');\n }\n}",
"function backgroundChange() {\n\t\tvar backgrounds = document.getElementById(\"backgroundChoices\");\n\t\tvar sqaures = document.getElementsByClassName(\"puzzlePiece\");\n\t\tfor (var i = 0; i < sqaures.length; i++) {\n\t\t\tvar picURL = \"url(\\'\" + backgrounds.options[backgrounds.selectedIndex].text + \".jpg\\')\";\n\t\t\tsqaures[i].style.backgroundImage = picURL;\n\t\t}\n\t}",
"backgroundImgCheck(currentObject) {\r\n var soIndex = document.getElementById(\"gameContainer\").gameMan.soIndex;\r\n if (currentObject.narration || currentObject.decision || currentObject.minigame) {\r\n var bgURL = \"url('./images/\"+currentObject.images[soIndex]+\"')\";\r\n document.getElementById(\"gameContainer\").style.backgroundImage = bgURL; // change the background image\r\n }\r\n }",
"function changebackground() {\r\n\t\tvar squares = document.getElementsByClassName(\"square\");\r\n\t\tfor (var i = 0; i < squares.length; i++) {\r\n\t\t\tsquares[i].style.backgroundImage = \"url(./\" + document.getElementById(\"menu\").value + \")\";\r\n\t\t}\r\n\t}",
"setImage(el, image) {\n el.style.backgroundImage = 'url('+image+')';\n }",
"function changeBackground() {\n var image = document.getElementById(\"select-background\").value;\n for(var i = 0; i < 15; ++i) {\n pieces[i].element.style.backgroundImage = 'url(' + image + ')';\n }\n}",
"static processBackgroundImage(element,valueNew){return TcHmi.System.Services.styleManager.processBackground(element,{image:valueNew})}",
"changeBackground(flag) {\n // Get the Icon\n var iconView = this.querySelector('.build-icon');\n\n // Build is un selected\n if (flag == 0) {\n // If the owner is the Computer set the background to Purple\n if (this._buildOwner == \"Computer\") {\n iconView.style.backgroundColor = \"rgb(109, 0, 67)\";\n }\n // The own is the Human set the background to Blue\n else {\n iconView.style.backgroundColor = \"rgb(37, 185, 154)\";\n }\n }\n // Build is selected, create background to green\n else if (flag == 1) {\n iconView.style.backgroundColor = \"rgb(0, 161, 75)\";\n }\n // Error\n else {\n console.log(\"ERROR - [Build Icon] changeBackground()\");\n }\n }",
"function images(){\n if (flag === array.length) {\n flag = 0\n // console.log(flag)\n document.getElementById('img').style.backgroundImage = \"url(\" +\"./img/\"+ array[flag] + \".png\" + \")\"\n } \n else{\n document.getElementById('img').style.backgroundImage = \"url(\" +\"./img/\"+ array[flag] + \".png\" + \")\";\n // console.log(flag)\n }\n}",
"function iconpref(value) {\n document.getElementById(\"iconprev\").style.backgroundImage = \"url(\"+markerIconTypes[value].options.iconUrl+\")\";\n}",
"function iconpref(value) {\n document.getElementById('iconprev').style.backgroundImage = \"url(\"+markerIconTypes[value].options.iconUrl+\")\";\n}",
"showBackgroundImage( )\n\t\t{\n\n\t\t}",
"function setImage(){\n\t\tbtn.backgroundImage = btn.value ? btn.imageOn : btn.imageOff;\n\t}",
"function changeHangImage() {\n $(\"#images-render\").css(\"background-image\", \"url(hang_images/\" + getHangImage() + \")\");\n}",
"function changeBGImage() {\n\t\t// 1. check all the drop zones\n\t\t// 2. if a drop zone has an image in it, then it needs to go back where it came from\n\t\t// 3. append it back into the drag zone\n\n\t\tdropZones.forEach(zone => {\n\t\t\tif (zone.childNodes.length > 0) {\n\t\t\t\tdragZone.appendChild(zone.firstElementChild);\n\t\t\t}\n\t\t});\n\n\t\t// get the custom data attribute from the clicked button\n\t\tlet currentImage = this.dataset.imageref;\n\t\t// `` is NOT a quote. it's a JavaScript template string\n\t\tdropZoneContainer.style.backgroundImage = `url(images/backGround${currentImage}.jpg)`;\n\t}",
"function changeBGImage() {\n\t\t// get the custom data attribute from the clicked button\n\t\tlet currentImage = this.dataset.imageref;\n\n\t\t// `` is NOT a quote. it's a JavaScript template string\n\t\tdropZoneContainer.style.backgroundImage = `url(images/backGround${currentImage}.jpg)`;\n\n\n\t\t// this is an intermediate way to do the same something\n\t\t// dropZoneContainer.style.backgroundImage = `url(images/backGround${this.dataset.imageref}.jpg)`;\n\t\t// debugger;\n\t}",
"function changeBgImg(x, url) {\n x.style.backgroundImage = \"url(\" + url + \")\";\n}",
"function image() {\n /* Set background image to desired URL, throw error if invalid URL */\n canvas.style.backgroundImage = \"url('\" + value + \"')\";\n /* Modify CSS Properties */\n\n if (options) {\n /* Set Repeat */\n canvas.style.backgroundRepeat = options.repeat ? 'repeat' : 'no-repeat';\n /* Set Position */\n\n canvas.style.backgroundPosition = options.position ? options.position : 'center';\n /* Set Size */\n\n canvas.style.backgroundSize = options.size ? options.size : 'contain';\n /* Set Color */\n\n canvas.style.backgroundColor = options.color ? options.color : 'none';\n }\n }",
"function pickBackground() {\n \n // console.log('Today: ', today); // for diag\n // console.log('State: ', state); // for diag\n \n var curntImgIndx = bgArr.indexOf(state.imgName),\n newImgIndex,\n newImgName;\n \n if (new Date(today) > new Date(state.date)) {\n \n // find new image index\n newImgIndex = (curntImgIndx === 7) ? 0 : curntImgIndx + 1;\n \n // find new image string name\n newImgName = bgArr[newImgIndex];\n \n // save new image name & date to local storage \n LS.setData('dev-dash-bg', {\n imgName: newImgName,\n date: today\n });\n \n // update the DOM\n render(newImgName);\n \n } else {\n render(state.imgName);\n // save current image name & date to local storage \n LS.setData('dev-dash-bg', {\n imgName: state.imgName,\n date: today\n });\n }\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pega a string formada na tela e computa o resultado | function mostrarResultado() {
if (valorTela.value.includes("%")) {
valorTela.value = eval(porcento())
} else if (valorTela.value.includes("!")) {
valorTela.value = eval(fatorial())
} else if (valorTela.value.includes("mod")) {
valorTela.value = eval(mod())
} else if (valorTela.value.includes("^")) {
valorTela.value = eval(exponencial())
} else {
valorTela.value = eval(valorTela.value)
}
} | [
"function tempSilaba( str ) {\n var temp = \"\";\n var s=\"\";\n \n //las tres primeras letras de 'str'\n var x,y,z;\n \n if( str.length <3){\n if( str.length == 2){\n x = str.charAt(0);\n y = str.charAt(1);\n if ( tipo_letra(x) != 5 && tipo_letra(y) != 5){ //X,Y son vocales\n ( hayHiato(x,y))? s = str.substring(0,1) : s = str;\n }else\n s = str;\n }else\n s = str;\n }else{\n x = str.charAt(0);\n y = str.charAt(1);\n z = str.charAt(2);\n if(tipo_letra(x) != 5 ){ //V ? ?\n if(tipo_letra(y)!= 5 ){ //V V ?\n if(tipo_letra(z)!= 5 ){ //V V V\n if(hayHiato(x,y)){\n s = str.substring(0, 1);\n }else{\n if(hayHiato(y,z)){\n s = str.substring(0,2);\n }else{\n s = str.substring(0,3);\n }\n }\n }else{ // V V C\n if(hayHiato(x,y)){\n s = str.substring(0,1);\n }else{\n s = str.substring(0,2);\n }\n }\n }else{ // V C ?\n if(tipo_letra(z)!= 5 ){ //V C V\n if( y == 'h'){ // V H C\n if(hayHiato(x,z)){\n s = str.substring(0,1);\n }else{\n s = str.substring(0,3);\n }\n }else{\n s = str.substring(0,1);\n }\n }else{ // V C C\n if(consonantesNoSeparables(y,z)){\n s = str.substring(0,1);\n }else{\n s = str.substring(0,2);\n }\n }\n }\n }else{ // C ??\n if(tipo_letra(y)!= 5 ){ //C V ?\n if(tipo_letra(z)!= 5 ){ // C V V\n temp = str.substring(0,3);\n if(temp == \"que\" || temp == \"qui\" || temp == \"gue\" || temp ==\"gui\" ){\n s = str.substring(0, 3);\n }else{\n if(hayHiato(y,z)){\n s = str.substring(0, 2);\n }else{\n s = str.substring(0, 3);\n }\n }\n }else{ // C V C\n s = str.substring(0,2);\n }\n }else{ // C C ?\n if(tipo_letra(z)!= 5 ){ // C C V\n if(consonantesNoSeparables(x,y)){\n s = str.substring(0,3);\n }else{\n s = str.substring(0,1);\n }\n }else{ // C C C\n if(consonantesNoSeparables(y,z)){\n s = str.substring(0,1);\n }else{\n s = str.substring(0,1);\n }\n }\n }\n }\n }\n return s;\n }",
"function convertirTexto(texto) {\n let nuevoTexto = \"\"\n if (texto !== null) {\n let primera = texto.slice(0, 1)\n nuevoTexto = texto.slice(1, texto.lenght) + primera + \"ay\"\n }\n return nuevoTexto\n}",
"function convertirTexto(texto) {\n let nuevoTexto = \"\"\n \n if (texto !== null) {\n // elimino caracteres en blanco al inicio y al final \n texto = texto.trim()\n // lo convierto en array de palabras usando \" \" como separador\n let listaPalabras = texto.split(\" \")\n //Guardo la longitud del array\n let c = listaPalabras.length\n // recorro el arreglo y transaformo cada palabra\n for (let i=0; i<c; i++){\n let primera = listaPalabras[i].slice(0, 1)\n let segunda= listaPalabras[i].slice(1, 2).toUpperCase()\n let medio= listaPalabras[i].slice(2, listaPalabras[i].lenght)\n let final=\"ay, \"\n // Si la última palabra de la lista, cierro con \"ay!\"\n if (i===(c-1)) {\n final=\"ay!\"\n } \n nuevoTexto = nuevoTexto + segunda + medio + primera + final \n } \n \n }\n return nuevoTexto\n}",
"function rovesciaStringa(stringa) {\n\n // A N N A\n // A N N A\n\n // ANDREA\n // A N D R E A => split('')\n // A E R D N A => reverse()\n // AERDNA => join('')\n\n // separo tutti i caratteri della stringa in un array\n var caratteri = stringa.split('');\n\n // alternativa alla funzione split()\n // var array_caratteri = [];\n // for (var i = 0; i < stringa_inziale.length; i++) {\n // var singolo_carattere = stringa_inziale.charAt(i);\n // console.log(singolo_carattere);\n // array_caratteri.push(singolo_carattere);\n // }\n // console.log(array_caratteri);\n\n // rovescio l'array di caratteri\n var caratteri_rovesciati = caratteri.reverse();\n\n // ricompongo la stringa unendo i caratteri dell'array\n var stringa_rovescia = caratteri_rovesciati.join('');\n\n // alternativa alla funzione join()\n // var stringa_finale = '';\n // for (var i = 0; i < caratteri_rovesciati.length; i++) {\n // var singolo_carattere = caratteri_rovesciati[i];\n // console.log(singolo_carattere);\n // stringa_finale += singolo_carattere;\n // }\n // console.log(stringa_finale);\n\n // restituisco il risultato dell'elaborazione\n return stringa_rovescia;\n}",
"function calcolaStringaProvv(provv) {\n var res = provv.anno + \"/\"+ provv.numero;\n res = provv.tipoAtto ? res + \"/\" + provv.tipoAtto.codice : res;\n return res;\n }",
"static stringFromTrytes(trytes) {\n // Trim trailing 9s\n let trimmed = trytes.replace(/\\9+$/, \"\");\n // And make sure it is even length (2 trytes per ascii char)\n if (trimmed.length % 2 === 1) {\n trimmed += \"9\";\n }\n const ascii = TrytesHelper.toAscii(trimmed);\n return TextHelper.decodeNonASCII(ascii);\n }",
"function parolaPalindroma3(parolaUtente) {\n\n // devo fare un ciclo che rovescia la parola, quindi un for inverso.\n var parola = '';//inizializzo la variabile per concatenare i caratteri\n\n for (var i = parolaUtente.length - 1; i >= 0; i--) {\n var singoloCarattere = parolaUtente[i]\n\n // devo salvare questa parola in una variabile, la devo concatenare dentro\n parola += singoloCarattere;\n console.log(`lettera che viene concatenata ${parola}, ${singoloCarattere} questo è il singolo carattere`);\n\n }\n // adesso ke ho concatenato e salvato la parola in una stringa, posso confrontarla\n if (parola === parolaUtente) {\n parola = ' è palindroma';\n\n }else {\n parola = ' non è palindroma';\n }\n return 'risultato ' + parola;\n}",
"function getStr(contextNode, xpathExpr) \n\t{ \n\t/*\tvar regex = /^string/;\n\t\t\n\t\tif(!regex.exec(xpathExpr)){ //la stringa non e' canonica\n\t\tvar newxp = \"string(\" + xpathExpr + \")\";\n\t\t\t}\n\t\t\n\t\telse*/ var newxp = xpathExpr;\n\t\tvar str = contextNode.ownerDocument.evaluate(newxp, contextNode, null, XPathResult.ANY_TYPE, null);\n\t\t//var str = document.evaluate(newxp, contextNode, null, XPathResult.STRING_TYPE, null);\n\t\tvar ciccio = str.iterateNext().textContent;\n\t\treturn ciccio;\n\t}",
"loadString(){\n return this.loadContent(result).then(function(buf){\n return buf.toString('UTF-8');\n });\n }",
"function dagaduString(aString) {\n aString = aString.toLowerCase();\n var last = aString.length;\n var result = \"\";\n for (var i = 0; i < last ; i++) {\n var tesdua = 'n';\n var siji = '';\n var loro = '';\n var balik = '';\n var ojonambah = 'n';\n\n siji = aString.charAt(i);\n if(i == 0) {\n if(siji == 'a') {\n balik = 'pa';\n tesdua = 'y';\n ojonambah = 'y';\n }\n if(siji == 'e') {\n balik = 'pe';\n tesdua = 'y';\n ojonambah = 'y';\n }\n if(siji == 'i') {\n balik = 'pi';\n tesdua = 'y';\n ojonambah = 'y';\n }\n if(siji == 'o') {\n balik = 'po';\n tesdua = 'y';\n ojonambah = 'y';\n }\n if(siji == 'u') {\n balik = 'pu';\n tesdua = 'y';\n ojonambah = 'y';\n }\n if(siji == 'p') {\n balik = '';\n tesdua = 'y';\n ojonambah = 'y';\n }\n }\n\n if(i < last-1) {\n loro = aString.charAt(i+1);\n if(siji == 'n' && loro == 'y') {\n balik = 'k';\n tesdua = 'y';\n }\n if(siji == 'n' && loro == 'g') {\n balik = 'l';\n tesdua = 'y';\n }\n if(siji == 'd' && loro == 'h') {\n balik = 'n';\n tesdua = 'y';\n }\n if(siji == 't' && loro == 'h') {\n balik = 'w';\n tesdua = 'y';\n }\n }\n\n if(i == last-1) {\n if(siji == 't'){\n balik = 'n';\n tesdua = 'y';\n }\n }\n\n if(tesdua == 'y') {\n result += balik;\n if(ojonambah == 'n')\n i++;\n }\n else result += dagaduChar(aString.charAt(i))\n }\n return result;\n}",
"function calcolaStringaProvvedimento(provv) {\n var res = provv.anno + \"/\"+ provv.numero;\n res = provv.tipoAtto ? res + \" - \" + provv.tipoAtto.descrizione : res;\n res = res + \" - \" + provv.oggetto;\n res = provv.strutturaAmmContabile ? res + \" - \" + provv.strutturaAmmContabile.codice : res;\n return res;\n }",
"function filtraCampo(campo) {\n var s = \"\";\n var cp = \"\";\n vr = campo.value;\n tam = vr.length;\n for (i = 0; i < tam; i++) {\n if (vr.substring(i, i + 1) != \"/\"\n && vr.substring(i, i + 1) != \"-\"\n && vr.substring(i, i + 1) != \".\"\n && vr.substring(i, i + 1) != \"(\"\n && vr.substring(i, i + 1) != \")\"\n && vr.substring(i, i + 1) != \":\"\n && vr.substring(i, i + 1) != \",\") {\n s = s + vr.substring(i, i + 1);\n }\n }\n return s;\n //return campo.value.replace(\"/\", \"\").replace(\"-\", \"\").replace(\".\", \"\").replace(\",\", \"\")\n}",
"function getNombre() {\n return `${nombre} ${real}`; // cuando juntas dos variables en un template literal ${nombre} ${real} es quivalente a concatenacion clásica nombre+real\n}",
"function getStringLan(lan, idString) {\r\n var strings = traduccions;\r\n\tstrings = JSON.parse(strings);\r\n var lanId = getLanId(lan);\r\n\tlan = lan.substring(0,3); //solució provisional; \r\n\tlan = lan.replace('-', '');\r\n\ttry {\r\n\t\tvar y = 'strings.' + idString + '[' + lanId + '].' + lan;\r\n\t\tvar x = eval(y);\r\n\t}\r\n\tcatch (e){\r\n\t\tvar x = \"no traduccio\";\r\n\t}\r\n return x;\r\n}",
"function country1(mark) {\n var masini = {//facem un obiect\n \"toyota\": \"Japonia\",\n \"hiunday\": \"China\",\n \"hummer h3\": \"America\",\n \"tata\": \"India\",\n \"pagani huayra\": \"Italia\",\n \"koenigsegg regera\": \"Suedia\",\n \"pontiac\": \"America\",\n \"aston martin\": \"Marea Britamie\",\n \"ssc tuatara\": \"America\",\n \"buick\": \"America\",\n }\n //facem o variabila pentru a putea transfosrma propietatile ce le are country1 in lowerCase\n var markLowerCase = mark.toLowerCase();\n //facem o returnare pentru concatenarea dintre stringuri si apelarea obiectelor din obirctul \"masini\"\n return \"Automobilul cu marca \" + markLowerCase + \" se produce in \" + masini[markLowerCase] + \".\";\n}",
"function prvi_str()\n{\n return \"bottles of beer on the wall\";\n}",
"function decodificar(ascci) {\r\n var texto = \"\";\r\n for (var i = 0; i < ascci.length; i++){\r\n texto = texto +String.fromCharCode(ascci[i]);\r\n }\r\n return texto;\r\n }",
"function filtraCampo(campo) {\r\r\n var s = \"\";\r\r\n var cp = \"\";\r\r\n vr = campo.value;\r\r\n tam = vr.length;\r\r\n for (i = 0; i < tam; i++) {\r\r\n if (vr.substring(i, i + 1) != \"/\"\r\r\n && vr.substring(i, i + 1) != \"-\"\r\r\n && vr.substring(i, i + 1) != \".\"\r\r\n && vr.substring(i, i + 1) != \":\"\r\r\n && vr.substring(i, i + 1) != \" \"\r\r\n && vr.substring(i, i + 1) != \",\") {\r\r\n s = s + vr.substring(i, i + 1);\r\r\n }\r\r\n }\r\r\n return s;\r\r\n //return campo.value.replace(\"/\", \"\").replace(\"-\", \"\").replace(\".\", \"\").replace(\",\", \"\") \r\r\n}",
"function converte(n){\r\n if( n==undefined ){\r\n retorno=\"\";\r\n } else {\r\n switch( n[0] ){\r\n case \"#\":\r\n n=n.substring(1);\r\n if( document.getElementById(n) ){\r\n retorno=document.getElementById(n).value;\r\n } else {\r\n throw \"NAO LOCALIZADO ELEMENTO \"+n+\" PARA ATRIBUIR VALOR\";\r\n }; \r\n break;\r\n case \"^\": \r\n n=n.substring(1); \r\n retorno=document.getElementById(n).options[document.getElementById(n).selectedIndex].text;\r\n break;\r\n default : retorno=n; break; \r\n };\r\n ////////////////////////////////////////////////////\r\n // Padrão da função tirar aspas e remover acentos //\r\n ////////////////////////////////////////////////////\r\n if( typeof(retorno) != \"number\" ){\r\n retorno=removeAcentos(retorno.replace(/'/g, \"\")); //remoceAcentos+tira aspas \r\n retorno=retorno.replace(/^\\s+/,\"\"); //ltrim\r\n retorno=retorno.replace(/\\s+$/,\"\"); //rtrim\r\n };\r\n };\r\n return retorno;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FINAL SUMMARY TOTAL LEFT | function generateSummaryLeftTableRow(doc, y, classhead, subtotal, disc, amount, sgst, cgst, gst, total, isIGST, igst) {
doc.fillColor('#000000');
doc.fontSize(9).text(classhead, 24, y, { width: 40, align: 'left' });
if (subtotal === 'SUB TOTAL') {
doc.text(subtotal, 64, y, { width: 50, align: 'right' });
} else {
doc.text((+subtotal + +disc).toFixed(2), 64, y, {
width: 50,
align: 'right',
});
}
if (disc === 'DISC') {
doc.text(disc, 113, y, { width: 49, align: 'right' });
} else {
doc.text((+disc).toFixed(2), 113, y, { width: 49, align: 'right' });
}
if (amount === 'AMOUNT') {
doc.text(amount, 169, y, { width: 49, align: 'right' });
} else {
doc.text((+amount).toFixed(2), 169, y, { width: 49, align: 'right' });
}
if (!isIGST) {
if (sgst === 'SGST') {
doc.text(sgst, 225, y, { width: 49, align: 'right' });
} else {
doc.text((+sgst / 2).toFixed(2), 225, y, { width: 49, align: 'right' });
}
if (cgst === 'CGST') {
doc.text(cgst, 281, y, { width: 49, align: 'right' });
} else {
doc.text((+cgst / 2).toFixed(2), 281, y, { width: 49, align: 'right' });
}
if (gst === 'GST') {
doc.text(gst, 337, y, { width: 49, align: 'right' });
} else {
doc.text((+gst).toFixed(2), 337, y, { width: 49, align: 'right' });
}
if (total === 'TOTAL') {
doc.text(total, 393, y, { width: 49, align: 'right' });
} else {
doc.text((+total).toFixed(2), 393, y, { width: 49, align: 'right' });
}
} else if (isIGST) {
if (igst === 'IGST') {
doc.text(igst, 225, y, { width: 39, align: 'right' });
} else {
doc.text((+igst).toFixed(2), 225, y, { width: 39, align: 'right' });
}
if (gst === 'GST') {
doc.text(gst, 281, y, { width: 49, align: 'right' });
} else {
doc.text((+gst).toFixed(2), 281, y, { width: 49, align: 'right' });
}
if (total === 'TOTAL') {
doc.text(total, 337, y, { width: 49, align: 'right' });
} else {
doc.text((+total).toFixed(2), 337, y, { width: 49, align: 'right' });
}
}
} | [
"calculateSummary(){\n let subtotal = 0\n this.cartItems.forEach(cartItem => {\n subtotal = subtotal + cartItem.price\n })\n this.setSummary(getFormatedPrice(subtotal),getFormatedPrice(shipping),getFormatedPrice(subtotal + shipping))\n }",
"summary(){\n return worker.total + farmer.total + lumberjack.total + miner.total;\n }",
"findTotals() {\n \t// Records how many boxes have been crossed out in each row\n \tthis.colorRowTotals.forEach((val, index, arr) => {\n \t\tfor (let col of this.numBoxesCrossedOut[index]) {\n \t\t\tif(col === true) {\n \t\t\t\t++arr[index];\n \t\t\t}\n \t\t}\n \t});\n \t\n \t// Uses the records of how many boxes have been crossed out in each row\n \t// to find the point total for each row\n \tthis.colorRowTotals.forEach((val, index, arr1) => {\n \t\tlet arr2 = new Array(val + 2);\n \t\tarr2[0] = 0;\n \t\tfor (let i = 1; i <= val; ++i) {\n \t\t\tarr2[i] = i + arr2[i - 1];\n \t\t}\n \t\tarr1[index] = arr2[val];\n \t});\n \t\n \tthis.penaltyTotals = this.amtOfPenalties * 5;\n \tthis.finalTotal = this.colorRowTotals.reduce((a, b) => a + b, 0) - this.penaltyTotals;\n }",
"function displayTotal() {\n\tscreen1.bugCount.html(prettyNumber(Math.round(state.larvae)));\n\tscreen1.larvaePerSec.html(prettyNumber(state.lps));\n}",
"function calculateTotals(book) {\n\t\tvar spine = book.spine,\n\t\t\t\twordCount = 0,\n\t\t\t\timageCount = 0,\n\t\t\t\ti = 0,\n\t\t\t\titem;\n\t\twhile ((item = spine[i++])) {\n\t\t\t// Check if the spine item is available (explicit type check as the active property might be undefined):\n\t\t\tif (item.active !== false) {\n\t\t\t\twordCount += item.wordCount;\n\t\t\t\timageCount += item.imageCount;\n\t\t\t}\n\t\t}\n\t\tbook.totalWordCount = wordCount;\n\t\tbook.totalImageCount = imageCount;\n\t}",
"function renderTotals() {\n cards[round - 1].calculateTotals()\n bonusEl.innerText = cards[round - 1].bonus;\n topEl.innerText = cards[round - 1].top;\n bottomEl.innerText = cards[round - 1].bottom;\n totalEl.innerText = cards[round - 1].total;\n}",
"function updateSummary() {\n var cart = app.getModel('Cart').get();\n Transaction.wrap(function () {\n cart.calculate();\n });\n app.getView({\n checkoutstep: 4,\n Basket: cart.object\n }).render('checkout/minisummary');\n}",
"function totalRetirement() {\r\n\t\tvar fwTotal = futureWorthMonth + futureWorthLump;\r\n\t\t$('#fwTotal').text('$ ' + fwTotal.toFixed(0));\r\n\t}",
"function calcTotalDayAgain() {\n var eventCount = $this.find('.this-month .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }",
"addTotalNoMore() { this.totalNoMore.value++; this.updateStatNav(this.totalNoMore); }",
"function updateSummary() {\r\n var html = \"\";\r\n var total = 0;\r\n if (hasCheckout == \"false\") {\r\n // placement payment\r\n for (var i = 0; i < prizeNumber; i++) {\r\n if (bankData && bankData[arrPrize[i]]) {\r\n html += '<tr><td class=\"label\">' + position[i] + ' Place Prize:</td><td>1</td><td class=\"sum\">' + fmoney(prizes[i + 1]) + '</td><td class=\"sum\">' + fmoney(prizes[i + 1]) + '</td></tr>';\r\n total += parseFloat(prizes[i + 1]);\r\n }\r\n }\r\n }\r\n\r\n // additional purchase\r\n var extraNumber = 0;\r\n for (var i = 0; i < listExtra.length; i++) {\r\n if ($(\"#extra_\" + listExtra[i]).is(\":checked\")) {\r\n extraNumber++;\r\n }\r\n }\r\n if (extraNumber > 0) {\r\n var totalExtra = extraNumber * additionalPrize;\r\n html += '<tr><td class=\"label\">Additional Purchases:</td><td>' + extraNumber + '</td><td class=\"sum\">' + fmoney(additionalPrize) + '</td><td class=\"sum\">' + fmoney(totalExtra) + '</td></tr>';\r\n total += parseFloat(totalExtra);\r\n }\r\n // checkpoint payment\r\n if (hasCheckout == \"false\") {\r\n if (checkpointAwardNumber > 0) {\r\n var totalCheckpoint = checkpointAwardNumber * checkpointPrize;\r\n html += '<tr><td class=\"label\">Checkpoint Prizes:</td><td>' + checkpointAwardNumber + '</td><td class=\"sum\">' + fmoney(checkpointPrize) + '</td><td class=\"sum\">' + fmoney(totalCheckpoint) + '</td></tr>';\r\n total += parseFloat(totalCheckpoint);\r\n }\r\n }\r\n html += '<tr class=\"total\"><td class=\"label\">Total</td><td colspan=\"3\" class=\"sum\">' + fmoney(total) + '</td></tr>';\r\n $(\"#summary\").html(html);\r\n}",
"function set_total_summary(total_count, fltr_count, offset) {\r\n\t\t_fltr_r_cnt = parseInt(fltr_count); //visible \r\n\t\t_total_r_cnt = parseInt(total_count); //total\r\n\t\t_offset = parseInt(offset);\r\n\t}",
"function CalculateAllTotals() {\n //use temp variables to prevent multiple dom updates\n var wt = 0;\n var dt = 0;\n var gt = 0;\n for (var i = 0; i < vm.territorySalesNumbers.length; i++) {\n wt += vm.territoryWritten[i];\n dt += vm.territoryDelivered[i];\n gt += vm.goals[i];\n }\n\n vm.writtenTotal = Round(wt, 2);\n vm.deliveredTotal = Round(dt, 2);\n vm.goalsTotal = Round(gt, 2);\n vm.goalsWrittenDifference = Round(vm.writtenTotal - vm.goalsTotal, 2);\n\n if (vm.goalsWrittenDifference > 0)\n vm.goalsWrittenDifference = '+' + vm.goalsWrittenDifference;\n\n }",
"function calcTotalDayAgain() {\r\n var eventCount = $this.find('.this-month .event-single').length;\n // $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\r\n }",
"function updateTotals() {\n\t\tvm.courseTotal = _.round(_.sumBy(vm.coursesAndCourseRelatedExpenses, 'tuitionAmount'), 2);\n\t\tvm.expenseTotal = _.round(_.sumBy(vm.coursesAndCourseRelatedExpenses, 'feesAmount'), 2) + _.round(_.sumBy(vm.otherExpenses, 'feesAmount'), 2);\n\t\tvar subResult = vm.courseTotal + vm.expenseTotal;\n\t\tvm.courseAndExpenseTotal = _.round(subResult, 2);\n\t}",
"function updateSummary() {\n summary.innerHTML = `${summaryCountChecked} / ${summaryCountTotal} Completed`;\n}",
"function getTotal() {\n // Refresh is the value of last calculation\n const refresh = calcBrain(CALC.inputs.join(''));\n CALC.operationsUpdate.value = CALC.inputs.join('');\n CALC.lastResult = refresh;\n CALC.screenUpdate.value = refresh;\n }",
"function calcTotalDayAgain() {\n var eventCount = $this.find(\".this-month .event-single\").length;\n if (eventCount == 0) {\n $this.find(\".total-bar\").hide(0);\n }\n $this.find(\".total-bar\").text(eventCount);\n $this.find(\".events h3 span\").text(eventCount);\n }",
"function displayTotals() {\n $('<div class=\"fluid-results norm-font purple\">All Done!</div>').appendTo('.js-main-section');\n $('<div class=\"fluid-results norm-font purple\">Correct Answers: ' + answersGuessedCorrect + '</div>').appendTo('.js-main-section');\n $('<div class=\"fluid-results norm-font purple\">Incorrect Answers: ' + answersGuessedIncorrect + '</div>').appendTo('.js-main-section');\n $('<div class=\"fluid-results norm-font purple\">Unanswered: ' + answersUnanswered + '</div>').appendTo('.js-main-section');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
6. Init Video Overlay | function initVideoOverlay()
{
if($('.video_overlay').length)
{
var overlay = $('.video_overlay');
$('.video_container_outer').on('click', function()
{
overlay.css('opacity', "0");
})
}
} | [
"function initVideo() {\n if (platform.isFlash) {\n initFlashPlayer();\n } else {\n initVideoPlayer();\n }\n }",
"function overVideoControl() {\n showVideoControl()\n }",
"function videoBGInit() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tif ($('.nectar-video-wrap').length == 0 && $('.nectar-youtube-bg').length == 0) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tresizeVideoToCover();\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Resize\r\n\t\t\t\t\t\t$window.on('resize',resizeVideoToCover);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$('.video-color-overlay').each(function () {\r\n\t\t\t\t\t\t\t$(this).css('background-color', $(this).attr('data-color'));\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$('.nectar-video-wrap').each(function () {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif ($(this).find('video').length == 0) {\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tvar $headerVideo = ($(this).parents('#page-header-bg').length > 0) ? true : false;\r\n\t\t\t\t\t\t\tvar $that = $(this);\r\n\t\t\t\t\t\t\tvar videoReady = setInterval(function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif ($that.find('video').get(0).readyState > 3) {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tif (!nectarDOMInfo.usingMobileBrowser) {\r\n\t\t\t\t\t\t\t\t\t\t$that.transition({\r\n\t\t\t\t\t\t\t\t\t\t\t'opacity': '1'\r\n\t\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t\t\t$that.find('video').transition({\r\n\t\t\t\t\t\t\t\t\t\t\t'opacity': '1'\r\n\t\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t\t\t$that.parent().find('.video-color-overlay').transition({\r\n\t\t\t\t\t\t\t\t\t\t\t'opacity': '0.7'\r\n\t\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t\t\tif ($headerVideo == true) {\r\n\t\t\t\t\t\t\t\t\t\t\tpageHeaderTextEffect();\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t// Remove page loading screen\r\n\t\t\t\t\t\t\t\t\t$loadingScreenEl.addClass('loaded');\r\n\t\t\t\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\t\t\t\t$loadingScreenEl.addClass('hidden');\r\n\t\t\t\t\t\t\t\t\t}, 1000);\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tclearInterval(videoReady);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t}, 60);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (nectarDOMInfo.usingMobileBrowser) {\r\n\t\t\t\t\t\t\t\tif ($that.parents('.full-width-section').length > 0 && $that.parents('#nectar_fullscreen_rows').length == 0) {\r\n\t\t\t\t\t\t\t\t\t$that.css('left', '50%');\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t$that.css('left', '0px');\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif ($headerVideo == true) {\r\n\t\t\t\t\t\t\t\t\tpageHeaderTextEffect();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t$that.find('video')[0].onplay = function () {\r\n\t\t\t\t\t\t\t\t\t$that.transition({\r\n\t\t\t\t\t\t\t\t\t\t'opacity': '1'\r\n\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t\t$that.find('video').transition({\r\n\t\t\t\t\t\t\t\t\t\t'opacity': '1'\r\n\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t\t$that.parent().find('.video-color-overlay').transition({\r\n\t\t\t\t\t\t\t\t\t\t'opacity': '0.7'\r\n\t\t\t\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}, 300);\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (nectarDOMInfo.usingMobileBrowser) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$('.nectar-video-wrap').each(function () {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (!$(this).find('video').is('[muted]')) {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t// Autoplay not supported unless muted\r\n\t\t\t\t\t\t\t\t$(this).parent().find('.mobile-video-image').show();\r\n\t\t\t\t\t\t\t\t$(this).remove();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t$('.wpb_row:has(\".nectar-video-wrap\"):not(.fp-section)').each(function (i) {\r\n\t\t\t\t\t\t$(this).css('z-index', 100 + i);\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(\".vc_row\").each(function () {\r\n\t\t\t\t\t\tvar youtubeUrl, youtubeId, $row = jQuery(this);\r\n\t\t\t\t\t\t$row.find('.nectar-youtube-bg').length > 0 ? (youtubeUrl = $row.find('.nectar-youtube-bg span').text(), youtubeId = nectarExtractYoutubeId(youtubeUrl), youtubeId && ($row.find(\".vc_video-bg\").remove(), nectarInsertYoutubeVideoAsBackground($row.find('.nectar-youtube-bg'), youtubeId))) : $row.find(\".nectar-youtube-bg\").remove();\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Remove yt url\r\n\t\t\t\t\t\t$row.find('.nectar-youtube-bg span').remove();\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (!nectarDOMInfo.usingMobileBrowser) {\r\n\t\t\t\t\t\t\t$row.find('.nectar-video-wrap, .nectar-youtube-bg').css({\r\n\t\t\t\t\t\t\t\t'opacity': '1',\r\n\t\t\t\t\t\t\t\t'width': '100%',\r\n\t\t\t\t\t\t\t\t'height': '100%'\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t$row.find('.video-color-overlay').transition({\r\n\t\t\t\t\t\t\t'opacity': '0.7'\r\n\t\t\t\t\t\t}, 400);\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tfunction nectarInsertYoutubeVideoAsBackground($element, youtubeId, counter) {\r\n\t\t\t\t\t\tif (\"undefined\" == typeof YT || void 0 === YT.Player) return 100 < (counter = void 0 === counter ? 0 : counter) ? void console.warn(\"Too many attempts to load YouTube api\") : void setTimeout(function () {\r\n\t\t\t\t\t\t\tnectarInsertYoutubeVideoAsBackground($element, youtubeId, counter++)\r\n\t\t\t\t\t\t}, 100);\r\n\t\t\t\t\t\tvar $container = $element.prepend('<div class=\"vc_video-bg\"><div class=\"inner\"></div></div>').find(\".inner\");\r\n\t\t\t\t\t\tnew YT.Player($container[0], {\r\n\t\t\t\t\t\t\twidth: \"100%\",\r\n\t\t\t\t\t\t\theight: \"100%\",\r\n\t\t\t\t\t\t\tvideoId: youtubeId,\r\n\t\t\t\t\t\t\tplayerVars: {\r\n\t\t\t\t\t\t\t\tplaylist: youtubeId,\r\n\t\t\t\t\t\t\t\tiv_load_policy: 3,\r\n\t\t\t\t\t\t\t\tenablejsapi: 1,\r\n\t\t\t\t\t\t\t\tdisablekb: 1,\r\n\t\t\t\t\t\t\t\tautoplay: 1,\r\n\t\t\t\t\t\t\t\tcontrols: 0,\r\n\t\t\t\t\t\t\t\tshowinfo: 0,\r\n\t\t\t\t\t\t\t\trel: 0,\r\n\t\t\t\t\t\t\t\tloop: 1\r\n\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\tevents: {\r\n\t\t\t\t\t\t\t\tonReady: function (event) {\r\n\t\t\t\t\t\t\t\t\tevent.target.mute().setLoop(!0);\r\n\t\t\t\t\t\t\t\t\tnectarResizeVideoBackground($element);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}), nectarResizeVideoBackground($element), jQuery(window).on(\"resize\", function () {\r\n\t\t\t\t\t\t\tnectarResizeVideoBackground($element);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\tnectarResizeVideoBackground($element);\r\n\t\t\t\t\t\t}, 100);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tfunction nectarResizeVideoBackground($element) {\r\n\t\t\t\t\t\tvar iframeW, iframeH, marginLeft, marginTop, containerW = $element.innerWidth(),\r\n\t\t\t\t\t\tcontainerH = $element.innerHeight(),\r\n\t\t\t\t\t\tratio1 = 16,\r\n\t\t\t\t\t\tratio2 = 9;\r\n\t\t\t\t\t\tratio1 / ratio2 > containerW / containerH ? (iframeW = containerH * (ratio1 / ratio2),\r\n\t\t\t\t\t\tiframeH = containerH, marginLeft = -Math.round((iframeW - containerW) / 2) + \"px\", marginTop = -Math.round((iframeH - containerH) / 2) + \"px\", iframeW += \"px\", iframeH += \"px\") : (iframeW = containerW, iframeH = containerW * (ratio2 / ratio1), marginTop = -Math.round((iframeH - containerH) / 2) + \"px\",\r\n\t\t\t\t\t\tmarginLeft = -Math.round((iframeW - containerW) / 2) + \"px\", iframeW += \"px\", iframeH += \"px\"),\r\n\t\t\t\t\t\t$element.find(\".vc_video-bg iframe\").css({\r\n\t\t\t\t\t\t\tmaxWidth: \"1000%\",\r\n\t\t\t\t\t\t\tmarginLeft: marginLeft,\r\n\t\t\t\t\t\t\tmarginTop: marginTop,\r\n\t\t\t\t\t\t\twidth: iframeW,\r\n\t\t\t\t\t\t\theight: iframeH\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tfunction nectarExtractYoutubeId(url) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (\"undefined\" == typeof url) {\r\n\t\t\t\t\t\t\treturn !1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar id = url.match(/(?:https?:\\/{2})?(?:w{3}\\.)?youtu(?:be)?\\.(?:com|be)(?:\\/watch\\?v=|\\/)([^\\s&]+)/);\r\n\t\t\t\t\t\treturn null !== id ? id[1] : !1\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t}",
"function createVideoOverlay() {\n const videoOverlay = document.createElement(\"div\");\n videoOverlay.setAttribute(\"id\", \"video-overlay\");\n videoOverlay.classList.add(\"video-overlay-poster\");\n getVideoWrapper().appendChild(videoOverlay);\n}",
"function launchVideo() {\r\n var mapAnim = $(\"#particles-js\");\r\n mapAnim.css(\"opacity\", 0);\r\n $(\".panel\").replaceWith(\"<div id='containerVideo'><div id='uiBox'><p id='uiTitle'>DATA DOWNLOAD : MONITORING</p> <div id='uiSubtitle'><p>ACCESSING CAMERAS : TIME SQUARE</p></div><div id='uiLoading'><div id='uiBar'></div><p id='uiCounter'>LOADING</p></div></div></div>\");\r\n videoAnimation();\r\n }",
"updateVideoDisplay() {\n this.setVideoTransparency({\n TRANSPARENCY: this.globalVideoTransparency\n });\n this.videoToggle({\n VIDEO_STATE: this.globalVideoState\n });\n }",
"updateVideoDisplay () {\n this.setVideoTransparency({\n TRANSPARENCY: this.globalVideoTransparency\n });\n this.videoToggle({\n VIDEO_STATE: this.globalVideoState\n });\n }",
"prepareVideo() {\n this.width = (document.documentElement.clientHeight / 5) * 4;\n this.height = document.documentElement.clientHeight;\n this.ui.videoContainer.style.width = this.width + \"px\";\n this.ui.videoContainer.style.height = this.height + \"px\";\n this.ui.videoOverlay.style.width = this.width + \"px\";\n this.ui.videoOverlay.style.height = this.height + \"px\";\n this.ui.body.style.gridTemplateColumns = \"1fr \" + this.width + \"px\" + \" 1fr\";\n this.ui.video.style.height = \"100vh\";\n this.renderReflection();\n }",
"function videoChanged() {\n myPlayer.addClass(\"hide-overlay\");\n }",
"function initBackgroundVideo() {\n\t\tif ($('.js-html-bg-video').length) {\n\t\t\t$('.js-html-bg-video').bgVideo({\n\t\t\t\tshowPausePlay: false,\n\t\t\t\tpauseAfter: 0\n\t\t\t});\n\t\t}\n\t}",
"function showInitializationVideo() {\r\n $('#videoPlayerOverlay').hide();\r\n\r\n initializationVideoVisible = true;\r\n }",
"displayVideo() {\n blendMode(ADD);\n this.transparency = map(this.corridorDistance, 1100, 0, 0, 127);\n push();\n noStroke();\n translate(user.position.x, user.position.y, user.position.z);\n rotateY(PI - user.pan);\n tint(255, this.transparency);\n texture(corridorScene);\n box(width/12, height/12, width/12);\n pop();\n }",
"function recallOverlay() {\n $(window).scrollTop(0);\n vcontrol.pauseVideo(); \n moocwidget.UI.ieye_intro(); \n \n //TODO: test\n // force fullscreen off to show intro\n if (fullscreen) {\n $('#'+vcontrol.getCurrentPlayerID()).find('button').closest('.control.add-fullscreen').click();\n }\n }",
"function setupOverlay() {\n objHeight = height + height / 2; // outside of the screen\n objInPosition = false;\n objMoveAway = false;\n}",
"function initializeVideoContainer() {\n let container = document.getElementById(\"video-container\");\n //todo - delete background image in css and implement actual content\n}",
"initializeVideo() {\n let $video = this.$('.video-wrapper');\n\n if ($video.length) {\n this.videoView = new VideoView({ el: $video });\n\n // When the post comes into view, play it, and when it goes out of\n // the view, stop it.\n this.on('onviewportin', this.videoView.play);\n this.on('onviewportout', this.videoView.pause);\n\n this.$viewportTarget = $video;\n }\n }",
"function onOverlayClicked() {\n FyberMraidVideoController.play();\n }",
"function video() {\n\t\t$('#wrapper').fitVids();\n\t}",
"function showVideoControl() {\n TweenLite.to(videocontrol, 1, {opacity: 1});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating the enum objects Call this in the set parameters function | function setEnumColor() {
BLUE = new Color();
GREEN = new Color();
RED = new Color();
GREEN = new Color();
NO_COLOR = new Color();
BLUE.setBLUE();
RED.setRED();
GREEN.setGREEN();
NO_COLOR.setNO_COLOR();
console.log("Different colours created used for creating Enum");
} | [
"_parseEnum () {\n if (this._currentOriginalParam.enum) {\n if (this._currentOriginalParam.enum.length === 1) {\n this._currentParam.isSingleton = true\n this._currentParam.singleton = this._currentOriginalParam.enum[0]\n } else {\n let _enum = {\n name : _.upperFirst(_.camelCase(this._currentOriginalParam.name)) + ' Enum',\n camelCaseName: _.camelCase(this._currentOriginalParam.name),\n values : this._currentOriginalParam.enum,\n }\n\n if (this.addEnumDescription) {\n _enum.description = this._currentOriginalParam.description\n }\n\n this.enums.push(_enum)\n }\n }\n }",
"function enumeration(namesToValues) {\n // This is the dummy constructor function that will be the return value.\n var enumeration = function () {\n throw \"Can't Instantiate Enumerations\";\n };\n\n // Enumerated values inherit from this object.\n var proto = (enumeration.prototype = {\n constructor: enumeration,\n toString: function () {\n return this.name;\n },\n\n valueOf: function () {\n return this.value;\n },\n\n toJSON: function () {\n return this.name; // for serialization\n },\n });\n enumeration.values = []; // An array of the enumerated values objects\n\n // Now create the instance of this new type\n for (name in namesToValues) {\n // For each value\n var e = inherit(proto); // Create an object to represent it\n e.name = name; // Create an object to represent it\n e.value = namesToValues[name]; // And a value\n enumeration[name] = e; // Make it a property of constructor\n enumeration.values.push(e); // And store in the values array\n }\n // console.log(enumeration.values);\n \n // A class method for iterating the instance of the class\n enumeration.foreach = function (f, c) {\n for (var i = 0; i < this.values.length; i++) {\n f.call(c, this.values[i]);\n }\n };\n // Return the constructor that identifies the new type\n return enumeration;\n}",
"SetProceduralEnum() {}",
"function enumeration(namesToValues) {\r\n // This is the dummy constructor function that will be the return value.\r\n var enumeration = function() { throw \"Can't Instantiate Enumerations\"; };\r\n // Enumerated values inherit from this object.\r\n var proto = enumeration.prototype = {\r\n constructor: enumeration, // Identify type\r\n toString: function() { return this.name; }, // Return name\r\n valueOf: function() { return this.value; }, // Return value\r\n toJSON: function() { return this.name; } // For serialization\r\n };\r\n enumeration.values = []; // An array of the enumerated value objects\r\n // Now create the instances of this new type.\r\n for(name in namesToValues) { // For each value \r\n var e = inherit(proto); // Create an object to represent it\r\n e.name = name; // Give it a name\r\n e.value = namesToValues[name]; // And a value\r\n enumeration[name] = e; // Make it a property of constructor\r\n enumeration.values.push(e); // And store in the values array\r\n }\r\n // A class method for iterating the instances of the class\r\n enumeration.foreach = function(f,c) {\r\n for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);\r\n };\r\n // Return the constructor that identifies the new type\r\n return enumeration;\r\n}",
"_constructor() {\n // ar[0] - a list of symbol\n // Returns a enum_set.\n return new Scheme.FunctionHolder(\"\", 0, 0, (ar) => {\n Scheme.assert_list(ar[0], \"(enum-set constructor)\");\n var symbols = ar[0].to_array();\n symbols.forEach((arg) => {\n Scheme.assert_symbol(arg, \"(enum-set constructor)\");\n });\n return new EnumSet(this, symbols);\n });\n }",
"constructor () {\n this._createConstants();\n }",
"CreateParameter(string, DataTypeEnum, ParameterDirectionEnum, int, Variant) {\n\n }",
"function _init(enums) {\n var _mapper = function (en) {\n return _createEnum(en);\n };\n\n return enums.map(_mapper);\n}",
"constructor_(){\n // ar[0] - a list of symbol\n // Returns a enum_set.\n return (ar) => {\n assert_list(ar[0], \"(enum-set constructor)\");\n var symbols = ar[0].to_array();\n symbols.forEach(function(arg){\n assert_symbol(arg, \"(enum-set constructor)\");\n });\n\n return new Enumeration.EnumSet(this, symbols);\n };\n }",
"function makeEnum(args) {\n var ret = {};\n for (var i = 0; i < args.length; ++i) {\n ret[args[i]] = i+1;\n }\n return ret;\n}",
"function MonkeyEnums() {}",
"function ObjTypeEnum(){\n this.player = 0;\n this.wall = 1;\n this.goo = 2;\n this.ladder = 3;\n }",
"constructor(enum_type, symbols){\n this.enum_type = enum_type;\n this.symbols = enum_type.members.filter((sym) => symbols.includes(sym));\n }",
"setFields(values: GraphQLEnumValueConfigMap): EnumTypeComposer {\n if (graphqlVersion >= 14) {\n this.gqType._values = defineEnumValues(this.gqType, values);\n this.gqType._valueLookup = new Map(\n this.gqType._values.map(enumValue => [enumValue.value, enumValue])\n );\n this.gqType._nameLookup = keyMap(this.gqType._values, value => value.name);\n } else {\n // cleanup isDepricated\n Object.keys(values).forEach(key => {\n // $FlowFixMe\n delete values[key].isDeprecated; // eslint-disable-line\n });\n\n // $FlowFixMe\n this.gqType._enumConfig.values = values;\n\n // clear builded fields in type\n delete this.gqType._values;\n delete this.gqType._valueLookup;\n delete this.gqType._nameLookup;\n\n this._fixEnumBelowV13();\n }\n\n return this;\n }",
"toString() {\n return private_1.shapeAddition({\n prefix: 'enum',\n name: this.name,\n fields: Object.keys(this.definition),\n modes: this.modes,\n });\n }",
"function build (t, prop) {\n var o = { types : t, enum : []};\n Object.keys (t).forEach(function(k){\n if (prop) {\n o.enum.push (t[k][prop]);\n } else {\n o.enum.push (t[k]);\n }\n\n });\n return o;\n}",
"static invalidArgumentEnum (objectName, enumClass, baseError) {\n return new ElevatorError(\"Argument '\" + objectName + \"' should be a value of enum '\" + enumClass + \"'\", baseError)\n }",
"get ENUM() {\n var result = function() {\n return {\n type: 'ENUM',\n values: Array.prototype.slice.call(arguments).reduce(function(result, element) {\n return result.concat(Array.isArray(element) ? element : [element]);\n }, []),\n toString: result.toString\n };\n };\n\n result.toString = result.valueOf = function() { return 'ENUM'; };\n\n return result;\n }",
"constructor(name : string) {\n super('enumlistfeature', name);\n this.listvalues = [];\n this.normalize();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set leds accoring to wind speed | function setWind(speed=0){
if(speed != 0){
windSpeed = speed;
}
clearDisplay()
bit= Math.abs((windSpeed/20));
if(windSpeed >=140){
setBits(bit, true)
}
else if(windSpeed >=120){
setBits(bit, true)
}else if(windSpeed >=100){
setBits(bit, true)
}else if(windSpeed >=80){
setBits(bit, true)
}else if(windSpeed >=60){
setBits(bit, false)
}else if(windSpeed >=40){
setBits(bit, false)
}else if(windSpeed >=20){
setBits(bit, false)
}else if(windSpeed >=0){
setBits(bit, false)
}
} | [
"function setSpeed() {}",
"function updateLED() {\n\tledR.pwmWrite(actualColour[0]);\n\tledG.pwmWrite(actualColour[1]);\n\tledB.pwmWrite(actualColour[2]);\n}",
"function updateLed() {\n GPIO.write(led, state.led ? LED_OFF : LED_ON);\n GPIO.write(relay, state.p5 ? LED_ON : LED_OFF);\n GPIO.write(reset, state.p4 ? LED_ON : LED_OFF);\n}",
"function setSpeed(side, speed) {\n\n const scaled = speed/100 * 82 + 18\n\n if (side == LEFT) {\n pwm.setPwm(0, 0, Math.round(dutyCycle * scaled / 100));\n } else if (side == RIGHT) {\n pwm.setPwm(1, 0, Math.round(dutyCycle * scaled / 100));\n }\n}",
"function setSpeed(speed){\n for (m in motors){\n ms.setMotorSpeed(motors[m], speed);\n }\n //currentSpeed = speed;\n console.log(\"Speed set to\" + speed);\n }",
"function setspeed (motora, motorb)\n{\n motorspeed = {a:motora, b:motorb};\n}",
"function setSpeed(speed_data){\r\n\tif(speed_data == 0)\r\n\t\tset_speed = 40;\r\n\telse if(speed_data == 1)\r\n\t\tset_speed = 25;\r\n\telse\r\n\t\tset_speed = 15;\r\n}",
"setMotorSpeed () {\n var tickDelta = this.tickDelta()\n\n switch (true) {\n case (tickDelta <= 3):\n this.motor.speed = SPEEDS.SINGLE_KERNEL\n break\n case (tickDelta > 3 && tickDelta <= 8):\n //this.motor.speed = SPEEDS.VERY_SLOW\n this.motor.speed = SPEEDS.SLOW\n break\n case (tickDelta > 8 && tickDelta <= 16):\n //this.motor.speed = SPEEDS.SLOW\n this.motor.speed = SPEEDS.FAST\n break\n case (tickDelta > 16 && tickDelta <= 32):\n //this.motor.speed = SPEEDS.MEDIUM\n this.motor.speed = SPEEDS.VERY_FAST\n break\n case (tickDelta > 32 && tickDelta <= 48):\n this.motor.speed = SPEEDS.VERY_FAST\n break\n case (tickDelta > 48):\n this.motor.speed = SPEEDS.VERY_FAST\n break\n }\n }",
"set color(value) {\n this.led1.color = value\n this.led2.color = value\n this.led3.color = value\n this.led4.color = value\n this.led5.color = value\n this.led6.color = value\n this.led7.color = value\n this.led8.color = value\n }",
"set white(value) {\n this.led1.white = value\n this.led2.white = value\n this.led3.white = value\n this.led4.white = value\n this.led5.white = value\n this.led6.white = value\n this.led7.white = value\n this.led8.white = value\n }",
"function setFlashSpeed() {\n switch (round) {\n case 5:\n flashSpeed = 0.8;\n break;\n case 10:\n flashSpeed = 0.65;\n break;\n case 15:\n flashSpeed = 0.5;\n break;\n }\n}",
"function turn_all_lights_on()\n{\n\tfor (row = 0; row < switchboard_rows; row++)\n\t{\n\t\tfor (column = 0; column < switchboard_columns; column++)\n\t\t{\n\t\t\tvar element_name = \"#circle_\" + column + \"_\" + row;\n\t\t\t$(element_name).attr('fill', lit);\n\t\t}\n\t}\n}",
"set speedUS(speed) {\r\n this.speed = speed * 1.6;\r\n }",
"set SpeedUS(newSpeed){\n this.speed = newSpeed * 1.6\n }",
"set wheelDampingRate(value) {}",
"function setLED(colorval){\n color[0] = colorval ;\n ws281x.render(color);\n}",
"set cursorFlashSpeed(value) {}",
"function changeLEDBrightness() {\n if ( dutyCycle <= 0 ) {\n // Increase the brightness\n delta = 0.1;\n } else if ( dutyCycle >= 1 ) {\n // Decrease the brightness\n delta = -0.1;\n }\n\n dutyCycle = parseFloat( ( dutyCycle + delta ).toFixed( 1 ) );\n pwmPin.setDutyCycle( dutyCycle * 10000 ).then( function() {\n console.log( \"LED brightness changed\" );\n } ).catch( function( error ) {\n console.log( \"PWM error: \", error );\n process.exit();\n } );\n}",
"setSpeedCoeff(left, right) {\n this.leftWheel = this.servoStop + (this.servoSpeedSpread * left) * this.leftServoCoeff;\n this.rightWheel = this.servoStop + (this.servoSpeedSpread * right) * this.rightServoCoeff;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse JS file, extract tags by traversing AST while tracking scopes | function generateTags(sourcefile,source) {
sourcelines = source.split(/\r?\n/); //access text of a line from source file by index
try {
// var result = parse(source,{loc:true});
var result = parse(source,{
sourceType: moduleParseMode ? 'module' : 'script',
plugins: [
// enable experimental async functions
"asyncFunctions",
"classProperties", //class AAA { ooo = { x:3} }
"objectRestSpread",
"classConstructorCall",
"doExpressions",
"trailingFunctionCommas",
"decorators",
"exportExtensions",
"exponentiationOperator",
"asyncGenerators",
"functionBind",
"functionSent",
// enable jsx and flow syntax
"jsx",
"flow"
]
});
//console.log(JSON.stringify(result)); //TODO:Debug:Remove
} catch (e) {
console.error("parse error in "+sourcefile,e);
return;
}
var scopes = []; // stack of function body scopes
plugins.forEach(function(plugin) {
plugin.init(tags);
});
function extractTags(node,ancestorsPath,children){
var scope;
// TODO: various module systems
// (for the moment, we fake it by tracking 'exports')
// not to mention various class/mixin systems or ember's
// lifted object system..
// var f = function(){}
// { f : function(){} }
// NOTE: location info is start of parsed text to start of unparsed text;
// also, lines are 1-based, columns are 0-based;
// for 1-based line/colums, we need to adjust start columns
if ((node.type==='FunctionDeclaration')
||(node.type==='FunctionExpression')
||(node.type==='ArrowFunctionExpression') ) {
scopes.push(nodeScope(node));
scope = scopes.length>1 ? scopes[scopes.length-2] : "global";
if (node.type==='FunctionDeclaration' && node.id)
{
tags_push({name: node.id.name
,file: sourcefile
,addr: node.id.loc.start.line
,kind: "f"
,lineno: node.id.loc.start.line
,scope: scope
});
} else if (node.id)
{
tags_push({name: node.id.name
,file: sourcefile
,addr: node.id.loc.start.line
,kind: "fe"
,lineno: node.id.loc.start.line
,scope: node.loc.start.line+":"+(node.loc.start.column+1)+"-"
+node.loc.end.line+":"+node.loc.end.column
});
}
var paramScope = nodeScope(node);
node.params.forEach(function(param){
indexDestructId(param,sourcefile,paramScope, 'vp');
});
} else if (node.type==='VariableDeclarator') {
scope = scopes.length>0 ? scopes[scopes.length-1] : "global";
indexDestructId(node.id,sourcefile,scope, 'v');
} else if (node.type==='CatchClause') {
tags_push({name: node.param.name
,file: sourcefile
,addr: node.param.loc.start.line
,kind: "ve"
,lineno: node.param.loc.start.line
,scope: node.loc.start.line+":"+(node.loc.start.column+1)+"-"
+node.loc.end.line+":"+node.loc.end.column
});
} else if (node.type==='AssignmentExpression') {
if (node.operator==='='
&& node.left.type==='MemberExpression'
&& !node.left.computed) {
if (node.left.object.type==='Identifier'
&& node.left.object.name==='exports') {
// approximation: we don't handle module systems properly,
// so record tags for 'exports' properties, at least
tags_push({name: node.left.property.name
,file: sourcefile
,addr: node.left.property.loc.start.line
,kind: "export"
,lineno: node.left.property.loc.start.line
,scope: "global"
});
} else if (node.left.object.type==='MemberExpression'
&& !node.left.object.computed
&& node.left.object.property.type==='Identifier'
&& node.left.object.property.name==='prototype'
&& node.left.property.type==='Identifier') {
// approximation: we don't handle object properties properly,
// so record tags for 'prototype' properties as globals
tags_push({name: node.left.property.name
,file: sourcefile
,addr: node.left.property.loc.start.line
,kind: "prototype"
,lineno: node.left.property.loc.start.line
,scope: "global"
});
} else if (classic && (node.right.type==='FunctionExpression' || node.right.type==='ArrowFunctionExpression')) {
// approximation: record tags for function assignments as globals
tags_push({name: node.left.property.name
,file: sourcefile
,addr: node.left.property.loc.start.line
,kind: "fa"
,lineno: node.left.property.loc.start.line
,scope: "global"
});
}
}
} else if (classic && node.type==='ObjectExpression') {
node.properties.forEach(function(property){
plugins.forEach(function(plugin) {
plugin.visitObjectExpressionProperty && plugin.visitObjectExpressionProperty(property,node,ancestorsPath,sourcefile);
});
if (property.value && (property.value.type==='FunctionExpression' || property.value.type==='ArrowFunctionExpression') && property.key && property.key.value) {
// approximation: we don't handle object properties properly,
// so record tags for function properties as globals
tags_push({name: property.key.value
,file: sourcefile
,addr: property.loc.start.line
,kind: "f"
,lineno: property.loc.start.line
,scope: "global"
,class_id: node.class_id
});
} else if (property.key && property.key.name) {
// approximation: we don't handle object properties properly,
// so record tags for function properties as globals
tags_push({name: property.key.name
,file: sourcefile
,addr: property.loc.start.line
,kind: (property.type === 'ObjectMethod') || (property.value && (property.value.type==='FunctionExpression' || property.value.type==='ArrowFunctionExpression')) ? "f" : "property"
,lineno: property.loc.start.line
,scope: "global"
,class_id: node.class_id
});
}
});
} else if (node.type==='CallExpression') {
plugins.forEach(function(plugin) {
plugin.visitCallExpression && plugin.visitCallExpression(node, sourcefile);
});
} else {
plugins.forEach(function(plugin) {
plugin.visitUnknownNode && plugin.visitUnknownNode(node,ancestorsPath,sourcefile,scopes);
});
}
children.forEach(function(child) {
traverseWithPath(extractTags)(child,ancestorsPath.slice().concat([node]));
});
if ((node.type==='FunctionDeclaration')
||(node.type==='FunctionExpression')
||(node.type==='ArrowFunctionExpression')
||(node.type==='ClassMethod')) {
scopes.pop();
}
}
traverseWithPath(extractTags)(result,[]);
} | [
"function generateTags(sourcefile,source) {\n\n try {\n var result = parse(source,{loc:true});\n } catch (e) {\n console.error(\"parse error in \"+sourcefile,e);\n return;\n }\n\n var scopes = []; // stack of function body scopes\n\n function extractTags(node,children){\n var scope;\n\n // TODO: various module systems\n // (for the moment, we fake it by tracking 'exports')\n // not to mention various class/mixin systems or ember's \n // lifted object system..\n // var f = function(){}\n // { f : function(){} }\n\n // NOTE: location info is start of parsed text to start of unparsed text;\n // also, lines are 1-based, columns are 0-based;\n // for 1-based line/colums, we need to adjust start columns\n\n if ((node.type==='FunctionDeclaration')\n ||(node.type==='FunctionExpression')) {\n\n scopes.push(node.loc.start.line+\":\"+(node.loc.start.column+1)+\"-\"\n +node.loc.end.line+\":\"+node.loc.end.column);\n\n scope = scopes.length>1 ? scopes[scopes.length-2] : \"global\";\n\n if (node.type==='FunctionDeclaration')\n\n tags.push({name: node.id.name\n ,file: sourcefile\n ,addr: node.id.loc.start.line\n ,kind: \"f\"\n ,lineno: node.id.loc.start.line\n ,scope: scope\n });\n\n else if (node.id)\n\n tags.push({name: node.id.name\n ,file: sourcefile\n ,addr: node.id.loc.start.line\n ,kind: \"fe\"\n ,lineno: node.id.loc.start.line\n ,scope: node.loc.start.line+\":\"+(node.loc.start.column+1)+\"-\"\n +node.loc.end.line+\":\"+node.loc.end.column\n });\n\n var paramScope = node.loc.start.line+\":\"+(node.loc.start.column+1)+\"-\"\n +node.loc.end.line+\":\"+node.loc.end.column;\n\n node.params.forEach(function(param){\n tags.push({name: param.name\n ,file: sourcefile\n ,addr: param.loc.start.line\n ,kind: \"vp\"\n ,lineno: param.loc.start.line\n ,scope: paramScope\n });\n });\n\n } else if (node.type==='VariableDeclarator') {\n\n scope = scopes.length>0 ? scopes[scopes.length-1] : \"global\";\n\n tags.push({name: node.id.name\n ,file: sourcefile\n ,addr: node.id.loc.start.line\n ,kind: \"v\"\n ,lineno: node.id.loc.start.line\n ,scope: scope\n });\n\n } else if (node.type==='CatchClause') {\n\n tags.push({name: node.param.name\n ,file: sourcefile\n ,addr: node.param.loc.start.line\n ,kind: \"ve\"\n ,lineno: node.param.loc.start.line\n ,scope: node.loc.start.line+\":\"+(node.loc.start.column+1)+\"-\"\n +node.loc.end.line+\":\"+node.loc.end.column\n });\n\n } else if (node.type==='AssignmentExpression') {\n\n if (node.operator==='='\n && node.left.type==='MemberExpression'\n && !node.left.computed) {\n\n if (node.left.object.type==='Identifier'\n && node.left.object.name==='exports') {\n\n // approximation: we don't handle module systems properly,\n // so record tags for 'exports' properties, at least\n tags.push({name: node.left.property.name\n ,file: sourcefile\n ,addr: node.left.property.loc.start.line\n ,kind: \"export\"\n ,lineno: node.left.property.loc.start.line\n ,scope: \"global\"\n });\n\n } else if (node.left.object.type==='MemberExpression'\n && !node.left.object.computed\n && node.left.object.property.type==='Identifier'\n && node.left.object.property.name==='prototype'\n && node.left.property.type==='Identifier') {\n\n // approximation: we don't handle object properties properly,\n // so record tags for 'prototype' properties as globals\n tags.push({name: node.left.property.name\n ,file: sourcefile\n ,addr: node.left.property.loc.start.line\n ,kind: \"prototype\"\n ,lineno: node.left.property.loc.start.line\n ,scope: \"global\"\n });\n\n } else if (classic && node.right.type==='FunctionExpression') {\n\n // approximation: record tags for function assignments as globals\n tags.push({name: node.left.property.name\n ,file: sourcefile\n ,addr: node.left.property.loc.start.line\n ,kind: \"fa\"\n ,lineno: node.left.property.loc.start.line\n ,scope: \"global\"\n });\n\n }\n }\n } else if (classic && node.type==='ObjectExpression') {\n\n node.properties.forEach(function(property){\n\n if (property.value.type==='FunctionExpression') {\n if (property.key.value) {\n\n // approximation: we don't handle object properties properly,\n // so record tags for function properties as globals\n tags.push({name: property.key.value\n ,file: sourcefile\n ,addr: property.loc.start.line\n ,kind: \"property\"\n ,lineno: property.loc.start.line\n ,scope: \"global\"\n });\n\n } else if (property.key.name) {\n\n // approximation: we don't handle object properties properly,\n // so record tags for function properties as globals\n tags.push({name: property.key.name\n ,file: sourcefile\n ,addr: property.loc.start.line\n ,kind: \"property\"\n ,lineno: property.loc.start.line\n ,scope: \"global\"\n });\n\n }\n }\n\n });\n\n }\n\n children.forEach(traverse(extractTags));\n\n if ((node.type==='FunctionDeclaration')\n ||(node.type==='FunctionExpression')) {\n\n scopes.pop();\n\n }\n }\n\n traverse(extractTags)(result);\n}",
"function parser(ast){\n var isTextNode = ast.type === 3;\n\n var $var = '_$var_' + ( ast.tag || 'text' ) + `_${uuid++}_`;\n codes.push(`var ${$var} = [];`);\n\n var parentVar = stack[stack.length - 1] || $root;\n //var parentAST = stackAST[stackAST.length - 1];\n\n stack.push($var);\n //stackAST.push(ast);\n\n if( !isTextNode ) {\n\n ast.children.forEach((child, i)=>{\n if( child.type === 3 ) {\n codes.push(`${$var}.push(${JSON.stringify(child.text)});`); \n } else if( child.type === 1 ) {\n if( child.tag == 'js' ) {\n if( child.children.length ) {\n codes.push(`${child.children[0].text}`);\n }\n } else {\n parser(child);\n }\n }\n });\n\n }\n\n stack.length -= 1;\n //stackAST.length -= 1;\n\n //if( ast.tag === 'js' ) return;\n\n //if( stack.length )\n codes.push(`${parentVar}.push(${program}(\"${ast.tag}\", ${JSON.stringify(ast.attrsMap)}, ${$var}));`);\n //else \n // codes.push(`${program}(\"${ast.tag}\", ${JSON.stringify(ast.attrsMap)}, ${$var});`);\n }",
"function getVars(src) {\n var names = {};\n var ast = Reflect.parse(src);\n\n function visit(node) {\n if (node == undefined || node == null) return;\n if (node instanceof Array) { node.forEach(visit); return; }\n\n // figure out type of node, visit children \n switch(node.type) {\n case 'Identifier':\n names[node.name] = true; // i seen it\n break;\n case 'Program':\n case 'BlockStatement':\n visit(node.body);\n break;\n case 'ExpressionStatement':\n visit(node.expression);\n break;\n case 'IfStatement':\n case 'ConditionalStatement':\n visit(node.test);\n visit(node.consequent);\n visit(node.alternate);\n break;\n case 'LabeledStatement':\n // label Identifier is not a variable\n visit(node.body);\n break; \n case 'WithStatement':\n visit(node.object); // object will be a var\n // We need to visit the body in case there are var uses there. But \n // this means we pick up any properties set in there too...\n // Not sure if we want to avoid them. If so, we would have to\n // avoid all declarations (even ones with assignments)\n visit(node.body);\n break;\n case 'SwitchStatement':\n visit(node.discriminant);\n visit(node.cases);\n break;\n case 'ReturnStatement':\n case 'ThrowStatement':\n visit(node.argument);\n break;\n case 'TryStatement':\n visit(node.block);\n visit(node.handler);\n visit(node.finalizer);\n break;\n case 'ForStatement':\n visit(node.init);\n visit(node.update);\n case 'WhileStatement':\n case 'DoWhileStatement':\n visit(node.test);\n visit(node.body);\n break;\n case 'ForInStatement':\n visit(node.left);\n visit(node.right);\n visit(node.body);\n break;\n case 'LetStatement':\n if (node.head != null) {\n visit(node.head.init);\n visit(node.head.id); \n }\n visit(node.body);\n break;\n case 'FunctionExpression':\n case 'FunctionDeclaration':\n visit(node.body);\n break;\n case 'VariableDeclaration':\n visit(node.declarations);\n break;\n case 'VariableDeclarator':\n visit(node.id);\n visit(node.init);\n break; \n case 'ArrayExpression':\n visit(node.elements);\n break;\n case 'SequenceExpression':\n visit(node.expressions);\n break;\n case 'UnaryExpression':\n visit(node.argument);\n break;\n case 'BinaryExpression':\n case 'AssignmentExpression':\n case 'LogicalExpression':\n visit(node.left);\n visit(node.right);\n break;\n case 'UpdateExpression':\n visit(node.argument);\n break;\n case 'NewExpression':\n visit(node.callee);\n visit(node.arguments);\n break;\n case 'CallExpression':\n visit(node.callee);\n visit(node.arguments);\n break;\n case 'MemberExpression':\n visit(node.object); \n // visit computed after . but not literal, It's what Dr. Clements wants\n if (node.computed) {\n visit(node.property);\n }\n break;\n case 'YieldExpression':\n visit(node.argument);\n break;\n case 'ComprehensionExpression':\n case 'GeneratorExpression':\n visit(node.body);\n visit(node.blocks);\n visit(node.filter);\n break;\n case 'LetExpression':\n if (node.head != null) {\n for (var i = 0; i < node.head.length; i++) {\n visit(node.head[i].id);\n visit(node.head[i].init);\n }\n }\n visit(node.body);\n break;\n case 'ObjectPattern':\n case 'ObjectExpression':\n for (var i = 0; i < node.properties.length; i++) {\n // I'm not visiting keys here, as that seems the same as the \n // literal . stuff from before.\n visit(node.properties[i].value);\n }\n break;\n case 'ArrayPattern':\n visit(node.elements);\n break;\n case 'SwitchCase':\n visit(node.test);\n visit(node.consequent);\n break;\n case 'CatchClause':\n visit(node.guard);\n visit(node.body);\n break;\n case 'ComprehensionBlock':\n visit(node.left);\n visit(node.right);\n break;\n case 'XMLDefaultDeclaration':\n visit(node.namespace);\n break;\n case 'XMLQualifiedIdentifier':\n visit(node.left);\n case 'XMLFunctionQualifiedIdentifier':\n if(node.computed) {\n visit(node.right);\n }\n break;\n case 'XMLAttributeSelector':\n // avoiding obj.@foo but visiting obj.@[foo] (just as above)\n if (node.attribute.type != 'Identifier') {\n visit(node.attribute);\n }\n break;\n case 'XMLFilterExpression':\n visit(node.left);\n visit(node.right);\n break;\n case 'XMLElement':\n case 'XMLList':\n case 'XMLStartTag':\n case 'XMLEndTag':\n case 'XMLPointTag':\n visit(node.contents);\n break;\n case 'XMLName':\n if (!(node.contents instanceof String)) {\n visit(node.contents); \n }\n break;\n case 'XMLEscape':\n visit(node.expression);\n break;\n default:\n break;\n }\n } \n visit(ast); \n\n // put items from set into a list\n var varlist = [];\n for (var name in names)\n varlist.push(name); \n return varlist;\n}",
"onopentag (name, attribs) {\n lastName = name;\n lastScriptIsModule = false;\n if (name === 'script') {\n const hasSource = Object.prototype.hasOwnProperty.call(\n attribs, 'src'\n );\n const isScript = !attribs.type ||\n attribs.type === 'text/javascript';\n const isModule = attribs.type === 'module';\n const isJS = isScript || isModule;\n if (\n !isJS ||\n // Handle later\n !hasSource\n ) {\n lastScriptIsModule = isModule;\n return;\n }\n\n const sourceType = isModule ? 'module' : 'script';\n promMethods.push(() => traverseJSFile({\n file: attribs.src,\n cwd: dirname(join(cwd, htmlFile)),\n node: false,\n html: true,\n parser,\n parserOptions: {\n ...parserOptions,\n sourceType\n },\n callback,\n serial,\n excludePathEntryExpression,\n ignoreResolutionErrors,\n singleTraverse,\n noEsm,\n cjs: cjsModules,\n amd: amdModules,\n resolvedMap,\n textSet\n }));\n }\n }",
"createFunctionScopes() {\n var _a;\n //find every function\n let functions = this.parser.references.functionExpressions;\n //create a functionScope for every function\n this._functionScopes = [];\n for (let func of functions) {\n let scope = new FunctionScope_1.FunctionScope(func);\n //find parent function, and add this scope to it if found\n {\n let parentScope = this.scopesByFunc.get(func.parentFunction);\n //add this child scope to its parent\n if (parentScope) {\n parentScope.childrenScopes.push(scope);\n }\n //store the parent scope for this scope\n scope.parentScope = parentScope;\n }\n //add every parameter\n for (let param of func.parameters) {\n scope.variableDeclarations.push({\n nameRange: param.name.range,\n lineIndex: param.name.range.start.line,\n name: param.name.text,\n type: param.type\n });\n }\n //add all of ForEachStatement loop varibales\n (_a = func.body) === null || _a === void 0 ? void 0 : _a.walk((0, visitors_1.createVisitor)({\n ForEachStatement: (stmt) => {\n scope.variableDeclarations.push({\n nameRange: stmt.item.range,\n lineIndex: stmt.item.range.start.line,\n name: stmt.item.text,\n type: new DynamicType_1.DynamicType()\n });\n },\n LabelStatement: (stmt) => {\n const { identifier } = stmt.tokens;\n scope.labelStatements.push({\n nameRange: identifier.range,\n lineIndex: identifier.range.start.line,\n name: identifier.text\n });\n }\n }), {\n walkMode: visitors_1.WalkMode.visitStatements\n });\n this.scopesByFunc.set(func, scope);\n //find every statement in the scope\n this._functionScopes.push(scope);\n }\n //find every variable assignment in the whole file\n let assignmentStatements = this.parser.references.assignmentStatements;\n for (let statement of assignmentStatements) {\n //find this statement's function scope\n let scope = this.scopesByFunc.get(statement.containingFunction);\n //skip variable declarations that are outside of any scope\n if (scope) {\n scope.variableDeclarations.push({\n nameRange: statement.name.range,\n lineIndex: statement.name.range.start.line,\n name: statement.name.text,\n type: this.getBscTypeFromAssignment(statement, scope)\n });\n }\n }\n }",
"parse() {\n try {\n let result = [];\n function _find(node) {\n // Find '#!' and extract all raw expressions in one string\n const expressionsRaw_RegExp = new RegExp(`#!(.*)`).exec(node.name);\n if (expressionsRaw_RegExp) {\n const expressionsRaw = expressionsRaw_RegExp[1];\n console.log('expressionsRaw', expressionsRaw);\n\n // Split into single expressions\n const expressionsRawArray = expressionsRaw.split(';');\n\n const expressions = [];\n expressionsRawArray.forEach((expression)=>{\n // Format a=b\n if (expression.indexOf('=' > -1)) {\n const [left, right] = expression.split('=');\n expressions.push({left, right});\n }\n });\n result.push({node, expressions});\n }\n if (node.children && node.children.length) {\n node.children.forEach((child)=>{\n _find(child);\n });\n }\n }\n _find(this.node);\n return result;\n }\n catch (err) {\n console.error(err.message);\n }\n }",
"processStatements() {\n\n // Define the regex for finding statements in the html\n const regex = /(?:\\$\\{)(.*?)(?:\\})/igms;\n\n // Extract all of the matches in the html\n const matches = this.model.code.matchAll(regex);\n\n // Iterate through each of the statements and extract the variables if th\n for (const [, statement] of matches) this.extractVariables(statement);\n }",
"function sourceElementVisitor(node){switch(node.kind){case 254/* ImportDeclaration */:return visitImportDeclaration(node);case 253/* ImportEqualsDeclaration */:return visitImportEqualsDeclaration(node);case 260/* ExportDeclaration */:return visitExportDeclaration(node);case 259/* ExportAssignment */:return visitExportAssignment(node);default:return nestedElementVisitor(node);}}",
"function AST(){}",
"parseJavaScript() {\n let comments = dox.parseComments(this.contents, { raw: true });\n let sections = this.sections;\n let docs = this.docs;\n let currentClass;\n for (const annotationObject of comments) {\n let a = new annotation_1.Annotation(annotationObject, this);\n let type;\n if (!a.ignore) {\n type = a.determineType();\n switch (type) {\n case 'class':\n this.classes.push(a);\n currentClass = a;\n break;\n case 'instance':\n case 'static':\n case 'method':\n case 'function':\n if (currentClass) {\n currentClass.methods.push(a);\n }\n else {\n this.methods.push(a);\n }\n break;\n case 'property':\n if (currentClass) {\n currentClass.propertyAnnotations.push(a);\n }\n else {\n this.properties.push(a);\n }\n break;\n }\n if (!(annotationObject.tags.length > 0 &&\n annotationObject.tags[0].type === 'class' &&\n annotationObject.tags[0].string in docs.classes)) {\n sections.push(a.section);\n }\n }\n }\n }",
"function AstWalker() {}",
"function parseSourceFile(filename) {\n\t\tvar filenameArr = filename.split(/\\\\|\\//g);\n\t\tvar folder = filenameArr[filenameArr.length-2].toLowerCase(); ;\n\t\t\n var src = fs.readFileSync(filename, 'utf-8');\n var outPath = filename.replace('.xml', '.json');\n var entryTree = et.parse(src);\n var contentNodes = entryTree.findall('./CONTENT');\n var contentOut = {\"template\": \"v18\"};\n\n for (var node in contentNodes) {\n var type = contentNodes[node].findtext('./SHARED_DATA/TYPE');\n\n // also filter out nodes if ECMCC_MULTI_OPT2 JavaScript[==]js ?? or CSS?\n if (nodeTypes.indexOf(type) > -1) {\n var synkey = contentNodes[node].findtext('./SHARED_DATA/SYNDICATION_KEY');\n var title = contentNodes[node].findtext('./SHARED_DATA/TITLE');\n console.log('node type:' ,type, synkey, title);\n if (typeof contentOut[synkey] === 'undefined') contentOut[synkey] = {};\n if (title) contentOut[synkey].title = title;\n console.log('we have content synkey node:', contentOut[synkey]);\n contentOut = parseGroupNode(contentOut, folder, synkey, contentNodes[node], true, \"\");\n }\n }\n\n fs.writeFileSync(outPath, JSON.stringify(contentOut, null, \"\\t\"));\n}",
"function sourceElementVisitor(node){switch(node.kind){case 254/* ImportDeclaration */:return visitImportDeclaration(node);case 253/* ImportEqualsDeclaration */:return visitImportEqualsDeclaration(node);case 260/* ExportDeclaration */:return visitExportDeclaration(node);case 259/* ExportAssignment */:return visitExportAssignment(node);case 225/* VariableStatement */:return visitVariableStatement(node);case 244/* FunctionDeclaration */:return visitFunctionDeclaration(node);case 245/* ClassDeclaration */:return visitClassDeclaration(node);case 328/* MergeDeclarationMarker */:return visitMergeDeclarationMarker(node);case 329/* EndOfDeclarationMarker */:return visitEndOfDeclarationMarker(node);default:return ts.visitEachChild(node,moduleExpressionElementVisitor,context);}}",
"function getRangeToExtract(sourceFile,span){var length=span.length;if(length===0){return{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractEmpty)]};}// Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.\n// This may fail (e.g. you select two statements in the root of a source file)\nvar start=ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile,span.start),sourceFile,span);// Do the same for the ending position\nvar end=ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile,ts.textSpanEnd(span)),sourceFile,span);var declarations=[];// We'll modify these flags as we walk the tree to collect data\n// about what things need to be done as part of the extraction.\nvar rangeFacts=RangeFacts.None;if(!start||!end){// cannot find either start or end node\nreturn{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractRange)]};}if(start.parent!==end.parent){// start and end nodes belong to different subtrees\nreturn{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractRange)]};}if(start!==end){// start and end should be statements and parent should be either block or a source file\nif(!isBlockLike(start.parent)){return{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractRange)]};}var statements=[];var start2=start;// TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248\nfor(var _i=0,_a=start2.parent.statements;_i<_a.length;_i++){var statement=_a[_i];if(statement===start||statements.length){var errors_1=checkNode(statement);if(errors_1){return{errors:errors_1};}statements.push(statement);}if(statement===end){break;}}if(!statements.length){// https://github.com/Microsoft/TypeScript/issues/20559\n// Ranges like [|case 1: break;|] will fail to populate `statements` because\n// they will never find `start` in `start.parent.statements`.\n// Consider: We could support ranges like [|case 1:|] by refining them to just\n// the expression.\nreturn{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractRange)]};}return{targetRange:{range:statements,facts:rangeFacts,declarations:declarations}};}if(ts.isJSDoc(start)){return{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractJSDoc)]};}if(ts.isReturnStatement(start)&&!start.expression){// Makes no sense to extract an expression-less return statement.\nreturn{errors:[ts.createFileDiagnostic(sourceFile,span.start,length,Messages.cannotExtractRange)]};}// We have a single node (start)\nvar node=refineNode(start);var errors=checkRootNode(node)||checkNode(node);if(errors){return{errors:errors};}return{targetRange:{range:getStatementOrExpressionRange(node),facts:rangeFacts,declarations:declarations}};// TODO: GH#18217\n/**\n * Attempt to refine the extraction node (generally, by shrinking it) to produce better results.\n * @param node The unrefined extraction node.\n */function refineNode(node){if(ts.isReturnStatement(node)){if(node.expression){return node.expression;}}else if(ts.isVariableStatement(node)){var numInitializers=0;var lastInitializer=void 0;for(var _i=0,_a=node.declarationList.declarations;_i<_a.length;_i++){var declaration=_a[_i];if(declaration.initializer){numInitializers++;lastInitializer=declaration.initializer;}}if(numInitializers===1){return lastInitializer;}// No special handling if there are multiple initializers.\n}else if(ts.isVariableDeclaration(node)){if(node.initializer){return node.initializer;}}return node;}function checkRootNode(node){if(ts.isIdentifier(ts.isExpressionStatement(node)?node.expression:node)){return[ts.createDiagnosticForNode(node,Messages.cannotExtractIdentifier)];}return undefined;}function checkForStaticContext(nodeToCheck,containingClass){var current=nodeToCheck;while(current!==containingClass){if(current.kind===159/* PropertyDeclaration */){if(ts.hasModifier(current,32/* Static */)){rangeFacts|=RangeFacts.InStaticRegion;}break;}else if(current.kind===156/* Parameter */){var ctorOrMethod=ts.getContainingFunction(current);if(ctorOrMethod.kind===162/* Constructor */){rangeFacts|=RangeFacts.InStaticRegion;}break;}else if(current.kind===161/* MethodDeclaration */){if(ts.hasModifier(current,32/* Static */)){rangeFacts|=RangeFacts.InStaticRegion;}}current=current.parent;}}// Verifies whether we can actually extract this node or not.\nfunction checkNode(nodeToCheck){var PermittedJumps;(function(PermittedJumps){PermittedJumps[PermittedJumps[\"None\"]=0]=\"None\";PermittedJumps[PermittedJumps[\"Break\"]=1]=\"Break\";PermittedJumps[PermittedJumps[\"Continue\"]=2]=\"Continue\";PermittedJumps[PermittedJumps[\"Return\"]=4]=\"Return\";})(PermittedJumps||(PermittedJumps={}));// We believe it's true because the node is from the (unmodified) tree.\nts.Debug.assert(nodeToCheck.pos<=nodeToCheck.end,\"This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)\");// For understanding how skipTrivia functioned:\nts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos),\"This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)\");if(!ts.isStatement(nodeToCheck)&&!(ts.isExpressionNode(nodeToCheck)&&isExtractableExpression(nodeToCheck))){return[ts.createDiagnosticForNode(nodeToCheck,Messages.statementOrExpressionExpected)];}if(nodeToCheck.flags&8388608/* Ambient */){return[ts.createDiagnosticForNode(nodeToCheck,Messages.cannotExtractAmbientBlock)];}// If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)\nvar containingClass=ts.getContainingClass(nodeToCheck);if(containingClass){checkForStaticContext(nodeToCheck,containingClass);}var errors;var permittedJumps=4/* Return */;var seenLabels;visit(nodeToCheck);return errors;function visit(node){if(errors){// already found an error - can stop now\nreturn true;}if(ts.isDeclaration(node)){var declaringNode=node.kind===242/* VariableDeclaration */?node.parent.parent:node;if(ts.hasModifier(declaringNode,1/* Export */)){// TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)\n// Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!\n// Also TODO: GH#19956\n(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractExportedEntity));return true;}declarations.push(node.symbol);}// Some things can't be extracted in certain situations\nswitch(node.kind){case 254/* ImportDeclaration */:(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractImport));return true;case 102/* SuperKeyword */:// For a super *constructor call*, we have to be extracting the entire class,\n// but a super *method call* simply implies a 'this' reference\nif(node.parent.kind===196/* CallExpression */){// Super constructor call\nvar containingClass_1=ts.getContainingClass(node);// TODO:GH#18217\nif(containingClass_1.pos<span.start||containingClass_1.end>=span.start+span.length){(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractSuper));return true;}}else{rangeFacts|=RangeFacts.UsesThis;}break;}if(ts.isFunctionLikeDeclaration(node)||ts.isClassLike(node)){switch(node.kind){case 244/* FunctionDeclaration */:case 245/* ClassDeclaration */:if(ts.isSourceFile(node.parent)&&node.parent.externalModuleIndicator===undefined){// You cannot extract global declarations\n(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.functionWillNotBeVisibleInTheNewScope));}break;}// do not dive into functions or classes\nreturn false;}var savedPermittedJumps=permittedJumps;switch(node.kind){case 227/* IfStatement */:permittedJumps=0/* None */;break;case 240/* TryStatement */:// forbid all jumps inside try blocks\npermittedJumps=0/* None */;break;case 223/* Block */:if(node.parent&&node.parent.kind===240/* TryStatement */&&node.parent.finallyBlock===node){// allow unconditional returns from finally blocks\npermittedJumps=4/* Return */;}break;case 278/* DefaultClause */:case 277/* CaseClause */:// allow unlabeled break inside case clauses\npermittedJumps|=1/* Break */;break;default:if(ts.isIterationStatement(node,/*lookInLabeledStatements*/false)){// allow unlabeled break/continue inside loops\npermittedJumps|=1/* Break */|2/* Continue */;}break;}switch(node.kind){case 183/* ThisType */:case 104/* ThisKeyword */:rangeFacts|=RangeFacts.UsesThis;break;case 238/* LabeledStatement */:{var label=node.label;(seenLabels||(seenLabels=[])).push(label.escapedText);ts.forEachChild(node,visit);seenLabels.pop();break;}case 234/* BreakStatement */:case 233/* ContinueStatement */:{var label=node.label;if(label){if(!ts.contains(seenLabels,label.escapedText)){// attempts to jump to label that is not in range to be extracted\n(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));}}else{if(!(permittedJumps&(node.kind===234/* BreakStatement */?1/* Break */:2/* Continue */))){// attempt to break or continue in a forbidden context\n(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));}}break;}case 206/* AwaitExpression */:rangeFacts|=RangeFacts.IsAsyncFunction;break;case 212/* YieldExpression */:rangeFacts|=RangeFacts.IsGenerator;break;case 235/* ReturnStatement */:if(permittedJumps&4/* Return */){rangeFacts|=RangeFacts.HasReturn;}else{(errors||(errors=[])).push(ts.createDiagnosticForNode(node,Messages.cannotExtractRangeContainingConditionalReturnStatement));}break;default:ts.forEachChild(node,visit);break;}permittedJumps=savedPermittedJumps;}}}",
"initFilesAst() {\n this.cssAst = css.parse(this.cssText);\n this.jsAst = esprima.parse(this.jsText);\n }",
"function parseTree(sourceCode, sourceFileName) {\r\n const associate = [];\r\n const functions = [];\r\n const extras = [];\r\n const enumList = [];\r\n const functionNames = [];\r\n const metadataFunctionNames = [];\r\n const ids = [];\r\n const sourceFile = ts.createSourceFile(sourceFileName, sourceCode, ts.ScriptTarget.Latest, true);\r\n buildEnums(sourceFile);\r\n visit(sourceFile);\r\n const parseTreeResult = {\r\n associate,\r\n extras,\r\n functions,\r\n };\r\n return parseTreeResult;\r\n function buildEnums(node) {\r\n if (ts.isEnumDeclaration(node)) {\r\n enumList.push(node.name.getText());\r\n }\r\n ts.forEachChild(node, buildEnums);\r\n }\r\n function visit(node) {\r\n if (ts.isFunctionDeclaration(node)) {\r\n if (node.parent && node.parent.kind === ts.SyntaxKind.SourceFile) {\r\n const functionDeclaration = node;\r\n const position = getPosition(functionDeclaration);\r\n const functionErrors = [];\r\n const functionName = functionDeclaration.name ? functionDeclaration.name.text : \"\";\r\n if (checkForDuplicate(functionNames, functionName)) {\r\n const errorString = `Duplicate function name: ${functionName}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n functionNames.push(functionName);\r\n if (isCustomFunction(functionDeclaration)) {\r\n const extra = {\r\n errors: functionErrors,\r\n javascriptFunctionName: functionName,\r\n };\r\n const idName = getTagComment(functionDeclaration, CUSTOM_FUNCTION);\r\n const idNameArray = idName.split(\" \");\r\n const jsDocParamInfo = getJSDocParams(functionDeclaration);\r\n const jsDocParamTypeInfo = getJSDocParamsType(functionDeclaration);\r\n const jsDocParamOptionalInfo = getJSDocParamsOptionalType(functionDeclaration);\r\n const [lastParameter] = functionDeclaration.parameters.slice(-1);\r\n const isStreamingFunction = hasStreamingInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const isCancelableFunction = hasCancelableInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const isInvocationFunction = hasInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const parametersToParse = isStreamingFunction || isCancelableFunction || isInvocationFunction\r\n ? functionDeclaration.parameters.slice(0, functionDeclaration.parameters.length - 1)\r\n : functionDeclaration.parameters.slice(0, functionDeclaration.parameters.length);\r\n const parameterItems = {\r\n enumList,\r\n extra,\r\n jsDocParamInfo,\r\n jsDocParamOptionalInfo,\r\n jsDocParamTypeInfo,\r\n parametersToParse,\r\n };\r\n const parameters = getParameters(parameterItems);\r\n const description = getDescription(functionDeclaration);\r\n const helpUrl = normalizeLineEndings(getTagComment(functionDeclaration, HELPURL_PARAM));\r\n const result = getResults(functionDeclaration, isStreamingFunction, lastParameter, jsDocParamTypeInfo, extra, enumList);\r\n const options = getOptions(functionDeclaration, isStreamingFunction, isCancelableFunction, isInvocationFunction, extra);\r\n const funcName = functionDeclaration.name ? functionDeclaration.name.text : \"\";\r\n const id = normalizeCustomFunctionId(idNameArray[0] || funcName);\r\n const name = idNameArray[1] || id;\r\n validateId(id, position, extra);\r\n validateName(name, position, extra);\r\n if (checkForDuplicate(metadataFunctionNames, name)) {\r\n const errorString = `@customfunction tag specifies a duplicate name: ${name}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n metadataFunctionNames.push(name);\r\n if (checkForDuplicate(ids, id)) {\r\n const errorString = `@customfunction tag specifies a duplicate id: ${id}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n ids.push(id);\r\n associate.push({ functionName, id });\r\n const functionMetadata = {\r\n description,\r\n helpUrl,\r\n id,\r\n name,\r\n options,\r\n parameters,\r\n result,\r\n };\r\n if (!options.cancelable &&\r\n !options.requiresAddress &&\r\n !options.stream &&\r\n !options.volatile &&\r\n !options.requiresParameterAddresses) {\r\n delete functionMetadata.options;\r\n }\r\n else {\r\n if (!options.cancelable) {\r\n delete options.cancelable;\r\n }\r\n if (!options.requiresAddress) {\r\n delete options.requiresAddress;\r\n }\r\n if (!options.stream) {\r\n delete options.stream;\r\n }\r\n if (!options.volatile) {\r\n delete options.volatile;\r\n }\r\n if (!options.requiresParameterAddresses) {\r\n delete options.requiresParameterAddresses;\r\n }\r\n }\r\n if (!functionMetadata.helpUrl) {\r\n delete functionMetadata.helpUrl;\r\n }\r\n if (!functionMetadata.description) {\r\n delete functionMetadata.description;\r\n }\r\n if (!functionMetadata.result) {\r\n delete functionMetadata.result;\r\n }\r\n extras.push(extra);\r\n functions.push(functionMetadata);\r\n }\r\n }\r\n }\r\n ts.forEachChild(node, visit);\r\n }\r\n}",
"function ParseScript(script) {\n\tif (!script) {\n\t\treturn [];\n\t}\n\t\n\tvar lines = script.split('\\n');\n\tvar cmdtree = [];\n\tvar i, j;\n\n\tfor (i = 0; i < lines.length; i++) { // Go thru each line.\n\n\t\tvar cmd = { line: i, code: [], src: lines[i], timeout: 5000 }; // setup cmd structure\n\n\t\tvar stmt = lines[i].match(/\\w+|'[^']+'|\"[^\"]+\"|\\{\\{(.*?)\\}\\}|\\*|:/g); // break the line into words, \"quoted\" or 'quoted' tokens, and {{tags}}\n\t\tif (stmt) {\n\t\t\tif (stmt[0].charAt(0)!=='*') { \t\t\t\t\t// We support bulleted lists of field/value pair. If this is not one, then we process it differently.\n\t\t\t\tfor (j = 0; j < stmt.length; j++) {\n\t\t\t\t\tvar z = stmt[j].charAt(0);\n\t\t\t\t\tif (z === '{' || z === '\"' || z === '\\'' ) {\n\t\t\t\t\t\tcmd.code.push(stmt[j]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar candidate = stmt[j].toLowerCase();\n\t\t\t\t\t\tswitch (candidate) {\n\t\t\t\t\t\t\t// verbs\n\t\t\t\t\t\t\tcase 'click':\n\t\t\t\t\t\t\t\tcmd.code.push(candidate);\n\t\t\t\t\t\t\t\tcmd.code.push('in');\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'type':\n\t\t\t\t\t\t\tcase 'capture':\n\t\t\t\t\t\t\tcase 'test':\n\t\t\t\t\t\t\tcase 'open':\n\t\t\t\t\t\t\tcase 'wait':\n\t\t\t\t\t\t\tcase 'switch':\n\t\t\t\t\t\t\tcase 'navigate':\n\t\t\t\t\t\t\tcase 'press':\n\n\t\t\t\t\t\t\t// nouns\n\t\t\t\t\t\t\tcase 'button':\n\t\t\t\t\t\t\tcase 'close':\n\t\t\t\t\t\t\tcase 'autocomplete':\n\t\t\t\t\t\t\tcase 'ok':\n\t\t\t\t\t\t\tcase 'save':\n\t\t\t\t\t\t\t\tcmd.code.push(candidate);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'on':\n\t\t\t\t\t\t\tcase 'in':\n\t\t\t\t\t\t\tcase 'into':\n\t\t\t\t\t\t\t\tif ((cmd.code.length) && (cmd.code[ cmd.code.length - 1 ] === 'in'))\n\t\t\t\t\t\t\t\t\t; // do nothing\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tcmd.code.push('in');\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else { // this is a field value pair. ie: * Field: value\n\t\t\t\tcmd.code.push('type');\n\t\t\t\tstmt = lines[i].match(/\\*[^:]+|:.+/g);\n\t\t\t\tcmd.code.push(stmt[1].slice(1).trim());\n\t\t\t\tcmd.code.push('in');\n\t\t\t\tcmd.code.push(stmt[0].slice(1).trim());\n\t\t\t}\n\t\t}\n\t\tcmdtree.push(cmd);\n\t}\n\treturn cmdtree;\n}",
"async loadAllFilesAST() {\n await this.logger.time(Logger_1.LogLevel.log, ['Parsing files'], async () => {\n let errorCount = 0;\n let files = await this.logger.time(Logger_1.LogLevel.debug, ['getFilePaths'], async () => {\n return util_1.util.getFilePaths(this.options);\n });\n this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);\n const typedefFiles = [];\n const nonTypedefFiles = [];\n for (const file of files) {\n const srcLower = file.src.toLowerCase();\n if (srcLower.endsWith('.d.bs')) {\n typedefFiles.push(file);\n }\n else {\n nonTypedefFiles.push(file);\n }\n }\n //preload every type definition file first, which eliminates duplicate file loading\n await Promise.all(typedefFiles.map(async (fileObj) => {\n try {\n this.program.setFile(fileObj, await this.getFileContents(fileObj.src));\n }\n catch (e) {\n //log the error, but don't fail this process because the file might be fixable later\n this.logger.log(e);\n }\n }));\n const acceptableExtensions = ['.bs', '.brs', '.xml'];\n //parse every file other than the type definitions\n await Promise.all(nonTypedefFiles.map(async (fileObj) => {\n try {\n let fileExtension = path.extname(fileObj.src).toLowerCase();\n //only process certain file types\n if (acceptableExtensions.includes(fileExtension)) {\n this.program.setFile(fileObj, await this.getFileContents(fileObj.src));\n }\n }\n catch (e) {\n //log the error, but don't fail this process because the file might be fixable later\n this.logger.log(e);\n }\n }));\n return errorCount;\n });\n }",
"function sourceElementVisitor(node) {\n switch (node.kind) {\n case 237 /* ImportDeclaration */:\n return visitImportDeclaration(node);\n case 236 /* ImportEqualsDeclaration */:\n return visitImportEqualsDeclaration(node);\n case 243 /* ExportDeclaration */:\n return visitExportDeclaration(node);\n case 242 /* ExportAssignment */:\n return visitExportAssignment(node);\n case 207 /* VariableStatement */:\n return visitVariableStatement(node);\n case 227 /* FunctionDeclaration */:\n return visitFunctionDeclaration(node);\n case 228 /* ClassDeclaration */:\n return visitClassDeclaration(node);\n case 298 /* MergeDeclarationMarker */:\n return visitMergeDeclarationMarker(node);\n case 299 /* EndOfDeclarationMarker */:\n return visitEndOfDeclarationMarker(node);\n default:\n // This visitor does not descend into the tree, as export/import statements\n // are only transformed at the top level of a file.\n return node;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add facebook integration to the user object | static async addFacebookIntegration(userId, authResponse) {
try {
//get long token
const longTermUserAuth = await FacebookLogic.extendAccessToken(authResponse.accessToken);
//get the user
const user = await DBManager.getUserById(userId);
//if this is a new user
if (!user) {
//create default user with default parameters
const newUser = deepCopy(DefaultUserModel);
newUser._id = userId;
newUser.fullname = displayName;
newUser.conversationData = conversationData;
await DBManager.saveUser(newUser);
}
//set the facebook integration to the user
user.integrations.Facebook = longTermUserAuth;
//get pages details
const pagesResult = await MyUtils.makeRequest("GET", MyUtils.addParamsToUrl("https://graph.facebook.com/me/accounts", {access_token: authResponse.accessToken}));
if (pagesResult && pagesResult.data) {
user.integrations.Facebook.pages = pagesResult.data;
//extend tokens for all pages TODO move it to promise.all
for (let page of user.integrations.Facebook.pages) {
const tokenObject = await FacebookLogic.extendAccessToken(page.access_token);
page.access_token = tokenObject.access_token;
//if there is only one page - make it enabled by default.
page.isEnabled = user.integrations.Facebook.pages.length === 1 || false;
}
}
//save user
await DBManager.saveUser(user);
return {status: 200, message: "integrated successfully with Facebook"};
} catch (err) {
MyLog.error("Failed to integrate with Facebook", err);
}
} | [
"function addFacebook(user, profile, token, done) {\n\n console.log(profile.name);\n\n user.facebook.id = profile.id;\n user.facebook.token = token;\n user.facebook.name = profile.displayName;\n user.facebook.email = profile.emails[0].value;\n user.firstName = profile.name.givenName;\n user.lastName = profile.name.familyName;\n\n user.save(function(err) { // save facebook credentials to db\n\n if (err) {\n\n throw err;\n\n }\n\n return done(null, user); // save user to session\n\n });\n\n}",
"function FacebookSignIn(){\n facebookConnectPlugin.login([\"public_profile\",\"email\"],fbCheckConnection, failure);\n }",
"setFbUser(state, fbUserData) {\n state.fbUser = fbUserData;\n }",
"function seeFacebookConnect()\r\n{\r\n // clear #seeForm (we may write an error there)\r\n $( '#seeForm' ).html('');\r\n\r\n player.UserRegistration.connectSocial( 'Facebook' );\r\n}",
"function seeFacebookConnect() {\n // clear #seeForm (we may write an error there)\n $(\"#seeForm\").html(\"\");\n\n player.UserRegistration.connectSocial(\"Facebook\");\n}",
"saveFacebookSignInAuth (data) {\n // console.log('saveFacebookSignInAuth (result of incoming data from the FB API) kicking off an api server voterFacebookSignInSave');\n Dispatcher.loadEndpoint('voterFacebookSignInSave', {\n facebook_access_token: data.accessToken || false,\n facebook_user_id: data.userID || false,\n facebook_expires_in: data.expiresIn || false,\n facebook_signed_request: data.signedRequest || false,\n save_auth_data: true,\n save_profile_data: false,\n });\n }",
"function weiboUser(accessToken, refreshToken, profile, done) {\n\n if(!profile) {\n console.log('fire');\n return done(null, false);\n }\n\n var user = {\n provider: profile.provider,\n id: profile.id,\n username: profile.username,\n nickname: profile.nickname,\n avatar: profile.avatarUrl,\n token: accessToken,\n secret: refreshToken\n }\n\n oauthUser(user, done);\n\n }",
"function updateFacebookInformation(user, profile, access_token, done) {\n var anythingChanged = false;\n\n if (user.facebook.id != profile.id) {\n user.facebook.id = profile.id;\n anythingChanged = true;\n }\n\n if (user.facebook.access_token != access_token) {\n user.facebook.access_token = access_token; // we will save the token that facebook provides to the user \n anythingChanged = true;\n }\n\n if (user.facebook.name != profile.displayName) {\n user.facebook.name = profile.displayName;\n anythingChanged = true;\n }\n\n var description = capitalizeFirstLetter(profile._json.gender);\n var country = country_language.getCountry(profile._json.locale.slice(3)).name;\n if (country) {\n if (description)\n description += \", from \";\n else\n description += \"From \";\n description += country;\n }\n if (user.facebook.description != description) {\n user.facebook.description = description;\n anythingChanged = true;\n }\n\n if (anythingChanged) {\n user.save(function(err) {\n if (err)\n return done(err);\n return done(null, user);\n });\n }\n}",
"registerUserLinkedCallback(callback) {\n this.callbacks.ACCOUNT_USER_LINKED.push(callback);\n }",
"FBSigninSuccess(state, payload) {\n FB.api('/me?fields=id,name,picture.type(large)', function (user) {\n //store user data in db and get that stored data from db and use it\n axios.post(state.config.api + 'fbuser.php', user, state.config.axiosHeader)\n .then(function (response) {\n //set userData and cookie to response data\n cookie.set('ud', JSON.stringify(response.data));\n state.userData = response.data;\n state.userData.socialAuth = true;\n state.isLoggedIn = true;\n state.socialAuth = true;\n state.loadingScreen = false; \n })\n .catch(function (response) {\n //if something goes wrong\n console.log(response);\n });\n }); \n }",
"function sendToFirebase() {\n let userBuilder = createUserObj();\n db.addUserFB(userBuilder);\n}",
"async askForFacebookIntegration() {\n\n\t\ttry {\n\t\t\tconst {user} = this;\n\n\t\t\tawait this.sendMessagesV2([\n\t\t\t\t[FacebookResponse.getButtonMessage(\"To post on Facebook page, you must integrate with Facebook platform. Let's do it! 💪\", [\n\t\t\t\t\tFacebookResponse.getGenericButton(\"web_url\", \"My Integrations\", null, `${ZoiConfig.clientUrl}/integrations?userId=${user._id}&skipExtension=true`, null, false)\n\t\t\t\t]), false]\n\t\t\t]);\n\n\t\t\treturn MyUtils.SUCCESS;\n\t\t} catch (err) {\n\t\t\tawait this.clearConversation();\n\t\t\tMyLog.error(err);\n\t\t\treturn MyUtils.ERROR;\n\t\t}\n\t}",
"function oauthLink(mappings, user, accessToken, profile, done) {\n user[mappings.providerField] = profile[mappings.id];\n user.tokens.push({ kind: mappings.providerField, accessToken });\n user.profile.name = user.profile.name || objectByString(profile, mappings.name);\n user.profile.picture = user.profile.picture || objectByString(profile, mappings.picture);\n user.profile.gender = user.profile.gender || objectByString(profile, mappings.gender);\n user.profile.location = user.profile.location || objectByString(profile, mappings.location);\n user.profile.website = user.profile.website || objectByString(profile, mappings.website);\n user.save((err) => {\n // console.info(err);\n return done(err, user, { message : `${mappings.provider} account has been linked.` });\n });\n}",
"function signupExternalUser(facebookAccessToken) {\n var uri = new productServiceEndPoints(window.IsProductionMode).registerExternalUserUrl();\n $.ajax({\n url: uri,\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'authorization': 'bearer ' + facebookAccessToken\n },\n success: function (response) {\n window.location.href = new facebookAuthServiceEndPoints(window.IsProductionMode).facebookSigninUrl();\n },\n error: function (jqXHR) {\n // API returns error in jQuery xml http request object.\n $('#errorMessage').text(jqXHR.responseText);\n $('#validationError').show('fade');\n }\n });\n }",
"function seeFacebookLogin() {\n // clear #seeForm (we may write an error there)\n $(\"#seeForm\").html(\"\");\n\n player.UserRegistration.login({ method: \"Facebook\" });\n}",
"function startGameWithFbUser(data){\n console.log(data);\n let username = data.displayName;\n let photoURL = data.photos[0];\n\n // validate unique name constraint\n let validUsername = validateUsername(username);\n if (!validUsername) {\n let errorMsg = document.querySelector('#usernameError');\n errorMsg.innerHTML = \"user already signed in\";\n return;\n } else {\n let errorMsg = document.querySelector('#usernameError');\n errorMsg.innerHTML = '';\n }\n\n let user = new User(socket.id, username);\n user.photoURL = photoURL;\n socket.userinfo = user;\n updateHeadAfterLogin(user);\n\n // update other users\n socket.emit('new user', user);\n\n // send player movement to server\n setInterval(function() {\n let data = {\n 'movement': movement,\n 'limits': {\n 'right': canvas.width,\n 'bottom': canvas.height\n }\n };\n socket.emit('movement', data);\n }, 1000 / 60);\n }",
"function createUserAccount(facebookResponse) {\n hashCode = function(s){\n return s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);\n };\n var newUser = { recordType: \"User\",\n fields: {\n Details: {value: [\"Welcome to Goe! Adjust me with the edit button in the upper right corner.\"]},\n Email: {value: facebookResponse.email},\n Name: {value: facebookResponse.first_name+\".\"+facebookResponse.last_name},\n Facebook_ID: {value: facebookResponse.id},\n Goe_Rating: {value: 0},\n Password: {value: \"NA\"},\n Status: {value: 0},\n ID: {value: hashCode(facebookResponse.first_name+\".\"+facebookResponse.last_name+\".\"+facebookResponse.id).toString()}\n }\n };\n publicDB.saveRecord(newUser).then(function(response) {\n //handle errors\n var userReference = response._results[0].recordName;\n var userID = response._results[0].fields.ID.value;\n var userName = response._results[0].fields.Name.value;\n createUserProfile({userID: userID, userReference: userReference, userName: userName});\n })\n}",
"function _addFbConnectorSucceed(connector) {\n RightMenu.rightMenuLoading(false);\n DataSources.addConnector(ConnectorsTemplate.ConnectorType.Facebook, connector);\n ////RightMenu.showHideRightMenu(false);\n ////DataSourcesHelper.addConnector(ConnectorsTemplate.ConnectorType.Facebook, connector);\n ////DataSources.showConnector(connector);\n }",
"function _addFbConnector() {\n var connectorLabel;\n //test if profil exist\n if (!_isFbProfilExist(fbconnectorModelToSend.connector.payload.id))\n {\n connectorLabel = CDHelper.trim(txt_fbSourceNameTxt_input.value);\n //check connector label validity \n if (DataSourcesHelper.isValidNameSource(ConnectorsTemplate.ConnectorType.Facebook, connectorLabel, lbl_fbSourceName_error)) {\n fbconnectorModelToSend.connector.payload.name = connectorLabel; //TODO\n\n // add group_id to connector\n CDHelper.requireScriptJS(Scripts.defaultWidget);\n var selectGroup = div_fbSourceName.querySelector(\".\" + DefaultWidget._SLCT_GROUP);\n if (selectGroup) {\n if (selectGroup.length > 0) {\n var groupId = selectGroup.options[selectGroup.selectedIndex].value;\n if (groupId) {\n fbconnectorModelToSend.connector.group_id = groupId;\n }\n }\n }\n \n RightMenu.rightMenuLoading(true);\n ConnectorsServices.addConnector(fbconnectorModelToSend, _addFbConnectorSucceed, _addFbConnectorFailed);\n }\n }\n else {\n if (fbconnectorModelToSend.connector.public) {\n lbl_fbSourceName_error.innerHTML = MessagesHelper.TXT_PROFIL_EXIST;\n }\n\n else {\n lbl_fbSourceName_error.innerHTML = MessagesHelper.FB_INSIGHT_PROFIL_EXIST;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DigitClassifier constructor, mirrors that of a NeuralNetwork, except output count is always | function DigitClassifier(inputCount, layers) {
if (layers === void 0) { layers = []; }
this.outputCount = layers.length > 0 ? layers[layers.length - 1].neuronCount : inputCount;
this.neuralNetwork = new NeuralNetwork_1.NeuralNetwork(inputCount, layers);
} | [
"constructor(inputCount, outputCount, innovationNumber) {\n\t\tthis._innovationNumber = innovationNumber;\n\t\tthis._inputCount = inputCount;\n\t\tthis._outputCount = outputCount;\n\t\tthis._genome = new HashMap();\n\t\tthis._values = [];\n\t\tthis._network = new NeuralNetwork(inputCount, outputCount);\n\t}",
"constructor() {\n this.knnClassifier = knnClassifier.create();\n this.mapStringToIndex = [];\n this.kNum = 25;\n }",
"constructor(numberOfNeuronsInInputLayer, numberOfNeuronsInHiddenLayers, numberOfNeuronsInOutputLayer) {\n super(numberOfNeuronsInInputLayer, numberOfNeuronsInHiddenLayers, numberOfNeuronsInOutputLayer);\n\n //-------------------------------------------------------------------------------------------------\n // Hyper-parameters\n\n // the maximum number of learning examples the net uses when learning.\n this.maxLearningBatchSize = 100;\n\n //-------------------------------------------------------------------------------------------------\n // Internal variables\n\n // What the net learns from, input values paired with output values.\n this.learningExamples = [];\n }",
"constructor(inputnodes, hiddennodes, outputnodes, learning_rate, activation) {\n // If it's a copy of another NN\n if (arguments[0] instanceof NeuralNetwork) {\n const nn = arguments[0];\n this.inodes = nn.inodes;\n this.hnodes = nn.hnodes;\n this.onodes = nn.onodes;\n this.wih = nn.wih.copy();\n this.who = nn.who.copy();\n this.activation = nn.activation;\n this.derivative = nn.derivative;\n this.lr = this.lr;\n } else {\n // Number of nodes in layer (input, hidden, output)\n // This network is limited to 3 layers\n this.inodes = inputnodes;\n this.hnodes = hiddennodes;\n this.onodes = outputnodes;\n\n // These are the weight matrices\n // wih: weights from input to hidden\n // who: weights from hidden to output\n // weights inside the arrays are w_i_j\n // where link is from node i to node j in the next layer\n // Matrix is rows X columns\n this.wih = new Matrix(this.hnodes, this.inodes);\n this.who = new Matrix(this.onodes, this.hnodes);\n\n // Start with random values\n this.wih.randomize();\n this.who.randomize();\n\n // Default learning rate of 0.3\n this.lr = learning_rate || 0.3;\n\n // Activation Function\n if (activation == 'tanh') {\n this.activation = NeuralNetwork.tanh;\n this.derivative = NeuralNetwork.dtanh;\n } else {\n this.activation = NeuralNetwork.sigmoid;\n this.derivative = NeuralNetwork.dsigmoid;\n }\n\n }\n\n }",
"constructor(numberOfNeuronsInInputLayer, numberOfNeuronsInHiddenLayers, numberOfNeuronsInOutputLayer) {\n // Hyper-parameters\n\n // The activation function that's applied to the hidden neurons.\n this.neuronActivation = Neuralt.Activations.LeakyReLU;\n\n // The activation function that's applied to the output neurons.\n this.outputNeuronActivation = Neuralt.Activations.LeakyReLU;\n\n //-------------------------------------------------------------------------------------------------\n // Internal variables\n\n // Two-dimensional array of neuron layers and neurons.\n this.neurons = [[]];\n\n // Total number of parameters in the whole neural network.\n this.numberOfParameters = 0;\n\n //-------------------------------------------------------------------------------------------------\n // Construct neural network\n\n // Input layer\n for (let a = 0; a < numberOfNeuronsInInputLayer; a++) {\n this.neurons[0].push(new Neuralt.InputNeuron());\n }\n\n // Hidden layers and output layer\n for (let a = 0; a < numberOfNeuronsInHiddenLayers.length + 1; a++) {\n this.neurons.push([]);\n let isOutputLayer = (a == numberOfNeuronsInHiddenLayers.length);\n for (let b = 0; b < (isOutputLayer ? numberOfNeuronsInOutputLayer : numberOfNeuronsInHiddenLayers[a]); b++) {\n this.neurons[this.neurons.length - 1].push(new Neuralt.Neuron(this.neurons[this.neurons.length - 2], isOutputLayer, this));\n }\n this.numberOfParameters += (this.neurons[a].length + 1) * this.neurons[a + 1].length;\n }\n }",
"constructor(numNeuronsNL, randomNum) {\n\t\tthis.weights = []; // array of weights which connects this layer's neurons to the previous layer's neurons\n\t\tthis.output = 0; // this is the activated output value that a neuron holds\t\t\n\t\tthis.deltaError = 0; // contains the delta error value\n\t\tthis.assignWeights(numNeuronsNL, randomNum);\n\t}",
"constructor(n, c) {\n this.lc = c; // learning constant\n this.weights = new Array(n);\n for (let i = 0; i < n; i++) {\n this.weights[i] = random (-1, 1);\n }\n }",
"constructor(structure) {\n /* structure is an array of the form [L_0, L_1, L_2, L_3, ..., L_n] \n where L_i is the number of nodes in layer i. L_0 is the \n number of inputs and L_n is the number of outputs \n */\n this.layers = structure.slice(0); // Non-reference copy of structure\n this.layers[0] += 1; // Make room for the bias\n this.nodes = []; // Node values in the network\n for (var layer=0; layer<this.layers.length; layer++) {\n this.nodes.push([]); \n for (var node=0; node<this.layers[layer]; node++) {\n this.nodes[layer].push(0.0); \n }\n } \n this.weights = []; \n this.activation_function = this.relu; \n this.randomize_weights(); \n }",
"function NeuralNetwork(){\n /**\n * matrix is an adjacentcy list representing the network\n * the value at matrix[i][j] is the weight of the synapse connecting\n * neuron i to neuron j.\n * Inherently, all neurons in the network always exist, it's just some\n * are not connected at all.\n * When looping, always go i = 0 -> TOTAL_NEURONS then j = i+1 -> TOTAL_NEURONS\n * This prevents cycles in the network, and actually saves some ram.\n **/\n this.matrix = new Array();\n for (var i = 0; i < TOTAL_NEURONS; i++){\n this.matrix[i] = new Array();\n for (var j = i+1; j < TOTAL_NEURONS; j++)\n this.matrix[i][j] = 0;\n }\n //connect input layer to output layer by default\n for (var i = INPUT_START; i < INPUT_END; i++)\n for (var j = OUTPUT_START; j < OUTPUT_END; j++)\n this.matrix[i][j] = g.random();\n\n /**\n * fires keeps the state of the network at an epoch.\n * hasFired becomes true if we have already calculated a neurons output,\n * in which case the value of that neurons output is `output`\n **/\n this.fires = new Array();\n for (var i = 0; i < TOTAL_NEURONS; i++)\n this.fires[i] = { hasFired : true , output : 0 };\n}",
"function Network() {\n\n\t// Initialize layers\n\tthis.inputLayer = new Layer();\n\tthis.hiddenLayer1 = new Layer();\n\tthis.hiddenLayer2 = new Layer();\n\tthis.outputLayer = new Layer();\n\tthis.inputLayer.initialize(784, 16, LayerType.INPUT);\n\tthis.hiddenLayer1.initialize(16, 16, LayerType.HIDDEN);\n\tthis.hiddenLayer2.initialize(16, 10, LayerType.HIDDEN);\n\tthis.outputLayer.initialize(10, 0, LayerType.OUTPUT);\n\n\n\t/**\n\t* Accepts an input and propagates it forward through the network\n\t* @param inputs: An array containing the input values for the input layer\n\t* @return: An array containing the output values of the output layer\n\t*/\n\tthis.input = function(inputs) {\n\n\t\t// Activate the layers\n\t\tthis.inputLayer.activate(inputs, 0);\n\t\tthis.hiddenLayer1.activate(0, this.inputLayer);\n\t\tthis.hiddenLayer2.activate(0, this.hiddenLayer1);\n\t\tthis.outputLayer.activate(0, this.hiddenLayer2);\n\n\t\t// Return the output\n\t\tvar result = [];\n\t\tfor(var i = 0; i < this.outputLayer.neurons.length; i++) {\n\t\t\tresult.push(this.outputLayer.neurons[i].activation);\n\t\t}\n\t\treturn result;\n\t}\n\n\n\t/**\n\t* Gets the network's prediction for an input drawing\n\t* @param inputPixels: The 2D array of input pixels\n\t* @return: The network's prediction, confidence, and output values\n\t*/\n\tthis.getPrediction = function(inputPixels) {\n\t\t\n\t\t// The result object\n\t\tvar result = {\n\t\t\tdigit: 0,\n\t\t\tconfidence: 0,\n\t\t\toutputs: 0\n\t\t};\n\n\t\t// Get output from network\n\t\tvar out = this.input(inputPixels);\n\n\t\t// Get the network's prediction\n\t\tvar digit = 0;\n\t\tvar maxActivation = 0;\n\t for(var j = 0; j < 10; j++) {\n\t if(out[j] > maxActivation) {\n\t digit = j;\n\t maxActivation = out[j];\n\t }\n\t }\n\t result.digit = digit;\n\t result.confidence = maxActivation;\n\t result.outputs = out;\n\t \n\t return result;\n\t}\n}",
"construct(n : int, prevLayer : Layer, last : boolean){\r\n _first = false\r\n _last = last\r\n _neurons = new Neuron[n]\r\n for(i in 0..|n){\r\n _neurons[i] = new SigmoidNeuron(prevLayer.Neurons) //sends all neurons from the previous layer as input\r\n }\r\n }",
"async classify(inputString, limit = 10) {\n\n if (DEBUG) {\n console.log(inputString.match(/.{1,64}/g).join('\\n'));\n }\n\n if (this.session === null) {\n this.session = new InferenceSession();\n await this.session.loadModel(ONNX_FILE);\n }\n\n const inputArray = new Float32Array(inputString.split('').map(digit => (digit === '1' ? 1 : 0)));\n\n const inputTensor = new Tensor(inputArray, 'float32', [1, 1, 64, 64]);\n\n const outputMap = await this.session.run([inputTensor]);\n\n const rawValues = Array.from(outputMap.values())[0].data;\n\n // Trim off any \"nothing\" labels. They are all at the end of this.labels.\n // They are added as padding during training and the client is not interested in them.\n const nothingOut = ((_e, i) => (!(this.labels[i].startsWith('nothing'))));\n\n const trimmedValues = rawValues.filter(nothingOut);\n const trimmedLabels = this.labels.filter(nothingOut);\n\n // Implementation detail with this particular network- we need to compute softmax\n const exponents = trimmedValues.map(Math.exp);\n const exponentSum = exponents.reduce((acc, e) => acc + e, 0);\n const softmax = exponents.map(e => e / exponentSum);\n\n const valueByLabel = trimmedLabels.reduce((acc, e, i) => {\n acc[e] = softmax[i];\n return acc;\n }, {});\n\n const sortedLabels = trimmedLabels.sort((e1, e2) => valueByLabel[e2] - valueByLabel[e1]);\n // Return top ten\n const tags = sortedLabels.slice(0, limit).map((label => ({ label, value: valueByLabel[label] })));\n\n // Reassemble valueByLabel but sort the keys in descending value order\n const sortedValueByLabel = sortedLabels.reduce((acc, label) => {\n acc[label] = valueByLabel[label];\n return acc;\n }, {});\n\n const returnValue = { valueByLabel: sortedValueByLabel, tags };\n if (DEBUG) {\n console.log(`Classifier result: ${sortedLabels[0]}`);\n console.dir(returnValue);\n }\n return returnValue;\n }",
"constructor(weights, trainingData, expectedResults, bias) {\n this.weights = weights;\n console.log('Perceptron weights: ');\n let i = 0;\n for(let weight of weights){\n console.log('W' + i + ': ' + weight + ' ');\n i++;\n }\n this.expectedResults = expectedResults;\n this.trainingData = trainingData;\n // position in training data set\n this.dataPos = 0;\n this.learningRate = 0.1;\n this.bias = bias;\n }",
"preprocessData() {\n const { features, labels } = this.dataController.getData();\n let points = features;\n if (this.algorithm.requiresFeatureScaling) {\n const scaler = new Scaler([0, 0], [this.plot.width, this.plot.height]);\n points = scaler.scale(features);\n }\n this.classifier = new this.algorithm();\n this.classifier.hyperParams = this.hyperParams.values; //inject hyperparams into classifier\n this.X = new Matrix(points);\n if (this.algorithm.requiresDesignMatrix) {\n this.X = this.X.insertCol(1); // insert 1 at the start of each row to make design matrix\n }\n this.Y = new Matrix([labels]).transpose();\n }",
"function KNN() {\n (0, _classCallCheck3.default)(this, KNN);\n\n this.knnClassifier = knnClassifier.create();\n this.mapStringToIndex = [];\n }",
"constructor(n, lr){\n this.weights = new Array(n);\n this.lr = lr;\n //Initialize the weights randomly\n for (let i = 0; i < this.weights.length; i++){\n this.weights[i] = Math.random(-1, 1);\n }\n }",
"constructor(sizes){\r\n this.layers = new Array(); //We wnt this lib to be as dinamic as possible, so we need to store all the layers in an array.\r\n this.biases = new Array(sizes.length-1);\r\n this.biases.fill(1); //We start of with every bias being 1.\r\n this.weights = new Array();\r\n this.temp = new Array();\r\n this.output = new Array(sizes[sizes.length -1]);\r\n this.netconfig = sizes; //Just so we can later see what the network looks like in the console.\r\n for(let i = 0; i < sizes.length; i++){ //Loop through every layer.\r\n //Create layers.\r\n this.layers.push(new Array(sizes[i])); //Put an array with the size of the layer inside the bigger array containing all the layers\r\n //Create Weights\r\n for(let j = 0; j < sizes[i + 1]; j++){\r\n this.temp.push(new Array(sizes[i]));\r\n this.temp[j].fill(Math.random() * 2 -1);\r\n }\r\n this.weights.push(this.temp);\r\n this.temp = new Array();\r\n }\r\n delete this.temp;\r\n this.weights.pop();\r\n }",
"constructor(label){\n // Affect the members\n this.label = label;\n this.totalData = [];\n this.trainingData = [];\n this.testingData = [];\n this.trainingLabels = [];\n this.testingLabels = [];\n }",
"constructor({\n neurons,\n data,\n maxStep = 10000,\n minLearningCoef = .1,\n maxLearningCoef = .4,\n minNeighborhood = .3,\n maxNeighborhood = 1,\n }) {\n\n // data vectors should have at least one dimension\n if (!data[0].length) {\n throw new Error('Kohonen constructor: data vectors should have at least one dimension');\n }\n\n // all vectors should have the same size\n // all vectors values should be number\n for (let ind in data) {\n if (data[ind].length !== data[0].length) {\n throw new Error('Kohonen constructor: all vectors should have the same size');\n }\n const allNum = _.reduce(\n (seed, current) => seed && !isNaN(current) && isFinite(current),\n true,\n data[ind]\n );\n if(!allNum) {\n throw new Error('Kohonen constructor: all vectors should number values');\n }\n }\n\n this.size = data[0].length;\n this.numNeurons = neurons.length;\n this.step = 0;\n this.maxStep = maxStep;\n\n // generate scaleStepLearningCoef,\n // as the learning coef decreases with time\n this.scaleStepLearningCoef = scaleLinear()\n .clamp(true)\n .domain([0, maxStep])\n .range([maxLearningCoef, minLearningCoef]);\n\n // decrease neighborhood with time\n this.scaleStepNeighborhood = scaleLinear()\n .clamp(true)\n .domain([0, maxStep])\n .range([maxNeighborhood, minNeighborhood]);\n\n // retrive min and max for each feature\n const unnormalizedExtents = _.flow(\n _.unzip,\n _.map(extent)\n )(data);\n\n // build scales for data normalization\n const scales = unnormalizedExtents.map(extent => scaleLinear()\n .domain(extent)\n .range([0, 1]));\n\n // build normalized data\n this.data = this.normalize(data, scales);\n\n // then we store means and deviations for normalized datas\n this.means = _.flow(\n _.unzip,\n _.map(mean)\n )(this.data);\n\n this.deviations = _.flow(\n _.unzip,\n _.map(deviation)\n )(this.data);\n\n // On each neuron, generate a random vector v\n // of <size> dimension\n const randomInitialVectors = this.generateInitialVectors();\n this.neurons = mapWithIndex(\n (neuron, i) => ({\n ...neuron,\n v: randomInitialVectors[i],\n }),\n neurons\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach to |aClient|'s tab whose title is |aTitle|; pass |aCallback| the response packet and a TabClient instance referring to that tab. | function attachTestTab(aClient, aTitle, aCallback) {
getTestTab(aClient, aTitle, function (aTab) {
aClient.attachTab(aTab.actor, aCallback);
});
} | [
"function attachTestTabAndResume(aClient, aTitle, aCallback) {\n attachTestThread(aClient, aTitle, function(aResponse, aTabClient, aThreadClient) {\n aThreadClient.resume(function (aResponse) {\n aCallback(aResponse, aTabClient, aThreadClient);\n });\n });\n}",
"function attachTestThread(aClient, aTitle, aCallback) {\n attachTestTab(aClient, aTitle, function (aTabResponse, aTabClient) {\n function onAttach(aResponse, aThreadClient) {\n aCallback(aResponse, aTabClient, aThreadClient, aTabResponse);\n }\n aTabClient.attachThread({\n useSourceMaps: true,\n autoBlackBox: true\n }, onAttach);\n });\n}",
"function getTestTab(aClient, aTitle, aCallback) {\n aClient.listTabs(function (aResponse) {\n for (let tab of aResponse.tabs) {\n if (tab.title === aTitle) {\n aCallback(tab);\n return;\n }\n }\n aCallback(null);\n });\n}",
"function AdminHeader_addTab( whichTab, link )\r\n{\r\n\tthis.tabs[ this.tabCount++ ] = new AdminHeaderTab( whichTab, link );\r\n}",
"function AdminHeader_addTab( whichTab, link )\n{\n\tthis.tabs[ this.tabCount++ ] = new AdminHeaderTab( whichTab, link );\n}",
"function createTab(tabState/*:Object*/, callback/*:Function*/)/*:void*/ {\n var tabType/*:WorkAreaTabType*/ = this.getEntityTabTypeForTabState$6OYc(tabState);\n if (tabType) {\n\n if (AS3.is(tabType, com.coremedia.cms.editor.sdk.desktop.reusability.ReusableTabType)) {\n // If we have a ReusableTabType, the type decides itself whether a new tab needs to be created or\n // whether an existing tab will be reused. In the latter case, only the transformed ProxyTabState\n // is passed on.\n (AS3.as(tabType, com.coremedia.cms.editor.sdk.desktop.reusability.ReusableTabType)).transformTabState(tabState, function (transformedState/*:Object*/, tab/*:Panel*/)/*:void*/ {\n callback(tab ? tab : transformedState);\n });\n } else {\n // Otherwise --> create new tab.\n tabType.createTab(tabState, function(tab/*:Panel*/)/*:void*/ {\n callback(tab);\n });\n }\n }\n else {\n //empty callback\n callback();\n }\n }",
"function registerTab(name, selectionCallback, initCallback) {\n tabs[name] = {\n select:selectionCallback,\n init:initCallback\n };\n }",
"function _jsTabControl_addTab(text, url) {\n\t//add the tab in a numeric slot\n\tthis.tabs[this.tabs.length] = new jsTab(text, url);\n\t\n\t//add the tab in a key-based slot\n\tthis.tabs[text] = this.tabs[this.tabs.length-1];\n\t\n\t//set the id\n\tthis.tabs[this.tabs.length - 1].id = this.tabs.length - 1;\n}",
"_onTabActivateRequested(sender, args) {\n args.title.owner.activate();\n }",
"function TabWatcher () {\n\t\tthis.add = function (id, url, callback) {\n\t\t\temit(callback, null);\n\t\t};\n\t}",
"function hookAddTabEvents(onTabEnqueFunc) {\n return function addTabClickHandler(e) {\n\n var query = {active: true, currentWindow: true};\n function addTab(tabs) {\n var currentTab = tabs[0]; // there will be only one in this array\n chrome.tabs.sendMessage(currentTab.id, {method: 'addTabManually'}, function (response) {\n onTabEnqueFunc();\n });\n }\n chrome.tabs.query(query, addTab);\n }\n}",
"function clientCreated(title) {\n iziToast.show({\n color: '#5F9EA0',\n icon: 'ico-check',\n titleColor: '#FFFFFF',\n iconColor: '#000000',\n title: title,\n position: 'topCenter',\n timeout: 2000,\n progressBar: false,\n });\n}",
"function set_tab_title (uuid, f_name) {\n\t\tvar info = {\n\t\t\tuuid : uuid,\n\t\t\ttitle : f_name\n\t\t};\n\t\ttoolbar.update_title(info);\n\n\t\tf_handle_cached.send_info ('*', 'title-change', info, 0);\n\t}",
"function processTabs(tabs, callback) {\n\n var tab = tabs[0];\n var url = tab.url;\n console.assert(typeof url == 'string', 'tab.url should be a string');\n\n var otherArguments = Array.prototype.slice.call(arguments, 2)\n otherArguments.unshift(url);\n callback.apply(null, otherArguments);\n}",
"function openTab(which,title){\n\n\t\t\tvar filename = which;\n\n\t\t\tapiMatch = new RegExp('/');\n\t\t\tif (filename.match(apiMatch)){\n\t\t\t\tfilename = which;\n\t\t\t} else {\n\t\t\t\tfilename = which.replace(\" \",\"_\").toLowerCase() + \".html\";\n\t\t\t}\n\n\t\t\tvar tabs = Ext.getCmp(\"tabPanel\");\n\t\t\tif (tabs.items.length==0){\n\t\t\t\t$('.introtext').hide();\n\t\t\t\t$('#tabs').fadeIn();\n\t\t\t}\n\n\n\t\t\tvar haveTabAlready=0;\n\t\t\tfor (tabId in tabs.items.keys){\n\t\t\t\tlogMessage(tabId,tabs.items.keys[tabId]);\n\t\t\t\tif (tabs.items.keys[tabId]==title){\n\t\t\t\t\thaveTabAlready=true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!haveTabAlready){\n\t\t\t\ttabs.add({\n\t\t\t\t\t closable: true,\n\t\t\t\t\t html: '<div id=\"info_' + title + '\"><div style=\"width:100%; text-align:center;\">Loading data for api:' + which + ' <br/><img style=\"margin:20px auto;\" src=\"images/spinner.gif\" /></div></div>',\n\t\t\t\t\t autoLoad:{url:filename},\n\t\t\t\t\t iconCls: 'tabs',\n\t\t\t\t\t id: title,\n\t\t\t\t\t title:title,\n\t\t\t\t\t name: title\n\t\t\t\t\t\t}\n\t\t\t\t).show();\n\t\t\t} else {\n\t\t\t\ttabs.setActiveTab(title);\n\t\t\t}\n}",
"function createTestTab(domain, callback) {\n var createdTabId = -1;\n var done = listenForever(\n chrome.tabs.onUpdated,\n function(tabId, changeInfo, tab) {\n if (tabId == createdTabId && changeInfo.status != 'loading') {\n callback(tab);\n done();\n }\n });\n\n chrome.tabs.create({url: testUrl(domain)}, pass(function(tab) {\n createdTabId = tab.id;\n }));\n}",
"function CreateLinkedInCompanyDtoNewTabAndListener_callback(tabId, changeInfo, tabInfo) {\n if (tabId === disposableTabId && changeInfo.status === \"complete\") {\n chrome.tabs.sendMessage(disposableTabId, { text: \"msgGetLinkedInCompanyDto\" }, POST_LinkedInCompanyDtoNewTabResponse);\n }\n}",
"function CreateLinkedInCompanyDtoNewTabAndListener(json) {\n chrome.tabs.create({ active: false, url: \"https://linkedin.com/company/\" + json.LinkedInCompanyId }, function (tab) {\n disposableTabId = tab.id;\n chrome.tabs.onUpdated.addListener(CreateLinkedInCompanyDtoNewTabAndListener_callback);\n });\n}",
"onLinkTapped() {\n ChromeGA.event(ChromeGA.EVENT.LINK, this.name);\n chrome.tabs.create({ url: this.url });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ageOneYear should add one to the `age` property of `obj` | function ageOneYear (obj) {
obj.age += 1
return obj
} | [
"function ageOneYear (obj) {\n obj.age++\n}",
"yearPasses() {\n return this.age + 1;\n }",
"function increaseYearByOne(book){\n book.year+=1;\n}",
"age(year){\n const y = new Date().getFullYear();\n if(year<y||year>2200){\n console.log(`Enter a valid year to return person's age`);\n }else{\n age = (year-y)+this._age;\n return age;\n }\n }",
"calculateYear() {\n let age = this.age.value;\n if (isNaN(age)) {\n return;\n }\n\n let today = new Date();\n let year = today.getFullYear() - age;\n\n let month = this.birthMonth.value;\n if (month != \"\") {\n month--; // Date object months are 0-indexed.\n let day = this.birthDay.value;\n if (\n month > today.getMonth() ||\n (month == today.getMonth() && day > today.getDate())\n ) {\n year--;\n }\n }\n this.birthYear.value = year;\n this.setDisabledMonthDays();\n }",
"function calculateAge(personName){\n var currentYear = 2018;\n return currentYear - personName.birthYear; \n}",
"ageInYears() {\n let currentYear = new Date().getFullYear();\n return currentYear - this.birthYear() - 1;\n }",
"incrementCurrentYear() {\n this.currentYear += 1;\n }",
"function addYears(date, numYears)\r\n{\r\n var newDate = date.clone();\r\n \r\n newDate.addYears( numYears );\r\n return newDate;\r\n}",
"function CalculateYear(birthYear, thisYear) {\n return thisYear - birthYear;\n}",
"function incrementCurrentYear() { currentYear++; }",
"_calculAge() {\n const today = new Date();\n this.age = today.getFullYear() - this.birthDate.getFullYear();\n }",
"function ageUp(person) {\n person.age++;\n console.log(person.age);\n}",
"celebrateBirthday() {\n this.age++;\n }",
"function get_double_age(obj) {\n return obj.age * 2;\n}",
"function celebrateBirthday() {\n this.age++;\n}",
"addAt(year, val){\n\t\tif(year < 2000 || year > 2050)\n\t\t\tthrow \"year must be in [2000:2050]\";\n\t\tthis.years[year - 2000] += val;\n\t}",
"function calculateAge() {\n var age = new Date().getYear() - new Date($scope.doctors.dob).getYear();\n $scope.doctors.age = age;\n }",
"function validate_age_yob(age, yob, status) {\n var year = new Date().getFullYear();\n var sum = parseInt(age) + parseInt(yob);\n\n if (status == 1) {\n // deceased\n return year >= sum;\n }\n\n return Math.abs(year - sum) <= 1 && year >= sum;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update map based styling. Map based styling could be anything which contains more than one binding. For example `string`, or object literal. Dealing with all of these types would complicate the logic so instead this function expects that the complex input is first converted into normalized `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it very cheap to compute deltas between the previous and current value. | function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
if (oldKeyValueArray === NO_CHANGE) {
// On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
oldKeyValueArray = EMPTY_ARRAY$3;
}
var oldIndex = 0;
var newIndex = 0;
var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
while (oldKey !== null || newKey !== null) {
ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
var setKey = null;
var setValue = undefined;
if (oldKey === newKey) {
// UPDATE: Keys are equal => new value is overwriting old value.
oldIndex += 2;
newIndex += 2;
if (oldValue !== newValue) {
setKey = newKey;
setValue = newValue;
}
} else if (newKey === null || oldKey !== null && oldKey < newKey) {
// DELETE: oldKey key is missing or we did not find the oldKey in the newValue
// (because the keyValueArray is sorted and `newKey` is found later alphabetically).
// `"background" < "color"` so we need to delete `"background"` because it is not found in the
// new array.
oldIndex += 2;
setKey = oldKey;
} else {
// CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
// `"color" > "background"` so we need to add `color` because it is in new array but not in
// old array.
ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
newIndex += 2;
setKey = newKey;
setValue = newValue;
}
if (setKey !== null) {
updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
}
oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
}
} | [
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY$3;\n }\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n }\n else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n }\n else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n}",
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY$3;\n }\n\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n } else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n } else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n }",
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY$3;\n }\n\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n } else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n } else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n}",
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY;\n }\n\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n } else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n } else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n }",
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY;\n }\n\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n var newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n var newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n } else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n } else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n}",
"function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {\n if (oldKeyValueArray === NO_CHANGE) {\n // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.\n oldKeyValueArray = EMPTY_ARRAY;\n }\n let oldIndex = 0;\n let newIndex = 0;\n let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;\n let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;\n const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;\n let setKey = null;\n let setValue = undefined;\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n }\n else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue\n // (because the keyValueArray is sorted and `newKey` is found later alphabetically).\n // `\"background\" < \"color\"` so we need to delete `\"background\"` because it is not found in the\n // new array.\n oldIndex += 2;\n setKey = oldKey;\n }\n else {\n // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.\n // `\"color\" > \"background\"` so we need to add `color` because it is in new array but not in\n // old array.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;\n newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;\n }\n}",
"function updateStylingMap(tView, tNode, lView, renderer, oldArrayMap, newArrayMap, isClassBased, bindingIndex) {\n if (oldArrayMap === NO_CHANGE) {\n // ON first execution the oldArrayMap is NO_CHANGE => treat is as empty ArrayMap.\n oldArrayMap = EMPTY_ARRAY$3;\n }\n var oldIndex = 0;\n var newIndex = 0;\n var oldKey = 0 < oldArrayMap.length ? oldArrayMap[0] : null;\n var newKey = 0 < newArrayMap.length ? newArrayMap[0] : null;\n while (oldKey !== null || newKey !== null) {\n ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');\n ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');\n var oldValue = oldIndex < oldArrayMap.length ? oldArrayMap[oldIndex + 1] : undefined;\n var newValue = newIndex < newArrayMap.length ? newArrayMap[newIndex + 1] : undefined;\n var setKey = null;\n var setValue = undefined;\n if (oldKey === newKey) {\n // UPDATE: Keys are equal => new value is overwriting old value.\n oldIndex += 2;\n newIndex += 2;\n if (oldValue !== newValue) {\n setKey = newKey;\n setValue = newValue;\n }\n }\n else if (newKey === null || oldKey !== null && oldKey < newKey) {\n // DELETE: oldKey key is missing or we did not find the oldKey in the newValue.\n oldIndex += 2;\n setKey = oldKey;\n }\n else {\n // CREATE: newKey is less than oldKey (or no oldKey) => we have new key.\n ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');\n newIndex += 2;\n setKey = newKey;\n setValue = newValue;\n }\n if (setKey !== null) {\n updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);\n }\n oldKey = oldIndex < oldArrayMap.length ? oldArrayMap[oldIndex] : null;\n newKey = newIndex < newArrayMap.length ? newArrayMap[newIndex] : null;\n }\n}",
"function applyStyling(context, renderer, element, bindingData, bitMaskValue, applyStylingFn, sanitizer) {\n var bitMask = normalizeBitMaskValue(bitMaskValue);\n var stylingMapsSyncFn = getStylingMapsSyncFn();\n var mapsGuardMask = getGuardMask(context, 3 /* MapBindingsPosition */);\n var applyAllValues = (bitMask & mapsGuardMask) > 0;\n var mapsMode = applyAllValues ? 1 /* ApplyAllValues */ : 0 /* TraverseValues */;\n var i = getPropValuesStartPosition(context);\n while (i < context.length) {\n var valuesCount = getValuesCount(context, i);\n var guardMask = getGuardMask(context, i);\n if (bitMask & guardMask) {\n var valueApplied = false;\n var prop = getProp(context, i);\n var valuesCountUpToDefault = valuesCount - 1;\n var defaultValue = getBindingValue(context, i, valuesCountUpToDefault);\n // case 1: apply prop-based values\n // try to apply the binding values and see if a non-null\n // value gets set for the styling binding\n for (var j = 0; j < valuesCountUpToDefault; j++) {\n var bindingIndex = getBindingValue(context, i, j);\n var value = bindingData[bindingIndex];\n if (isStylingValueDefined(value)) {\n var finalValue = sanitizer && isSanitizationRequired(context, i) ?\n sanitizer(prop, value, 2 /* SanitizeOnly */) :\n value;\n applyStylingFn(renderer, element, prop, finalValue, bindingIndex);\n valueApplied = true;\n break;\n }\n }\n // case 2: apply map-based values\n // traverse through each map-based styling binding and update all values up to\n // the provided `prop` value. If the property was not applied in the loop above\n // then it will be attempted to be applied in the maps sync code below.\n if (stylingMapsSyncFn) {\n // determine whether or not to apply the target property or to skip it\n var mode = mapsMode | (valueApplied ? 4 /* SkipTargetProp */ :\n 2 /* ApplyTargetProp */);\n var valueAppliedWithinMap = stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mode, prop, defaultValue);\n valueApplied = valueApplied || valueAppliedWithinMap;\n }\n // case 3: apply the default value\n // if the value has not yet been applied then a truthy value does not exist in the\n // prop-based or map-based bindings code. If and when this happens, just apply the\n // default value (even if the default value is `null`).\n if (!valueApplied) {\n applyStylingFn(renderer, element, prop, defaultValue);\n }\n }\n i += 3 /* BindingsStartOffset */ + valuesCount;\n }\n // the map-based styling entries may have not applied all their\n // values. For this reason, one more call to the sync function\n // needs to be issued at the end.\n if (stylingMapsSyncFn) {\n stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mapsMode);\n }\n}",
"function updateStyleBinding(context, data, prop, bindingIndex, value, sanitizer, deferRegistration, forceUpdate) {\n var isMapBased = !prop;\n var index = isMapBased ? STYLING_INDEX_FOR_MAP_BINDING : currentStyleIndex++;\n var sanitizationRequired = isMapBased ?\n true :\n (sanitizer ? sanitizer(prop, null, 1 /* ValidateProperty */) : false);\n var updated = updateBindingData(context, data, index, prop, bindingIndex, value, deferRegistration, forceUpdate, sanitizationRequired);\n if (updated || forceUpdate) {\n stylesBitMask |= 1 << index;\n }\n}",
"function patchStylingMapIntoContext(context, directiveIndex, playerBuilderIndex, ctxStart, ctxEnd, props, values, cacheValue, entryIsClassBased) {\n var dirty = false;\n var cacheIndex = 1 /* ValuesStartPosition */ +\n directiveIndex * 4 /* Size */;\n // the cachedValues array is the registry of all multi style values (map values). Each\n // value is stored (cached) each time is updated.\n var cachedValues = context[entryIsClassBased ? 6 /* CachedMultiClasses */ : 7 /* CachedMultiStyles */];\n // this is the index in which this directive has ownership access to write to this\n // value (anything before is owned by a previous directive that is more important)\n var ownershipValuesStartIndex = cachedValues[cacheIndex + 1 /* PositionStartOffset */];\n var existingCachedValue = cachedValues[cacheIndex + 2 /* ValueOffset */];\n var existingCachedValueCount = cachedValues[cacheIndex + 3 /* ValueCountOffset */];\n var existingCachedValueIsDirty = cachedValues[cacheIndex + 0 /* DirtyFlagOffset */] === 1;\n // A shape change means the provided map value has either removed or added new properties\n // compared to what were in the last time. If a shape change occurs then it means that all\n // follow-up multi-styling entries are obsolete and will be examined again when CD runs\n // them. If a shape change has not occurred then there is no reason to check any other\n // directive values if their identity has not changed. If a previous directive set this\n // value as dirty (because its own shape changed) then this means that the object has been\n // offset to a different area in the context. Because its value has been offset then it\n // can't write to a region that it wrote to before (which may have been apart of another\n // directive) and therefore its shape changes too.\n var valuesEntryShapeChange = existingCachedValueIsDirty || ((!existingCachedValue && cacheValue) ? true : false);\n var totalUniqueValues = 0;\n var totalNewAllocatedSlots = 0;\n // this is a trick to avoid building {key:value} map where all the values\n // are `true` (this happens when a className string is provided instead of a\n // map as an input value to this styling algorithm)\n var applyAllProps = values === true;\n // STEP 1:\n // loop through the earlier directives and figure out if any properties here will be placed\n // in their area (this happens when the value is null because the earlier directive erased it).\n var ctxIndex = ctxStart;\n var totalRemainingProperties = props.length;\n while (ctxIndex < ownershipValuesStartIndex) {\n var currentProp = getProp(context, ctxIndex);\n if (totalRemainingProperties) {\n for (var i = 0; i < props.length; i++) {\n var mapProp = props[i];\n var normalizedProp = mapProp ? (entryIsClassBased ? mapProp : hyphenate(mapProp)) : null;\n if (normalizedProp && currentProp === normalizedProp) {\n var currentValue = getValue(context, ctxIndex);\n var currentDirectiveIndex = getDirectiveIndexFromEntry(context, ctxIndex);\n var value = applyAllProps ? true : values[normalizedProp];\n var currentFlag = getPointers(context, ctxIndex);\n if (hasValueChanged(currentFlag, currentValue, value) &&\n allowValueChange(currentValue, value, currentDirectiveIndex, directiveIndex)) {\n setValue(context, ctxIndex, value);\n setPlayerBuilderIndex(context, ctxIndex, playerBuilderIndex, directiveIndex);\n if (hasInitialValueChanged(context, currentFlag, value)) {\n setDirty(context, ctxIndex, true);\n dirty = true;\n }\n }\n props[i] = null;\n totalRemainingProperties--;\n break;\n }\n }\n }\n ctxIndex += 4 /* Size */;\n }\n // STEP 2:\n // apply the left over properties to the context in the correct order.\n if (totalRemainingProperties) {\n var sanitizer = entryIsClassBased ? null : getStyleSanitizer(context, directiveIndex);\n propertiesLoop: for (var i = 0; i < props.length; i++) {\n var mapProp = props[i];\n if (!mapProp) {\n // this is an early exit in case a value was already encountered above in the\n // previous loop (which means that the property was applied or rejected)\n continue;\n }\n var value = applyAllProps ? true : values[mapProp];\n var normalizedProp = entryIsClassBased ? mapProp : hyphenate(mapProp);\n var isInsideOwnershipArea = ctxIndex >= ownershipValuesStartIndex;\n for (var j = ctxIndex; j < ctxEnd; j += 4 /* Size */) {\n var distantCtxProp = getProp(context, j);\n if (distantCtxProp === normalizedProp) {\n var distantCtxDirectiveIndex = getDirectiveIndexFromEntry(context, j);\n var distantCtxPlayerBuilderIndex = getPlayerBuilderIndex(context, j);\n var distantCtxValue = getValue(context, j);\n var distantCtxFlag = getPointers(context, j);\n if (allowValueChange(distantCtxValue, value, distantCtxDirectiveIndex, directiveIndex)) {\n // even if the entry isn't updated (by value or directiveIndex) then\n // it should still be moved over to the correct spot in the array so\n // the iteration loop is tighter.\n if (isInsideOwnershipArea) {\n swapMultiContextEntries(context, ctxIndex, j);\n totalUniqueValues++;\n }\n if (hasValueChanged(distantCtxFlag, distantCtxValue, value)) {\n if (value === null || value === undefined && value !== distantCtxValue) {\n valuesEntryShapeChange = true;\n }\n setValue(context, ctxIndex, value);\n // SKIP IF INITIAL CHECK\n // If the former `value` is `null` then it means that an initial value\n // could be being rendered on screen. If that is the case then there is\n // no point in updating the value in case it matches. In other words if the\n // new value is the exact same as the previously rendered value (which\n // happens to be the initial value) then do nothing.\n if (distantCtxValue !== null ||\n hasInitialValueChanged(context, distantCtxFlag, value)) {\n setDirty(context, ctxIndex, true);\n dirty = true;\n }\n }\n if (distantCtxDirectiveIndex !== directiveIndex ||\n playerBuilderIndex !== distantCtxPlayerBuilderIndex) {\n setPlayerBuilderIndex(context, ctxIndex, playerBuilderIndex, directiveIndex);\n }\n }\n ctxIndex += 4 /* Size */;\n continue propertiesLoop;\n }\n }\n // fallback case ... value not found at all in the context\n if (value != null) {\n valuesEntryShapeChange = true;\n totalUniqueValues++;\n var flag = prepareInitialFlag(context, normalizedProp, entryIsClassBased, sanitizer) |\n 1 /* Dirty */;\n var insertionIndex = isInsideOwnershipArea ?\n ctxIndex :\n (ownershipValuesStartIndex + totalNewAllocatedSlots * 4 /* Size */);\n insertNewMultiProperty(context, insertionIndex, entryIsClassBased, normalizedProp, flag, value, directiveIndex, playerBuilderIndex);\n totalNewAllocatedSlots++;\n ctxEnd += 4 /* Size */;\n ctxIndex += 4 /* Size */;\n dirty = true;\n }\n }\n }\n // STEP 3:\n // Remove (nullify) any existing entries in the context that were not apart of the\n // map input value that was passed into this algorithm for this directive.\n while (ctxIndex < ctxEnd) {\n valuesEntryShapeChange = true; // some values are missing\n var ctxValue = getValue(context, ctxIndex);\n var ctxFlag = getPointers(context, ctxIndex);\n var ctxDirective = getDirectiveIndexFromEntry(context, ctxIndex);\n if (ctxValue != null) {\n valuesEntryShapeChange = true;\n }\n if (hasValueChanged(ctxFlag, ctxValue, null)) {\n setValue(context, ctxIndex, null);\n // only if the initial value is falsy then\n if (hasInitialValueChanged(context, ctxFlag, ctxValue)) {\n setDirty(context, ctxIndex, true);\n dirty = true;\n }\n setPlayerBuilderIndex(context, ctxIndex, playerBuilderIndex, directiveIndex);\n }\n ctxIndex += 4 /* Size */;\n }\n // Because the object shape has changed, this means that all follow-up directives will need to\n // reapply their values into the object. For this to happen, the cached array needs to be updated\n // with dirty flags so that follow-up calls to `updateStylingMap` will reapply their styling code.\n // the reapplication of styling code within the context will reshape it and update the offset\n // values (also follow-up directives can write new values in case earlier directives set anything\n // to null due to removals or falsy values).\n valuesEntryShapeChange = valuesEntryShapeChange || existingCachedValueCount !== totalUniqueValues;\n updateCachedMapValue(context, directiveIndex, entryIsClassBased, cacheValue, ownershipValuesStartIndex, ctxEnd, totalUniqueValues, valuesEntryShapeChange);\n if (dirty) {\n setContextDirty(context, true);\n }\n return totalNewAllocatedSlots;\n}",
"function styleArrayMapSet(arrayMap, key, value) {\n if (stylePropNeedsSanitization(key)) {\n value = ɵɵsanitizeStyle(value);\n }\n arrayMapSet(arrayMap, key, value);\n}",
"function applyStyling(context, renderer, element, bindingData, bitMaskValue, applyStylingFn, sanitizer) {\n deferredBindingQueue.length && flushDeferredBindings();\n var bitMask = normalizeBitMaskValue(bitMaskValue);\n var stylingMapsSyncFn = getStylingMapsSyncFn();\n var mapsGuardMask = getGuardMask(context, 2 /* MapBindingsPosition */);\n var applyAllValues = (bitMask & mapsGuardMask) > 0;\n var mapsMode = applyAllValues ? 1 /* ApplyAllValues */ : 0 /* TraverseValues */;\n var i = getPropValuesStartPosition(context);\n while (i < context.length) {\n var valuesCount = getValuesCount(context, i);\n var guardMask = getGuardMask(context, i);\n if (bitMask & guardMask) {\n var valueApplied = false;\n var prop = getProp$1(context, i);\n var valuesCountUpToDefault = valuesCount - 1;\n var defaultValue = getBindingValue(context, i, valuesCountUpToDefault);\n // case 1: apply prop-based values\n // try to apply the binding values and see if a non-null\n // value gets set for the styling binding\n for (var j = 0; j < valuesCountUpToDefault; j++) {\n var bindingIndex = getBindingValue(context, i, j);\n var value = bindingData[bindingIndex];\n if (isStylingValueDefined(value)) {\n var finalValue = sanitizer && isSanitizationRequired(context, i) ?\n sanitizer(prop, value, 2 /* SanitizeOnly */) :\n value;\n applyStylingFn(renderer, element, prop, finalValue, bindingIndex);\n valueApplied = true;\n break;\n }\n }\n // case 2: apply map-based values\n // traverse through each map-based styling binding and update all values up to\n // the provided `prop` value. If the property was not applied in the loop above\n // then it will be attempted to be applied in the maps sync code below.\n if (stylingMapsSyncFn) {\n // determine whether or not to apply the target property or to skip it\n var mode = mapsMode | (valueApplied ? 4 /* SkipTargetProp */ :\n 2 /* ApplyTargetProp */);\n var valueAppliedWithinMap = stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mode, prop, defaultValue);\n valueApplied = valueApplied || valueAppliedWithinMap;\n }\n // case 3: apply the default value\n // if the value has not yet been applied then a truthy value does not exist in the\n // prop-based or map-based bindings code. If and when this happens, just apply the\n // default value (even if the default value is `null`).\n if (!valueApplied) {\n applyStylingFn(renderer, element, prop, defaultValue);\n }\n }\n i += 3 /* BindingsStartOffset */ + valuesCount;\n }\n // the map-based styling entries may have not applied all their\n // values. For this reason, one more call to the sync function\n // needs to be issued at the end.\n if (stylingMapsSyncFn) {\n stylingMapsSyncFn(context, renderer, element, bindingData, applyStylingFn, sanitizer, mapsMode);\n }\n}",
"function _stylingMap(elementIndex, context, bindingIndex, value, isClassBased, defer) {\n activateStylingMapFeature();\n var lView = getLView();\n var valueHasChanged = false;\n if (value !== NO_CHANGE) {\n var tNode = getTNode(elementIndex, lView);\n var native = getNativeByTNode(tNode, lView);\n var oldValue = lView[bindingIndex];\n valueHasChanged = hasValueChanged(oldValue, value);\n var stylingMapArr = normalizeIntoStylingMap(oldValue, value, !isClassBased);\n if (isClassBased) {\n updateClassBinding(context, lView, native, null, bindingIndex, stylingMapArr, defer, valueHasChanged);\n }\n else {\n var sanitizer = getCurrentStyleSanitizer();\n updateStyleBinding(context, lView, native, null, bindingIndex, stylingMapArr, sanitizer, defer, valueHasChanged);\n }\n }\n return valueHasChanged;\n}",
"function patchInitialStylingValue(initialStyling, prop, value) {\n // Even values are keys; Odd numbers are values; Search keys only\n for (var i = 1 /* KeyValueStartPosition */; i < initialStyling.length;) {\n var key = initialStyling[i];\n if (key === prop) {\n var existingValue = initialStyling[i + 1 /* ValueOffset */];\n // If there is no previous style value (when `null`) or no previous class\n // applied (when `false`) then we update the the newly given value.\n if (existingValue == null || existingValue == false) {\n initialStyling[i + 1 /* ValueOffset */] = value;\n }\n return;\n }\n i = i + 2 /* Size */;\n }\n // We did not find existing key, add a new one.\n initialStyling.push(prop, value);\n}",
"function styleKeyValueArraySet(keyValueArray, key, value) {\n if (stylePropNeedsSanitization(key)) {\n value = ɵɵsanitizeStyle(value);\n }\n keyValueArraySet(keyValueArray, key, value);\n}",
"function innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, mode, targetProp, currentMapIndex, defaultValue) {\n var targetPropValueWasApplied = false;\n var totalMaps = getValuesCount(context, 3 /* MapBindingsPosition */);\n if (currentMapIndex < totalMaps) {\n var bindingIndex = getBindingValue(context, 3 /* MapBindingsPosition */, currentMapIndex);\n var stylingMapArr = data[bindingIndex];\n var cursor = getCurrentSyncCursor(currentMapIndex);\n while (cursor < stylingMapArr.length) {\n var prop = getMapProp(stylingMapArr, cursor);\n var iteratedTooFar = targetProp && prop > targetProp;\n var isTargetPropMatched = !iteratedTooFar && prop === targetProp;\n var value = getMapValue(stylingMapArr, cursor);\n var valueIsDefined = isStylingValueDefined(value);\n // the recursive code is designed to keep applying until\n // it reaches or goes past the target prop. If and when\n // this happens then it will stop processing values, but\n // all other map values must also catch up to the same\n // point. This is why a recursive call is still issued\n // even if the code has iterated too far.\n var innerMode = iteratedTooFar ? mode : resolveInnerMapMode(mode, valueIsDefined, isTargetPropMatched);\n var innerProp = iteratedTooFar ? targetProp : prop;\n var valueApplied = innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, innerMode, innerProp, currentMapIndex + 1, defaultValue);\n if (iteratedTooFar) {\n if (!targetPropValueWasApplied) {\n targetPropValueWasApplied = valueApplied;\n }\n break;\n }\n if (!valueApplied && isValueAllowedToBeApplied(mode, isTargetPropMatched)) {\n var useDefault = isTargetPropMatched && !valueIsDefined;\n var valueToApply = useDefault ? defaultValue : value;\n var bindingIndexToApply = useDefault ? bindingIndex : null;\n var finalValue = sanitizer ?\n sanitizer(prop, valueToApply, 3 /* ValidateAndSanitize */) :\n valueToApply;\n applyStylingFn(renderer, element, prop, finalValue, bindingIndexToApply);\n valueApplied = true;\n }\n targetPropValueWasApplied = valueApplied && isTargetPropMatched;\n cursor += 2 /* TupleSize */;\n }\n setCurrentSyncCursor(currentMapIndex, cursor);\n // this is a fallback case in the event that the styling map is `null` for this\n // binding but there are other map-based bindings that need to be evaluated\n // afterwards. If the `prop` value is falsy then the intention is to cycle\n // through all of the properties in the remaining maps as well. If the current\n // styling map is too short then there are no values to iterate over. In either\n // case the follow-up maps need to be iterated over.\n if (stylingMapArr.length === 1 /* ValuesStartPosition */ || !targetProp) {\n return innerSyncStylingMap(context, renderer, element, data, applyStylingFn, sanitizer, mode, targetProp, currentMapIndex + 1, defaultValue);\n }\n }\n return targetPropValueWasApplied;\n}",
"updateMapStyle(nextPropsMapStyle) {\n\n // if the mapStyles prop (passed in from redux) is null/empty, nothing\n // to do here\n if (this.props.mapStyle === null || isEmpty(this.props.mapStyle)) {\n return\n };\n\n const thisMap = this.webmap;\n\n // uses the stylesheets read into Immutable objects for the comparison\n\n // 'oldStyle' is what we have in redux\n const oldStyle = Immutable.fromJS(this.props.mapStyle);\n\n // newStyle is what we've just received\n const newStyle = Immutable.fromJS(nextPropsMapStyle);\n\n // diffstyles crosswalks the difference in mapStyle to the types\n // of mapboxGL map methods that would need to be executed to make the change.\n if (!Immutable.is(oldStyle, newStyle)) {\n // console.log(\"changes detected between old and new style\")\n let changes = diffStyles(oldStyle.toJS(), newStyle.toJS());\n if (DEBUG) { console.log(`updating mapStyle (${changes.map(c => c.command)})`) }\n\n // if changes are detected, then we apply each one to the map\n // this executes map methods to do things like pan, zoom, change layer\n // visibility and filters, and CRUD data sources\n\n changes.forEach((change) => {\n\n // NOTE: this is a workaround for the setGeoJSONSourceData command,\n // which was throwing an error when called. We simply do what it otherwise\n // would have done to the style via the map's method.\n if (change.command == \"setGeoJSONSourceData\") {\n // thisMap.setGeoJSONSourceData.apply(thisMap, change.args)\n // console.log(change.args)\n let src = thisMap.getSource(change.args[0])\n // console.log(src)\n if (src) {\n src.setData(change.args[1])\n }\n } else {\n // console.log(thisMap)\n // console.log(thisMap[change.command])\n thisMap[change.command].apply(thisMap, change.args);\n }\n });\n }\n }",
"function renderStylingMap(renderer, element, stylingValues, isClassBased) {\n var stylingMapArr = getStylingMapArray(stylingValues);\n if (stylingMapArr) {\n for (var i = 1 /* ValuesStartPosition */; i < stylingMapArr.length; i += 2 /* TupleSize */) {\n var prop = getMapProp(stylingMapArr, i);\n var value = getMapValue(stylingMapArr, i);\n if (isClassBased) {\n setClass(renderer, element, prop, value, null);\n }\n else {\n setStyle(renderer, element, prop, value, null);\n }\n }\n }\n}",
"function updateStyleProp(context, index, value) {\n var singleIndex = 6 /* SingleStylesStartPosition */ + index * 3 /* Size */;\n var currValue = getValue(context, singleIndex);\n var currFlag = getPointers(context, singleIndex);\n // didn't change ... nothing to make a note of\n if (hasValueChanged(currFlag, currValue, value)) {\n // the value will always get updated (even if the dirty flag is skipped)\n setValue(context, singleIndex, value);\n var indexForMulti = getMultiOrSingleIndex(currFlag);\n // if the value is the same in the multi-area then there's no point in re-assembling\n var valueForMulti = getValue(context, indexForMulti);\n if (!valueForMulti || valueForMulti !== value) {\n var multiDirty = false;\n var singleDirty = true;\n var isClassBased_5 = (currFlag & 2 /* Class */) === 2 /* Class */;\n // only when the value is set to `null` should the multi-value get flagged\n if (!valueExists(value, isClassBased_5) && valueExists(valueForMulti, isClassBased_5)) {\n multiDirty = true;\n singleDirty = false;\n }\n setDirty(context, indexForMulti, multiDirty);\n setDirty(context, singleIndex, singleDirty);\n setContextDirty(context, true);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET /statuses/public Retrieve a list of all existing statuses. [Learn more on Dev Center]( `options` An object containing the search params. [See accepted params]( `callback` The callback function returning the results. An error object is passed as first argument and the result as last. | function public(options, callback) {
core.api('GET', '/statuses/public', options, callback);
} | [
"function all(options, callback) {\n core.api('GET', '/statuses', options, callback);\n }",
"function twitterSearch() {\n var client = new Twitter(keys.twitter);\n var params = { screen_name: 'HwNode' };\n client.get('statuses/user_timeline', params, function (error, tweets, response) {\n if (!error) {\n tweetLogger(tweets)\n }\n else {\n console.log(error);\n }\n });\n}",
"function find(id, callback) {\n core.api('GET', '/statuses/' + id, {}, callback);\n }",
"function myTweets() {\n client.get('search/tweets', params, gotData);\n\n function gotData(error, data, response) {\n var tweets = data.statuses;\n for (var i = 0; i < tweets.length; i++) {\n if (error) {\n twittPrint(error);\n } else {\n answersPrint(tweets[i].created_at);\n answersPrint(tweets[i].text);\n }\n }\n }\n}",
"function getTweets() {\n // Variable - request.params()\n var params = {\n screen_name: 'okayitsofficial'\n };\n\n // Get - Twitter API\n twitter.get('statuses/user_timeline', params, function (error, tweets, repsonse) {\n // If - no errors\n if (!error) {\n logData(hal + 'Here are your most recent tweets.', 'red');\n logData('');\n for (var i = 0; i < tweets.length; i++) {\n logData('Tweeted on ' + tweets[i].created_at, 'blue');\n logData(' \"' + tweets[i].text + '\"', 'white');\n logData('');\n }\n } else {\n console.log(error);\n }\n });\n}",
"function search(){\n var params = {\n q: 'Taylor Swift',\n count: '20'\n }\n\n T.get('search/tweets', params, gotData);\n function gotData(err, data, response){\n var tweets = data.statuses;\n for (var i = 0; i < tweets.length; i++){\n console.log(tweets[i].text)\n }\n };\n}",
"function myTweets(){\n var params = {screen_name: 'tomkim825'};\n client.get('statuses/user_timeline', params, function(error, tweets, response) {\n if (!error) {\n addLog('20 recent tweets from @'+params.screen_name+': \\n');\n for(var i=0; i<20; i++){\n addLog('('+tweets[i].created_at.slice(0,16)+') '+tweets[i].text);\n };\n additionalCommand();\n } else { console.log(error) }\n});\n}",
"function twitterRequest() {\n\n var params = { screen_name: 'Reza03583634', count: 20 };\n client.get('statuses/user_timeline', params, function (error, tweets, response) {\n if (!error) {\n tweets.forEach(function (element) {\n console.log(element.text);\n });\n }\n });\n}",
"function pullTweet() {\n\tclient.get('statuses/user_timeline', params, function(error, tweets, response) {\n\t\tif (!error) {\n \t\tfor (var i = 0; i < tweets.length; i++) {\n \tconsole.log(tweets[i].text);\t\n \t\t }\n \t\t} else {\n \t\t\tconsole.log(error);\n \t\t};\n\t});\n}",
"function printTweets(error, data, response) {\n if(data != null){\n const tweets = data.statuses;\n for (let i=0; i<tweets.length; i++){\n console.log(tweets[i].text);\n }\n } else {\n console.log('No tweet is retrieved');\n }\n}",
"function get_tweets(params,callback) {\n\t\t// just in case someone only wants to send a callback\n\t\tif (typeof(params)=='function' && typeof(callback)=='undefined') {\n\t\t\tcallback = params;\n\t\t\tparams = '';\n\t\t}\n\n\t\tapi(\"https://api.twitter.com/1/statuses/friends_timeline.json\",\"GET\",params,function(tweets){\n\t\t\ttry {\n\t\t\t\tTi.API.info('fn-get_tweets: WE GOT TWEETS!');\n\t\t\t\ttweets = JSON.parse(tweets);\n\t\t\t} catch (e) {\n\t\t\t\tTi.API.info('fn-get_tweets: api returned a non-JSON string');\n\t\t\t\ttweets = false;\n\t\t\t}\n\n\t\t\t// execute the callback function\n\t\t\tif(typeof(callback)=='function'){\n\t\t\t\tcallback(tweets);\n\t\t\t}\n\n\t\t\treturn tweets;\n\t\t})\n\t}",
"function myTweets () {\n var params = {screen_name: 'ChrisFalk16', count: tweetLimit};\n twitterKey.get('statuses/user_timeline', params, function(error, tweets, response) {\n if (error) {\n console.log(error);\n }\n else if (!error) {\n console.log(\"\\nThese are your last \" + (tweets.length) + \" tweets: \\n\");\n for (var i = 0; i < tweets.length; i++) {\n console.log(\"Tweet # \" + (i+1) + \": \" + \"\\n\" + tweets[i].text +\n \"\\n\" + \"Created on: \" + tweets[i].created_at);\n console.log(\"--------------------\");\n }\n }\n });\n}",
"function myTweets() {\n\t\tclient.get(\"search/tweets\", {q: \"NASA\", count: 6}, function(error, data, response) {\n \t\t\tvar tweets = data.statuses;\n \t\t\tconsole.log(\"\");\n \t\t\tfor (var i = 0; i < tweets.length; i++) {\n \t\t\t\tconsole.log((i+1) + \". \" + tweets[i].text);\n \t\t\t}\n\t\t});\n\t}",
"function myTweets() {\n // sets screen_name to fix value.\n var params = {\n screen_name: 'poornima_sewak'\n };\n // Client get method send the user's tweets request and recieve the tweets in a call back function.\n client.get('statuses/user_timeline', params, function(error, tweets, response) {\n // if there is an error then throw an exception.\n if (error) throw error;\n console.log(tweets);\n // Loop through to get top 20 tweets.\n for (var i = 0; i < 20; i++) {\n var k = i + 1;\n console.log(k + \". Tweets : \" + tweets[i].text + \"\\n\" + k + \". Created at : \" + tweets[i].created_at);\n }\n });\n}",
"function myTweets() {\n\tclient.get(\"statuses/user_timeline\", params, function(error,tweets,response){\n\t\tif (!error){\n\n\t\t\tconsole.log(\"Last 20 tweets\");\n\t\t\tfor (i=0; i < tweets.length; i++) {\n\t\t\t\tvar number = i + 1;\n\t\t\t\tconsole.log(\" \");\n\t\t\t\tconsole.log([i + 1] + \".\" + tweets[i].text);\n\t\t\t\tconsole.log(\"Created on \" + tweets[i].created_at);\n\t\t\t}\n\t\t}\n\t});\n}",
"function getStatusesForAccount(username) {\n console.log(`Grabbing statuses for ${username}`);\n\n client.get('statuses/user_timeline', {\n screen_name: username,\n exclude_replies: !INCLUDE_MENTIONS,\n include_rts: INCLUDE_RTS,\n exclude_replies: EXCLUDE_REPLIES,\n exclude_retweets: EXCLUDE_RETWEETS,\n exclude_mentions: EXCLUDE_MENTIONS,\n count: 10,\n since_id: MOST_RECENT_TWEET_ID\n }, (err, tweets, response) => {\n if (err) return console.log(err);\n processStatuses(tweets)\n });\n}",
"function twitterCall() {\n\tclient.get('search/tweets', { q: 'jbs_twitbot', count: 20 }, function (error, tweets, response) {\n\t\tif (!error) {\n\t\t\tconsole.log(\"\\n-------------------\")\n\t\t\tconsole.log(\"\\n Now searching Twitter user @jbs_twitbot ! \\n]\")\n\t\t\tfor (var i = 0; i < 20; i++) {\n\t\t\t\tconsole.log(\"\\n-------------------\")\n\t\t\t\tconsole.log(\"Tweet #\" + (i + 1))\n\t\t\t\tconsole.log(tweets.statuses[i].text)\n\t\t\t\tconsole.log(\"Time Tweet Created:\" + tweets.statuses[i].created_at)\n\t\t\t}\n\t\t\treturn console.log(\"Twitter Feed complete!\")\n\t\t}\n\t\tconsole.log(\"There was an error, please try again!\")\n\t})\n}",
"function getTweets() {\n\t\t//accessing twitter keys\n\t\tvar client = new Twitter(keys.twitterKeys);\n\t\t\n\t\t//retrieving tweets \n\t\tvar params = {screen_name: 'twicklvnv'};\n\t\tclient.get('statuses/user_timeline', params, function(error, tweets, response) {\n\t\t if (!error) {\n\t\t \t//loop through tweets and display wanted info for each tweet\n\t\t \tfor (var i = 0; i<tweets.length; i++) {\n\t\t \t\tconsole.log(tweets[i].created_at);\n\t\t \t\tconsole.log(tweets[i].text);\n\t\t \t\tconsole.log(\" \"); \n\t\t }\n\t\t}\n\t\t else {\n\t\t \tconsole.log(error);\n\t\t }\n\t\t\n\t});\n}",
"function tweetPull() {\r\n\tclient.get('statuses/user_timeline.json?screen_name=PaulPostsTweets&count=20', function(error, tweets, response) {\r\n\t\tif (error) {\r\n\t\t\tconsole.log(error);\r\n\t\t}\r\n\t\t// Prints the text property of each of tweets pulled:\r\n\t\tfor (var i = 0; i < tweets.length; i++) {\r\n\t\t\tconsole.log(tweets[i].text);\r\n\t\t}\r\n\t});\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put default plotTile layouts here | function cloneLayoutOverride(tileClass) {
var override;
switch (tileClass) {
case 'themes__thumb':
override = {
autosize: true,
width: 150,
height: 150,
title: {
text: ''
},
showlegend: false,
margin: {
l: 5,
r: 5,
t: 5,
b: 5,
pad: 0
},
annotations: []
};
break;
case 'thumbnail':
override = {
title: {
text: ''
},
hidesources: true,
showlegend: false,
borderwidth: 0,
bordercolor: '',
margin: {
l: 1,
r: 1,
t: 1,
b: 1,
pad: 0
},
annotations: []
};
break;
default:
override = {};
}
return override;
} | [
"layoutTiles() {\n this.generateTileSet();\n this.updateTiles();\n }",
"function layoutTiles() {\n var layout = scope.layout;\n\n if (layout) {\n if (singleColumnMode) {\n moveTilesToContainer(element, column1, layout.one_column_layout);\n } else {\n moveTilesToContainer(element, column1, layout.two_column_layout[0]);\n moveTilesToContainer(element, column2, layout.two_column_layout[1]);\n }\n }\n }",
"onLayout(/*layoutParamsGetter, tilePositionSetter*/) {\n }",
"layout() {\n const x = (0,d3_hierarchy__WEBPACK_IMPORTED_MODULE_14__.default)();\n\n x.ratio = _ => {\n const t = x.tile();\n if (t.ratio) x.tile(t.ratio(_));\n };\n\n x.method = _ => {\n if ((0,vega_util__WEBPACK_IMPORTED_MODULE_1__.hasOwnProperty)(Tiles, _)) x.tile(Tiles[_]);else (0,vega_util__WEBPACK_IMPORTED_MODULE_1__.error)('Unrecognized Treemap layout method: ' + _);\n };\n\n return x;\n }",
"defaultLayout() {\n WidgetModel.allAvailable.map(widget => {\n this.newWidget(widget, true)\n })\n }",
"function contentDefaults(layoutIn, layoutOut) {\n var gridOut = layoutOut.grid;\n // make sure we got to the end of handleGridSizing\n if(!gridOut || !gridOut._domains) return;\n\n var gridIn = layoutIn.grid || {};\n var subplots = layoutOut._subplots;\n var hasSubplotGrid = gridOut._hasSubplotGrid;\n var rows = gridOut.rows;\n var columns = gridOut.columns;\n var useDefaultSubplots = gridOut.pattern === 'independent';\n\n var i, j, xId, yId, subplotId, subplotsOut, yPos;\n\n var axisMap = gridOut._axisMap = {};\n\n if(hasSubplotGrid) {\n var subplotsIn = gridIn.subplots || [];\n subplotsOut = gridOut.subplots = new Array(rows);\n var index = 1;\n\n for(i = 0; i < rows; i++) {\n var rowOut = subplotsOut[i] = new Array(columns);\n var rowIn = subplotsIn[i] || [];\n for(j = 0; j < columns; j++) {\n if(useDefaultSubplots) {\n subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);\n index++;\n }\n else subplotId = rowIn[j];\n\n rowOut[j] = '';\n\n if(subplots.cartesian.indexOf(subplotId) !== -1) {\n yPos = subplotId.indexOf('y');\n xId = subplotId.slice(0, yPos);\n yId = subplotId.slice(yPos);\n if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||\n (axisMap[yId] !== undefined && axisMap[yId] !== i)\n ) {\n continue;\n }\n\n rowOut[j] = subplotId;\n axisMap[xId] = j;\n axisMap[yId] = i;\n }\n }\n }\n }\n else {\n var xAxes = getAxes(layoutOut, gridIn, 'x');\n var yAxes = getAxes(layoutOut, gridIn, 'y');\n gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');\n gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');\n }\n\n var anchors = gridOut._anchors = {};\n var reversed = gridOut.roworder === 'top to bottom';\n\n for(var axisId in axisMap) {\n var axLetter = axisId.charAt(0);\n var side = gridOut[axLetter + 'side'];\n\n var i0, inc, iFinal;\n\n if(side.length < 8) {\n // grid edge - ie not \"* plot\" - make these as free axes\n // since we're not guaranteed to have a subplot there at all\n anchors[axisId] = 'free';\n }\n else if(axLetter === 'x') {\n if((side.charAt(0) === 't') === reversed) {\n i0 = 0;\n inc = 1;\n iFinal = rows;\n }\n else {\n i0 = rows - 1;\n inc = -1;\n iFinal = -1;\n }\n if(hasSubplotGrid) {\n var column = axisMap[axisId];\n for(i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[i][column];\n if(!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if(subplotId.slice(0, yPos) === axisId) {\n anchors[axisId] = subplotId.slice(yPos);\n break;\n }\n }\n }\n else {\n for(i = i0; i !== iFinal; i += inc) {\n yId = gridOut.yaxes[i];\n if(subplots.cartesian.indexOf(axisId + yId) !== -1) {\n anchors[axisId] = yId;\n break;\n }\n }\n }\n }\n else {\n if((side.charAt(0) === 'l')) {\n i0 = 0;\n inc = 1;\n iFinal = columns;\n }\n else {\n i0 = columns - 1;\n inc = -1;\n iFinal = -1;\n }\n if(hasSubplotGrid) {\n var row = axisMap[axisId];\n for(i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[row][i];\n if(!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if(subplotId.slice(yPos) === axisId) {\n anchors[axisId] = subplotId.slice(0, yPos);\n break;\n }\n }\n }\n else {\n for(i = i0; i !== iFinal; i += inc) {\n xId = gridOut.xaxes[i];\n if(subplots.cartesian.indexOf(xId + axisId) !== -1) {\n anchors[axisId] = xId;\n break;\n }\n }\n }\n }\n }\n}",
"function contentDefaults(layoutIn, layoutOut) {\n var gridOut = layoutOut.grid;\n // make sure we got to the end of handleGridSizing\n if(!gridOut || !gridOut._domains) return;\n\n var gridIn = layoutIn.grid || {};\n var subplots = layoutOut._subplots;\n var hasSubplotGrid = gridOut._hasSubplotGrid;\n var rows = gridOut.rows;\n var columns = gridOut.columns;\n var useDefaultSubplots = gridOut.pattern === 'independent';\n\n var i, j, xId, yId, subplotId, subplotsOut, yPos;\n\n var axisMap = gridOut._axisMap = {};\n\n if(hasSubplotGrid) {\n var subplotsIn = gridIn.subplots || [];\n subplotsOut = gridOut.subplots = new Array(rows);\n var index = 1;\n\n for(i = 0; i < rows; i++) {\n var rowOut = subplotsOut[i] = new Array(columns);\n var rowIn = subplotsIn[i] || [];\n for(j = 0; j < columns; j++) {\n if(useDefaultSubplots) {\n subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);\n index++;\n } else subplotId = rowIn[j];\n\n rowOut[j] = '';\n\n if(subplots.cartesian.indexOf(subplotId) !== -1) {\n yPos = subplotId.indexOf('y');\n xId = subplotId.slice(0, yPos);\n yId = subplotId.slice(yPos);\n if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||\n (axisMap[yId] !== undefined && axisMap[yId] !== i)\n ) {\n continue;\n }\n\n rowOut[j] = subplotId;\n axisMap[xId] = j;\n axisMap[yId] = i;\n }\n }\n }\n } else {\n var xAxes = getAxes(layoutOut, gridIn, 'x');\n var yAxes = getAxes(layoutOut, gridIn, 'y');\n gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');\n gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');\n }\n\n var anchors = gridOut._anchors = {};\n var reversed = gridOut.roworder === 'top to bottom';\n\n for(var axisId in axisMap) {\n var axLetter = axisId.charAt(0);\n var side = gridOut[axLetter + 'side'];\n\n var i0, inc, iFinal;\n\n if(side.length < 8) {\n // grid edge - ie not \"* plot\" - make these as free axes\n // since we're not guaranteed to have a subplot there at all\n anchors[axisId] = 'free';\n } else if(axLetter === 'x') {\n if((side.charAt(0) === 't') === reversed) {\n i0 = 0;\n inc = 1;\n iFinal = rows;\n } else {\n i0 = rows - 1;\n inc = -1;\n iFinal = -1;\n }\n if(hasSubplotGrid) {\n var column = axisMap[axisId];\n for(i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[i][column];\n if(!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if(subplotId.slice(0, yPos) === axisId) {\n anchors[axisId] = subplotId.slice(yPos);\n break;\n }\n }\n } else {\n for(i = i0; i !== iFinal; i += inc) {\n yId = gridOut.yaxes[i];\n if(subplots.cartesian.indexOf(axisId + yId) !== -1) {\n anchors[axisId] = yId;\n break;\n }\n }\n }\n } else {\n if((side.charAt(0) === 'l')) {\n i0 = 0;\n inc = 1;\n iFinal = columns;\n } else {\n i0 = columns - 1;\n inc = -1;\n iFinal = -1;\n }\n if(hasSubplotGrid) {\n var row = axisMap[axisId];\n for(i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[row][i];\n if(!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if(subplotId.slice(yPos) === axisId) {\n anchors[axisId] = subplotId.slice(0, yPos);\n break;\n }\n }\n } else {\n for(i = i0; i !== iFinal; i += inc) {\n xId = gridOut.xaxes[i];\n if(subplots.cartesian.indexOf(xId + axisId) !== -1) {\n anchors[axisId] = xId;\n break;\n }\n }\n }\n }\n }\n}",
"function cloneLayoutOverride(tileClass) {\n var override;\n\n switch(tileClass) {\n case 'themes__thumb':\n override = {\n autosize: true,\n width: 150,\n height: 150,\n title: {text: ''},\n showlegend: false,\n margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},\n annotations: []\n };\n break;\n\n case 'thumbnail':\n override = {\n title: {text: ''},\n hidesources: true,\n showlegend: false,\n borderwidth: 0,\n bordercolor: '',\n margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},\n annotations: []\n };\n break;\n\n default:\n override = {};\n }\n\n\n return override;\n}",
"function plot_get_base_layout() {\n const layout = {\n font: { size: 16, },\n hovermode: 'x',\n showlegend: true,\n legend: {\n x: 0.0,\n xanchor: 'left',\n y: 1.01,\n yanchor: 'bottom',\n orientation: 'h',\n font: { size: 18, },\n },\n margin: {\n l: 60,\n r: 20,\n t: 5,\n b: 50,\n autoexpand: true,\n }\n };\n\n return layout;\n}",
"_layoutTiles() {\n if (!this._tileCoordinator) {\n this._tileCoordinator = new TileCoordinator();\n }\n const tracker = this._tileCoordinator;\n const tiles = this._tiles.filter(tile => !tile._gridList || tile._gridList === this);\n const direction = this._dir ? this._dir.value : 'ltr';\n this._tileCoordinator.update(this.cols, tiles);\n this._tileStyler.init(this.gutterSize, tracker, this.cols, direction);\n tiles.forEach((tile, index) => {\n const pos = tracker.positions[index];\n this._tileStyler.setStyle(tile, pos.row, pos.col);\n });\n this._setListStyle(this._tileStyler.getComputedHeight());\n }",
"layout() {\n const x = (0, _d3Hierarchy.treemap)();\n\n x.ratio = _ => {\n const t = x.tile();\n if (t.ratio) x.tile(t.ratio(_));\n };\n\n x.method = _ => {\n if ((0, _vegaUtil.hasOwnProperty)(Tiles, _)) x.tile(Tiles[_]);else (0, _vegaUtil.error)('Unrecognized Treemap layout method: ' + _);\n };\n\n return x;\n }",
"function contentDefaults(layoutIn, layoutOut) {\n var gridOut = layoutOut.grid;\n // make sure we got to the end of handleGridSizing\n if (!gridOut || !gridOut._domains) return;\n\n var gridIn = layoutIn.grid || {};\n var subplots = layoutOut._subplots;\n var hasSubplotGrid = gridOut._hasSubplotGrid;\n var rows = gridOut.rows;\n var columns = gridOut.columns;\n var useDefaultSubplots = gridOut.pattern === 'independent';\n\n var i, j, xId, yId, subplotId, subplotsOut, yPos;\n\n var axisMap = gridOut._axisMap = {};\n\n if (hasSubplotGrid) {\n var subplotsIn = gridIn.subplots || [];\n subplotsOut = gridOut.subplots = new Array(rows);\n var index = 1;\n\n for (i = 0; i < rows; i++) {\n var rowOut = subplotsOut[i] = new Array(columns);\n var rowIn = subplotsIn[i] || [];\n for (j = 0; j < columns; j++) {\n if (useDefaultSubplots) {\n subplotId = index === 1 ? 'xy' : 'x' + index + 'y' + index;\n index++;\n } else subplotId = rowIn[j];\n\n rowOut[j] = '';\n\n if (subplots.cartesian.indexOf(subplotId) !== -1) {\n yPos = subplotId.indexOf('y');\n xId = subplotId.slice(0, yPos);\n yId = subplotId.slice(yPos);\n if (axisMap[xId] !== undefined && axisMap[xId] !== j || axisMap[yId] !== undefined && axisMap[yId] !== i) {\n continue;\n }\n\n rowOut[j] = subplotId;\n axisMap[xId] = j;\n axisMap[yId] = i;\n }\n }\n }\n } else {\n var xAxes = getAxes(layoutOut, gridIn, 'x');\n var yAxes = getAxes(layoutOut, gridIn, 'y');\n gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');\n gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');\n }\n\n var anchors = gridOut._anchors = {};\n var reversed = gridOut.roworder === 'top to bottom';\n\n for (var axisId in axisMap) {\n var axLetter = axisId.charAt(0);\n var side = gridOut[axLetter + 'side'];\n\n var i0, inc, iFinal;\n\n if (side.length < 8) {\n // grid edge - ie not \"* plot\" - make these as free axes\n // since we're not guaranteed to have a subplot there at all\n anchors[axisId] = 'free';\n } else if (axLetter === 'x') {\n if (side.charAt(0) === 't' === reversed) {\n i0 = 0;\n inc = 1;\n iFinal = rows;\n } else {\n i0 = rows - 1;\n inc = -1;\n iFinal = -1;\n }\n if (hasSubplotGrid) {\n var column = axisMap[axisId];\n for (i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[i][column];\n if (!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if (subplotId.slice(0, yPos) === axisId) {\n anchors[axisId] = subplotId.slice(yPos);\n break;\n }\n }\n } else {\n for (i = i0; i !== iFinal; i += inc) {\n yId = gridOut.yaxes[i];\n if (subplots.cartesian.indexOf(axisId + yId) !== -1) {\n anchors[axisId] = yId;\n break;\n }\n }\n }\n } else {\n if (side.charAt(0) === 'l') {\n i0 = 0;\n inc = 1;\n iFinal = columns;\n } else {\n i0 = columns - 1;\n inc = -1;\n iFinal = -1;\n }\n if (hasSubplotGrid) {\n var row = axisMap[axisId];\n for (i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[row][i];\n if (!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if (subplotId.slice(yPos) === axisId) {\n anchors[axisId] = subplotId.slice(0, yPos);\n break;\n }\n }\n } else {\n for (i = i0; i !== iFinal; i += inc) {\n xId = gridOut.xaxes[i];\n if (subplots.cartesian.indexOf(xId + axisId) !== -1) {\n anchors[axisId] = xId;\n break;\n }\n }\n }\n }\n }\n }",
"function contentDefaults(layoutIn, layoutOut) {\n var gridOut = layoutOut.grid;\n // make sure we got to the end of handleGridSizing\n if (!gridOut || !gridOut._domains) return;\n var gridIn = layoutIn.grid || {};\n var subplots = layoutOut._subplots;\n var hasSubplotGrid = gridOut._hasSubplotGrid;\n var rows = gridOut.rows;\n var columns = gridOut.columns;\n var useDefaultSubplots = gridOut.pattern === 'independent';\n var i, j, xId, yId, subplotId, subplotsOut, yPos;\n var axisMap = gridOut._axisMap = {};\n if (hasSubplotGrid) {\n var subplotsIn = gridIn.subplots || [];\n subplotsOut = gridOut.subplots = new Array(rows);\n var index = 1;\n for (i = 0; i < rows; i++) {\n var rowOut = subplotsOut[i] = new Array(columns);\n var rowIn = subplotsIn[i] || [];\n for (j = 0; j < columns; j++) {\n if (useDefaultSubplots) {\n subplotId = index === 1 ? 'xy' : 'x' + index + 'y' + index;\n index++;\n } else subplotId = rowIn[j];\n rowOut[j] = '';\n if (subplots.cartesian.indexOf(subplotId) !== -1) {\n yPos = subplotId.indexOf('y');\n xId = subplotId.slice(0, yPos);\n yId = subplotId.slice(yPos);\n if (axisMap[xId] !== undefined && axisMap[xId] !== j || axisMap[yId] !== undefined && axisMap[yId] !== i) {\n continue;\n }\n rowOut[j] = subplotId;\n axisMap[xId] = j;\n axisMap[yId] = i;\n }\n }\n }\n } else {\n var xAxes = getAxes(layoutOut, gridIn, 'x');\n var yAxes = getAxes(layoutOut, gridIn, 'y');\n gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');\n gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');\n }\n var anchors = gridOut._anchors = {};\n var reversed = gridOut.roworder === 'top to bottom';\n for (var axisId in axisMap) {\n var axLetter = axisId.charAt(0);\n var side = gridOut[axLetter + 'side'];\n var i0, inc, iFinal;\n if (side.length < 8) {\n // grid edge - ie not \"* plot\" - make these as free axes\n // since we're not guaranteed to have a subplot there at all\n anchors[axisId] = 'free';\n } else if (axLetter === 'x') {\n if (side.charAt(0) === 't' === reversed) {\n i0 = 0;\n inc = 1;\n iFinal = rows;\n } else {\n i0 = rows - 1;\n inc = -1;\n iFinal = -1;\n }\n if (hasSubplotGrid) {\n var column = axisMap[axisId];\n for (i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[i][column];\n if (!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if (subplotId.slice(0, yPos) === axisId) {\n anchors[axisId] = subplotId.slice(yPos);\n break;\n }\n }\n } else {\n for (i = i0; i !== iFinal; i += inc) {\n yId = gridOut.yaxes[i];\n if (subplots.cartesian.indexOf(axisId + yId) !== -1) {\n anchors[axisId] = yId;\n break;\n }\n }\n }\n } else {\n if (side.charAt(0) === 'l') {\n i0 = 0;\n inc = 1;\n iFinal = columns;\n } else {\n i0 = columns - 1;\n inc = -1;\n iFinal = -1;\n }\n if (hasSubplotGrid) {\n var row = axisMap[axisId];\n for (i = i0; i !== iFinal; i += inc) {\n subplotId = subplotsOut[row][i];\n if (!subplotId) continue;\n yPos = subplotId.indexOf('y');\n if (subplotId.slice(yPos) === axisId) {\n anchors[axisId] = subplotId.slice(0, yPos);\n break;\n }\n }\n } else {\n for (i = i0; i !== iFinal; i += inc) {\n xId = gridOut.xaxes[i];\n if (subplots.cartesian.indexOf(xId + axisId) !== -1) {\n anchors[axisId] = xId;\n break;\n }\n }\n }\n }\n }\n}",
"function defaultGrid() {\n setGridSize(24);\n fillGrid(24);\n}",
"function createEmptyHeatMapContainer(){\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(heatMapContainer != null){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tme.remove(heatMapContainer);\n\t\t\t\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\t\t\t\theatMapContainer = Ext.widget('container',{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlayout: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'table',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolumns: xAxisBands.length + 3,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\talign:'stretch'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tflex:1\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\tme.add(heatMapContainer);\n\t\t\t\t\t\t\t\t\t\t\t\t}",
"layout() {\n const x = d3Hierarchy.treemap();\n\n x.ratio = _ => {\n const t = x.tile();\n if (t.ratio) x.tile(t.ratio(_));\n };\n\n x.method = _ => {\n if (vegaUtil.hasOwnProperty(Tiles, _)) x.tile(Tiles[_]);else vegaUtil.error('Unrecognized Treemap layout method: ' + _);\n };\n\n return x;\n }",
"createLayout() { }",
"layout() {\n const x = d3Hierarchy.treemap();\n\n x.ratio = _ => {\n const t = x.tile();\n if (t.ratio) x.tile(t.ratio(_));\n };\n\n x.method = _ => {\n if (has(Tiles, _)) x.tile(Tiles[_]);else error('Unrecognized Treemap layout method: ' + _);\n };\n\n return x;\n }",
"function setLayout(){\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2. Read and parse file containing the feed URLs. | function readRSSFile (configFilename) {
fs.readFile(configFilename, function(err, feedList) {
if (err) return next(err);
// convert list of feed URLs to a string and then into an array of feed URLs.
feedList = feedList
.toString()
.replace(/^\s+|\s+$/g, '')
.split("\n");
console.log('**feed list count:' + feedList.length + '|' + Math.random() + '|' + (Math.random()*feedList.length));
// Select random feed URL from array of feed URLs.
var random = Math.floor(Math.random()*feedList.length);
next(null, feedList[random]);
});
} | [
"function read_feed_links() {\n\tlet feeds = {}\n\treturn new Promise((resolve) => {\n\t\tglob(FEED_ROOT + \"/**/**/_feed_.json\", {}, (err, files) => {\n\t\t\tfiles.forEach((path, idx) => {\n\t\t\t\tconst json = JSON.parse(fs.readFileSync(path).toString())\n\t\t\t\tconst url = normUrl(json.url)\n\t\t\t\tfeeds[url] = {\n\t\t\t\t\t'path': path,\n\t\t\t\t\t'title': json.title\n\t\t\t\t}\n\t\t\t})\n\t\t\tresolve(feeds)\n\t\t});\n\t})\n}",
"function parseFeed(feedURL) {\n let title, description, link, date, pubdate, author, language, image, categories\n let req = request(feedURL),\n feedParser = new FeedParser()\n \n req.on('error', function(error) { console.log(error) })\n req.on('response', function(res) {\n let stream = this\n if(res.statusCode != 200) { return this.emit('error', new Error('Bad status code'))}\n stream.pipe(feedParser)\n })\n\n feedParser.on('error', function(error) { console.log(error) })\n feedParser.on('readable', function() {\n let stream = this, \n meta = this.meta, \n item\n while (item = stream.read()) { console.log(\"Title: \" + item.title + \"\\n\" + \"Author: \" + item.author) }\n })\n}",
"function parseRSSFile(cb) {\r\n var rssParser = require(\"rss-parser\");\r\n // var absPath = path.join(pathToFile);\r\n rssParser.parseFile(pathToFile, function (err, parsedRss) {\r\n\r\n cb(null, parsedRss);\r\n\r\n });\r\n }",
"function processFile (filename, done) {\n // Find which URL to use.\n var url = files[filename].feedparser || false;\n if (url) {\n // Load up the request object stream.\n var req = request(url);\n\n // Create the FeedParser object.\n var feedparser = new FeedParser(files[filename]);\n\n // Set the error responses.\n req.on('error', done);\n feedparser.on('error', done);\n\n // Pipe the requested data over to FeedParser.\n req.on('response', function (res) {\n if (res.statusCode !== 200) {\n return this.emit('error', new Error('Bad status code'));\n }\n this.pipe(feedparser);\n });\n\n // When finished, delete the original feedparser file.\n feedparser.on('end', function () {\n delete files[filename];\n done();\n });\n\n // When data from the request comes in.\n feedparser.on('readable', function () {\n // Parse through every RSS item.\n for (var item = this.read(); item !== null; item = this.read()) {\n // Construct the new RSS feed item file.\n var newFile = clone(files[filename]);\n // Find the contents.\n newFile.contents = new Buffer(item.description || item.summary || '');\n // Inject additional properties from the original file.\n extend(newFile, item);\n\n // Find a new filename for the item to live.\n var newFilename = getFilename(newFile.title || newFile.guid, newFile.extension || 'html');\n files[newFilename] = newFile;\n }\n });\n } else {\n // Error out if no URL is found.\n done('FeedParser URL `file.feedparser` not set.');\n }\n }",
"function parseAndProcessFeed(feedUrl, callback) {\n\tvar now = new Date();\n\tvar item;\n\t// when parsing is finished, iterate over articles to store them in an array of all articles of all streams\n\tfeedparser.parseUrl(feedUrl).on('complete', function onComplete(meta, articles) {\n\t\tfor (var article in articles) {\n\t\t\t// some people put a future date as the pubDate of their articles to stay on top of aggregated feeds, fuck them\n\t\t\tif (now > Date.parse(articles[article].date)) {\n\t\t\t\titem = new RssItem(articles[article].title, articles[article].summary, articles[article].link, articles[article].author, articles[article].date);\n\t\t\t\titems.push(item);\n\t\t\t}\n\t\t}\n\t\t// tell async that this parse and process is finished\n\t\tcallback();\n\t});\n}",
"function readRssFeed(url) {\n var fac = Factory.newInstance()\n var reader = fac.createXMLEventReader(url.openStream())\n\n // get text content from next event\n function getChars() {\n var result = \"\"\n var e = reader.nextEvent()\n if (e instanceof Characters) {\n result = e.getData()\n }\n return result\n }\n\n var items = []\n var title, link\n var inItem = false\n while (reader.hasNext()) {\n var evt = reader.nextEvent()\n if (evt.isStartElement()) {\n var local = evt.name.localPart\n if (local == \"item\") {\n // capture title, description now\n inItem = true\n }\n \n if (inItem) {\n switch (local) {\n case 'title':\n title = getChars()\n break\n case 'link':\n link = getChars()\n break\n }\n }\n } else if (evt.isEndElement()) {\n var local = evt.name.localPart\n if (local == \"item\") {\n // one item done, save it in result array\n items.push({ title: title, link: link })\n inItem = false\n }\n }\n }\n\n return items\n}",
"function parseRSS(file, factory) {\n var events = file.getElementsByTagName(\"item\");\n var title, date, parsed, link;\n\n var cut = events.length <= CUTOFF ? events.length : CUTOFF;\n\n document.body.addEventListener(\"resourceLoaded\",\n handleResource, false);\n\n document.body.addEventListener(\"doneLoading\",\n function () {\n\t\t\t\t$(\"#myCarousel\").carousel(\"pause\").removeData();\n\t\t\t\t$(\"#myCarousel\").carousel({\n \t\t\t\t\tinterval: INTERVAL\n\t\t\t\t});\n\t\t\t}, true);\n\n for (var i = 0; i < cut; i++) {\n title = events[i].getElementsByTagName(\"title\")[0].childNodes[0].nodeValue;\n date = events[i].getElementsByTagName(\"pubDate\")[0].childNodes[0].nodeValue;\n link = events[i].getElementsByTagName(\"link\")[0].childNodes[0].nodeValue;\n date = translateDate(date);\n factory.addEvent(new KSETEvent(title, date, link));\n\n fetchData(corsProxy + link, function(evNum) {\n return function(f) {\n fetchImage(f, evNum, factory);\n };\n }(factory.size() - 1), failure, false);\n }\n\n}",
"function parseURLFile(f, cb) {\n fs.readFile(f, function(err, buf) {\n if (err) return cb(err);\n try {\n var s = parseString(buf.toString());\n cb(null, s);\n } catch (e) {\n cb(e);\n }\n });\n}",
"async function getUrls() {\n try {\n await access(urlsFile)\n return await parseCSV(urlsFile)\n } catch {\n console.log(yellow('No urls.csv file found.'))\n process.exit(1)\n }\n}",
"function readAlbumUrls () {\n // reset the songs list for a new file\n all_songs_array = [];\n\n var file_name = path.join(__dirname, '../collections/albumUrls/albumUrls'+file_number+'.js'),\n album_urls_object;\n\n try {\n // get the json object of album page urls\n album_urls_object = jsonfile.readFileSync(file_name);\n } catch (err) {\n if (err.code === 'ENOENT') {\n console.log('File'+file_name+' not found!');\n // exit the script\n process.exit();\n } else {\n throw err;\n }\n }\n\n // map to an array of album-urls\n var album_urls_array = _.flatten(_.map(album_urls_object, function (albums_object, artist_name) {\n return _.map(albums_object, function (album_url, album_name) {\n return album_url;\n });\n }));\n\n return album_urls_array;\n}",
"function parse_all_feeds(){\n\twindow.active_feeds = [];\n\n\twindow.num_feeds = window.user_feeds.length;\n\n\tvar first_feed_info = window.user_feeds[0];\n\tif (first_feed_info.ignore){\n\t\tparse_remaining_feeds(0);\n\t}\n\telse{\n\t\t//console.log(\"\\nloading: \" + first_feed_info.feed_name);\n\t\tvar first_feed = first_feed_info.connection;\n console.log(\"First feed: \" + first_feed);\n\t\tfirst_feed.setNumEntries(4);\n\t\tvar load_contents = function(result){\n\t\t\t\t\t\t\t\t\t\tparse_feed_entries(result, 0);\n\t\t\t\t\t\t\t\t\t};\n\t\tfirst_feed.load(load_contents);\n\t}\n}",
"function readLibsynFeed(url, handler) {\n $.get(url, function(data) { \n var xmlResults = $.makeArray($(data).find('item'));\n var results = $.map(xmlResults, function(item, idx) { \n var $item = $(item); \n var date = new Date($item.find('pubDate').text());\n var month = monthNames[date.getUTCMonth()];\n var result = {\n id: idx,\n title: $item.find('title').text(),\n link: $item.find('link').text(),\n text: $item.find('description').text(),\n date: date.getUTCDate() + ' ' + month,\n year: date.getUTCFullYear(),\n timestamp: date,\n audio: $item.find('enclosure').attr('url'),\n }; \n return result;\n }); \n handler(results);\n }); \n }",
"function parseURLFileSync(f) {\n return parseString(fs.readFileSync(f).toString());\n}",
"function parseURL(feedURL, options, callback) {\n if (typeof options === 'function' && !callback) {\n callback = options;\n options = {};\n }\n var defaults = {uri: feedURL, jar: false, proxy: false, followRedirect: true, timeout: 1000 * 30};\n options = _.extend(defaults, options);\n //check that the protocal is either http or https\n var u = URL.parse(feedURL);\n if (u.protocol === 'http:' || u.protocol === 'https:') {\n //make sure to have a 30 second timeout\n var req = request(options, function (err, response, xml) {\n if (err || xml === null) {\n if (err) {\n callback(err, null);\n } else {\n callback('Failed to retrieve source!', null);\n }\n } else {\n if ((typeof response !== \"undefined\" && response !== null ? response.statusCode : void 0) != null) {\n if (response.statusCode >= 400) {\n callback(\"Failed to retrieve source! Invalid response code (\" + response.statusCode + \")!\", null);\n } else {\n parseString(xml, options, callback);\n }\n } else {\n callback(\"Failed to retrieve source! No response code!!\", null);\n }\n }\n });\n } else {\n callback({error: \"Only http or https protocols are accepted\"}, null);\n }\n}",
"function processFile(file){\n fs.readFile(file, \"utf8\", function(err, data){\n if(err){\n console.log(err)\n }else{\n lineArray = data.toString().split(\"\\n\");\n console.log(\"Number of lines in file is: \", lineArray.length, \"\\n\");\n //goes through \"lineArray\" and uses the filter method to find lines with http and https in them.\n //Also removes lines that do NOT have urls in them so that we wont wate time on those using our regex on them.\n //Then puts the lines with http and https (with all capitals too) in \"lineWithURLArray\"\n lineWithURLArray = lineArray.filter(\n (line) =>\n line.includes(\"https:\") ||\n line.includes(\"http:\") ||\n line.includes(\"HTTPS:\") ||\n line.includes(\"HTTP:\")\n );\n console.log(\"The number of lines with URLs in this file: \",lineWithURLArray.length,\"\\n\");\n console.log(\"Checking for the number of URL's in this file...\\n\");\n //goes through the \"lineWithURLArray\" and finds things that match the regex. Then puts them into onlyURLArray made at line 21-ish\n for (let i = 0; i < lineWithURLArray.length; i++) {\n let res = lineWithURLArray[i].match(regexForURLs);\n if (res) {\n onlyURLArray = onlyURLArray.concat(res);\n }\n }\n console.log(\"The number of URLs in this file: \", onlyURLArray.length, \"\\n\");\n \n //goes through onlyURLArray and checks for unique URLs and puts them into uniqueURLArray\n for (i = 0; i < onlyURLArray.length; i++) {\n if (uniqueURLArray.indexOf(onlyURLArray[i]) === -1) {\n uniqueURLArray.push(onlyURLArray[i]);\n }\n }\n //a nested forloop that checks for system urls (things that html and pdf files need to open) and removes them\n for (j = 0; j < systemURLs.length; j++) {\n for (i = 0; i < uniqueURLArray.length; i++) {\n if (uniqueURLArray[i] === systemURLs[j]) {\n uniqueURLArray.splice(i, 1);\n }\n }\n }\n console.log(\n \"The number of UNIQUE URLs in this file: \",\n uniqueURLArray.length,\n \"\\n\"\n );\n uniqueURLArray.forEach(async (url) => {\n try {\n const urlIndiv = await fetch(url, { method: \"head\", timeout: 13000 });\n if (urlIndiv.status === 200) {\n console.log(chalk.green(\"good: \", url));\n } else if (urlIndiv.status === 400 || urlIndiv.status === 404) {\n console.log(chalk.redBright(\"bad: \", url));\n } else {\n console.log(chalk.grey(\"unknown: \", url));\n }\n } catch (err) {\n console.log(chalk.rgb(210, 0, 0)(\"bad (other): \", url));\n }\n });\n var greeting = chalk.white.bold(\"lFinder is now testing: \", `${file}!`);\n const msgBox = boxen(greeting, boxenOptions);\n //code for displaying the statuses above\n console.log(msgBox);\n\n }\n })\n }",
"function feedParser(url, source,number) {\n\tvar allCollection = new AllNewsCollection({});\n\tnewsName = {\n\t\t'AP': 'Associated Press'\n\t};\n\n\t$.jGFeed(url,\n\t\tfunction(feeds) {\n\t\t\t// Check for errors\n\t\t\tif (!feeds) {\n\t\t\t\t// there was an error\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// do whatever you want with feeds here\n //used regular expression to get what I want from feeds\n\t\t\tfor (var i = 0; i < feeds.entries.length; i++) {\n\t\t\t\tvar entry = feeds.entries[i];\n\t\t\t\tvar newssrc;\n\t\t\t\tvar myTitle;\n\t\t\t\tvar newlink;\n\t\t\t\tif (source == 'google') {\n\t\t\t\t\tentry.link = entry.link.match(/url=[^\\s]+/g);\n\t\t\t\t\tnewlink = entry.link[0].substring(4);\n\t\t\t\t\tmyTitle = entry.title.match(/.* - /g);\n\t\t\t\t\tmyTitle = myTitle[0].substring(0, myTitle[0].length - 2);\n\t\t\t\t\tnewssrc = entry.title.match(/ - .*/g);\n\t\t\t\t\tnewssrc = newssrc[0].substring(2);\n\t\t\t\t}\n\t\t\t\tif (source == 'yahoo') {\n\t\t\t\t\tnewlink = entry.link;\n\t\t\t\t\tmyTitle = entry.title;\n\t\t\t\t\tnewssrc = entry.contentSnippet.match(/\\(.*\\) /g);\n\t\t\t\t\tif (newssrc != null) {\n\t\t\t\t\t\tnewssrc = newssrc[0].substring(1, newssrc[0].length - 2);\n\t\t\t\t\t\tif (newssrc == 'AP') {\n\t\t\t\t\t\t\tnewssrc = 'Associated Press';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t newssrc ='Yahoo';\n\t\t\t\t\t }\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewssrc = 'Yahoo';\n\t\t\t\t\t}\n\n\n\t\t\t\t}\n\t\t\t\tvar mynews = new News({\n\t\t\t\t\ttitle: myTitle,\n\t\t\t\t\tdate: entry.publishDate,\n\t\t\t\t\tsummary: entry.contentSnippet,\n\t\t\t\t\tlink: newlink,\n\t\t\t\t\tnewsSource: newssrc\n\n\t\t\t\t});\n\t\t\t\tallCollection.add(mynews);\n\n\t\t\t}\n\n\t\t}, number);\n\n\n\n\n\n\treturn allCollection;\n}",
"loadXml(url){\n\t\tthis.props.startLoading();\n // eslint-disable-next-line\n\t\tfeednami.load(url).then(({entries}) => {\n\t\t\tthis.props.endLoading();\n\t\t\tthis.setState({\n\t\t\t\tentries\n\t\t\t});\n\t\t}).catch(() => {\n\t\t\tthis.props.endLoading();\n\t\t\tthis.setState({\n\t\t\t\tentries: []\n\t\t\t});\n\t\t\talert('Not rss feeds');\n\t\t});\n\t}",
"function getRelFeeds (url) {\n\t\tconst feeds = [];\n\t\tconst relLinks = document.querySelectorAll('link[rel*=\"alternate\"]');\n\t\trelLinks.forEach((link) => {\n\t\t\tlet href = link.getAttribute('href');\n\t\t\tlet type = link.getAttribute('type');\n\n\t\t\tif (typeof href !== 'string' || typeof type !== 'string') {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thref = href.trim();\n\t\t\ttype = type.trim();\n\n\t\t\tswitch (type) {\n\t\t\t\tcase 'application/rss+xml': // rss\n\t\t\t\tcase 'application/atom+xml': // atom\n\t\t\t\tcase 'application/xml': // rss or atom\n\t\t\t\tcase 'text/xml': // rss or atom\n\t\t\t\tcase 'application/json': // jsonfeed\n\t\t\t\t\tif ( !href.startsWith('http') && !href.startsWith('//') ) {\n\t\t\t\t\t\tconst feedUrl = new URL(href, url.origin + url.pathname);\n\t\t\t\t\t\thref = feedUrl.toString();\n\t\t\t\t\t}\n\t\t\t\t\tfeeds.push(href);\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\treturn feeds;\n\t}",
"function parseOfferedFeedUrls(siteBody, done) {\n try {\n var parser = new htmlparser.Parser(new htmlparser.DefaultHandler(function(err, dom) {\n if (err) {\n log.error(\"error: \" + util.inspect(err));\n done(err);\n } else {\n log.trace(\"parsing\");\n var links = _.filter(select(dom, \"link\"), function(e) {\n return /(rss|atom)/i.test(e.attribs.type);\n });\n\n done(null, _.map(links, function(e) {\n return e.attribs.href;\n }));\n }\n }));\n log.trace(\"Built parser\");\n parser.parseComplete(siteBody);\n } catch (e) {\n log.error(\"error caught: \" + util.inspect(e));\n done(e);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the most specific link available for the given Singly item: | function getPermalink(item){
// console.log('getPermalink:', item);
switch(getService(item)) {
case 'facebook':
return 'https://www.facebook.com/photo.php?fbid='+item.data.id;
// case 'foursquare':
// return 'https://foursquare.com/ + ??? + /checkin/'+item.data.checkin.id;
case 'twitter':
return 'https://twitter.com/' + item.data.user.screen_name + '/statuses/' + item.data.id_str;
case 'instagram':
return item.data.link;
case 'tumblr':
return item.data.post_url;
// case 'linkedin':
// return '#';
default:
return '#link-unknown';
}
} | [
"function getURL(link) {\n const items = [\n {\n name: 'Home',\n url: './index.php'\n },\n {\n name: 'Shopping Cart',\n url: './Assignments/week3/store.html'\n },\n {\n name: 'DB Setup',\n url: '#'\n },\n {\n name: 'DB Access',\n url: './Assignments/week5/index.html'\n },\n {\n name: 'DB Update',\n url: '#'\n },\n {\n name: 'Project 1 Completion',\n url: '#'\n },\n {\n name: 'Hello World',\n url: '#'\n },\n {\n name: 'Postal Rate Calculator',\n url: '#'\n },\n {\n name: 'Milestone 1',\n url: '#'\n },\n {\n name: 'Milestone 2',\n url: '#'\n },\n {\n name: 'Milestone 3',\n url: '#'\n },\n {\n name: 'Project Self Assessment',\n url: '#'\n },\n {\n name: 'Week 2',\n url: '../../Team_Activities/week2/index.html'\n },\n {\n name: 'Week 3',\n url: '../../Team_Activities/week3/team_assignment.php'\n },\n {\n name: 'Week 4',\n url: '#'\n },\n {\n name: 'Week 5',\n url: '#'\n },\n {\n name: 'Week 6',\n url: '#'\n },\n {\n name: 'Week 7',\n url: '#'\n },\n {\n name: 'Week 8',\n url: '#'\n },\n {\n name: 'Week 9',\n url: '#'\n },\n {\n name: 'Week 10',\n url: '#'\n },\n {\n name: 'Week 11',\n url: '#'\n },\n {\n name: 'Week 12',\n url: '#'\n },\n {\n name: 'Week 13',\n url: '#'\n }\n ];\n\n // loop over items and find the correct item and then return the url for that\n // item\n const result = items.find( item => item.name === link);\n return result.url;\n}",
"getLink(item) {\n if (item.url) {\n return item.url;\n }\n else if (item.contentPageLabelOrId) {\n return item.contentPageLabelOrId;\n }\n else if (item.categoryCode) {\n return this.semanticPathService.transform({\n cxRoute: 'category',\n params: {\n code: item.categoryCode,\n name: item.name,\n },\n });\n }\n else if (item.productCode) {\n return this.semanticPathService.transform({\n cxRoute: 'product',\n params: {\n code: item.productCode,\n name: item.name,\n },\n });\n }\n }",
"function findLinkedItem(item) {\n return $('#gallery tr[data-uri=\"' + item._links.self.href + '\"]');\n }",
"getLink(item) {\r\n if (item.url) {\r\n return item.url;\r\n }\r\n else if (item.contentPageLabelOrId) {\r\n return item.contentPageLabelOrId;\r\n }\r\n else if (item.categoryCode) {\r\n return this.semanticPathService.transform({\r\n cxRoute: 'category',\r\n params: {\r\n code: item.categoryCode,\r\n name: item.name,\r\n },\r\n });\r\n }\r\n else if (item.productCode) {\r\n return this.semanticPathService.transform({\r\n cxRoute: 'product',\r\n params: {\r\n code: item.productCode,\r\n name: item.name,\r\n },\r\n });\r\n }\r\n }",
"function findLargestUrl(callback) {\n Url.find().sort({ shortUrl:-1 }).limit(1)\n .exec(function(err, data) {\n if (err) return callback(err, null); \n return callback(null, data[0].shortUrl);\n });\n }",
"getCanonicalLink(doc) {\n const { hostname } = this.props;\n\n // 1. Use the canonical url as a first option\n if (Object.hasOwnProperty.call(doc, 'ss_canonical_url') && doc.ss_canonical_url) {\n return doc.ss_canonical_url;\n }\n\n // Use a url from the current host, if present. Otherwise use the first Url.\n if (Object.hasOwnProperty.call(doc, 'sm_urls') && Array.isArray(doc.sm_urls)) {\n // Attempt to find a url from the current host.\n const currentHostUrl = doc.sm_urls.find((item) => {\n const myUrl = url.parse(item);\n return myUrl.hostname === hostname;\n });\n\n // 2. Use the url from the current host.\n if (currentHostUrl) {\n return currentHostUrl;\n }\n\n // 3. Use the first url.\n return doc.sm_urls[0];\n }\n\n // 4. Fall back to the single url (which will be relative)\n if (Object.hasOwnProperty.call(doc, 'ss_url') && doc.ss_url) {\n return doc.ss_url;\n }\n\n // 5. If no valid urls are passed, return nothing. This will result in an\n // unlinked title, but at least it won't crash.\n return '';\n }",
"function findCurrentTitleLink() {\r\n var entry = document.getElementById('current-entry');\r\n if (entry) {\r\n var anchors = entry.getElementsByTagName('a');\r\n for (var i = 0; i < anchors.length; i++) {\r\n if (\"entry-title-link\" == anchors[i].className) {\r\n return anchors[i];\r\n } \r\n }\r\n }\r\n return null;\r\n}",
"function getItemId(item) {\n var regexString = '^' + escapeRegExp(window.location.origin) + '\\/(.+)$';\n var match = item.href.match(new RegExp(regexString));\n if (match && match.length === 2) {\n return match[1];\n } else {\n console.log('could not match \\'' + item.href + '\\' with \\'' + regexString + '\\': ' + match);\n return undefined;\n }\n }",
"function getItemLink (url, user_id, item_id) {\n url = url.replace(/(%26|\\&)tag(%3D|=)[^%]+/, '%26tag%3D' + tag)\n logging.debug('ITEM IDDDDDDDDD ', url)\n\n var url_swapped = swapAmazonTLD(url, user_id)\n return googl.shorten('http://motorwaytoroswell.space/product/' + querystring.escape(url_swapped) + '/id/' + user_id + '/pid/' + item_id)\n}",
"function getItemUrl() {\n\n // get the full url.\n var url = window.location.href;\n\n // get the sanitized url removing the first part.\n var theItemUrl = getItemUrlProcessed(url);\n\n // return the item part.\n return theItemUrl;\n}",
"get_url(callback) {\n const collection = this.db.collection(\"shortener\")\n collection\n .findOne({ shortenedUrl: this.shortenedUrl }, (err, item) => {\n if (err) { return }\n\n if (item) {\n callback(item)\n } else {\n callback()\n }\n })\n }",
"function getLinkValue(link) {\n return link.substring(link.indexOf(enum_1.default.T_link) + 5);\n}",
"getLinkForApiItem(apiItem) {\n return this._implementation.getLinkForApiItem(apiItem);\n }",
"function fGetHref() {\n var aLinks = document.getElementById('social-bookmarks').getElementsByTagName('a');\n var nLength = aLinks.length;\n\n for (nCount = 0; nCount < nLength ; nCount++) {\n if (aLinks[nCount].className.match('explanation')) {\n var sLinkRef = aLinks[nCount].href;\n return sLinkRef;\n }\n }\n}",
"function findCurrentTitleLink() {\r\n var entry = document.getElementById('photoswftd');\r\n if (entry) {\r\n var anchors = entry.getElementsByTagName('h1');\r\n\treturn anchors[0];\r\n// for (var i = 0; i < anchors.length; i++) {\r\n// if (\"entry-title-link\" == anchors[i].className) {\r\n// return anchors[i];\r\n// } \r\n// }\r\n }\r\n return null;\r\n}",
"findIndex(target) {\n for (let i in this.items) {\n if (this.items[i].link == target)\n return (i)\n }\n return (-1)\n }",
"function dogooglemaplink(elt, domain, url, urlquery)\n{ // Look for fields indicating Google map item links. Use lowercase field names here.\n var targeturl = findqueryfield(urlquery, {\"q\":0,}); // find target link\n if (targeturl) // if find\n { var linkitem = dolinkurl(elt, targeturl); // treat as a basic link\n return(linkitem);\n }\n if (prefs.verbosepref) { console.log(\"Expected fields not found in Google map URL: \" + url); }\n return(null); // nothing to rate\n}",
"function findHoldBinder(SO_ResultSet,salesOrderOnPO,itemLinkOnPO ){\n var SOKey = Object.keys(SO_ResultSet);\n \n if(SOKey.indexOf(salesOrderOnPO) >= 0)\n \treturn SO_ResultSet[salesOrderOnPO][itemLinkOnPO];\n else\n \t return '';\n }",
"function useCategoryHrefWithSSRFallback(item) {\n const isBrowser = useIsBrowser();\n return useMemo(() => {\n if (item.href) {\n return item.href;\n }\n // In these cases, it's not necessary to render a fallback\n // We skip the \"findFirstCategoryLink\" computation\n if (isBrowser || !item.collapsible) {\n return undefined;\n }\n return findFirstCategoryLink(item);\n }, [item, isBrowser]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Legacy route handler is defined in cocoapods.service.js. | static registerLegacyRouteHandler() {} | [
"routeFor(...args) {\r\n this.native.routeFor.apply(this.native, args)\r\n }",
"function code() {\n server.route({\n method: 'GET',\n path: '/foobar',\n handler(request, reply) {\n reply({foo: 'bar'});\n },\n config: {\n description: 'foobar sample route',\n tags: ['api']\n }\n });\n}",
"function normalRoute() {\n\n }",
"_updateRouter(route) {\n\n /*\n (R.intersection(getMetods(route), verbs)).forEach(routeVerb => {\n route.log(`found route handler for '${routeVerb}' method`);\n route.router[routeVerb]('/', route[routeVerb].bind(route));\n });\n */\n\n this._getMethods(route).forEach(method => {\n let verb = this._startsWithVerb(method);\n if (verb) {\n let spec = this._routeify(method);\n if (spec) {\n route.log(`found route handler for '${spec.verb}' method`);\n route.router[spec.verb](spec.route, route[method].bind(route));\n }\n }\n });\n }",
"buildRoute (app, rawRoute) {\n const route = lib.Util.decorateRouteWithPrerequisites(app, rawRoute)\n if (_.isString(route.handler)){\n route.handler = _.get(app.controllers, rawRoute.handler)\n }\n\n if (!route.handler) {\n app.log.warn('trailpack-router: route handler [', rawRoute.handler, ']',\n 'does not correspond to any defined Controller handler')\n\n return\n }\n\n return route\n }",
"routes () {\n\n }",
"function route(handle, pathname, response, postData) {\n console.log(\"The route for path: %s, data: %s\", pathname, postData);\n try {\n if(pathname == '/') {\n // TODO: show desktop\n response.writeHead(302, {Location: 'http://' + serverAddr + '/app/desktop-app/main'});\n return response.end();\n } else if(pathname == '/ws') {\n var wsclient = response;\n var message = postData;\n wsclient.send(\"I have got your message whose length is \" + postData.length);\n // handle message\n handleWSMsg(wsclient, message);\n return;\n } else if(pathname == '/api') {\n // this is for remote call api in internet browser.\n return handleAPICall(handle, pathname, response, postData);\n // } else if(pathname.lastIndexOf(\"/callapp/\", 0) === 0) {\n } else if(pathname.lastIndexOf(\"/app/\", 0) === 0) {\n // This is for remote open app in internet browser.\n return handleAPPCall(handle, pathname, response, postData);\n } else {\n //Use api_remote.js for /lib/api.js\n var realPath;\n if(pathname == \"/lib/api.js\") {\n pathname = \"./lib/api_remote.js\";\n getRealFile(pathname, response);\n return;\n } else if(pathname.lastIndexOf(\"/lib/api/\", 0) === 0\n && pathname.indexOf(\".js\", pathname.length - 3) !== -1) {\n console.log('api:', pathname);\n var modulename = pathname.substring(9, pathname.length - 3);\n getRemoteAPIFile(handle, modulename, response);\n return;\n } else {\n getRealFile(pathname, response);\n return;\n }//end of /lib/api/***.js\n }//end of if callapi callapp and else\n } catch(e) {\n console.log('Router Error:', e);\n errorHandler(500, response, e.toString());\n }\n}",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, (error) => {\n res.send(400, 'Error processing hook');\n this.logger.error({ err: error }, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post(\n '/builds/:bid/status/:context',\n restify.plugins.jsonBodyParser(),\n this.buildStatusController.bind(this)\n );\n this.server.post(\n '/update',\n restify.plugins.jsonBodyParser(),\n this.buildStatusController.bind(this)\n );\n this.server.post(\n '/builds/hash',\n restify.plugins.jsonBodyParser(),\n this.hashBuildController.bind(this)\n );\n this.server.get(\n '/pull-request/:owner/:repo/:pullRequestNumber',\n this.getMergeRequest.bind(this)\n );\n }",
"doRoute() {\n let routename = 'HTTP:' + this.request.method + ':' + this.url.pathname;\n this.run(routename, this.restnio.routes, \n Parser.parseFullHttpParams, this.request, this.url);\n }",
"initRoute(route){\n this.notifyRoute(route);\n switch (route.method){\n case \"GET\":\n this.app.get(route.endpoint, route.handler);\n break;\n case \"PUT\":\n this.app.put(route.endpoint, route.handler);\n break;\n case \"POST\":\n this.app.post(route.endpoint, route.handler);\n break;\n case \"DELETE\":\n this.app.delete(route.endpoint, route.handler);\n break;\n default:\n throw new Error(\"Invalid http method \"+route.method);\n }\n }",
"routes()\n {\n return {\n 'ServiceStatus':\n {\n inboundTypes: this.inboundTypes,\n method: '/ServiceStatus',\n callback: this.serviceStatus,\n note: 'Used for requesting service details.'\n },\n 'Init':\n {\n inboundTypes: ['http'],\n method: '/',\n callback: this._pageInit,\n note: 'Used for requesting the home page.'\n }\n };\n\n }",
"__getRoute() {\n return '/';\n }",
"function route(handle, pathname, response, postData) {\n console.log(\"The route for path: %s, data: %s\", pathname, postData);\n if ( pathname == '/') {\n response.write(\"The index pages is blank.\");\n response.end();\n return;\n }else if ( pathname == '/ws') {\n var wsclient = response;\n var message = postData;\n wsclient.send(\"I have got your message whose length is \" + postData.length);\n // Handle message\n handleWSMsg(wsclient, message);\n return;\n }else if ( pathname == '/callapi' ) {\n //This is for remote call api in internet browser.\n if ( postData === null || postData.length === 0 ){\n response.writeHead(404, {'Content-Type': 'text/plain'});\n response.write(\"Invalid callapi\");\n response.end();\n return;\n }\n var postDataJSON=JSON.parse(postData);\n var args=postDataJSON.args;\n var apiPathArr=postDataJSON.api.split(\".\");\n var sendresponse = function(){\n response.writeHead(200, {\"Content-Type\": mimeTypes[\"js\"]});\n response.write(JSON.stringify(Array.prototype.slice.call(arguments)));\n response.end();\n }\n args.unshift(sendresponse);\n handle[apiPathArr[0]][apiPathArr[1]].apply(null, args);\n return;\n }else if ( pathname.lastIndexOf(\"/callapp/\", 0) === 0) {\n // This is for remote open app in internet browser.\n // request url: /callapp/ + appID + / + request file name\n var url = pathname.replace(/^\\//, '').split('/'),\n sAppID = url[1],\n sFilename = path.join.apply(this, url.slice(2));\n // var sAppName=pathname.substring(9, pathname.indexOf('/', 10));\n // var sFilename=pathname.substring(9 + sAppName.length + 1, pathname.length);\n /* var runapp=null; */\n // var app;\n // for(var i = 0; i < config.AppList.length; i++) {\n // app = config.AppList[i];\n // if (app.name == sAppName) {\n // runapp=app;\n // break;\n // }\n /* } */\n\n var runapp = appManager.getRegistedInfo(sAppID),\n rootPath = (runapp.local ? '' : config.APPBASEPATH);\n if(runapp === null) {\n console.log(\"Error no app \" + sAppID);\n response.writeHead(404, {\n 'Content-Type': 'text/plain'\n });\n response.write(\"This request URL \" + pathname + \" was not found on this server.\");\n response.end();\n return;\n }\n\n if(sFilename === \"index.html\") {\n getRealFile(path.join(rootPath, runapp.path, sFilename), response);\n } else if(sFilename === \"lib/api.js\") {\n getRealFile(path.join(rootPath, runapp.path, \"lib/api_remote.js\"), response);\n } else if(sFilename.lastIndexOf(\"lib/api/\", 0) === 0 \n && sFilename.indexOf(\".js\", sFilename.length - 3) !== -1) {\n var modulename = sFilename.substring(8, sFilename.length - 3);\n getRemoteAPIFile(handle, modulename, response);\n } else {\n getRealFile(path.join(rootPath, runapp.path, sFilename), response);\n }\n return;\n } else {\n //Use api_remote.js for /lib/api.js\n var realPath;\n if (pathname == \"/lib/api.js\") {\n pathname = \"./lib/api_remote.js\";\n getRealFile(pathname, response);\n return;\n }else if (pathname.lastIndexOf(\"/lib/api/\", 0) === 0 && pathname.indexOf(\".js\", pathname.length - 3) !== -1) {\n var modulename = pathname.substring(9, pathname.length - 3);\n getRemoteAPIFile(handle, modulename, response);\n return;\n }else {\n getRealFile(pathname, response);\n return;\n }//end of /lib/api/***.js\n }//end of if callapi callapp and else\n}",
"appRoutes(){\n\n\t\tthis.app.post('/singup', (request, response) => {\n\t\t\trouteHandler.singupRouteHandler(request, response);\n\t\t});\n\t}",
"function Route(){}",
"function Route() {}",
"onRoutes(routes) {}",
"getRouteHandler (handler) {\n return `${handler.controllerName}.${handler.handlerName}`\n }",
"static addNotSupportedRoute (server) {\n server.route({\n method: 'GET',\n path: '/test/not-supported',\n handler: NotSupportedController.index,\n options: {\n auth: false\n }\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the server on the specified port | start (port) {
// Listen for and handle incoming HTTP requests
this.server.on('request', (request, response) => {
const res = new Response(response)
this.handleRequest(request, res)
})
this.server.listen(port)
} | [
"function run(port) {\n const server = new Server(port);\n server.start();\n}",
"function start(port) {\n var service = HTTP.createServer(handle);\n service.listen(port, 'localhost');\n console.log(\"Visit localhost:\" + port);\n}",
"function start(port) {\n app.listen(port, () => {\n console.log(`im listen for the ${port}`);\n });\n}",
"async start () {\n const port = await tryPort(this.httpServer, this.maxPort, this.basePort)\n this.endpoint = `http://localhost:${port}`\n debug(`server is listening on port ${port}`)\n }",
"function startServer(port) {\n var connect = require(kettlePath);\n var open = require('open');\n\n connect.createServer(connect[\"static\"](__dirname)).listen(port);\n console.log(\"Preferences Management Tool server running...\");\n console.log(\"Visit http://\"+ host + \":\" + port + \"/demos/prefsEditor/index.html\");\n open(\"http://\"+ host + \":\" + port + \"/demos/prefsEditor/index.html\");\n}",
"function setUpPort(port){ \n server.listen(port, () => console.log(`Listening on port ${port}...`));\n}",
"function startServer() {\n\tportscanner.findAPortNotInUse(portStart, portEnd, '127.0.0.1', function(error, port) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t} else {\n\t\t\tconsole.log('Port available at: ' + port);\n\t\t\thttp.createServer(ecstatic).listen(port);\n\n\t\t\tcmd.get('open http://localhost:' + port, function(err) {\n\t\t\t\tif (err) {\n\t\t\t\t\tconsole.log('error', err)\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log('Listening on : ' + port);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}",
"function serverStarten(_port) {\n let server = Http.createServer(); //erstellen eines einfachen Servers\n console.log(\"Server gestartet\");\n server.listen(_port);\n server.addListener(\"request\", handleRequest);\n }",
"listen() {\n this._createServer();\n this.server.listen(this.config.port);\n }",
"function startServer() {\n const server = app.listen(8899, () => {\n const { port } = server.address();\n console.log(`Listening on port ${port}`);\n });\n}",
"function startServer(port, { open }) {\n clear();\n\n const loadingMessage = ora(`Starting CLI-GUI server on port ${port}`);\n loadingMessage.start();\n\n const serverPath = path.resolve(\n __dirname,\n '../',\n 'dist',\n 'server',\n 'server.bundle.js'\n );\n\n const productionEnv = Object.create(process.env);\n productionEnv.GLICKY_ENV = 'production';\n productionEnv.FORCE_COLOR = 1;\n\n const proc = spawn('node', [serverPath, `--port=${port}`], {\n env: productionEnv\n });\n\n proc.stdout.on('data', data => {\n // TODO: do this better\n if (data.toString().startsWith('🚀')) {\n if (open) {\n opn(`http://localhost:${port}`);\n }\n loadingMessage.stop();\n printSuccessMessage(port);\n }\n });\n}",
"function startServer(port, callback) {\n port = port || 8080;\n console.log('Starting Modified Polyserve on port ' + port);\n\n var app = express();\n var polyserve = polyServe.makeApp();\n\n app.use('/components/', polyserve);\n\n console.log('Files in this directory are available at localhost:' +\n port + '/components/' + polyserve.packageName + '/...');\n\n return callback(app, app.listen(port));\n}",
"function startServer(){\n var ps = spawn('forever', [ 'start', base + 'lib/www.js' ]);\n var err = '';\n ps.stderr.on('data', function (data) { \n err += data;\n });\n ps.on('exit', function (code) {\n if(code !== null){\n success('Nserv started on port 8080.');\n }\n else {\n error(err, \"Could not start main nserv server.\");\n }\n });\n}",
"function startTestServer(port) {\n\t\tconst testServer = spawn('npx', ['svelte-kit', 'dev', `--port=${port}`]);\n\n\t\ttestServer.stderr.on('data', (data) => {\n\t\t\tconsole.error(data.toString());\n\t\t});\n\n\t\ttestServer.stdout.on('data', (data) => {\n\t\t\tconsole.log(data.toString());\n\t\t});\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\ttestServer.stdout.on('data', (data) => {\n\t\t\t\tif (/http:\\/\\/localhost:\\d+/.test(data)) {\n\t\t\t\t\tresolve(testServer);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\ttestServer.on('close', reject);\n\t\t});\n\t}",
"start() {\n this.httpServer.listen(this.port);\n console.log('Servidor corriendo en el puerto :', this.port);\n }",
"startListening() {\n\t\tthis.server.listen(this.port, () => {\n\t\t\tconsole.log('Server started listening on port', this.port);\n\t\t});\n\t}",
"function startServer(app, port) {\n const server = app\n .listen(port, () => {\n logger.log(\"server\", `Example app listening on port ${port}!`);\n })\n .on(\"error\", err => {\n if (err.code === \"EADDRINUSE\") {\n server.close();\n startServer(app, port + 1);\n }\n });\n}",
"function startServer() {\nvar generatedRandomPort = calculateRandomPort(); // generates random port\nvar server = http.createServer(serveURL); // calls create server with callback function of serveURL\nserver.listen(generatedRandomPort,hostname); // listens on the generated port name and const host\nconsole.log(\"Server started. Listening on http://\"+hostname+\":\"+generatedRandomPort+\"\");\n}",
"initWebServer(port) {\n this.server = new Server(port, this);\n this.server.init();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do not modify this file it is generated by m4 / $dollar_lib.m4.js | function getDollarNumber ( ) {
'use strict';
var __FUNCTION__ = "getDollarNumber";
this.dollar = {};
this.next_dollar = 1;
this.data_saved = [];
} | [
"set Dollar(value) {}",
"function amount() {}",
"protected internal function m252() {}",
"function price() constant returns (uint){\n return 1 finney;\n }",
"function centsInDollar() {\n return 100;\n}",
"function MathUtils() {}",
"function Package()\n{\n}",
"_generateLibrary() {}",
"function HiPaySignitureMgr() {}",
"function AstroMath() {}",
"static gasAmountConstants() {\n return {\n createLock: 2500000,\n updateKeyPrice: 1000000,\n purchaseKey: 1000000,\n withdrawFromLock: 1000000,\n }\n }",
"function Library() {\n \n}",
"function EBX_Constants() {\n\n}",
"function vB_PHP_Emulator()\n{\n}",
"function $3j4(){\n var global$=new $3j4.$$;RegExpFlag(\"g\",global$);\n return global$;\n}",
"function EBX_Constants() {\r\n\r\n}",
"function MsrcryptoECC() {\r\n /// <summary>Elliptic Curve Cryptography (ECC) functions.</summary>\r\n\r\n // Create an array, mimics the constructors for typed arrays.\r\n function createArray(/*@dynamic*/parameter) {\r\n var i, array = null;\r\n if (!arguments.length || typeof arguments[0] === \"number\") {\r\n // A number.\r\n array = [];\r\n for (i = 0; i < parameter; i += 1) {\r\n array[i] = 0;\r\n }\r\n } else if (typeof arguments[0] === \"object\") {\r\n // An array or other index-able object\r\n array = [];\r\n for (i = 0; i < parameter.length; i += 1) {\r\n array[i] = parameter[i];\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n var btd = cryptoMath.bytesToDigits;\r\n\r\n var EllipticCurveFp = function (p1, a1, b1, order, gx, gy) {\r\n /// <param name=\"p1\" type=\"Digits\"/>\r\n /// <param name=\"a1\" type=\"Digits\"/>\r\n /// <param name=\"b1\" type=\"Digits\"/>\r\n /// <param name=\"order\" type=\"Digits\"/>\r\n /// <param name=\"gx\" type=\"Digits\"/>\r\n /// <param name=\"gy\" type=\"Digits\"/>\r\n /// <returns type=\"EllipticCurveFp\"/>\r\n\r\n var fieldStorageBitLength = p1.length;\r\n\r\n var generator = EllipticCurvePointFp(this, false, gx, gy, null, false);\r\n\r\n return {\r\n p: p1, // field prime\r\n a: a1, // Weierstrass coefficient a\r\n b: b1, // Weierstrass coefficient b\r\n order: order, // EC group order\r\n generator: generator, // EC group generator\r\n allocatePointStorage: function () {\r\n return EllipticCurvePointFp(\r\n this,\r\n false,\r\n cryptoMath.intToDigits(0, fieldStorageBitLength),\r\n cryptoMath.intToDigits(0, fieldStorageBitLength)\r\n );\r\n },\r\n createPointAtInfinity: function () {\r\n return EllipticCurvePointFp(\r\n this,\r\n true,\r\n cryptoMath.intToDigits(0, fieldStorageBitLength),\r\n cryptoMath.intToDigits(0, fieldStorageBitLength)\r\n );\r\n }\r\n };\r\n };\r\n\r\n var createWeierstrassCurve = function (curveData) {\r\n\r\n var newCurve = new EllipticCurveFp(\r\n btd(curveData.p), // P\r\n btd(curveData.a), // A\r\n btd(curveData.b), // B\r\n btd(curveData.order), // Order\r\n btd(curveData.gx), // gX\r\n btd(curveData.gy) // gy\r\n );\r\n\r\n newCurve.type = curveData.type;\r\n newCurve.name = curveData.name;\r\n newCurve.generator.curve = newCurve;\r\n\r\n return newCurve;\r\n };\r\n\r\n var createTedCurve = function (curveData) {\r\n\r\n var btd = cryptoMath.bytesToDigits;\r\n\r\n var newCurve = new EllipticCurveFp(\r\n btd(curveData.p), // P\r\n btd(curveData.a), // A\r\n btd(curveData.d), // D\r\n btd(curveData.order), // Order\r\n btd(curveData.gx), // gX\r\n btd(curveData.gy) // gy\r\n );\r\n\r\n newCurve.type = curveData.type;\r\n\r\n if (newCurve.type == 1) {\r\n newCurve.d = newCurve.b.slice();\r\n delete newCurve.b;\r\n }\r\n\r\n newCurve.rbits = curveData.info[2];\r\n newCurve.name = curveData.name;\r\n newCurve.generator.curve = newCurve;\r\n\r\n return newCurve;\r\n };\r\n\r\n var EllipticCurvePointFp = function (curve, isInfinity, x, y, z, isInMontgomeryForm) {\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n /// <param name=\"isInfinity\" type=\"Boolean\"/>\r\n /// <param name=\"x\" type=\"Digits\"/>\r\n /// <param name=\"y\" type=\"Digits\"/>\r\n /// <param name=\"z\" type=\"Digits\" optional=\"true\"/>\r\n /// <param name=\"isInMontgomeryForm\" type=\"Boolean\" optional=\"true\"/>\r\n /// <returns type=\"EllipticCurvePointFp\"/>\r\n\r\n var returnObj;\r\n\r\n // 'optional' parameters\r\n if (typeof z === \"undefined\") {\r\n z = null;\r\n }\r\n\r\n if (typeof isInMontgomeryForm === \"undefined\") {\r\n isInMontgomeryForm = false;\r\n }\r\n\r\n function equals(/*@type(EllipticCurvePointFp)*/ellipticCurvePointFp) {\r\n /// <param name=\"ellipticCurvePointFp\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If null\r\n if (!ellipticCurvePointFp) {\r\n return false;\r\n }\r\n\r\n // Infinity == infinity\r\n if (returnObj.isInfinity && ellipticCurvePointFp.isInfinity) {\r\n return true;\r\n }\r\n\r\n // Otherwise its member-wise comparison\r\n\r\n if (returnObj.z === null && ellipticCurvePointFp.z !== null) {\r\n return false;\r\n }\r\n\r\n if (returnObj.z !== null && ellipticCurvePointFp.z === null) {\r\n return false;\r\n }\r\n\r\n if (returnObj.z === null) {\r\n return (cryptoMath.compareDigits(returnObj.x, ellipticCurvePointFp.x) === 0 &&\r\n cryptoMath.compareDigits(returnObj.y, ellipticCurvePointFp.y) === 0 &&\r\n returnObj.isInMontgomeryForm === ellipticCurvePointFp.isInMontgomeryForm);\r\n }\r\n\r\n return (cryptoMath.compareDigits(returnObj.x, ellipticCurvePointFp.x) === 0 &&\r\n cryptoMath.compareDigits(returnObj.y, ellipticCurvePointFp.y) === 0 &&\r\n cryptoMath.compareDigits(returnObj.z, ellipticCurvePointFp.z) === 0 &&\r\n returnObj.isInMontgomeryForm === ellipticCurvePointFp.isInMontgomeryForm);\r\n }\r\n\r\n function copyTo(/*@type(EllipticCurvePointFp)*/ source, /*@type(EllipticCurvePointFp)*/ destination) {\r\n /// <param name=\"source\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"destination\" type=\"EllipticCurvePointFp\"/>\r\n\r\n destination.curve = source.curve;\r\n destination.x = source.x.slice();\r\n destination.y = source.y.slice();\r\n\r\n if (source.z !== null) {\r\n destination.z = source.z.slice();\r\n } else {\r\n destination.z = null;\r\n }\r\n\r\n setterSupport || (destination.isAffine = source.isAffine);\r\n destination.isInMontgomeryForm = source.isInMontgomeryForm;\r\n destination.isInfinity = source.isInfinity;\r\n\r\n if (!destination.equals(source)) {\r\n throw new Error(\"Instances should be equal.\");\r\n }\r\n\r\n }\r\n\r\n function clone() {\r\n\r\n var clonePoint = EllipticCurvePointFp(\r\n returnObj.curve,\r\n returnObj.isInfinity,\r\n createArray(returnObj.x),\r\n createArray(returnObj.y),\r\n returnObj.z ? createArray(returnObj.z) : null,\r\n returnObj.isInMontgomeryForm);\r\n\r\n returnObj.ta && (clonePoint.ta = createArray(returnObj.ta));\r\n returnObj.tb && (clonePoint.tb = createArray(returnObj.tb));\r\n\r\n return clonePoint;\r\n }\r\n\r\n returnObj = /*@static_cast(EllipticCurvePointFp)*/ {\r\n equals: function (ellipticCurvePointFp) {\r\n return equals(ellipticCurvePointFp);\r\n },\r\n copy: function (destination) {\r\n copyTo(this, destination);\r\n return;\r\n },\r\n clone: function () {\r\n return clone();\r\n }\r\n };\r\n\r\n createProperty(returnObj, \"curve\", curve, function () { return curve; }, function (val) { curve = val; });\r\n\r\n createProperty(returnObj, \"x\", x, function () { return x; }, function (val) { x = val; });\r\n createProperty(returnObj, \"y\", y, function () { return y; }, function (val) { y = val; });\r\n createProperty(returnObj, \"z\", z, function () { return z; }, function (val) { z = val; });\r\n\r\n createProperty(returnObj, \"isInMontgomeryForm\", isInMontgomeryForm, function () { return isInMontgomeryForm; }, function (val) { isInMontgomeryForm = val; });\r\n createProperty(returnObj, \"isInfinity\", isInfinity, function () { return isInfinity; }, function (val) { isInfinity = val; });\r\n createProperty(returnObj, \"isAffine\", (z === null), function () { return (z === null); });\r\n\r\n return returnObj;\r\n };\r\n\r\n var EllipticCurveOperatorFp = function (curve) {\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n\r\n // Store a reference to the curve.\r\n var m_curve = curve;\r\n\r\n var tedCurve = (curve.type === 1);\r\n\r\n var fieldElementWidth = curve.p.length;\r\n\r\n var montgomeryMultiplier = cryptoMath.MontgomeryMultiplier(curve.p);\r\n\r\n // Pre-compute and store the montgomeryized form of A, and set our\r\n // zero flag to determine whether or not we should use implementations\r\n // optimized for A = 0.\r\n var montgomerizedA = curve.a.slice();\r\n montgomeryMultiplier.convertToMontgomeryForm(montgomerizedA);\r\n\r\n var aequalsZero = cryptoMath.isZero(curve.a);\r\n\r\n var one = cryptoMath.One;\r\n\r\n var onemontgomery = createArray(fieldElementWidth);\r\n onemontgomery[0] = 1;\r\n montgomeryMultiplier.convertToMontgomeryForm(onemontgomery);\r\n\r\n var group = cryptoMath.IntegerGroup(cryptoMath.digitsToBytes(montgomeryMultiplier.m), true);\r\n\r\n // Setup temp storage.\r\n var temp0 = createArray(fieldElementWidth);\r\n var temp1 = createArray(fieldElementWidth);\r\n var temp2 = createArray(fieldElementWidth);\r\n var temp3 = createArray(fieldElementWidth);\r\n var temp4 = createArray(fieldElementWidth);\r\n var temp5 = createArray(fieldElementWidth);\r\n var temp6 = createArray(fieldElementWidth);\r\n var temp7 = createArray(fieldElementWidth);\r\n var swap0 = createArray(fieldElementWidth);\r\n\r\n // Some additional temp storage used in point conversion routines.\r\n var conversionTemp0 = createArray(fieldElementWidth);\r\n var conversionTemp1 = createArray(fieldElementWidth);\r\n var conversionTemp2 = createArray(fieldElementWidth);\r\n\r\n function modSub(left, right, result) {\r\n var resultElement = group.createElementFromInteger(0);\r\n resultElement.m_digits = result;\r\n group.subtract(\r\n group.createElementFromDigits(left),\r\n group.createElementFromDigits(right),\r\n resultElement);\r\n }\r\n\r\n function modAdd(left, right, result) {\r\n var resultElement = group.createElementFromInteger(0);\r\n resultElement.m_digits = result;\r\n group.add(\r\n group.createElementFromDigits(left),\r\n group.createElementFromDigits(right),\r\n resultElement);\r\n }\r\n\r\n function modInv(number, result) {\r\n cryptoMath.modInv(number, m_curve.p, result);\r\n }\r\n\r\n function modDivByTwo( /*@type(Digits)*/ dividend, /*@type(Digits)*/ result) {\r\n\r\n var s = dividend.length;\r\n\r\n var modulus = curve.p;\r\n\r\n // If dividend is odd, add modulus\r\n if ((dividend[0] & 0x1) === 0x1) {\r\n var carry = 0;\r\n\r\n for (var i = 0; i < s; i += 1) {\r\n carry += dividend[i] + modulus[i];\r\n result[i] = carry & cryptoMath.DIGIT_MASK;\r\n carry = (carry >>> cryptoMath.DIGIT_BITS);\r\n }\r\n\r\n // Put carry bit into position for masking in\r\n carry = carry << (cryptoMath.DIGIT_BITS - 1);\r\n\r\n // Bit shift\r\n cryptoMath.shiftRight(result, result);\r\n\r\n // Mask in the carry bit\r\n result[s - 1] |= carry;\r\n } else {\r\n // Shift directly into result\r\n cryptoMath.shiftRight(dividend, result);\r\n }\r\n\r\n }\r\n\r\n function montgomeryMultiply(left, right, result) {\r\n montgomeryMultiplier.montgomeryMultiply(\r\n left,\r\n right,\r\n result);\r\n }\r\n\r\n function montgomerySquare(left, result) {\r\n montgomeryMultiplier.montgomeryMultiply(\r\n left,\r\n left,\r\n result);\r\n }\r\n\r\n function correctInversion(digits) {\r\n /// <param name=\"digits\" type=\"Digits\"/>\r\n var results = createArray(digits.length);\r\n montgomeryMultiply(digits, montgomeryMultiplier.rCubedModm, results);\r\n for (var i = 0; i < results.length; i += 1) {\r\n digits[i] = results[i];\r\n }\r\n }\r\n\r\n function doubleAequalsNeg3(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If point = infinity then outputPoint := infinity.\r\n if (point.isInfinity) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // t1 = z^2\r\n montgomerySquare(point.z, temp1);\r\n\r\n // t4 = zy\r\n montgomeryMultiply(point.z, point.y, temp4);\r\n\r\n // t2 = x + z^2\r\n // t2 = x + t1\r\n modAdd(point.x, temp1, temp2);\r\n\r\n // t1 = x - z^2\r\n // t1 = x - t1\r\n modSub(point.x, temp1, temp1);\r\n\r\n // Zfinal = zy\r\n outputPoint.z = temp4.slice();\r\n\r\n // t3 = (x + z^2)(x - z^2)\r\n montgomeryMultiply(temp1, temp2, temp3);\r\n\r\n // t2 = (x + z^2)(x - z^2)/2\r\n modDivByTwo(temp3, temp2);\r\n\r\n // t1 = alpha = 3(x + z^2)(x - z^2)/2 \r\n modAdd(temp3, temp2, temp1);\r\n\r\n // t2 = y^2\r\n montgomerySquare(point.y, temp2);\r\n\r\n // t4 = alpha^2\r\n montgomerySquare(temp1, temp4);\r\n\r\n // t3 = beta = xy^2\r\n montgomeryMultiply(point.x, temp2, temp3);\r\n\r\n // t4 = alpha^2-beta\r\n modSub(temp4, temp3, temp4);\r\n\r\n // Xfinal = alpha^2-2beta\r\n modSub(temp4, temp3, outputPoint.x);\r\n\r\n // t4 = beta-Xfinal\r\n modSub(temp3, outputPoint.x, temp4);\r\n\r\n // t3 = y^4\r\n montgomerySquare(temp2, temp3);\r\n\r\n // t3 = y^4\r\n montgomeryMultiply(temp1, temp4, temp2);\r\n\r\n // Yfinal = alpha.(beta-Xfinal)-y^4\r\n modSub(temp2, temp3, outputPoint.y);\r\n\r\n // Finalize the flags on the output point.\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n }\r\n\r\n function doubleAequals0(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If point = infinity then outputPoint := infinity.\r\n if (point.isInfinity) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // 't3:=Y1^2;'\r\n montgomerySquare(point.y, temp3);\r\n\r\n // 't4:=X1^2;'\r\n montgomerySquare(point.x, temp4);\r\n\r\n // 't4:=3*t4;'\r\n modAdd(temp4, temp4, temp0);\r\n modAdd(temp0, temp4, temp4);\r\n\r\n // 't5:=X1*t3;'\r\n montgomeryMultiply(point.x, temp3, temp5);\r\n\r\n // 't0:=t3^2;'\r\n montgomerySquare(temp3, temp0);\r\n\r\n // 't1:=t4/2;'\r\n modDivByTwo(temp4, temp1);\r\n\r\n // 't3:=t1^2;'\r\n montgomerySquare(temp1, temp3);\r\n\r\n // 'Z_out:=Y1*Z1;'\r\n montgomeryMultiply(point.y, point.z, swap0);\r\n for (var i = 0; i < swap0.length; i += 1) {\r\n outputPoint.z[i] = swap0[i];\r\n }\r\n\r\n // 'X_out:=t3-2*t5;'\r\n modSub(temp3, temp5, outputPoint.x);\r\n modSub(outputPoint.x, temp5, outputPoint.x);\r\n\r\n // 't4:=t5-X_out;'\r\n modSub(temp5, outputPoint.x, temp4);\r\n\r\n // 't2:=t1*t4;'\r\n montgomeryMultiply(temp1, temp4, temp2);\r\n\r\n // 'Y_out:=t2-t0;'\r\n modSub(temp2, temp0, outputPoint.y);\r\n\r\n // Finalize the flags on the output point.\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n }\r\n\r\n // Given a povar P on an elliptic curve, return a table of \r\n // size 2^(w-2) filled with pre-computed values for \r\n // P, 3P, 5P, ... Etc.\r\n function generatePrecomputationTable(w, generatorPoint) {\r\n /// <summary>Given a point P on an elliptic curve, return a table of \r\n /// size 2^(w-2) filled with pre-computed values for \r\n /// P, 3P, 5P, ... Etc.</summary>\r\n /// <param name=\"w\" type=\"Array\">Window size</param>\r\n /// <param name=\"generatorPoint\" type=\"EllipticCurvePointFp\"></param>\r\n /// <returns type=\"Array\">Precomputation table</returns>\r\n\r\n var validationPoint = generatorPoint.clone();\r\n convertToStandardForm(validationPoint);\r\n if (!validatePoint(validationPoint)) {\r\n throw new Error(\"Invalid Parameter\");\r\n }\r\n\r\n // Create a Jacobian clone\r\n var pointJac = generatorPoint.clone();\r\n convertToJacobianForm(pointJac);\r\n\r\n var tablePos = [generatorPoint.clone()];\r\n\r\n // Q := P;\r\n var qJac = pointJac.clone();\r\n\r\n // Px2 = 2 * P\r\n var px2 = pointJac.clone();\r\n double(pointJac, px2);\r\n convertToAffineForm(px2);\r\n\r\n var qAff;\r\n\r\n for (var i = 1; i < Math.pow(2, w - 2) ; i++) {\r\n\r\n //Q := Q+P2;\r\n mixedAdd(qJac, px2, qJac);\r\n\r\n qAff = qJac.clone();\r\n convertToAffineForm(qAff);\r\n\r\n tablePos[i] = qAff;\r\n }\r\n\r\n return tablePos;\r\n }\r\n\r\n function double(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (typeof point === \"undefined\") {\r\n throw new Error(\"point undefined\");\r\n }\r\n if (typeof outputPoint === \"undefined\") {\r\n throw new Error(\"outputPoint undefined\");\r\n }\r\n\r\n //// if (!point.curve.equals(outputPoint.curve)) {\r\n //// throw new Error(\"point and outputPoint must be from the same curve object.\");\r\n //// }\r\n\r\n if (point.isAffine) {\r\n throw new Error(\"Given point was in Affine form. Use convertToJacobian() first.\");\r\n }\r\n\r\n if (!point.isInMontgomeryForm) {\r\n throw new Error(\"Given point must be in Montgomery form. Use montgomeryize() first.\");\r\n }\r\n\r\n\r\n\r\n\r\n // Currently we support only two curve types, those with A=-3, and\r\n // those with A=0. In the future we will implement general support.\r\n // For now we switch here, assuming that the curve was validated in\r\n // the constructor.\r\n if (aequalsZero) {\r\n doubleAequals0(point, outputPoint);\r\n } else {\r\n doubleAequalsNeg3(point, outputPoint);\r\n }\r\n\r\n }\r\n\r\n function mixedDoubleAdd(jacobianPoint, affinePoint, outputPoint) {\r\n /// <param name=\"jacobianPoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"affinePoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (jacobianPoint.isInfinity) {\r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n return;\r\n }\r\n\r\n if (affinePoint.isInfinity) {\r\n jacobianPoint.copy(outputPoint);\r\n return;\r\n }\r\n\r\n // Ok then we do the full double and add.\r\n\r\n // Note: in pseudo-code the capital X,Y,Z is Jacobian point, lower \r\n // case x, y, z is Affine point.\r\n\r\n // 't5:=Z1^ 2;'\r\n montgomerySquare(jacobianPoint.z, temp5);\r\n\r\n // 't6:=Z1*t5;'\r\n montgomeryMultiply(jacobianPoint.z, temp5, temp6);\r\n\r\n // 't4:=x2*t5;'\r\n montgomeryMultiply(affinePoint.x, temp5, temp4);\r\n\r\n // 't5:=y2*t6;'\r\n montgomeryMultiply(affinePoint.y, temp6, temp5);\r\n\r\n // 't1:=t4-X1;'\r\n modSub(temp4, jacobianPoint.x, temp1);\r\n\r\n // 't2:=t5-Y1;'\r\n modSub(temp5, jacobianPoint.y, temp2);\r\n\r\n //if t1 eq 0 then\r\n // if t2 eq 0 then\r\n // X2,Y2,Z2 := DBL(X1,Y1,Z1,prime,rr,m,RR); \r\n // return mADD(X2,Y2,Z2,x2,y2,prime,rr,m,RR);\r\n // else\r\n // return X1,Y1,Z1;\r\n // end if;\r\n //end if;\r\n\r\n // 't4:=t2^2;'\r\n montgomerySquare(temp2, temp4);\r\n\r\n // 't6:=t1^2;'\r\n montgomerySquare(temp1, temp6);\r\n\r\n // 't5:=t6*X1;'\r\n montgomeryMultiply(temp6, jacobianPoint.x, temp5);\r\n\r\n // 't0:=t1*t6;'\r\n montgomeryMultiply(temp1, temp6, temp0);\r\n\r\n // 't3:=t4-2*t5;'\r\n modSub(temp4, temp5, temp3);\r\n modSub(temp3, temp5, temp3);\r\n\r\n // 't4:=Z1*t1;'\r\n montgomeryMultiply(jacobianPoint.z, temp1, temp4);\r\n\r\n // 't3:=t3-t5;'\r\n modSub(temp3, temp5, temp3);\r\n\r\n // 't6:=t0*Y1;'\r\n montgomeryMultiply(temp0, jacobianPoint.y, temp6);\r\n\r\n // 't3:=t3-t0;'\r\n modSub(temp3, temp0, temp3);\r\n\r\n var temp3isZero = true;\r\n\r\n for (var i = 0; i < temp3.length; i++) {\r\n if (temp3[i] !== 0) {\r\n temp3isZero = false;\r\n break;\r\n }\r\n }\r\n\r\n if (temp3isZero) {\r\n for (i = 0; i < outputPoint.x.length; i++) {\r\n outputPoint.x[i] = 0;\r\n outputPoint.y[i] = 0;\r\n outputPoint.z[i] = 0;\r\n }\r\n outputPoint.y[0] = 1;\r\n return;\r\n }\r\n\r\n //if t3 eq 0 then\r\n // return 0,1,0;\r\n //end if;\r\n\r\n // 't1:=2*t6;'\r\n modAdd(temp6, temp6, temp1);\r\n\r\n // 'Zout:=t4*t3;'\r\n montgomeryMultiply(temp4, temp3, outputPoint.z);\r\n\r\n // 't4:=t2*t3;'\r\n montgomeryMultiply(temp2, temp3, temp4);\r\n\r\n // 't0:=t3^2;'\r\n montgomerySquare(temp3, temp0);\r\n\r\n // 't1:=t1+t4;'\r\n modAdd(temp1, temp4, temp1);\r\n\r\n // 't4:=t0*t5;'\r\n montgomeryMultiply(temp0, temp5, temp4);\r\n\r\n // 't7:=t1^2;'\r\n montgomerySquare(temp1, temp7);\r\n\r\n // 't4:=t0*t5;'\r\n montgomeryMultiply(temp0, temp3, temp5);\r\n\r\n // 'Xout:=t7-2*t4;'\r\n modSub(temp7, temp4, outputPoint.x);\r\n modSub(outputPoint.x, temp4, outputPoint.x);\r\n\r\n // 'Xout:=Xout-t5;'\r\n modSub(outputPoint.x, temp5, outputPoint.x);\r\n\r\n // 't3:=Xout-t4;'\r\n modSub(outputPoint.x, temp4, temp3);\r\n\r\n // 't0:=t5*t6;'\r\n montgomeryMultiply(temp5, temp6, temp0);\r\n\r\n // 't4:=t1*t3;'\r\n montgomeryMultiply(temp1, temp3, temp4);\r\n\r\n // 'Yout:=t4-t0;'\r\n modSub(temp4, temp0, outputPoint.y);\r\n\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n }\r\n\r\n function mixedAdd(jacobianPoint, affinePoint, outputPoint) {\r\n /// <param name=\"jacobianPoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"affinePoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (jacobianPoint === null) {\r\n throw new Error(\"jacobianPoint\");\r\n }\r\n\r\n if (affinePoint === null) {\r\n throw new Error(\"affinePoint\");\r\n }\r\n\r\n if (outputPoint === null) {\r\n throw new Error(\"outputPoint\");\r\n }\r\n\r\n if (jacobianPoint.curve !== affinePoint.curve ||\r\n jacobianPoint.curve !== outputPoint.curve) {\r\n throw new Error(\"All points must be from the same curve object.\");\r\n }\r\n\r\n if (jacobianPoint.isAffine) {\r\n throw new Error(\r\n \"Given jacobianPoint was in Affine form. Use ConvertToJacobian() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (!affinePoint.isAffine) {\r\n throw new Error(\r\n \"Given affinePoint was in Jacobian form. Use ConvertToAffine() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (outputPoint.isAffine) {\r\n throw new Error(\r\n \"Given jacobianPoint was in Jacobian form. Use ConvertToJacobian() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (!jacobianPoint.isInMontgomeryForm) {\r\n throw new Error(\"Jacobian point must be in Montgomery form\");\r\n }\r\n\r\n if (!affinePoint.isInMontgomeryForm) {\r\n throw new Error(\"Affine point must be in Montgomery form\");\r\n }\r\n\r\n if (jacobianPoint.isInfinity) {\r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n return;\r\n }\r\n\r\n if (affinePoint.isInfinity) {\r\n jacobianPoint.copy(outputPoint);\r\n return;\r\n }\r\n\r\n // Ok then we do the full double and add.\r\n\r\n // Note: in pseudo-code the capital X1,Y1,Z1 is Jacobian point, \r\n // lower case x2, y2, z2 is Affine point.\r\n\r\n //if (X1 eq 0) and (Y1 eq 1) and (Z1 eq 0) then \r\n // z2 := ToMontgomery(1,prime,rr,m,RR);\r\n // return x2,y2;\r\n //end if;\r\n //if (x2 eq 0) and (y2 eq 1) then \r\n // return X1,Y1,Z1;\r\n //end if;\r\n\r\n // 't1 := Z1^2;'.\r\n montgomerySquare(jacobianPoint.z, temp1);\r\n\r\n // 't2 := t1 * Z1;'\r\n montgomeryMultiply(temp1, jacobianPoint.z, temp2);\r\n\r\n // 't3 := t1 * x2;'\r\n montgomeryMultiply(temp1, affinePoint.x, temp3);\r\n\r\n // 't4 := t2 * y2;'\r\n montgomeryMultiply(temp2, affinePoint.y, temp4);\r\n\r\n // 't1 := t3 - X1;'\r\n modSub(temp3, jacobianPoint.x, temp1);\r\n\r\n // 't2 := t4 - Y1;'\r\n modSub(temp4, jacobianPoint.y, temp2);\r\n\r\n // If t1 != 0 then\r\n var i;\r\n for (i = 0; i < temp1.length; i += 1) {\r\n if (temp1[i] !== 0) {\r\n\r\n // 'Zout := Z1 * t1;'\r\n montgomeryMultiply(jacobianPoint.z, temp1, temp0);\r\n for (var j = 0; j < fieldElementWidth; j += 1) {\r\n outputPoint.z[j] = temp0[j];\r\n }\r\n\r\n // 't3 := t1^2;'\r\n montgomerySquare(temp1, temp3);\r\n\r\n // 't4 := t3 * t1;'\r\n montgomeryMultiply(temp3, temp1, temp4);\r\n\r\n // 't5 := t3 * X1;'\r\n montgomeryMultiply(temp3, jacobianPoint.x, temp5);\r\n\r\n // 't1 := 2 * t5;'\r\n modAdd(temp5, temp5, temp1);\r\n\r\n // 'Xout := t2^2;'\r\n montgomerySquare(temp2, outputPoint.x);\r\n\r\n // 'Xout := Xout - t1;'\r\n modSub(outputPoint.x, temp1, outputPoint.x);\r\n\r\n // 'Xout := Xout - t4;'\r\n modSub(outputPoint.x, temp4, outputPoint.x);\r\n\r\n // 't3 := t5 - Xout;'\r\n modSub(temp5, outputPoint.x, temp3);\r\n\r\n // 't5 := t3*t2;'\r\n montgomeryMultiply(temp2, temp3, temp5);\r\n\r\n // 't6 := t4*Y1;'\r\n montgomeryMultiply(jacobianPoint.y, temp4, temp6);\r\n\r\n // 'Yout := t5-t6;'\r\n modSub(temp5, temp6, outputPoint.y);\r\n\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n return;\r\n }\r\n }\r\n\r\n // Else if T2 != 0 then\r\n for (i = 0; i < temp2.length; i += 1) {\r\n if (temp2[i] !== 0) {\r\n // Return infinity\r\n outputPoint.isInfinity = true;\r\n outputPoint.isInMontgomeryForm = true;\r\n return;\r\n }\r\n }\r\n // Else use DBL routine to return 2(x2, y2, 1) \r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n this.double(outputPoint, outputPoint);\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n }\r\n\r\n function scalarMultiply(k, point, outputPoint, muliplyBy4) {\r\n /// <param name=\"k\" type=\"Digits\"/>\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // Special case for the point at infinity or k == 0\r\n if (point.isInfinity || cryptoMath.isZero(k)) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // Runtime check for 1 <= k < order to ensure we don't get hit by\r\n // subgroup attacks. Since k is a FixedWidth it is a positive integer\r\n // and we already checked for zero above. So it must be >= 1 already.\r\n if (cryptoMath.compareDigits(k, curve.order) >= 0) {\r\n throw new Error(\"The scalar k must be in the range 1 <= k < order.\");\r\n }\r\n\r\n // copy k so we can modify it without modifying the passed in array. \r\n k = k.slice();\r\n\r\n if (point.curve.type === 1) {\r\n\r\n var pointIsEP = (typeof point.ta !== 'undefined');\r\n\r\n if (!pointIsEP) {\r\n convertToExtendedProjective(point);\r\n }\r\n\r\n scalarMultiplyTed(k, point, outputPoint, muliplyBy4);\r\n\r\n // Convert the points back to standard if they arrived that way.\r\n if (!pointIsEP) {\r\n normalizeTed(point);\r\n }\r\n\r\n } else {\r\n\r\n var pointIsMF = point.isInMontgomeryForm,\r\n outputIsMF = outputPoint.isInMontgomeryForm,\r\n outputIsAffine = outputPoint.isAffine;\r\n\r\n // Convert parameters to Montgomory form if not already.\r\n if (!pointIsMF) {\r\n convertToMontgomeryForm(point);\r\n }\r\n\r\n if (!outputIsMF) {\r\n convertToMontgomeryForm(outputPoint);\r\n }\r\n\r\n scalarMultiplyW(k, point, outputPoint);\r\n\r\n // outputPoint returns as Jacobian - convert back to original state.\r\n if (outputIsAffine) {\r\n convertToAffineForm(outputPoint);\r\n }\r\n\r\n // Convert the points back to standard if they arrived that way.\r\n if (!pointIsMF) {\r\n convertToStandardForm(point);\r\n }\r\n\r\n if (!outputIsMF) {\r\n convertToStandardForm(outputPoint);\r\n }\r\n }\r\n\r\n return;\r\n\r\n }\r\n\r\n function scalarMultiplyW(k, point, outputPoint) {\r\n /// <param name=\"k\" type=\"Digits\"/>\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // The point should be in Montgomery form.\r\n var validationPoint = point.clone();\r\n convertToStandardForm(validationPoint);\r\n\r\n if (!validatePoint(validationPoint)) {\r\n throw new Error(\"Invalid Parameters.\");\r\n }\r\n\r\n var odd = (k[0] & 1),\r\n tempk = [];\r\n\r\n // If (odd) then k = temp else k = k\r\n modSub(point.curve.order, k, tempk);\r\n for (i = 0; i < k.length; i++) {\r\n k[i] = ((odd - 1) & (k[i] ^ tempk[i])) ^ k[i];\r\n }\r\n\r\n // Change w based on the size of the digits, \r\n // 5 is good for 256 bits, use 6 for bigger sizes.\r\n var w = (fieldElementWidth <= 8) ? 5 : 6;\r\n var m = point.curve.p.length * cryptoMath.DIGIT_BITS;\r\n var t = Math.ceil(m / (w - 1));\r\n\r\n var kDigits = cryptoMath.fixedWindowRecode(k, w, t);\r\n\r\n var Tm = generatePrecomputationTable(w, point);\r\n\r\n var position =\r\n Math.floor(Math.abs(kDigits[t]) - 1) / 2;\r\n\r\n var Q = Tm[position].clone();\r\n convertToJacobianForm(Q);\r\n\r\n for (var i = t - 1; i >= 0; i--) {\r\n\r\n for (var j = 0; j < (w - 2) ; j++) {\r\n double(Q, Q);\r\n }\r\n\r\n position = Math.floor((Math.abs(kDigits[i]) - 1) / 2);\r\n\r\n var L = tableLookupW(Tm, position);\r\n\r\n if (kDigits[i] < 0) {\r\n negate(L, L);\r\n }\r\n\r\n mixedDoubleAdd(Q, L, Q);\r\n\r\n }\r\n\r\n // if k is even, negate Q\r\n modSub(point.curve.p, Q.y, tempk);\r\n for (i = 0; i < Q.y.length; i++) {\r\n Q.y[i] = ((odd - 1) & (Q.y[i] ^ tempk[i])) ^ Q.y[i];\r\n }\r\n\r\n Q.copy(outputPoint);\r\n\r\n return;\r\n\r\n }\r\n\r\n function tableLookupW(table, index) {\r\n\r\n var pos = (index + 1) % table.length;\r\n\r\n for (var i = 0; i < table.length; i++) {\r\n var L = table[pos].clone();\r\n pos = (pos + 1) % table.length;\r\n }\r\n\r\n return L;\r\n }\r\n\r\n function negate(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\">Input point to negate.</param>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\">(x, p - y).</param>\r\n\r\n if (point !== outputPoint) {\r\n point.copy(outputPoint);\r\n }\r\n modSub(point.curve.p, point.y, outputPoint.y);\r\n }\r\n\r\n function convertToMontgomeryForm(point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (point.isInMontgomeryForm) {\r\n throw new Error(\"The given point is already in Montgomery form.\");\r\n }\r\n\r\n if (!point.isInfinity) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.x);\r\n montgomeryMultiplier.convertToMontgomeryForm(point.y);\r\n\r\n if (point.z !== null) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.z);\r\n }\r\n\r\n if (typeof point.ta !== 'undefined') {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.ta);\r\n montgomeryMultiplier.convertToMontgomeryForm(point.tb);\r\n }\r\n }\r\n\r\n point.isInMontgomeryForm = true;\r\n }\r\n\r\n function convertToStandardForm(point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (!point.isInMontgomeryForm) {\r\n throw new Error(\"The given point is not in montgomery form.\");\r\n }\r\n\r\n if (!point.isInfinity) {\r\n montgomeryMultiplier.convertToStandardForm(point.x);\r\n montgomeryMultiplier.convertToStandardForm(point.y);\r\n if (point.z !== null) {\r\n montgomeryMultiplier.convertToStandardForm(point.z);\r\n }\r\n if (typeof point.ta !== 'undefined') {\r\n montgomeryMultiplier.convertToStandardForm(point.ta);\r\n montgomeryMultiplier.convertToStandardForm(point.tb);\r\n }\r\n }\r\n\r\n point.isInMontgomeryForm = false;\r\n\r\n }\r\n\r\n function convertToAffineForm(point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (point.isInfinity) {\r\n point.z = null;\r\n setterSupport || (point.isAffine = true);\r\n return;\r\n }\r\n\r\n // DETERMINE 1/Z IN MONTGOMERY FORM --------------------------------\r\n\r\n // Call out to the basic inversion function, not the one in this class.\r\n cryptoMath.modInv(point.z, curve.p, conversionTemp2, true);\r\n\r\n if (point.isInMontgomeryForm) {\r\n montgomeryMultiply(conversionTemp2, montgomeryMultiplier.rCubedModm, conversionTemp1);\r\n var swap = conversionTemp2;\r\n conversionTemp2 = conversionTemp1;\r\n conversionTemp1 = swap;\r\n }\r\n\r\n // CONVERT TO AFFINE COORDS ----------------------------------------\r\n\r\n // 'temp0 <- 1/z^2'\r\n montgomerySquare(conversionTemp2, conversionTemp0);\r\n\r\n // Compute point.x = x / z^2 mod p\r\n // NOTE: We cannot output directly to the X digit array since it is \r\n // used for input to the multiplication routine, so we output to temp1\r\n // and copy.\r\n montgomeryMultiply(point.x, conversionTemp0, conversionTemp1);\r\n for (var i = 0; i < fieldElementWidth; i += 1) {\r\n point.x[i] = conversionTemp1[i];\r\n }\r\n\r\n // Compute point.y = y / z^3 mod p\r\n // temp1 <- y * 1/z^2.\r\n montgomeryMultiply(point.y, conversionTemp0, conversionTemp1);\r\n // 'y <- temp1 * temp2 (which == 1/z)'\r\n montgomeryMultiply(conversionTemp1, conversionTemp2, point.y);\r\n\r\n // Finally, point.z = z / z mod p = 1\r\n // We use z = NULL for this case to make detecting Jacobian form \r\n // faster (otherwise we would have to scan the entire Z digit array).\r\n point.z = null;\r\n\r\n delete point.ta;\r\n delete point.tb;\r\n\r\n setterSupport || (point.isAffine = true);\r\n }\r\n\r\n function convertToJacobianForm(point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (!point.isAffine) {\r\n throw new Error(\"The given point is not in Affine form.\");\r\n }\r\n\r\n setterSupport || (point.isAffine = false);\r\n\r\n var clonedDigits,\r\n i,\r\n zOne = point.isInMontgomeryForm ? onemontgomery : one;\r\n\r\n clonedDigits = createArray(zOne.length);\r\n for (i = 0; i < zOne.length; i += 1) {\r\n clonedDigits[i] = zOne[i];\r\n }\r\n\r\n point.z = clonedDigits;\r\n\r\n return;\r\n }\r\n\r\n function validatePoint(point) {\r\n /// <summary>\r\n /// Point validation\r\n // Check if point P=(x,y) lies on the curve and if x,y are in [0, p-1]\r\n /// </summary>\r\n\r\n if (point.isInfinity) {\r\n return false;\r\n }\r\n\r\n // Does P lie on the curve? \r\n cryptoMath.modMul(point.y, point.y, point.curve.p, temp1)\r\n\r\n cryptoMath.modMul(point.x, point.x, point.curve.p, temp2); \r\n cryptoMath.modMul(point.x, temp2, point.curve.p, temp3); \r\n modAdd(temp3, point.curve.b, temp2);\r\n cryptoMath.modMul(point.x, point.curve.a, point.curve.p, temp3);\r\n modAdd(temp2, temp3, temp2);\r\n modSub(temp1, temp2, temp1);\r\n\r\n if (cryptoMath.isZero(temp1) == false) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /// Ted functions\r\n\r\n function validatePointTed(point) {\r\n\r\n if (point.ta) {\r\n point = point.clone();\r\n normalizeTed(point);\r\n }\r\n\r\n // Does P lie on the curve?\r\n cryptoMath.modMul(point.y, point.y, point.curve.p, temp3);\r\n cryptoMath.modMul(point.x, point.x, point.curve.p, temp2);\r\n\r\n cryptoMath.add(temp2, temp3, temp1);\r\n cryptoMath.reduce(temp4, point.curve.p, temp4);\r\n\r\n cryptoMath.modMul(temp2, temp3, point.curve.p, temp4);\r\n cryptoMath.modMul(point.curve.d, temp4, point.curve.p, temp3);\r\n\r\n cryptoMath.add(temp3, [1], temp2);\r\n cryptoMath.reduce(temp2, point.curve.p, temp2);\r\n\r\n cryptoMath.subtract(temp1, temp2, temp1);\r\n cryptoMath.reduce(temp1, point.curve.p, temp1);\r\n\r\n if (cryptoMath.isZero(temp1) == false) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n function generatePrecomputationTableTed(npoints, point) {\r\n\r\n // Precomputation function, points are stored using representation (X,Y,Z,dT)\r\n // Twisted Edwards a=1 curve\r\n\r\n var Q = point.clone(),\r\n P2 = Q.clone(),\r\n T = [];\r\n\r\n // Generating P2 = 2(X1,Y1,Z1,T1a,T1b) -> (XP2,YP2,ZP2,d*TP2) and T[0] = P = (X1,Y1,Z1,T1a,T1b) \r\n T[0] = convert_R1_to_R2(point);\r\n doubleTed(Q, Q);\r\n P2 = convert_R1_to_R2(Q);\r\n Q = point.clone();\r\n\r\n for (var i = 1; i < npoints; i++) {\r\n // T[i] = 2P+T[i-1] = (2*i+1)P = (XP2,Y2P,ZP2,d*TP2) + (X_(2*i-1), Y_(2*i-1), Z_(2*i-1), Ta_(2*i-1), Tb_(2*i-1)) = (X_(2*i+1), Y_(2*i+1), Z_(2*i+1), d*T_(2*i+1))\r\n addTedExtended(P2, Q, Q);\r\n T[i] = convert_R1_to_R2(Q);\r\n }\r\n\r\n return T;\r\n }\r\n\r\n function convertToExtendedProjective(affinePoint) {\r\n affinePoint.ta = affinePoint.x.slice();\r\n affinePoint.tb = affinePoint.y.slice();\r\n affinePoint.z = [1];\r\n }\r\n\r\n function scalarMultiplyTed(k, point, outputPoint, multiplyBy4) {\r\n\r\n if (!validatePointTed(point)) {\r\n throw new Error(\"Invalid Parameter\");\r\n }\r\n\r\n var rbits = point.curve.rbits;\r\n multiplyBy4 = typeof multiplyBy4 === 'undefined' ? true : multiplyBy4;\r\n\r\n var w = (fieldElementWidth <= 8) ? 5 : 6;\r\n\r\n var t = Math.floor((rbits + (w - 2)) / (w - 1));\r\n var i, j;\r\n\r\n // copy k so we can modify it without modifying the passed in array. \r\n k = k.slice();\r\n\r\n var T = point.clone();\r\n\r\n convertToExtendedProjective(T);\r\n\r\n if (multiplyBy4) {\r\n doubleTed(T, T);\r\n doubleTed(T, T);\r\n }\r\n\r\n var precomputationTable = generatePrecomputationTableTed(1 << (w - 2), T);\r\n\r\n var odd = (k[0] & 1),\r\n tempk = [];\r\n\r\n // If (odd) then k = temp else k = k\r\n modSub(point.curve.order, k, tempk);\r\n for (i = 0; i < k.length; i++) {\r\n k[i] = ((odd - 1) & (k[i] ^ tempk[i])) ^ k[i];\r\n }\r\n\r\n var kDigits = cryptoMath.fixedWindowRecode(k, w, t);\r\n\r\n var position =\r\n Math.floor(Math.abs(kDigits[t]) - 1) / 2;\r\n\r\n var R = precomputationTable[position];\r\n\r\n T.x = R.x.slice();\r\n T.y = R.y.slice();\r\n T.z = R.z.slice();\r\n\r\n for (i = t - 1; i >= 0; i--) {\r\n\r\n for (j = 0; j < (w - 1) ; j++) {\r\n doubleTed(T, T);\r\n }\r\n\r\n position = Math.floor((Math.abs(kDigits[i]) - 1) / 2);\r\n\r\n var L = tableLookupTed(precomputationTable, position);\r\n\r\n if (kDigits[i] < 0) {\r\n modSub(point.curve.p, L.x, L.x);\r\n modSub(point.curve.p, L.td, L.td);\r\n }\r\n\r\n addTedExtended(L, T, T);\r\n }\r\n\r\n // If (odd) then T.x = temp else T.x = T.x\r\n modSub(point.curve.p, T.x, tempk);\r\n for (i = 0; i < T.x.length; i++) {\r\n T.x[i] = ((odd - 1) & (T.x[i] ^ tempk[i])) ^ T.x[i];\r\n }\r\n\r\n normalizeTed(T);\r\n\r\n outputPoint.x = T.x.slice();\r\n outputPoint.y = T.y.slice();\r\n\r\n return;\r\n\r\n }\r\n\r\n function tableLookupTed(table, index) {\r\n\r\n var pos = (index + 1) % table.length;\r\n\r\n for (var i = 0; i < table.length; i++) {\r\n var L = {\r\n x: table[pos].x.slice(),\r\n y: table[pos].y.slice(),\r\n z: table[pos].z.slice(),\r\n td: table[pos].td.slice()\r\n }\r\n pos = (pos + 1) % table.length;\r\n }\r\n\r\n return L;\r\n }\r\n\r\n function normalizeTed(point) {\r\n\r\n cryptoMath.modInv(point.z, curve.p, conversionTemp2, true);\r\n\r\n cryptoMath.modMul(point.x, conversionTemp2, curve.p, point.x);\r\n\r\n cryptoMath.modMul(point.y, conversionTemp2, curve.p, point.y);\r\n\r\n delete point.ta;\r\n delete point.tb;\r\n\r\n point.z = null;\r\n\r\n return;\r\n }\r\n\r\n function doubleTed(point, outputPoint) {\r\n\r\n if (typeof point.ta === 'undefined') {\r\n throw new Error(\"Point should be in Extended Projective form.\");\r\n }\r\n\r\n // t0 = x1^2\r\n cryptoMath.modMul(point.x, point.x, point.curve.p, temp0);\r\n\r\n // t1 = y1^2\r\n cryptoMath.modMul(point.y, point.y, point.curve.p, temp1);\r\n\r\n // Ta = z1^2 \r\n cryptoMath.modMul(point.z, point.z, point.curve.p, point.ta);\r\n\r\n\r\n // (new) Tbfinal = Y1^2-X1^2\r\n modSub(temp1, temp0, outputPoint.tb);\r\n\r\n\r\n //(new) t0 = X1^2+Y1^2 \r\n modAdd(temp0, temp1, temp0);\r\n\r\n //(ok) Ta = 2z1^2\r\n modAdd(point.ta, point.ta, point.ta);\r\n\r\n // (ok) y = 2y1\r\n modAdd(point.y, point.y, point.y);\r\n\r\n // (new) t1 = 2z1^2-(X1^2+Y1^2)\r\n modSub(point.ta, temp0, temp1);\r\n\r\n // Tafinal = 2x1y1\r\n cryptoMath.modMul(point.x, point.y, point.curve.p, outputPoint.ta);\r\n\r\n // Yfinal = (x1^2+y1^2)(y1^2-x1^2) \r\n cryptoMath.modMul(temp0, outputPoint.tb, point.curve.p, outputPoint.y);\r\n\r\n // Xfinal = 2x1y1[2z1^2-(y1^2-x1^2)]\r\n cryptoMath.modMul(temp1, outputPoint.ta, point.curve.p, outputPoint.x);\r\n\r\n // Zfinal = (y1^2-x1^2)[2z1^2-(y1^2-x1^2)] \r\n cryptoMath.modMul(temp0, temp1, point.curve.p, outputPoint.z);\r\n\r\n return;\r\n }\r\n\r\n function addTed(point1 /*Q*/, point2 /*P*/, outputPoint) {\r\n\r\n var cm = cryptoMath;\r\n\r\n var modulus = point1.curve.p;\r\n var temp1 = [];\r\n\r\n if (typeof point1.ta === 'undefined') {\r\n throw new Error(\"Point1 should be in Extended Projective form.\");\r\n }\r\n\r\n if (typeof point2.ta === 'undefined') {\r\n throw new Error(\"Point2 should be in Extended Projective form.\");\r\n }\r\n\r\n\r\n var qq = convert_R1_to_R2(point1);\r\n\r\n addTedExtended(qq, point2, outputPoint);\r\n\r\n return;\r\n }\r\n\r\n function convert_R1_to_R2(point) {\r\n\r\n var curve = point.curve,\r\n modulus = curve.p,\r\n qq = {\r\n x: point.x.slice(),\r\n y: point.y.slice(),\r\n z: point.z.slice(),\r\n td: [],\r\n curve: point.curve\r\n };\r\n\r\n cryptoMath.modMul(point.ta, point.tb, modulus, conversionTemp0);\r\n\r\n cryptoMath.modMul(conversionTemp0, curve.d, modulus, qq.td);\r\n\r\n return qq;\r\n }\r\n\r\n function addTedExtended(qq /*Q*/, point2 /*P*/, outputPoint) {\r\n\r\n // Complete point addition P = P+Q, including the cases P!=Q, P=Q, P=-Q, P=neutral and Q=neutral\r\n // Twisted Edwards a=1 curve\r\n // Inputs: P = (X1,Y1,Z1,Ta,Tb), where T1 = Ta*Tb, corresponding to extended twisted Edwards coordinates (X1:Y1:Z1:T1)\r\n // Q = (X2,Y2,Z2,dT2), corresponding to extended twisted Edwards coordinates (X2:Y2:Z2:T2)\r\n // Output: P = (X1,Y1,Z1,Ta,Tb), where T1 = Ta*Tb, corresponding to extended twisted Edwards coordinates (X1:Y1:Z1:T1)\r\n\r\n var cm = cryptoMath;\r\n var modulus = point2.curve.p;\r\n\r\n temp1 = []; temp2 = []; temp3 = [];\r\n\r\n //FP_MUL(P->Z, Q->Z, t3); // t3 = Z1*Z2 \r\n cm.modMul(point2.z, qq.z, modulus, temp3);\r\n\r\n //FP_MUL(P->Ta, P->Tb, t1); // t1 = T1 \r\n cm.modMul(point2.ta, point2.tb, modulus, temp1);\r\n\r\n //FP_ADD(P->X, P->Y, P->Ta); // Ta = (X1+Y1) \r\n modAdd(point2.x, point2.y, point2.ta);\r\n\r\n //FP_MUL(t1, Q->Td, t2); // t2 = dT1*T2 \r\n cm.modMul(temp1, qq.td, modulus, temp2);\r\n\r\n //FP_ADD(Q->X, Q->Y, P->Tb); // Tb = (X2+Y2) \r\n modAdd(qq.x, qq.y, point2.tb);\r\n\r\n //FP_SUB(t3, t2, t1); // t1 = theta\r\n modSub(temp3, temp2, temp1);\r\n\r\n //FP_ADD(t3, t2, t3); // t3 = alpha\r\n modAdd(temp3, temp2, temp3);\r\n\r\n //FP_MUL(P->Ta, P->Tb, t2); // t2 = (X1+Y1)(X2+Y2)\r\n cm.modMul(point2.ta, point2.tb, modulus, temp2);\r\n\r\n //FP_MUL(P->X, Q->X, P->Z); // Z = X1*X2\r\n cm.modMul(point2.x, qq.x, modulus, point2.z);\r\n\r\n //FP_MUL(P->Y, Q->Y, P->X); // X = Y1*Y2\r\n cm.modMul(point2.y, qq.y, modulus, point2.x);\r\n\r\n //FP_SUB(t2, P->Z, t2); \r\n modSub(temp2, point2.z, temp2);\r\n\r\n //FP_SUB(P->X, P->Z, P->Ta); // Tafinal = omega = Y1*Y2-X1*X2 \r\n modSub(point2.x, point2.z, outputPoint.ta);\r\n\r\n //FP_SUB(t2, P->X, P->Tb); // Tbfinal = beta = (X1+Y1)(X2+Y2)-X1*X2-Y1*Y2\r\n modSub(temp2, point2.x, outputPoint.tb);\r\n\r\n //FP_MUL(P->Ta, t3, P->Y); // Yfinal = alpha*omega\r\n cm.modMul(outputPoint.ta, temp3, modulus, outputPoint.y);\r\n\r\n //FP_MUL(P->Tb, t1, P->X); // Xfinal = beta*theta\r\n cm.modMul(outputPoint.tb, temp1, modulus, outputPoint.x);\r\n\r\n //FP_MUL(t3, t1, P->Z); // Zfinal = theta*alpha\r\n cm.modMul(temp3, temp1, modulus, outputPoint.z);\r\n\r\n return;\r\n }\r\n\r\n function convertTedToWeierstrass(tedPoint, wPoint) {\r\n /// <summary></summary>\r\n /// <param name=\"tedPoint\" type=\"\"></param>\r\n /// <param name=\"outputPoint\" type=\"\"></param>\r\n\r\n var a = tedPoint.curve.a.slice(),\r\n d = tedPoint.curve.d.slice(),\r\n p = tedPoint.curve.p,\r\n modMul = cryptoMath.modMul,\r\n modInv = cryptoMath.modInv;\r\n\r\n // t1 = 5\r\n temp1 = [5];\r\n\r\n // t2 = 5a\r\n modMul(a, temp1, p, temp2);\r\n\r\n // t2 = 5a-d\r\n modSub(temp2, d, temp2);\r\n\r\n // t3 = 5d\r\n modMul(d, temp1, p, temp3);\r\n\r\n // t1 = a-5d\r\n modSub(a, temp3, temp1);\r\n\r\n // t3 = yTE*(a-5d)\r\n modMul(tedPoint.y, temp1, p, temp3);\r\n\r\n // t2 = (5a-d) + yTE*(a-5d)\r\n modAdd(temp3, temp2, temp2);\r\n\r\n // t1 = 1\r\n temp1 = [1];\r\n\r\n // t3 = 1-yTE\r\n modSub(temp1, tedPoint.y, temp3);\r\n\r\n // t1 = 12\r\n temp1 = [12];\r\n\r\n // t4 = 12(1-yTE)\r\n modMul(temp1, temp3, p, temp4);\r\n\r\n // t4 = 1/12(1-yTE)\r\n modInv(temp4, p, temp4, true);\r\n\r\n // t1 = xTE*(1-yTE)\r\n modMul(tedPoint.x, temp3, p, temp1);\r\n\r\n // t3 = 2xTE*(1-yTE)\r\n modAdd(temp1, temp1, temp3);\r\n\r\n // t3 = 4xTE*(1-yTE)\r\n modAdd(temp3, temp3, temp3);\r\n\r\n // t3 = 1/4xTE*(1-yTE)\r\n modInv(temp3, p, temp3, true);\r\n\r\n // Xfinal = ((5a-d) + yTE*(a-5d))/12(1-yTE)\r\n modMul(temp4, temp2, p, wPoint.x);\r\n\r\n // t1 = 1\r\n temp1 = [1];\r\n\r\n // t1 = yTE+1\r\n modAdd(tedPoint.y, temp1, temp1);\r\n\r\n // t2 = a-d\r\n modSub(a, d, temp2);\r\n\r\n // t4 = (a-d)*(yTE+1)\r\n modMul(temp1, temp2, p, temp4);\r\n\r\n // Yfinal = ((a-d)*(yTE+1))/4xTE*(1-yTE)\r\n modMul(temp4, temp3, p, wPoint.y);\r\n\r\n return;\r\n }\r\n\r\n function convertWeierstrassToTed(wPoint, tedPoint) {\r\n\r\n var a = tedPoint.curve.a.slice(),\r\n d = tedPoint.curve.d.slice(),\r\n p = tedPoint.curve.p,\r\n modMul = cryptoMath.modMul,\r\n modInv = cryptoMath.modInv;\r\n\r\n modAdd(wPoint.x, wPoint.x, temp1);\r\n\r\n modAdd(wPoint.x, temp1, temp1);\r\n\r\n // t1 = 6xW\r\n modAdd(temp1, temp1, temp1);\r\n\r\n // t2 = 6xW - a\r\n modSub(temp1, a, temp2);\r\n\r\n // t2 = 6xW - a - d\r\n modSub(temp2, d, temp2);\r\n\r\n modAdd(wPoint.y, wPoint.y, temp3);\r\n\r\n modAdd(wPoint.y, temp3, temp3);\r\n\r\n // t3 = 6yW\r\n modAdd(temp3, temp3, temp3);\r\n\r\n // t3 = 1/6yW\r\n modInv(temp3, p, temp3, true);\r\n\r\n // Xfinal = (6xW - a - d)/6yW\r\n modMul(temp2, temp3, p, tedPoint.x);\r\n\r\n // t1 = 12xW\r\n modAdd(temp1, temp1, temp1);\r\n\r\n // t2 = 12xW + d\r\n modAdd(temp1, d, temp2);\r\n\r\n // t1 = 12xW + a\r\n modAdd(temp1, a, temp1);\r\n\r\n modAdd(a, a, temp3);\r\n\r\n // t2 = 12xW + d - 2a \r\n modSub(temp2, temp3, temp2);\r\n\r\n // t2 = 12xW + d - 4a \r\n modSub(temp2, temp3, temp2);\r\n\r\n // t2 = 12xW + d - 5a \r\n modSub(temp2, a, temp2);\r\n\r\n modAdd(d, d, temp3);\r\n\r\n // t1 = 12xW + a - 2d \r\n modSub(temp1, temp3, temp1);\r\n\r\n // t1 = 12xW + a - 4d \r\n modSub(temp1, temp3, temp1);\r\n\r\n // t1 = 12xW + a - 5d \r\n modSub(temp1, d, temp1);\r\n\r\n // t1 = 1/(12xW + a - 5d)\r\n modInv(temp1, p, temp1, true);\r\n\r\n // Yfinal = (12xW + d - 5a)/(12xW + a - 5d)\r\n modMul(temp1, temp2, p, tedPoint.y);\r\n\r\n return;\r\n }\r\n\r\n var methods = {\r\n\r\n convertToMontgomeryForm: convertToMontgomeryForm,\r\n\r\n convertToStandardForm: convertToStandardForm,\r\n\r\n convertToAffineForm: convertToAffineForm,\r\n\r\n convertToJacobianForm: convertToJacobianForm,\r\n\r\n // For tests\r\n generatePrecomputationTable: function (w, generatorPoint) {\r\n /// <param name=\"w\" type=\"Number\"/>\r\n /// <param name=\"generatorPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n return generatePrecomputationTable(w, generatorPoint);\r\n }\r\n\r\n };\r\n\r\n if (tedCurve) {\r\n\r\n methods.double = doubleTed;\r\n methods.add = addTed;\r\n methods.scalarMultiply = scalarMultiply;\r\n methods.normalize = normalizeTed;\r\n methods.convertToExtendedProjective = convertToExtendedProjective;\r\n methods.convertTedToWeierstrass = convertTedToWeierstrass;\r\n methods.convertWeierstrassToTed = convertWeierstrassToTed;\r\n methods.generatePrecomputationTable = function (w, generatorPoint) {\r\n /// <param name=\"w\" type=\"Number\"/>\r\n /// <param name=\"generatorPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n return generatePrecomputationTableTed(w, generatorPoint);\r\n };\r\n } else {\r\n\r\n methods.double = double;\r\n methods.mixedDoubleAdd = mixedDoubleAdd;\r\n methods.mixedAdd = mixedAdd;\r\n methods.scalarMultiply = scalarMultiply;\r\n methods.negate = negate;\r\n }\r\n\r\n return methods;\r\n\r\n };\r\n\r\n var sec1EncodingFp = function () {\r\n return {\r\n encodePoint: function (/*@type(EllipticCurvePointFp)*/ point) {\r\n /// <summary>Encode an EC point without compression.\r\n /// This function encodes a given points into a bytes array containing 0x04 | X | Y, where X and Y are big endian bytes of x and y coordinates.</summary>\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\">Input EC point to encode.</param>\r\n /// <returns type=\"Array\">A bytes array containing 0x04 | X | Y, where X and Y are big endian encoded x and y coordinates.</returns>\r\n\r\n if (!point) {\r\n throw new Error(\"point\");\r\n }\r\n\r\n if (!point.isAffine) {\r\n throw new Error(\"Point must be in affine form.\");\r\n }\r\n\r\n if (point.isInMontgomeryForm) {\r\n throw new Error(\"Point must not be in Montgomery form.\");\r\n }\r\n\r\n if (point.isInfinity) {\r\n return createArray(1); /* [0] */\r\n } else {\r\n var xOctetString = cryptoMath.digitsToBytes(point.x);\r\n var yOctetString = cryptoMath.digitsToBytes(point.y);\r\n var pOctetString = cryptoMath.digitsToBytes(point.curve.p); // just to get byte length of p\r\n var mlen = pOctetString.length;\r\n if (mlen < xOctetString.length || mlen < yOctetString.length) {\r\n throw new Error(\"Point coordinate(s) are bigger than the field order.\");\r\n }\r\n var output = createArray(2 * mlen + 1); // for encoded x and y\r\n\r\n output[0] = 0x04;\r\n var offset = mlen - xOctetString.length;\r\n for (var i = 0; i < xOctetString.length; i++) {\r\n output[i + 1 + offset] = xOctetString[i];\r\n }\r\n offset = mlen - yOctetString.length;\r\n for (i = 0; i < yOctetString.length; i++) {\r\n output[mlen + i + 1 + offset] = yOctetString[i];\r\n }\r\n\r\n return output;\r\n }\r\n\r\n },\r\n decodePoint: function (encoded, curve) {\r\n /// <param name=\"encoded\" type=\"Digits\"/>\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n\r\n if (encoded.length < 1) {\r\n throw new Error(\"Byte array must have non-zero length\");\r\n }\r\n\r\n var pOctetString = cryptoMath.digitsToBytes(curve.p);\r\n var mlen = pOctetString.length;\r\n\r\n if (encoded[0] === 0x0 && encoded.length === 1) {\r\n return curve.createPointAtInfinity();\r\n } else if (encoded[0] === 0x04 && encoded.length === 1 + 2 * mlen) {\r\n // Standard encoding.\r\n // Each point is a big endian string of bytes of length.\r\n // 'ceiling(log_2(Q)/8)'\r\n // Zero-padded and representing the magnitude of the coordinate.\r\n var xbytes = createArray(mlen);\r\n var ybytes = createArray(mlen);\r\n\r\n for (var i = 0; i < mlen; i++) {\r\n xbytes[i] = encoded[i + 1];\r\n ybytes[i] = encoded[mlen + i + 1];\r\n }\r\n\r\n var x = cryptoMath.bytesToDigits(xbytes);\r\n var y = cryptoMath.bytesToDigits(ybytes);\r\n\r\n return EllipticCurvePointFp(curve, false, x, y);\r\n } else {\r\n // We don't support other encoding features such as compression\r\n throw new Error(\"Unsupported encoding format\");\r\n }\r\n }\r\n };\r\n };\r\n\r\n var ModularSquareRootSolver = function (modulus) {\r\n /// <param name=\"modulus\" type=\"Digits\"/>\r\n\r\n // The modulus we are going to use.\r\n var p = modulus;\r\n\r\n // Special-K not just for breakfast anymore! This is k = (p-3)/4 + 1\r\n // which is used for NIST curves (or any curve of with P= 3 mod 4).\r\n // This field is null if p is not of the special form, or k if it is.\r\n var specialK = [];\r\n\r\n if (typeof modulus === \"undefined\") {\r\n throw new Error(\"modulus\");\r\n }\r\n\r\n // Support for odd moduli, only.\r\n if (cryptoMath.isEven(modulus)) {\r\n throw new Error(\"Only odd moduli are supported\");\r\n }\r\n\r\n // A montgomery multiplier object for doing fast squaring.\r\n var mul = cryptoMath.MontgomeryMultiplier(p);\r\n\r\n // 'p === 3 mod 4' then we can use the special super fast version.\r\n // Otherwise we must use the slower general case algorithm.\r\n if (p[0] % 4 === 3) {\r\n // 'special k = (p + 1) / 4'\r\n cryptoMath.add(p, cryptoMath.One, specialK);\r\n cryptoMath.shiftRight(specialK, specialK, 2);\r\n } else {\r\n specialK = null;\r\n }\r\n\r\n // Temp storage\r\n var temp0 = new Array(p.length);\r\n var temp1 = new Array(p.length);\r\n\r\n function squareRootNistCurves(a) {\r\n /// <summary>Given a number a, returns a solution x to x^2 = a (mod p).</summary>\r\n /// <param name=\"a\" type=\"Array\">An integer a.</param>\r\n /// <returns type=\"Array\">The square root of the number a modulo p, if it exists,\r\n /// otherwise null.</returns>\r\n\r\n // beta = a^k mod n where k=(n+1)/4 for n == 3 mod 4, thus a^(1/2) mod n\r\n var beta = cryptoMath.intToDigits(0, 16);\r\n mul.modExp(a, specialK, beta);\r\n\r\n // Okay now we gotta double check by squaring.\r\n var aPrime = [0];\r\n cryptoMath.modMul(beta, beta, mul.m, aPrime);\r\n\r\n // If a != x^2 then a has no square root\r\n if (cryptoMath.compareDigits(a, aPrime) !== 0) {\r\n return null;\r\n }\r\n\r\n return beta;\r\n }\r\n\r\n var publicMethods = {\r\n\r\n squareRoot: function (a) {\r\n if (specialK !== null) {\r\n // Use the special case fast code\r\n return squareRootNistCurves(a);\r\n } else {\r\n // Use the general case code\r\n throw new Error(\"GeneralCase not supported.\");\r\n }\r\n },\r\n\r\n // Given an integer a, this routine returns the Jacobi symbol (a/p), \r\n // where p is the modulus given in the constructor, which for p an \r\n // odd prime is also the Legendre symbol. From \"Prime Numbers, A \r\n // Computational Perspective\" by Crandall and Pomerance, alg. 2.3.5.\r\n // The Legendre symbol is defined as:\r\n // 0 if a === 0 mod p.\r\n // 1 if a is a quadratic residue (mod p).\r\n // -1 if a is a quadratic non-reside (mod p).\r\n jacobiSymbol: function (a) {\r\n /// <param name=\"a\">An integer a.</param>\r\n\r\n var modEightMask = 0x7,\r\n modFourMask = 0x3,\r\n aPrime,\r\n pPrime;\r\n\r\n // Clone our inputs, we are going to destroy them\r\n aPrime = a.slice();\r\n pPrime = p.slice();\r\n\r\n // 'a = a mod p'.\r\n cryptoMath.reduce(aPrime, pPrime, aPrime, temp0, temp1);\r\n\r\n // 't = 1'\r\n var t = 1;\r\n\r\n // While (a != 0)\r\n while (!cryptoMath.isZero(aPrime)) {\r\n // While a is even\r\n while (cryptoMath.isEven(aPrime)) {\r\n // 'a <- a / 2'\r\n cryptoMath.shiftRight(aPrime, aPrime);\r\n\r\n // If (p mod 8 in {3,5}) t = -t;\r\n var pMod8 = (pPrime[0] & modEightMask);\r\n if (pMod8 === 3 || pMod8 === 5) {\r\n t = -t;\r\n }\r\n }\r\n\r\n // Swap variables\r\n // (a, p) = (p, a).\r\n var tmp = aPrime;\r\n aPrime = pPrime;\r\n pPrime = tmp;\r\n\r\n // If (a === p === 3 (mod 4)) t = -t;\r\n var aMod4 = (aPrime[0] & modFourMask);\r\n var pMod4 = (pPrime[0] & modFourMask);\r\n if (aMod4 === 3 && pMod4 === 3) {\r\n t = -t;\r\n }\r\n\r\n // 'a = a mod p'\r\n cryptoMath.reduce(aPrime, pPrime, aPrime, temp0, temp1);\r\n }\r\n\r\n // If (p == 1) return t else return 0\r\n if (cryptoMath.compareDigits(pPrime, cryptoMath.One) === 0) {\r\n return t;\r\n } else {\r\n return 0;\r\n }\r\n }\r\n\r\n };\r\n\r\n return publicMethods;\r\n };\r\n\r\n var curvesInternal = {};\r\n\r\n var createCurve = function (curveName) {\r\n\r\n var curveData = curvesInternal[curveName.toUpperCase()];\r\n\r\n if (!curveData) {\r\n throw new Error(curveName + \" Unsupported curve.\");\r\n }\r\n\r\n if (curveData.type === 0) {\r\n return createWeierstrassCurve(curveData);\r\n }\r\n\r\n if (curveData.type === 1) {\r\n return createTedCurve(curveData);\r\n }\r\n\r\n throw new Error(curveName + \" Unsupported curve type.\");\r\n };\r\n\r\n return {\r\n createCurve: createCurve,\r\n curves: curvesInternal,\r\n sec1EncodingFp: sec1EncodingFp,\r\n EllipticCurvePointFp: EllipticCurvePointFp,\r\n EllipticCurveOperatorFp: EllipticCurveOperatorFp,\r\n ModularSquareRootSolver: ModularSquareRootSolver\r\n };\r\n}",
"function dollarize(expr)\n{\n return \"$\" + format(expr,2);\n}",
"function MsrcryptoECC() {\r\n /// <summary>Elliptic Curve Cryptography (ECC) funcions.</summary>\r\n\r\n // Create an array, mimics the constructors for typed arrays.\r\n function createArray(/*@dynamic*/parameter) {\r\n var i, array = null;\r\n if (!arguments.length || typeof arguments[0] === \"number\") {\r\n // A number.\r\n array = [];\r\n for (i = 0; i < parameter; i += 1) {\r\n array[i] = 0;\r\n }\r\n } else if (typeof arguments[0] === \"object\") {\r\n // An array or other index-able object\r\n array = [];\r\n for (i = 0; i < parameter.length; i += 1) {\r\n array[i] = parameter[i];\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n var btd = cryptoMath.bytesToDigits;\r\n var utils = msrcryptoUtilities;\r\n\r\n var EllipticCurveFp = function (p1, a1, b1, order, gx, gy) {\r\n /// <param name=\"p1\" type=\"Digits\"/>\r\n /// <param name=\"a1\" type=\"Digits\"/>\r\n /// <param name=\"b1\" type=\"Digits\"/>\r\n /// <param name=\"order\" type=\"Digits\"/>\r\n /// <param name=\"gx\" type=\"Digits\"/>\r\n /// <param name=\"gy\" type=\"Digits\"/>\r\n /// <returns type=\"EllipticCurveFp\"/>\r\n\r\n var fieldStorageBitLength = p1.length;\r\n\r\n var generator = EllipticCurvePointFp(this, false, gx, gy, null, false);\r\n\r\n return {\r\n p: p1, // field prime\r\n a: a1, // Weierstrass coefficient a\r\n b: b1, // Weierstrass coefficient b\r\n order: order, // EC group order\r\n generator: generator, // EC group generator\r\n allocatePointStorage: function () {\r\n return EllipticCurvePointFp(\r\n this,\r\n false,\r\n cryptoMath.intToDigits(0, fieldStorageBitLength),\r\n cryptoMath.intToDigits(0, fieldStorageBitLength)\r\n );\r\n },\r\n createPointAtInfinity: function () {\r\n return EllipticCurvePointFp(\r\n this,\r\n true,\r\n cryptoMath.intToDigits(0, fieldStorageBitLength),\r\n cryptoMath.intToDigits(0, fieldStorageBitLength)\r\n );\r\n }\r\n };\r\n };\r\n var createANeg3Curve = function (p, b, order, gx, gy) {\r\n /// <param name=\"p\" type=\"Digits\"/>\r\n /// <param name=\"b\" type=\"Digits\"/>\r\n /// <param name=\"order\" type=\"Digits\"/>\r\n /// <param name=\"gx\" type=\"Digits\"/>\r\n /// <param name=\"gy\" type=\"Digits\"/>\r\n\r\n var a = cryptoMath.intToDigits(3, p.length);\r\n cryptoMath.subtract(p, a, a);\r\n var curve = EllipticCurveFp(p, a, b, order, gx, gy);\r\n curve.generator.curve = curve;\r\n return curve;\r\n };\r\n\r\n var curvesData = {\r\n \"256\": { size: 32, data: \"/////wAAAAEAAAAAAAAAAAAAAAD///////////////9axjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgS/////8AAAAA//////////+85vqtpxeehPO5ysL8YyVRaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9Q==\"},\r\n \"384\": { size: 48, data: \"//////////////////////////////////////////7/////AAAAAAAAAAD/////szEvp+I+5+SYjgVr4/gtGRgdnG7+gUESAxQIj1ATh1rGVjmNii7RnSqFyO3T7Crv////////////////////////////////x2NNgfQ3Ld9YGg2ySLCneuzsGWrMxSlzqofKIr6LBTeOscce8yCtdG4dO2KLp5uYWfdB4IJUKjhVAvJdv1UpbDpUXjhydgq3NhfeSpYmLG9dnpi/kpLcKfj0Hb0omhR86doxE7XwuMAKYLHOHX6BnXpDHXyQ6g5f\"},\r\n \"521\": { size: 32, data: \"Af//////////////////////////////////////////////////////////////////////////////////////UZU+uWGOHJofkpohoLaFQO6i2nJbmbMV87i0iZGO8QnhVhk5Uex+k3sWUsC9O7G/BzVz34g9LDTx70Uf1GtQPwAB///////////////////////////////////////////6UYaHg78vlmt/zAFI9wml0Du1ybiJnEeuu2+3HpE4ZAnGhY4GtwQE6c2ePstmI5W0QpxkgTkFP7Uh+CivYGtNPbqhS1537+dZKP4dwSei/6jeM0izwYVqQpv5fn4xwuW9ZgEYOSlqeJo7wARcil+0LH0b2Zj1RElXm0RoF6+9Fyc+ZiyX7nKZXvQmQMVQuQE/rQdhNTxwhqJywkCIvpR2n9FmUA==\" }\r\n };\r\n\r\n var createP256 = function () {\r\n return createPCurve(\"256\");\r\n };\r\n\r\n var createP384 = function () {\r\n return createPCurve(\"384\");\r\n };\r\n\r\n var createP521 = function () {\r\n return createPCurve(\"521\");\r\n };\r\n\r\n var createPCurve = function (curveSize) {\r\n\r\n var cd = utils.unpackData(curvesData[curveSize].data, curvesData[curveSize].size);\r\n\r\n var newCurve = createANeg3Curve(\r\n btd(cd[0]), // P\r\n btd(cd[1]), // B\r\n btd(cd[2]), // Order\r\n btd(cd[3]), // gX\r\n btd(cd[4]) // gy\r\n );\r\n\r\n newCurve.name = \"P-\" + curveSize;\r\n\r\n return newCurve;\r\n\r\n };\r\n\r\n var createBN254 = function () {\r\n\r\n return EllipticCurveFp(\r\n cryptoMath.stringToDigits(\"16798108731015832284940804142231733909889187121439069848933715426072753864723\", 10), // 'p'\r\n cryptoMath.intToDigits(0, 16), // 'a'\r\n cryptoMath.intToDigits(2, 16), // 'b'\r\n cryptoMath.stringToDigits(\"16798108731015832284940804142231733909759579603404752749028378864165570215949\", 10), // 'order'\r\n cryptoMath.stringToDigits(\"16798108731015832284940804142231733909889187121439069848933715426072753864722\", 10), // 'gx = -1'\r\n cryptoMath.intToDigits(1, 16) // 'gy = 1'\r\n );\r\n };\r\n var EllipticCurvePointFp = function (curve, isInfinity, x, y, z, isInMontgomeryForm) {\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n /// <param name=\"isInfinity\" type=\"Boolean\"/>\r\n /// <param name=\"x\" type=\"Digits\"/>\r\n /// <param name=\"y\" type=\"Digits\"/>\r\n /// <param name=\"z\" type=\"Digits\" optional=\"true\"/>\r\n /// <param name=\"isInMontgomeryForm\" type=\"Boolean\" optional=\"true\"/>\r\n /// <returns type=\"EllipticCurvePointFp\"/>\r\n\r\n var returnObj;\r\n\r\n // 'optional' parameters\r\n if (typeof z === \"undefined\") {\r\n z = null;\r\n }\r\n\r\n if (typeof isInMontgomeryForm === \"undefined\") {\r\n isInMontgomeryForm = false;\r\n }\r\n\r\n function equals(/*@type(EllipticCurvePointFp)*/ellipticCurvePointFp) {\r\n /// <param name=\"ellipticCurvePointFp\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If null\r\n if (!ellipticCurvePointFp) {\r\n return false;\r\n }\r\n\r\n // Infinity == infinity\r\n if (returnObj.isInfinity && ellipticCurvePointFp.isInfinity) {\r\n return true;\r\n }\r\n\r\n // Otherwise its member-wise comparison\r\n\r\n if (returnObj.z === null && ellipticCurvePointFp.z !== null) {\r\n return false;\r\n }\r\n\r\n if (returnObj.z !== null && ellipticCurvePointFp.z === null) {\r\n return false;\r\n }\r\n\r\n if (returnObj.z === null) {\r\n return (cryptoMath.sequenceEqual(returnObj.x, ellipticCurvePointFp.x) &&\r\n cryptoMath.sequenceEqual(returnObj.y, ellipticCurvePointFp.y) &&\r\n returnObj.isInMontgomeryForm === ellipticCurvePointFp.isInMontgomeryForm);\r\n }\r\n\r\n return (cryptoMath.sequenceEqual(returnObj.x, ellipticCurvePointFp.x) &&\r\n cryptoMath.sequenceEqual(returnObj.y, ellipticCurvePointFp.y) &&\r\n cryptoMath.sequenceEqual(returnObj.z, ellipticCurvePointFp.z) &&\r\n returnObj.isInMontgomeryForm === ellipticCurvePointFp.isInMontgomeryForm);\r\n }\r\n\r\n function copyTo(/*@type(EllipticCurvePointFp)*/ source, /*@type(EllipticCurvePointFp)*/ destination) {\r\n /// <param name=\"source\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"destination\" type=\"EllipticCurvePointFp\"/>\r\n\r\n destination.curve = source.curve;\r\n destination.x = source.x.slice();\r\n destination.y = source.y.slice();\r\n\r\n if (source.z !== null) {\r\n destination.z = source.z.slice();\r\n } else {\r\n destination.z = null;\r\n }\r\n\r\n setterSupport || (destination.isAffine = source.isAffine);\r\n destination.isInMontgomeryForm = source.isInMontgomeryForm;\r\n destination.isInfinity = source.isInfinity;\r\n\r\n if (!destination.equals(source)) {\r\n throw new Error(\"Instances should be equal.\");\r\n }\r\n\r\n }\r\n\r\n function clone() {\r\n if (returnObj.z === null) { // isAffine\r\n\r\n return EllipticCurvePointFp(\r\n returnObj.curve,\r\n returnObj.isInfinity,\r\n createArray(returnObj.x),\r\n createArray(returnObj.y),\r\n null,\r\n returnObj.isInMontgomeryForm);\r\n } else {\r\n\r\n return EllipticCurvePointFp(\r\n returnObj.curve,\r\n returnObj.isInfinity,\r\n createArray(returnObj.x),\r\n createArray(returnObj.y),\r\n createArray(returnObj.z),\r\n returnObj.isInMontgomeryForm);\r\n }\r\n }\r\n\r\n returnObj = /*@static_cast(EllipticCurvePointFp)*/ {\r\n equals: function (ellipticCurvePointFp) {\r\n return equals(ellipticCurvePointFp);\r\n },\r\n copy: function (destination) {\r\n copyTo(this, destination);\r\n return;\r\n },\r\n clone: function () {\r\n return clone();\r\n }\r\n };\r\n\r\n createProperty(returnObj, \"curve\", curve, function () { return curve; }, function (val) { curve = val; });\r\n\r\n createProperty(returnObj, \"x\", x, function () { return x; }, function (val) { x = val; });\r\n createProperty(returnObj, \"y\", y, function () { return y; }, function (val) { y = val; });\r\n createProperty(returnObj, \"z\", z, function () { return z; }, function (val) { z = val; });\r\n\r\n createProperty(returnObj, \"isInMontgomeryForm\", isInMontgomeryForm, function () { return isInMontgomeryForm; }, function (val) { isInMontgomeryForm = val; });\r\n createProperty(returnObj, \"isInfinity\", isInfinity, function () { return isInfinity; }, function (val) { isInfinity = val; });\r\n createProperty(returnObj, \"isAffine\", (z === null), function () { return (z === null); });\r\n\r\n return returnObj;\r\n };\r\n var EllipticCurveOperatorFp = function (/*@type(EllipticCurveFp)*/curve) {\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n\r\n // Store a reference to the curve.\r\n var m_curve = curve;\r\n\r\n var fieldElementWidth = curve.p.length;\r\n\r\n var montgomeryMultiplier = cryptoMath.MontgomeryMultiplier(curve.p);\r\n\r\n // Pre-compute and store the montgomeryized form of A, and set our\r\n // zero flag to determine whether or not we should use implementations\r\n // optimized for A = 0.\r\n var montgomerizedA = curve.a.slice();\r\n montgomeryMultiplier.convertToMontgomeryForm(montgomerizedA);\r\n\r\n var aequalsZero = cryptoMath.isZero(curve.a);\r\n\r\n var one = cryptoMath.One;\r\n\r\n var onemontgomery = createArray(fieldElementWidth);\r\n onemontgomery[0] = 1;\r\n montgomeryMultiplier.convertToMontgomeryForm(onemontgomery);\r\n\r\n var group = cryptoMath.IntegerGroup(cryptoMath.digitsToBytes(montgomeryMultiplier.m), true);\r\n\r\n // Setup temp storage.\r\n var temp0 = createArray(fieldElementWidth);\r\n var temp1 = createArray(fieldElementWidth);\r\n var temp2 = createArray(fieldElementWidth);\r\n var temp3 = createArray(fieldElementWidth);\r\n var temp4 = createArray(fieldElementWidth);\r\n var temp5 = createArray(fieldElementWidth);\r\n var temp6 = createArray(fieldElementWidth);\r\n var temp7 = createArray(fieldElementWidth);\r\n var swap0 = createArray(fieldElementWidth);\r\n\r\n // Some additional temp storage used in point conversion routines.\r\n var conversionTemp0 = createArray(fieldElementWidth);\r\n var conversionTemp1 = createArray(fieldElementWidth);\r\n var conversionTemp2 = createArray(fieldElementWidth);\r\n\r\n function modSub(left, right, result) {\r\n var resultElement = group.createElementFromInteger(0);\r\n resultElement.m_digits = result;\r\n group.subtract(\r\n group.createElementFromDigits(left),\r\n group.createElementFromDigits(right),\r\n resultElement);\r\n }\r\n\r\n function modAdd(left, right, result) {\r\n var resultElement = group.createElementFromInteger(0);\r\n resultElement.m_digits = result;\r\n group.add(\r\n group.createElementFromDigits(left),\r\n group.createElementFromDigits(right),\r\n resultElement);\r\n }\r\n\r\n function modInv(number, result) {\r\n cryptoMath.modInv(number, m_curve.p, result);\r\n }\r\n\r\n function modDivByTwo( /*@type(Digits)*/ dividend, /*@type(Digits)*/ result) {\r\n\r\n var s = dividend.length;\r\n\r\n var modulus = curve.p;\r\n\r\n // If dividend is odd, add modulus\r\n if ((dividend[0] & 0x1) === 0x1) {\r\n var carry = 0;\r\n\r\n for (var i = 0; i < s; i += 1) {\r\n carry += dividend[i] + modulus[i];\r\n result[i] = carry & cryptoMath.DIGIT_MASK;\r\n carry = (carry >>> cryptoMath.DIGIT_BITS);\r\n }\r\n\r\n // Put carry bit into position for masking in\r\n carry = carry << (cryptoMath.DIGIT_BITS - 1);\r\n\r\n // Bit shift\r\n cryptoMath.shiftRight(result, result);\r\n\r\n // Mask in the carry bit\r\n result[s - 1] |= carry;\r\n } else {\r\n // Shift directly into result\r\n cryptoMath.shiftRight(dividend, result);\r\n }\r\n\r\n }\r\n\r\n function montgomeryMultiply(left, right, result) {\r\n montgomeryMultiplier.montgomeryMultiply(\r\n left,\r\n right,\r\n result);\r\n }\r\n\r\n function montgomerySquare(left, result) {\r\n montgomeryMultiplier.montgomeryMultiply(\r\n left,\r\n left,\r\n result);\r\n }\r\n\r\n function correctInversion(digits) {\r\n /// <param name=\"digits\" type=\"Digits\"/>\r\n var results = createArray(digits.length);\r\n montgomeryMultiply(digits, montgomeryMultiplier.rCubedModm, results);\r\n for (var i = 0; i < results.length; i += 1) {\r\n digits[i] = results[i];\r\n }\r\n }\r\n\r\n function doubleAequalsNeg3(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If point = infinity then outputPoint := infinity.\r\n if (point.isInfinity) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // 't4:=Z1^2;'\r\n montgomerySquare(point.z, temp4);\r\n\r\n // 't3:=Y1^2;'\r\n montgomerySquare(point.y, temp3);\r\n\r\n // 't1:=X1+t4;'\r\n modAdd(point.x, temp4, temp1);\r\n\r\n // 't4:=X1-t4;'\r\n modSub(point.x, temp4, temp4);\r\n\r\n // 't0:=3*t4;'\r\n modAdd(temp4, temp4, temp0);\r\n modAdd(temp0, temp4, temp0);\r\n\r\n // 't5:=X1*t3;'\r\n montgomeryMultiply(point.x, temp3, temp5);\r\n\r\n // 't4:=t1*t0;'\r\n montgomeryMultiply(temp1, temp0, temp4);\r\n\r\n // 't0:=t3^2;'\r\n montgomerySquare(temp3, temp0);\r\n\r\n // 't1:=t4/2'\r\n modDivByTwo(temp4, temp1);\r\n\r\n // 't3:=t1^2;'\r\n montgomerySquare(temp1, temp3);\r\n\r\n // 'Z_out:=Y1*Z1;'\r\n montgomeryMultiply(point.y, point.z, swap0);\r\n for (var i = 0; i < swap0.length; i += 1) {\r\n outputPoint.z[i] = swap0[i];\r\n }\r\n\r\n // 'X_out:=t3-2*t5;'\r\n modSub(temp3, temp5, outputPoint.x);\r\n modSub(outputPoint.x, temp5, outputPoint.x);\r\n\r\n // 't3:=t5-X_out;'\r\n modSub(temp5, outputPoint.x, temp3);\r\n\r\n // 't5:=t1*t3'\r\n montgomeryMultiply(temp1, temp3, temp5);\r\n\r\n // 'Y_out:=t5-t0;'\r\n modSub(temp5, temp0, outputPoint.y);\r\n\r\n // Finalize the flags on the output point.\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n }\r\n\r\n function doubleAequals0(point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // If point = infinity then outputPoint := infinity.\r\n if (point.isInfinity) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // 't3:=Y1^2;'\r\n montgomerySquare(point.y, temp3);\r\n\r\n // 't4:=X1^2;'\r\n montgomerySquare(point.x, temp4);\r\n\r\n // 't4:=3*t4;'\r\n modAdd(temp4, temp4, temp0);\r\n modAdd(temp0, temp4, temp4);\r\n\r\n // 't5:=X1*t3;'\r\n montgomeryMultiply(point.x, temp3, temp5);\r\n\r\n // 't0:=t3^2;'\r\n montgomerySquare(temp3, temp0);\r\n\r\n // 't1:=t4/2;'\r\n modDivByTwo(temp4, temp1);\r\n\r\n // 't3:=t1^2;'\r\n montgomerySquare(temp1, temp3);\r\n\r\n // 'Z_out:=Y1*Z1;'\r\n montgomeryMultiply(point.y, point.z, swap0);\r\n for (var i = 0; i < swap0.length; i += 1) {\r\n outputPoint.z[i] = swap0[i];\r\n }\r\n\r\n // 'X_out:=t3-2*t5;'\r\n modSub(temp3, temp5, outputPoint.x);\r\n modSub(outputPoint.x, temp5, outputPoint.x);\r\n\r\n // 't4:=t5-X_out;'\r\n modSub(temp5, outputPoint.x, temp4);\r\n\r\n // 't2:=t1*t4;'\r\n montgomeryMultiply(temp1, temp4, temp2);\r\n\r\n // 'Y_out:=t2-t0;'\r\n modSub(temp2, temp0, outputPoint.y);\r\n\r\n // Finalize the flags on the output point.\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n }\r\n\r\n function generatePrecomputationTable(w, generatorPoint) {\r\n\r\n if (w < 4) {\r\n throw new Error(\"This pre-computation algorithm assumes w >= 4\");\r\n }\r\n\r\n if (!generatorPoint.isInMontgomeryForm) {\r\n throw new Error(\"Generator point must be in montgomery form\");\r\n }\r\n\r\n if (!generatorPoint.isAffine) {\r\n throw new Error(\"Generator point must be in affine form\");\r\n }\r\n\r\n // Currently we support only two curve types, those with A=-3, and\r\n // those with A=0. In the future we will implement general support.\r\n // For now we switch here, assuming that the curve was validated in\r\n // the constructor.\r\n if (aequalsZero) {\r\n return generatePrecomputationTableAequals0(w, generatorPoint);\r\n } else {\r\n return generatePrecomputationTableAequalsNeg3(w, generatorPoint);\r\n }\r\n }\r\n\r\n // Given a point P on an elliptic curve, return a table of \r\n // size 2^(w-2) filled with pre-computed values for \r\n // P, 3P, 5P, ... Etc.\r\n\r\n function generatePrecomputationTableAequalsNeg3(w, generatorPoint) {\r\n /// <param name=\"w\" type=\"Number\">The \"width\" of the table to use. The should match the width used to generate the NAF.</param>\r\n /// <param name=\"generatorPoint\">The point P in affine, montgomery form.</param>\r\n /// <returns>A table of size 2^(w-2) filled with pre-computed values for P, 3P, 5P, ... Etc in De-montgomeryized Affine Form.</returns>\r\n\r\n // Width of our field elements.\r\n var s = curve.p.length;\r\n\r\n // Initialize table\r\n // The first element is set to our generator povar initially.\r\n // The rest are dummy points to be filled in by the pre-computation\r\n // algorithm.\r\n var tableSize = (1 << (w - 2)); // 2^(w-2)\r\n var t = []; // Of EllipticCurvePointFp\r\n var i;\r\n t[0] = generatorPoint.clone();\r\n\r\n for (i = 1; i < tableSize; i += 1) {\r\n var newPoint = EllipticCurvePointFp(\r\n curve,\r\n false,\r\n createArray(s),\r\n createArray(s),\r\n createArray(s),\r\n true\r\n );\r\n t[i] = newPoint;\r\n }\r\n\r\n // Initialize temp tables for povar recovery.\r\n var d = [];\r\n var e = [];\r\n\r\n for (i = 0; i < tableSize - 2; i += 1) {\r\n d[i] = createArray(s);\r\n e[i] = createArray(s);\r\n }\r\n\r\n // Alias temp7 to Z for readability.\r\n var z = temp7;\r\n\r\n // Pseudocode Note:\r\n // Arrays of points use element 1 for X, element 2 for Y\r\n // so e.g. T[0][1] === T[0].x.\r\n\r\n // SETUP -----------------------------------------------------------\r\n\r\n // Compute T[0] = 2*P and T[1] = P such that both are in Jacobian \r\n // form with the same Z. These values are then used to compute \r\n // T[0] = 3P, T[1] = 5P, ..., T[n] = (3 + 2*n) * P.\r\n\r\n // 't1 := T[0].x^2; '\r\n montgomerySquare(t[0].x, temp1);\r\n\r\n // 't3 := T[0].y^2;'\r\n montgomerySquare(t[0].y, temp3);\r\n\r\n // 't1 := (3*t1 + A)/2;'\r\n modAdd(temp1, temp1, temp2);\r\n modAdd(temp2, temp1, temp1);\r\n modAdd(temp1, montgomerizedA, temp1);\r\n modDivByTwo(temp1, temp1);\r\n\r\n // 'T[2].x := t3 * T[0].x;'\r\n montgomeryMultiply(temp3, t[0].x, t[2].x);\r\n\r\n // 'T[2].y := t3^2;'\r\n montgomerySquare(temp3, t[2].y);\r\n\r\n // 'Z := T[0].y;'\r\n for (i = 0; i < s; i += 1) {\r\n z[i] = t[0].y[i];\r\n }\r\n\r\n // 'T[1].x := t1^2;'\r\n montgomerySquare(temp1, t[1].x);\r\n\r\n // 'T[1].x := T[1].x - 2 * T[2].x;'\r\n // PERF: Implementing DBLSUB here (and everywhere where we compute A - 2*B) \r\n // may possibly result in some performance gain.\r\n modSub(t[1].x, t[2].x, t[1].x);\r\n modSub(t[1].x, t[2].x, t[1].x);\r\n\r\n // 't2 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp2);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using temp0 as target since montmul is destructive.\r\n montgomeryMultiply(temp1, temp2, temp0);\r\n\r\n // 'T[1].y := t1 - T[2].y;'\r\n modSub(temp0, t[2].y, t[1].y);\r\n\r\n // First iteration ------------------------------------------------\r\n\r\n // 't1 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp1);\r\n\r\n // 't2 := T[2].y - T[1].y;'\r\n modSub(t[2].y, t[1].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n montgomeryMultiply(z, temp1, temp0);\r\n var idx;\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[0] := t1^2;'\r\n montgomerySquare(temp1, d[0]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'T[2].x := d[0] * T[1].x;'\r\n montgomeryMultiply(d[0], t[1].x, t[2].x);\r\n\r\n // 't3 := t3 - 2 * T[2].x;'\r\n modSub(temp3, t[2].x, temp3);\r\n modSub(temp3, t[2].x, temp3);\r\n\r\n // 'd[0] := d[0] * t1;'\r\n montgomeryMultiply(d[0], temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n d[0][idx] = temp0[idx];\r\n }\r\n\r\n // 'T[1].x := t3 - d[0];'\r\n modSub(temp3, d[0], t[1].x);\r\n\r\n // 't1 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp1);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using t0 as target due to destructive multiply.\r\n montgomeryMultiply(temp1, temp2, temp0);\r\n\r\n // 'T[2].y := T[1].y*d[0];'\r\n montgomeryMultiply(t[1].y, d[0], t[2].y);\r\n\r\n // 'T[1].y := t1 - T[2].y;'\r\n // NOTE: Reusing t0 result from above.\r\n modSub(temp0, t[2].y, t[1].y);\r\n\r\n // INNER ITERATIONS ------------------------------------------------\r\n var j, k, l;\r\n\r\n for (i = 0; i < tableSize - 3; i += 1) {\r\n j = i + 1;\r\n k = i + 2;\r\n l = i + 3;\r\n\r\n // 't1 := T[j].x - T[k].x;'\r\n modSub(t[j].x, t[k].x, temp1);\r\n\r\n // 't2 := T[j].y - T[k].y;'\r\n modSub(t[j].y, t[k].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n // NOTE: Using temp0 as target since multiply is destructive.\r\n montgomeryMultiply(z, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[i] := t1^2;'\r\n montgomerySquare(temp1, d[i]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'T[l].x := d[i] * T[k].x;'\r\n montgomeryMultiply(d[i], t[k].x, t[l].x);\r\n\r\n // 't3 := t3 - 2 * T[l].x;'\r\n modSub(temp3, t[l].x, temp3);\r\n modSub(temp3, t[l].x, temp3);\r\n\r\n // 'e[i] := d[i] * t1;'\r\n montgomeryMultiply(d[i], temp1, e[i]);\r\n\r\n // 'T[k].x := t3 - e[i];'\r\n modSub(temp3, e[i], t[k].x);\r\n\r\n // 't1 := T[l].x - T[k].x;'\r\n // NOTE: Using temp0 as target so we can multiply into temp1 below.\r\n modSub(t[l].x, t[k].x, temp0);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using temp0 result from above.\r\n montgomeryMultiply(temp0, temp2, temp1);\r\n\r\n // 'T[l].y := T[k].y*e[i];'\r\n montgomeryMultiply(t[k].y, e[i], t[l].y);\r\n\r\n // 'T[k].y := t1 - T[l].y;'\r\n modSub(temp1, t[l].y, t[k].y);\r\n }\r\n\r\n // FINAL ITERATION -------------------------------------------------\r\n // {\r\n i = tableSize - 3;\r\n j = i + 1;\r\n k = i + 2; // 't1 := T[j].x - T[k].x;'\r\n modSub(t[j].x, t[k].x, temp1);\r\n\r\n // 't2 := T[j].y - T[k].y;'\r\n modSub(t[j].y, t[k].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n montgomeryMultiply(z, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[i] := t1^2;'\r\n montgomerySquare(temp1, d[i]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'e[i] := d[i] * t1;'\r\n montgomeryMultiply(d[i], temp1, e[i]);\r\n\r\n // 't1 := d[i] * T[k].x;'\r\n montgomeryMultiply(d[i], t[k].x, temp1);\r\n\r\n // 't3 := t3 - 2 * t1;'\r\n modSub(temp3, temp1, temp3);\r\n modSub(temp3, temp1, temp3);\r\n\r\n // 'T[k].x := t3 - e[i];'\r\n modSub(temp3, e[i], t[k].x);\r\n\r\n // 't1 := t1 - T[k].x;'\r\n // NOTE: Using temp0 as target so we can multiply into temp1 below.\r\n modSub(temp1, t[k].x, temp0);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Reusing temp0 to multiply into temp1.\r\n montgomeryMultiply(temp0, temp2, temp1);\r\n\r\n // 'T[k].y := T[k].y * e[i];'\r\n // NOTE: Using temp3 as target due to destructive multiply.\r\n montgomeryMultiply(t[k].y, e[i], temp3);\r\n\r\n // 'T[k].y := t1 - T[k].y;'\r\n // NOTE: Using temp3 instead of T[k].y.\r\n modSub(temp1, temp3, t[k].y);\r\n\r\n // POST ITERATIONS - INVERT Z AND PREPARE TO RECOVER TABLE ENTRIES ---------------\r\n\r\n // 'Z := 1/Z;'\r\n // NOTE: Z is in montgomery form at this point, i.e. Z*R. After \r\n // inversion we will have 1/(Z*R) but we want (1/Z)*R (the \r\n // montgomery form of Z inverse) so we use the inversion \r\n // correction, which does a montgomery multiplication by R^3\r\n // yielding the correct result.\r\n modInv(z, z);\r\n correctInversion(z);\r\n\r\n // 't1 := Z^2;'\r\n montgomerySquare(z, temp1);\r\n\r\n // 't2 := t1 * Z;'\r\n montgomeryMultiply(temp1, z, temp2);\r\n\r\n // 'T[k].x := T[k].x * t1;'\r\n montgomeryMultiply(t[k].x, temp1, temp0);\r\n\r\n // Copy temp0 to T[k].x.\r\n for (idx = 0; idx < s; idx++) {\r\n t[k].x[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[k].y := T[k].y * t2;'\r\n montgomeryMultiply(t[k].y, temp2, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[k].y[idx] = temp0[idx];\r\n }\r\n // } FINAL ITERATION\r\n\r\n // RECOVER POINTS FROM TABLE ---------------------------------------\r\n\r\n // For i in [(2^(w-2)-2)..1 by -1] do\r\n for (i = tableSize - 3; i >= 0; i--) {\r\n // 'j := i + 1;'\r\n j = i + 1; // 't1 := t1 * d[i];'\r\n montgomeryMultiply(temp1, d[i], temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n temp1[idx] = temp0[idx];\r\n }\r\n\r\n // 't2 := t2 * e[i];'\r\n montgomeryMultiply(temp2, e[i], temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n temp2[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[j].x := T[j].x * t1;'\r\n montgomeryMultiply(t[j].x, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[j].x[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[j].y := T[j].y * t2;'\r\n montgomeryMultiply(t[j].y, temp2, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[j].y[idx] = temp0[idx];\r\n }\r\n\r\n // End for;\r\n }\r\n\r\n // Points are now in affine form, set Z coord to null (== 1).\r\n for (i = 0; i < t.length; i += 1) {\r\n t[i].z = null;\r\n setterSupport || (t[i].isAffine = true);\r\n }\r\n\r\n for (i = 0; i < t.length; i += 1) {\r\n\r\n if (!t[i].isAffine) {\r\n throw new Error(\"Non-affine povar found in precomputation table\");\r\n }\r\n if (!t[i].isInMontgomeryForm) {\r\n convertToMontgomeryForm(t[i]);\r\n }\r\n }\r\n\r\n return t;\r\n }\r\n\r\n // Given a povar P on an elliptic curve, return a table of \r\n // size 2^(w-2) filled with pre-computed values for \r\n // P, 3P, 5P, ... Etc.\r\n\r\n function generatePrecomputationTableAequals0(w, generatorPoint) {\r\n /// <param name=\"w\" type=\"Number\">The \"width\" of the table to use. The should match\r\n /// the width used to generate the NAF.</param>\r\n /// <param name=\"generatorPoint\" type=\"EllipticCurvePointFp\">The povar P in affine, montgomery form.</param>\r\n /// <returns>A table of \r\n /// size 2^(w-2) filled with pre-computed values for \r\n /// P, 3P, 5P, ... Etc in De-montgomeryized Affine Form.</returns>\r\n\r\n // Width of our field elements.\r\n var s = curve.p.length;\r\n\r\n // Initialize table\r\n // The first element is set to our generator povar initially.\r\n // The rest are dummy points to be filled in by the pre-computation\r\n // algorithm.\r\n var tableSize = (1 << (w - 2)); // '2^(w-2)'\r\n var t = []; // Of EllipticCurvePointFp\r\n t[0] = generatorPoint.clone();\r\n var i;\r\n for (i = 1; i < tableSize; i += 1) {\r\n var newPoint = EllipticCurvePointFp(\r\n curve,\r\n false,\r\n createArray(s),\r\n createArray(s),\r\n createArray(s),\r\n true\r\n );\r\n t[i] = newPoint;\r\n }\r\n\r\n // Initialize temp tables for povar recovery.\r\n var d = [];\r\n var e = [];\r\n\r\n for (i = 0; i < tableSize - 2; i += 1) {\r\n d[i] = createArray(s);\r\n e[i] = createArray(s);\r\n }\r\n\r\n // Alias temp7 to Z for readability.\r\n var z = temp7;\r\n\r\n // Pseudocode Note:\r\n // Arrays of points use element 1 for X, element 2 for Y\r\n // so e.g. T[0][1] === T[0].x.\r\n\r\n // SETUP -----------------------------------------------------------\r\n\r\n // Compute T[0] = 2*P and T[1] = P such that both are in Jacobian \r\n // form with the same Z. These values are then used to compute \r\n // T[0] = 3P, T[1] = 5P, ..., T[n] = (3 + 2*n) * P.\r\n\r\n // 't1 := T[0].x^2; '\r\n montgomerySquare(t[0].x, temp1);\r\n\r\n // 't3 := T[0].y^2;'\r\n montgomerySquare(t[0].y, temp3);\r\n\r\n // 't1 := (3*t1)/2;'\r\n modAdd(temp1, temp1, temp2);\r\n modAdd(temp2, temp1, temp1);\r\n modDivByTwo(temp1, temp1);\r\n\r\n // 'T[2].x := t3 * T[0].x;'\r\n montgomeryMultiply(temp3, t[0].x, t[2].x);\r\n\r\n // 'T[2].y := t3^2;'\r\n montgomerySquare(temp3, t[2].y);\r\n\r\n // 'Z := T[0].y;'\r\n for (i = 0; i < s; i += 1) {\r\n z[i] = t[0].y[i];\r\n }\r\n\r\n // 'T[1].x := t1^2;'\r\n montgomerySquare(temp1, t[1].x);\r\n\r\n // 'T[1].x := T[1].x - 2 * T[2].x;'\r\n // PERF: Implementing DBLSUB here (and everywhere where we compute A - 2*B) \r\n // may possibly result in some performance gain.\r\n modSub(t[1].x, t[2].x, t[1].x);\r\n modSub(t[1].x, t[2].x, t[1].x);\r\n\r\n // 't2 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp2);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using temp0 as target since montmul is destructive.\r\n montgomeryMultiply(temp1, temp2, temp0);\r\n\r\n // 'T[1].y := t1 - T[2].y;'\r\n modSub(temp0, t[2].y, t[1].y);\r\n\r\n // First iteration ------------------------------------------------\r\n\r\n // 't1 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp1);\r\n\r\n // 't2 := T[2].y - T[1].y;'\r\n modSub(t[2].y, t[1].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n montgomeryMultiply(z, temp1, temp0);\r\n var idx;\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[0] := t1^2;'\r\n montgomerySquare(temp1, d[0]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'T[2].x := d[0] * T[1].x;'\r\n montgomeryMultiply(d[0], t[1].x, t[2].x);\r\n\r\n // 't3 := t3 - 2 * T[2].x;'\r\n modSub(temp3, t[2].x, temp3);\r\n modSub(temp3, t[2].x, temp3);\r\n\r\n // 'd[0] := d[0] * t1;'\r\n montgomeryMultiply(d[0], temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n d[0][idx] = temp0[idx];\r\n }\r\n\r\n // 'T[1].x := t3 - d[0];'\r\n modSub(temp3, d[0], t[1].x);\r\n\r\n // 't1 := T[2].x - T[1].x;'\r\n modSub(t[2].x, t[1].x, temp1);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using t0 as target due to destructive multiply.\r\n montgomeryMultiply(temp1, temp2, temp0);\r\n\r\n // 'T[2].y := T[1].y*d[0];'\r\n montgomeryMultiply(t[1].y, d[0], t[2].y);\r\n\r\n // 'T[1].y := t1 - T[2].y;'\r\n // NOTE: Reusing t0 result from above.\r\n modSub(temp0, t[2].y, t[1].y);\r\n\r\n var j, k, l;\r\n // INNER ITERATIONS ------------------------------------------------\r\n for (i = 0; i < tableSize - 3; i += 1) {\r\n j = i + 1;\r\n k = i + 2;\r\n l = i + 3;\r\n\r\n // 't1 := T[j].x - T[k].x;'\r\n modSub(t[j].x, t[k].x, temp1);\r\n\r\n // 't2 := T[j].y - T[k].y;'\r\n modSub(t[j].y, t[k].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n // NOTE: Using temp0 as target since multiply is destructive.\r\n montgomeryMultiply(z, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[i] := t1^2;'\r\n montgomerySquare(temp1, d[i]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'T[l].x := d[i] * T[k].x;'\r\n montgomeryMultiply(d[i], t[k].x, t[l].x);\r\n\r\n // 't3 := t3 - 2 * T[l].x;'\r\n modSub(temp3, t[l].x, temp3);\r\n modSub(temp3, t[l].x, temp3);\r\n\r\n // 'e[i] := d[i] * t1;'\r\n montgomeryMultiply(d[i], temp1, e[i]);\r\n\r\n // 'T[k].x := t3 - e[i];'\r\n modSub(temp3, e[i], t[k].x);\r\n\r\n // 't1 := T[l].x - T[k].x;'\r\n // NOTE: Using temp0 as target so we can multiply into temp1 below.\r\n modSub(t[l].x, t[k].x, temp0);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Using temp0 result from above.\r\n montgomeryMultiply(temp0, temp2, temp1);\r\n\r\n // 'T[l].y := T[k].y*e[i];'\r\n montgomeryMultiply(t[k].y, e[i], t[l].y);\r\n\r\n // 'T[k].y := t1 - T[l].y;'\r\n modSub(temp1, t[l].y, t[k].y);\r\n }\r\n\r\n // FINAL ITERATION -------------------------------------------------\r\n // {\r\n i = tableSize - 3;\r\n j = i + 1;\r\n k = i + 2;\r\n\r\n // 't1 := T[j].x - T[k].x;'\r\n modSub(t[j].x, t[k].x, temp1);\r\n\r\n // 't2 := T[j].y - T[k].y;'\r\n modSub(t[j].y, t[k].y, temp2);\r\n\r\n // 'Z := Z * t1;'\r\n montgomeryMultiply(z, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n z[idx] = temp0[idx];\r\n }\r\n\r\n // 'd[i] := t1^2;'\r\n montgomerySquare(temp1, d[i]);\r\n\r\n // 't3 := t2^2;'\r\n montgomerySquare(temp2, temp3);\r\n\r\n // 'e[i] := d[i] * t1;'\r\n montgomeryMultiply(d[i], temp1, e[i]);\r\n\r\n // 't1 := d[i] * T[k].x;'\r\n montgomeryMultiply(d[i], t[k].x, temp1);\r\n\r\n // 't3 := t3 - 2 * t1;'\r\n modSub(temp3, temp1, temp3);\r\n modSub(temp3, temp1, temp3);\r\n\r\n // 'T[k].x := t3 - e[i];'\r\n modSub(temp3, e[i], t[k].x);\r\n\r\n // 't1 := t1 - T[k].x;'\r\n // NOTE: Using temp0 as target so we can multiply into temp1 below.\r\n modSub(temp1, t[k].x, temp0);\r\n\r\n // 't1 := t1 * t2;'\r\n // NOTE: Reusing temp0 to multiply into temp1.\r\n montgomeryMultiply(temp0, temp2, temp1);\r\n\r\n // 'T[k].y := T[k].y*e[i];'\r\n // NOTE: Using temp3 as target due to destructive multiply.\r\n montgomeryMultiply(t[k].y, e[i], temp3);\r\n\r\n // 'T[k].y := t1 - T[k].y;'\r\n // NOTE: Using temp3 instead of T[k].y.\r\n modSub(temp1, temp3, t[k].y);\r\n\r\n // POST ITERATIONS - INVERT Z AND PREPARE TO RECOVER TABLE ENTRIES ---------------\r\n\r\n // 'Z := 1/Z;'\r\n // NOTE: Z is in montgomery form at this point, i.e. Z*R. After \r\n // inversion we will have 1/(Z*R) but we want (1/Z)*R (the \r\n // montgomery form of Z inverse) so we use the inversion \r\n // correction, which does a montgomery multiplication by R^3\r\n // yielding the correct result.\r\n modInv(z, z);\r\n correctInversion(z);\r\n\r\n // 't1 := Z^2;'\r\n montgomerySquare(z, temp1);\r\n\r\n // 't2 := t1 * Z;'\r\n montgomeryMultiply(temp1, z, temp2);\r\n\r\n // 'T[k].x := T[k].x * t1;'\r\n montgomeryMultiply(t[k].x, temp1, temp0);\r\n\r\n // Copy temp0 to T[k].x.\r\n for (idx = 0; idx < s; idx++) {\r\n t[k].x[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[k].y := T[k].y * t2;'\r\n montgomeryMultiply(t[k].y, temp2, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[k].y[idx] = temp0[idx];\r\n }\r\n // }\r\n\r\n // RECOVER POINTS FROM TABLE ---------------------------------------\r\n\r\n // For i in [(2^(w-2)-2)..1 by -1] do\r\n for (i = tableSize - 3; i >= 0; i--) {\r\n // 'j := i + 1;'\r\n j = i + 1;\r\n\r\n // 't1 := t1 * d[i];'\r\n montgomeryMultiply(temp1, d[i], temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n temp1[idx] = temp0[idx];\r\n }\r\n\r\n // 't2 := t2 * e[i];'\r\n montgomeryMultiply(temp2, e[i], temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n temp2[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[j].x := T[j].x * t1;'\r\n montgomeryMultiply(t[j].x, temp1, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[j].x[idx] = temp0[idx];\r\n }\r\n\r\n // 'T[j].y := T[j].y * t2;'\r\n montgomeryMultiply(t[j].y, temp2, temp0);\r\n\r\n for (idx = 0; idx < s; idx++) {\r\n t[j].y[idx] = temp0[idx];\r\n }\r\n\r\n // End for;\r\n }\r\n\r\n // Points are now in affine form, set Z coord to null (== 1).\r\n for (i = 0; i < t.length; i += 1) {\r\n t[i].z = null;\r\n setterSupport || (t[i].isAffine = true);\r\n }\r\n\r\n for (i = 0; i < t.length; i += 1) {\r\n\r\n if (!t[i].isAffine) {\r\n throw new Error(\"Non-affine povar found in precomputation table\");\r\n }\r\n if (!t[i].isInMontgomeryForm) {\r\n convertToMontgomeryForm(t[i]);\r\n }\r\n }\r\n\r\n return t;\r\n }\r\n\r\n function convertToMontgomeryForm(point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (point.isInMontgomeryForm) {\r\n throw new Error(\"The given point is already in montgomery form.\");\r\n }\r\n\r\n if (!point.isInfinity) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.x);\r\n montgomeryMultiplier.convertToMontgomeryForm(point.y);\r\n\r\n if (point.z !== null) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.z);\r\n }\r\n }\r\n\r\n point.isInMontgomeryForm = true;\r\n }\r\n\r\n return {\r\n\r\n double: function (point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (typeof point === \"undefined\") {\r\n throw new Error(\"point undefined\");\r\n }\r\n if (typeof outputPoint === \"undefined\") {\r\n throw new Error(\"outputPoint undefined\");\r\n }\r\n\r\n //// if (!point.curve.equals(outputPoint.curve)) {\r\n //// throw new Error(\"point and outputPoint must be from the same curve object.\");\r\n //// }\r\n\r\n if (point.isAffine) {\r\n throw new Error(\"Given point was in Affine form. Use convertToJacobian() first.\");\r\n }\r\n\r\n if (!point.isInMontgomeryForm) {\r\n throw new Error(\"Given point must be in montgomery form. Use montgomeryize() first.\");\r\n }\r\n\r\n if (outputPoint.isAffine) {\r\n throw new Error(\"Given output point was in Affine form. Use convertToJacobian() first.\");\r\n }\r\n\r\n // Currently we support only two curve types, those with A=-3, and\r\n // those with A=0. In the future we will implement general support.\r\n // For now we switch here, assuming that the curve was validated in\r\n // the constructor.\r\n if (aequalsZero) {\r\n doubleAequals0(point, outputPoint);\r\n } else {\r\n doubleAequalsNeg3(point, outputPoint);\r\n }\r\n\r\n },\r\n\r\n mixedDoubleAdd: function (jacobianPoint, affinePoint, outputPoint) {\r\n /// <param name=\"jacobianPoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"affinePoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (jacobianPoint.isInfinity) {\r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n return;\r\n }\r\n\r\n if (affinePoint.isInfinity) {\r\n jacobianPoint.copy(outputPoint);\r\n return;\r\n }\r\n\r\n // Ok then we do the full double and add.\r\n\r\n // Note: in pseudo-code the capital X,Y,Z is Jacobian point, lower \r\n // case x, y, z is Affine point.\r\n\r\n // 't5:=Z1^ 2;'\r\n montgomerySquare(jacobianPoint.z, temp5);\r\n\r\n // 't6:=Z1*t5;'\r\n montgomeryMultiply(jacobianPoint.z, temp5, temp6);\r\n\r\n // 't4:=x2*t5;'\r\n montgomeryMultiply(affinePoint.x, temp5, temp4);\r\n\r\n // 't5:=y2*t6;'\r\n montgomeryMultiply(affinePoint.y, temp6, temp5);\r\n\r\n // 't1:=t4-X1;'\r\n modSub(temp4, jacobianPoint.x, temp1);\r\n\r\n // 't2:=t5-Y1;'\r\n modSub(temp5, jacobianPoint.y, temp2);\r\n\r\n // 't4:=t2^2;'\r\n montgomerySquare(temp2, temp4);\r\n\r\n // 't6:=t1^2;'\r\n montgomerySquare(temp1, temp6);\r\n\r\n // 't5:=t6*X1;'\r\n montgomeryMultiply(temp6, jacobianPoint.x, temp5);\r\n\r\n // 't0:=t1*t6;'\r\n montgomeryMultiply(temp1, temp6, temp0);\r\n\r\n // 't3:=t4-2*t5;'\r\n modSub(temp4, temp5, temp3);\r\n modSub(temp3, temp5, temp3);\r\n\r\n // 't4:=Z1*t1;'\r\n montgomeryMultiply(jacobianPoint.z, temp1, temp4);\r\n\r\n // 't3:=t3-t5;'\r\n modSub(temp3, temp5, temp3);\r\n\r\n // 't6:=t0*Y1;'\r\n montgomeryMultiply(temp0, jacobianPoint.y, temp6);\r\n\r\n // 't3:=t3-t0;'\r\n modSub(temp3, temp0, temp3);\r\n\r\n // 't1:=2*t6;'\r\n modAdd(temp6, temp6, temp1);\r\n\r\n // 'Zout:=t4*t3;'\r\n montgomeryMultiply(temp4, temp3, outputPoint.z);\r\n\r\n // 't4:=t2*t3;'\r\n montgomeryMultiply(temp2, temp3, temp4);\r\n\r\n // 't0:=t3^2;'\r\n montgomerySquare(temp3, temp0);\r\n\r\n // 't1:=t1+t4;'\r\n modAdd(temp1, temp4, temp1);\r\n\r\n // 't4:=t0*t5;'\r\n montgomeryMultiply(temp0, temp5, temp4);\r\n\r\n // 't7:=t1^2;'\r\n montgomerySquare(temp1, temp7);\r\n\r\n // 't4:=t0*t5;'\r\n montgomeryMultiply(temp0, temp3, temp5);\r\n\r\n // 'Xout:=t7-2*t4;'\r\n modSub(temp7, temp4, outputPoint.x);\r\n modSub(outputPoint.x, temp4, outputPoint.x);\r\n\r\n // 'Xout:=Xout-t5;'\r\n modSub(outputPoint.x, temp5, outputPoint.x);\r\n\r\n // 't3:=Xout-t4;'\r\n modSub(outputPoint.x, temp4, temp3);\r\n\r\n // 't0:=t5*t6;'\r\n montgomeryMultiply(temp5, temp6, temp0);\r\n\r\n // 't4:=t1*t3;'\r\n montgomeryMultiply(temp1, temp3, temp4);\r\n\r\n // 'Yout:=t4-t0;'\r\n modSub(temp4, temp0, outputPoint.y);\r\n\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n },\r\n\r\n mixedAdd: function (jacobianPoint, affinePoint, outputPoint) {\r\n /// <param name=\"jacobianPoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"affinePoint\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (jacobianPoint === null) {\r\n throw new Error(\"jacobianPoint\");\r\n }\r\n\r\n if (affinePoint === null) {\r\n throw new Error(\"affinePoint\");\r\n }\r\n\r\n if (outputPoint === null) {\r\n throw new Error(\"outputPoint\");\r\n }\r\n\r\n if (jacobianPoint.curve !== affinePoint.curve ||\r\n jacobianPoint.curve !== outputPoint.curve) {\r\n throw new Error(\"All points must be from the same curve object.\");\r\n }\r\n\r\n if (jacobianPoint.isAffine) {\r\n throw new Error(\r\n \"Given jacobianPoint was in Affine form. Use ConvertToJacobian() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (!affinePoint.isAffine) {\r\n throw new Error(\r\n \"Given affinePoint was in Jacobian form. Use ConvertToAffine() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (outputPoint.isAffine) {\r\n throw new Error(\r\n \"Given jacobianPoint was in Jacobian form. Use ConvertToJacobian() before calling DoubleJacobianAddAffinePoints().\");\r\n }\r\n\r\n if (!jacobianPoint.isInMontgomeryForm) {\r\n throw new Error(\"Jacobian point must be in Montgomery form\");\r\n }\r\n\r\n if (!affinePoint.isInMontgomeryForm) {\r\n throw new Error(\"Affine point must be in Montgomery form\");\r\n }\r\n\r\n if (jacobianPoint.isInfinity) {\r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n return;\r\n }\r\n\r\n if (affinePoint.isInfinity) {\r\n jacobianPoint.copy(outputPoint);\r\n return;\r\n }\r\n\r\n // Ok then we do the full double and add.\r\n\r\n // Note: in pseudo-code the capital X1,Y1,Z1 is Jacobian point, \r\n // lower case x2, y2, z2 is Affine point.\r\n // 't1 := Z1^2;'.\r\n montgomerySquare(jacobianPoint.z, temp1);\r\n\r\n // 't2 := t1 * Z1;'\r\n montgomeryMultiply(temp1, jacobianPoint.z, temp2);\r\n\r\n // 't3 := t1 * x2;'\r\n montgomeryMultiply(temp1, affinePoint.x, temp3);\r\n\r\n // 't4 := t2 * y2;'\r\n montgomeryMultiply(temp2, affinePoint.y, temp4);\r\n\r\n // 't1 := t3 - X1;'\r\n modSub(temp3, jacobianPoint.x, temp1);\r\n\r\n // 't2 := t4 - Y1;'\r\n modSub(temp4, jacobianPoint.y, temp2);\r\n\r\n // If t1 != 0 then\r\n var i;\r\n for (i = 0; i < temp1.length; i += 1) {\r\n if (temp1[i] !== 0) {\r\n\r\n // 'Zout := Z1 * t1;'\r\n montgomeryMultiply(jacobianPoint.z, temp1, temp0);\r\n for (var j = 0; j < fieldElementWidth; j += 1) {\r\n outputPoint.z[j] = temp0[j];\r\n }\r\n\r\n // 't3 := t1^2;'\r\n montgomerySquare(temp1, temp3);\r\n\r\n // 't4 := t3 * t1;'\r\n montgomeryMultiply(temp3, temp1, temp4);\r\n\r\n // 't5 := t3 * X1;'\r\n montgomeryMultiply(temp3, jacobianPoint.x, temp5);\r\n\r\n // 't1 := 2 * t5;'\r\n modAdd(temp5, temp5, temp1);\r\n\r\n // 'Xout := t2^2;'\r\n montgomerySquare(temp2, outputPoint.x);\r\n\r\n // 'Xout := Xout - t1;'\r\n modSub(outputPoint.x, temp1, outputPoint.x);\r\n\r\n // 'Xout := Xout - t4;'\r\n modSub(outputPoint.x, temp4, outputPoint.x);\r\n\r\n // 't3 := t5 - Xout;'\r\n modSub(temp5, outputPoint.x, temp3);\r\n\r\n // 't5 := t3*t2;'\r\n montgomeryMultiply(temp2, temp3, temp5);\r\n\r\n // 't6 := t4*Y1;'\r\n montgomeryMultiply(jacobianPoint.y, temp4, temp6);\r\n\r\n // 'Yout := t5-t6;'\r\n modSub(temp5, temp6, outputPoint.y);\r\n\r\n outputPoint.isInfinity = false;\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n return;\r\n }\r\n }\r\n\r\n // Else if T2 != 0 then\r\n for (i = 0; i < temp2.length; i += 1) {\r\n if (temp2[i] !== 0) {\r\n // Return infinity\r\n outputPoint.isInfinity = true;\r\n outputPoint.isInMontgomeryForm = true;\r\n return;\r\n }\r\n }\r\n // Else use DBL routine to return 2(x2, y2, 1) \r\n affinePoint.copy(outputPoint);\r\n this.convertToJacobianForm(outputPoint);\r\n this.double(outputPoint, outputPoint);\r\n outputPoint.isInMontgomeryForm = true;\r\n\r\n },\r\n\r\n scalarMultiply: function (k, point, outputPoint) {\r\n /// <param name=\"k\" type=\"Digits\"/>\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n // Special case for the point at infinity or k == 0\r\n if (point.isInfinity || cryptoMath.isZero(k)) {\r\n outputPoint.isInfinity = true;\r\n return;\r\n }\r\n\r\n // Runtime check for 1 <= k < order to ensure we dont get hit by\r\n // subgroup attacks. Since k is a FixedWidth it is a positive integer\r\n // and we already checked for zero above. So it must be >= 1 already.\r\n if (cryptoMath.compareDigits(k, curve.order) >= 0) {\r\n throw new Error(\"The scalar k must be in the range 1 <= k < order.\");\r\n }\r\n\r\n var digit;\r\n\r\n // Change w based on the size of the digits, \r\n // 5 is good for 256 bits, use 6 for bigger sizes.\r\n var w = (fieldElementWidth <= 8) ? 5 : 6;\r\n // Generate wNAF representation.\r\n // Using an Array because we want to allow negative numbers.\r\n var nafDigits = msrcryptoUtilities.getVector(k.length * cryptoMath.DIGIT_BITS + 1);\r\n var numNafDigits = cryptoMath.computeNAF(k, w, temp0, nafDigits);\r\n\r\n // Generate pre-computation table.\r\n var table = generatePrecomputationTable(w, point);\r\n\r\n // Setup output point as Infinity, Jacobian, montgomery.\r\n outputPoint.isInfinity = true;\r\n\r\n // Main algorithm.\r\n for (var i1 = numNafDigits - 1; i1 >= 0; i1--) {\r\n if (nafDigits[i1] === 0) {\r\n this.double(outputPoint, outputPoint);\r\n } else if (nafDigits[i1] < 0) {\r\n digit = (-nafDigits[i1] >> 1);\r\n\r\n // Negate Y coord before doing the add.\r\n this.negate(table[digit], table[digit]);\r\n this.mixedDoubleAdd(outputPoint, table[digit], outputPoint);\r\n this.negate(table[digit], table[digit]);\r\n } else if (nafDigits[i1] > 0) {\r\n digit = (nafDigits[i1] >> 1);\r\n this.mixedDoubleAdd(outputPoint, table[digit], outputPoint);\r\n }\r\n }\r\n\r\n return;\r\n\r\n },\r\n\r\n negate: function (point, outputPoint) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\">Input point to negate.</param>\r\n /// <param name=\"outputPoint\" type=\"EllipticCurvePointFp\">(x, p - y).</param>\r\n\r\n if (point !== outputPoint) {\r\n point.copy(outputPoint);\r\n }\r\n cryptoMath.subtract(point.curve.p, point.y, outputPoint.y);\r\n },\r\n\r\n convertToMontgomeryForm: function (point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (point.isInMontgomeryForm) {\r\n throw new Error(\"The given point is already in montgomery form.\");\r\n }\r\n\r\n if (!point.isInfinity) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.x);\r\n montgomeryMultiplier.convertToMontgomeryForm(point.y);\r\n\r\n if (point.z !== null) {\r\n montgomeryMultiplier.convertToMontgomeryForm(point.z);\r\n }\r\n }\r\n\r\n point.isInMontgomeryForm = true;\r\n },\r\n\r\n convertToStandardForm: function (point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (!point.isInMontgomeryForm) {\r\n throw new Error(\"The given point is not in montgomery form.\");\r\n }\r\n\r\n if (!point.isInfinity) {\r\n montgomeryMultiplier.convertToStandardForm(point.x);\r\n montgomeryMultiplier.convertToStandardForm(point.y);\r\n if (point.z !== null) {\r\n montgomeryMultiplier.convertToStandardForm(point.z);\r\n }\r\n }\r\n\r\n point.isInMontgomeryForm = false;\r\n\r\n },\r\n\r\n convertToAffineForm: function (point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (point.isInfinity) {\r\n point.z = null;\r\n setterSupport || (point.isAffine = true);\r\n return;\r\n }\r\n\r\n // DETERMINE 1/Z IN MONTGOMERY FORM --------------------------------\r\n\r\n // Call out to the basic inversion function, not the one in this class.\r\n cryptoMath.modInv(point.z, curve.p, conversionTemp2);\r\n\r\n if (point.isInMontgomeryForm) {\r\n montgomeryMultiply(conversionTemp2, montgomeryMultiplier.rCubedModm, conversionTemp1);\r\n var swap = conversionTemp2;\r\n conversionTemp2 = conversionTemp1;\r\n conversionTemp1 = swap;\r\n }\r\n\r\n // CONVERT TO AFFINE COORDS ----------------------------------------\r\n\r\n // 'temp0 <- 1/z^2'\r\n montgomerySquare(conversionTemp2, conversionTemp0);\r\n\r\n // Compute point.x = x / z^2 mod p\r\n // NOTE: We cannot output directly to the X digit array since it is \r\n // used for input to the multiplication routine, so we output to temp1\r\n // and copy.\r\n montgomeryMultiply(point.x, conversionTemp0, conversionTemp1);\r\n for (var i = 0; i < fieldElementWidth; i += 1) {\r\n point.x[i] = conversionTemp1[i];\r\n }\r\n\r\n // Compute point.y = y / z^3 mod p\r\n // temp1 <- y * 1/z^2.\r\n montgomeryMultiply(point.y, conversionTemp0, conversionTemp1);\r\n // 'y <- temp1 * temp2 (which == 1/z)'\r\n montgomeryMultiply(conversionTemp1, conversionTemp2, point.y);\r\n\r\n // Finally, point.z = z / z mod p = 1\r\n // We use z = NULL for this case to make detecting Jacobian form \r\n // faster (otherwise we would have to scan the entire Z digit array).\r\n point.z = null;\r\n setterSupport || (point.isAffine = true);\r\n },\r\n\r\n convertToJacobianForm: function (point) {\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\"/>\r\n\r\n if (!point.isAffine) {\r\n throw new Error(\"The given point is not in Affine form.\");\r\n }\r\n\r\n setterSupport || (point.isAffine = false);\r\n\r\n var clonedDigits;\r\n var i;\r\n if (point.isInMontgomeryForm) {\r\n\r\n // Z = 1 (montgomery form)\r\n clonedDigits = createArray(onemontgomery.length);\r\n for (i = 0; i < onemontgomery.length; i += 1) {\r\n clonedDigits[i] = onemontgomery[i];\r\n }\r\n\r\n point.z = clonedDigits;\r\n } else {\r\n\r\n // Z = 1 (standard form)\r\n clonedDigits = createArray(one.length);\r\n for (i = 0; i < one.length; i += 1) {\r\n clonedDigits[i] = one[i];\r\n }\r\n\r\n point.z = clonedDigits;\r\n }\r\n\r\n },\r\n\r\n // For tests\r\n generatePrecomputationTable: function (w, generatorPoint) {\r\n /// <param name=\"w\" type=\"Number\"/>\r\n /// <param name=\"generatorPoint\" type=\"EllipticCurvePointFp\"/>\r\n\r\n return generatePrecomputationTable(w, generatorPoint);\r\n }\r\n\r\n };\r\n };\r\n var sec1EncodingFp = function () {\r\n return {\r\n encodePoint: function (/*@type(EllipticCurvePointFp)*/ point) {\r\n /// <summary>Encode an EC point without compression.\r\n /// This function encodes a given points into a bytes array containing 0x04 | X | Y, where X and Y are big endian bytes of x and y coordinates.</summary>\r\n /// <param name=\"point\" type=\"EllipticCurvePointFp\">Input EC point to encode.</param>\r\n /// <returns type=\"Array\">A bytes array containing 0x04 | X | Y, where X and Y are big endian encoded x and y coordinates.</returns>\r\n\r\n if (!point) {\r\n throw new Error(\"point\");\r\n }\r\n\r\n if (!point.isAffine) {\r\n throw new Error(\"Point must be in affine form.\");\r\n }\r\n\r\n if (point.isInMontgomeryForm) {\r\n throw new Error(\"Point must not be in Montgomery form.\");\r\n }\r\n\r\n if (point.isInfinity) {\r\n return createArray(1); /* [0] */\r\n } else {\r\n var xOctetString = cryptoMath.digitsToBytes(point.x);\r\n var yOctetString = cryptoMath.digitsToBytes(point.y);\r\n var pOctetString = cryptoMath.digitsToBytes(point.curve.p); // just to get byte length of p\r\n var mlen = pOctetString.length;\r\n if (mlen < xOctetString.length || mlen < yOctetString.length) {\r\n throw new Error(\"Point coordinate(s) are bigger than the field order.\");\r\n }\r\n var output = createArray(2 * mlen + 1); // for encoded x and y\r\n\r\n output[0] = 0x04;\r\n var offset = mlen - xOctetString.length;\r\n for (var i = 0; i < xOctetString.length; i++) {\r\n output[i + 1 + offset] = xOctetString[i];\r\n }\r\n offset = mlen - yOctetString.length;\r\n for (i = 0; i < yOctetString.length; i++) {\r\n output[mlen + i + 1 + offset] = yOctetString[i];\r\n }\r\n\r\n return output;\r\n }\r\n\r\n },\r\n decodePoint: function (encoded, curve) {\r\n /// <param name=\"encoded\" type=\"Digits\"/>\r\n /// <param name=\"curve\" type=\"EllipticCurveFp\"/>\r\n\r\n if (encoded.length < 1) {\r\n throw new Error(\"Byte array must have non-zero length\");\r\n }\r\n\r\n var pOctetString = cryptoMath.digitsToBytes(curve.p);\r\n var mlen = pOctetString.length;\r\n\r\n if (encoded[0] === 0x0 && encoded.length === 1) {\r\n return curve.createPointAtInfinity();\r\n } else if (encoded[0] === 0x04 && encoded.length === 1 + 2 * mlen) {\r\n // Standard encoding.\r\n // Each point is a big endian string of bytes of length.\r\n // 'ceiling(log_2(Q)/8)'\r\n // Zero-padded and representing the magnitude of the coordinate.\r\n var xbytes = createArray(mlen);\r\n var ybytes = createArray(mlen);\r\n\r\n for (var i = 0; i < mlen; i++) {\r\n xbytes[i] = encoded[i + 1];\r\n ybytes[i] = encoded[mlen + i + 1];\r\n }\r\n\r\n var x = cryptoMath.bytesToDigits(xbytes);\r\n var y = cryptoMath.bytesToDigits(ybytes);\r\n\r\n return EllipticCurvePointFp(curve, false, x, y);\r\n } else {\r\n // We don't support other encoding features such as compression\r\n throw new Error(\"Unsupported encoding format\");\r\n }\r\n }\r\n };\r\n };\r\n var ModularSquareRootSolver = function (modulus) {\r\n /// <param name=\"modulus\" type=\"Digits\"/>\r\n\r\n // The modulus we are going to use.\r\n var p = modulus;\r\n\r\n // Special-K not just for breakfast anymore! This is k = (p-3)/4 + 1\r\n // which is used for NIST curves (or any curve of with P= 3 mod 4).\r\n // This field is null if p is not of the special form, or k if it is.\r\n var specialK = [];\r\n\r\n if (typeof modulus === \"undefined\") {\r\n throw new Error(\"modulus\");\r\n }\r\n\r\n // Support for odd moduli, only.\r\n if (cryptoMath.isEven(modulus)) {\r\n throw new Error(\"Only odd moduli are supported\");\r\n }\r\n\r\n // A montgomery multiplier object for doing fast squaring.\r\n var mul = cryptoMath.MontgomeryMultiplier(p);\r\n\r\n // 'p === 3 mod 4' then we can use the special super fast version.\r\n // Otherwise we must use the slower general case algorithm.\r\n if (p[0] % 4 === 3) {\r\n // 'special k = (p + 1) / 4'\r\n cryptoMath.add(p, cryptoMath.One, specialK);\r\n cryptoMath.shiftRight(specialK, specialK, 2);\r\n } else {\r\n specialK = null;\r\n }\r\n\r\n // Temp storage\r\n var temp0 = new Array(p.length);\r\n var temp1 = new Array(p.length);\r\n\r\n function squareRootNistCurves(a) {\r\n /// <summary>Given a number a, returns a solution x to x^2 = a (mod p).</summary>\r\n /// <param name=\"a\" type=\"Array\">An integer a.</param>\r\n /// <returns type=\"Array\">The square root of the number a modulo p, if it exists,\r\n /// otherwise null.</returns>\r\n\r\n // beta = a^k mod n where k=(n+1)/4 for n == 3 mod 4, thus a^(1/2) mod n\r\n var beta = cryptoMath.intToDigits(0, 16);\r\n mul.modExp(a, specialK, beta);\r\n\r\n // Okay now we gotta double check by squaring.\r\n var aPrime = [0];\r\n cryptoMath.modMul(beta, beta, mul.m, aPrime);\r\n\r\n // If a != x^2 then a has no square root\r\n if (cryptoMath.compareDigits(a, aPrime) !== 0) {\r\n return null;\r\n }\r\n\r\n return beta;\r\n }\r\n\r\n var publicMethods = {\r\n\r\n squareRoot: function (a) {\r\n if (specialK !== null) {\r\n // Use the special case fast code\r\n return squareRootNistCurves(a);\r\n } else {\r\n // Use the general case code\r\n throw new Error(\"GeneralCase not supported.\");\r\n }\r\n },\r\n\r\n // Given an integer a, this routine returns the Jacobi symbol (a/p), \r\n // where p is the modulus given in the constructor, which for p an \r\n // odd prime is also the Legendre symbol. From \"Prime Numbers, A \r\n // Computational Perspective\" by Crandall and Pomerance, alg. 2.3.5.\r\n // The Legendre symbol is defined as:\r\n // 0 if a === 0 mod p.\r\n // 1 if a is a quadratic residue (mod p).\r\n // -1 if a is a quadratic non-reside (mod p).\r\n jacobiSymbol: function (a) {\r\n /// <param name=\"a\">An integer a.</param>\r\n\r\n var modEightMask = 0x7,\r\n modFourMask = 0x3,\r\n aPrime,\r\n pPrime;\r\n\r\n // Clone our inputs, we are going to destroy them\r\n aPrime = a.slice();\r\n pPrime = p.slice();\r\n\r\n // 'a = a mod p'.\r\n cryptoMath.reduce(aPrime, pPrime, aPrime, temp0, temp1);\r\n\r\n // 't = 1'\r\n var t = 1;\r\n\r\n // While (a != 0)\r\n while (!cryptoMath.isZero(aPrime)) {\r\n // While a is even\r\n while (cryptoMath.isEven(aPrime)) {\r\n // 'a <- a / 2'\r\n cryptoMath.shiftRight(aPrime, aPrime);\r\n\r\n // If (p mod 8 in {3,5}) t = -t;\r\n var pMod8 = (pPrime[0] & modEightMask);\r\n if (pMod8 === 3 || pMod8 === 5) {\r\n t = -t;\r\n }\r\n }\r\n\r\n // Swap variables\r\n // (a, p) = (p, a).\r\n var tmp = aPrime;\r\n aPrime = pPrime;\r\n pPrime = tmp;\r\n\r\n // If (a === p === 3 (mod 4)) t = -t;\r\n var aMod4 = (aPrime[0] & modFourMask);\r\n var pMod4 = (pPrime[0] & modFourMask);\r\n if (aMod4 === 3 && pMod4 === 3) {\r\n t = -t;\r\n }\r\n\r\n // 'a = a mod p'\r\n cryptoMath.reduce(aPrime, pPrime, aPrime, temp0, temp1);\r\n }\r\n\r\n // If (p == 1) return t else return 0\r\n if (cryptoMath.compareDigits(pPrime, cryptoMath.One) === 0) {\r\n return t;\r\n } else {\r\n return 0;\r\n }\r\n }\r\n\r\n };\r\n\r\n return publicMethods;\r\n };\r\n\r\n return {\r\n createP256: createP256,\r\n createP384: createP384,\r\n createBN254: createBN254,\r\n createANeg3Curve: createANeg3Curve,\r\n sec1EncodingFp: sec1EncodingFp,\r\n EllipticCurvePointFp: EllipticCurvePointFp,\r\n EllipticCurveOperatorFp: EllipticCurveOperatorFp,\r\n ModularSquareRootSolver: ModularSquareRootSolver\r\n };\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a User from an idToken server response | static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {
const stsTokenManager = new StsTokenManager();
stsTokenManager.updateFromServerResponse(idTokenResponse);
// Initialize the Firebase Auth user.
const user = new UserImpl({
uid: idTokenResponse.localId,
auth,
stsTokenManager,
isAnonymous
});
// Updates the user info and data and resolves with a user instance.
await _reloadWithoutSaving(user);
return user;
} | [
"static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse); // Initialize the Firebase Auth user.\n\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n }); // Updates the user info and data and resolves with a user instance.\n\n await _reloadWithoutSaving(user);\n return user;\n }",
"constructor() { \n \n UserResponse.initialize(this);\n }",
"function parse_user_init_reg(responseJsonObj) {\n\tif (responseJsonObj) {\n\t\tif(responseJsonObj.user) {\n\t\t\tthis.user = responseJsonObj.user;\n\t\t}\n\t\tif(responseJsonObj.wallet) {\n\t\t\tthis.wallet = responseJsonObj.wallet;\n\t\t}\n\t\tthis.errorCode = responseJsonObj.errorCode;\n\t\tthis.errorMessage = responseJsonObj.errorMessage;\n\t}\n}",
"async function getCurrentUserFromIdToken(idToken) {\n\n let token = null;\n if (!idToken){\n token = await SecureStore.getItemAsync(\"idToken\") \n }else{\n token = idToken\n }\n const userdata = jwtDecode(token);\n const {id,first_name,last_name,email,account_type} = userdata;\n return {\n id,\n firstName: first_name,\n lastName: last_name,\n email,\n accountType: account_type,\n };\n}",
"AUTH_USER (state, userData) {\n state.idToken = userData.token\n state.userId = userData.userId\n }",
"static parseUser(response) {\n const user = response.body.data;\n if (!user) {\n throw new Error('Cannot parse Northstar API response.body.data.');\n }\n\n return user;\n }",
"function init() {\n userFactory.getUser();\n\n }",
"async function loadUserObject(req, res) {\n const token = req.headers.authorization;\n var userId = getUserIdFromToken(token, res);\n var user = await getUserByUserId(userId, res); //The user object\n \n return {\n user: user,\n id: userId,\n }\n}",
"constructor() { \n \n UserLoginRespDTO.initialize(this);\n }",
"createOrUpdateUser(response) {\n const existingUser = this.users.find(u => u.id === response.userId);\n if (existingUser) {\n // Update the users access and refresh tokens\n existingUser.accessToken = response.accessToken;\n existingUser.refreshToken = response.refreshToken;\n return existingUser;\n }\n else {\n // Create and store a new user\n const user = new User({\n app: this,\n id: response.userId,\n accessToken: response.accessToken,\n refreshToken: response.refreshToken,\n });\n this.users.unshift(user);\n return user;\n }\n }",
"static async getLoggedInUser(token, username) {\n // if we don't have user info, return null\n if (!token || !username) return null;\n\n // call the API\n const response = await axios.get(`${BASE_URL}/users/${username}`, {\n params: {\n token\n }\n });\n\n // instantiate the user from the API information\n const existingUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n existingUser.loginToken = token;\n\n // instantiate Story instances for the user's favorites and ownStories\n existingUser.favorites = response.data.user.favorites.map(s => new Story(s));\n existingUser.ownStories = response.data.user.stories.map(s => new Story(s));\n return existingUser;\n\n }",
"static async getLoggedInUser(token, username) {\n // if we don't have user info, return null\n if (!token || !username) return null;\n // call the API\n const response = await axios.get(`${BASE_URL}/users/${username}`, {\n params: {\n token\n }\n });\n // instantiate the user from the API information\n const existingUser = new User(response.data.user);\n // attach the token to the newUser instance for convenience\n existingUser.loginToken = token;\n // instantiate Story instances for the user's favorites and ownStories\n existingUser.favorites = response.data.user.favorites.map((s) => new Story(s));\n existingUser.ownStories = response.data.user.stories.map((s) => new Story(s));\n return existingUser; // return existingUser\n }",
"function parse_upgrade_guest_user(responseJsonObj) {\n if (responseJsonObj) {\n \tif(responseJsonObj.user) {\n \t\tthis.user_id = responseJsonObj.user.id;\n \tthis.username = responseJsonObj.user.username;\n \t}\n \tthis.errorCode = responseJsonObj.errorCode;\n this.errorMessage = responseJsonObj.errorMessage;\n }\n}",
"static async getLoggedInUser(token, username) {\n // if we don't have user info, return null\n if (!token || !username) return null;\n\n // call the API\n const response = await axios.get(`${BASE_URL}/users/${username}`, {\n params: {\n token\n }\n });\n\n // instantiate the user from the API information\n const existingUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n existingUser.loginToken = token;\n\n // instantiate Story instances for the user's favorites and ownStories\n existingUser.favorites = response.data.user.favorites.map(s => new Story(s));\n existingUser.ownStories = response.data.user.stories.map(s => new Story(s));\n return existingUser;\n }",
"static async getLoggedInUser(token, username) {\n // if we don't have user info, return null\n if (!token || !username) return null;\n\n // call the API\n const response = await axios.get(`${BASE_URL}/users/${username}`, {\n params: {\n token\n }\n });\n\n // instantiate the user from the API information\n const existingUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n existingUser.loginToken = token;\n\n // instantiate Story instances for the user's favorites and ownStories\n existingUser.favorites = response.data.user.favorites.map(s => new Story(s));\n existingUser.ownStories = response.data.user.stories.map(s => new Story(s));\n\n return existingUser;\n }",
"function parseUserfromDB(results){\n if(results == null || results == undefined){\n user = null;\n } else {\n var user = new User;\n user.pk = results.user_pk;\n user.username = results.user_username;\n user.fname = results.user_fname;\n user.lname = results.user_lname;\n user.email = results.user_email;\n user.hash = results.user_hash;\n user.signup = results.user_signup;\n user.last_signin = results.user_last_signin;\n user.security_question = results.user_security_question;\n user.security_answer = results.user_security_answer;\n }\n return user; \n }",
"static async getUserById(dbController, id){\n const userData = await dbController.select(USER_TABLE, USER_DATA_COLUMNS, mysql.format('user_id=?',id));\n return new User(userData[0].user_id, userData[0].user_name, userData[0].user_surname, userData[0].user_email, userData[0].user_pwd, dbController);\n }",
"function load_userObj(data) {\n userObj.id = data.id;\n userObj.email = data.email;\n userObj.nick = data.nick;\n userObj.name = data.name;\n userObj.role = data.role;\n}",
"constructor() { \n \n UIDTokenDetails.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FamiliesEvacuated textfield change event handler | function OnFamiliesEvacuated_Change( e , type )
{
Alloy.Globals.AeDESModeSectionEight["FAMILIES_EVACUATED"] = $.widgetAppTextFieldAeDESModeFormsSectionEightFamiliesEvacuated.get_text_value() ;
} | [
"onBlur() {\n ChromeGA.event(ChromeGA.EVENT.TEXT, this.name);\n this.fireEvent('setting-text-changed', this.value);\n }",
"onFnaFieldValueChanged(value) {}",
"onFieldChanged(control, controlName, currentValue) {}",
"_handleFieldChange() {\n if (this.type === \"text\" || this.type === \"textarea\") this._updateCount();\n if (this.autovalidate) this.validate();\n this.value = this._getFieldValue();\n if (this.type === \"textarea\") this.autoGrow();\n }",
"function changed_text(event){\n var field = $(this)\n var item = field.parents('.item:first')\n var old_text = field.attr(\"data-text\")\n var new_text = field.val()\n if (old_text != new_text){\n field.attr(\"data-text\", new_text)\n var field_kind = field.hasClass('title') ? 'title' : 'note'\n action_history.record({type:'change_text', item_id:item.attr('data-id'), field:field_kind, old_text:old_text, new_text:new_text}) \n }\n}",
"function field_change(target, func) {\n target.bind('keyup cut paste', func);\n }",
"_textBoxKeyUpHandler() {\n const that = this;\n\n const value = that.value;\n that.value = that._getValueWithTextMaskFormat({ start: 0, end: that._mask.length }, that.textMaskFormat);\n\n if (value !== that.value) {\n that.$.fireEvent('change', {\n 'newValue': that.value,\n 'oldValue': value\n });\n }\n }",
"function NonAddableFieldTextChanged(e) {\n\tchangeValueOfNonAddableField(userDataInArrays, clickedTextField.id, clickedTextField.text);\t// editProfileHelper.js\n}",
"onTextChanged_() {\n // Delay the 'textchanged' event so StreamingEngine time to absorb the\n // changes before the user tries to query it.\n const event = this.makeEvent_(conf.EventName.TextChanged)\n this.delayDispatchEvent_(event)\n }",
"function onTextInput(index) {\r\n $(\"#name\" + index)\r\n .on('change', modifyData);\r\n $(\"#text\" + index)\r\n .on('change', modifyData);\r\n}",
"onKeyUp(ev) {\n // check if 'Enter' was pressed\n if (ev.code === 'Enter') {\n ChromeGA.event(ChromeGA.EVENT.TEXT, this.name);\n this.fireEvent('setting-text-changed', this.value);\n }\n }",
"function inputChanged(e) {\n formChanged = true;\n }",
"function fieldChanged(type, name, linenum) {\r\n\r\n}",
"function listenForEditorChanges(e)\n{\n if(e.type == 'keyup' || e.type == 'blur' || e.type == 'click' || e.type == 'change')\n summarizeText();\n}",
"function on_font_changed() {}",
"function TextChanged(value, formNameObject, onBlur)\n{\n\tvar i = self.TABLE.document.TimeEntry.yCord.value;\n\tvar j = self.TABLE.document.TimeEntry.xCord.value;\n\tvar NumRecs = 0;\n\tvar timeObject = self.TABLE.document.TimeEntry;\n\n \ttry\n \t{\n\t\n\t\tif (typeof(TimeCard.Form[j].OffsetPayCode) != \"undefined\")\n\t\t{\n\t\t\tvar lineObject \t= eval('timeObject.lineFc'+i+'_'+j);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar lineObject \t= eval('timeObject.lineFc'+i);\n\t\t}\n\t\n\t\tif (typeof(lineObject.value) == \"undefined\") \n\t\t{\n\t\t\tlineObject.value = \"-\";\n\t\t}\n\t\t\n\t\tvar label;\n\t\n \t\t// PT 159549. Display a split time edit error only if the entry has changed.\n\t\tif (lineObject.value == \"Split\" && !onBlur)\n\t\t{\n\t\t\tseaAlert(getSeaPhrase(\"USE_DAILY_TE_CHANGE_MULTIENTRIED\",\"TE\"));\n\t\t\ttimeObject[formNameObject].value = \"\";\n\t\t\tif (TimeCard.Form[j].FormField == \"HOURS\")\n\t\t\t{\n\t\t\t\ttimeObject[TimeCard.Form[j].FormField +'_'+ i].value = FormatHours(TimeCard.Records[i].Hours,TimeCard.Form[j].Size);\n\t\t\t}\n \t\ttimeObject[TimeCard.Form[j].FormField +'_'+ i].focus();\n \t\ttimeObject[TimeCard.Form[j].FormField +'_'+ i].select();\n\t\t\t// PT 159549\n\t\t\treturn false;\n\t\t}\n\t\telse if (lineObject.value == \"Split\" && onBlur && timeObject[TimeCard.Form[j].FormField +'_'+ i].value != FormatHours(TimeCard.Records[i].Hours,TimeCard.Form[j].Size))\n\t\t{\n\t\t ;\n \t\t}\n\t\telse\n\t\t{\n\t\t\tif (lineObject.value == \"-\" && typeof(value) != \"undefined\" && NonSpace(value) > 0)\n\t\t\t{\n\t\t\t\tlineObject.value = \"A\";\n\t\t\t}\n\t\t\telse if (lineObject.value == \"A\" && NonSpace(value) == 0)\n\t\t\t{\n\t\t\t\tlineObject.value = \"-\";\n\t\t\t\tfor (var k=1; k<TimeCard.Form.length; k++)\n\t\t\t\t{\n\t\t\t\t\tvar tmpVal = timeObject[TimeCard.Form[k].FormField +'_'+ i].value;\n\t\t\t\t\tif (typeof(tmpVal) != \"undefined\" && NonSpace(tmpVal) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tlineObject.value = \"A\"\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lineObject.value == \"D\" && NonSpace(value) > 0 && parseFloat(value) != 0)\n\t\t\t{\n\t\t\t\tlineObject.value = \"C\";\n\t\t\t}\n\t\t\telse if (lineObject.value == \"C\" && NonSpace(value) == 0 && parseFloat(value) != 0)\n\t\t\t{\n\t\t\t\tlineObject.value = \"D\";\n\t\t\t\tif (typeof(TimeCard.Form[j].OffsetPayCode) == \"undefined\")\n\t\t\t\t{\n\t\t\t\t\tfor (var k=1; k<TimeCard.Form.length; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar tmpVal = timeObject[TimeCard.Form[k].FormField +'_'+ i].value;\n\t\t\t\t\t\tif (typeof(tmpVal) != \"undefined\" && NonSpace(tmpVal) > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlineObject.value = \"C\";\n\t\t\t\t\t\t\tbreak;\n\t\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\tlabel = TimeCard.Form[j].FormField;\n\n\t\t\t//PT 157125 check for numeric field for addition label GLAccount\n\t\t\tvar tmpVal2 = timeObject[TimeCard.Form[j].FormField +'_'+ i].value;\n\t\t\tif ((label == \"HOURS\" || label == \"RATE\" || label == \"SHIFT\" || label == \"GLACCOUNT\" || label == \"GLCOMPANY\" || label == \"ACCOUNT\" || label == \"SUBACCT\" || label == \"STEP\") && typeof(tmpVal2) != \"undefined\" && NonSpace(tmpVal2) > 0)\n\t\t\t{\t\n\t\t\t\tCheckNumeric(i,j);\n\t\t\t}\n\t\t\telse if (typeof(TimeCard.Form[j].OffsetPayCode) != \"undefined\" && typeof(tmpVal2) != \"undefined\" && NonSpace(tmpVal2) > 0)\n\t\t\t{\t\n\t\t\t\tCheckNumeric(i,j);\n\t\t\t}\n\t\t\t\n\t\t\tif (label == \"HOURS\" && !emssObjInstance.emssObj.teAllowNegativeHours && typeof(tmpVal2) != \"undefined\" && NonSpace(tmpVal2) > 0)\n\t\t\t{\n\t\t\t\tCheckPositiveNumber(i,j);\n\t\t\t}\n\t\t\telse if (typeof(TimeCard.Form[j].OffsetPayCode) != \"undefined\" && !emssObjInstance.emssObj.teAllowNegativeHours && typeof(tmpVal2) != \"undefined\" && NonSpace(tmpVal2) > 0)\n\t\t\t{\n\t\t\t\tCheckPositiveNumber(i,j);\n\t\t\t}\n\t\t\t\n\t\t\tif (typeof(TimeCard.Form[j].OffsetPayCode) != \"undefined\")\n\t\t\t{\n\t\t\t\tTotalHours();\n\t\t\t}\n\t\t\n\t\t\tif (label == \"HOURS\" || label == \"RATE\")\n\t\t\t{\n\t\t\t\tif (label == \"HOURS\")\n\t\t\t\t{\n\t\t\t\t\t// PTs 102499, 105365: do not continue if an edit is produced, as this function will be re-called for the text box in error.\n\t\t\t\t\t// Infinite loop scenario.\n\t\t\t\t\tif (Check24HourEdit(i,j)) \n\t\t\t\t\t{\n\t\t\t\t\t\tlastHourCheckFailed = true;\n\t\t\t\t\t\tlastI = i;\n\t\t\t\t\t\tlastJ = j;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t} \n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlastHourCheckFailed = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t\tvar sizeString = String(TimeCard.Form[j].Size);\n\t\t\t\t\t\n\t\t\t\tif (sizeString.indexOf(\".\")== -1) \n\t\t\t\t{\n\t\t\t\t\tsizeString = String(Number(TimeCard.Form[j].Size)/10);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tvar numberDecimals = sizeString.split(\".\");\n\t\t\t\ttimeObject = timeObject[TimeCard.Form[j].FormField +'_'+ i];\n\t\t\n\t\t\t\tif (numberDecimals.length == 2) \n\t\t\t\t{\n\t\t\t\t\ttimeObject.value = roundToDecimal(timeObject.value, Number(numberDecimals[1]));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttimeObject.value = roundToDecimal(timeObject.value, 0);\n\t\t\t\t}\n\t\n\t\t\t\tif (parseFloat(timeObject.value) == 0.00)\n\t\t\t\t{\n\t\t\t\t\ttimeObject.value = \"\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (label == \"HOURS\")\n\t\t\t\t{\t\n\t\t\t\t\tTotalHours();\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\tif (label == \"PAYCODE\")\n\t\t\t{\n\t\t\t\ttimeObject = timeObject[TimeCard.Form[j].FormField +'_'+ i];\n\t\t\t\tif (timeObject.value == \"=OFF\")\n\t\t\t\t{\n\t\t\t\t\tIgnorePeriodOutOfRangeAndLockOut = true;\n\t\t\t\t\twindow.status = getSeaPhrase(\"VIEWS_OFF\",\"TE\");\n\t\t\t\t\ttimeObject.value = \"\";\n\t\t\t\t}\n\t\t\t\telse if (timeObject.value == \"=ON\")\n\t\t\t\t{\n\t\t\t\t\tIgnorePeriodOutOfRangeAndLockOut = false;\n\t\t\t\t\twindow.status = getSeaPhrase(\"VIEWS_ON\",\"TE\");\n\t\t\t\t\ttimeObject.value = \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\t//PT115978\n\t\tif (!onBlur && lineObject.value != \"-\") \n\t\t{\n\t\t\tboolSaveChanges = true;\n\t\t}\n \t}\t\n \tcatch(e)\n \t{}\n\t\n\treturn true;\n}",
"function on_textInput_changed()\n\t\t{\n\t\t\t// Set the scale_factor based on the text.\n\t\t\tvar value = this.text;\n\t\t\tif (isNaN(value)) {\n\t\t\t\talert(value + \" is not a number. Please enter a number.\", scriptName);\n\t\t\t} else {\n\t\t\t\tscale_factor = value;\n\t\t\t}\n\t\t}",
"onTextChanged() {\n const model = this.completer.model;\n if (!model || !this._enabled) {\n return;\n }\n // If there is a text selection, no completion is allowed.\n const editor = this.editor;\n if (!editor) {\n return;\n }\n const { start, end } = editor.getSelection();\n if (start.column !== end.column || start.line !== end.line) {\n return;\n }\n // Dispatch the text change.\n model.handleTextChange(this.getState(editor, editor.getCursorPosition()));\n }",
"function on_selection_changed() { }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a payment method TODO: returns? Deferred resolved with ? TODO: data parameter ? what's the structure? | addPayment(data) {
return null
} | [
"addPaymentMethod(paymentMethod) {\n const pm = new PaymentMethod(paymentMethod);\n pm.customer = this.id;\n\n return pm.validate().then(() => new Promise((resolve, reject) => {\n Conekta.Customer.find(this.externalReference, (err, extCust) => {\n if (err) {\n reject(err);\n }\n\n extCust.createPaymentSource({\n type: 'card',\n token_id: paymentMethod.conektaToken,\n }, (err, extPaymentMethod) => {\n if (err) {\n reject(err);\n }\n\n pm.externalReference = extPaymentMethod.id;\n pm.brand = extPaymentMethod.brand;\n pm.save().then(savedPM => resolve(savedPM));\n });\n });\n }));\n }",
"function _submitPayment(){ // 3.x\n\t\t\tvar obj = GetRequest.for.submitPayment();\n\n\t\t\t$http({\n\t\t\t\tmethod: 'POST',\n\t\t\t\turl: obj.url,\n\t\t\t\tdata: appData.helpers._serialize(obj.data),\n\t\t\t\tresponseType: 'json',\n\t\t\t\theaders: appData.headers,\n\t\t\t\ttransformResponse: _transformPaymentMethodResponse,\n\t\t\t\ttransformRequest: _transformPaymentMethodRequest,\n\t\t\t\twithCredentials: true,\n\t\t\t}).then(function(response){\n\t\t\t\t$rootScope.$broadcast(\"RESPONSE-SUCCESS\");\n\n\t\t\t\t// only add payment when receiving a new payment method; not when validating the cvv\n\t\t\t\tif (!obj.verifyPayment){\n\t\t\t\t\t$rootScope.$broadcast(\"PAYMENT-METHOD-SUCCESS\", response.data);\n\t\t\t\t\tDataStore.save(\"paymentMethod\", response.data);\n\t\t\t\t}\n\n\t\t\t\tstatemachine.setCondition(conditions.hasData);\n\t\t\t\t$timeout(function(){_submitShoppingCart();},100);\n\t\t\t},function(error){\n\t\t\t\terror.data.for = \"page-error\";\n\t\t\t\terror.data.message = error.data;\n\t\t\t\t$rootScope.$broadcast(\"RESPONSE-FAIL\", error.data);\n\t\t\t}).finally(function(){\n\t\t\t\t$rootScope.$broadcast(\"WAIT\", {wait: false, label: \"DEFAULT\"});\n\t\t\t});\n\n\t\t\tfunction _transformPaymentMethodRequest(request){\n\t\t\t\trequest = request.replace(/number%3A/g,\"\");\n\t\t\t\treturn request;\n\t\t\t}\n\n\t\t\tfunction _transformPaymentMethodResponse(response){\n\t\t\t\t// IE sucks\n\t\t\t\tif (typeof response === \"string\"){\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresponse = JSON.parse(response);\n\t\t\t\t\t} catch(e){console.error(e)}\n\t\t\t\t}\n\t\t\t\tif (response && !response.exception){ // not an error\n\t\t\t\t\tresponse.label = appData.helpers._makeMethodLabel(response.last_four);\n\t\t\t\t\tresponse.id = response.qcommerce_payment_method_id;\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}",
"function createPaymentMethod({ card }) {\n const customerId = $('#id_customer_id').text().slice(1, -1);\n let billingName = $('#id_billing_name').text().slice(1, -1); \n let billingEmail = $('#id_billing_email').text().slice(1, -1); \n let priceId = $('#id_price_id').text().toUpperCase().slice(1, -1);\n \n stripe\n .createPaymentMethod({\n type: 'card',\n card: card,\n billing_details: {\n name: billingName,\n email: billingEmail,\n },\n })\n .then((result) => {\n if (result.error) {\n displayError(result);\n } else {\n createSubscription({\n customerId: customerId,\n paymentMethodId: result.paymentMethod.id,\n priceId: priceId,\n });\n }\n });\n }",
"addCheck(){ return this.addPayment(\"check\") }",
"function PaymentMethods() {\n\n}",
"submitPayment (payment) {\n return Promise.resolve()\n }",
"static add(householdPaymentMethod){\n\t\tlet kparams = {};\n\t\tkparams.householdPaymentMethod = householdPaymentMethod;\n\t\treturn new kaltura.RequestBuilder('householdpaymentmethod', 'add', kparams);\n\t}",
"createPaymentMethod(nonce) {\n let gateway = BraintreeHelper.getInstance().getGateway();\n let options = {\n customerId: this._id,\n paymentMethodNonce: nonce\n }\n let wrappedCall = Meteor.wrapAsync(gateway.paymentMethod.create, gateway.paymentMethod);\n let response = wrappedCall(options);\n console.log(\"[Customer] create new method: \", options, JSON.stringify(response));\n }",
"function buy() {\n try {\n new PaymentRequest(\n [{\n supportedMethods: 'foo',\n }],\n {\n total: {\n label: 'Total',\n amount: {\n currency: 'USD',\n value: '5.00',\n },\n },\n modifiers: [{\n supportedMethods: 'foo',\n }],\n })\n .show()\n .then(function(response) {\n response.complete()\n .then(function() {\n print(complete);\n })\n .catch(function(error) {\n print(error);\n });\n })\n .catch(function(error) {\n print(error);\n });\n } catch (error) {\n print(error.message);\n }\n}",
"addNewCancleRequest(payment) {\n return h({\n url: `${this.basePath}addNewCancleRequest`,\n method: 'post',\n data: payment,\n });\n }",
"payment(data, actions) {\n return actions.payment.create({\n transactions: [{\n amount: {\n total: paymentDetails.total(),\n currency: 'HKD'\n }\n }]\n });\n }",
"payment(data, actions) {\n return actions.payment.create({\n transactions: [\n {\n amount: {\n total: order.totalPrice,\n currency: 'USD',\n },\n },\n ],\n });\n }",
"function addPaymentToUser() {\n var payment = {\n amount: $scope.totalRentAmount,\n date: new Date(),\n email: $scope.user.email,\n userid: $scope.user._id\n };\n\n $scope.user.rentDueDate = incrementDueDate($scope.user.rentDueDate);\n $scope.user.rentPaid = true;\n\n UserService.updateUser($scope.user._id, $scope.user).then(function (res) {\n UserService.payRent($scope.user._id, payment).then(function (res) {\n $scope.user = res;\n $scope.needToPayRent = false;\n $state.go('payment-success');\n }, function (err) {\n console.log(err);\n });\n }, function (err) {\n console.log(err);\n });\n }",
"function PaymentService() {\n\n}",
"addpaymentDetails(payment) {\r\n return axios.post(USER_API_BASE_URL+'/payment', payment);\r\n }",
"AttachPayment(req,res){\n if(!req.customerId || !req.paymentMethod_id) return res.send({status:0, message:\"Enter the valid credentaila\"});\n \n let control = new StripeControl();\n control.AttachPaymentMethod(req.customerId,req.paymentMethod_id).then(paymentMethod => {\n if(_.isEmpty(paymentMethod)) return res.send({status:0, message:\"Error in attaching the payment_methods\"});\n\n return res.send({status:1, message:\"Payment Method is attached successfully\", paymentMethod:paymentMethod});\n \n }).catch(error => {\n return res.send({status:0, message:error});\n });\n \n }",
"makePayment() {\n this.setState({ loading: true });\n const { handleClose, lesson } = this.props;\n const {\n price,\n teacher,\n student,\n } = lesson;\n const resolve = (response) => {\n this.updateLessonPaid();\n };\n const reject = (response) => console.log(response);\n\n var stripePrice = priceToStripePrice(price);\n var params = {\n amount: stripePrice,\n teacher_id: teacher.id,\n student_id: student.id,\n };\n\n Requester.post(\n ApiConstants.stripe.charge,\n params,\n resolve,\n reject\n );\n }",
"function payment_create(request, response, next) {\n console.log('Payment create');\n}",
"function PaymentResponse() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
closing bracket for getRandomValue function function to display gifs in sidebar: | function sidebarGif(){
var sideBarGifCategories = ["soothing", "satisfying", "funny"];
queryURL =
`https://api.giphy.com/v1/gifs/random?api_key=YH4MrA2S7hO4bt490OPWcfMSS4SQUtl1&tag=${getRandomValue(sideBarGifCategories)}`;
//ajax call for gifs
$.ajax({
url: queryURL,
method: "GET",
}).then(function (response) {
//this builds an image and sets the source to be the url in the response
$("#sidebarImage").html($("<img>").attr("src", response.data.images.original.url));
}); //closing bracket for sidebar gif ajax call
} | [
"function getRandomGif() {\n\t// Retrieve all possible gifs in an array\n\tlet allGifs = getGifs();\n\t// Use Math.random() to get a random index number and get the random gif file name\n\tlet randomGif = allGifs[Math.floor(Math.random() * allGifs.length)];\n\treturn randomGif;\n}",
"function getRandomGifFile() {\n setActiveButton('random'); // make the random button active state\n togglePagination('off'); // remove pagination since only showing 1 image\n toggleLoader('on'); // add the loader UNTIL we receive response from server ***may need to move this further down the chain of operations though***\n\n // create function to receive random data (no need for total pages, just need 1 gif)\n $.get( \"/gif-random\", function(data) {\n data = JSON.parse(data);\n gifBuilder(data.gifList); // send our gif to the builder to handle it\n toggleLoader('off'); // hide toggle loader\n });\n }",
"function randomGIF() {\n\treturn random.gifs[Math.floor(Math.random() * random.gifs.length)];\n}",
"function randomGif() {\n let randomNumber = Math.floor(Math.random() * 12);\n\n return \"images/win-\" + randomNumber + \".gif\";\n }",
"function randomLoader(){\n // gif list\n var gifs = [\"images/1.gif\", \"images/2.gif\", \"images/3.gif\", \"images/4.gif\", \"images/5.gif\", \"images/6.gif\", \"images/7.gif\", \"images/8.gif\", \"images/9.gif\", \"images/10.gif\", \"images/11.gif\", \"images/12.gif\", \"images/13.gif\", \"images/14.gif\", \"images/15.gif\", \"images/16.gif\", \"images/17.gif\", \"images/18.gif\", \"images/19.gif\", \"images/20.gif\", \"images/21.gif\", \"images/22.gif\", \"images/23.gif\"];\n // random number\n var num = Math.floor(Math.random() * 23);\n return gifs[num];\n}",
"function dispImage() {\n var queryURL = \"https://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC\";\n var gifImg;\n var randomindex;\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function(response) {\n randomindex = Math.floor(Math.random()*(response.data.length-1+1)+1);\n\n\n gifImg = response.data[randomindex].images.downsized.url;\n $(\"#gipgif\").attr(\"src\",gifImg);\n });\n}",
"function randomGif(){\n $(\".gif\").empty();\n $(\".gif\").attr(\"id\",\"quesGif\");\n key = Math.floor(Math.random()*10);\n console.log(\"The key index being selected is\")\n console.log(key);\n console.log(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n var playerGif = $(\"<img>\").attr(\"src\", gifList[key]);\n playerGif.css(\"width\",\"40%\")\n playerGif.css(\"margin-left\",\"30%\")\n playerGif.css(\"margin-top\",\"30px\")\n $(\".gif\").append(playerGif);\n console.log(\"The name of that player should be\")\n console.log(playerList[key]);\n}",
"function gifLocator(){\n\t\tfor (var i = 0; i < 100; i++) {\n\t\t\tarray.push(i);\n\t\t\tif (array.length === 100) {\n\t\t\t\t//Shuffle\n\t\t\t\tfor (var j = array.length; j; j--) {\n\t\t\t\t\tx = Math.floor(Math.random() * j);\n\t\t\t y = array[j - 1];\n\t\t\t array[j - 1] = array[x];\n\t\t\t array[x] = y;\n\t\t \t}\n\t\t\t}\n\t\t}\n\t}",
"function showRandomPicture() {\n return Math.floor(Math.random() * allPictureNames.length);\n}",
"function appendGif(res) {\n // random gif from selection\n let randomPicker = Math.floor(Math.random() * 50);\n // console.log(randomPicker);\n // console.log(res.data.data[randomPicker].images.original.url);\n\n // create img\n const gif = document.createElement('img');\n gif.classList.add('gif');\n gif.src = res.data.data[randomPicker].images.original.url;\n\n //append img to div\n gifStaging.append(gif);\n}",
"function showSample(){\n\t \tfor(let j = 0; j < 16; j++){\n\t \t\timgtag[j].src = \"img/\" + j + \".jpg\";\n\t \t}//end for loop\n\n\t \tshuffleflag = false;\n\t}//end function showSample",
"function getRandomDog(){\n let i = getRandomInt(171);\n try{$('.sub__voting-image img').attr('src', MyVariables.breedOptions[i].url);\n $('.sub__voting-image img').attr('ImgId', MyVariables.breedOptions[i].reffImgId);\n $('.sub__voting-image img').attr('value',MyVariables.breedOptions[i].id);\n $('.sub__voting-image img').attr('name', MyVariables.breedOptions[i].name);}\n catch(e){\n console.error(e);\n getRandomDog();\n }\n }",
"function getImage(){\n var min = 0; \n var max = stock_images.length - 1; \n var random = Math.floor(Math.random() * (+max - +min)) + +min;\n return stock_images[random];\n}",
"getRandomImage() {\n return require(`./images/correct_${random(1,5)}.gif`);\n }",
"function displayGif(response){\n\tvar gif = randomElement(response.data);\n\tdocument.getElementById(\"weather-gif\").src = gif.embed_url;\n\n\t// Preferred way of setting gif: get direct link to gif and set it as a background, rather than use iframe\n\t// Unfortunately, Giphy gives 404 errors half the time when you link directly to a gif\n\t// var gifURL = \"http://i.giphy.com/\"+response.data[num].id+\".gif\";\n\t// document.body.style.backgroundImage = \"url('\"+gifURL+\"')\";\n}",
"function FetchHappyPicture() {\n fetch(\"http://api.giphy.com/v1/gifs/search?api_key=mcdoiGMok69AqKOKB7F4LrNYdoHVTdyB&q=happy&limit=10\").then(response => response.json())\n .then(json => {\n let randomIndex = Math.floor((Math.random() * 10).toFixed());\n ShowGiphyAlert(\"You made it!\", `<img src=\"${json.data[randomIndex].images.original.url}\"/>`);\n });\n}",
"function trendingGif(num){\n http.get(\"http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC&limit=100\", function(res){\n\n var body = '';\n var rand = Math.floor(Math.random()*100)-1;\n res.on('data', function(chunk){\n body += chunk;\n });\n res.on('end', function(){\n var data = JSON.parse(body);\n if(num != undefined && num >= 0 && num < 100){\n bot.say(config.channels[0], \"Trending gif \"+num+\"/100 \"+ data.data[num].images.original.url);\n } else {\n bot.say(config.channels[0], \"Trending gif \"+rand+\"/100 \"+ data.data[rand].images.original.url);\n }\n });\n });\n}",
"function showARandomPicture(){\n // generate a random number\n return Math.floor(Math.random() * productPicsArray.length);\n}",
"function showRandomIdle(){\n\tshowThis(\"cat_idle0\" + String(Math.ceil(Math.random()*arr_catImages_idle.length)));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.