query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Handles the click on the name of the folder in the explorer. | function onFolderNameClick() {
var clickedLink = $(this);
if (clickedLink.closest("li").hasClass("collapsed")) {
clickedLink.siblings('div').click();
}
const elementId = $(this).attr("data-id");
showFolderOrFileContentById(elementId);
} | [
"function clickFolder(e) {\n const folder = e.target.closest('.bookmark-folder');\n const subFolderBtn = e.target.closest('i.fa-level-down-alt');\n\n if (!folder) {\n return;\n }\n\n if (!!subFolderBtn) {\n if (parseInt(folder.dataset.folders) > 0) {\n setActiveFolderById(folder.dataset.id);\n }\n }\n else { \n toggleFolderSelection(folder);\n }\n }",
"function onDirectoryClick()\n\t{\n\t\tmoveToDirectory( this.getAttribute('data-path') + '/', true );\n\t}",
"function onFolderIconClick() {\n const folderId = $(this).siblings('a').attr(\"data-id\");\n if (fileSystem.hasSubfoldersById(folderId)) {\n $(this).parent().toggleClass(\"collapsed\");\n }\n }",
"function onContentItemClick() {\n var elementId = $(this).attr(\"data-id\");\n showFolderOrFileContentById(elementId);\n }",
"function folderLabelClick(folder_label){\n var folder_id = folder_label.data('fid');\n var folder_name = folder_label.text();\n $('#directory_trail').animate({\n width: $('#directory_trail').width()+55\n },300);\n var new_trail = $(\"<div class='folder_trail' data-fid =\"+folder_id+\">\"+ folder_name+\"</div>\");\n $('#directory_trail').append(new_trail);\n new_trail.css({\n left: $('#directory_trail').width()\n });\n display_folder(folder_id);\n}",
"function newFolderActionHandle(_container, _context, _fileTablePanel){\n\t\t\ton(registry.byId(\"da_newFolderMenuItem\"), \"click\", function(){\n\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\tdialog.show();\n\t\t\t});\n\n\t\t\t//new folder\n\t\t\ton(registry.byId(\"de_dialog_newFolder_okBtn\"), \"click\", function(){\n\t\t\t\tvar inputValue = registry.byId(\"de_dialog_newFolder_dirName\").value;\n\t\t\t\t\n\t\t\t\tvar cHost = _fileTablePanel.getHost();\n\t\t\t\tvar cPath = _fileTablePanel.getPath();\n\t\t\t\t\n\t\t\t\tvar url = _context.contextPath + \"/webservice/pac/data/action/mkdir?rnd=\" + (new Date()).getTime();\n\t\t\t\tvar path = encodeURIComponent(cPath + \"/\" + inputValue);\n\t\t\t\tvar postData = \"filePath=\" + path + \"&hostName=\" + cHost;\n\n\t\t\t\trequest.post(url, {\n\t\t\t\t\tdata : postData\n\t\t\t\t}).then(function(data) {\n\t\t\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\t\t\tif(data != null && data != \"\"){\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t\tshowMessage(data);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t//close the dialog and refrsh the file table\n\t\t\t\t\t\t\t_fileTablePanel.refresh(cHost, cPath);\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, function(err) {\n\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t}, function(evt) {\n\t\t\t\t\t\t//console.log(evt);\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"function browseFolder() \n{\n\t//Is the folder writable/unlocked?\n\tif (isSiteRootSane()) {\n\t\t//Set lib source folder\n\t\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\t\n\t\t// Call Dw to bring up the browse for folder dialog\n\t\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\t\tvar jQuerySourceFolder = dw.browseForFolderURL(dw.loadString(\"Commands/jQM/files/alert/browseFile\"), browseRoot, false);\n\t \n\t\tfindjQMFiles(jQuerySourceFolder);\n\t} else {\n\t\talert(dw.loadString(\"Commands/jQM/files/alert/lockedFolder\"));\n\t}\n}",
"function test_switch_to_tab_folder_a() {\n switch_tab(tabFolderA);\n assert_messages_in_view(setA);\n assert_nothing_selected();\n assert_folder_tree_focused();\n}",
"onButtonAddTableErDirClicked(e) {\n let erTree = new TadTableErTree();\n\n if ((this.gCurrent.erTreeNode !== null) && (this.gCurrent.erTreeNode !== undefined)) {\n if (this.gCurrent.erTreeNode.nodeType !== \"NODE_DIR\") return\n erTree.node_parent_id = this.gCurrent.erTreeNode.id;\n } else {\n erTree.node_parent_id = -1;\n }\n\n erTree.node_zhname = \"新增目录\";\n erTree.node_enname = \"newErDir\";\n erTree.node_type = \"NODE_DIR\";\n\n this.doAddTableErTree(erTree);\n }",
"function folderTrailClick(folder_trail){\n var folder_id = folder_trail.data('fid');\n //remove following trails\n var num_removed = folder_trail.nextAll().length;\n folder_trail.nextAll().remove();\n $('#directory_trail').animate({\n width: $('#directory_trail').width()- (55*num_removed)\n },300);\n //decrease with of the '#directory_trail'\n //check to see if the 'home' folder_trail was clicked\n if(folder_id == 'home'){\n display_home();\n }\n //selected folder_trail was not 'home' \n else{\n display_folder(folder_id); //display the folder that you clicked on \n }\n}",
"function getResultsDirForCase(tag) {\n var callback_on_accept = function(selectedValue) { \n \t\tconsole.log(selectedValue);\n \t\t// Convert to relative path.\n \t\tvar savefilepath = katana.$activeTab.find('#savefilepath').text();\n \t\tconsole.log(\"File path ==\", savefilepath);\n \t\t//var nf = katana.fileExplorerAPI.prefixFromAbs(pathToBase, selectedValue);\n \t\tvar nf = prefixFromAbs(savefilepath, selectedValue);\n \t\tkatana.$activeTab.find(tag).attr(\"value\", nf);\n \t\tkatana.$activeTab.find(tag).attr(\"fullpath\", selectedValue);\n\n };\n var callback_on_dismiss = function(){ \n \t\tconsole.log(\"Dismissed\");\n\t };\n katana.fileExplorerAPI.openFileExplorer(\"Select a file\", false , $(\"[name='csrfmiddlewaretoken']\").val(), false, callback_on_accept, callback_on_dismiss);\n}",
"function createNewFolder() {\n var id = $(this).parent().attr(\"data-id\");\n fileSystem.createFileOrFolder(id, \"folder\");\n updateUI();\n }",
"renameFolder(aFolder) {\n let folder = aFolder || GetSelectedMsgFolders()[0];\n\n let controller = this;\n function renameCallback(aName, aUri) {\n if (aUri != folder.URI)\n Cu.reportError(\"got back a different folder to rename!\");\n\n controller._resetThreadPane();\n let folderTree = GetFolderTree();\n folderTree.view.selection.clearSelection();\n\n folder.rename(aName, msgWindow);\n }\n\n window.openDialog(\"chrome://messenger/content/renameFolderDialog.xul\",\n \"\", \"chrome,modal,centerscreen\",\n {preselectedURI: folder.URI,\n okCallback: renameCallback, name: folder.prettyName});\n }",
"function displayFolderContent(folderElement) {\n var contentDiv = clearAndReturnContentDiv();\n var folderContent = fileSystem.sortFolderContent(folderElement.children);\n for (var i = 0; i < folderContent.length; i++) {\n var contentItem = $(\"<div data-id='\" + folderContent[i].id + \"'><div>\" + folderContent[i].name + \"</div></div>\");\n contentItem.addClass(\"contentItem\");\n contentItem.contextmenu(function (event) {\n showContextMenu(event);\n return false;\n });\n if (fileSystem.isFolder(folderContent[i])) {\n contentItem.attr(\"data-type\", \"folder\");\n $(\"<img src='_images/folder.png'/>\").prependTo(contentItem);\n } else {\n contentItem.attr(\"data-type\", \"file\");\n $(\"<img src='_images/file.png'/>\").prependTo(contentItem);\n }\n contentDiv.append(contentItem);\n contentItem.click(onContentItemClick);\n }\n }",
"function toggleFolderSelection(folderElement) {\n const index = currentSet.ids.indexOf(folderElement.dataset.id);\n\n if (index > -1) {\n currentSet.ids.splice(index, 1);\n }\n else {\n currentSet.ids.push(folderElement.dataset.id);\n }\n\n displayFolderCount();\n giveSaveBtnFeedback();\n folderElement.classList.toggle('selected', index === -1);\n }",
"function getResultsDirForCaseStep(tag) {\n var callback_on_accept = function(selectedValue) { \n \t\tconsole.log(selectedValue);\n \t\tvar popup = katana.$activeTab.find(\"#editCaseStepDiv\").attr('popup-id');\n\n \t\t// Convert to relative path.\n \t\tvar pathToBase = katana.$activeTab.find('#savefilepath').text();\n \t\tconsole.log(\"File path ==\", pathToBase);\n \t\t// var nf = katana.fileExplorerAPI.prefixFromAbs(pathToBase, selectedValue);\n \t\tvar nf = prefixFromAbs(pathToBase, selectedValue);\n \t\t\n \t\tpopup.find(tag).attr(\"value\", nf);\n \t\tpopup.find(tag).attr(\"fullpath\", selectedValue);\n\n };\n var callback_on_dismiss = function(){ \n \t\tconsole.log(\"Dismissed\");\n\t };\n\t //var popup = katana.$activeTab.find(\"#editCaseStepDiv\").attr('popup-id');\n katana.fileExplorerAPI.openFileExplorer(\"Select a file\", false , $(\"[name='csrfmiddlewaretoken']\").val(), false, callback_on_accept, callback_on_dismiss);\n}",
"function handleDriveClick(event) {\n document.getElementById(\"drive\").style.display = 'block';\n document.getElementById(\"home\").style.display = \"none\";\n AnalyticsManager.clickedDrive();\n}",
"addFolder(e) {\n e.preventDefault();\n if(this.props.client) {\n let clientName = this.props.client.clientName;\n let clientId = this.props.client.objectId;\n let subFolderName = this.refs.folderName.value.toLowerCase();\n store.fileStore.createSubFolder(clientName, clientId, subFolderName);\n\n } else {\n let clientName = this.refs.folderName.value;\n store.fileStore.createClientFolder(clientName);\n store.session.set({ addFolder: false});\n }\n }",
"uploadClick (){\n this.upload.click();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses given JSON Schema string. Prevents invalid JSON to be consumed by a validator. | resolveJsonSchema(jsonSchema) {
let resolvedJsonSchema = jsonSchema;
if (typeof jsonSchema === 'string') {
try {
resolvedJsonSchema = parseJson(jsonSchema);
} catch (error) {
const unparsableJsonSchemaError = new errors.SchemaNotJsonParsableError(
`Given JSON Schema is not a valid JSON. ${error.message}`
);
unparsableJsonSchemaError.schema = jsonSchema;
throw unparsableJsonSchemaError;
}
}
return resolvedJsonSchema;
} | [
"function IsValidJsonString(str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n }",
"parseJsonToObject(str) {\n try {\n const obj = JSON.parse(str);\n return obj;\n } catch (error) {\n return {};\n }\n }",
"function parseJSON(string) {\n function dateReviver(key, value) {\n var a;\n if (typeof value === 'string') {\n a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n }\n\n return JSON.parse(string, dateReviver);\n }",
"static loadAndValidate(jsonFilename, jsonSchema, options) {\n const jsonObject = JsonFile.load(jsonFilename);\n jsonSchema.validateObject(jsonObject, jsonFilename, options);\n return jsonObject;\n }",
"function parseJson (json) {\n try {\n return JSON.parse(json)\n } catch (_ignored) {\n ignore(_ignored)\n return undefined\n }\n }",
"static loadAndValidateWithCallback(jsonFilename, jsonSchema, errorCallback) {\n const jsonObject = JsonFile.load(jsonFilename);\n jsonSchema.validateObjectWithCallback(jsonObject, errorCallback);\n return jsonObject;\n }",
"function parseMessage(data) {\n if (isMessage(data)) {\n return data;\n }\n if (typeof data !== 'string') {\n throw new Error('Message not parsable');\n }\n const message = JSON.parse(data);\n if (!isMessage(message)) {\n throw new Error('Invalid message');\n }\n return message;\n }",
"_validate (schema){\n return SwaggerParser.validate(schema, this.options);\n }",
"parseFormat(dateString){\n\t\tlet format;\n\t\tlet validFormats = new Set(Object.getOwnPropertyNames(FORMAT));\n\t\tvalidFormats.forEach(valid => {\n\t\t\tlet regex = new RegExp(FORMAT[valid]['regex'], 'g');\n\t\t\tif(regex.test(dateString)){\n\t\t\t\tformat = valid;\n\t\t\t}\n\t\t});\n\t\tif(! format) \n\t\t\tthrow new Error(`Invalid Format: The given \"${dateString}\" does not conform to acceptable formats.`);\n\n\t\treturn format ; \n\t}",
"function parseString(str, isCorrect) {\n if ((str.indexOf(\"+\") || str.indexOf(\"-\") || str.indexOf(\"{\") || str.indexOf(\"}\") || str.indexOf(\"|\")) < 0) {\n return {\"value\": str, \"code\": null};\n }\n\n //weird cases: {+Plantations.-plantations. / Plantations.|508}\n //have to remove /Plantations.\n if (str.indexOf('/') > -1) {\n let toRemove = \"/ \" + str.match(/\\+(.*)\\-/)[1];\n str = str.replace(toRemove, '');\n }\n\n //removing whitespace... necessary?\n // str = str.replace(/^\\s+|\\s+$/g,'');\n //if + comes before -\n if (str.indexOf('+') < str.indexOf('-')){\n value = isCorrect ? str.match(/\\+(.*)\\-/).pop() : str.match(/\\-(.*)\\|/).pop();\n } else {\n //if - comes before +\n value = isCorrect ? str.match(/\\-(.*)\\+/).pop() : str.match(/\\+(.*)\\|/).pop();\n }\n\n let code = str.match(/\\|(.*)/)[1];\n storeConceptCode(str, code);\n return {\"value\": value, \"code\": code};\n}",
"validate (object, schema) {\n\n return JV.validate(object, schema);\n\n }",
"function ParseJson(jsonStr) {\r\n\r\n\t// Create htmlfile COM object\r\n\tvar HFO = CreateOleObject(\"htmlfile\"), jsonObj;\r\n\r\n\t// force htmlfile to load Chakra engine\r\n\tHFO.write(\"<meta http-equiv='x-ua-compatible' content='IE=9' />\");\r\n\r\n\t// Add custom method to objects\r\n\tHFO.write(\"<script type='text/javascript'>Object.prototype.getProp=function(t){return this[t]},Object.prototype.getKeys=function(){return Object.keys(this)};</script>\");\r\n\r\n\t// Parse JSON string\r\n\ttry jsonObj = HFO.parentWindow.JSON.parse(jsonStr);\r\n\texcept jsonObj = \"\"; // JSON parse error\r\n\r\n\t// Unload COM object\r\n\tHFO.close();\r\n\r\n\treturn jsonObj;\r\n}",
"function convertFromSchema(schema, options) {\n\tschema = convertSchema(schema, options);\n\n\tschema['$schema'] = 'http://json-schema.org/draft-04/schema#';\n\n\treturn schema;\n}",
"jsonErrorSchema() {\n return {\n type: \"object\",\n properties: {\n error: { type: \"string\" }\n },\n required: [\"error\"],\n additionalProperties: false\n }\n }",
"function JSONChecker()\n{\n}",
"function parseHeader(dataString) {\n\n // make sure all lines in the header are comma separated\n const commaLines = dataString.split('\\n').reduce((a, b) => {\n const r = b.trim();\n if (r.length !== 0) { // ignore empty lines\n a.push(r.slice(-1) === ',' ? r : `${r},`);\n }\n return a;\n }, []);\n\n // remove comma at end\n const joinedLines = commaLines.join('\\n').slice(0, -1);\n const wrapped = `{${joinedLines}}`;\n let json;\n\n try {\n json = JSON.parse(wrapped);\n } catch (e) {\n throw {\n data: wrapped,\n e,\n message: 'failed to parse the JSON header'\n };\n }\n\n return json;\n}",
"jsonSchema() {\n return {\n type: \"object\",\n properties: {\n result: { type: \"string\" }\n },\n required: [\"result\"],\n additionalProperties: false\n }\n }",
"function validateFormData(formData, schema, customValidate, transformErrors) {\n\t try {\n\t ajv$$1.validate(schema, formData);\n\t } catch (e) {\n\t // swallow errors thrown in ajv due to invalid schemas, these\n\t // still get displayed\n\t }\n\n\t var errors = transformAjvErrors(ajv$$1.errors);\n\n\t if (typeof transformErrors === \"function\") {\n\t errors = transformErrors(errors);\n\t }\n\t var errorSchema = toErrorSchema(errors);\n\n\t if (typeof customValidate !== \"function\") {\n\t return { errors: errors, errorSchema: errorSchema };\n\t }\n\n\t var errorHandler = customValidate(formData, createErrorHandler(formData));\n\t var userErrorSchema = unwrapErrorHandler(errorHandler);\n\t var newErrorSchema = (0, utils.mergeObjects)(errorSchema, userErrorSchema, true);\n\t // XXX: The errors list produced is not fully compliant with the format\n\t // exposed by the jsonschema lib, which contains full field paths and other\n\t // properties.\n\t var newErrors = toErrorList(newErrorSchema);\n\n\t return { errors: newErrors, errorSchema: newErrorSchema };\n\t}",
"async getJsonSchema(obj) {\n var self = this;\n\n // start creating the schema\n var jsonSchema = {\n definitions: {},\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {}\n }\n var properties = {}\n var required = []\n\n // interpret the info message and create json schema\n self.rawSql.split('\\n').forEach(function (rawLine, index) {\n var line = self.sanitizeLine(rawLine)\n\n // ignore lines we're not interested in\n // TODO: these are important:\n // CONSTRAINT - primary key(s)\n // ALTER TABLE - foreign keys\n if (\n line.startsWith(\"CREATE\") ||\n line.startsWith(\"ALTER TABLE\") ||\n line.startsWith(\"CONSTRAINT\") ||\n line.startsWith('(') ||\n line.startsWith(')') ||\n line.length == 0\n ) {\n return\n }\n\n var lineSplit = line.trim().split(' ')\n\n // remove the brackets from the col name\n const columnName = lineSplit[0].substring(1, lineSplit[0].length-1);\n const dataType = lineSplit[1]\n\n properties[columnName] = {}\n // set description as the col type\n properties[columnName].description = dataType\n\n var dataTypeOnly = dataType.replace(/\\(.*\\)/, '')\n\n var isString = false\n // useful: https://www.connectionstrings.com/sql-server-2008-data-types-reference/\n switch (dataTypeOnly.toUpperCase()) {\n case 'BIGINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = Math.pow(-2, 63)\n properties[columnName].exclusiveMaximum = Math.pow(2, 63)\n break\n case 'INT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = -2147483648\n properties[columnName].maximum = 2147483647\n break\n case 'SMALLINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = -32768\n properties[columnName].maximum = 32767\n break\n case 'TINYINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = 0\n properties[columnName].maximum = 255\n break\n case \"BIT\":\n properties[columnName].type = 'boolean'\n break\n case \"DECIMAL\":\n case \"NUMERIC\":\n properties[columnName].type = 'number'\n properties[columnName].exclusiveMinimum = Math.pow(-10, 38)\n properties[columnName].exclusiveMaximum = Math.pow(10, 38)\n break\n case \"MONEY\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = Math.pow(-2, 63) / 10000\n properties[columnName].maximum = (Math.pow(2, 63) - 1) / 10000\n break\n case \"SMALLMONEY\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -214748.3648\n properties[columnName].maximum = 214748.3647\n break\n case \"FLOAT\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -1.79e308\n properties[columnName].maximum = 1.79e308\n break\n case \"REAL\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -3.40e38\n properties[columnName].maximum = 3.40e38\n break\n case \"DATETIME\":\n case \"SMALLDATETIME\":\n case \"DATETIME2\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"date-time\"\n break\n case \"DATE\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"date\"\n break\n case \"TIME\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"time\"\n break\n case 'CHAR':\n isString = true\n properties[columnName].maxLength = 8000\n break\n case \"NCHAR\":\n isString = true\n properties[columnName].maxLength = 8000\n break\n case 'VARCHAR':\n isString = true\n properties[columnName].maxLength = Math.pow(2, 31)\n break\n case 'NVARCHAR':\n isString = true\n properties[columnName].maxLength = Math.pow(2, 30)\n break\n case \"TEXT\":\n isString = true\n properties[columnName].maxLength = 2147483647\n break\n case \"NTEXT\":\n isString = true\n properties[columnName].maxLength = 1073741823\n break\n case \"UNIQUEIDENTIFIER\":\n properties[columnName].type = 'string'\n properties[columnName].format = \"uuid\"\n properties[columnName].minLength = 36\n properties[columnName].maxLength = 36\n break;\n case \"XML\":\n properties[columnName].type = 'string'\n break\n // unsupported yet\n //case \"DATETIMEOFFSET\":\n //case \"BINARY\":\n //case \"VARBINARY\":\n //case \"IMAGE\":\n //case \"GEOGRAPHY\":\n //case \"GEOMETRY\":\n //case \"HIERARCHYID\":\n default:\n throw ('Unknown type: ' + dataType)\n }\n\n // handle extra stuff for strings\n if (isString) {\n properties[columnName].type = 'string'\n properties[columnName].minLength = 0\n\n // extract the max length\n var maxLength = dataType.substring(\n dataType.lastIndexOf(\"(\") + 1,\n dataType.lastIndexOf(\")\")\n );\n\n // if this isnt set to max then include it (max was set above)\n if (maxLength.toLowerCase() != 'max') {\n properties[columnName].maxLength = parseInt(maxLength)\n }\n }\n\n // check if it can be null\n if (line.endsWith(\"NOT NULL\")) {\n required.push(columnName)\n }\n });\n\n // sew the schema together\n jsonSchema.properties = properties\n jsonSchema.required = required\n\n return JSON.stringify(jsonSchema)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor, for users who consider it annoying. | get ConfigInputTextCursorBlink() { return this.native.ConfigInputTextCursorBlink; } | [
"_setDefault(){\n this.defaultCursor = \"default\";\n // this.hOverCursor = \"pointer\";\n }",
"function pauseCursorBlink() {\n \n // Remove and add \"blinking\"-class\n inputCurrent.removeClass(CLASS_BLINK);\n setTimeout(function() {\n inputCurrent.addClass(CLASS_BLINK);\n }, TIME_PAUSE);\n }",
"function blinkCursor() {\n\t\tcursor.style.textDecoration = \"underline\";\n\t\tsetTimeout(function () {\n\t\t\tcursor.style.textDecoration = \"\";\n\t\t\tsetTimeout(blinkCursor, 500);\n\t\t}, 500);\n\t}",
"showSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(false);\n this._cursorTracker.set_pointer_visible(true);\n }",
"function changeCursor(cursor) {\n document.body.style.cursor = cursor; \n}",
"function OnQueryCursor(/*object*/ sender, /*QueryCursorEventArgs*/ e)\r\n { \r\n /*Hyperlink*/var link = sender;\r\n\r\n if (link.IsEnabled && link.IsEditable)\r\n { \r\n if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)\r\n { \r\n e.Cursor = link.TextContainer.TextSelection.TextEditor._cursor; \r\n e.Handled = true;\r\n } \r\n }\r\n }",
"function displayInput(){\r\n\tdrawNewInput();\r\n\tscrollToEnd();\r\n}",
"function flashCursor() {\n cursor.style.background = \"#e0556170\";\n setTimeout(() => {\n cursor.style.background = \"#5dbeff\";\n }, 100);\n }",
"function setStatusButton(status, cursorStyle) {\n button.disabled = status;\n button.style.cursor = cursorStyle;\n}",
"updateCaret() {\n\t\tthis.caret = this.textarea.selectionStart;\n\t}",
"function add_character_move_cursor(input_string) {\r\n\ttextarea_element.setRangeText(input_string, textarea_element.selectionStart, textarea_element.selectionEnd, \"end\");\r\n\t//textarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}",
"responding(){\n setTimeout(_=>{\n this.focusInput()\n })\n }",
"flashCursor() {\n if ( this.cursorTimer ) return;\n\n var toggle = function() {\n return setTimeout( function() {\n this.cursorElement.classList.toggle( 'hidden' );\n this.cursorTimer = toggle();\n }.bind( this ), 350 );\n }.bind( this );\n\n this.cursorTimer = toggle();\n }",
"function hintStyle() {\n \n document.getElementById(\"hint\").style.display = \"none\";\n document.getElementById(\"hintDisplay\").style.display = \"inherit\";\n document.getElementById(\"hintDisplay\").style.margin = \"90px 0px -64px 18px\";\n \n}",
"hideSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(true);\n this._cursorTracker.set_pointer_visible(false);\n }",
"function setCaretPosition(position) {\n\tdocument.getElementById(\"content-editor\").setSelectionRange(position, position);\n\tdocument.getElementById(\"content-editor\").focus();\n}",
"__refreshCursor() {\n var currentCursor = this.getStyle(\"cursor\");\n this.setStyle(\"cursor\", null, true);\n this.setStyle(\"cursor\", currentCursor, true);\n }",
"function setCursorPosition(field, position){\n \n // If not focused, set focus on field\n \n if(!$(field).is(':focus')){\n \n $(field).focus();\n \n }\n \n // Set cursor position for field\n \n field.selectionStart = position;\n field.selectionEnd = position;\n}",
"function resetCursorPos(element) {\n element.selectionStart = 0;\n element.selectionEnd = 0;\n }",
"async preventKeyEvent() {\n this.dummyTextArea.focus();\n await sleep(0);\n this.focus();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to create TimeSlot and save in database Removes other entires that belong to the current user | async function createTimeSlots() {
if (!formData.slot1 || !formData.slot2 || !formData.slot3) return;
formData.userid = (await Auth.currentSession()).getIdToken().payload["cognito:username"];
// Loop through TimeSlots and remove any that belong to the current user
var timeSlots;
for (timeSlots in timeSlotss) {
var tempTimeSlots = timeSlotss.[timeSlots];
if (re.localeCompare(new String(tempTimeSlots.userid)) == 0) {
deleteTimeSlots(tempTimeSlots);
}
}
await API.graphql({ query: createTimeSlotsMutation, variables: { input: formData } });
setTimeSlots([...timeSlotss, formData]);
setFormData(initialFormState);
} | [
"function saveTime() {\n firebase.auth().onAuthStateChanged(function (user) {\n let d = new Date();\n let showerDate = d.toDateString().slice(0, 15);\n let userRef = db.collection(\"users\").doc(user.uid);\n userRef.collection(\"times\").add({\n date: showerDate,\n time: currentTimer\n })\n document.getElementById(\"saveButton\").style.visibility = \"hidden\";\n document.getElementById(\"main-timer-button\").onclick = startTimer;\n document.getElementById(\"timer-number\").innerHTML = \"00:00:000\"\n });\n}",
"function addNewTimeslot(event) {\r\n\r\n // Remove the dialogclose binding, or it will fire once for every\r\n // time the dialog has been created, causing multiple refreshes\r\n // every time the dialog is closed.\r\n jQuery('#timeslot_dialog').unbind('dialogclose');\r\n\r\n // Refresh the calendar on dialog close. The dialog is closed after saving,\r\n // canceling or deleting, and the calendar should be updated in all three of\r\n // those cases.\r\n jQuery('#timeslot_dialog').bind('dialogclose', function(closeEvent) {\r\n jQuery('#calendar').weekCalendar('refresh');\r\n });\r\n\r\n // Fill in the codeblock select element with the current codeblocks\r\n populateWithCodeblocks(jQuery('#timeslot_codeblock'));\r\n\r\n // Populate the form with the time and date from the event\r\n jQuery('#timeslot_start_time').val(event.start.toString(\"hh:mm tt\"));\r\n jQuery('#timeslot_end_time').val(event.end.toString(\"hh:mm tt\"));\r\n\r\n jQuery('#timeslot_start_date').val(event.start.toString(\"dd/MM/yyyy\"));\r\n jQuery('#timeslot_end_date').val(event.end.toString(\"dd/MM/yyyy\"));\r\n\r\n // Enable the day on which this event was created, and no others.\r\n jQuery('.timeslot_day').prop('checked', false);\r\n\r\n switch (event.start.getDay()) {\r\n case 1:\r\n jQuery('#timeslot_on_monday').prop('checked', true);\r\n break;\r\n case 2:\r\n jQuery('#timeslot_on_tuesday').prop('checked', true);\r\n break;\r\n case 3:\r\n jQuery('#timeslot_on_wednesday').prop('checked', true);\r\n break;\r\n case 4:\r\n jQuery('#timeslot_on_thursday').prop('checked', true);\r\n break;\r\n case 5:\r\n jQuery('#timeslot_on_friday').prop('checked', true);\r\n break;\r\n case 6:\r\n jQuery('#timeslot_on_saturday').prop('checked', true);\r\n break;\r\n case 0:\r\n jQuery('#timeslot_on_sunday').prop('checked', true);\r\n break;\r\n }\r\n\r\n // Display the timeslot add dialog. This dialog has three buttons: Save,\r\n // Delete and Cancel. Save sends a request to the server to add a new\r\n // timeslot, Delete and Cancel are synonyms that do nothing. After all three\r\n // complete, the dialog is closed, which sends a request to the server for a\r\n // refresh. In the case of save, that means that the new timeslot is\r\n // displayed on the calendar. For the other two, it means the placeholds\r\n // event created by dragging will disappear.\r\n jQuery('#timeslot_dialog')\r\n .dialog(\r\n 'option',\r\n 'buttons',\r\n {\r\n \"Save\" : function() {\r\n\r\n // Read in the date information from the timeslot\r\n // form. The hours can be in various formats and\r\n // still be read, but the dates must be in day month\r\n // year form, separated by slashes. This shouldn't\r\n // be a problem, as the pop up calendar does this\r\n // automatically.\r\n var startTime = tryToParse(jQuery('#timeslot_start_time')\r\n .val());\r\n var endTime = tryToParse(jQuery('#timeslot_end_time').val());\r\n var startDate = Date.parseExact(jQuery(\r\n '#timeslot_start_date').val(), \"dd/MM/yyyy\");\r\n var endDate = Date.parseExact(jQuery('#timeslot_end_date')\r\n .val(), \"dd/MM/yyyy\");\r\n\r\n // Send a request to the server to create the\r\n // timeslot, along with the parsed date information\r\n // in the interchange format.\r\n jQuery.post(ajaxurl, {\r\n action : \"tw-ajax-timeslot-add-update\",\r\n codeblock_id : jQuery('#timeslot_codeblock').val(),\r\n schedule_id : current_schedule_id,\r\n start_time : startTime.toString(\"HHmm\"),\r\n end_time : endTime.toString(\"HHmm\"),\r\n start_date : startDate.toString(\"yyyyMMdd\"),\r\n end_date : endDate.toString(\"yyyyMMdd\"),\r\n on_monday : jQuery('#timeslot_on_monday:checked').prop(\r\n 'checked'),\r\n on_tuesday : jQuery('#timeslot_on_tuesday:checked')\r\n .prop('checked'),\r\n on_wednesday : jQuery('#timeslot_on_wednesday:checked')\r\n .prop('checked'),\r\n on_thursday : jQuery('#timeslot_on_thursday:checked')\r\n .prop('checked'),\r\n on_friday : jQuery('#timeslot_on_friday:checked').prop(\r\n 'checked'),\r\n on_saturday : jQuery('#timeslot_on_saturday:checked')\r\n .prop('checked'),\r\n on_sunday : jQuery('#timeslot_on_sunday:checked').prop(\r\n 'checked')\r\n }, function() {\r\n // When the request comes back, close the\r\n // dialog. This will trigger an update of the\r\n // calendar data, which should reflect the new\r\n // timeslot being added.\r\n jQuery('#timeslot_dialog').dialog('close');\r\n });\r\n },\r\n \"Delete\" : function() {\r\n // Close the dialog without saving any changes. This\r\n // will trigger a refresh of calendar data, and so\r\n // the placeholder event should disappear.\r\n jQuery('#timeslot_dialog').dialog('close');\r\n },\r\n \"Cancel\" : function() {\r\n // Close the dialog without saving any changes. This\r\n // will trigger a refresh of calendar data, and so\r\n // the placeholder event should disappear.\r\n jQuery('#timeslot_dialog').dialog('close');\r\n }\r\n });\r\n // Display the dialog.\r\n jQuery('#timeslot_dialog').dialog('open');\r\n}",
"async function addSchedule(ctx) {\n const { usernamect, availdate} = ctx.params;\n try {\n const sqlQuery = `INSERT INTO parttime_schedules VALUES ('${usernamect}', '${availdate}')`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'username_caretaker': usernamect,\n 'availdate': availdate\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}",
"createAppointment(event) {\n event.preventDefault()\n const selectedDate = this.refs.selectedDate.value;\n const selectedTime = this.refs.selectedTime.value;\n var patientDescription = this.refs.selectedPatient.value;\n var patient = this.findPatientIndex(patientDescription, this.state.patientsList);\n var fullTime = selectedDate + \" \" + selectedTime;\n var finalTime = moment(fullTime, \"YYYY-MM-DD hh:mm A\").unix();\n\n if(!patient){\n alert(\"Please select a valid patient!\");\n }else if(moment(selectedDate).isValid() === false\n || moment(selectedDate).isSameOrAfter(moment(), 'day') === false){\n alert(\"Please check if the date is valid and not in the past!\");\n }else if(moment.unix(finalTime).isSameOrAfter(moment(), 'minute') === false){\n alert(\"Please select a valid time!\");\n }else{\n var appt = {\n patientUuid: patient.patientUUID,\n doctorUuid: sessionStorage.userUUID,\n dateScheduled: finalTime\n }\n\n requests.postFutureAppointment(appt)\n .then((res) => {\n console.log(\"created future appointment sucessfully\");\n location.reload();\n })\n .catch((e) =>{\n console.log(\"Could not create future appointment\");\n });\n }\n }",
"function deleteTimeDetails() {\n let timeDetails = myStorage.timeDetails;\n timeDetails = null;\n myStorage.timeDetails = timeDetails;\n myStorage.sync();\n}",
"function updateTimeslot(calEvent) {\r\n\r\n // Get the information about the event's timeslot from the server.\r\n jQuery.post(ajaxurl, {\r\n action : \"tw-ajax-get-timeslot\",\r\n timeslot_id : calEvent.timeslot_id\r\n }, function(response) {\r\n // If the server was able to retrieve the timeslot's information, then\r\n // populate the timeslot dialog with information and display it.\r\n if (response.success) {\r\n // Fill in the codeblock select element with the current codeblocks\r\n populateWithCodeblocks(jQuery('#timeslot_codeblock'));\r\n\r\n // Populate the form with dates and times from the server's\r\n // response. All dates and times are in the interchange format.\r\n jQuery('#timeslot_codeblock').val(response.timeslot.codeblock_id);\r\n\r\n jQuery('#timeslot_start_time').val(\r\n Date.parseExact(response.timeslot.start_time, \"HHmm\").toString(\r\n \"hh:mm tt\"));\r\n jQuery('#timeslot_end_time').val(\r\n Date.parseExact(response.timeslot.end_time, \"HHmm\").toString(\r\n \"hh:mm tt\"));\r\n\r\n jQuery('#timeslot_start_date').val(\r\n Date.parseExact(response.timeslot.start_date, \"yyyyMMdd\")\r\n .toString(\"dd/MM/yyyy\"));\r\n jQuery('#timeslot_end_date').val(\r\n Date.parseExact(response.timeslot.end_date, \"yyyyMMdd\")\r\n .toString(\"dd/MM/yyyy\"));\r\n\r\n // Read in which days the timeslot is enabled on.\r\n jQuery('#timeslot_on_monday').prop('checked',\r\n response.timeslot.onMonday);\r\n jQuery('#timeslot_on_tuesday').prop('checked',\r\n response.timeslot.onTuesday);\r\n jQuery('#timeslot_on_wednesday').prop('checked',\r\n response.timeslot.onWednesday);\r\n jQuery('#timeslot_on_thursday').prop('checked',\r\n response.timeslot.onThursday);\r\n jQuery('#timeslot_on_friday').prop('checked',\r\n response.timeslot.onFriday);\r\n jQuery('#timeslot_on_saturday').prop('checked',\r\n response.timeslot.onSaturday);\r\n jQuery('#timeslot_on_sunday').prop('checked',\r\n response.timeslot.onSunday);\r\n\r\n // Remove the dialogclose binding, or it will fire once for every\r\n // time the dialog has been created, causing multiple refreshes\r\n // every time the dialog is closed.\r\n jQuery('#timeslot_dialog').unbind('dialogclose');\r\n\r\n // Refresh the calendar on dialog close. The dialog is closed after\r\n // saving, canceling or deleting, and the calendar should be updated\r\n // unless there is a cancel, in which case the refresh is disabled.\r\n jQuery('#timeslot_dialog').bind('dialogclose',\r\n function(closeEvent) {\r\n jQuery('#calendar').weekCalendar('refresh');\r\n });\r\n\r\n // Display the timeslot edit dialog. This dialog has three buttons:\r\n // Save, Delete and Cancel. Save sends a request to the server to\r\n // update the timeslot information. Delete sends a request to the\r\n // server to update the current timeslot's information. Cancel\r\n // simply closes the dialog with no changes made.\r\n jQuery('#timeslot_dialog').dialog(\r\n 'option',\r\n 'buttons',\r\n {\r\n \"Save\" : function() {\r\n\r\n // Read in the date information from the timeslot\r\n // form. The hours can be in various formats and\r\n // still be read, but the dates must be in day month\r\n // year form, separated by slashes. This shouldn't\r\n // be a problem, as the pop up calendar does this\r\n // automatically.\r\n var startTime = tryToParse(jQuery(\r\n '#timeslot_start_time').val());\r\n var endTime = tryToParse(jQuery('#timeslot_end_time')\r\n .val());\r\n var startDate = Date.parseExact(jQuery(\r\n '#timeslot_start_date').val(), \"dd/MM/yyyy\");\r\n var endDate = Date.parseExact(jQuery(\r\n '#timeslot_end_date').val(), \"dd/MM/yyyy\");\r\n // Send a request to the server to update the\r\n // timeslot, along with the parsed date information\r\n // in the interchange format.\r\n jQuery.post(ajaxurl, {\r\n action : \"tw-ajax-timeslot-add-update\",\r\n timeslot_id : calEvent.timeslot_id,\r\n schedule_id : current_schedule_id,\r\n codeblock_id : jQuery('#timeslot_codeblock').val(),\r\n start_time : startTime.toString(\"HHmm\"),\r\n end_time : endTime.toString(\"HHmm\"),\r\n start_date : startDate.toString(\"yyyyMMdd\"),\r\n end_date : endDate.toString(\"yyyyMMdd\"),\r\n on_monday : jQuery('#timeslot_on_monday:checked')\r\n .prop('checked'),\r\n on_tuesday : jQuery('#timeslot_on_tuesday:checked')\r\n .prop('checked'),\r\n on_wednesday : jQuery(\r\n '#timeslot_on_wednesday:checked').prop(\r\n 'checked'),\r\n on_thursday : jQuery(\r\n '#timeslot_on_thursday:checked')\r\n .prop('checked'),\r\n on_friday : jQuery('#timeslot_on_friday:checked')\r\n .prop('checked'),\r\n on_saturday : jQuery(\r\n '#timeslot_on_saturday:checked')\r\n .prop('checked'),\r\n on_sunday : jQuery('#timeslot_on_sunday:checked')\r\n .prop('checked')\r\n }, function() {\r\n // When the request comes back, close the\r\n // dialog. This will trigger an update of the\r\n // calendar data, which should reflect the edits\r\n // done to the timeslot.\r\n jQuery('#timeslot_dialog').dialog('close');\r\n });\r\n },\r\n \"Delete\" : function() {\r\n // If the delete button is pressed, then we request\r\n // the server removes the current timeslot\r\n jQuery.post(ajaxurl, {\r\n action : \"tw-ajax-timeslot-remove\",\r\n timeslot_id : calEvent.timeslot_id\r\n }, function() {\r\n // Close the dialog, triggering a refresh of the\r\n // calendar, which will remove the deleted\r\n // timeslot from view.\r\n jQuery('#timeslot_dialog').dialog('close');\r\n });\r\n },\r\n \"Cancel\" : function() {\r\n // Disable the refresh that happens when the dialog\r\n // is closed.\r\n jQuery('#timeslot_dialog').unbind('dialogclose');\r\n\r\n // Close the timeslot editing dialog\r\n jQuery('#timeslot_dialog').dialog('close');\r\n }\r\n });\r\n\r\n // Open the dialog.\r\n jQuery('#timeslot_dialog').dialog('open');\r\n }\r\n\r\n });\r\n}",
"function setSchedule(hour){\n localStorage.setItem(hour, $(\"#hour\"+hour).val());\n}",
"function saveAndStore() {\n console.log('saveAndStore was run');\n\n i = allTrips.length;\n\n var beginTrip = document.getElementById(\"beginPoint\").value;\n var endTrip = document.getElementById(\"endPoint\").value;\n var typeTrip = document.getElementById(\"mode\").value;\n var tripDistance = document.getElementById(\"distance\").innerHTML;\n var tripDuration = document.getElementById(\"duration\").innerHTML;\n var tripArticleType = document.getElementById(\"articleType\").value;\n allTrips.push({start: beginTrip, destination: endTrip, type: typeTrip, distance: tripDistance, duration: tripDuration, choice: tripArticleType, id: i++});\n\n listTrip(\"all\", allTrips);\n \n // Searches for what type of trip was taken and runs listTrip to place it into that specific tab\n if(document.getElementById(\"mode\").value == \"DRIVING\") {\n var drivingTrips = allTrips.filter(function(trip){ return trip.type === \"DRIVING\"});\n listTrip(\"driving\", drivingTrips);\n } else if(document.getElementById(\"mode\").value == \"BICYCLING\") {\n var bicyclingTrips = allTrips.filter(function(trip){ return trip.type === \"BICYCLING\"});\n listTrip(\"biking\", bicyclingTrips);\n } else if(document.getElementById(\"mode\").value == \"TRANSIT\") {\n var transitTrips = allTrips.filter(function(trip){ return trip.type === \"TRANSIT\"});\n listTrip(\"public\", transitTrips);\n } else if(document.getElementById(\"mode\").value == \"WALKING\") {\n var walkingTrips = allTrips.filter(function(trip){ return trip.type === \"WALKING\"});\n listTrip(\"walking\", walkingTrips);\n }\n\n storeTrip();\n\n $(\"#beginPoint\").val(\"\");\n $(\"#endPoint\").val(\"\");\n $(\"#mode\").val(\"\");\n $(\"#articleType\").val(\"\");\n}",
"async function fetchTimeSlots() {\n const apiData = await API.graphql({ query: listTimeSlotss });\n setTimeSlots(apiData.data.listTimeSlotss.items);\n }",
"function saveSchedules() {\n\t\tlocalStorage.setItem(\"aPossibleSchedules\", JSON.stringify(aPossibleSchedules));\n\t}",
"function registerAppointment() {\n const submittedData = {};\n\n // Make a timestamp with date and time and add it to json\n let dateTimestampInSeconds = convertDateToTimestamp(document.getElementById(\"appointment-date\").value);\n let timepickerValue = document.getElementById(\"appointment-time\").value;\n if (!timepickerValue) {\n alert(\"Wybierz godzinę wizyty\");\n return;\n }\n\n let timeInSeconds = convertTimepickerValueToSeconds(timepickerValue);\n if (!validateTimepickerValue(timeInSeconds)) {\n return;\n }\n let dateTimeInSeconds = dateTimestampInSeconds + timeInSeconds;\n submittedData.startDate = dateTimeInSeconds;\n\n let selectDuration = document.getElementById(\"select-duration\");\n let appointmentDuration = selectDuration.options[selectDuration.selectedIndex].value;\n // Appointment duration should be presented in seconds\n if (appointmentDuration == 1) {\n submittedData.duration = 3600;\n } else if (appointmentDuration == 2) {\n submittedData.duration = 7200;\n } else submittedData.duration = 0;\n\n // Doctor email\n let selectDoctor = document.getElementById(\"select-doctor\");\n let doctorValue = selectDoctor.options[selectDoctor.selectedIndex].value;\n submittedData.mail = doctorValue;\n\n if (!validateFormInput(submittedData)) {\n // Data is not valid, don't send it\n return;\n }\n\n // Send data to sever and react to responses\n let xhr = new XMLHttpRequest();\n xhr.open(\"POST\", chooseProtocol() + window.location.host + \"/api/appointment/new\", true);\n xhr.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n xhr.addEventListener('load', function () {\n if (this.status === 200) {\n const response = this.response;\n\n // Show message to user, after user clicks 'OK', redirecting to login screen\n alert(\"Wizyta została poprawnie utworzona\");\n\n } else if (this.status === 400) {\n const response = JSON.parse(this.responseText);\n // Sent data was wrong, show message to user\n alert(response.error);\n }\n });\n xhr.send(JSON.stringify(submittedData));\n}",
"'userTasks.createUserTask'(taskId, fCompletionState) {\n check(taskId, Mongo.ObjectID);\n check(fCompletionState, Boolean);\n const userId = Meteor.userId();\n const task = Tasks.findOne(taskId);\n\n if (!task) {\n throw new Meteor.Error('invalid-parameter', \"the given taskId does not have an associated task\");\n }\n\n if (UserTasks.findOne({task_id: taskId})) {\n throw new Meteor.Error('bad-state', \"the given user has already received this task.\");\n }\n\n var today = new Date();\n today.setUTCHours(0,0,0,0);\n var tomorrow = new Date(today);\n tomorrow.setUTCHours(23, 59, 59, 999)\n\n var userTask = {\n user_id: userId,\n task_type: task.task_type,\n task_id: task._id,\n task_statistics: \"TBA\",\n given_on: new Date(),\n lasts_until: tomorrow,\n is_active : true,\n is_completed: false,\n is_repeatable: false,\n never_show_again: false,\n group_id: task.group_id\n }\n\n const userTaskId = UserTasks.insert(userTask);\n Meteor.users.update(userId, {$inc: {\"statistics.activeTasks\":1}});\n if (fCompletionState) {\n Meteor.call('userTasks.completeTask', userTaskId);\n }\n }",
"add(appointment) {\n this.timeSlots = this.timeSlots.filter(timeSlot => {\n return timeSlot.startsAt !== appointment.startsAt\n });\n this.appointments.push(appointment)\n return appointment;\n }",
"function SaveAddTimeperiode(Number){\r\n\tvar StartTime = $(\"#StartTime\"+Number).val();\r\n\tvar StopTime = $(\"#StopTime\"+Number).val();\r\n\tvar timePeriode = $(\"#TimePeriode\"+Number).text();\r\n\t\r\n\twriteAddData(StartTime,StopTime,timePeriode,Number, function(Data){\r\n\t\tif (Data.write == 'success'){\r\n\t\t\t$(\"#tableCleaningInterval div\").remove();\r\n\t\t\tupdateTableafterChange();\r\n\t\t\t}\r\n\t});\t\r\n}",
"function createButtonElement(inputHour) {\n let buttonEl = $(\"<button class=\\\"saveBtn col-2 col-md-1 fas fa-save\\\"></button>\");\n $(buttonEl).click (function (event) {\n //append the hour and date to the local storage name so that it will not show prev day events\n localStorage.setItem(\"slot-\"+ inputHour + moment().format(\"DDMMYY\"), event.target.previousElementSibling.value)\n });\n return buttonEl;\n}",
"function handleAdd() {\n if (selectedTimeZone) {\n let newTimeZones = [...myTimeZones, selectedTimeZone]\n setMyTimeZones(newTimeZones)\n localStorage.setItem(TIME_ZONE_KEY, JSON.stringify(newTimeZones))\n }\n }",
"function createAccount()\n{\n let nameRef = document.getElementById(\"name\");\n let emailIdRef = document.getElementById(\"emailId1\");\n let password1Ref = document.getElementById(\"password1\");\n let password2Ref = document.getElementById(\"password2\");\n if(password1Ref.value == password2Ref.value)\n {\n accounts.addAccount(emailIdRef.value);\n let user = accounts.getAccount(accounts.count - 1); //to get the last account\n user.name = nameRef.value;\n user.password = password1Ref.value;\n if (getDataLocalStorageTrip() != undefined)\n {\n let trip = getDataLocalStorageTrip();\n user.addTrip(trip._tripId);\n //subtracting -1 to access the last trip\n user.getTripIndex(user._trips.length -1)._country = trip._country;\n user.getTripIndex(user._trips.length -1)._date = trip._date;\n user.getTripIndex(user._trips.length -1)._start = trip._start;\n user.getTripIndex(user._trips.length -1)._end = trip._end;\n user.getTripIndex(user._trips.length -1)._stops = trip._stops;\n trip = \"\"; //to clear the trip local data\n updateLocalStorageTrip(trip);\n }\n updateLocalStorageUser(user)\n updateLocalStorageAccount(accounts); //updating the new accounts array into the local storage\n alert(\"Account created successfully\");\n window.location = \"index.html\"; \n }\n else\n {\n alert(\"ERROR! Password does not match\");\n }\n}",
"function submitForm(){\n let form = document.querySelector(Form.id);\n let appointment = Object.create(Appointment);\n appointment.who = form.querySelector(\"[name=who]\").value;\n appointment.about = form.querySelector(\"[name=about]\").value;\n appointment.agenda = form.querySelector(\"[name=agenda]\").value;\n let day = form.querySelector(\"[name=day]\").value;\n appointment.day = day;\n // Create a random id if it is a new appointment\n appointment.id = form.querySelector(\"[name=id]\").value || \n 'appointment-'+\n form.querySelector(\"[name=day]\").value+'-'+\n (1+Math.random()).toString(36).substring(7)\n ;\n Calendar.appointments[day] = appointment;\n closeForm();\n showNewAppointment(appointment);\n showMessage(\"Success\", \"Your appointment has been sucessfully saved.\");\n}",
"function makeWorkout(number) {\n \n var time_created = parseInt(1435000000 + number * Math.random());\n var time_completed = time_created + 50000;\n var date = 20151000 + parseInt(Math.random() * 30);\n var steps = parseInt(Math.random() * 2000);\n var time = parseInt(Math.random() * 4000);\n var meters = parseInt(Math.random() * 5000);\n var calories = parseInt(Math.random() * 600);\n var intensity = parseInt(Math.random() * 5);\n\n var newWorkout = new workout({\n userID: 1,\n xid: \"xid goes here\",\n date: date,\n title: 'Run',\n steps: steps,\n time: time,\n meters: meters,\n calories: calories,\n intensity: intensity,\n time_created: time_created,\n time_completed: time_completed\n });\n\n testWorkouts.push({\n userID: 1,\n xid: \"xid goes here\",\n date: date,\n title: 'Run',\n steps: steps,\n time: time,\n meters: meters,\n calories: calories,\n intensity: intensity,\n time_created: time_created,\n time_completed: time_completed\n });\n\n if (time_completed > lastWorkout.time_completed) {\n lastWorkout = testWorkouts[testWorkouts.length - 1];\n }\n\n totalStepsWorkout += steps;\n totalTimeWorkout += time;\n totalCaloriesWorkout += calories;\n totalDistanceWorkout += meters;\n\n newWorkout.save(function (err, thor) {\n if (err) {\n return console.log(err);\n }\n });\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of all known objects of the given type. | function getObjectsOfType(objType) {
var objArr = [];
for (var i = 0; i < objects.length; i++) {
if (objects[i] instanceof objType) {
objArr.push(objects[i]);
}
}
return objArr;
} | [
"_collectClasses() {\n const result = []\n let current = Object.getPrototypeOf(this)\n while (current.constructor.name !== 'Object') {\n result.push(current)\n current = Object.getPrototypeOf(current)\n }\n return result\n }",
"allObjects() {\n return fs.readdirSync(Files.gitletPath('objects')).map(Objects.read);\n }",
"getAll(typeDef) {\n return __awaiter(this, void 0, void 0, function* () {\n let inv = yield this.invoke();\n try {\n return inv.getAll(typeDef);\n }\n catch (e) {\n throw e;\n }\n finally {\n inv.close();\n }\n });\n }",
"function extract_all_objs ( mod ) {\n var out = [];\n function extract ( obj ) {\n if ( obj.canonical_name === undefined ) {\n throw 'No canonical name!';\n }\n out.push ( obj );\n if ( obj.objects !== undefined ) {\n obj.objects.forEach ( function ( child ) {\n extract ( child );\n } );\n }\n }\n mod.globals.each_text ( function ( key, glob ) {\n extract ( get_canonical_value ( glob ) );\n } );\n return out;\n }",
"findAllTI(type, instance) {\n\t\tlet query = { type, instance, group: 0 };\n\t\tlet index = bsearch.lt(this.records, query, compare);\n\t\tlet out = [];\n\t\tlet record;\n\t\twhile (\n\t\t\t(record = this.records[++index]) &&\n\t\t\trecord.type === type &&\n\t\t\trecord.instance === instance\n\t\t) {\n\t\t\tout.push(record);\n\t\t}\n\t\treturn out;\n\t}",
"_get_dependency_instances(type, instances) {\n return type.dependency.map(item => {\n return instances.get(item)\n })\n }",
"function searchProductsByType(type) {\n\n let productsByType = new Promise(function(resolve, reject) {\n let products = [];\n let possibleTypes = ['Book', 'Clothing', 'Electronics', 'Food'];\n let pattern = new RegExp(type, \"i\");\n let validType;\n\n possibleTypes.forEach(function(possibleType) {\n if(pattern.test(possibleType) === true) {\n validType = possibleType;\n }\n })\n\n if(validType === undefined) {\n reject(\"Invalid type: \" + type);\n }\n else {\n setTimeout(function() {\n catalog.forEach(function(item) {\n if((item.type).toLowerCase() == type.toLowerCase()) {\n products.push(item);\n }\n });\n\n resolve(products);\n }, 1000);\n \n }\n \n })\n\n return productsByType;\n }",
"function includableTypes() {\n if (!config.graphite || !config.graphite.events) return [];\n var c = config.graphite.events;\n\n return c.types || [];\n }",
"async function getObjectList(connection, owner, type, name, status, query) {\n // Get the list of object types\n query = sql.statement[query];\n const filtered_name = name.toString().toUpperCase().replace('*', '%').replace('_', '\\\\_');\n const filtered_type = type.toString().replace('*', '%');\n let filtered_status = status.toString().toUpperCase();\n if (filtered_status !== 'VALID' &&\n filtered_status !== 'INVALID') {\n filtered_status = '%';\n }\n query.params.owner.val = owner;\n query.params.object_type.val = filtered_type;\n query.params.object_name.val = filtered_name;\n query.params.status.val = filtered_status;\n\n const result = await dbService.query(connection, query.sql, query.params);\n return result;\n}",
"selectModelsByType(type) {\n return this.filterAllByProperty('type', type)\n }",
"getTypes(pokemon) {\n let types = [];\n for(let i = 0; i < pokemon.types.length; i++) {\n const type = pokemon.types[i].type.name;\n types.push(\n <span\n className={\"b-outline type type-\" + type}\n key={type}\n >\n {type}\n </span>\n );\n }\n return types;\n }",
"async index() {\n return Type.all();\n }",
"static getChecks(type) {\n return type._checks.slice();\n }",
"function customObjectIds(objType) {\n\tcustomObjectsExported[objType] = true;\n\tif (!currentExport.hasOwnProperty(\"customObjects\")) return [];\n\t\n\tfor (var obj of currentExport.customObjects) {\n\t\tif (obj.objectType == objType) {\n\t\t\treturn obj.objectIds;\n\t\t}\n\t}\n\treturn [];\n}",
"function getItemsOfType(items, type) {\n return _.where(items, { 'type': type });\n }",
"function getGazeObjects () {\n\n return gazeObjects;\n\n }",
"function discoverTypes () {\n // rdf:type properties of subjects, indexed by URI for the type.\n\n const types = {}\n\n // Get a list of statements that match: ? rdfs:type ?\n // From this we can get a list of subjects and types.\n\n const subjectList = kb.statementsMatching(\n undefined,\n UI.ns.rdf('type'),\n tableClass, // can be undefined OR\n sourceDocument\n ) // can be undefined\n\n // Subjects for later lookup. This is a mapping of type URIs to\n // lists of subjects (it is necessary to record the type of\n // a subject).\n\n const subjects = {}\n\n for (let i = 0; i < subjectList.length; ++i) {\n const type = subjectList[i].object\n\n if (type.termType !== 'NamedNode') {\n // @@ no bnodes?\n continue\n }\n\n const typeObj = getTypeForObject(types, type)\n\n if (!(type.uri in subjects)) {\n subjects[type.uri] = []\n }\n\n subjects[type.uri].push(subjectList[i].subject)\n typeObj.addUse()\n }\n\n return [subjects, types]\n }",
"function cast(type) {\n var members = [],\n count = app.state[type],\n constructor;\n\n for (var c = 0; c < count; c++) {\n constructor = type.caps().single();\n members.push(new app[constructor]({\n id: self.serial++,\n onDeath: self.remove\n }));\n }\n\n // add to the cast\n self.array = self.array.concat(members);\n\n // assign global name shortcuts\n app[type] = members;\n app[type].each = function(callback) {\n self.select(type, callback);\n };\n\n }",
"async function getType(url) {\n const response = await axios.get(url);\n const data = await response;\n const namesByTypeArr = [];\n for (let pokemon of data.data.pokemon) {\n namesByTypeArr.push(pokemon.pokemon.name);\n }\n buildNameList(namesByTypeArr);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribe to workspace commands | subscribeToCommands () {
for (const command of workspaceCommandNames) {
this.subscriptions.add(
atom.commands.add('atom-workspace', command, () => {
// this will not activate package fully because of command prop
this.activateFn(command)
})
)
}
} | [
"function registerCommands() {\r\n return [\r\n vscode_1.commands.registerCommand('rls.update', () => { var _a; return (_a = activeWorkspace.value) === null || _a === void 0 ? void 0 : _a.rustupUpdate(); }),\r\n vscode_1.commands.registerCommand('rls.restart', () => __awaiter(this, void 0, void 0, function* () { var _a; return (_a = activeWorkspace.value) === null || _a === void 0 ? void 0 : _a.restart(); })),\r\n vscode_1.commands.registerCommand('rls.run', (cmd) => { var _a; return (_a = activeWorkspace.value) === null || _a === void 0 ? void 0 : _a.runRlsCommand(cmd); }),\r\n vscode_1.commands.registerCommand('rls.start', () => { var _a; return (_a = activeWorkspace.value) === null || _a === void 0 ? void 0 : _a.start(); }),\r\n vscode_1.commands.registerCommand('rls.stop', () => { var _a; return (_a = activeWorkspace.value) === null || _a === void 0 ? void 0 : _a.stop(); }),\r\n ];\r\n}",
"acceptServerChanges() {\n this.props.updateCode(this.props.serverCode, this.props.projectName);\n this.props.startStreamingEditor();\n }",
"listenForCommands(messageTypes) {\n this.slackController.hears(\".*\", messageTypes, (bot, message) => {\n // For direct messages and mentions, no prefix needed\n let usingPrefix = !(message.type === 'direct_message' || message.type === 'direct_mention');\n\n let command = this.parseCommand(message.text, usingPrefix);\n if (command) {\n command.run(new Message(this, message), usingPrefix);\n }\n });\n }",
"_keyboardShortcuts() {\n browser.commands.onCommand.addListener((command) => {\n if (command === 'action-accept-new') {\n this.app.modules.calls.callAction('accept-new')\n } else if (command === 'action-decline-hangup') {\n this.app.modules.calls.callAction('decline-hangup')\n } else if (command === 'action-dnd') {\n // Only toggle when calling options are enabled and webrtc is enabled.\n if (!this.app.helpers.callingDisabled() && this.app.state.settings.webrtc.enabled) {\n this.app.setState({availability: {dnd: !this.app.state.availability.dnd}})\n }\n } else if (command === 'action-hold-active') {\n this.app.modules.calls.callAction('hold-active')\n }\n })\n }",
"_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n this.fs.copy(this.sourceRoot() + '/typings', context.name + '/typings');\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/installTypings.js', context.name + '/installTypings.js', context);\n\n this.extensionConfig.installDependencies = true;\n }",
"_writingCommandJs() {\n let context = this.extensionConfig;\n\n this.fs.copy(this.sourceRoot() + '/vscode', context.name + '/.vscode');\n this.fs.copy(this.sourceRoot() + '/test', context.name + '/test');\n\n this.fs.copy(this.sourceRoot() + '/vscodeignore', context.name + '/.vscodeignore');\n\n if (this.extensionConfig.gitInit) {\n this.fs.copy(this.sourceRoot() + '/gitignore', context.name + '/.gitignore');\n }\n\n this.fs.copyTpl(this.sourceRoot() + '/README.md', context.name + '/README.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/CHANGELOG.md', context.name + '/CHANGELOG.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/vsc-extension-quickstart.md', context.name + '/vsc-extension-quickstart.md', context);\n this.fs.copyTpl(this.sourceRoot() + '/jsconfig.json', context.name + '/jsconfig.json', context);\n\n this.fs.copyTpl(this.sourceRoot() + '/extension.js', context.name + '/extension.js', context);\n this.fs.copyTpl(this.sourceRoot() + '/package.json', context.name + '/package.json', context);\n this.fs.copyTpl(this.sourceRoot() + '/.eslintrc.json', context.name + '/.eslintrc.json', context);\n\n this.extensionConfig.installDependencies = true;\n }",
"registerToShell() {\n this.postMessageToShell(MessageType.registration, this.id);\n }",
"function watchFiles() {\n watch('source/*.*', build);\n}",
"function make_external_command({command_info,client_id,ws}) { \n\n //dynamically create the command class here \n class external_command extends base_command { \n\t\n\tconstructor(config) {\n \t super({id : command_info['id']})\n\t this.command_info = command_info //store the info within the command \n\t}\n\t\n\tstatic get_info() { \n\t return command_info \n\t}\n\t//loop read from the external receive channel and emit \n\tasync listen(receive) { \n\t this.log.i(\"Starting listen loop\")\n\t while (true) { \n\t\tlet msg = await receive.shift() //read from the receive channel \n\t\tswitch(msg['type']) { \n\t\t \n\t\tcase 'emit' : \n\t\t this.emit(msg['data'] )\n\t\t break\n\t\t \n\t\tcase 'feedback' : \n\t\t this.feedback(msg['data'] )\n\t\t break\n\t\t \n\t\t \n\t\tcase 'finish' : \n\t\t this.finish({payload : {result: msg['data']['result']},\n\t\t\t\t error : msg['data']['error']})\n\t\t break \n\n\t\tcase 'call_command' : \n\t\t this.log.i(\"Calling command\")\n\t\t this.launch_command(msg['data']) \n\t\t break \n\t\t \n\t\tdefault : \n\t\t this.log.i(\"Unrecognized msg type in listen loop:\")\n\t\t this.log.i(msg)\n\t\t break \n\t\t}\n\t }\n\t}\n\t\n\t// define the relay function \n\trelay(data) { \n\t //append id and instance id\n\t data.id = this.cmd_id.split(\".\").slice(1).join(\".\") //get rid of module name\n\t data.instance_id = this.instance_id \n\t ws.send(JSON.stringify(data)) // send it \n\t}\n\t\n\tasync run() { \n\t let id = this.command_info['id']\n\t \n\t this.log.i(\"Running external command: \" + id )\n\t \n\t //make a new channel \n\t let receive = new channel.channel()\n\t \n\t //update the global clients structure \n\t let instance_id = this.instance_id\n\t add_client_command_channel({client_id,receive,instance_id})\n\n\t \n\t //start the async input loop\n\t this.listen(receive)\n\t \n\t //notify external interface that the command has been loaded \n\t let args = this.args \n\t var call_info = {instance_id,args } \n\t //external interface does not know about the MODULE PREFIX added to ID \n\t call_info.id = id.split(\".\").slice(1).join(\".\") \n\t \n\t let type = 'init_command' \n\t this.relay({type, call_info}) \n\t this.log.i(\"Sent info to external client\")\n\t \n\t //loop read from input channel \n\t this.log.i(\"Starting input channel loop and relay\")\n\t var text \n\t while(true) { \n\t\tthis.log.i(\"(csi) Waiting for input:\")\n\t\t//text = await this.get_input()\n\t\ttext = await this.input.shift() //to relay ABORTS \n\t\tthis.log.i(\"(csi) Relaying received msg to external client: \" + text)\n\t\t//now we will forward the text to the external cmd \n\t\tthis.relay({type: 'text' , data: text})\n\t }\n\t}\n }\n //finish class definition ------------------------------ \n return external_command\n}",
"async FillRegisteredCommands () {\n this.REGISTERED_COMMANDS.GLOBAL = await this.GetAll({ local: false })\n this.REGISTERED_COMMANDS.LOCAL = await this.GetAll({ local: true })\n\n if (!this.config.UNIT_TESTS) { this.Purge() }\n }",
"started() {\n this.ready = true;\n console.log(\"SlackBot is ready.\");\n }",
"function addCommands(app, services) {\n let { commands } = app;\n const namespace = 'terminal';\n const tracker = new apputils_2.InstanceTracker({ namespace });\n let gitApi = new git_1.Git();\n /**\n * Get the current path of the working directory.\n */\n function findCurrentFileBrowserPath() {\n try {\n let leftSidebarItems = app.shell.widgets('left');\n let fileBrowser = leftSidebarItems.next();\n while (fileBrowser.id !== 'filebrowser') {\n fileBrowser = leftSidebarItems.next();\n }\n return fileBrowser.model.path;\n }\n catch (err) { }\n }\n /** Add open terminal command */\n commands.addCommand(CommandIDs.gitTerminal, {\n label: 'Open Terminal',\n caption: 'Start a new terminal session to directly use git command',\n execute: args => {\n let currentFileBrowserPath = findCurrentFileBrowserPath();\n let name = args ? args['name'] : '';\n let terminal = new terminal_1.Terminal();\n terminal.title.closable = true;\n terminal.title.label = '...';\n app.shell.addToMainArea(terminal);\n let promise = name\n ? services.terminals.connectTo(name)\n : services.terminals.startNew();\n return promise\n .then(session => {\n terminal.session = session;\n tracker.add(terminal);\n app.shell.activateById(terminal.id);\n terminal.session.send({\n type: 'stdin',\n content: [\n 'cd \"' + currentFileBrowserPath.split('\"').join('\\\\\"') + '\"\\n'\n ]\n });\n return terminal;\n })\n .catch(() => {\n terminal.dispose();\n });\n }\n });\n /** Add open terminal and run command */\n commands.addCommand(CommandIDs.gitTerminalCommand, {\n label: 'Terminal Command',\n caption: 'Open a new terminal session and perform git command',\n execute: args => {\n let currentFileBrowserPath = findCurrentFileBrowserPath();\n let changeDirectoryCommand = currentFileBrowserPath === ' '\n ? ''\n : 'cd \"' + currentFileBrowserPath.split('\"').join('\\\\\"') + '\"';\n let gitCommand = args ? args['cmd'] : '';\n let linkCommand = changeDirectoryCommand !== '' && gitCommand !== '' ? '&&' : '';\n let terminal = new terminal_1.Terminal();\n terminal.title.closable = true;\n terminal.title.label = '...';\n app.shell.addToMainArea(terminal);\n let promise = services.terminals.startNew();\n return promise\n .then(session => {\n terminal.session = session;\n tracker.add(terminal);\n app.shell.activateById(terminal.id);\n terminal.session.send({\n type: 'stdin',\n content: [changeDirectoryCommand + linkCommand + gitCommand + '\\n']\n });\n return terminal;\n })\n .catch(() => {\n terminal.dispose();\n });\n }\n });\n /** Add open/go to git interface command */\n commands.addCommand(CommandIDs.gitUI, {\n label: 'Git Interface',\n caption: 'Go to Git user interface',\n execute: () => {\n try {\n app.shell.activateById('jp-git-sessions');\n }\n catch (err) { }\n }\n });\n /** Add git init command */\n commands.addCommand(CommandIDs.gitInit, {\n label: 'Init',\n caption: ' Create an empty Git repository or reinitialize an existing one',\n execute: () => {\n let currentFileBrowserPath = findCurrentFileBrowserPath();\n apputils_1.showDialog({\n title: 'Initialize a Repository',\n body: 'Do you really want to make this directory a Git Repo?',\n buttons: [apputils_1.Dialog.cancelButton(), apputils_1.Dialog.warnButton({ label: 'Yes' })]\n }).then(result => {\n if (result.button.accept) {\n gitApi.init(currentFileBrowserPath);\n }\n });\n }\n });\n /** Add remote tutorial command */\n commands.addCommand(CommandIDs.setupRemotes, {\n label: 'Set Up Remotes',\n caption: 'Learn about Remotes',\n execute: () => {\n window.open('https://www.atlassian.com/git/tutorials/setting-up-a-repository');\n }\n });\n /** Add remote tutorial command */\n commands.addCommand(CommandIDs.googleLink, {\n label: 'Something Else',\n caption: 'Dummy Link ',\n execute: () => {\n window.open('https://www.google.com');\n }\n });\n}",
"initializeCommands() {\n for (const filename of glob(kCommandDirectory, '.*fights[\\\\\\\\/][^\\\\\\\\/]*\\.json$')) {\n const configuration = JSON.parse(readFile(kCommandDirectory + filename));\n const settings = new Map();\n\n for (const [ identifier, value ] of Object.entries(configuration.settings))\n settings.set(identifier, value);\n\n settings.set('internal/goal', configuration.goal);\n settings.set('internal/name', configuration.name);\n\n this.registerCommand(configuration, settings);\n }\n }",
"function loadExportPlaylist(){\r\n commands.set('regularCommands',\"exportPlaylist\",exportPlaylist);\r\n}",
"onMessage (message) {\n if (message.command && message.options) {\n this.executeCommand(message.command, message.options);\n }\n }",
"function setup()\n{\n commandQueue = [];\n commandQueue.push({c : createDefaultFolders , msg : \"Folders -> OK\"});\n commandQueue.push({c : writeIndexBoilerplate , msg : \"Index Boilerplate -> OK\"});\n commandQueue.push({c : writePluginsJS , msg : \"Default Plugins -> OK\"});\n commandQueue.push({c : writeDefaultIcon , msg : \"Default Icon -> OK\"});\n commandQueue.push({c : writeGitIgnore , msg : \"git ignore -> OK\"});\n \n processQueue();\n}",
"function notifyLiveServer(changedFile) {\n for (const cli of httpWatches) {\n if (cli === undefined) continue;\n cli.write(\n 'data: ' + path.relative(cfg.outDistRootDir, changedFile) + '\\n\\n');\n }\n}",
"registerCommand() {\n this._commander\n .command(this.command)\n .description(this.description)\n .action((args, options) => this.action(args, options));\n }",
"function getChangesForWorkspace(workspaceName) {\n return new Promise(function (resolve, reject) {\n if (App.TEST_MODE) {\n setTimeout(function () {\n var sampleOutput = fs.readFileSync('test/tf-changes.txt').toString();\n resolve(parseChanges(sampleOutput));\n }, 500);\n } else {\n child_process.execFile(tfPath, ['status', `/workspace:${workspaceName}`],\n { maxBuffer: 20*1024*1024 },\n function (err, stdout, stderr) {\n if (err || stderr) {\n reject(err || stderr);\n } else {\n resolve(parseChanges(stdout));\n }\n });\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves localespecific rules used to determine which day period to use when more than one period is defined for a locale. There is a rule for each defined day period. The first rule is applied to the first day period and so on. Fall back to AM/PM when no rules are available. A rule can specify a period as time range, or as a single time value. This functionality is only available when you have loaded the full locale data. See the ["I18n guide"](guide/i18ni18npipes). | function getLocaleExtraDayPeriodRules(locale) {
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
checkFullData(data);
const rules = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][2 /* ExtraDayPeriodsRules */] || [];
return rules.map((rule) => {
if (typeof rule === 'string') {
return extractTime(rule);
}
return [extractTime(rule[0]), extractTime(rule[1])];
});
} | [
"calculatePeriods() {\n\n // go through all jobs and generate compound child elements\n let chart = get(this, 'chart'),\n childs = get(this, 'childLines'),\n start = get(this, 'parentLine._start'),\n end = get(this, 'parentLine._end')\n\n // generate period segments\n let periods = dateUtil.mergeTimePeriods(childs, start, end);\n\n // calculate width of segments\n if (periods && periods.length > 0) {\n periods.forEach(period => {\n period.width = chart.dateToOffset(period.dateEnd, period.dateStart, true);\n period.background = this.getBackgroundStyle(period.childs);\n period.style = htmlSafe(`width:${period.width}px;background:${period.background};`);\n });\n }\n\n set(this, 'periods', periods);\n }",
"visitPeriod_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function updateByDayRRule(rrule, removeDate, addDate) {\n var frequency = rrule && rrule.freq;\n\n if (frequency != 'WEEKLY' && frequency != 'MONTHLY') {\n return;\n }\n\n var oldDate = new Date(removeDate),\n newDate = new Date(addDate);\n\n //Need to know if we have BYDAY rule or a BYMONTHDAY rule, and if so, which one is it?\n var byDayRuleIndex = -1;\n var byMonthDayRuleIndex = -1;\n var rulesLength = rrule.rules.length;\n for (var i = 0; i < rulesLength; i++) {\n var rule = rrule.rules[i];\n if (rule.ruleType == \"BYMONTHDAY\") {\n byMonthDayRuleIndex = i;\n break;\n }\n else if (rule.ruleType == \"BYDAY\") {\n byDayRuleIndex = i;\n break;\n }\n }\n\n var dayArray;\n var monthDayArray;\n switch (frequency) {\n\n case 'WEEKLY': // Do NOT Localize\n //if we're weekly and don't have a BYDAY rule, bad things would happen.\n if (byDayRuleIndex == -1) {\n break;\n }\n\n dayArray = rrule.rules[byDayRuleIndex].ruleValue;\n if (!dayArray) {\n break;\n }\n\n //Weekly: weekdays\n if (Utilities.isWeekdaysRule(dayArray) && (rrule.interval == 1 || !rrule.interval)) {\n //Weekdays -> do nothing.\n break;\n }\n\n //Weekly: single day\n else if (dayArray.length === 1) {\n rrule.rules[byDayRuleIndex].ruleValue = [\n {\"day\": newDate.getDay()}\n ];\n }\n\n //Weekly: custom.\n //Remove old date's weekday, add new date's weekday, leaving previous values intact\n else {\n //find the index of the old date's weekday in the byday array\n var oldDayIndex = Utilities.findDayInByDayArray(dayArray, oldDate.getDay());\n var newDay = newDate.getDay();\n //remove the old day from the byday array\n if (oldDayIndex > -1) {\n dayArray.splice(oldDayIndex, 1);\n }\n\n //Make sure the new day we're adding isn't already in the array\n if (Utilities.findDayInByDayArray(dayArray, newDay) == -1) {\n //find the right spot to add the new day\n var j = 0;\n var daysLength = dayArray.length;\n while (j < daysLength && newDay > dayArray[j].day) {\n j++;\n }\n //insert the new day\n dayArray.splice(j, 0, {\"day\": newDay});\n }\n }\n break;\n\n case 'MONTHLY': // Do NOT Localize\n //Monthly by date\n\n if (byMonthDayRuleIndex != -1) {\n rrule.rules[byMonthDayRuleIndex].ruleValue = [\n {\"ord\": newDate.getDate()}\n ];\n }\n else {\n var nth = Utilities.getDOWCount(newDate);\n rrule.rules[byDayRuleIndex].ruleValue = [\n {\"ord\": nth, \"day\": newDate.getDay()}\n ];\n }\n break;\n\n default:\n break;\n }\n }",
"async buildLikelyLocaleTable() {\n let localeList = [];\n\n if (process.platform === 'linux') {\n let locales = await spawn('locale', ['-a'])\n .reduce((acc,x) => { acc.push(...x.split('\\n')); return acc; }, [])\n .toPromise()\n .catch(() => []);\n\n d(`Raw Locale list: ${JSON.stringify(locales)}`);\n\n localeList = locales.reduce((acc, x) => {\n let m = x.match(validLangCodeWindowsLinux);\n if (!m) return acc;\n\n acc.push(m[0]);\n return acc;\n }, []);\n }\n\n if (process.platform === 'win32') {\n localeList = require('keyboard-layout').getInstalledKeyboardLanguages();\n }\n\n if (isMac) {\n fallbackLocaleTable = fallbackLocaleTable || require('./fallback-locales');\n\n // NB: OS X will return lists that are half just a language, half\n // language + locale, like ['en', 'pt_BR', 'ko']\n localeList = this.currentSpellchecker.getAvailableDictionaries()\n .map((x => {\n if (x.length === 2) return fallbackLocaleTable[x];\n return normalizeLanguageCode(x);\n }));\n }\n\n d(`Filtered Locale list: ${JSON.stringify(localeList)}`);\n\n // Some distros like Ubuntu make locale -a useless by dumping\n // every possible locale for the language into the list :-/\n let counts = localeList.reduce((acc,x) => {\n let k = x.split(/[-_\\.]/)[0];\n acc[k] = acc[k] || [];\n acc[k].push(x);\n\n return acc;\n }, {});\n\n d(`Counts: ${JSON.stringify(counts)}`);\n\n let ret = Object.keys(counts).reduce((acc, x) => {\n if (counts[x].length > 1) return acc;\n\n d(`Setting ${x}`);\n acc[x] = normalizeLanguageCode(counts[x][0]);\n\n return acc;\n }, {});\n\n // NB: LANG has a Special Place In Our Hearts\n if (process.platform === 'linux' && process.env.LANG) {\n let m = process.env.LANG.match(validLangCodeWindowsLinux);\n if (!m) return ret;\n\n ret[m[0].split(/[-_\\.]/)[0]] = normalizeLanguageCode(m[0]);\n }\n\n d(`Result: ${JSON.stringify(ret)}`);\n return ret;\n }",
"function _getSegments() {\n switch ($scope.options.timeScope) {\n case 'day':\n return _getHours();\n case 'range':\n return _getDaysForRange();\n case 'month':\n return _getDaysForMonth();\n case 'week':\n default:\n return _getWeekDays();\n }\n }",
"function calculateRecurDates(rule, from /* utc millis */, to /* utc millis */) {\n var dates = []; /* array of utc millis (number) */\n var runDate = new Date(from);\n var i;\n\n var candidate = null;\n var counter = 0;\n // (open) loop to collect recurrences\n while (counter < 100) {\n counter++;\n // stop collecting when we reach the end of the period specified\n if (candidate && candidate.getTime() > to) {\n break;\n }\n\n var candidates = calculateCandidates(rule, runDate.clone());\n for (i=0; i < candidates.length; i++) {\n candidate = candidates[i];\n // only use candidates that lie in the given period\n if (candidate.getTime() >= from && candidate.getTime() <= to) {\n dates.push(candidate.getTime());\n }\n }\n\n runDate = increment(rule, runDate);\n }\n return dates;\n }",
"function updatePeriods(){\n var periods;\n\n /* 726: Set the period to hourly for ww3 dataset and hide the monthly option as it is not available for surface map. */\n if (ocean.datasetid == 'ww3'){\n if (ocean.plottype == 'histogram'){\n periods = {\"monthly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['monthly']};\n }else if (ocean.plottype == 'map'){\n periods = {\"hourly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['hourly']};\n } else if (ocean.plottype == 'waverose'){\n periods = {\"monthly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['monthly']};\n }\n } else {\n periods = ocean.variables[ocean.variable].plots[ocean.plottype];\n }\n\n filterOpts('period', periods);\n selectFirstIfRequired('period');\n showControls('period');\n}",
"function getMealPeriod() {\n var currentHour = new Date().getHours();\n \n // Get the current meal period\n var currentMealPeriod;\n // Breakfast 6am - 10am\n if ([6, 7, 8, 9, 10].includes(currentHour))\n currentMealPeriod = \"breakfast\";\n // Lunch 11am - 2pm\n else if ([11, 12, 13, 14].includes(currentHour))\n currentMealPeriod = \"lunch\";\n // Dinner 4pm - 8pm\n else if ([16, 17, 18, 19, 20].includes(currentHour))\n currentMealPeriod = \"dinner\";\n // Late Night 9pm - 2am\n else if ([21, 22, 23, 24, 1, 2].includes(currentHour))\n currentMealPeriod = \"latenight\";\n else\n currentMealPeriod = \"N/A\";\n\n return currentMealPeriod;\n }",
"getTimesBetween(start, end, day) {\n var times = [];\n // First check if the time is a period\n if (this.data.periods[day].indexOf(start) >= 0) {\n // Check the day given and return the times between those two\n // periods on that given day.\n var periods = Data.gunnSchedule[day];\n for (\n var i = periods.indexOf(start); i <= periods.indexOf(end); i++\n ) {\n times.push(periods[i]);\n }\n } else {\n var timeStrings = this.data.timeStrings;\n // Otherwise, grab every 30 min interval from the start and the end\n // time.\n for (\n var i = timeStrings.indexOf(start); i <= timeStrings.indexOf(end); i += 30\n ) {\n times.push(timeStrings[i]);\n }\n }\n return times;\n }",
"function parseWeekday() {\n if (!ctrl.rrule.byweekday) return\n var prefix = _.find(Object.keys(weekdayPrefixes), function(prefix) {\n return weekdayPrefixes[prefix] === ctrl.rrule.byweekday.n\n })\n ctrl.weekdayPrefix = prefix\n var suffix = ctrl.options.days[ctrl.rrule.byweekday.weekday]\n ctrl.weekdaySuffix = suffix\n setWeekday()\n }",
"getTranslatedEnums() {\n if (this.translatedEnumCache) {\n return this.translatedEnumCache;\n }\n\n let result = map(this.rule.in || [], (value) => {\n let translated;\n if (\n this.rule.fieldName === this.FIELD_NAME_LIST.area &&\n this.newAccountForm.model.country\n ) {\n translated = this.$translate.instant(\n `signup_enum_${this.newAccountForm.model.country}_${this.rule.fieldName}_${value}`,\n );\n } else if (this.rule.fieldName === this.FIELD_NAME_LIST.timezone) {\n translated = value;\n } else if (this.rule.fieldName === this.FIELD_NAME_LIST.managerLanguage) {\n translated = get(find(LANGUAGES.available, { key: value }), 'name');\n } else {\n translated = this.$translate.instant(\n `signup_enum_${this.rule.fieldName}_${value}`,\n );\n }\n return {\n key: value,\n translated,\n };\n });\n\n result = this.$filter('orderBy')(\n result,\n 'translated',\n this.rule.fieldName === this.FIELD_NAME_LIST.phoneType,\n (a, b) => String(a.value).localeCompare(String(b.value)),\n );\n\n // if there is only a single value, auto select it\n if (\n result.length === 1 &&\n this.value !== head(result).key &&\n !this.autoSelectPending\n ) {\n this.autoSelectPending = true;\n this.value = head(result);\n this.$timeout(() => {\n this.onChange();\n this.autoSelectPending = false;\n });\n }\n\n this.translatedEnumCache = result;\n return result;\n }",
"function buildRecurrenceRule() {\n\tvar recurrenceRule = CalendarApp.newRecurrence();\n\tvar dates = getDates(2020);\n\tfor (var i = 0; i < dates.length; i++) {\n\t\trecurrenceRule.addDate(dates[i]); // for each date, add a new date to the recurrence rule\n\t}\n\treturn recurrenceRule;\n}",
"function getCourseEventDays(meetings) {\n let meet = meetings.split(' ')[0];\n let days = [];\n for (let i = 0; i < daysOfWeek.length; i++) {\n if (meet.includes(daysOfWeek[i])) {\n days.push(translateDaysForIcs[daysOfWeek[i]]);\n }\n }\n return days;\n }",
"function getDefaultHourSymbolFromLocale(locale) {\n var hourCycle = locale.hourCycle;\n if (hourCycle === undefined &&\n // @ts-ignore hourCycle(s) is not identified yet\n locale.hourCycles &&\n // @ts-ignore\n locale.hourCycles.length) {\n // @ts-ignore\n hourCycle = locale.hourCycles[0];\n }\n if (hourCycle) {\n switch (hourCycle) {\n case 'h24':\n return 'k';\n case 'h23':\n return 'H';\n case 'h12':\n return 'h';\n case 'h11':\n return 'K';\n default:\n throw new Error('Invalid hourCycle');\n }\n }\n // TODO: Once hourCycle is fully supported remove the following with data generation\n var languageTag = locale.language;\n var regionTag;\n if (languageTag !== 'root') {\n regionTag = locale.maximize().region;\n }\n var hourCycles = timeData[regionTag || ''] ||\n timeData[languageTag || ''] ||\n timeData[\"\".concat(languageTag, \"-001\")] ||\n timeData['001'];\n return hourCycles[0];\n }",
"function resolveRelativeTimeFormatInternals(lazyRelativeTimeFormatData) {\n assert(IsObject(lazyRelativeTimeFormatData), \"lazy data not an object?\");\n\n var internalProps = std_Object_create(null);\n\n var RelativeTimeFormat = relativeTimeFormatInternalProperties;\n\n // Step 10.\n const r = ResolveLocale(callFunction(RelativeTimeFormat.availableLocales, RelativeTimeFormat),\n lazyRelativeTimeFormatData.requestedLocales,\n lazyRelativeTimeFormatData.opt,\n RelativeTimeFormat.relevantExtensionKeys,\n RelativeTimeFormat.localeData);\n\n // Step 11.\n internalProps.locale = r.locale;\n\n // Step 14.\n internalProps.style = lazyRelativeTimeFormatData.style;\n\n // Step 16.\n internalProps.numeric = lazyRelativeTimeFormatData.numeric;\n\n return internalProps;\n}",
"function getConfig(data) {\n var\n i;\n\n data.each(function (_, e) {\n var\n text = $(e).text()\n .replace(/#.*?(\\n|$)/g, '$1') // remove all comments\n .replace(/\\s+/g, ' ') // compress whitespace\n .replace(/^\\s|\\s$/g, '') // trim\n .split(' '), // tokenize\n c;\n\n // process tokens, sanitizing them along the way\n if ((text.length === 3) || (text.length === 13)) {\n // basic zone definition\n clock.push({\n e: $(e),\n name: text[0] // location description\n .replace(/_/g, ' '), // translate spaces\n utcoff: parseHM(text[1] // [+|-]hh:mm UTC offset\n .replace(/[^+\\-\\d:]/g, '')\n ),\n zone: text[2] // zone designator\n .replace(/_/g, ' '), // translate spaces\n });\n c = clock[clock.length - 1];\n if (text.length === 13) {\n // daylight time rules\n c.year = 1; // truthy, but purposefully wrong\n c.rule1 = [\n text[3] // in month (Jan - Dec)\n .replace(/[^a-zA-Z]/g, ''),\n text[4] // on day (number, last, >=)\n .replace(/[^a-zA-Z>=\\d]/g, ''),\n parseHM(text[5] // at time hh:mm\n .replace(/[^\\d:]/g, '')\n )\n ];\n c.rule2 = [\n text[8] // in month (Jan - Dec)\n .replace(/[^a-zA-Z]/g, ''),\n text[9] // on day (number, last, >=)\n .replace(/[^a-zA-Z>=\\d]/g, ''),\n parseHM(text[10] // at time hh:mm\n .replace(/[^\\d:]/g, '')\n )\n ];\n c.save1 = parseHM(text[6] // daylight adjust hh:mm\n .replace(/[^\\d:]/g, '')\n );\n c.save2 = parseHM(text[11] // daylight adjust hh:mm\n .replace(/[^\\d:]/g, '')\n );\n c.letters1 = text[7] // zone designator\n .replace(/_/g, ' '); // translate spaces\n c.letters2 = text[12] // zone designator\n .replace(/_/g, ' '); // translate spaces\n }\n } else {\n // error\n $(e).empty().text('Incorrect number of data for clock');\n }\n });\n }",
"async function polyfill(locale = '') {\n const dataPolyfills = [];\n // Polyfill Intl.getCanonicalLocales if necessary\n if (shouldPolyfillGetCanonicalLocales()) {\n await import(\n /* webpackChunkName: \"intl-getcanonicallocales\" */ '@formatjs/intl-getcanonicallocales/polyfill'\n );\n }\n\n // Polyfill Intl.PluralRules if necessary\n if (shouldPolyfillPluralRules()) {\n await import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/polyfill'\n );\n }\n\n if ((Intl.PluralRules).polyfilled) {\n const lang = locale.split('-')[0];\n switch (lang) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-pluralrules\" */ '@formatjs/intl-pluralrules/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.NumberFormat if necessary\n if (shouldPolyfillNumberFormat()) {\n await import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/polyfill'\n );\n }\n\n if ((Intl.NumberFormat).polyfilled) {\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-numberformat\" */ '@formatjs/intl-numberformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.DateTimeFormat if necessary\n if (shouldPolyfillDateTimeFormat()) {\n await import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/polyfill'\n );\n }\n\n if ((Intl.DateTimeFormat).polyfilled) {\n dataPolyfills.push(import('@formatjs/intl-datetimeformat/add-all-tz'));\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-datetimeformat\" */ '@formatjs/intl-datetimeformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n // Polyfill Intl.RelativeTimeFormat if necessary\n if (shouldPolyfillRelativeTimeFormat()) {\n await import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/polyfill'\n );\n }\n\n if ((Intl).RelativeTimeFormat.polyfilled) {\n switch (locale) {\n default:\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/locale-data/en'\n )\n );\n break;\n case 'fr':\n dataPolyfills.push(\n import(\n /* webpackChunkName: \"intl-relativetimeformat\" */ '@formatjs/intl-relativetimeformat/locale-data/fr'\n )\n );\n break;\n }\n }\n\n await Promise.all(dataPolyfills);\n}",
"actualWeekdays(start, end) {\n return this.weekdaysBetween(start, end) - (\n this.holidays().length + this.leaves().length)\n }",
"getDayRanges() {\n let params = '?part=day-ranges&time_zone='\n + Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n return fetch(`${config.API_ENDPOINT}/projects${params}`, {\n headers: {\n 'authorization': `bearer ${TokenService.getAuthToken()}`,\n }\n })\n .then(res =>\n (!res.ok)\n ? res.json().then(e => Promise.reject(e))\n : res.json()\n )\n }",
"function dateTimeRules(e, target) {\n var event = window.event || e,\n input = target,\n delims,\n validationSegment,\n inputvalidationSegment,\n newSel,\n thisChar,\n explode,\n char,\n sel,\n val;\n if (event.charCode >= 48 && event.charCode <= 57) { //user enters a number\n delims = looseconfig.delims;\n sel = input.selectionStart;\n val = input.value;\n explode = val.split(\"\");\n char = event.charCode - 48;\n if (sel <= input.maxLength + 1) {\n thisChar = input.getAttribute('data-loosetime').charAt(sel);\n if (!Number(thisChar)) { //if we hit a delimeter check the validation char after it\n thisChar = input.getAttribute('data-loosetime').charAt(sel + 1);\n }\n if (delims.indexOf(explode[sel]) !== -1) {\n validationSegment = input.getAttribute('data-loosetime').substring(sel + 1, sel + 3);\n if (char <= thisChar && !thisChar.isNaN) {\n //need to evaluate the number validationSegment in the delimeter\n explode = val.split(\"\");\n explode[sel + 1] = event.charCode - 48;\n val = explode.join(\"\");\n newSel = sel + 2;\n } else {\n newSel = sel;\n }\n } else {\n validationSegment = input.getAttribute('data-loosetime').substring(sel === 0 ? 0 : sel - 1, sel === 0 ? sel + 2 : sel + 1);\n inputvalidationSegment = input.value.charAt(sel === 0 ? 0 : sel - 1);\n if (sel > 0) {\n inputvalidationSegment = inputvalidationSegment.concat(char);\n if (inputvalidationSegment <= validationSegment && !thisChar.isNaN) {\n explode = val.split(\"\");\n explode[sel] = event.charCode - 48;\n val = explode.join(\"\");\n newSel = sel + 1;\n } else {\n newSel = sel;\n }\n }\n else {\n if (char <= input.getAttribute('data-loosetime').charAt(sel)) {\n explode = val.split(\"\");\n explode[sel] = event.charCode - 48;\n val = explode.join(\"\");\n newSel = sel + 1;\n }\n else {\n newSel = sel;\n }\n }\n }\n input.value = val;\n input.selectionStart = newSel;\n input.selectionEnd = newSel;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the bound bank card Exchange | function DeleteBank(token, account_id, suc_func, error_func) {
let api_url = 'del_us_bank_card.php',
post_data = {
'token': token,
'account_id': account_id
};
CallApi(api_url, post_data, suc_func, error_func);
} | [
"async deleteSmartACKMailbox(){\n\t\tconst data = Buffer.from([0x0a, 0x05, 0x83, 0x4b, 0x83, 0x01, 0x9d, 0x45, 0x44]);\n\t\tawait this.sendData(this, data, null, 6);\n\t\tconst response = await this.waitForResponse();\n\t\tconst telegram = new HandleType2(this, response);\n\t\tconsole.log(`Delet Smart ACK mailbox: ${JSON.stringify(telegram.main)}`);\n\t}",
"function deleteRegimen(req, res, next) {\r\n var card = req.body.regimen;\r\n var card_id = req.body.test3;\r\n\r\n req.app.get('db').regimens.destroy({id: card_id}, function(err, result){\r\n //Array containing the destroyed record is returned\r\n if (err) {\r\n console.log(\"Could not delete card\");\r\n } else{\r\n console.log(\"Card successfully deleted\");\r\n res.json(result);\r\n }\r\n });\r\n\r\n}",
"async function reclaimExchangeTx(contract, targetAddress, amount) {\n return await contract.functions\n .reclaim(wallet.bob.publicKey, new SignatureTemplate(wallet.bob.privateKey))\n .to(targetAddress, amount)\n .withFeePerByte(1)\n .send()\n}",
"deleteBoard({ dispatch, commit, state }, boardId) {\n api.delete('/api/boards/' + boardId)\n .then(res => {\n console.log(\"deleted\")\n dispatch('getBoards')\n // commit('setBoard', res.data)\n }).catch(err => console.log(err))\n }",
"function deleteCard(id) {\n if (id === editId) {\n closeEditor()\n }\n cards.get(id).removeEvents(id)\n cards.get(id).node.remove()\n cards.delete(id)\n markDirty()\n }",
"function callback_deleteDevice(errorCode) {\n console.log('callback_deleteDevice called');\n //Terminates connection with device\n ePosDev.disconnect();\n console.log('disconnect with invoice printer');\n}",
"deleteCardByUserIdWalletId(userId, walletId) {\n return http.delete(`/wallet/${userId}/${walletId}`);\n }",
"function rmEnquiry() {\n\t\t\tvm.enquiry.enquiries.pop();\n\t\t}",
"removeBalance(accountView) {\n // verify required parameter 'accountView' is not null or undefined\n if (accountView === null || accountView === undefined) {\n throw new Error('Required parameter accountView was null or undefined when calling removeBalance.');\n }\n let queryParameters = {};\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('POST', '/api/user/v1/account/remove-balance', queryParameters, headerParams, formParams, isFile, false, accountView);\n }",
"function deleteDebtByID(token, debtID) {\n try {\n var userData = validateToken(token);\n var userEmail = userData.email;\n var createQuery = 'DELETE FROM Debts WHERE email=? AND debtID=?;';\n var parameters = [userEmail, debtID];\n executeManipulationQuery(createQuery, parameters);\n return \"Success\";\n }\n catch (err) {\n throw new Error( \"Error deleting debt!\" );\n }\n}",
"function clickCardHandler(e) {\n if (isEqual(e.target, deleteSvg.current)) {\n return\n }\n\n setTimeout(() => {\n let addedCurrencies = [...appState.addedCurrencies]\n addedCurrencies.splice(props.id, 1)\n addedCurrencies.unshift(appState.addedCurrencies[props.id])\n\n appDispatch({ type: 'updateOrder', value: addedCurrencies })\n\n if (addedCurrencies.length === 0) {\n appDispatch({ type: 'clearLocalStorage' })\n }\n }, 200)\n }",
"function CtrlDelete() {\n //in case we are in state 1 . we simply delete all filled coupons.\n if(typeof UICtrl.getExpandedCoupon() === \"undefined\") { //if there is no expanded coupon then we are in state 1.\n jackpotCtrl.deleteAllCoupons();\n UICtrl.makeAllFilledCouponsClickable(jackpotCtrl.getAllCoupons());\n UICtrl.deactivateDoneFillingBtn()\n UICtrl.setInitialUI(); \n updateTotal(); \n }\n\n // in case we are in state 2 . we delete all fields.\n else { \n CtrlDeleteAllFieldsInOneCoupon();\n if(decrementTotalFlag) { updateTotal(-1); decrementTotalFlag = 0; } //we can update the total , only if the flag is released.\n } \n\n UICtrl.hideDeleteAllButton();\n }",
"function deleteIDCard(req, res, next) {\n if (!req.decoded) {\n return next(new errs.ForbiddenError('Current user does not have access to the requested resource.'));\n }\n\n if (req.decoded.userId !== req.params.userId) {\n return next(new errs.ForbiddenError('Current user does not have access to the requested resource.'));\n }\n\n return IDCard.deleteOne({ userId: req.params.userId, _id: req.params.idCardId })\n .then((response) => {\n if (response && response.n && response.n === 1) {\n res.send(204);\n return next();\n }\n return next(new errs.NotFoundError('IDCard not found.'));\n });\n}",
"function deletePaymentGroup() {\n Merchant.delete('payment_group', vm.delete_payment_group.id).then(function(response){\n vm.payment_groups.splice(delete_payment_group_index, 1);\n $(\"#delete-payment_group-modal\").modal('toggle');\n });\n }",
"function handle_bp_remove_biller_corp_account(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"function removeFromDeck() {\n\tvar name = \"count_\" + deckCounter;\n\tshowImage('deckImage', name, 'deckHolder');\n}",
"deleteRecord() {}",
"removeValidationRequest(address){\r\n //removes item in index reference array and mempool array\r\n let indexToFind = this.walletList[address];\r\n delete this.walletList[address];\r\n delete this.mempool[indexToFind];\r\n\r\n //clear timeouts\r\n clearTimeout(this.timeoutRequests[address]);\r\n delete this.timeoutRequests[address]\r\n }",
"delete (req, res) {\n const id = req.params.slotId;\n console.log('id from controller', id)\n Slot2.findByIdAndRemove(id, (err) => {\n if (err) return res.status(500).send(err);\n getAll(res);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TEMPORARY FORM FIELD STORAGE FOR COMPARISON | function storeFormValsTemporarily()
{
var myForm = arguments[0];
var formElementValues = convertFormElements(myForm);
pageControl.setConvertedFormElements(formElementValues);
} | [
"function fillSavedInputs() {\n const getFieldByName = name => $(`#id_${name}`);\n\n for (const fieldName in DOM.orderFieldData) { // Ignore ESLintBear (no-restricted-syntax)\n if ({}.hasOwnProperty.call(DOM.orderFieldData, fieldName)) {\n const $field = getFieldByName(fieldName);\n const savedValue = localStorage.getItem(fieldName);\n\n if ($field && savedValue) {\n $field.val(savedValue);\n }\n }\n }\n }",
"loadFieldInfo(){\n let fieldInfo = [];\n this.props.orderStore.currentOrder.templateFields.fieldlist.field.forEach(field =>\n this.props.orderStore.fieldInfo.push([field, '']));\n this.props.orderStore.fieldInfo.forEach(field =>\n {\n if(field[0].type == \"SEPARATOR\"){\n field[1] = \"**********\";\n }\n });\n }",
"function formField(type, key, val, units) \n{\n if(type == 'chooseOne') return chooseOneField(key, val);\n else return inputField(key, val, units);\n}",
"saveFormData() {\n let formData = { ['form-data']: {} };\n for (let item of this.view.form) {\n if (item.name.length > 0) formData['form-data'][item.name] = item.value;\n }\n localStorage.setItem('form-data', JSON.stringify(formData));\n }",
"function parseDataModelFromForm(form) {\n var data = {};\n\n // Add item id in the data to pass to save method\n data[config.fieldId] = $(form).find(\"#\" + createIdName(config.fieldId)).val();\n\n $.each(config.fields, function (index, field) {\n if (field.type != FieldType.IMAGE) {\n\t data[field.name] = $(form).find(\"#\" + createIdName(field.name)).val();\n }\n });\n\n return data;\n }",
"get fieldValue(){}",
"function formDataToDocument(formData) {\n\n if (formData.year && !isNaN(formData.year)) {\n formData.year = parseInt(formData.year, 10);\n }\n if (formData.authors) {\n formData.authors = personsStringToArray(formData.authors);\n }\n if (formData.editors) {\n formData.editors = personsStringToArray(formData.editors);\n }\n if (formData.websites) {\n formData.websites = formData.websites.filter(function (val) {\n return val !== '';\n });\n }\n\n formData.hidden = formData.hidden === 'true';\n\n return formData;\n}",
"function createFieldToken(field){\n \n createFieldToken(field, '', '');\n \n}",
"function formToObject(form, tripId) {\n let formData = {};\n let rawForm;\n if (tripId) {\n rawForm = $(`${form}[data=${tripId}]`).serializeArray();\n }\n else {\n rawForm = $(`${form}`).serializeArray();\n }\n rawForm.forEach(input => { \n if (input.value != '') {\n formData[input.name] = input.value; \n }\n });\n return formData;\n}",
"createFields(fieldList) {\n const formFields = fieldList.reduce((fields, field) => ({\n ...fields,\n [field]: createField(field, this.onFieldChange)\n }), {});\n this.fields = { ...formFields };\n }",
"function make_formData(form_id, fields) {\n let formData = new FormData();\n $.each(fields, function(name, value) {\n formData.append(name, get_node_info_field(form_id, value));\n });\n return formData;\n}",
"fillsuppliersFields() {\n // fill the fields\n this.$suppliersName.value = this.state.suppliers.name;\n this.$suppliersPhone.value = this.state.suppliers.phone;\n this.$suppliersEmail.value = this.state.suppliers.email;\n this.$suppliersWebsite.value = this.state.suppliers.website;\n this.$suppliersContactFirstName.value = this.state.suppliers.contactFirstName;\n this.$suppliersContactLastName.value = this.state.suppliers.contactLastName;\n this.$suppliersContactPhone.value = this.state.suppliers.contactPhone;\n this.$suppliersContactEmail.value = this.state.suppliers.contactEmail;\n this.$suppliersNote.value = this.state.suppliers.note;\n this.makeFieldsReadOnly();\n }",
"function formFieldPopulation(){\n\t\tvar detailsObject = JSON.parse(localStorage.getItem('details'));\n\t\tif(detailsObject != null){\n\t\t\tconsole.log(detailsObject.firstname);\n\t\t\t$('#firstname').val(detailsObject.firstname);\n\t\t\t$('#lastname').val(detailsObject.lastname);\n\t\t\t$('#email').val(detailsObject.email);\n\t\t\t$('#phone').val(detailsObject.phone);\n\t\t\tconsole.log(detailsObject);\n\t\t}\n\t}",
"function fieldClone(field)\n{\n // first, just get a copy of the object itself\n\n var clone = Object.assign({},field); // clone ALL object fields\n\n var listFields = [\"perspective\",\"target\",\"start\",\"end\",\"targetVal\",\n\t\t \"multiplier\",\"low\",\"high\",\n\t\t \"shape\",\"x\",\"y\",\"width\",\"height\", // fields added for geoSubset\n\t\t ]; // then replace arrays with clones\n\n listFields.forEach((listField) => {\n\tif(clone.hasOwnProperty(listField)) {\n\t clone[listField] = field[listField].slice(0);\n\t}\n });\n\n return(clone);\n}",
"function getFormElement(frm,fldname, fieldType)\n{\n var returnMe = null;\n if ( frm != null )\n {\n if ( fldname == 'language' || (!isBackend && (fldname == 'item' || fldname == 'cash')) )\n {\n for ( var i = 0; i < frm.elements.length; i++ )\n if ( frm.elements[i].name == fldname )\n {\n returnMe = frm.elements[i];\n break;\n }\n }\n else if (fieldType && fieldType == 'inlinehtml')\n {\n returnMe = document.getElementById(fldname + \"_val\");\n }\n else if (frm.elements != null)\n returnMe = frm.elements[fldname];\n }\n return returnMe;\n}",
"get fieldValuesForEdit() {\n return SPInstance(this, \"FieldValuesForEdit\");\n }",
"function getFormData(){\n\t\tvar distance = $('#distance_slider').slider('getValue');\n\t\tvar wage = $('#wage_slider').slider('getValue');\t\t\n\t\tvar formArray = $('#filter_form').serializeArray();\n\t\tvar form = {};\n\n $.each(formArray, function (i, input) {\n form[input.name] = input.value;\n });\n\t\t\n\t\tform['distance'] = distance;\n\t\t// console.log(distance);\n\t\tform['wage'] = wage;\n\n\t\treturn form;\n\t}",
"function getFormData() {\n return formRef.current;\n }",
"getPersonObject(form) {\n const person = {\n name: form.elements['name'].value,\n age: form.elements['age'].value,\n gender: form.elements['gender'].value,\n email: form.elements['email'].value\n }\n\n if (this.props.person != undefined) {\n person.id = this.props.person.id;\n }\n\n return person;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Profile Created Validation For Popup | function profilecreatedforvalidation(){
if($("#profilecreatedforpopup").val() == ""){
$("#notnullprofilecreated").show();
return false;
} else {
$("#notnullprofilecreated").hide();
return true;
}
} | [
"function onProceedButtonClicked () {\n let isValid = true;\n let isProfileUrl = true;\n $('#onboardingProfessionError').hide()\n $('#onboardingBioError').hide()\n $('#onboardingPageNameError').hide()\n $('#onboardingProfileImageError').hide()\n const profileUrl = $('#profileImageDataURl')[0].src;\n const profession = $('#onboardingProfession')[0].value;\n const bio = $('#onboardingBio')[0].value;\n const subDomain = $('#onboardingPageName')[0].value;\n if (profileUrl === 'data:image/jpeg;base64') {\n // $('#onboardingProfileImageError').text('Please select profile image');\n // $('#onboardingProfileImageError').show()\n isProfileUrl = false\n }\n if (!profession) {\n $('#onboardingProfessionError').text('Please provide profession name');\n $('#onboardingProfessionError').show()\n isValid = false;\n }\n if (!bio) {\n $('#onboardingBioError').text('Please provide bio');\n $('#onboardingBioError').show()\n isValid = false;\n }\n if (!subDomain && validateSubdomain(subDomain)) {\n $('#onboardingPageNameError').text('Please provide page name');\n $('#onboardingPageNameError').show()\n isValid = false;\n }\n if (isValid && window.subdomainValid) {\n if (isProfileUrl) {\n createTeacherProfile(profession, bio, subDomain, profileUrl)\n } else {\n createTeacherProfile(profession, bio, subDomain)\n }\n }\n}",
"function initSecondWizardPage() \n{\n var profileName = document.getElementById(\"profileName\");\n profileName.select();\n profileName.focus();\n\n // Initialize profile name validation.\n checkCurrentInput(profileName.value);\n}",
"function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}",
"function gendervalidation(){\n\tif($(\"#genderpopup\").val() == \"\"){\n\t\t$(\"#notnullgender\").show();\n\t\treturn false;\n\t} else {\n\t\t$(\"#notnullgender\").hide();\n\t\treturn true;\n\t}\n}",
"function custPreFormValidation(preChatlableObject, user){\n return true;\n}",
"function mothertonguevalidation(){\n\tif($(\"#mothertonguepopup\").val() == \"\"){\n\t\t$(\"#notnullmothertongue\").show();\n\t\treturn false;\n\t} else {\n\t\t$(\"#notnullmothertongue\").hide();\n\t\treturn true;\n\t}\n}",
"function editForm() {\n app.getForm('profile').handleAction({\n cancel: function () {\n app.getForm('profile').clear();\n response.redirect(URLUtils.https('Account-Show'));\n },\n confirm: function () {\n var isProfileUpdateValid = true;\n var hasEditSucceeded = false;\n var Customer = app.getModel('Customer');\n\n if (!Customer.checkUserName()) {\n app.getForm('profile.customer.email').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (app.getForm('profile.customer.email').value() !== app.getForm('profile.customer.emailconfirm').value()) {\n app.getForm('profile.customer.emailconfirm').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (!app.getForm('profile.login.password').value()) {\n app.getForm('profile.login.password').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (isProfileUpdateValid) {\n hasEditSucceeded = Customer.editAccount(app.getForm('profile.customer.email').value(), app.getForm('profile.login.password').value(), app.getForm('profile.login.password').value(), app.getForm('profile'));\n\n if (!hasEditSucceeded) {\n app.getForm('profile.login.password').invalidate();\n isProfileUpdateValid = false;\n }\n }\n\n if (isProfileUpdateValid && hasEditSucceeded) {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n response.redirect(URLUtils.https('Account-Show'));\n } else {\n response.redirect(URLUtils.https('Account-EditProfile', 'invalid', 'true'));\n }\n },\n changepassword: function () {\n var isProfileUpdateValid = true;\n var hasEditSucceeded = false;\n var Customer = app.getModel('Customer');\n\n if (!Customer.checkUserName()) {\n app.getForm('profile.customer.email').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (!app.getForm('profile.login.currentpassword').value()) {\n app.getForm('profile.login.currentpassword').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (app.getForm('profile.login.newpassword').value() !== app.getForm('profile.login.newpasswordconfirm').value()) {\n app.getForm('profile.login.newpasswordconfirm').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (isProfileUpdateValid) {\n hasEditSucceeded = Customer.editAccount(app.getForm('profile.customer.email').value(), app.getForm('profile.login.newpassword').value(), app.getForm('profile.login.currentpassword').value(), app.getForm('profile'));\n if (!hasEditSucceeded) {\n app.getForm('profile.login.currentpassword').invalidate();\n }\n }\n\n if (isProfileUpdateValid && hasEditSucceeded) {\n response.redirect(URLUtils.https('Account-Show'));\n } else {\n response.redirect(URLUtils.https('Account-EditProfile', 'invalid', 'true'));\n }\n }\n });\n}",
"function register() {\n\tvar newProfile = userObject.getUserData();\n\tvar\tconfirmPassword = document.getElementById('confirm-password').value;\n\n\t// ---=== Conditions to check that each form has been filled out ===--- // \n\tif (newProfile.firstName === '') {\n\t\treturn alert(\"Please enter your first name\")\n\t}\n\n\tif (newProfile.lastName === '') {\n\t\treturn alert(\"Please enter your last name\")\n\t}\n\n\tif (newProfile.email === '') {\n\t\t\treturn alert(\"Please enter your email address\")\n\t\t}\n\n\tif (newProfile.number.length !== 10) {\n\t\treturn alert(\"Please enter a valid 10 digit phone number with no spaces or symbols \\n i.e. 5551235555\")\n\t}\n\n\tif (newProfile.username === '') {\n\t\treturn alert(\"Please enter a username\")\n\t}\n\n\t// ---=== checks that username doesn't already exist ===---\n\tfor (var i = 0; i < userObject.profiles.length; i++) {\n\t\tif (newProfile.username === userObject.profiles[i].username) {\n\t\t\tdocument.getElementById('choose-username').value = '';\n\t\t\treturn alert(\"Sorry the username \" + newProfile.username + \", has already been taken. Please select another!\");\n\t\t}\n\t}\n\t// ---=== Checks that password is at least 6 characters ===---\n\tif (!validatePassword(newProfile.password)) {\n\t\treturn alert(\"Please enter a valid password. \\nYour password must be at least 6 characters long.\");\n\t}\n\t// ---=== Checks that password entry has been confirmed ===--- \n\tif (newProfile.password !== confirmPassword) {\n\t\tdocument.getElementById('confirm-password').value = '';\n\t\treturn alert(\"Please confirm password\");\n\t}\n\n\t// ---=== If everything passes then the new object is added to the userObject.profiles array ===---\n\tuserObject.addProfile(newProfile);\n\n\t// then the register input forms are reset\n\tuserObject.resetUserData();\n\t// then the login input forms are reset\n\tuserObject.resetLoginData();\n\n\t// Finally the show profile function is called\n\tshowProfile();\n}",
"function emptyWarning() {\n \n user_warning.innerHTML = validate.required((user.value == \"\")? \"user\" : 0)\n phone_warning.innerHTML = validate.required((phone.value == \"\")? \"phone\" : 0)\n email_warning.innerHTML = validate.required((email.value == \"\")? \"email\" : 0)\n pass_warning.innerHTML = validate.required((pass.value == \"\") ? \"password\" : 0)\n c_pass_warning.innerHTML = validate.required((c_pass.value == \"\") ? \"confirm password\" : 0)\n \n \n \n \n \n }",
"function registrationForm() {\n app.getForm('profile').handleAction({\n confirm: function () {\n var email, profileValidation, password, passwordConfirmation, existingCustomer, Customer, target, customerExist;\n\n Customer = app.getModel('Customer');\n email = app.getForm('profile.customer.email').value();\n \n profileValidation = true;\n customerExist = false;\n \n password = app.getForm('profile.login.password').value();\n passwordConfirmation = app.getForm('profile.login.passwordconfirm').value();\n\n if (password !== passwordConfirmation) {\n app.getForm('profile.login.passwordconfirm').invalidate();\n profileValidation = false;\n }\n\n // Checks if login is already taken.\n existingCustomer = Customer.retrieveCustomerByLogin(email);\n if (existingCustomer !== null) {\n app.getForm('profile.customer.email').invalidate();\n profileValidation = false;\n customerExist = true;\n }\n\n if (profileValidation) {\n profileValidation = Customer.createAccount(email, password, app.getForm('profile'));\n }\n\n if (!profileValidation) {\n \tif(customerExist){\n \t\tresponse.redirect(URLUtils.https('Login-Show','existing', true));\n \t} else {\n \t\tresponse.redirect(URLUtils.https('Account-Show'));\n \t}\n } else {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n app.getForm('profile').clear();\n target = session.custom.TargetLocation;\n if (target) {\n delete session.custom.TargetLocation;\n //@TODO make sure only path, no hosts are allowed as redirect target\n dw.system.Logger.info('Redirecting to \"{0}\" after successful login', target);\n response.redirect(target);\n } else {\n response.redirect(URLUtils.https('Account-Show', 'registration', 'true'));\n }\n }\n }\n });\n}",
"function fillCreateProfileFromPromoRegister() {\n\t$('#emailIdChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#confrmEmailIdChkOut').val($(\"#confrmEmailIdPromoCode\").val());\n\t$('#passwordChkOut').val($(\"#passwordPromoCode\").val());\n\t$('#mobileNoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeChkOut').val($(\"#zipCodePromoCode\").val());\n\t$('#promoCodeDiscount2').val($(\"#promoCodeDiscount1\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', false);\n\t}\n\t$(\"#createAccountBoxChkOut\").show();\n\tvalidateCreateProfile();\n}",
"function showSelect() {\n $(\"#user\").hide();\n $(\"#user_sel\").show().focus();\n utils.runEval(' Page_Validators[0].controltovalidate = \"user_sel\" ');\n}",
"function errorGetOtherProfile(error){\n removeLoading();\n document.getElementById(\"showProfileMsg\").innerHTML = error.message;\n document.getElementById(\"showProfileMsg\").className = \"errors\"; \n}",
"function toggleValidationPopUp() {\n if (!lodash.isEmpty(ctrl.validationRules)) {\n var popUp = $element.find('.validation-pop-up');\n ctrl.isValidationPopUpShown = !ctrl.isValidationPopUpShown;\n\n if (ctrl.isValidationPopUpShown) {\n $document.on('click', handleDocumentClick);\n\n // in order for the calculation in the function of `$timeout` below to work, the pop up should first\n // be positioned downwards, then it will determine whether it does not have enough room there and\n // will move it upwards in that case.\n ctrl.showPopUpOnTop = false;\n\n $timeout(function () {\n fieldElement.focus();\n ctrl.inputFocused = true;\n ctrl.showPopUpOnTop = $window.innerHeight - popUp.offset().top - popUp.outerHeight() < 0;\n });\n } else {\n $document.off('click', handleDocumentClick);\n }\n }\n }",
"function checkDialog(name, expectedNameText, expectedNameHtml) {\n var expectedText = expectedNameText || name;\n var expectedHtml = expectedNameHtml || expectedText;\n\n // Configure the test profile and show the confirmation dialog.\n var testProfile = self.testProfileInfo_(true);\n testProfile.name = name;\n CreateProfileOverlay.onSuccess(testProfile);\n assertEquals('managedUserCreateConfirm',\n OptionsPage.getTopmostVisiblePage().name);\n\n // Check for the presence of the name and email in the UI, without depending\n // on the details of the messsages.\n assertNotEquals(-1,\n $('managed-user-created-title').textContent.indexOf(expectedText));\n assertNotEquals(-1,\n $('managed-user-created-switch').textContent.indexOf(expectedText));\n var message = $('managed-user-created-text');\n assertNotEquals(-1, message.textContent.indexOf(expectedText));\n assertNotEquals(-1, message.textContent.indexOf(custodianEmail));\n\n // The name should be properly HTML-escaped.\n assertNotEquals(-1, message.innerHTML.indexOf(expectedHtml));\n\n OptionsPage.closeOverlay();\n assertEquals('settings', OptionsPage.getTopmostVisiblePage().name, name);\n }",
"function CreatePatientMessage(val)\n{\t\n\tif(val == 0)\n\t{\n\t\t$('#Create_Patient_Main_Error').html(\"Patient alreday exist\");\n\t\t$(\"#Create_Patient_Main_Success\").hide();\n\t\t$('#Create_Patient_Main_Error').show();\n\t//\t$(\"#Create_User_user_name_error\").show();\n\t//\tdocument.getElementById('Create_User_user_name_error').innerHTML=\"Username already exists\";\n\t}\n\telse if(val == 1)\n\t{\n\t\t $('#Create_Patient_Main_Success').html(\"New patient has been created\");\n\t\t$(\"#Create_Patient_Main_Success\").show();\n\t\t$('#Create_Patient_Main_Error').hide();\n\t//\tdocument.getElementById('Create_User_error_message').innerHTML=\"User Created Successfully\";\t\t\n\t}\n}",
"function validateFunction(name,email,website,image,gender,skills){\n var flag=0;\n var str=\"\";\n //validating name\n if(validateName(name)==false)\n {\n flag=1;\n str=str+\"Name is Required \\n\";\n }\n var isEmailEntered=1;\n //validating email \n if(validateEmail(email)==false)\n {\n flag=1;\n isEmailEntered=0;\n str=str+\"Email is Required \\n\";\n }\n //varify only when email is entered\n if(varifyEmail(email)==false) \n {\n if(isEmailEntered==1){\n flag=1;\n str=str+\"Email is not correct \\n\";\n }\n \n }\n var isWebsiteEntered=1;\n //validating website\n if(validateWebsite(website)==false)\n {\n flag=1;\n isWebsiteEntered=0;\n str=str+\"Website is Required \\n\";\n }\n //varify website only when it is entered\n if((varifyWebsite(website)==false)&&(isWebsiteEntered==1))\n {\n flag=1;\n str=str+\"Unreached Website \\n\";\n }\n //validating image\n if(validateImage(image)==false)\n {\n flag=1;\n str=str+\"Image is required\\n\";\n }\n //validating gender\n if(validateGender(gender==false))\n {\n flag=1;\n str=str+\"Gender is required\\n\";\n }\n //validating skills\n if( validateskills(skills==false))\n {\n flag=1;\n str=str+\"Skill is required\\n\";\n }\n if(flag==0){\n \n return true;\n }\n else {\n alert(str);\n \n return false;\n }\n}",
"tooltipMessage(userInfoType) {\n // if (userInfoType === \"email\" && this.props.email.length < 1) {\n // return \"Please enter your email and search again\"\n // }\n // else if (userInfoType === \"phone\" && this.props.phone.length < 1) {\n // return \"Please enter your phone number and search again\"\n // }\n return \"Changes will not be made until you click SAVE CHANGES\"\n }",
"function drawUserEditor(username){\n\n $.getJSON( root + '/en/users/get_user/' + username, function(data){\n\n console.log( data );\n console.log( user.acc );\n\n var html = \"<form id='user-editor' class='user-editor'>\";\n\n //Creating the inputs for editing core details.\n //---------------------------------------------\n\n html += \"<div class='row top-part'><div class='personal-editor col-xs-12 col-sm-6 col-md-6'>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='username col-xs-12 col-md-6 col-lg-5'>\" + i18n.gettext(\"Username\") +\n \":</label><input type='text' class='username col-xs-12 col-md-6 col-lg-7' \" +\n \"name='username' value='\" + data.username + \"' id='username' \" +\n \"oninput='checkValidUsername()' required /></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='email col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Email\") + \":</label>\" +\n \"<input id='email' type='text' class='email col-xs-12 col-md-6 col-lg-7' \" +\n \"oninput='checkEqual(\\\"email\\\", \\\"email2\\\")' name='email' value='\" +\n data.email + \"' required/></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='email2 col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Retype Email\") + \":</label>\" +\n \"<input id='email2' type='text' oninput='checkEqual(\\\"email\\\", \\\"email2\\\")' \" +\n \"class='email2 col-xs-12 col-md-6 col-lg-7' value='\" +\n data.email + \"' autocomplete='off' required /></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='password col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Password\") + \":</label>\" +\n \"<input id='password' oninput='checkEqual(\\\"password\\\", \\\"password2\\\")' \" +\n \"type='password' class='password col-xs-12 col-md-6 col-lg-7' \" +\n \"name='password' autocomplete='off' value=''/></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='password2 col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Retype Password\") + \":</label>\" +\n \"<input id='password2' oninput='checkEqual(\\\"password\\\", \\\"password2\\\")' \" +\n \"type='password' class='password2 col-xs-12 col-md-6 col-lg-7' \"+\n \"value=''/></div>\";\n\n //Make the time stamps readable.\n creation = data.creation ? new Date(data.creation).toString() : \"\";\n updated = data.updated ? new Date(data.updated).toString() : \"\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='creation col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Creation time\") + \":</label>\" +\n \"<input type='text' readonly class='creation col-xs-12 col-md-6 col-lg-7' value='\" +\n creation + \"' name='creation' /></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='updated col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Last update\") + \":</label>\" +\n \"<input type='text' readonly class='updated col-xs-12 col-md-6 col-lg-7' value='\" +\n updated + \"'/></div>\";\n\n //HACK\n //These hidden password fields stop most browsers applying auto complete to the form.\n //Hidden and dsiabled so they don't cause any detriment to user experience.\n html += \"<input type='password' class='hidden' disabled/>\";\n html += \"<input type='password' class='hidden' disabled />\";\n\n html += \"</div>\";\n\n //Now create the access editor.\n //-----------------------------\n\n html += \"<div class='access-editor col-xs-12 col-sm-6 col-md-4'>\";\n\n html += \"<div class='form-section clearfix'> <div class='section-title'> \" +\n i18n.gettext(\"Add New Access\") + \" </div>\";\n\n //Show the countries selector, only if the user has access to multiple countries.\n var countries = Object.keys(user.acc);\n\n html += \"<div class='input-group row \";\n\n if( countries.length <=1 ) html += \"hidden\";\n\n html += \"'><label class='country col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Country\") + \":</label>\" +\n \"<select class='country col-xs-12 col-md-6 col-lg-7' >\";\n\n for( var i in countries){\n country = countries[i];\n html += \"<option value='\" + country + \"' \";\n if( i === 0 ) html += \"selected\";\n html += \">\" + caps( country ) + \"</option>\";\n }\n\n html += \"</select></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='role col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Access Role\") + \":</label>\" +\n \"<select class='role col-xs-12 col-md-6 col-lg-7'>\";\n\n function drawAvailableRoles(country){\n var roles = user.acc[country];\n var optionsHTML = \"\";\n for( var j in roles){\n role = roles[j];\n optionsHTML += \"<option value='\" + role + \"' \";\n if( j === 0 ) optionsHTML += \"selected\";\n optionsHTML += \">\" + caps( role ) + \"</option>\";\n }\n $('select.role').html( optionsHTML );\n createTooltips();\n }\n\n //Add tooltips that tell the user what access each role inherits.\n function createTooltips(){\n $('select.role option').each( function(){\n console.log( this );\n var country = $('select.country').val();\n var role = $(this).attr('value');\n var element = $(this);\n console.log( \"Country: \" + country + \" Role: \" + role );\n $.getJSON( root + '/en/roles/get_all_access/' + country +'/' + role, function(data){\n var tooltip = \"\";\n console.log( element );\n if( data.access.length > 1 ){\n tooltip = i18n.gettext(\"Complete access from: \");\n tooltip += data.access.map(caps).join(', ') + \".\";\n }else{\n tooltip += i18n.gettext(\"Does not inherit any access.\");\n }\n console.log( tooltip );\n element.attr('title', tooltip);\n\n });\n });\n }\n\n html += \"</select></div>\";\n\n html += \"<button class='btn btn-sm pull-right add-access' type='button'>\" +\n i18n.gettext(\"Add Access\") + \"</button>\";\n\n html += \"</div>\"; //End of form section\n\n html += \"<div class='input-group'><label class='access col-xs-12'>\" +\n i18n.gettext(\"Select Current Access:\") + \"</label>\";\n\n html += \"<select multiple id='access-levels' class='access-levels col-xs-12'>\";\n\n //Factorise this bit out so that we can redraw the options once access has been updated.\n function drawAccessOptions(){\n var optionsHTML = \"\";\n for( var k in data.countries ){\n country = data.countries[k];\n role = data.roles[k];\n optionsHTML += \"<option country='\" + country + \"' role='\" + role + \"' value='\" + k + \"' \" ;\n if( countries.indexOf( country ) == -1 ) optionsHTML += \"disabled\";\n optionsHTML += \">\" + caps( country ) + \" | \" + caps( role ) + \"</option>\";\n }\n $('select.access-levels').html( optionsHTML );\n }\n\n html += \"</select>\";\n\n html += \"<button type='button' class='btn btn-sm pull-right delete-access' >\" +\n i18n.gettext(\"Delete Access\") + \"</button>\";\n\n html += \"</div></div>\"; //End of input group and end of middle part.\n\n //Now create the data editor.\n //---------------------------\n //FOR NOW HIDE THE DATA EDITOR TO KEEP THINGS SIMPLER FOR THE USER\n //...since we don't really use it yet.\n\n html += \"<div class='data-editor col-xs-12 col-sm-6 col-md-4'>\";\n\n html += \"<div class='form-section clearfix'> <div class='section-title'>\" +\n i18n.gettext(\"Edit Data\") + \"</div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='dataKey col-xs-12 col-md-6 col-lg-5'>Data Key:</label>\" +\n \"<input type='text' class='dataKey col-xs-12 col-md-6 col-lg-7'/></div>\";\n\n html += \"<div class='input-group row'>\" +\n \"<label class='dataValue col-xs-12 col-md-6 col-lg-5'>\" +\n i18n.gettext(\"Data Value:\") + \"</label>\" +\n \"<input type='text' class='dataValue col-xs-12 col-md-6 col-lg-7'/></div>\";\n\n html += \"<button class='btn btn-sm pull-right add-data' type='button' >\" +\n i18n.gettext(\"Add Data\") + \"</button>\";\n\n html += \"</div>\"; //End of form section\n\n html += \"<div class='input-group reset-data'><label class='data col-xs-12'>\" +\n i18n.gettext(\"Select Current Data:\") + \"</label>\";\n\n html += \"<select multiple class='data-elements col-xs-12'>\";\n\n //Factorise this bit out so that we can redraw the options once data has been updated.\n function drawDataOptions(){\n var optionsHTML = \"\";\n var dataKeys = Object.keys(data.data);\n for( var x in dataKeys ){\n var element = data.data[dataKeys[x]];\n\n if( element.status != \"uneditable\" ){\n var val = element.val || element.value || \"\" ;\n optionsHTML += \"<option dataKey='\" + dataKeys[x] + \"' dataValue='\" + val + \"' \";\n if( element.status == \"undeletable\" ) optionsHTML += \"disabled datastatus='undeletable' \";\n optionsHTML += \">\" + dataKeys[x] + \" | \" + val + \"</option>\";\n }\n }\n $('select.data-elements').html( optionsHTML );\n }\n\n html += \"</select>\";\n\n html += \"<button class='btn btn-sm pull-right delete-data' type='button'>\" +\n i18n.gettext(\"Delete Data\") + \"</button>\";\n\n html += \"</div></div></div>\"; //End of input group and end of final part and end of row.\n\n html += \"<input type='hidden' class='original_username' name='original_username' value='\" +\n data.username + \"' />\";\n\n html += \"<input type='hidden' class='original_password' name='original_password' value='\" +\n data.password + \"' />\";\n\n state = data.state !== \"\" ? data.state : \"new\";\n\n html += \"<input type='hidden' class='state' name='state' value='\" + state + \"' />\";\n\n html += \"<div class='form-messages col-xs-12 col-sm-6'> </div>\";\n\n buttonText = username === \"\" ? i18n.gettext(\"Create User\") : i18n.gettext(\"Submit Changes\");\n\n html += \"<button type='submit' class='col-xs-12 col-sm-6 btn btn-large submit-form pull-right'>\"+\n buttonText + \"</button>\";\n\n html += \"</form>\";\n\n //DRAW THE FORM\n $('.user-editor').html( html );\n\n\n //Add dynamic links across the form\n //---------------------------------\n\n //HANDLE DATA EDITING.\n\n drawDataOptions();\n\n //Update the data elements shown in the multi-select box.\n function updateData(){\n //Re draw the data\n drawDataOptions();\n\n //Fill in data element values when clicking on a data element in select box.\n $('.data-elements option').click( function(e){\n\n $('input.dataKey').attr('disabled','disabled');\n $('input.dataKey').val($(this).attr(\"dataKey\"));\n $('input.dataValue').val($(this).attr(\"dataValue\"));\n $('button.add-data').text(i18n.gettext('Edit Data'));\n e.stopPropagation();\n\n });\n }\n\n //Refactorisation of the code required to reset the data editor.\n function resetData(){\n $('input.dataKey').removeAttr('disabled');\n $('input.dataKey').val(\"\");\n $('input.dataValue').val(\"\");\n $('button.add-data').text(i18n.gettext('Add Data'));\n }\n\n updateData();\n\n //Reset values to empty for adding new data when clicking outside select box.\n $('.reset-data').click( function(){ reset(); });\n\n //Add the new data element when clicking on the add data value.\n $('button.add-data').click( function(){\n key = $('input.dataKey').val();\n val = $('input.dataValue').val();\n if( key && val ){\n if( data.data.hasOwnProperty( key ) ){\n data.data[key].val = val;\n }else{\n data.data[key] = { \"val\": val };\n }\n resetData();\n updateData();\n }\n });\n\n //Delete selected data when clicking the delete button.\n $('button.delete-data').click( function(e){\n\n //Assemble a list of keys for data tot be deleted.\n var keys = [];\n $('select.data-elements option:selected').each( function(){\n keys.push( $(this).attr('dataKey') );\n });\n\n //Only delete if some data is actually select.\n if( keys.length > 0 ){\n\n //Create a confirm dialouge showing the user what data they are about to delete.\n var confirmString = i18n.gettext(\"Are you sure you want to delete this data?\") +\n \"\\n\";\n for (var y in keys){\n var key = keys[y];\n confirmString += \" \" + key + \" | \" + data.data[key].val + \"\\n\";\n }\n\n //If the user confirms, actually do the deletion.\n if( confirm( confirmString ) ){\n for( var z in keys ) delete data.data[keys[z]];\n updateData();\n }\n resetData();\n }\n //Stop rest kicking in if no deletion happens.\n e.stopPropagation();\n });\n\n //HANDLE ACCESS LEVELS\n\n drawAccessOptions();\n drawAvailableRoles($('select.country').val());\n\n $('select.country').change(function(){\n drawAvailableRoles($('select.country').val());\n });\n\n //Add the new access element when clicking on the add access value.\n $('button.add-access').click( function(){\n country = $('select.country').val();\n role = $('select.role').val();\n if( country && role ){\n data.countries.push( country );\n data.roles.push( role );\n drawAccessOptions();\n }\n });\n\n //Delete selected access when clicking the delete button.\n $('button.delete-access').click( function(e){\n\n //Assemble a list of indicies for access to be deleted.\n var indicies = [];\n $('select.access-levels option:selected').each( function(){\n indicies.push( $(this).val() );\n });\n\n //Only delete if some access is actually select.\n if( indicies.length > 0 ){\n\n //Create a confirm dialouge showing the user what access they are about to delete.\n var confirmString = i18n.gettext(\"Are you sure you want to delete this access?\") +\n \"\\n\";\n for( var y in indicies ){\n country = data.countries[indicies[y]];\n role = data.roles[indicies[y]];\n confirmString += \" \" + country + \" | \" + role + \"\\n\";\n }\n\n //If the user confirms, actually do the deletion.\n if( confirm( confirmString ) ){\n for( var z in indicies ){\n delete data.countries[ indicies[z] ]; //Will not reindex array.\n delete data.roles[ indicies[z] ]; //Will not reindex array.\n }\n data.countries = cleanArray( data.countries );\n data.roles = cleanArray( data.roles );\n drawAccessOptions();\n }\n\n }\n\n });\n\n //FORM SUBMISSION\n $('.user-editor .submit-form').click(function(evt){\n\n if( formValid() ){\n evt.preventDefault();\n $('.user-editor .submit-form').html( i18n.gettext(\"Working\" ) +\n \" <div class='loading'></div>\" );\n //Assemble complete json object.\n var data = {};\n var form = $('.user-editor');\n var formArray = form.serializeArray();\n\n for( var z in formArray ){\n var element = formArray[z];\n data[element.name] = element.value;\n }\n\n $.extend( data, extractAccess() );\n $.extend( data, extractData() );\n\n //Post json to server.\n $.ajax({\n url: root + '/en/users/update_user/' + data.original_username,\n type: 'post',\n success: function (data) {\n alert(data);\n drawUserEditor(\"\");\n $('#user-table table').bootstrapTable('refresh');\n },\n error: function (data) {\n alert( i18n.gettext(\"There has been a server error. \" +\n \"Please contact administrator and try again later.\") );\n $('.user-editor .submit-form').text( buttonText );\n $('#user-table table').bootstrapTable('refresh');\n },\n contentType: 'application/json;charset=UTF-8',\n data: JSON.stringify(data, null, '\\t')\n });\n }\n });\n\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the F distribution CDF | static cdf_f(f_stat, f1, f2) {
var X = f_stat;
var Z = X / (X + f2/f1);
var Fcdf = this.Betacdf(Z, f1/2, f2/2);
Fcdf = Math.round(Fcdf * 100000) / 100000;
return Fcdf;
} | [
"static cdf_t(t_stat, df) {\n\t\tvar X = t_stat;\n\t\tvar tcdf, betacdf;\n\n\t\tvar A = df/2;\n\t\tvar S = A+.5;\n\t\tvar Z = df / (df + X*X);\n\t\tvar BT = Math.exp(this.LogGamma(S)-this.LogGamma(.5)-this.LogGamma(A) + A * Math.log(Z) + .5 * Math.log(1-Z));\n\t\tif (Z < (A+1) / (S+2)) {\n\t\t\tbetacdf = BT * this.Betinc(Z,A,.5)\n\t\t} else {\n\t\t\tbetacdf = 1 - BT * this.Betinc(1-Z,.5,A)\n\t\t}\n\t\tif (X<0) {\n\t\t\ttcdf = betacdf/2\n\t\t} else {\n\t\t\ttcdf = 1 - betacdf/2\n\t\t}\n\t\ttcdf = Math.round(tcdf*100000)/100000;\n\t\t\n\t\treturn tcdf;\n\t}",
"static cdf_chisq(x, df) {\n\t\tlet Z = x\n\t\tlet DF = df;\n\t\tlet Chisqcdf = this.Gammacdf(Z/2, DF/2)\n\n\t\tChisqcdf = Math.round(Chisqcdf * 100000) / 100000;\n\t\treturn 1 - Chisqcdf;\n\t}",
"static Gcf(X,A) {\n\t\tvar A0 = 0;\n\t\tvar B0 = 1;\n\t\tvar A1 = 1;\n\t\tvar B1 = X;\n\t\tvar AOLD = 0;\n\t\tvar N = 0;\n\t\twhile (Math.abs((A1 - AOLD)/A1)>.00001) {\n\t\t\tAOLD = A1;\n\t\t\tN = N+1;\n\t\t\tA0 = A1+(N-A)*A0;\n\t\t\tB0 = B1+(N-A)*B0;\n\t\t\tA1 = X*A0+N*A1;\n\t\t\tB1 = X*B0+N*B1;\n\t\t\tA0 = A0/B1;\n\t\t\tB0 = B0/B1;\n\t\t\tA1 = A1/B1;\n\t\t\tB1 = 1;\n\t\t}\n\t\tvar Prob=Math.exp(A*Math.log(X)-X-this.LogGamma(A))*A1;\n\t\t\n\t\treturn 1-Prob\n\t}",
"Coef(e) {\r\n for (let i = 0; i < this._term.Length(); ++i) {\r\n if (this._term.GetElement(i).Exp === e) {\r\n return this._term.GetElement(i).Coef;\r\n }\r\n }\r\n return null;\r\n }",
"function doFV(){\n let principal = parseFloat(document.getElementById(\"principal\").value);\n let rate = parseFloat(document.getElementById(\"rate\").value);\n let years = parseInt(document.getElementById(\"years\").value);\n let periods = parseInt(document.getElementById(\"periods\").value);\n document.getElementById(\"output\").value = '$' + computeFutureValue(principal,rate,years,periods).toFixed(2);\n\n}",
"function determineFrequency(f) {\n var qstate = new jsqubits.QState(numInBits + numOutBits).hadamard(inputBits);\n qstate = qstate.applyFunction(inputBits, outBits, f);\n // We do not need to measure the outBits, but it does speed up the simulation.\n qstate = qstate.measure(outBits).newState;\n return qstate.qft(inputBits)\n .measure(inputBits).result;\n }",
"function cdc()\n {\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let s = undefined ;\n let vi = undefined ;\n\n for( i = 0 ; i < this.nr ; i++ )\n\n for( j = 0 ; j <= i ; ++j )\n {\n\n for( s = k = 0 ; k < j ; s += (this.v[ this.idx( i , k ) ] * this.v[ this.idx( j , k++ ) ]) ) ;\n\n if( i == j )\n {\n\n // Diagonal element:\n\n vi = this.idx( i , i ) ;\n\n this.v[ vi ] = Math.sqrt( this.v[ vi ] - s ) ;\n\n } // end if +\n\n else\n {\n\n // Outer diagonal element:\n\n vi = this.idx( i , j ) ;\n\n this.v[ vi ] = ( (this.v[ vi ] - s) / this.v[ this.idx( j , j ) ] ) ;\n\n } ; // end else \n\n } ; // end for()\n\n }",
"function guesstimatorInputToCdf({\n guesstimatorInput,\n simulationSampleCount,\n outputSampleCount,\n smoothingWidth,\n min,\n max\n}) {\n let toSamples = inputToSamples({\n input: guesstimatorInput,\n simulationSampleCount: simulationSampleCount\n });\n var samp = new cdfLib.Samples(toSamples.values);\n return samp.toCdf({\n size: outputSampleCount,\n width: smoothingWidth,\n min: min,\n max: max\n });\n}",
"function correlation_coeff_p(X, Y) {\n return covariance_p(X, Y) / (stddev_p(X) * stddev_p(Y));\n}",
"function jacobi_cd(u, m) {\n return jacobi_cn(u, m) / jacobi_dn(u, m);\n}",
"function calcFactorial(numb) {\n \n return Math.sqrt(2*Math.PI)*Math.pow(numb,numb+(1/2))*Math.pow(Math.E,-numb); //the calculated factorial is returned\n \n \n}",
"function fScore (precisie, recall) {\n return 2 * ((precisie * recall) / (precisie + recall))\n}",
"function local_correlations() {\n let R = 0;\n for (let x = 0; x < gridSize; x++) {\n for (let y = 0; y < gridSize; y++) {\n R += calcDeltaE(x, y) / 8;\n }\n }\n return R / N;\n}",
"calDiscount(){\n this._discount = this._totalCharged * (10/100) ;\n }",
"function coeff_of_determination_s(X, Y) {\n return correlation_coeff_s(X, Y) ** 2;\n}",
"function getFrequency(value) {\n\tif (!ctx) {\n\t\treturn 0;\n\t}\n\t// get frequency by passing number from 0 to 1\n\t// Clamp the frequency between the minimum value (40 Hz) and half of the\n\t// sampling rate.\n\tvar minValue = 40;\n\tvar maxValue = ctx.sampleRate / 2;\n\t// Logarithm (base 2) to compute how many octaves fall in the range.\n\tvar numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n\t// Compute a multiplier from 0 to 1 based on an exponential scale.\n\tvar multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n\t// Get back to the frequency value between min and max.\n\treturn maxValue * multiplier;\n}",
"function compute_LF_ferment(ibu) {\n var LF_ferment = 0.0;\n var LF_flocculation = 0.0;\n\n // The factors here come from Garetz, p. 140\n if (ibu.flocculation.value == \"high\") {\n LF_flocculation = 0.95;\n } else if (ibu.flocculation.value == \"medium\") {\n LF_flocculation = 1.00;\n } else if (ibu.flocculation.value == \"low\") {\n LF_flocculation = 1.05;\n } else {\n console.log(\"ERROR: unknown flocculation value: \" + ibu.flocculation.value);\n LF_flocculation = 1.00;\n }\n\n LF_ferment = SMPH.fermentationFactor * LF_flocculation;\n if (SMPH.verbose > 5) {\n console.log(\"LF ferment : \" + LF_ferment.toFixed(4));\n }\n return LF_ferment;\n}",
"calcDiscount() {\n if (this.discount != 0 || this.discount != null) {\n this.discPrice = (1 - this.discount / 100) * this.totalPrice;\n }\n }",
"function createHfLut(fs, hfLut, n) {\n\t//var n = 1 + Math.ceil(1.0 / p);\n\tvar b = 0.65;\n\tvar u0 = 0.0;\n\tvar u1 = 1.0;\n\tvar nn = 1;\n//\tvar fsn = fs.length;\n\tvar fis = (u1 - u0) / functionSummaries.length;\n\tfor (var i = 0; i < n; ++i) {\n\t\tvar u = (1.0 * i) / n;\n\t\tvar fic = Math.floor(functionSummaries.length * u);\n\t\tvar v = 0;\n\t\tvar fi0 = Math.max(0, fic - nn), fi1 = Math.min(functionSummaries.length - 1, fic + nn);\n\t\tfor (var fi = fi0;\n\t\t\tfi <= fi1; ++fi) {\n\t\t\tvar ficu = u0 + fis / 2 + fis * fi;\n\t\t\tvar su = b * (u - ficu) * 2.0 / fis;\n//\t\t\talert(\"\" + fi + \":\" + su);\n\t\t\tv += fs[fi] * (su < 0 ? stepf(-su) : stepf(su));\n\t\t}\n\t\thfLut[i] = v;\n\t\t\n\t\t\n\t\t\n\t}\n\thfLut[n] = hfLut[n - 1];\n//\talert(hfLut);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a return character and enough spaces to indent the text so as to match the previous line. | function returnWithIndent() {
// Selection DOM object
const dSel = ta;
// How many spaces will be put before the first non-space?
var space = 0;
if (dSel.selectionStart || dSel.selectionStart == '0') {
var startPos = dSel.selectionStart;
var endPos = dSel.selectionEnd;
var scrollTop = dSel.scrollTop;
var before = dSel.value.substring(0, startPos);
var after = dSel.value.substring(endPos,dSel.value.length);
var split = before.split("\n");
// What is the last line before the caret?
var last = split[split.length-1];
for(var i=0; i<last.length; i++) {
if(last.charAt(i) != ' ') {
break;
}
space++;
}
// Create the return
var myValue = "\n";
for(i=0; i<space; i++) {
myValue += ' ';
}
insertText(dSel, myValue);
dSel.selectionStart = startPos + myValue.length;
dSel.selectionEnd = startPos + myValue.length;
} else {
dSel.value += "\n";
dSel.focus();
}
return space > 0;
} | [
"function Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}",
"indentation() {\n var _a\n return (_a = this.overrideIndent) !== null && _a !== void 0\n ? _a\n : countCol(this.string, null, this.tabSize)\n }",
"ReturnStatement() {\n this._eat(\"return\");\n const argument = this._lookahead.type !== \";\" ? this.Expression() : null;\n this._eat(\";\");\n return {\n type: \"ReturnStatement\",\n argument,\n };\n }",
"insertMarkdownBetween (character) {\n const beforeText = this.state.text.substring(0, this.state.endOfSelection)\n const afterText = this.state.text.substring(this.state.endOfSelection, this.state.text.length)\n\n this.setState({\n text: beforeText + character + afterText\n })\n }",
"function showReturn(ctx){\r\n ctx.telegram.sendMessage(ctx.chat.id,wordsList[language].Return,{\r\n reply_markup : {\r\n inline_keyboard: [\r\n [{text:\"\\u{21A9}\",callback_data:\"RETURN\"}],\r\n ]\r\n }\r\n })\r\n}",
"function deleteCharAtPos() {\n if (column < promptText.length) {\n promptText =\n promptText.substring(0, column) +\n promptText.substring(column + 1);\n restoreText = promptText;\n return true;\n } else return false;\n }",
"insertBreak(editor) {\n editor.insertBreak();\n }",
"continue() {\n let parent = this.node.parent\n return parent ? indentFrom(parent, this.pos, this.base) : 0\n }",
"insertLinebreak() {\n const prompt = this.prompt;\n const model = prompt.model;\n const editor = prompt.editor;\n // Insert the line break at the cursor position, and move cursor forward.\n let pos = editor.getCursorPosition();\n const offset = editor.getOffsetAt(pos);\n const text = model.value.text;\n model.value.text = text.substr(0, offset) + '\\n' + text.substr(offset);\n // pos should be well defined, since we have inserted a character.\n pos = editor.getPositionAt(offset + 1);\n editor.setCursorPosition(pos);\n }",
"function printNewLine() {\r\n\tterminal.innerHTML += '\\n';\r\n}",
"function getOffset() {\n var indentation = [];\n var pos = line + 1;\n\n /* Done. Called when the last character is\n * eaten to retrieve the range’s offsets. */\n return function () {\n var last = line + 1;\n\n while (pos < last) {\n indentation.push((offset[pos] || 0) + 1);\n\n pos++;\n }\n\n return indentation;\n };\n }",
"function syntaxIndentation(cx, ast, pos) {\n return indentFrom(\n ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),\n pos,\n cx\n )\n }",
"function skipNewline(text,index,opts){var backwards=opts&&opts.backwards;if(index===false){return false;}var atIndex=text.charAt(index);if(backwards){if(text.charAt(index-1)===\"\\r\"&&atIndex===\"\\n\"){return index-2;}if(atIndex===\"\\n\"||atIndex===\"\\r\"||atIndex===\"\\u2028\"||atIndex===\"\\u2029\"){return index-1;}}else{if(atIndex===\"\\r\"&&text.charAt(index+1)===\"\\n\"){return index+2;}if(atIndex===\"\\n\"||atIndex===\"\\r\"||atIndex===\"\\u2028\"||atIndex===\"\\u2029\"){return index+1;}}return index;}",
"function spacebar(e) {\n if (e.keyCode === 32) {\n jumping()\n }\n}",
"function extendLine (line, st) {\n if ((line.length + st.length) > 78) {\n output += line + \"-\\n\";\n return \"M V30 \" + st;\n }\n return line + st;\n }",
"function insertThinSpaces(text, start, end) {\n if (!start) start = 0;\n if (!end) end = text.getText().length - 1;\n if (end - start <= 1)\n return;\n var oldText = text.getText().slice(start, end + 1);\n var newText = oldText;\n var numberCount = 0;\n \n newText = newText.replace(/ /g, '');\n \n for (var i = newText.length - 1; i > 0; i--) {\n \n if (isNumber(newText[i])) {\n numberCount++;\n \n if (numberCount % 3 === 0 && numberCount !== 0 && isNumber(newText[i - 1])) {\n newText = [newText.slice(0, i), \"\\u2009\", newText.slice(i)].join('');\n }\n } else {\n numberCount = 0;\n }\n }\n \n text.deleteText(start, end);\n text.insertText(start, newText);\n}",
"function insertChar(charCode) {\n var state = getState();\n removeExtraStuff(state);\n var myChar = String.fromCharCode(charCode);\n if (state.selection.start !== state.selection.end) {\n state.value = clearRange(state.value, state.selection.start, state.selection.end);\n }\n dotPos = state.value.indexOf('.');\n if (myChar === '.' && dotPos !== -1) {\n // If there is already a dot in the field, don't do anything\n return;\n }\n if (state.value.length - (dotPos === -1 && myChar !== '.' ? 0 : 1) >= config.digits) {\n // If inserting the new value makes the field too long, don't do anything\n return;\n }\n state.value = state.value.substring(0, state.selection.start) + myChar +\n state.value.substring(state.selection.start);\n addExtraStuff(state, false);\n setState(state);\n }",
"function insertText(a) {\n\t$chatline.val($chatline.val()+a).focus();\n}",
"function getLineBreak(theForm){\n var retVal;\n var selInd = theForm.WhichPlatform.selectedIndex;\n\n switch (selInd){\n case 0:\n\t retVal = \"\\r\\n\";\n\t\t break;\n\t case 1:\n\t retVal = \"\\r\";\n\t\t break;\n\t case 2:\n\t retVal = \"\\n\";\n\t\t break;\n }\n \n return retVal;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines a reference to an enum able | function enumReference(table, colEnum, tableEnum, required = false) {
const column = table
.specificType(colEnum, "smallint")
.references("id")
.inTable(tableEnum);
if (required) {
column.notNullable();
}
return column;
} | [
"bindIdeLinkEnum() {\n this.app.singleton('ide.link', _IdeLink.default);\n }",
"function Reference() {}",
"function MoveEnumObj() {\n let e = d.Config.enums\n let i = u.GetNumber(event.target.id);\n if (i === 0) { return false; }\n let enumName = u.ID(\"selectAdminEnum\").value;\n let j;\n if (event.target.id.charAt(7) === \"U\") { j = i - 1; }\n else { j = i + 1; }\n u.Swap(e[enumName], i, j);\n u.WriteDict(0);\n u.WriteConfig();\n}",
"function AddEnumItem() {\n let e = d.Config.enums\n let enumName = u.ID(\"selectAdminEnum\").value;\n e[enumName].push(\"\");\n u.WriteConfig();\n}",
"function enumCycleFunction(name, value) {\n\n const enumDefinition = value.enumDefinition();\n const valueCount = enumDefinition.getValueCount();\n\n let showPopup = false;\n let onChangeFn = (newValue) => { if (showPopup) popup(`${name}: ${enumDefinition.valueDefinitionFor(newValue).getDisplayName()}`); showPopup = false; };\n\n value.addValueObserver(onChangeFn);\n\n return (status, data1, data2) => {\n if (data2 !== 0) {\n // let me know if there's a less convoluted way to do this..........\n const currentId = value.get();\n const valueDefinition = enumDefinition.valueDefinitionFor(currentId);\n const currentIndex = valueDefinition.getValueIndex();\n const nextIndex = (currentIndex + 1) % valueCount;\n const nextValue = enumDefinition.valueDefinitionAt(nextIndex);\n const nextId = nextValue.getId();\n\n showPopup = true;\n value.set(nextId);\n }\n }\n}",
"function isJSMFEnum(o) {\n return conformsTo(o) === Enum\n}",
"createEnumResources(model) {\n if (model.subClassOf !== ENUM || !model.enum)\n return\n let eProp\n for (let p in model.properties) {\n if (p !== TYPE) {\n eProp = p\n break\n }\n }\n model.enum.forEach((r) => {\n let enumItem = {\n [TYPE]: model.id,\n [ROOT_HASH]: r.id,\n [eProp]: r.title\n }\n this.loadStaticItem(enumItem)\n })\n }",
"injectEnumEntity(lang, entity) {\n return new Promise((resolve) => {\n const { name: entityName, options } = entity\n const optionKeys = Object.keys(options)\n\n optionKeys.forEach((optionName) => {\n const { synonyms } = options[optionName]\n\n this.ner.addRuleOptionTexts(lang, entityName, optionName, synonyms)\n })\n\n resolve()\n })\n }",
"createEnumResources(model) {\n if (!utils.isEnum(model) || !model.enum)\n return\n let eProp\n for (let p in model.properties) {\n if (p !== TYPE) {\n eProp = p\n break\n }\n }\n model.enum.forEach((r) => {\n let enumItem = {\n [TYPE]: model.id,\n [ROOT_HASH]: r.id,\n [eProp]: r.title\n }\n this.loadStaticItem(enumItem)\n })\n }",
"asEnum(values) {\n return new CreateTypeBuilder({\n ...this.#props,\n node: create_type_node_js_1.CreateTypeNode.cloneWithEnum(this.#props.node, values),\n });\n }",
"function getEnumData(reagent) {\n\n if(reagent == REAGENTS.NaHCO3.name)\n return(REAGENTS.NaHCO3);\n else if(reagent == REAGENTS.Na2CO3.name)\n return(REAGENTS.Na2CO3);\n else if(reagent == REAGENTS.NaOH.name)\n return(REAGENTS.NaOH);\n else if(reagent == REAGENTS.HCl.name)\n return(REAGENTS.HCl);\n else if(reagent == REAGENTS.CaOH2.name)\n return(REAGENTS.CaOH2);\n else if(reagent == REAGENTS.CaCO3.name)\n return(REAGENTS.CaCO3);\n else if(reagent == REAGENTS.CaO.name)\n return(REAGENTS.CaO);\n else if(reagent == REAGENTS.CO2_Remove.name)\n return(REAGENTS.CO2_Remove);\n else if(reagent == REAGENTS.CO2_Add.name)\n return(REAGENTS.CO2_Add);\n}",
"exitEnumConstantModifier(ctx) {\n\t}",
"enterEnumConstantList(ctx) {\n\t}",
"exitEnumConstantName(ctx) {\n\t}",
"function renderEnumSelector (rows, columns, column, list) {\n const doMultiple = true\n const result = doc.createElement('div')\n const dropdown = doc.createElement('select')\n\n let searchValue = {} // Defualt to all enabled\n for (let i = 0; i < list.length; ++i) {\n const value = list[i]\n searchValue[value.uri] = true\n }\n\n const initialSelection = getHints(column).initialSelection\n if (initialSelection) searchValue = initialSelection\n\n if (doMultiple) dropdown.setAttribute('multiple', 'true')\n else dropdown.appendChild(optionElement('(All)', '-1'))\n\n for (let i = 0; i < list.length; ++i) {\n const value = list[i]\n const ele = optionElement(utils.label(value), i)\n if (searchValue[value.uri]) ele.selected = true\n dropdown.appendChild(ele)\n }\n result.appendChild(dropdown)\n\n // Select based on an enum value.\n\n column.filterFunction = function (colValue) {\n return !searchValue || (colValue && searchValue[colValue.uri])\n }\n\n dropdown.addEventListener(\n 'click',\n function () {\n if (doMultiple) {\n searchValue = {}\n const opt = dropdown.options\n for (let i = 0; i < opt.length; i++) {\n const option = opt[i]\n const index = Number(option.value)\n if (opt[i].selected) searchValue[list[index].uri] = true\n }\n } else {\n const index = Number(dropdown.value) // adjusted in Standard tweaks 2018-01\n if (index < 0) {\n searchValue = null\n } else {\n searchValue = {}\n searchValue[list[index].uri] = true\n }\n }\n applyColumnFilters(rows, columns)\n },\n true\n )\n\n return result\n }",
"function favouriteTeamReferenceAction() {\n const action = {\n type: ApiConstants.API_FAVOURITE_TEAM_REFERENCE_LOAD,\n };\n return action;\n}",
"function countryReferenceAction() {\n const action = {\n type: ApiConstants.API_COUNTRY_REFERENCE_LOAD,\n };\n return action;\n}",
"static _generateEnums(modules) {\n const pallets = eNum(\"Pallets\", [], true);\n const moduleCalls = [];\n\n modules.forEach((module, index) => {\n pallets.addMember([module.name, index]);\n if (module.calls) {\n const calls = [];\n module.calls.forEach((call, index) => {\n calls.push([call.name, index]);\n });\n moduleCalls.push(eNum(`${module.name}Calls`, calls, true));\n };\n });\n return {\n pallets,\n moduleCalls\n }\n }",
"static checkEnum(a, enumeration) {\n\t\tconst valid = Object.values(enumeration);\n\t\tif (a === undefined) {\n\t\t\treturn;\n\t\t}\n\t\tif (valid.indexOf(a) === -1) {\n\t\tthrow Error(\n\t\t\t\"Invalid enum value \" + a + \n\t\t\t\", expected one of \" + valid.join(\", \"));\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expects r and s to be positive DER integers. The DER format uses the most significant bit as a sign bit (& 0x80). If the significant bit is set AND the integer is positive, a 0x00 is prepended. Examples: 0 => 0x00 1 => 0x01 1 => 0xff 127 => 0x7f 127 => 0x81 128 => 0x0080 128 => 0x80 255 => 0x00ff 255 => 0xff01 16300 => 0x3fac 16300 => 0xc054 62300 => 0x00f35c 62300 => 0xff0ca4 | function encode (r, s) {
var lenR = r.length
var lenS = s.length
if (lenR === 0) throw new Error('R length is zero')
if (lenS === 0) throw new Error('S length is zero')
if (lenR > 33) throw new Error('R length is too long')
if (lenS > 33) throw new Error('S length is too long')
if (r[0] & 0x80) throw new Error('R value is negative')
if (s[0] & 0x80) throw new Error('S value is negative')
if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
var signature = new Buffer(6 + lenR + lenS)
// 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
signature[0] = 0x30
signature[1] = signature.length - 2
signature[2] = 0x02
signature[3] = r.length
r.copy(signature, 4)
signature[4 + lenR] = 0x02
signature[5 + lenR] = s.length
s.copy(signature, 6 + lenR)
return signature
} | [
"function toDER(r, s) {\n r = r.toArray()\n s = s.toArray()\n \n function constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len)\n return\n }\n \n let octets = 1 + (Math.log(len) / Math.LN2 >>> 3)\n arr.push(octets | 0x80)\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff)\n }\n \n arr.push(len)\n }\n\n function rmPadding(buf) {\n let i = 0\n const len = buf.length - 1\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++\n }\n if (i === 0) {\n return buf\n }\n return buf.slice(i)\n }\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r)\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s)\n\n r = rmPadding(r)\n s = rmPadding(s)\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1)\n }\n \n let arr = [ 0x02 ]\n constructLength(arr, r.length)\n arr = arr.concat(r)\n arr.push(0x02)\n constructLength(arr, s.length)\n const backHalf = arr.concat(s)\n let res = [ 0x30 ]\n constructLength(res, backHalf.length)\n res = res.concat(backHalf)\n return Buffer.from(res).toString('hex')\n }",
"function binl(x, len) {\n var T, j, i, l,\n h0 = 0x67452301,\n h1 = 0xefcdab89,\n h2 = 0x98badcfe,\n h3 = 0x10325476,\n h4 = 0xc3d2e1f0,\n A1, B1, C1, D1, E1,\n A2, B2, C2, D2, E2;\n\n /* append padding */\n x[len >> 5] |= 0x80 << (len % 32);\n x[(((len + 64) >>> 9) << 4) + 14] = len;\n l = x.length;\n\n for (i = 0; i < l; i += 16) {\n A1 = A2 = h0;\n B1 = B2 = h1;\n C1 = C2 = h2;\n D1 = D2 = h3;\n E1 = E2 = h4;\n for (j = 0; j <= 79; j += 1) {\n T = safe_add(A1, rmd160_f(j, B1, C1, D1));\n T = safe_add(T, x[i + rmd160_r1[j]]);\n T = safe_add(T, rmd160_K1(j));\n T = safe_add(bit_rol(T, rmd160_s1[j]), E1);\n A1 = E1;\n E1 = D1;\n D1 = bit_rol(C1, 10);\n C1 = B1;\n B1 = T;\n T = safe_add(A2, rmd160_f(79 - j, B2, C2, D2));\n T = safe_add(T, x[i + rmd160_r2[j]]);\n T = safe_add(T, rmd160_K2(j));\n T = safe_add(bit_rol(T, rmd160_s2[j]), E2);\n A2 = E2;\n E2 = D2;\n D2 = bit_rol(C2, 10);\n C2 = B2;\n B2 = T;\n }\n\n T = safe_add(h1, safe_add(C1, D2));\n h1 = safe_add(h2, safe_add(D1, E2));\n h2 = safe_add(h3, safe_add(E1, A2));\n h3 = safe_add(h4, safe_add(A1, B2));\n h4 = safe_add(h0, safe_add(B1, C2));\n h0 = T;\n }\n return [h0, h1, h2, h3, h4];\n }",
"function encodeSignedNumber_(num) {\n var sgn_num = num << 1;\n\n if (num < 0) {\n sgn_num = ~(sgn_num);\n }\n\n var encodeString = \"\";\n\n while (sgn_num >= 0x20) {\n encodeString += ALPHABET_.charAt(0x20 | (sgn_num & 0x1f));\n sgn_num >>= 5;\n }\n\n encodeString += ALPHABET_.charAt(sgn_num);\n return encodeString;\n }",
"function negbigint2behex(intvalue) {\n if (intvalue >= 0) // ONLY NEGATIVE!\n return null;\n x = intvalue;\n /*\n // https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx\n The BigInteger structure assumes that negative values are stored by using two's complement representation. Because the BigInteger structure represents a numeric value with no fixed length, the BigInteger(Byte[]) constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the BigInteger(Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the BigInteger(Byte[]) constructor as -1,000,000. To instantiate a BigInteger whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor.\n */\n //x=-1000000; // must become (big endian) \"f0bdc0\" => little endian C0 BD F0 (careful with positive 4,293,967,296 that may become negative, need to be C0 BD F0 FF 00)\n // ASSERT (x < 0) !!! x==0 is problematic! equals to 256...\n //x=-1; // ff\n //x=-2; // fe\n //x=-127; // 81\n //x=-255; // \"ff01\" => 01 ff\n //x=-256; // \"ff00\" => 00 ff\n //x=-257; // \"feff\" => ff fe\n //x=-128; // \"ff80\" => 80 ff\n // only for negative integers\n x *= -1; // turn into positive\n // ========================\n // perform two's complement\n // ========================\n // convert to binary\n y = x.toString(2);\n //console.log(\"FIRST BINARY: \"+y);\n // extra padding for limit cases (avoid overflow)\n y = \"0\" + y;\n //guarantee length must be at least 8, or add padding!\n while ((y.length < 8) || (y.length % 8 != 0)) {\n //console.log(\"ADDING PADDING 1!\");\n y = \"0\" + y;\n }\n // invert bits\n y2 = \"\";\n for (i = 0; i < y.length; i++)\n y2 += y[i] == '0' ? '1' : '0';\n //console.log(\"SECOND BINARY: \"+y2);\n // go back to int\n y3 = parseInt(y2, 2);\n //console.log(\"INT is \"+y3);\n // sum 1\n y3 += 1;\n //console.log(\"INT is after sum \"+y3);\n // convert to binary again\n y4 = y3.toString(2);\n //guarantee length must be at least 8, or add padding!\n while (y4.length < 8) {\n //console.log(\"ADDING PADDING!\");\n y4 = \"0\" + y4;\n }\n ///// verify if most important bit in LAST byte would is already set... (NO NEED.. ONLY FOR POSITIVE INTEGERS)\n //index = y4.length-8;\n //if(y4[index]=='0') {\n //console.log(\"CREATING EXTRA BYTE! BUT HOW?\");\n // must create an extra byte just to inform sign...\n //y4=\"10000000\"+y4; // could be 1xxxxxxx I guess, but everyone is just using f0 (which is 11110000)...\n //}\n\n //console.log(\"final binary:\"+y4);\n\n // convert to hex\n y5 = parseInt(y4, 2).toString(16);\n // adjust padding\n\n return revertHexString(y5); // big endian\n}",
"static bytes11(v) { return b(v, 11); }",
"function rstr_sha1(s)\n\t\t{\n\t\t return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));\n\t\t}",
"function pkcs1pad2(s,n) {\r\n if(n < s.length + 11) {\r\n alert(\"Message too long for RSA\");\r\n return null;\r\n }\r\n var ba = new Array();\r\n var i = s.length - 1;\r\n while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);\r\n ba[--n] = 0;\r\n var rng = new SecureRandom();\r\n var x = new Array();\r\n while(n > 2) { // random non-zero pad\r\n x[0] = 0;\r\n while(x[0] == 0) rng.nextBytes(x);\r\n ba[--n] = x[0];\r\n }\r\n ba[--n] = 2;\r\n ba[--n] = 0;\r\n return new BigInteger(ba);\r\n}",
"function intToHex(integer){if(integer<0){throw new Error('Invalid integer as argument, must be unsigned!');}var hex=integer.toString(16);return hex.length%2?\"0\"+hex:hex;}",
"function hex2base58(s){ return Bitcoin.Base58.encode(hex2bytes(s))}",
"static bytes10(v) { return b(v, 10); }",
"static int8(v) { return n(v, -8); }",
"static bytes22(v) { return b(v, 22); }",
"function _rsapem_publicKeyToX509HexString(rsaKey) {\n var encodedIdentifier = \"06092A864886F70D010101\";\n var encodedNull = \"0500\";\n var headerSequence = \"300D\" + encodedIdentifier + encodedNull;\n\n var keys = _rsapem_derEncodeNumber(rsaKey.n);\n keys += _rsapem_derEncodeNumber(rsaKey.e);\n\n var keySequence = \"0030\" + _rsapem_encodeLength(keys.length / 2) + keys;\n var bitstring = \"03\" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;\n\n var mainSequence = headerSequence + bitstring;\n\n return \"30\" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;\n}",
"function rdm_hex_pair(){\n\tvar pair = Math.floor(Math.random() * 256).toString(16);\n\tif (pair.length < 2){\n\t pair = \"0\" + pair\n\t}\n\treturn pair;\n }",
"function base582hex(s){\r\n var res, bytes\r\n try { res = parseBase58Check(s); bytes = res[1]; }\r\n catch (err) { bytes = Bitcoin.Base58.decode(s); }\r\n return bytes2hex(bytes)\r\n}",
"static uint112(v) { return n(v, 112); }",
"function hash2sign(h, k){ return bytes2hex(bigInt2ECKey(hex2bigInt(k)).sign(hex2bytes(h))); }",
"function leftCircularShift(num,bits){\nnum = num.toString(2);\nnum = parseInt(num.substr(1,num.length-1)+num.substr(0,1),2);\nnum = parseInt(num,2);\nreturn num;\n}",
"static int112(v) { return n(v, -112); }",
"function _signDigest(d, hashAlg) {\n var EM = codificaEMSA(d, this.n.bitLength(), hashAlg);\n var m = parseBigInt(EM, 16);//converte EM in un intero non negativo\n var s = this.doPrivate(m);//applica la primitiva di firma usando la chiave privata\n var S = s.toString(16);//firma in esadecimale\n var signature=zeroPad(S, this.n.bitLength());//padding affinchè la lunghezza sia k\n return signature;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to return an array with all the indexes where toSearch appears in str. | function allIndexOf(str, toSearch) {
var indices = [];
for (var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {
indices.push(pos);
}
return indices;
} | [
"function findAllOccurances(arr, searchTerm, startIndex = 0) {\n let indexArray = [];\n for (let i = startIndex; i < arr.length; i++) {\n if (arr[i] == searchTerm) {\n indexArray.push(i)\n }\n }\n\n return indexArray;\n}",
"function getIndicesOf(str, keywords) {\n\tvar searchlength = keywords.length;\n\tif (searchlength == 0) return [];\n\tvar startIndex = 0, index, indices = [];\n\twhile ((index = str.indexOf(keywords, startIndex)) > -1) {\n\t\tindices.push(index);\n\t\tstartIndex = index + searchlength;\n\t}\n\treturn indices;\n}",
"function searchArray(input, array){\n //creates new RegExp\n //g = flag to make search global, i means ignore case\n let regex = new RegExp(input, 'gi');\n //filters by matching strings\n \n //match can only be used on strings\n let result = array.filter(current => current.match(regex));\n\n // stores index numbers of match\n let match = [];\n for(i = 0; i < result.length; i++){\n match.push(\n array.indexOf(\n result[i]));\n }\n \n //returns indexes of matches in array\n return match;\n}",
"function matchIndices(str, re) {\r\n var result, indices = [];\r\n while(result = re.exec(str)) {\r\n indices.push(result.index); // Match found, push its index in the array\r\n }\r\n return indices; // return matches indices\r\n}",
"function myIndexOf(string, searchTerm) {}",
"function findSubString(toSearch, toFind) {\n const sLen = toSearch.length;\n const fLen = toFind.length;\n\n for(let i = 0; i < sLen; i++) {\n if(toSearch[i] === toFind[0]) {\n if(toSearch.slice(i, i + fLen) === toFind) { return i; }\n }\n }\n return -1;\n}",
"function arraySubstring(words, str) {\n const result = [];\n for( let i = 0; i < words.length; i++) {\n if (words[i].includes(str)) {\n result.push(true);\n } else {\n result.push(false);\n }\n }\n return result;\n}",
"function linearSearch(searchObj, searchArr){\n\n for(let index = 0; index < searchArr.length; index++){\n if(searchArr[index] === searchObj){\n return index\n }\n }\n return undefined\n}",
"function cari(){\n\tvar isi = \"saya beajar di rumah teman\";\n\tconsole.log(isi.search(\"beajar\"));\n\tconsole.log(isi.search(/beajar/));\n}",
"function FindIntersection(strArr) {\n let intersection = [];\n\n strArr[0].split(\", \").forEach((char0) => {\n strArr[1].split(\", \").forEach((char1) => {\n if (char0 === char1) intersection.push(char1);\n });\n });\n\n if (intersection.length === 0) return false;\n else return intersection;\n}",
"function GetMatches(targetPattern, dnaString, maxMisMatches){\n\n\tvar targetKmerLength = targetPattern.length; //casting for correct behavior\n\t\n\t//get all Kmers\n\tvar loopLength = dnaString.length - targetKmerLength + 1;//do loop length calculatiion here as it is faster then recalculating for each loop itteration\n\tvar matchedIndexes = ''; \n\tfor (var i = 0; i < loopLength; i++) {\n\t\tvar upperBound = targetKmerLength+i;\n\t\tvar tempKmer = dnaString.substring(i,upperBound).toString();\n\t\tif(matchesWithInMargin(tempKmer, targetPattern, maxMisMatches))\n\t\t\t//console.log('match at index: '+ i +' ');\n\t\t\tmatchedIndexes += i +' ';\n\t};\n\t//console.log('Done');\n\treturn matchedIndexes;\n}",
"function getIndices(arr, el) {\n\tconst a = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] === el) {\n\t\t\ta.push(i)\n\t\t}\n\t}\n\treturn a;\n}",
"function searchLinear(array, target){\n\tfor(let i = 0;i<array.length;i++){\n\t\tif(target == array[i]){\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1\n}",
"function findWords(string, func) {\n // TODO: implement using a standard loop\n var words = splitToWords(string),\n matchedWords = [];\n\n for (var i = 0; i < words.length; i++) {\n var word = words[i];\n\n if (func(word)) {\n matchedWords.push(word);\n }\n }\n\n return matchedWords;\n}",
"function getSearchArray(original, originalu, query) {\n var destination = [];\n var destinationu = [];\n\n for (var i = 0; i < original.length; ++i) {\n var penalty = find(original[i].toLowerCase(), query);\n if (penalty > -1 && penalty < original[i].length / 3) {\n destination.push(original[i]);\n destinationu.push(originalu[i]);\n }\n }\n\n return [destination, destinationu];\n}",
"function linear_search(arr, target) {\n for (var i=0; i<arr.length; i++) {\n if (arr[i] == target)\n return \"Found\";\n }\n return \"Not Found\";\n}",
"function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}",
"function allIndexesOf(array, value){//create function named allIndexes that takes two arguments/parameters\n var indexes = [] ; //creating an empty array (brand new list)\n\n array.forEach(function(element, index){ //forEach example of a loop to go through the list\n if(element === value) {//conditionally element is the same as the value\n indexes.push(index);//add that to the blank indexes\n }\n });\n\n /**for (var i = 0; i < array.length; i++) { //for loop example to go through the list\n if (array[i] === value) { //conditionally if the element of the array is the same as the value parameter\n indexes.push(i); //add that index position to my empty array.\n }\n }\n */\n return indexes; //give me all of those positions in an array\n}",
"function text_search(q, ids, search_index){\n if (!search_index){\n console.log('Warning, no search index, searching manually');\n ids = ids.filter(id => id.match(q));\n } else {\n const results = search_index.query((query) => {\n const {LEADING, TRAILING} = lunr.Query.wildcard;\n q.split(/(\\s+)/).forEach(s => {\n if (s){\n query = query.term(s, {wildcard: LEADING|TRAILING});\n }\n });\n return query;\n });\n const valid_ids = {};\n results.forEach(r => valid_ids[r.ref] = 1);\n ids = ids.filter(id => valid_ids[id]);\n }\n return ids;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new offer to the user's wallet | function addItem(req, res, next) {
var userId = req.userId,
offerId = req.body.offerId; // the id in the postgres table
console.log(JSON.stringify(req.body));
db.query('SELECT offerId FROM wallet WHERE userId=$1 AND offerId=$2', [userId, offerId], true)
.then(function(offer) {
if (offer) {
return res.send(400, 'This offer is already in your wallet');
}
db.query('INSERT INTO wallet (userId, offerId) VALUES ($1, $2)', [userId, offerId], true)
.then(function () {
return res.send('ok');
})
.fail(function(err) {
return next(err);
});
})
.catch(next);
} | [
"async addOfferingToInvestmentMethod(req, res, next) {\n try {\n const {\n body,\n models: { Investments },\n } = req;\n var { offering, investment } = body;\n var inv = await Investments.findById(investment);\n if (!inv) {\n throw Error('Couldnt find this investment');\n }\n inv.offering = offering;\n if (!inv.completed.includes('Offering')) {\n inv.completed.push('Offering');\n }\n await inv.save();\n return successResponse(\n res,\n 'Offering detail added successfully',\n 200,\n inv\n );\n } catch (error) {\n return errorHandler(error, req, res, next);\n }\n }",
"function addNewOffer() {\n\n\tvar flag = '#addNewOffer';\n\t//apply selected class on current button\n\taddSelectedClassOnButton1(flag);\n\n\tif($('ul#mostVoucherCode li').length > 25) {\n\n\t\tbootbox.alert(__('Popular Voucher code list can have maximum 25 records, please delete one if you want to add more popular voucher code'));\n\n\t} else {\n\n\t\tif($(\"input#searchCodeTxt\").val()=='' || $(\"input#searchCodeTxt\").val()==undefined)\n\t\t\t{\n\t\t\t\t//console.log('ok');\n\t\t\t\tbootbox.alert(__('Please select an offer'));\n\n\t\t\t} else {\n\n\t\t\t\tvar offerName = $(\"input#searchCodeTxt\").val();\n\n\t\t\t\t$.ajax({\n\t \t\turl : HOST_PATH + \"admin/homepage/addoffercode/name/\" + offerName,\n\t \t\t\tmethod : \"post\",\n\t \t\t\tdataType : \"json\",\n\t \t\t\ttype : \"post\",\n\t \t\t\tsuccess : function(data) {\n\n\t \t\t\t\tif(data=='2' || data==2)\n\t \t\t\t\t\t{\n\t \t\t\t\t\t\tbootbox.alert(__('This offer does not exist'));\n\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\t$('ul#mostVoucherCode li#noRecord').remove();\n\t \t\t\t\t\t\tvar li = \"<li reltype='\" + data.type + \"' relpos='\" + data.position + \"' reloffer='\" + data.offerId + \"' id='\" + data.id + \"' >\" + offerName + \"</li>\";\n\t \t\t\t\t\t\t$('ul#mostVoucherCode').append(li);\n\n\t \t\t\t\t\t\t$('ul#mostVoucherCode li#'+ data.id).click(changeSelectedClass1);\n\n\t \t\t\t\t\t\t$(\"input#searchCodeTxt\").val('');\n\t \t\t\t\t\t}\n\n\t \t\t\t}\n\n\n\t\t\t\t});\n\t\t\t\t//code add offer in list here\n\t\t\t}\n\t}\n}",
"function addToInventory() {\n\tconnection.query('SELECT * FROM products', function(err,res) {\n\t\tif(err) throw err;\n\t\tconsole.log(res);\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\ttype: 'input',\n\t\t\t\tmessage: 'enter the Item Id you would like to add more to.',\n\t\t\t\tname: 'addInvId'\n\t\t\t}\n\t\t]).then(function(inquireResponse) {\n\t\t\t\n\t\t\tvar id = inquireResponse.addInvId;\n\t\t\tidValidCheck(id);\n\n\t\t});\n\n\t});\n\t\n}",
"function addBuyer() {\n\tvar lName = $('#lName').val();\n\tvar fName = $('#fName').val();\n\tvar addr = $('#addr').val();\n\tbuyers[buyersCounter][lName] = lName;\n\tbuyers[buyersCounter][fName] = fName;\n\tbuyers[buyersCounter][addr] = addr;\n\t$('#buyerList').prepend('<li class=\"arrow swipeDelete\"><a class=\"swipeDelete\" href=\"#customerInfo\">' + fName + ' ' + lName + '</a></li>');\n\tdeleteHandler()\n\tjQT.goBack();\n\tbuyersCounter++\n\treturn false;\n}",
"function create(req, res) {\n Offer\n .create(req.body)\n .then(offer => res.status(201).json(offer))\n .catch(err => {\n if (err.name === 'ValidationError') {\n res.status(422).json(err)\n } else {\n res.status(500).json(err)\n }\n })\n}",
"function addDelivery () {\n\tvar settings = [];\n\tsettings.from = lastFrom = (widget.preferenceForKey('store')) ? \n\t\twidget.preferenceForKey('store') : 'www.amazon.com';\n\n\teditingDelivery = new Delivery(settings);\n\tupdateEditForm(editingDelivery.from);\n\tfillEditForm(editingDelivery,true);\n\tswitchToView('back','edit');\n}",
"function addInventory() {\n\n\t//Lets manager identify which item to credit\n\tinquirer\n\t\t.prompt ({\n\t\t\tname: \"restock_product\",\n\t\t\ttype: \"input\",\n\t\t\tmessage: \"Type the Id of the product you want to re-stock:\"\n\t\t})\n\t\t//Initiates database credit process\n\t\t.then(function(answer) {\n\n\t\t\t//Queries database and increases quantity by +5\n\t\t\tconnection.query(\"UPDATE products SET quantity = quantity + 5 WHERE id =\"+answer.restock_product, function(err, res) {\n\t\t\tif (err) throw err;\n\n\t\t\t//Returns the updated inventory table\n\t\t\tallInventory();\n\t\t\t})\n\t\t}\n\t)\n}",
"function addNewVoter() {\n if (!$scope.voter.name || !$scope.voter.email) {\n notify.alert(\"Campo Obrigatório\");\n } else {\n var r = $resource('/app/voter');\n r.save($scope.voter, function (response) {\n notify.successOnSave();\n $scope.voters.push($scope.voter)\n $scope.voter = {};\n }, function (response) {\n $scope.voter = {};\n notify.danger(\"Esse email já está sendo usado.\");\n });\n }\n }",
"function createBlankOffer(data) {\n console.log(data);\n return $http.post('/api/v1/offers/', data)\n .then(generalCallbackSuccess)\n .catch(generalCallbackError);\n }",
"function addEntry() {\n inq.prompt({\n name: \"addChoice\",\n type: \"rawlist\",\n message: \"What would you like to add?\",\n choices: [\n \"employee\",\n \"role\",\n \"department\",\n \"return to start\"\n ]\n // switch cases to draw in questions, then answers are pushed to DB rather than array. INSERT command.\n }).then(answer => {\n console.log(\"You chose: \" + JSON.stringify(answer));\n switch (answer.addChoice) {\n case \"employee\":\n addEmployee();\n break;\n\n case \"role\":\n addRole();\n break;\n\n case \"department\":\n addDepartment();\n break;\n\n case \"return to start\":\n startPage();\n\n }\n });\n}",
"function createProduct(name, price) {\n // this.setState({ loading: true });\n const web3 = window.web3;\n // const networkId = web3.eth.net.getId();\n // const networkData = Marketplace.networks[networkId];\n\n\n const { account } = formData;\n console.log(\"account\", account);\n\n\n formData.marketplace.methods\n .createProduct(name, price)\n .send({ from: localStorage.getItem(\"account\") })\n .once(\"receipt\", (receipt) => {\n });\n\n }",
"createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }",
"function addExpense() {\n\tconsole.log('Adding expense');\n\tvar expense = {};\n\texpense.amount = document.querySelector('#amount').value;\n\texpense.date = new Date(document.querySelector('#date').value);\n\texpense.date = expense.date.toDateString();\n\tconsole.log(expense.date);\n\texpense.category = document.querySelector('#category').value;\n\texpense.notes = document.querySelector('#notes').value;\n\n\tif (user.expenses[expense.date]) {\n\t\tconsole.log('expenses exist');\n\t} else {\n\t\tconsole.log(\"expenses don't exist\");\n\t\tuser.expenses[expense.date] = [];\n\t}\n\n\tconsole.log(expense.date.length);\n\tuser.expenses[expense.date].push(expense);\n\tusers[currentUser] = user;\n\n\tlocalStorage.setItem('users', JSON.stringify(users));\n\tlocation.href = 'expenses.html';\n}",
"addExpense(expenseObj, expenseOut) {\r\n budgetParams['expenses'] += parseInt(expenseObj.amount); \r\n expenseOut.textContent = budgetParams['expenses'];\r\n }",
"function manageOffer(offer, action, them) {\n var counter = 0;\n var maxTries = 10;\n var retryInterval = 1000;\n var alreadyUpdating = false; //prevents offer.update spam\n\n var offerFunc = function() { //extra function to sort Everything\n if (counter < maxTries) { //dont retry forever\n if (offer.isGlitched() == true && !alreadyUpdating) { //if glitched\n alreadyUpdating = true; //prevents offer.update spam\n offer.update(function(err) {\n if (err) {\n alreadyUpdating = false; //prevents offer.update spam\n } else {\n accept(); //tries to accept\n }\n });\n } else {\n accept(); //tries to accept\n }\n } else {\n logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') cancelled. Accepting/Declining failed.'); //limit of retries reached\n clearInterval(interval); //stops the retry interval\n }\n };\n\n var accept = function() {\n if (offer.state == TradeOfferManager.ETradeOfferState.Active) { //if the trade is active -> acceptable|declineable\n if (action == 'accept') {\n offer.accept(function(err) {\n if (err) { //accepting failed\n logError('Accepting the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);\n counter++; //used for the limit of retries\n } else {\n logSuccess('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully accepted.');\n clearInterval(interval); //stops the retry interval because of success\n }\n });\n } else {\n offer.decline(function(err) {\n if (err) { //declining failed\n logError('Declining the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);\n counter++; //used for the limit of retries\n } else {\n logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully declined.');\n clearInterval(interval); //stops the retry interval because of success\n }\n });\n }\n } else {\n clearInterval(interval); //stops the retry interval because its not active anymore\n }\n };\n\n offerFunc(); //instantly runs the Function\n var interval = setInterval(offerFunc, retryInterval); // & runs it in an interval\n}",
"function addToInventory() {\n\t// Querying the Database\n\tconnection.query(\"SELECT * FROM products\", function (err, res) {\n\n\t\tif (err) throw err;\n \n // Setting up our results in the console.table NPM\n consoleTable(\"\\nCurrent Inventory Data\", res);\n \n\t\t// Inquirer asking Manager to select ID of the item they wish to add Inventory of\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\tname: \"id\",\n\t\t\t\tmessage: \"Input the item ID to increase inventory on.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0 && value <= res.length) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"amount\",\n\t\t\t\tmessage: \"Input the amount to increase inventory by.\",\n\t\t\t\tvalidate: function(value) {\n\t\t\t\t\tif (isNaN(value) === false && value > 0) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t]).then(function(answer) {\n\n\t\t\tvar itemQty;\n\n\t\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\t\tif (parseInt(answer.id) === res[i].item_id) {\n\t\t\t\t\titemQty = res[i].stock_quantity;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Call the function to Increase the Quantity with the Parameters needed\n\t\t\tincreaseQty(answer.id, itemQty, answer.amount);\n\t\t});\n\t});\n}",
"function addRole() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"What is the name of the new employee role?\",\n name: \"title\"\n },\n {\n type: \"input\",\n message: \"How much is the new salary of the employee's role?\",\n name: \"salary\"\n },\n {\n type: \"list\",\n message: \"In which department is the new role?\",\n name: \"id\",\n choices: showdepartments\n }\n ])\n .then(function (response) {\n \n addEmployeeRole(response);\n })\n }",
"function addExpense(){\n var Addexpen = document.getElementById(\"AddExpen\").value\n \n if(Addexpen > 0 ){\n\n setExpense( Addexpen)\n setExpenId( expenId + 1)\n\n }\n }",
"function addToFacebank(name) {\n\n\t// <Prevent browser caching>\n\tmax = 9999999999999999;\n\tmin = 1000000000000000;\n\tvar id = Math.floor(Math.random() * (max - min)) + min;\n\tvar url = \"../data/facebank/\" + name + \"Banked.jpg?id=\" + id;\n\t// </ Prevent Browser Caching>\n\n\t// Hard Code a bunch of descriptions in for the people found by the face\n\t// tracker.\n\tdescription = \"\";\n\tswitch (name) {\n\tcase \"Andrew\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Mark\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Paul\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Nick\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Meg\":\n\t\tdescription = \"MIT Design student and Mentor\"\n\t\tbreak;\n\tcase \"Federico\":\n\t\tdescription = \"Director of MIT Media Labs\"\n\t\tbreak;\n\tdefault:\n\t\tdescripion = \"New Challenger!\"\n\t}\n\tfaceBank[name] = createNotification(name, description, url);\n\tconsole.log(\"ADDED TO FACEBANK\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Ratings of this vssue according to the issue id | async getRatings() {
try {
if (!this.API || !this.issueR || this.isLoadingComments)
return;
this.isLoadingComments = true;
const ratings = await this.API.getRatings({
accessToken: this.accessToken,
issueId: this.issueR.id,
query: this.query,
});
this.ratings = ratings;
if (this.query.page !== ratings.page) {
this.query.page = ratings.page;
}
if (this.query.perPage !== ratings.perPage) {
this.query.perPage = ratings.perPage;
}
return ratings;
}
catch (e) {
if (e.response && [401, 403].includes(e.response.status) && !this.isLogined) {
this.isLoginRequired = true;
}
else {
this.$emit('error', e);
throw e;
}
}
finally {
this.isLoadingComments = false;
}
} | [
"function ratings_obj() {\n this.fi;\n this.vendor;\n this.audit_category;\n this.rating;\n this.date;\n }",
"get ids() {\n return issues.map(obj => obj.id);\n }",
"function getRatingByLearnerParnetId() {\n return db(\"ratings\").where(\"ratings.learnParentId\", id);\n}",
"async populateCrashRating(){\n let data = await nhtsa.getStars(this);\n /**\n * Overall Crashrating star count of vehicle.\n * @type {string}\n */\n this.CrashRaiting = data.data.Results[0].OverallRating;\n\n return data;\n }",
"get withPullRequest() {\n return issues.filter(obj => obj.pull_request !== undefined\n && obj.pull_request !== null)\n .map(obj => obj.id);\n }",
"function setRating(trouble) {\n var model = {\n numRate: trouble.rate\n };\n troubleshootFactory.setRating(trouble.id, model).then(function (resp) {\n trouble.rate = resp.data.rate;\n trouble.isRated = true;\n });\n }",
"async function getAllIssues() {\n var issues;\n\n await axios\n \n axios.get(\"http://singhealthdb.herokuapp.com/api/issue/audit_id_param\", {\n params: { secret_token: token, audit_id : audit_id },\n })\n .then(\n resarr=>{\n //alert(\"hello\");\n issues = Object.values(resarr.data);\n console.log(issues);\n //setIssues(issues);\n categoriseIssues(issues);\n setLoading(false);\n setAuditResolved(issues);\n }\n \n )\n .catch((error) => {\n setIssues([]);\n setLoading(false);\n console.log(error);\n });\n }",
"static async rateTrip(id, username, rating) {\n const result = await db.query(\n `UPDATE user_trips\n SET trip_rating = $1\n WHERE trip_id = $2\n AND username = $3\n RETURNING trip_id AS \"tripId\", \n username, \n trip_rating AS \"tripRating\"`,\n [rating, id, username]\n );\n return result.rows[0];\n }",
"get withAssignee() {\n return issues.filter(obj => obj.assignee !== null)\n .map(obj => obj.id);\n }",
"function averageStarRating(placeId) {\n return Details.getReviews(placeId).then(function(reviews) {\n var ratings = _(reviews)\n .pluck('rating')\n .filter(function(rating) { return rating > 0; });\n\n var sum = ratings.reduce(function(result, rating) { return result + rating; }, 0);\n var count = ratings.value().length;\n if (count > 0) {\n return sum / count;\n } else {\n return 0;\n }\n });\n }",
"function showRating(ratings) {\n let oneStars = +ratings.one \n let twoStars = +ratings.two *2\n let threeStars = +ratings.three*3\n let fourStars = +ratings.four*4\n let fiveStars = +ratings.five*5\n\n let totalRatings = +ratings.one + +ratings.two + +ratings.three + +ratings.four + +ratings.five\n\n let averageRating = ((oneStars + twoStars + threeStars + fourStars + fiveStars)/totalRatings)\n let averageRatingFormatted = averageRating.toFixed(2)\n return averageRatingFormatted\n}",
"getInterestIDsByType(userID) {\n const user = this._collection.findOne({ _id: userID });\n const interestIDs = [];\n interestIDs.push(user.interestIDs);\n let careerInterestIDs = [];\n _.map(user.careerGoalIDs, (goalID) => {\n const goal = CareerGoals.findDoc(goalID);\n careerInterestIDs = _.union(careerInterestIDs, goal.interestIDs);\n });\n careerInterestIDs = _.difference(careerInterestIDs, user.interestIDs);\n interestIDs.push(careerInterestIDs);\n return interestIDs;\n }",
"fetchByFruit(fruitId) {\n\t\t\treturn FruitRating.collection().query(qb => {\n\t\t\t\tqb.where('fruit_id', fruitId);\n\t\t\t\tqb.orderBy('created_at', 'desc');\n\t\t\t}).fetch({\n\t\t\t\twithRelated: [\n\t\t\t\t\t'user'\n\t\t\t\t]\n\t\t\t});\n\t\t}",
"async function getAvgRate(req, res) {\n const { id } = req.query;\n const post = await Post.findById(id);\n const AVG = post.rateAVG;\n res.send({ AVG });\n}",
"async getResearchPaperByID(id){\n return await fetch(RESEARCH_PAPER_API_BASE_URI+\"/paper/\"+id,{\n method:'GET',\n }).then(response =>{\n return response.json();\n }).catch(reason => {\n return reason;\n })\n\n }",
"getOtherUserReviews() {\n HttpRequestsService.getRequest(`other-user-reviews?usernameId=${this.otherUsernameId}&p=${this.page}`).then(result => {\n this.reviewCount = Math.ceil(result.data.reviewsTotal / 5);\n this.reviews = result.data.reviews;\n }).catch(err => {\n EventBus.$emit('toast', { type: \"error\", text: \"Oops something went wrong\" });\n })\n }",
"async getCommentReactions({ commentId, }) {\n try {\n if (!this.API || !this.issue)\n return;\n const reactions = await this.API.getCommentReactions({\n accessToken: this.accessToken,\n issueId: this.issue.id,\n commentId,\n });\n return reactions;\n }\n catch (e) {\n this.$emit('error', e);\n throw e;\n }\n }",
"function getIssuesByProjectId(id){\n var deferred = $q.defer();\n\n $http.get(BASE_URL + 'projects/' + id + '/issues')\n .then(function(response){\n deferred.resolve(response.data);\n });\n\n return deferred.promise;\n }",
"function getRanking(roomId) {\n return roomsRef.child(`${roomId}/ranking`).once('value');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a mapping from a resourceId to the filename of that resource | function createFileMap(resourceType, resourceMappingFile) {
const fileMap = {};
const fileKeys = Object.keys(resourceMappingFile);
fileKeys.forEach((key) => {
const rMap = Array.isArray(resourceMappingFile[key]) ? resourceMappingFile[key] : [resourceMappingFile[key]];
rMap.forEach((map) => {
if (map.hasOwnProperty('contentId')) {
fileMap[map.contentId] = map.fileName;
}
});
});
return fileMap;
} | [
"function ResourceKey(id, name) {\n this.id = id;\n this.name = name;\n }",
"function run_getFileNameIdMap() {\n var fileNameIdMap = getFileNameIdMap();\n Logger.log(fileNameIdMap);\n}",
"function mapImageResources(rootDir, subDir, type, resourceName) {\n var pathMap = {};\n shell.ls(path.join(rootDir, subDir, type + '-*'))\n .forEach(function (drawableFolder) {\n var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);\n pathMap[imagePath] = null;\n });\n return pathMap;\n}",
"function buildResourceMap(resourceDefinitions, start) {\n var map = {};\n if(resourceDefinitions) {\n for(var i = 0, len = resourceDefinitions.length; i < len; i++) {\n addResourceToMap(map, resourceDefinitions[i], start);\n }\n }\n\n return map;\n }",
"function getShipMapKeyFromFileName(filename)\r\n{\r\n return \"_\" + filename.match(/-(.*)Shipyard/)[1]\r\n}",
"function ResourceHash(urls) {\n this.id = 1;\n var letter = 'a';\n var self = this;\n urls.forEach(function(url) {\n self[letter] = url;\n letter = String.fromCharCode(letter.charCodeAt(0) + 1);\n });\n }",
"function createMap(id, object) {\n\t\t\tobj_to_id[0].unshift(object);\n\t\t\tobj_to_id[1].unshift(id);\n\t\t}",
"function mapResources(resourceOrCollection, mapFn) {\n if (resourceOrCollection instanceof _typesCollection2[\"default\"]) {\n return resourceOrCollection.resources.map(mapFn);\n } else {\n return mapFn(resourceOrCollection);\n }\n}",
"byIdOrName (resource_identifier) {\n let uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (resource_identifier.match(uuid_regex)) return 'id';\n return 'name';\n }",
"assignRootResource(state, {key, resource}) {\n state[key] = resource\n }",
"uploadResource (itemId, owner, file, filename, replace = false, portalOpts) {\n let action = this.addResource.bind(this);\n if (replace) {\n action = this.updateResource.bind(this);\n }\n return action(itemId, owner, filename, file, portalOpts);\n }",
"function getAlertFile(id) {\n return alertDir + '/' + id + '.json';\n}",
"addMapping(identityString, id) {\n // Ensure that id is not duplicated\n if (this.stringToIdMap.has(identityString) && this.stringToIdMap.get(identityString) != id) {\n var dupId = this.stringToIdMap.get(identityString);\n this.stringToIdMap.delete(identityString);\n throw new Error(Util.format(\"duplicate identity string in store as '%s' and '%s'\", id, dupId));\n }\n this.stringToIdMap.set(identityString, id);\n }",
"function getFileName(index, name) {\n return index.file[index.namemap.indexOf(name)];\n}",
"function find_next_autogen_key(resourceName,offset) {\n var nextId = 'id_'+(Object.keys(DATA[resourceName]).length + offset);\n if (DATA[resourceName][nextId]) {\n nextId = find_next_autogen_key(resourceName,offset + 1);\n }\n return nextId;\n }",
"_findResource(id) {\n return this.template.resources.find(res => {\n // Simple match on substring is possible after \n // fully resolving names & types\n return res.fqn.toLowerCase().includes(id.toLowerCase());\n });\n }",
"constructor() {\n this.stringToIdMap = new Map();\n }",
"get resourceMapper() {\n return this._resourceMapper;\n }",
"function migrateFile(sourceCode, mapping) {\n var e_1, _a;\n var legacyIds = Object.keys(mapping);\n try {\n for (var legacyIds_1 = tslib_1.__values(legacyIds), legacyIds_1_1 = legacyIds_1.next(); !legacyIds_1_1.done; legacyIds_1_1 = legacyIds_1.next()) {\n var legacyId = legacyIds_1_1.value;\n var cannonicalId = mapping[legacyId];\n var pattern = new RegExp(escapeRegExp(legacyId), 'g');\n sourceCode = sourceCode.replace(pattern, cannonicalId);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (legacyIds_1_1 && !legacyIds_1_1.done && (_a = legacyIds_1.return)) _a.call(legacyIds_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return sourceCode;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that calculates clicked candle from d3.mouse coordinates and returns candle index in dtArray | calculateClickedCandle(coord) {
return this.dataPointer - this.noCandles + Math.floor((coord[0] - this.xScale.step()*this.xScale.padding()/2)/this.xScale.step());
} | [
"function klik(evt) { // mousedown on svg\n function x2time(x, line) {\n\n function isBigEnough(element) {\n return element >= x;\n }\n\n // Get the sfaff measure number from an X-value;\n var measure = bars[line].xs.findIndex(isBigEnough) - 1;\n var measure_width = bars[line].xs[measure + 1] - bars[line].xs[measure];\n\n console.log(\"X: \" + x + \" , \" + \"measure: \" + measure + \" width: \" + measure_width);\n\n }\n\n evt.preventDefault();\n evt.stopPropagation();\n var line = msc_svgs.get().indexOf(this); // index of the clicked svg\n var x = evt.clientX; // position click relative to page\n x -= $(this).position().left; // minus (position left edge if svg relative to page)\n x2time(x, line);\n}",
"function coordinates(mousePosition){ \n if (mousePosition < cellSize){\n return 0;\n };\n let position = 1;\n while (mousePosition > cellSize*position){\n position+=1;\n };\n return position-1;\n}",
"function chartClickData () {\n var data = [];\n for (var i = 0; i < allProducts.length ; i++) {\n data.push(allProducts[i].timesClicked);\n }\n return data;\n}",
"function mousePressed() {\n covid20.x = mouseX;\n covid20.y = mouseY;\n}",
"getlines(){\n\n const {data,maxCandles=30}=this.props;\n\n if(data.length==0){\n return\n }\n\n const whole = [\n ...data.map( x => [ x[ TIMESTAMP ] , x[ HIGH ] ] ) ,\n ...data.map( x => [ x[ TIMESTAMP ] , x[ LOW] ] )\n ].slice(0,maxCandles);\n\n this.generateTicks( whole );\n\n const xvalues = whole.map( item => item[ TIMESTAMP ] );\n const yvalues = whole.map( item => item[1] );\n let barWidth=( xvalues[0]-xvalues[1])/5;\n const [ymin,ymax] = d3Array.extent(yvalues);//height min\n let [ start , end ] = d3Array.extent( xvalues );\n end=end+barWidth*5;\n\n const generateCandleBarEdges=(x)=>([\n [ x[ TIMESTAMP ] - barWidth , x[ OPEN ] ] ,\n [ x[ TIMESTAMP ] - barWidth , x[ CLOSE ] ] ,\n [ x[ TIMESTAMP ] + barWidth , x[ CLOSE ] ] ,\n [ x[ TIMESTAMP ] + barWidth , x[ OPEN ] ] ,\n ]);\n const generateCandleStickEdges=(x)=>([\n [ x[ TIMESTAMP ] , x[ LOW ] ],\n [ x[ TIMESTAMP ] , x[ HIGH ] ] ,\n ]);\n\n //manipulation of min max to diplay content at edges of graphs\n const yGap = (ymax-ymin)*2/this.height;\n let currentPrice=( (data[0][CLOSE]==ymax) ? ( data[0][CLOSE]-yGap) :( (data[0][CLOSE]==ymin) ? (data[0][CLOSE]+yGap) : data[0][CLOSE]) );\n const currentPriceEdges=[ [ start , currentPrice ] , [ end , currentPrice ] ];\n this.isFalling = data.slice(0,maxCandles).map( x =>( x[ OPEN ] < x[ CLOSE ]))\n\n const path=this.getPath( { xvalues,yvalues } )\n\n let openClose = data.slice(0,maxCandles).map( generateCandleBarEdges );\n let lowHighs = data.slice(0,maxCandles).map( generateCandleStickEdges );\n\n this.bars = openClose.map( lineData => ( path( lineData ) + ` Z`) ) ;\n this.sticks = lowHighs.map( lineData => ( path( lineData ) ) ) ;\n this.currentPriceAxis = path( currentPriceEdges );\n }",
"function getCurrentDateIndex() {\n const dateSelection = d3.select('#date-selection');\n return parseInt(dateSelection.property('value')) + 1;\n}",
"function getClickX(input) {\n return ((input.offsetX / getCanvas().width()) * viewWidth) + viewX;\n}",
"function findXY(event) {\n x = event.clientX;\n y = event.clientY;\n}",
"function generateCrosshair() {\n //returns corresponding value from the domain\n const correspondingDate = xScale.invert(d3.mouse(this)[0]);\n //gets insertion point\n const i = bisectDate(data, correspondingDate, 1);\n const d0 = data[i - 1];\n const d1 = data[i];\n const currentPoint =\n correspondingDate - d0['date'] > d1['date'] - correspondingDate ? d1 : d0;\n focus.attr(\n 'transform',\n `translate(${xScale(currentPoint['date'])}, ${yScale(\n currentPoint['close']\n )})`\n );\n\n focus\n .select('line.x')\n .attr('x1', 0)\n .attr('x2', -xScale(currentPoint['date']))\n .attr('y1', 0)\n .attr('y2', 0);\n\n focus\n .select('line.y')\n .attr('x1', 0)\n .attr('x2', 0)\n .attr('y1', 0)\n .attr('y2', height - yScale(currentPoint['close']));\n\n updateData(currentPoint);\n }",
"function clickOnPoint() {\n var x = 58,\n y = 275;\n _DygraphOps[\"default\"].dispatchMouseDown_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseMove_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseUp_Point(g, x, y);\n }",
"function mouseclicks()\n{\n //mouse makes yellow dot\n fill(255,255,0);\n circle(mousex, mousey, d);\n \n}",
"function clickloc (){\n var x;\n var y;\n\n // jQuery gets. jQuery gets what?\n $(document).click(function(loc) {\n x = loc.pageX;\n y = loc.pageY;\n logClicks(x,y);\n });\n}",
"function mousePressed() {\n if (mouseY < dSlider.y) { // if you clicked above the slider,\n trackColor = video.get(mouseX,mouseY); // get the color you clicked\n }\n}",
"function mousePressed() {\n birthday();\n mouseWasPressed += 1;\n}",
"function mouseDragged(){\ncircles.push(new Circle(mouseX, mouseY));\n}",
"function abs2index(x, y) {\n return pos2index(x - canvasX[ci], y - canvasY[ci], g_cal_params.grid_w, g_cal_params.cell_h);\n}",
"function mouseMoved(){\n if(selected !== null){\n selLine[0] = digraph.vertices[selected]['x'];\n selLine[1] = digraph.vertices[selected]['y'];\n selLine[2] = mouseX;\n selLine[3] = mouseY;\n }\n}",
"function onMouseDownEvent()\n{\n let clickedTime = calculateClickedTime();\n let minute = (30 * clock.indicators.m.angle) / (Math.PI + 15);\n let hour = (6 * clock.indicators.h.angle) / (Math.PI + 3);\n let threshold = 0.25;\n\n if((clickedTime[0] < minute + threshold) && (clickedTime[0] > minute - threshold))\n {\n clock.minuteTimeChanger.highlightIndicator('red'); // threshold makes it easier to click on hand \n return;\n } \n if((clickedTime[1] < hour + threshold) && (clickedTime[1] > hour - threshold)) \n clock.hourTimeChanger.highlightIndicator('red'); \n}",
"function mouseoverhandler(event) {\n mouseIn = event.target.id;\n //console.log(\"the mouse is over canvas:: \" + mouseIn);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
flip the current active block if possible | flipBlock(){
if(!this.started) return false;
if(this.active.flip(this.grid)) postMessage(this.state);
else console.log("couldn't flip");
} | [
"function restoreBlock() {\n if (blockStack.length > 0 && !currentBlock.isChildToggled()) {\n currentBlock.setIcon(true);\n currentBlock = blockStack.pop();\n currentBlock.setIcon(false);\n resizeCanvas(); // this redraws the screen\n return true;\n }\n return false;\n }",
"backFlip() {\n\t\tsuper.backFlip(KEN_SPRITE_POSITION.backFlip, KEN_IDLE_ANIMATION_TIME - 3, false, 2, MOVE_SPEED + 3);\n\t}",
"function flip() {\r\n if (stopFlip) return;\r\n //add the flip style to a clicked card\r\n this.classList.add(\"flip\");\r\n moveCount();\r\n pickedCards.push(this);\r\n // card 1 selected\r\n if (cardSelected === false) {\r\n cardSelected = true;\r\n cardOne = this;\r\n return;\r\n //card 2 selected\r\n } else {\r\n cardSelected = false;\r\n cardTwo = this;\r\n match();\r\n }\r\n}",
"shiftUp() {\n const blocks = this.getNavigableBlocks();\n const selectedBlocks = blocks.filterBy('isSelected');\n const idx = blocks.indexOf(selectedBlocks.get('firstObject'));\n const prevBlock = blocks.objectAt(idx - 1);\n\n if (!prevBlock) return;\n\n selectedBlocks.get('lastObject').set('isSelected', false);\n prevBlock.set('isSelected', true);\n }",
"frontFlip() {\n\t\tsuper.frontFlip(KEN_SPRITE_POSITION.frontFlip, KEN_IDLE_ANIMATION_TIME - 3, false, 2, MOVE_SPEED + 3);\n\t}",
"moveCurrentBlockLeft(){\n this.blocks.currentBlock.x--;\n\n if(this.checkCollision(this.blocks.currentBlock)){\n this.blocks.currentBlock.x++;\n }\n\n this.updateGhostBlock();\n }",
"function flip (){\n\tif (showing.length){\n\t\treturn;\n\t}\n\tfor (let i = 0; i < cards.length; i++){\n\t\tcards[i].classList.remove('open', 'show');\n\t}\n}",
"function flipCell() {\n // Run flip from style.css for the clicked cell (this)\n this.classList.toggle('flip');\n\n flippedCell = this;\n cellColor = flippedCell.dataset.color;\n outcome(cellColor);\n}",
"function lastBlockWorldsSwap(e, target1, target2, content1, content2){\n e.preventDefault();\n target1.classList.remove('active_world');\n target2.classList.add('active_world');\n content1.classList.remove('visible'); \n content2.classList.add('visible');\n}",
"moveCurrentBlockDown(){\n this.blocks.currentBlock.y++;\n\n if(this.checkCollision(this.blocks.currentBlock)){\n this.blocks.currentBlock.y--;\n\n this.saveBlock();\n this.checkLines();\n this.newBlockFromBag();\n\n return false;\n }\n\n return true;\n }",
"moveCurrentBlockRight(){\n this.blocks.currentBlock.x++;\n\n if(this.checkCollision(this.blocks.currentBlock)){\n this.blocks.currentBlock.x--;\n }\n\n this.updateGhostBlock();\n }",
"function flipX() {\n\t/// TODO:\n}",
"function flipTile(data, currTile){\n\t// if two cards are currently flipped, do nothing\n\tif(twoFlipped === true){\n\t\treturn;\n\t}\n\t// if no tiles are active and face down, flip tile, \n\telse if(prevTile === undefined){\n\t\tprevTile = currTile;\n\t\tprevNum = data;\n\t\tprevTile.data('isFlipped', true);\n\t\tprevTile.attr(\"class\", \"tileUp\");\n\t\tprevTile.html(\"<span>\" +data+ \"</span>\");\n\t}\n\t// if card clicked is already flipped, do nothing\n\telse if(currTile.data('isFlipped') == true){\n\t\treturn;\n\t}\n\t// one card is active and tile clicked is face down,\n\telse {\n\t\t// flip tile and change properties\n\t\tcurrTile.attr(\"class\", \"tileUp\");\n\t\tcurrTile.html(\"<span>\" +data+ \"</span>\");\n\t\ttwoFlipped = true;\n\t\tcurrTile.data('isFlipped', true);\n\t\t// if the two tiles match, deactivate both cards and leave face up\n\t\tif(prevNum === data){\n\t\t\tprevTile = undefined;\n\t\t\tprevNum = 0;\n\t\t\tpairs++;\n\t\t\tguess++;\n\t\t\ttwoFlipped = false;\n\t\t\t// if game is over, alert guesses and start new game\n\t\t\tif(pairs === difficulty*difficulty / 2){\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\talert(guess+\" guesses were made.\");\n\t\t\t\t\tinitGame();\n\t\t\t\t\tguess = 0;\n\t\t\t\t\tpairs = 0;\n\t\t\t\t}, 500);\n\t\t\t}\n\t\t// if the two tiles do not match, flip both tiles down\n\t\t}else{\n\t\t\t// timeout to see cards before flipping down\n\t\t\tsetTimeout(function(){\n\t\t\t\tprevTile.attr(\"class\", \"tileDown\");\n\t\t\t\tcurrTile.attr(\"class\", \"tileDown\");\n\t\t\t\tprevTile.data('isFlipped', false);\n\t\t\t\tcurrTile.data('isFlipped', false);\n\t\t\t\tprevTile = undefined;\n\t\t\t\tprevNum = 0;\n\t\t\t\t\n\t\t\t\tguess++;\n\t\t\t\ttwoFlipped = false;\n\t\t\t}, 750);\n\t\t}\n\t}\n}",
"function doFlipToBack()\n{\n var front = document.getElementById(\"front\");\n var back = document.getElementById(\"back\");\n\n if (back.style.display == \"block\")\n {\n return;\n }\n\t\n if(window.widget)\n {\n widget.prepareForTransition(\"ToBack\");\n }\n\n front.style.display=\"none\";\n back.style.display=\"block\";\n\n if(window.widget)\n {\n setTimeout(\"widget.performTransition();\", 0);\n }\n}",
"standingBlock() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.standingBlock, KEN_IDLE_ANIMATION_TIME, false);\n\t}",
"function flip(fn){\n return function(a, b){\n return fn(b,a);\n }\n }",
"selectDown() {\n const blocks = this.getNavigableBlocks();\n const selectedBlocks = blocks.filterBy('isSelected');\n\n if (this.get('isReversed')) {\n if (selectedBlocks.get('length') === 1) {\n const idx = blocks.indexOf(selectedBlocks.get('firstObject'));\n const nextBlock = blocks.objectAt(idx + 1);\n if (!nextBlock) return;\n nextBlock.set('isSelected', true);\n this.set('isReversed', false);\n } else {\n selectedBlocks.get('firstObject').set('isSelected', false);\n }\n } else {\n const idx = blocks.indexOf(selectedBlocks.get('lastObject'));\n const nextBlock = blocks.objectAt(idx + 1);\n if (!nextBlock) return;\n nextBlock.set('isSelected', true);\n }\n }",
"goToNextBlock () {\n const nextBlockId = this.target.blocks.getNextBlock(this.peekStack());\n this.reuseStackForNextBlock(nextBlockId);\n }",
"flipRTL() {\n // Mirror the block's path.\n this.svgPath.setAttribute('transform', 'scale(-1 1)');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide function constructor and request as arguments. It will throw an exception if the constructor is not valid. | validateTransformerConstructor(constructor, request) {
!validators_1.isFunction(constructor) &&
errorHandling_1.throwExpection(`Transformer does not exist "${request.url}"`);
} | [
"function GenericRequest() {}",
"makeTransformerInstance(constructor, request) {\n return validators_1.isFunction(constructor.make) ?\n constructor.make(request) :\n new constructor(request);\n }",
"function myNew(constructor, ...args) {\n // skip this part...\n // it explains how 'new' is written in ES5\n}",
"function buildStepFunctionRequest(arn, request, name) {\n const stateMachineArn = `arn:aws:states:${arn.region}:${arn.account}:function:${arn.appName}-${arn.fn}`;\n let input;\n if (request.headers) {\n request.headers[\"X-Correlation-Id\"] = state_1.getCorrelationId();\n request.headers[\"x-calling-function\"] = state_1.getContext().functionName;\n request.headers[\"x-calling-request-id\"] = state_1.getContext().requestId;\n input = JSON.stringify(request);\n }\n else {\n input = JSON.stringify(Object.assign(Object.assign({}, request), {\n headers: {\n \"X-Correlation-Id\": state_1.getCorrelationId(),\n \"x-calling-function\": state_1.getContext().functionName,\n \"x-calling-request-id\": state_1.getContext().requestId\n }\n }));\n }\n // if(!name) {\n // name =\n // }\n return {\n stateMachineArn,\n input,\n name\n };\n}",
"enterConstructorInvocation(ctx) {\n\t}",
"function objetoAjax(metodo) { \r\n/*Primero necesitamos un objeto XMLHttpRequest que cogeremos del \r\nconstructor para que sea compatible con la mayoría de navegadores \r\nposible. */ \r\nthis.objetoRequest = new ConstructorXMLHttpRequest(); \r\nthis.metodo = metodo; \r\n}",
"function Input() {\n throw new Error('Input should not be instantiated!');\n}",
"customRequest (data) {\n return http(data)\n }",
"enterExplicitConstructorInvocation(ctx) {\n\t}",
"function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }",
"enterConstructorDelegationCall(ctx) {\n\t}",
"function createRequestListener(path) {\n\treturn function(request, response) {\n\t\tvar httpRequest;\n\t\t\n\t\t// Create the right request for the HTTP method. Works similar\n\t\t// to Factory Pattern.\n\t\tswitch (request.method) {\n\t\tcase 'HEAD':\n\t\t\twinston.info('Process HEAD request with url: ' + request.url);\n\t\t\thttpRequest = new HeadRequest(request, response, path);\n\t\t\tbreak;\n\t\tcase 'GET':\n\t\t\twinston.info('Process GET request with url: ' + request.url);\n\t\t\thttpRequest = new GetRequest(request, response, path);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\twinston.info('Not implemented request: ' + request.method);\n\t\t\thttpRequest = new InvalidRequest(response, 501);\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t// Process request.\n\t\ttry {\n\t\t\thttpRequest.process();\n\t\t} catch (err) {\n\t\t\twinston.error(\"Server exception: \" + err);\n\t\t\tnew InvalidRequest(response, 500).process();\n\t\t}\n\t};\n}",
"function RestRequest(params) {\n\tthis.connections = params.connections;\n\tthis.connection = params.connection;\n\tthis.collection = params.collection;\n\tthis.options = params.options;\n\tthis.defaults = params.defaults;\n\tthis.cb = params.cb;\n}",
"enterConstructorBody(ctx) {\n\t}",
"function Playjax(router){\n\n function using( pathFn ){\n const route = pathFn(router.controllers);\n return {\n /**\n * Return the request object\n * @param body optional body of request\n */\n request: function( body ) { return routeToRequest(route, body);},\n /**\n * Fetches the request\n * @param body optional request payload\n */\n fetch: function( body ) { return fetchRequest(route, body); }\n };\n }\n\n function routeToRequest(route, body) {\n const properties = {\n method: route.method,\n redirect: \"follow\",\n credentials: \"same-origin\",\n headers: new Headers()\n };\n\n if ( Playjax_csrfTokenValue ) {\n properties.headers.append(\"Csrf-Token\", Playjax_csrfTokenValue);\n }\n if ( body ) {\n switch (typeof body) {\n case \"string\":\n properties.body = body;\n properties.headers.append(\"Content-Type\", \"text/plain\");\n break;\n case \"object\":\n case \"number\":\n case \"boolean\":\n properties.body = JSON.stringify(body);\n properties.headers.append(\"Content-Type\", \"application/json\");\n break;\n case \"function\":\n throw \"Cannot send function object over HTTP yet\";\n\n }\n }\n\n return new Request(route.url, properties);\n }\n\n function fetchRequest(route, body){\n return fetch(routeToRequest(route, body));\n }\n\n return {\n request:routeToRequest,\n fetch:fetchRequest,\n using:using\n };\n\n}",
"create(req, res) {\n Request.create(req.body)\n .then((request) => res.json(request))\n .catch((err) => res.status(400).json(err));\n }",
"enterPrimaryConstructor(ctx) {\n\t}",
"function tryCatch(fn,obj,arg){try{return{type:\"normal\",arg:fn.call(obj,arg)};}catch(err){return{type:\"throw\",arg:err};}}",
"function Function() {\n this.id = \"\";\n this.lang = \"\";\n this.returnType = \"\";\n this.code = \"\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SRP0[] Set Reference Point 0 0x10 | function SRP0(state) {
state.rp0 = state.stack.pop();
if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); }
} | [
"constructor(sourceVoltage, connections) {\r\n //voltage point to copy, array of voltage points to copy it to\r\n this.sourceVoltage = sourceVoltage;\r\n this.connections = connections;\r\n }",
"setFreeSpinsReelsData ( freeSpinReelsData = {}){\n this.getService(\"LinesService\").updateHistory();\n\n this.memory.set(this.getName(\"freespins_ReelsData\"), freeSpinReelsData);\n }",
"access(n, addr) {\n this.sets[addr.idx][n].access = 0;\n }",
"resetPath() {\n this.path = new Array();\n this.path_idx = -1;\n }",
"init() {\n let default_input = new Array(8);\n default_input.fill(0);\n\n // Map data to all slave devices using the specific address\n for (var device_name in this.devices) {\n\n // Get the device\n var device = this.devices[device_name];\n\n this.updateDevice(device, default_input);\n\n }\n\n }",
"[createFunctionName('set', collection, false)](object) {\n return setObjectToArray(object, self[collection], findField)\n }",
"function srLatch () {\n return {\n id: nextId(),\n type: 'srLatch',\n inputs: Object.seal([\n pin(),\n pin(),\n pin()\n ]),\n outputs: Object.seal([\n pin(),\n pin()\n ])\n }\n}",
"function SetColors(stationId,startIndex,colorArray){\n //update server's copy of the LED custer state\n colors[stationId][ledIndex].r = ledColor.r;\n colors[stationId][ledIndex].g = ledColor.g;\n colors[stationId][ledIndex].b = ledColor.b;\n\n var dataBuffer = new Uint8Array([ledIndex,numToFill,ledColor.r,ledColor.g,ledColor.b]);\n io.sockets.to(stationId).emit('setColors',dataBuffer);\n}",
"setSpinsReelsData (spinsReelsData = {}){\n this.getService(\"LinesService\").updateHistory();\n\n this.memory.set(this.getName(\"spins_ReelsData\"), spinsReelsData);\n }",
"setSPQRTree(tree){\n this.spqrTree = tree;\n this.spqrTree.getUtilities().processinOfAnSPQRTreeFromAnUnrootedTreeToARootedTree(this.spqrTree);\n }",
"function assignCrystalValues () {\n\n for (var i = 0; i < 4; i++) {\n var rndmCrystalValues = Math.floor((Math.random() * 12) + 1);\n rndmCrystalArray.push(rndmCrystalValues);\n \n }\n \n crystalOne.push(rndmCrystalArray[0]);\n crystalTwo.push(rndmCrystalArray[1]);\n crystalThree.push(rndmCrystalArray[2]);\n crystalFour.push(rndmCrystalArray[3]);\n \n crystalOne = parseInt(crystalOne);\n crystalTwo = parseInt(crystalTwo);\n crystalThree = parseInt(crystalThree);\n crystalFour = parseInt(crystalFour);\n \n }",
"rectifySignalReferencesByName(){\r\n this.plottedSignalsMap.forEach((ps, sigName) => {\r\n var newSig = this.signalFromNameCallback(sigName);\r\n if(newSig != null){\r\n ps.signal = newSig;\r\n }\r\n });\r\n }",
"loadZero()\n\t{\n\t\tvar TcI,TcJ;\n\t\tfor (TcI = 0; TcI < 4; TcI++)\n\t\t{\n\t\t\tfor (TcJ = 0; TcJ < 4; TcJ++)\n\t\t\t{\n\t\t\t\tthis._data[TcI][TcJ] = 0;\n\t\t\t}\n\t\t}\n\t}",
"ldReg(registerTo, registerFrom) {\n registerTo[0] = registerFrom[0];\n return 4;\n }",
"setReSpinsReelsData(reSpinsReelsData = {}){\n this.getService(\"LinesService\").updateHistory();\n\n this.memory.set(this.getName(\"respins_ReelsData\"), reSpinsReelsData);\n }",
"fromArray(array) {\n const isMultidimensional = (0, _TypeCheck.isArray)(array) && array[0].length > 0;\n const channels = isMultidimensional ? array.length : 1;\n const len = isMultidimensional ? array[0].length : array.length;\n const context = (0, _Global.getContext)();\n const buffer = context.createBuffer(channels, len, context.sampleRate);\n const multiChannelArray = !isMultidimensional && channels === 1 ? [array] : array;\n\n for (let c = 0; c < channels; c++) {\n buffer.copyToChannel(multiChannelArray[c], c);\n }\n\n this._buffer = buffer;\n return this;\n }",
"function updateReceivers(sample) {\n for(var cRadio = 0;\n cRadio < sample[$scope.transmitterId].radioDecodings.length;\n cRadio++) {\n var receiverTemp = sample[$scope.transmitterId].radioDecodings[cRadio].identifier.value;\n if(!(receiverTemp in $scope.receivers)) {\n var colorTemp = COLORS_ARRAY[cCOlOR_TRANSMITTER++ % COLORS_ARRAY.length];\n $scope.receivers[receiverTemp] = { color: colorTemp, isDrawn: false, isDisplayed: true, latest: 0, receiverId: receiverTemp };\n }\n }\n }",
"function fSetcode(obj, sc) {\n\n var val = obj.setcode,\n hexA = val.toString(16),\n hexB = sc.toString(16);\n if (val === sc || parseInt(hexA.substr(hexA.length - 4), 16) === parseInt(hexB, 16) || parseInt(hexA.substr(hexA.length - 2), 16) === parseInt(hexB, 16) || (val >> 16).toString(16) === hexB) {\n return true;\n } else {\n return false;\n }\n }",
"function InitSq120ToSq64 ()\n{\n\t//Filling array 120 w/ placeholder values\n\tfor (let i = 0; i < BRD_SQ_NUM; i++)\n\t{\n\t\tSq120ToSq64[i] = SQUARES.OFFBOARD;\n\t}\n\t//Filling array 64 w/ placeholder values\n\tfor (let i = 0; i < 64; i++)\n\t{\n\t\tSq120ToSq64[i] = SQUARES.OFFBOARD;\n\t}\n\t\n\tlet sq64 = 0;\n\t//Filling them with their actual values\n\tfor (let rank = RANKS.RANK_1; rank < RANKS.RANK_NONE; rank++)\n\t{\n\t\tfor (let file = FILES.FILE_A; file < FILES.FILE_NONE; file++)\n\t\t{\n\t\t\tlet sq = FR2SQ(file, rank);\n\t\t\t\n\t\t\tSq64ToSq120[sq64] = sq;\n\t\t\tSq120ToSq64[sq] = sq64;\n\t\t\tsq64++;\n\t\t}\n\t}\n}",
"function PushPrimitiveReference(value) {\n return [PushPrimitive(value), op(31\n /* PrimitiveReference */\n )];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check or Uncheck All Client CheckBox | function selectAllClientMenuCheckBox(){
if(document.getElementById('clientMenuSelectAllId').checked==true){
document.getElementById('clientMenuAddId').checked=true;
document.getElementById('clientMenuViewId').checked=true;
document.getElementById('clientMenuUpdateId').checked=true;
document.getElementById('clientMenuDeleteId').checked=true;
}else{
document.getElementById('clientMenuAddId').checked=false;
document.getElementById('clientMenuViewId').checked=false;
document.getElementById('clientMenuUpdateId').checked=false;
document.getElementById('clientMenuDeleteId').checked=false;
}
} | [
"function selectAllCoutryMenuCheckBox(){ \n\tif(document.getElementById('countryMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('countryMenuAddId').checked=true;\n\t\tdocument.getElementById('countryMenuViewId').checked=true;\n\t\tdocument.getElementById('countryMenuUpdateId').checked=true;\n\t\tdocument.getElementById('countryMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('countryMenuAddId').checked=false;\n\t\tdocument.getElementById('countryMenuViewId').checked=false;\n\t\tdocument.getElementById('countryMenuUpdateId').checked=false;\n\t\tdocument.getElementById('countryMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllCustomerMenuCheckBox(){ \n\tif(document.getElementById('customerMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('customerMenuAddId').checked=true;\n\t\tdocument.getElementById('customerMenuViewId').checked=true;\n\t\tdocument.getElementById('customerMenuUpdateId').checked=true;\n\t\tdocument.getElementById('customerMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('customerMenuAddId').checked=false;\n\t\tdocument.getElementById('customerMenuViewId').checked=false;\n\t\tdocument.getElementById('customerMenuUpdateId').checked=false;\n\t\tdocument.getElementById('customerMenuDeleteId').checked=false;\n\t}\n}",
"function uncheckAll(name) {\r\n\tsetCheckboxState(name, false);\r\n}",
"function selectAllEmpStatusMenuCheckBox(){ \n\tif(document.getElementById('empStatusMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('empStatusMenuAddId').checked=true;\n\t\tdocument.getElementById('empStatusMenuViewId').checked=true;\n\t\tdocument.getElementById('empStatusMenuUpdateId').checked=true;\n\t\tdocument.getElementById('empStatusMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('empStatusMenuAddId').checked=false;\n\t\tdocument.getElementById('empStatusMenuViewId').checked=false;\n\t\tdocument.getElementById('empStatusMenuUpdateId').checked=false;\n\t\tdocument.getElementById('empStatusMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllHolidayMenuCheckBox(){ \n\tif(document.getElementById('holidayMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('holidayMenuAddId').checked=true;\n\t\tdocument.getElementById('holidayMenuViewId').checked=true;\n\t\tdocument.getElementById('holidayMenuUpdateId').checked=true;\n\t\tdocument.getElementById('holidayMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('holidayMenuAddId').checked=false;\n\t\tdocument.getElementById('holidayMenuViewId').checked=false;\n\t\tdocument.getElementById('holidayMenuUpdateId').checked=false;\n\t\tdocument.getElementById('holidayMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllTeamMenuCheckBox(){ \n\tif(document.getElementById('teamMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('teamMenuAddId').checked=true;\n\t\tdocument.getElementById('teamMenuViewId').checked=true;\n\t\tdocument.getElementById('teamMenuUpdateId').checked=true;\n\t\tdocument.getElementById('teamMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('teamMenuAddId').checked=false;\n\t\tdocument.getElementById('teamMenuViewId').checked=false;\n\t\tdocument.getElementById('teamMenuUpdateId').checked=false;\n\t\tdocument.getElementById('teamMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllNationalityMenuCheckBox(){ \n\tif(document.getElementById('nationalityMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('nationalityMenuAddId').checked=true;\n\t\tdocument.getElementById('nationalityMenuViewId').checked=true;\n\t\tdocument.getElementById('nationalityMenuUpdateId').checked=true;\n\t\tdocument.getElementById('nationalityMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('nationalityMenuAddId').checked=false;\n\t\tdocument.getElementById('nationalityMenuViewId').checked=false;\n\t\tdocument.getElementById('nationalityMenuUpdateId').checked=false;\n\t\tdocument.getElementById('nationalityMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllTaxAndDeductionMenuCheckBox(){ \n\tif(document.getElementById('taxAndDeductionMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('taxAndDeductionMenuAddId').checked=true;\n\t\tdocument.getElementById('taxAndDeductionMenuViewId').checked=true;\n\t\tdocument.getElementById('taxAndDeductionMenuUpdateId').checked=true;\n\t\tdocument.getElementById('taxAndDeductionMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('taxAndDeductionMenuAddId').checked=false;\n\t\tdocument.getElementById('taxAndDeductionMenuViewId').checked=false;\n\t\tdocument.getElementById('taxAndDeductionMenuUpdateId').checked=false;\n\t\tdocument.getElementById('taxAndDeductionMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllCurrencyMenuCheckBox(){ \n\tif(document.getElementById('currencyMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('currencyMenuAddId').checked=true;\n\t\tdocument.getElementById('currencyMenuViewId').checked=true;\n\t\tdocument.getElementById('currencyMenuUpdateId').checked=true;\n\t\tdocument.getElementById('currencyMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('currencyMenuAddId').checked=false;\n\t\tdocument.getElementById('currencyMenuViewId').checked=false;\n\t\tdocument.getElementById('currencyMenuUpdateId').checked=false;\n\t\tdocument.getElementById('currencyMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllLeaveapproverMenuCheckBox(){ \n\tif(document.getElementById('leaveapproverMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('leaveapproverMenuAddId').checked=true;\n\t\tdocument.getElementById('leaveapproverMenuViewId').checked=true;\n\t\tdocument.getElementById('leaveapproverMenuUpdateId').checked=true;\n\t\tdocument.getElementById('leaveapproverMenuDeleteId').checked=true;\n\t\t\n\t}else{\n\t\tdocument.getElementById('leaveapproverMenuAddId').checked=false;\n\t\tdocument.getElementById('leaveapproverMenuViewId').checked=false;\n\t\tdocument.getElementById('leaveapproverMenuUpdateId').checked=false;\n\t\tdocument.getElementById('leaveapproverMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllEmployeeMenuCheckBox(){ \n\tif(document.getElementById('employeeMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('employeeMenuAddId').checked=true;\n\t\tdocument.getElementById('employeeMenuViewId').checked=true;\n\t\tdocument.getElementById('employeeMenuUpdateId').checked=true;\n\t\tdocument.getElementById('employeeMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('employeeMenuAddId').checked=false;\n\t\tdocument.getElementById('employeeMenuViewId').checked=false;\n\t\tdocument.getElementById('employeeMenuUpdateId').checked=false;\n\t\tdocument.getElementById('employeeMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllProjActivityMenuCheckBox(){ \n\tif(document.getElementById('projActivityMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('projActivityMenuAddId').checked=true;\n\t\tdocument.getElementById('projActivityMenuViewId').checked=true;\n\t\tdocument.getElementById('projActivityMenuUpdateId').checked=true;\n\t\tdocument.getElementById('projActivityMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('projActivityMenuAddId').checked=false;\n\t\tdocument.getElementById('projActivityMenuViewId').checked=false;\n\t\tdocument.getElementById('projActivityMenuUpdateId').checked=false;\n\t\tdocument.getElementById('projActivityMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllLocationMenuCheckBox(){ \n\tif(document.getElementById('locationMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('locationMenuAddId').checked=true;\n\t\tdocument.getElementById('locationMenuViewId').checked=true;\n\t\tdocument.getElementById('locationMenuUpdateId').checked=true;\n\t\tdocument.getElementById('locationMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('locationMenuAddId').checked=false;\n\t\tdocument.getElementById('locationMenuViewId').checked=false;\n\t\tdocument.getElementById('locationMenuUpdateId').checked=false;\n\t\tdocument.getElementById('locationMenuDeleteId').checked=false;\n\t}\n}",
"slaveCheckboxChanged() {\n const allCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']\"\n ).length;\n const checkedCheckboxesLength = document.querySelectorAll(\n \"input[name='employee']:checked\"\n ).length;\n\n let masterCheckbox = document.querySelector(\"input[name='all']\");\n masterCheckbox.checked = allCheckboxesLength === checkedCheckboxesLength;\n\n // make button visible if any checkbox is checked\n this.setState({\n masterCheckboxVisibility: Boolean(checkedCheckboxesLength),\n });\n }",
"function updateCheckCount() {\n var checkedCount = $(\"#itemsList input[type=checkbox]:checked\").length;\n var checkBoxCount = $(\"#itemsList input[type=checkbox]\").length;\n var selectBtn = $(\"#selectItemBtn\");\n\n if (checkedCount == checkBoxCount && checkBoxCount != 0) {\n selectBtn.val(\"Deselect all\");\n }\n else if (checkedCount != checkBoxCount || checkBoxCount == 0) {\n selectBtn.val(\"Select all\");\n }\n\n selectBtn.prop(\"disabled\", checkBoxCount == 0);\n}",
"function selectAllDepartmentMenuCheckBox(){ \n\tif(document.getElementById('departmentMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('departmentMenuAddId').checked=true;\n\t\tdocument.getElementById('departmentMenuViewId').checked=true;\n\t\tdocument.getElementById('departmentMenuUpdateId').checked=true;\n\t\tdocument.getElementById('departmentMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('departmentMenuAddId').checked=false;\n\t\tdocument.getElementById('departmentMenuViewId').checked=false;\n\t\tdocument.getElementById('departmentMenuUpdateId').checked=false;\n\t\tdocument.getElementById('departmentMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllProjectMenuCheckBox(){ \n\tif(document.getElementById('projectMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('projectMenuAddId').checked=true;\n\t\tdocument.getElementById('projectMenuViewId').checked=true;\n\t\tdocument.getElementById('projectMenuUpdateId').checked=true;\n\t\tdocument.getElementById('projectMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('projectMenuAddId').checked=false;\n\t\tdocument.getElementById('projectMenuViewId').checked=false;\n\t\tdocument.getElementById('projectMenuUpdateId').checked=false;\n\t\tdocument.getElementById('projectMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllLeaveTypeMenuCheckBox(){ \n\tif(document.getElementById('leaveTypeMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('leaveTypeMenuAddId').checked=true;\n\t\tdocument.getElementById('leaveTypeMenuViewId').checked=true;\n\t\tdocument.getElementById('leaveTypeMenuUpdateId').checked=true;\n\t\tdocument.getElementById('leaveTypeMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('leaveTypeMenuAddId').checked=false;\n\t\tdocument.getElementById('leaveTypeMenuViewId').checked=false;\n\t\tdocument.getElementById('leaveTypeMenuUpdateId').checked=false;\n\t\tdocument.getElementById('leaveTypeMenuDeleteId').checked=false;\n\t}\n}",
"function selectAllRegionMenuCheckBox(){ \n\tif(document.getElementById('regionMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('regionMenuAddId').checked=true;\n\t\tdocument.getElementById('regionMenuViewId').checked=true;\n\t\tdocument.getElementById('regionMenuUpdateId').checked=true;\n\t\tdocument.getElementById('regionMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('regionMenuAddId').checked=false;\n\t\tdocument.getElementById('regionMenuViewId').checked=false;\n\t\tdocument.getElementById('regionMenuUpdateId').checked=false;\n\t\tdocument.getElementById('regionMenuDeleteId').checked=false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if it's a NodeJS output filesystem or if it's a foreign/virtual one. The internal webpack5 implementation of outputFileSystem is gracefulfs. | function isNodeOutputFS(compiler) {
return compiler.outputFileSystem && JSON.stringify(compiler.outputFileSystem) === JSON.stringify(fs);
} | [
"function isNodeOutputFS(compiler) {\n\treturn (\n\t\tcompiler.outputFileSystem &&\n\t\tcompiler.outputFileSystem.constructor &&\n\t\tcompiler.outputFileSystem.constructor.name === 'NodeOutputFileSystem'\n\t);\n}",
"getOutput() {\n // Assuming it is production\n const output = {\n // Here we create a directory inside the user provided outputPath\n // The name of the directory is the sluggified verion of `name`\n // of this configuration object.\n // Also here we assume, user has passed in the correct `relative`\n // path for `outputPath`. Otherwise this will break.\n // We do not use path.resolve, because we expect outputPath to be\n // relative. @todo: create a test here\n path: this.outputPath,\n filename: `${this.appDir}/${this.isDev ? '[name]' : '[name]-[contenthash:8]'}.js`,\n // leave blank because we would handle with free variable\n // __webpack_public_path__ in runtime.\n publicPath: '',\n // we need different jsonpFunction, it has to\n // be unique for every webpack config, otherwise\n // the later will override the previous\n // having combination of appName and file.name\n // kind of ensures that billions of devs, don't\n // override each other!!!!\n jsonpFunction: `wpackio${this.config.appName}${this.file.name}Jsonp`\n }; // Add the publicPath if it is in devMode\n\n if (this.isDev) {\n // This is calculated by CreateWebpackConfig\n // taking into consideration user's own value.\n // So, if WordPress defaults are changed, then\n // depending on wpackio.server.js, it will still\n // point to the right location. It only makes\n // dynamic import and some on-demand split-chunk\n // work.\n output.publicPath = this.config.publicPathUrl;\n }\n\n return output;\n }",
"function getPlatformVariant() {\n var contents = '';\n\n if (process.platform !== 'linux') {\n return '';\n }\n\n try {\n contents = fs.readFileSync(process.execPath); // Buffer.indexOf was added in v1.5.0 so cast to string for old node\n // Delay contents.toStrings because it's expensive\n\n if (!contents.indexOf) {\n contents = contents.toString();\n }\n\n if (contents.indexOf('libc.musl-x86_64.so.1') !== -1) {\n return 'musl';\n }\n } catch (err) {} // eslint-disable-line no-empty\n\n\n return '';\n}",
"function is_nodejs() {\n return (typeof process === 'object' &&\n typeof process.versions === 'object' &&\n typeof process.versions.node !== 'undefined');\n}",
"function shouldEmit(compiler, file, cache) {\n\tif (isNodeOutputFS(compiler)) {\n\t\ttry {\n\t\t\tconst src = fs.statSync(file);\n\t\t\tconst dest = fs.statSync(\n\t\t\t\tpath.join(compiler.options.output.path, transformPath(compiler.options.context, file))\n\t\t\t);\n\t\t\treturn src.isDirectory() || src.mtime.getTime() > dest.mtime.getTime() || !cache;\n\t\t} catch (e) {\n\t\t\treturn true;\n\t\t}\n\t} else {\n\t\treturn true;\n\t}\n}",
"getOutputType() {\n if (this.outputType !== null && (typeof (this.outputType) !== null) && this.outputType !== undefined) { return this.outputType; }\n return null;\n }",
"function determineOutputDirectory(outdir) {\n return outdir ?? fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'cdk.out'));\n}",
"function FileSystem(props) {\n return __assign({ Type: 'AWS::EFS::FileSystem' }, props);\n }",
"function haveOutputErr() {\n return OUTPUT_ERROR;\n}",
"function isDistAvailable(logger) {\n let arch;\n const detectedArch = detectArch_1.detectArch(logger);\n switch (detectedArch) {\n case \"x64\":\n arch = \"x64\" /* x64 */;\n break;\n default:\n if (logger) {\n logger.error(`System arch \"${detectedArch}\" not supported. Must build from source.`);\n }\n return false;\n }\n let platform;\n switch (os.platform()) {\n case \"win32\":\n case \"cygwin\":\n platform = \"windows\" /* WINDOWS */;\n break;\n case \"darwin\":\n platform = \"macos\" /* MACOS */;\n break;\n case \"linux\":\n if (detectLibc_1.detectLibc().isNonGlibcLinux) {\n platform = \"linux-musl\" /* LINUX_MUSL */;\n }\n else {\n platform = \"linux\" /* LINUX */;\n }\n break;\n default:\n if (logger) {\n logger.error(`System platform \"${os.platform()}\" not supported. Must build from source.`);\n }\n return false;\n }\n return {\n platform,\n arch\n };\n}",
"function detectPlatform () {\n var type = os.type();\n var arch = os.arch();\n\n if (type === 'Darwin') {\n return 'osx-64';\n }\n\n if (type === 'Windows_NT') {\n return arch == 'x64' ? 'windows-64' : 'windows-32';\n }\n\n if (type === 'Linux') {\n if (arch === 'arm' || arch === 'arm64') {\n return 'linux-armel';\n }\n return arch == 'x64' ? 'linux-64' : 'linux-32';\n }\n\n return null;\n}",
"async _is_same_inode(fs_context, source_file_path, file_path) {\n try {\n dbg.log2('NamespaceFS: checking _is_same_inode');\n const file_path_stat = await nb_native().fs.stat(fs_context, file_path);\n const file_path_inode = file_path_stat.ino.toString();\n const file_path_device = file_path_stat.dev.toString();\n const source_file_stat = await nb_native().fs.stat(fs_context, source_file_path, { skip_user_xattr: true });\n const source_file_inode = source_file_stat.ino.toString();\n const source_file_device = source_file_stat.dev.toString();\n dbg.log2('NamespaceFS: file_path_inode:', file_path_inode, 'source_file_inode:', source_file_inode,\n 'file_path_device:', file_path_device, 'source_file_device:', source_file_device);\n if (file_path_inode === source_file_inode && file_path_device === source_file_device) {\n return this._get_upload_info(file_path_stat);\n }\n } catch (e) {\n dbg.log2('NamespaceFS: _is_same_inode got an error', e);\n // If we fail for any reason, we want to return undefined. so doing nothing in this catch.\n }\n }",
"async resolveAlternativeBinaryPath(platform) {\n const compatiblePlatforms = knownPlatforms.slice(1).filter(p => get_platform_1.mayBeCompatible(p, platform));\n const binariesExist = await Promise.all(compatiblePlatforms.map(async (platform) => {\n const filePath = this.getQueryEnginePath(platform);\n return {\n exists: await exists(filePath),\n platform,\n filePath,\n };\n }));\n const firstExistingPlatform = binariesExist.find(b => b.exists);\n if (firstExistingPlatform) {\n return firstExistingPlatform.filePath;\n }\n return null;\n }",
"isInitable() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.F_OK);\n return false;\n } catch (err) {\n return true;\n }\n }",
"function createMemFileSystem(realFileSystem) {\n function exists(path) {\n return memfs_1.fs.existsSync(realFileSystem.normalizePath(path));\n }\n function readStats(path) {\n return exists(path) ? memfs_1.fs.statSync(realFileSystem.normalizePath(path)) : undefined;\n }\n function readFile(path, encoding) {\n const stats = readStats(path);\n if (stats && stats.isFile()) {\n return memfs_1.fs\n .readFileSync(realFileSystem.normalizePath(path), { encoding: encoding })\n .toString();\n }\n }\n function readDir(path) {\n const stats = readStats(path);\n if (stats && stats.isDirectory()) {\n return memfs_1.fs.readdirSync(realFileSystem.normalizePath(path), {\n withFileTypes: true,\n });\n }\n return [];\n }\n function createDir(path) {\n memfs_1.fs.mkdirSync(realFileSystem.normalizePath(path), { recursive: true });\n }\n function writeFile(path, data) {\n if (!exists(path_1.dirname(path))) {\n createDir(path_1.dirname(path));\n }\n memfs_1.fs.writeFileSync(realFileSystem.normalizePath(path), data);\n }\n function deleteFile(path) {\n if (exists(path)) {\n memfs_1.fs.unlinkSync(realFileSystem.normalizePath(path));\n }\n }\n function updateTimes(path, atime, mtime) {\n if (exists(path)) {\n memfs_1.fs.utimesSync(realFileSystem.normalizePath(path), atime, mtime);\n }\n }\n return Object.assign(Object.assign({}, realFileSystem), { exists(path) {\n return exists(realFileSystem.realPath(path));\n },\n readFile(path, encoding) {\n return readFile(realFileSystem.realPath(path), encoding);\n },\n readDir(path) {\n return readDir(realFileSystem.realPath(path));\n },\n readStats(path) {\n return readStats(realFileSystem.realPath(path));\n },\n writeFile(path, data) {\n writeFile(realFileSystem.realPath(path), data);\n },\n deleteFile(path) {\n deleteFile(realFileSystem.realPath(path));\n },\n createDir(path) {\n createDir(realFileSystem.realPath(path));\n },\n updateTimes(path, atime, mtime) {\n updateTimes(realFileSystem.realPath(path), atime, mtime);\n },\n clearCache() {\n realFileSystem.clearCache();\n } });\n}",
"function isAbsolute(path) {\n return __WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */] ?\n isAbsolute_win32(path) :\n isAbsolute_posix(path);\n}",
"function resolvePlatform (input) {\n switch (input) {\n case 'mac':\n case 'osx':\n case 'mac-64':\n case 'osx-64':\n return 'osx-64';\n break;\n\n case 'linux':\n case 'linux-32':\n return 'linux-32';\n break;\n\n case 'linux-64':\n return 'linux-64';\n break;\n\n case 'linux-arm':\n case 'linux-armel':\n return 'linux-armel';\n break;\n\n case 'linux-armhf':\n return 'linux-armhf';\n break;\n\n case 'win':\n case 'win-32':\n case 'windows':\n case 'windows-32':\n return 'windows-32';\n break;\n\n case 'win-64':\n case 'windows-64':\n return 'windows-64';\n break;\n\n default:\n return null;\n }\n}",
"function platform() {\n\tvar s = process.platform; // \"darwin\", \"freebsd\", \"linux\", \"sunos\" or \"win32\"\n\tif (s == \"darwin\") return \"mac\"; // Darwin contains win, irony\n\telse if (s.starts(\"win\")) return \"windows\"; // Works in case s is \"win64\"\n\telse return \"unix\";\n}",
"function outputRec(val) {\n if (val === null || typeof val !== \"object\") {\n // strings, numbers, booleans, functions, symbols, undefineds, nulls are all returned as\n // themselves. They are always 'known' (i.e. we can safely 'apply' off of them even during\n // preview).\n return val;\n }\n else if (resource_1.Resource.isInstance(val)) {\n // Don't unwrap Resources, there are existing codepaths that return Resources through\n // Outputs and we want to preserve them as is when flattening.\n return val;\n }\n else if (isUnknown(val)) {\n return val;\n }\n else if (val instanceof Promise) {\n // Recurse into the value the Promise points to. This may end up producing a\n // Promise<Output>. Wrap this in another Output as the final result. This Output's\n // construction will be able to merge the inner Output's data with its own. See\n // liftInnerOutput for more details.\n return createSimpleOutput(val.then((v) => outputRec(v)));\n }\n else if (exports.Output.isInstance(val)) {\n // We create a new output here from the raw pieces of the original output in order to\n // accommodate outputs from downlevel SxS SDKs. This ensures that within this package it is\n // safe to assume the implementation of any Output returned by the `output` function.\n //\n // This includes:\n // 1. that first-class unknowns are properly represented in the system: if this was a\n // downlevel output where val.isKnown resolves to false, this guarantees that the\n // returned output's promise resolves to unknown.\n // 2. That the `isSecret` property is available.\n // 3. That the `.allResources` is available.\n const allResources = getAllResources(val);\n const newOutput = new OutputImpl(val.resources(), val.promise(/*withUnknowns*/ true), val.isKnown, val.isSecret, allResources);\n return newOutput.apply(outputRec, /*runWithUnknowns*/ true);\n }\n else if (val instanceof Array) {\n const allValues = [];\n let hasOutputs = false;\n for (const v of val) {\n const ev = outputRec(v);\n allValues.push(ev);\n if (exports.Output.isInstance(ev)) {\n hasOutputs = true;\n }\n }\n // If we didn't encounter any nested Outputs, we don't need to do anything. We can just\n // return this value as is.\n if (!hasOutputs) {\n // Note: we intentionally return 'allValues' here and not 'val'. This ensures we get a\n // copy. This has been behavior we've had since the beginning and there may be subtle\n // logic out there that depends on this that we would not want ot break.\n return allValues;\n }\n // Otherwise, combine the data from all the outputs/non-outputs to one final output.\n const promisedArray = Promise.all(allValues.map((v) => getAwaitableValue(v)));\n const [syncResources, isKnown, isSecret, allResources] = getResourcesAndDetails(allValues);\n return new exports.Output(syncResources, promisedArray, isKnown, isSecret, allResources);\n }\n else {\n const promisedValues = [];\n let hasOutputs = false;\n for (const k of Object.keys(val)) {\n const ev = outputRec(val[k]);\n promisedValues.push({ key: k, value: ev });\n if (exports.Output.isInstance(ev)) {\n hasOutputs = true;\n }\n }\n if (!hasOutputs) {\n // Note: we intentionally return a new value here and not 'val'. This ensures we get a\n // copy. This has been behavior we've had since the beginning and there may be subtle\n // logic out there that depends on this that we would not want ot break.\n return promisedValues.reduce((o, kvp) => {\n o[kvp.key] = kvp.value;\n return o;\n }, {});\n }\n const promisedObject = getPromisedObject(promisedValues);\n const [syncResources, isKnown, isSecret, allResources] = getResourcesAndDetails(promisedValues.map((kvp) => kvp.value));\n return new exports.Output(syncResources, promisedObject, isKnown, isSecret, allResources);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. | function isENOENT(error) {
return isExpectedError(error, -ENOENT, 'ENOENT');
} | [
"function checkJavaErrno(ne) {\n if (ne instanceof NodeOSException) {\n return ne.getCode();\n }\n throw ne;\n}",
"function getJavaErrno(ne) {\n if (ne instanceof OSException) {\n return ne.getStringCode();\n }\n return Constants.EIO;\n}",
"validateFilePath(file) {\n try {\n if (fs.existsSync(file)) {\n return;\n } else {\n // File wasn't found, but we didn't get an error\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n } catch (error) {\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n }",
"function fileNotFound(req, h){\n const response = req.response\n //Preguntamos que si la response es un mensaje de boom y si el codigo es 404\n if (!req.path.startsWith('/api') && response.isBoom && response.output.statusCode === 404) {\n //Retornamos la vista de la pagina que muestra el error 404 de una forma visual mas agradable\n return h.view('404', {}, {\n layout: 'errLayout'\n }) .code(404)\n }\n\n return h.continue\n}",
"function convertJavaErrno(errCode) {\n if (errCode === 0) {\n return null;\n }\n return ErrorCodes.get().toString(errCode);\n}",
"function isUNC(path) {\n if (!__WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */]) {\n // UNC is a windows concept\n return false;\n }\n if (!path || path.length < 5) {\n // at least \\\\a\\b\n return false;\n }\n var code = path.charCodeAt(0);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n code = path.charCodeAt(1);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n var pos = 2;\n var start = pos;\n for (; pos < path.length; pos++) {\n code = path.charCodeAt(pos);\n if (code === 92 /* Backslash */) {\n break;\n }\n }\n if (start === pos) {\n return false;\n }\n code = path.charCodeAt(pos + 1);\n if (isNaN(code) || code === 92 /* Backslash */) {\n return false;\n }\n return true;\n}",
"function check_file_exist(file){\n\tvar http = new XMLHttpRequest();\n\thttp.open('HEAD',file,false);\n\thttp.send();\n\treturn http.status == 404;\n}",
"error() {\n const isAbsolute = this.options.fail.indexOf('://') > -1;\n const url = isAbsolute ? this.options.fail : this.options.url + this.options.fail;\n\n this.request(url);\n }",
"function statSafe (path, requestedPermissions, callback) {\n fs.stat(path, function (err, stat) {\n onSafeStat(err, stat, requestedPermissions, callback)\n })\n }",
"function notExistsOrErro(value, msg) {\n try {\n existsOrErro(value, msg)\n } catch (msg) {\n return\n }\n throw msg\n}",
"function isAbsolute(path) {\n return __WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */] ?\n isAbsolute_win32(path) :\n isAbsolute_posix(path);\n}",
"function error(err) {\n if (error.err) return;\n callback(error.err = err);\n }",
"errorHandler(err, invokeErr) {\n const message = err.message && err.message.toLowerCase() || '';\n if (message.includes('organization slug is required') || message.includes('project slug is required')) {\n // eslint-disable-next-line no-console\n console.log('Sentry [Info]: Not uploading source maps due to missing SENTRY_ORG and SENTRY_PROJECT env variables.')\n return;\n }\n if (message.includes('authentication credentials were not provided')) {\n // eslint-disable-next-line no-console\n console.warn('Sentry [Warn]: Cannot upload source maps due to missing SENTRY_AUTH_TOKEN env variable.')\n return;\n }\n invokeErr(err);\n }",
"error(errorCode) {\n throw new Error(errors[errorCode] || errorCode);\n }",
"function fail(errcode) {\n if (typeof(errcode) === 'undefined') {\n errcode = 1;\n }\n if (exitFn) {\n exitFn(errcode);\n } else {\n process.exit(errcode);\n }\n return null;\n}",
"function getValidHttpErrorCode (err) {\n var errorCode\n if (err.code && String(err.code).match(/[1-5][0-5][0-9]$/)) {\n errorCode = parseInt(err.code)\n } else {\n errorCode = 500\n }\n return errorCode\n}",
"function failure() {\n process.exit(ExitCode.Failure);\n}",
"function onstatparent(error) {\n if (error) {\n next(new Error('Cannot read parent directory. Error:\\n' + error.message))\n } else {\n done(false)\n }\n }",
"function nodeCB(code, stdout, stderr, cb) {\n if (code !== 0) {\n console.log('Program stderr:', stderr);\n shell.exit(1);\n } else {\n cb();\n }\n}",
"function unix_stat(fname) {\n if (!caml_sys_file_exists(fname)) {\n var errname = caml_new_string(\"Unix.Unix_error\");\n var Unix_error = caml_named_value(caml_bytes_of_string(errname));\n throw [0, Unix_error, 20, caml_new_string(\"stat\"), fname];\n }\n\n var is_dir = caml_sys_is_directory(fname) ? 1 : 0;\n var kind = is_dir ? 1 : 0;\n var perms = is_dir ? 493 : 420;\n\n var size = 4096;\n if (!is_dir) {\n var channel = caml_ml_open_descriptor_in(caml_sys_open(fname, [0,0,[0,7,0]], 0));\n caml_ml_set_channel_name(channel, fname);\n size = caml_ml_channel_size(channel);\n caml_ml_close_channel(channel);\n }\n\n return [0, -1, -1, kind, perms, -1, -1, -1, -1, size, -1, -1, -1];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get information by http protocol | function getInfoByHttp(url, callback) {
// http.get(url, function(res) {
// var body = '';
// res.on('data', function(d) {
// body += d;
// console.log(body);
// //callback(null, JSON.parse(body));
// });
// // res.on('end', function() {
// // //var obj = JSON.parse(body);
// // console.log();
// // });
// }).on('error', function(e) {
// console.log(e);
// });
var request = require("request")
request({
url: url,
json: true
}, function(error, response, body) {
if (!error && response.statusCode === 200) {
callback(null, body);
//console.log(JSON.parse(body)) // Print the json response
}
})
} | [
"static getLib (url) {\n let urlo = URL.parse(url);\n let lib;\n switch (urlo.protocol) {\n case 'http:':\n return HTTP;\n\n case 'https:':\n return HTTPS;\n }\n throw new Error(`Unknown protocol ${urlo.protocol}.`);\n }",
"function checkForHTTP(url) {\n let outputString = \"\";\n if (url.slice(0,7) === \"http://\") {\n return url;\n } else if (url.slice(0,8) === \"https://\") {\n return url;\n } else {\n outputString += \"http://\";\n outputString += url;\n return outputString;\n }\n}",
"function getIpProtoByServCatPubUrl (pubUrl)\n{\n var ipAddr = null;\n var port = null;\n var reqProto = global.PROTOCOL_HTTP;\n var ipAddrStr = pubUrl, portStr = null;\n var ipIdx = -1, portIdx = -1;\n\n ipIdx = pubUrl.indexOf(global.HTTPS_URL);\n if (ipIdx >= 0) {\n reqProto = global.PROTOCOL_HTTPS;\n ipAddrStr = pubUrl.slice(ipIdx + (global.HTTPS_URL).length);\n }\n ipIdx = pubUrl.indexOf(global.HTTP_URL);\n if (ipIdx >= 0) {\n ipAddrStr = pubUrl.slice(ipIdx + (global.HTTP_URL).length);\n }\n\n /* Format is http://<ip/host>:<port>/XXXX */\n portIdx = ipAddrStr.indexOf(':');\n if (-1 != portIdx) {\n ipAddr = ipAddrStr.substr(0, portIdx);\n portStr = ipAddrStr.slice(portIdx + 1);\n portIdx = portStr.indexOf('/');\n if (-1 != portIdx) {\n port = portStr.substr(0, portIdx);\n } else {\n port = portStr;\n }\n }\n return {'ipAddr': ipAddr, 'port': port, 'protocol': reqProto};\n}",
"function getFoodInformation(Ean) {\n //https://world.openfoodfacts.org/api/v0/product/\n var opts = {\n hostname: 'world.openfoodfacts.org',\n path: '/api/v0/product/' + Ean,\n method: 'GET',\n headers: {\n 'connection': 'keep-alive',\n \"Content-Type\": \"application/json\",\n }\n };\n console.log(opts.hostname + opts.path);\n var req = https.request(opts, function (res) {\n res.on('data', function (d) {\n // console.log(d);\n });\n });\n req.end();\n}",
"vaidateProtocol(host){\n let protocols = ['https://', 'http://'];\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\n throw new Error('Host String must include http:// or https://')\n }",
"function getHost() {\n return location.protocol + '//' + location.host\n }",
"get protocolType() {\n return this.getStringAttribute('protocol_type');\n }",
"get url() {\n return this._serverRequest.url;\n }",
"function domainParse(){\n var l = location.hostname\n return {\n \"prot\": location.protocol,\n \"host\": l,\n \"statics\" : 'cdn.kaskus.com'\n };\n}",
"function httpGet(url, callback) {\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() {\n if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n callback(JSON.parse(xmlHttp.responseText));\n }\n }\n\n xmlHttp.open(\"GET\", url, true); // true for asynchronous \n xmlHttp.send(null);\n}",
"function validateProtocol(proto2,url2) {\n if (proto2 == \"\" && (/^disk[0-2]|disk$/.test(url2) == true || /^slot[0-1]$/.test(url2) == true || /^NVRAM$/.test(url2) == true || /^bootflash$/.test(url2) == true || /^flash[0-1]|flash$/.test(url2) == true)) {\n return 0;\n } else if (/^FTP$/i.test(proto2) == false && /^TFTP$/i.test(proto2) == false) {\n return 1;\n } else {\n return 0;\n }\n\n}",
"sendGETRequest() {\n\n const options = {\n hostname: 'localhost',\n port: SERVER_PORT,\n path: '/',\n method: 'GET'\n };\n\n const clientGETReq = http.request(options, function(res) {\n\n console.log(`STATUS CODE: ${res.statusCode}`);\n\n });\n\n clientGETReq.on('error', function(err) {\n console.log('ERROR:' + err);\n });\n\n clientGETReq.end();\n\n }",
"function getInternetInfo(callback){\r\n\tjQuery.getJSON( 'APIS/returnInternetJSON.txt', \r\n\t\t\tfunction(returnData, status){\r\n\t\t\t\tif(returnData.RETURN.success){\r\n\t\t\t\t\tcallback(returnData.RETURN.success,returnData.INTERNET);\r\n\t\t\t\t}else{\r\n\t\t\t\t\tcallback(returnData.RETURN.success,returnData.RETURN.errorDescription);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t);\r\n}",
"function _parse(info) {\n if (typeof info !== 'string') {\n throw new TypeError('expecting string transport uri');\n }\n\n var uri = url.parse(info);\n\n if (!(uri.port > 0)) {\n throw new Error('expected valid transport uri');\n }\n\n return {\n host: uri.hostname,\n port: uri.port\n };\n}",
"function getServerFriendlyName(url){\n\trequest(url, function(error, response, body){\n\t parseString(body, function(err, result){\n\t\tconsole.log(result.root.device[0].friendlyName[0]);\n\t });\n\t});\n }",
"function getSpec(host, path) {\n console.log('Calling ', `${host}${path}`);\n const options = {\n host: host.match(/[http|https]:\\/\\/(.+)/)[1],\n path: path,\n };\n\n return new Promise((resolve, reject) => {\n const request = http.get(options, response => {\n let body = '';\n response.on('data', chunk => (body += chunk));\n response.on('end', () => resolve(JSON.parse(body)));\n });\n request.on('error', err => reject(err));\n });\n}",
"async getInfo(city) {\n // complete request\n const query = `?action=query&formatversion=2&format=json&origin=*&prop=extracts|info|pageimages&inprop=url&piprop=thumbnail&pithumbsize=300&exchars=500&explaintext&exintro&exsectionformat=plain&redirects=1&titles=${city}`;\n const response = await fetch(this.wikiURI + query);\n const data = await response.json();\n\n return data.query.pages[0];\n }",
"getPrologRequest(requestString, onSuccess, onError, port) {\r\n var requestPort = port || 8081\r\n var request = new XMLHttpRequest();\r\n request.open('GET', 'http://localhost:' + requestPort + '/' + requestString, true);\r\n\r\n request.onload = onSuccess || function (data) { console.log(\"Request successful. Reply: \" + data.target.response); };\r\n request.onerror = onError || function () { console.log(\"Error waiting for response\"); };\r\n\r\n request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\r\n request.send();\r\n }",
"function getQuestions() {\r\n\r\n\tclient = new XMLHttpRequest();\r\n\tclient.open('GET','http://developer.cege.ucl.ac.uk:30288/getquestions');\r\n\tclient.onreadystatechange = questionResponse;\r\n\tclient.send();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function remove the shake functionality | function removeShake() {
document.getElementById('input').classList.remove('shake')
} | [
"function shakeEventDidOccur () {\n\n //put your own code here etc.\n roll();\n}",
"function upAndDownShake() {\n \t\tif (counter < numberOfShakes) {\n\n \t\t//Reset the element's position at the start of each shake\n \t\telement.style.transform = 'translate(' + startX + 'px, ' + startY + 'px)';\n \t\t//reduce the magnitude by which the element is shaked\n \t\tmagnitude -= magnitudeUnit;\n \t\t//Randomly change the element's position\n \t\tvar randomX = randomInt(-magnitude, magnitude);\n \t\tvar randomY = randomInt(-magnitude, magnitude);\n \t\telement.style.transform = 'translate(' + randomX + 'px, ' + randomY + 'px)';\n \t\tcounter += 1;\n \t\trequestAnimationFrame(upAndDownShake);\n \t\t}\n\n\t //When the shaking is finished, restore the element to its original \n\t //position and remove it from the `shakingElements` array\n\t if (counter >= numberOfShakes) {\n\t \telement.style.transform = 'translate(' + startX + ', ' + startY + ')';\n\t \tshakingElements.splice(shakingElements.indexOf(element), 1);\n\t }\n\t}",
"function shake() {\n const allImgs = document.querySelectorAll('.img-thumbnail');\n for (let i = 0; i < allImgs.length; i++) {\n allImgs[i].classList.add('shake');\n }\n setTimeout(function() {\n for (let i = 0; i < allImgs.length; i++) {\n allImgs[i].classList.remove('shake');\n }\n }, 500);\n}",
"function shakebox()\n{\n\t$('#loginform').animate({ left: '100' }, 80, function(){\n\t\t$('#loginform').animate({ left: '-100' }, 80, function(){\n\t\t\t$('#loginform').animate({ left: '70' }, 80, function(){\n\t\t\t\t$('#loginform').animate({ left: '-70' }, 80, function(){\n\t\t\t\t\t$('#loginform').animate({ left: '0' }, 1000, 'easeOutElastic');\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}",
"function preventStartUpAnimation(){\n setStartUpAnimation(false);\n }",
"function whacked() {\n\tif (timeLeft > 0) {\n\t\tthis.classList.remove(\"mole\");\n\t\tthis.removeEventListener(\"click\", giveMePoints, true);\n\t\tthis.classList.add(\"whacked\");\n\t\tsetTimeout(resetWhacked, 250);\n\t}\n}",
"removeMouseInteractions() {\t\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"click\", this.towerStoreClick);\n\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"mousemove\", this.towerStoreMove);\t\t\n\t}",
"function unScareAlien(){\n aliens.forEach(alien => alien.isScared = false)\n }",
"function clearables(){\n //remove moveable...\n _$showcase.find('.moveable').removeClass('moveable');\n \n //remove clippingable...\n _$showcase.find('.clippingable').removeClass('clippingable');\n \n //remove contextmenu...\n _$showcase.find('.contextmenu').remove();\n \n \n }",
"function onTouchMoveLightbox(e) {\n e.preventDefault();\n}",
"stopShooting() {\n this.shooting = false;\n this.sentAddShooterPacket = false;\n\n var msg = {\n type: \"RemoveShooter\",\n entityType: \"Player\",\n };\n\n game.getNetwork.sendMessage(JSON.stringify(msg));\n }",
"function stopAnimation() {\n animatedMove = {};\n autoRotateSpeed = config.autoRotate ? config.autoRotate : autoRotateSpeed;\n config.autoRotate = false;\n}",
"function cancelWheel(e) {\n e = e || window.event;\n e.preventDefault ? e.preventDefault() : (e.returnValue = false);\n }",
"__cancelTwoFingersOverlay() {\n if (this.config.touchmoveTwoFingers) {\n if (this.data.twofingersTimeout) {\n clearTimeout(this.data.twofingersTimeout);\n this.data.twofingersTimeout = null;\n }\n this.viewer.overlay.hide(IDS.TWO_FINGERS);\n }\n }",
"function handleResetTransition(){\n let swipeContainers = document.getElementsByClassName('react-swipeable-view-container');\n for(let i = 0; i < swipeContainers.length; i++) {\n swipeContainers[i].style.transition = null;\n }\n }",
"killTurtle() {\r\n if (typeof Sk.TurtleGraphics.reset === \"function\") {\r\n Sk.TurtleGraphics.reset();\r\n }\r\n }",
"function gestureCancel(e)\n{\n if (gesture.on) {\n gesture.on = false;\n /* Undo visual feedback */\n if (slidemode) document.body.style.opacity = gesture.opacity;\n }\n}",
"isWarning(id) {\r\n $(id).removeClass('shake-normal');\r\n setTimeout(() => {\r\n $(id).addClass('shake-normal');\r\n }, 0);\r\n }",
"function RemoveUpgrade(){\n\tplayer.upgraded = false;\n\tplayer.sprite =Sprite(currentActivePlayer);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Once we have confirmed that we want to share, prepare the tokbox publishing initiating and toggle back to the selects page | function screenConfirmed(isConfirmed) {
document.getElementById("selects").innerHTML = "";
if (isConfirmed === true){
onAccessApproved(currentScreensharePickID);
}
togglePage();
} | [
"function ChooseTypeSubmit() {\n $Dialog.find('button').attr('disabled', 'disabled');\n TargetNS.FinishLinking(Conn.sourceId, Conn.targetId, Conn.connection);\n }",
"function pushSubscription(chkbox){\n\tif(chkbox[\"selectedKeys\"]==null)\n\t\taudiencePushSubs=false;\n\telse\n\t\taudiencePushSubs=true;\n}",
"function shareScreen() {\n console.log(\"SHARING SCREEN \" + isSharingScreen);\n document.getElementById(\"share\").disabled = true;\n document.getElementById(\"unshare\").disabled = false;\n document.getElementById(\"share\").style.display = \"none\";\n document.getElementById(\"unshare\").style.display = \"block\";\n leaveChannel();\n setTimeout(function() { \n joinChannel(channel_name, true); \n }, 1000);\n}",
"_startChoose(e) {\n let target = e.target;\n if (target.nodeName !== 'BUTTON') {\n target = target.parentElement;\n }\n this._chosenServer = target.dataset.server;\n let choices = this._state.packages[target.dataset.app];\n let chosen = choices.findIndex(choice => choice.Name === target.dataset.name);\n this._push_selection.choices = choices;\n this._push_selection.chosen = chosen;\n this._push_selection.show();\n }",
"function submitShareDialog() {\n closeShareDialog();\n successDialog.classList.add(\"dialog__show\");\n // Timeout for closing animations\n setTimeout(closeSuccessDialog, 5000);\n}",
"function initShareButton() {\n // share button clicked. copy the link to the clipboard\n $('#share-copy').click(() => {\n var aux = document.createElement(\"input\"); \n aux.setAttribute(\"value\", window.location.href); \n document.body.appendChild(aux); \n aux.select();\n document.execCommand(\"copy\"); \n document.body.removeChild(aux);\n\n alert(\"The share link has been copied to your clipboard.\");\n });\n}",
"function startPost() {\n const selectedMarkets = identifyCCs()\n if (selectedMarkets.length <= 0) {\n dialog.showMessageBox( {type: 'error', title: 'No Markets Selected', message: 'You have not selected any markets to send a post to. Contact a KBase Admin for help.'} )\n } else if (document.querySelector('#content').innerHTML.length < 50 && document.querySelector('#headline').value.length < 3) {\n dialog.showMessageBox({\n type: 'warning',\n title: 'Wait!',\n buttons: ['No. I want to edit it before sending', 'Yes. This post is finished'],\n message: 'This post is not very long. Are you sure you want to send it?',\n }, resp => {\n if (resp === 1) {\n ipcRenderer.send('open-smt-window')\n }\n })\n } else {\n ipcRenderer.send('open-smt-window')\n }\n}",
"function janrain_popup_share(url, options, variables) {\n // RPXNOW is not loaded in offline (demo) mode\n if (typeof RPXNOW === 'undefined')\n return;\n\tRPXNOW.loadAndRun(['Social'], function () {\n\t\tif (typeof options != 'object') options = {};\n\t\tvar activity = new RPXNOW.Social.Activity(variables.share_display,\n\t\t\t\t\t\t\t\t\t\t\t\t variables.action_share_description,\n\t\t\t\t\t\t\t\t\t\t\t\t url\n\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\n\t\tactivity.setTitle (variables.action_page_title);\n\t\tactivity.setDescription (variables.action_page_description);\n\t\tactivity.setUserGeneratedContent(variables.share_usergen_default);\n\t\t\n\t\tif (typeof variables.action_links == 'object') {\n\t\t\tfor (i=0; i<variables.action_links.length; i++) {\n\t\t\t\tactivity.addActionLink(variables.action_links[i].text, variables.action_links[i].href);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/*\n\t\tif (typeof variables.properties == 'object') {\n\t\t\tfor (i=0; i<variables.properties.length; i++) {\n\t\t\t\tactivity.addTextProperty(variables.properties[i].text, variables.properties[i].value);\n\t\t\t}\n\t\t}\n\t\t*/\n\t\t\n\t\tif (typeof variables.media == 'object') {\n\t\t\tvar rpx_images;\n\t\t\tfor (i=0; i<variables.media.length; i++) {\n\t\t\t\tvar media = variables.media[i];\n\t\t\t\tif (media.type=='image') {\n\t\t\t\t\tif (typeof rpx_images == 'undefined')\n\t\t\t\t\t\trpx_images = new RPXNOW.Social.ImageMediaCollection();\n\t\t\t\t\trpx_images.addImage(media.src, media.href);\n\t\t\t\t} else if (media.type=='audio') {\n\t\t\t\t\tactivity.setMediaItem(new RPXNOW.Social.Mp3MediaItem(media.src));\n\t\t\t\t} else if (media.type=='video') {\n\t\t\t\t\tvar rpx_video = new RPXNOW.Social.VideoMediaItem(\n\t\t\t\t\t\tmedia.original_url,\n\t\t\t\t\t\tmedia.thumbnail_url\n\t\t\t\t\t);\n\t\t\t\t\trpx_video.setVideoTitle(variables.video[i].caption);\n\t\t\t\t\tactivity.setMediaItem(rpx_video);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof rpx_images != 'undefined')\n\t\t\t\tactivity.setMediaItem(rpx_images); \n\t\t}\n\t\t\n\t\tvar finished = function(results) {\n\t\t // Process results of publishing.\n\t\t}\n\t\t\n\t\toptions.finishCallback = finished;\n\t\toptions.urlShortening = true;\n\t\t\n\t\tRPXNOW.Social.publishActivity(activity, options);\n\t});\n}",
"function handleShareClick() {\n setShareUrl(window.location.origin + '/?' + simplifiedSharedParamsString);\n }",
"function smsSubscription(chkbox){\n\tif(chkbox[\"selectedKeys\"]==null)\n\t\taudienceSmsSubs=false;\n\telse\n\t\taudienceSmsSubs=true;\n}",
"function saveSettings() {\n // Update the sources variable.\n $('.js-social-media-source', modal).each(function () {\n var source = $(this).val();\n\n if (sources.hasOwnProperty(source)) {\n sources[source] = $(this).is(':checked');\n }\n });\n\n // Save settings in cookie.\n if (Drupal.eu_cookie_compliance.hasAgreed()) {\n cookieSaveSettings();\n }\n\n // Apply new settings.\n $('.js-social-media-wrapper').each(function () {\n applySettings($(this));\n });\n }",
"function updatePrivateMessengerSettings(){\n $('#messenger_settings_form .loading-wrapper').show();\n $.ajax({\n url: '/private_messenger.php',\n data: $('#messenger_settings_form').serialize() + '&action=save-settings',\n type: 'post',\n dataType: 'xml',\n success: function (rsp){\n if($('#messenger_privacy_all').prop('checked'))\n $('#add-user-to-buddylist').addClass('add-user-to-buddylist-hidden');else\n $('#add-user-to-buddylist').removeClass('add-user-to-buddylist-hidden');\n $('#private_messenger_buddies_list').html($(rsp).find('html').text());\n },\n complete: function (){\n $('#messenger_settings_form .loading-wrapper').hide();\n }\n })\n }",
"function saveFrameworkPublish() {\n hideModalError(FWK_PUBLISH_MODAL);\n if (isValidPublishDataFromFrameworkPublish()) {\n showModalBusy(FWK_PUBLISH_MODAL,\"Publishing framework...\");\n setTimeout(function() {\n hideModalBusy(FWK_PUBLISH_MODAL);\n enableModalInputsAndButtons();\n },\n 3000);\n }\n}",
"function MASE_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASE_SetInfoboxesAndBtns =====\") ;\n\n const step = mod_MASE_dict.step;\n const is_response = (!!response);\n\n console.log(\"......................step\", step) ;\n console.log(\"is_response\", is_response) ;\n console.log(\"test_is_ok\", mod_MASE_dict.test_is_ok) ;\n console.log(\"saved_is_ok\", mod_MASE_dict.saved_is_ok) ;\n console.log(\"is_approve_mode\", mod_MASE_dict.is_approve_mode) ;\n console.log(\"verification_is_ok\", mod_MASE_dict.verification_is_ok) ;\n\n // step 0: opening modal\n // step 1 + response : return after check\n // step 1 without response: save clicked approve or request verifcode\n // step 2 + response : return after approve or after email sent\n // step 2 without response: submit Exform wit hverifcode\n // step 3 + response: return from submit Exform\n\n // TODO is_reset\n const is_reset = mod_MASE_dict.is_reset;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false;\n let show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.approve_msg_html) {\n mod_MASE_dict.msg_html = response.approve_msg_html;\n };\n\n console.log(\" >> step:\", step);\n\n if (step === 0) {\n // step 0: when form opens and request to check is sent to server\n // tekst: 'The subjects of the candidates are checked'\n msg_info_txt = loc.MASE_info.checking_exams;\n show_loader = true;\n } else {\n if(mod_MASE_dict.is_approve_mode){\n // --- is approve\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = mod_MASE_dict.has_already_approved;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.MASE_info.Approve_exams;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n msg_info_txt = (is_reset) ? loc.MASE_info.removing_approval_exams : loc.MASE_info.approving_exams;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else {\n // --- is submit\n if (step === 1) {\n // response with checked subjects\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.Request_verifcode;\n };\n } else if (step === 2) {\n // clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MASE_info.sending_verifcode;\n show_loader = true;\n } else if (step === 3) {\n // response 'email sent'\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n show_input_verifcode = true;\n disable_save_btn = !el_MASE_input_verifcode.value;\n save_btn_txt = loc.Publish_exams;\n } else if (step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n show_loader = true;\n } else if (step === 5) {\n // response 'Exform submittes'\n // msg_info_txt is in response\n }\n } // if(mod_MASE_dict.is_approve_mode)\n } // if (step === 0)\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n\n if (msg_info_txt){\n mod_MASE_dict.msg_html = \"<div class='pt-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \" ...</p></div>\";\n }\n\n const hide_info_container = (!msg_info_txt || show_loader)\n add_or_remove_class(el_MASE_info_container, cls_hide, hide_info_container)\n\n el_MASE_msg_container.innerHTML = mod_MASE_dict.msg_html;\n add_or_remove_class(el_MASE_msg_container, cls_hide, !mod_MASE_dict.msg_html)\n\n add_or_remove_class(el_MASE_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASE_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n add_or_remove_class(el_MASE_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n\n if (el_MASE_info_request_msg1){\n el_MASE_info_request_msg1.innerText = loc.MASE_info.need_verifcode +\n ((permit_dict.requsr_role_admin) ? loc.MASE_info.to_publish_exams : \"\");\n };\n\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASE_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASE_btn_delete, cls_hide, !show_delete_btn);\n\n console.log(\"save_btn_txt\", save_btn_txt) ;\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASE_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASE_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MASE_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASE_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n } // MASE_SetInfoboxesAndBtns",
"function subtest_show_tos_privacy_links_for_selected_providers(w) {\n wait_for_provider_list_loaded(w);\n\n // We should be showing the TOS and Privacy links for the selected\n // providers immediately after the providers have been loaded.\n // Those providers should be \"foo\" and \"bar\".\n assert_links_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n ]);\n\n assert_links_not_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n ]);\n\n // Now click off one of those providers - we shouldn't be displaying\n // and links for that one now.\n let input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n w.click(new elib.Elem(input));\n\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n\n // Ensure that the \"Other languages\" div is visible\n wait_for_element_visible(w, \"otherLangDesc\");\n // Now show the providers from different locales...\n w.click(w.eid(\"otherLangDesc\"));\n wait_for_element_invisible(w, \"otherLangDesc\");\n\n // And click on one of those providers...\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"French\"]'\n );\n w.click(new elib.Elem(input));\n // We should be showing the French TOS / Privacy links, along\n // with those from the bar provider.\n assert_links_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n ]);\n\n // The foo provider should still have it's links hidden.\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n\n // Click on the German provider. It's links should now be\n // shown, along with the French and bar providers.\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"German\"]'\n );\n w.click(new elib.Elem(input));\n assert_links_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n \"http://www.example.com/German-tos\",\n \"http://www.example.com/German-privacy\",\n ]);\n\n // And the foo links should still be hidden.\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n}",
"function commitOptionsOk(){\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].DeviceSanity = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = \"false\";\n\tvar devSan = $(\"#comOpDevSanity\").is(\":checked\");\n\tvar accSan = $(\"#comOpAccSanity\").is(\":checked\");\n\tvar connec = $(\"#comOpConnectivity\").is(\":checked\");\n\tvar enaInt = $(\"#comOpEnaInterface\").is(\":checked\");\n\tvar lnkSan = $(\"#comOpLinkSanity\").is(\":checked\");\n\tvar startR = $(\"#comOpStartRes\").is(\":checked\");\n\tvar endR = $(\"#comOpEndRes\").is(\":checked\");\n\tfor(var t=0; t<globalMAINCONFIG.length; t++){\n\t\tif(globalMAINCONFIG[t].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].DeviceSanity = devSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity = accSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = lnkSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface = enaInt.toString();\n\t\t\tStartReservation = startR.toString();\n\t\t\tEndReservation = endR.toString();\n\t\t}\n\t}\n\tStartReservation = startR.toString();\n\tEndReservation = endR.toString();\n\tif($(\"#comOpConnectivity\").is(\":visible\")){\n\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = connec.toString();\n\t}\n\tif($(\"#comOpConnectivity\").parent().parent().parent().attr('style') == \"display: none;\"){\n\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = \"false\";\n\t}\n\tif(lnkSan == \"true\" || lnkSan == true){\n\t\tlnkSan = \"yes\";\n\t}else{\n\t\tlnkSan = \"no\";\n\t}\n\tif(globalInfoType == \"JSON\"){\n\t\tvar devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n\t}\n\tfor(var a=0;a < devices.length; a++){\n\t\tdevices[a].ConnectivityFlag = lnkSan;\n\t}\n\tfor(var b=0;b < window['variable' + dynamicLineConnected[pageCanvas]].length; b++){\n\t\twindow['variable' + dynamicLineConnected[pageCanvas]][b].ConnectivityFlag = lnkSan;\n\t}\n\twindow['variable' + ConnectivityFlag[pageCanvas]] = lnkSan;\n\tsetTimeout(function(){\n \tif(TimePicker == false){\n \t$(\"#RequestButton\").trigger(\"click\");\n }\n \t},1000);\n\tshowPickerOption();\n}",
"function emailSubscription(chkbox){\n\tif(chkbox[\"selectedKeys\"]==null)\n\t\taudienceEmailSubs=false;\n\telse\n\t\taudienceEmailSubs=true;\n}",
"function setupBtnsSensorSelect() {\n\n //add a click action listener to the select buttons\n $(\"#sidebar button.sensorNavBtn\").click(function () {\n var button = $(this);\n\n //check if this is already the current page loaded \n if (!button.hasClass(\"current\")) { //if not then\n loadContent(button.attr(\"data-graph-sensor\")); //load new page\n $(\"#sidebar button.current\").removeClass(\"current\"); //remove current from the previous button\n button.addClass(\"current\"); //add current to the button pressed\n }\n });\n}",
"function onProceedClick() {\n setDisplayValue('q1');\n updateLastViewed('q1');\n showHideElements();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get List Item Type metadata | function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
} | [
"function getItemTypes() {\n\tvar itemTypes;\n\n\ttry {\n\t\titemTypes = com.ibm.team.workitem.web.cache.internal.Cache.getItem('workitems/itemTypes');\n\t} catch (e) {\n\t\titemTypes = null;\n\t}\n\n\treturn itemTypes;\n}",
"function getType(item) {\n console.log(item + ' is a ' + typeof(item));\n}",
"getDataTypes(moduleType) {\n return this._resources.modules[moduleType];\n }",
"getType() {\n return this.type\n }",
"_getSelectionItemType()\n {\n var keys = this.getSelectedItemKeys();\n var itemType = null;\n var urls = [];\n for (var index in keys)\n {\n var item = this.getSelectedItem(keys[index]);\n if (itemType === null)\n {\n itemType = item.constructor;\n }\n }\n return itemType;\n }",
"getType () {\n\t\tlet type = this.definition.type;\n\n\t\t// if it's not a relationship or fetched property, it's an attribute\n\t\t// NOTE: Probably need to separate this out into different classes\n\t\ttype !== 'relationship' && type !== 'fetched' && (type = 'attribute');\n\n\t\treturn type;\n\t}",
"static getClass(itemType)\n\t{\n\t\treturn item_types[itemType];\n\t}",
"function getItemSubType() {\n return new RegExp(`^${template.bug.headlines[0]}`).test(itemBody)\n ? ItemSubType.bug\n : new RegExp(`^${template.feature.headlines[0]}`).test(itemBody)\n ? ItemSubType.feature\n : new RegExp(`^${template.pr.headlines[0]}`).test(itemBody)\n ? ItemSubType.pr\n : undefined;\n}",
"getType(){\n const { type } = this.props\n if (type) return type\n return \"posts\"\n }",
"function setType(itemType){\n\ttype = itemType;\n}",
"listDesc() {\n const desc = this.st.lists[t.getKey(this.path.key)];\n return desc || null;\n }",
"get listItemAllFields() {\n return SPInstance(this, \"listItemAllFields\");\n }",
"get icon_type() {\n return this.args.icon_type;\n }",
"function getItemsOfType(items, type) {\n return _.where(items, { 'type': type });\n }",
"typesList(types) {\n this.snippet.appendText(\" [\");\n this.textOrPlaceholder(types, \"<Type>\");\n this.snippet.appendText(\"]\");\n }",
"get calendarItemType()\n\t{\n\t\t//dump(\"get calendarItemType: title:\"+this.title+\", this._calendarItemType:\"+this._calendarItemType+\", startdate=\"+this.startDate.toString()+\"\\n\");\n\t\treturn this._calendarItemType;\n\t}",
"function getProductTypeAttributes(client, productType){\n return client.productTypes.byId(productType).fetch().then(function(data){\n if (data && data.body.attributes) {\n return data.body.attributes;\n }\n });\n}",
"get type() {\n return typeof this._content == 'number'\n ? BlockType.Text\n : Array.isArray(this._content)\n ? this._content\n : this._content.type\n }",
"get typeURL() {\n return this._content[0];\n }",
"function show(type) { console.log(type.schema({exportAttrs: true})); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HSB to RGB conversion function Note: this function will not work if the hue value given is the maximum, i.e. 360 degrees. This is because the "i" value will then be 6, and there is no option specified for i=6 in the notes. | function HSBtoRGB(hue, saturation, brightness){
//Normalize input
let h = hue*(Math.PI/180);
let s = saturation/100;
let b = brightness/100;
//Define variables i and f
let i = Math.floor((3*h)/Math.PI);
let f = ((3*h)/Math.PI) - i;
//Calculating RGB values
let p = b * (1 - s);
let q = b * (1 - (f*s));
let t = b * (1 - ((1 - f)*s));
switch(i){
case 0:
printRGB(b,t,p);
break;
case 1:
printRGB(q,b,p);
break;
case 2:
printRGB(p,b,t);
break;
case 3:
printRGB(p,q,b);
break;
case 4:
printRGB(t,p,b);
break;
case 5:
printRGB(b,p,q);
break;
}
//Function that prints result to console
//Saves on writting repeated code
function printRGB(r, g , b){
print("HSB(" + hue + ", " + saturation + ", " + brightness + ") = RGB(" + Math.round(r*255) + ", " + Math.round(g*255) + ", " + Math.round(b*255) + ")");
}
} | [
"function RGBtoHSB(red, green, blue)\n{\n //Normalize input\n let r = red/255;\n let g = green/255;\n let b = blue/255;\n \n //Obtain maximum and minimum input values\n let maximum = max(r,g,b);\n let minimum = min(r,g,b);\n \n //Declare h, s, and b variables\n var hue;\n var saturation;\n var brightness; \n \n //Find hue value in radians\n if (maximum == minimum){\n hue = 0;\n \n } else if (maximum == r){\n hue = (Math.PI/3)*((g-b)/(maximum-minimum)%(2*Math.PI));\n \n } else if (maximum == g){\n hue = ((2*Math.PI)/3)+((Math.PI/3)*((b-r)/(maximum-minimum)));\n \n } else if (maximum == b){\n hue = ((4*Math.PI)/3)+((Math.PI/3)*((r-g)/(maximum-minimum)));\n \n }\n \n //Find saturation\n if (maximum == 0){\n saturation = 0;\n } else {\n saturation = 1 - (minimum/maximum);\n }\n \n //Find brightness\n brightness = maximum;\n \n //Convert hue to degrees\n if (hue > 0){\n hue = hue*(180/Math.PI);\n } else {\n hue = 360 + (hue*(180/Math.PI));\n }\n \n //Print result to console\n print(\"RGB(\" + red + \", \" + green + \", \" + blue + \") = HSB(\" + Math.round(hue) + \", \" + Math.round(saturation*100) + \", \" + Math.round(brightness*100) + \")\");\n}",
"function HSL_to_RGB(H, S, L){\n\t\n\tfunction Hue_2_RGB( v1, v2, vH ) //Function Hue_2_RGB\n\t{\n\t if ( vH < 0 )\n\t vH += 1\n\t if ( vH > 1 )\n\t vH -= 1\n\t if ( ( 6 * vH ) < 1 )\n\t return ( v1 + ( v2 - v1 ) * 6 * vH )\n\t if ( ( 2 * vH ) < 1 )\n\t return ( v2 )\n\t if ( ( 3 * vH ) < 2 )\n\t return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vH ) * 6 )\n\t \n\t return ( v1 )\n\t}\n\t\n\t H = H / 360;\n S = S / 100;\n L = L / 100;\n\t\t\n\tif ( S == 0 ) //HSL values = 0 � 1\n\t{\n\t R = L * 255; //RGB results = 0 � 255\n\t G = L * 255;\n\t B = L * 255;\n\t}\n\telse\n\t{\n\t if ( L < 0.5 )\n\t \t\tvar_2 = L * ( 1 + S );\n\t else\n\t \t\tvar_2 = ( L + S ) - ( S * L );\n\t\n\t var_1 = 2 * L - var_2;\n\t\n\t R = 255 * Hue_2_RGB( var_1, var_2, H + ( 1 / 3 ) );\n\t G = 255 * Hue_2_RGB( var_1, var_2, H );\n\t B = 255 * Hue_2_RGB( var_1, var_2, H - ( 1 / 3 ) );\n\t}\n\t\n\tRGBcolor = {};\n\tRGBcolor.R = parseInt(R);\n\tRGBcolor.G = parseInt(G);\n\tRGBcolor.B = parseInt(B);\n\treturn RGBcolor;\n\t\n}",
"function RGB_to_HSL(R, G, B){\n\t\n\tvar_R = ( R / 255 ); //Where RGB values = 0 � 255\n\tvar_G = ( G / 255 );\n\tvar_B = ( B / 255 );\n\t\n\tvar_Min = Math.min( var_R, var_G, var_B ); //Min. value of RGB\n\tvar_Max = Math.max( var_R, var_G, var_B ); //Max. value of RGB\n\tdel_Max = var_Max - var_Min; //Delta RGB value\n\t\n\tL = ( var_Max + var_Min ) / 2;\n\t\n\tif ( del_Max == 0 ) //This is a gray, no chroma...\n\t{\n\t H = 0; //HSL results = 0 � 1\n\t S = 0;\n\t}\n\telse //Chromatic data...\n\t{\n\t if ( L < 0.5 )\n\t S = del_Max / ( var_Max + var_Min );\n\t else\n\t S = del_Max / ( 2 - var_Max - var_Min );\n\t\n\t del_R = ( ( ( var_Max - var_R ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t del_G = ( ( ( var_Max - var_G ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t del_B = ( ( ( var_Max - var_B ) / 6 ) + ( del_Max / 2 ) ) / del_Max;\n\t\n\t if ( var_R == var_Max )\n\t H = del_B - del_G;\n\t else if ( var_G == var_Max )\n\t H = ( 1 / 3 ) + del_R - del_B;\n\t else if ( var_B == var_Max )\n\t H = ( 2 / 3 ) + del_G - del_R;\n\t\n\t if ( H < 0 )\n\t H += 1;\n\t if ( H > 1 )\n\t H -= 1;\n\t}\n\tHSLcolor = {};\n\tHSLcolor.H = parseInt(H*360);\n\tHSLcolor.S = parseInt(S*100);\n\tHSLcolor.L = parseInt(L*100);\n\treturn HSLcolor;\n}",
"function rgb2hsb(rgb) {\n var hsb = { h: 0, s: 0, b: 0 };\n var min = Math.min(rgb.r, rgb.g, rgb.b);\n var max = Math.max(rgb.r, rgb.g, rgb.b);\n var delta = max - min;\n hsb.b = max;\n hsb.s = max !== 0 ? 255 * delta / max : 0;\n if (hsb.s !== 0) {\n if (rgb.r === max) {\n hsb.h = (rgb.g - rgb.b) / delta;\n } else if (rgb.g === max) {\n hsb.h = 2 + (rgb.b - rgb.r) / delta;\n } else {\n hsb.h = 4 + (rgb.r - rgb.g) / delta;\n }\n } else {\n hsb.h = -1;\n }\n hsb.h *= 60;\n if (hsb.h < 0) {\n hsb.h += 360;\n }\n hsb.s *= 100 / 255;\n hsb.b *= 100 / 255;\n return hsb;\n }",
"function RGBToHSL_optimized(r, g, b) {\r\n\r\n // Note: multiplication is faster than division\r\n const m = 1 / 255;\r\n r *= m;\r\n g *= m;\r\n b *= m;\r\n\r\n // Note: replace the calls to Math.min and Math.max with 3 if statements\r\n let cmin = r;\r\n let cmax = g;\r\n\r\n if (r > g) {\r\n cmin = g;\r\n cmax = r;\r\n }\r\n\r\n if (b < cmin) cmin = b;\r\n if (b > cmax) cmax = b;\r\n\r\n const delta = cmax - cmin;\r\n\r\n let h = 0;\r\n let s = 0;\r\n let l = (cmax + cmin);\r\n\r\n if (delta > 0) {\r\n\r\n switch (cmax) {\r\n case r:\r\n h = (g - b) / delta + (g < b && 6);\r\n break;\r\n case g:\r\n h = (b - r) / delta + 2;\r\n break;\r\n case b:\r\n h = (r - g) / delta + 4;\r\n break;\r\n }\r\n\r\n h *= 60;\r\n\r\n // Note: abs on an f64 is as easy as flipping a bit\r\n s = 100 * delta / (1 - Math.abs(l - 1));\r\n }\r\n\r\n l *= 50;\r\n\r\n return [h, s, l]\r\n}",
"function wb2rgb(h) {\n var r, g, b, i, p, q;\n i = (h === 1) ? 6 : Math.floor(h * 7);\n p = h * 7 - i;\n q = 1 - p;\n switch (i % 7) {\n case 0: r = 1, g = q, b = 1; break;\n case 1: r = q, g = 0, b = 1; break;\n case 2: r = 0, g = p, b = 1; break;\n case 3: r = 0, g = 1, b = q; break;\n case 4: r = p, g = 1, b = 0; break;\n case 5: r = 1, g = q, b = 0; break;\n case 6: r = q, g = 0, b = 0; break;\n }\n return {\n r: Math.round(r * 255),\n g: Math.round(g * 255),\n b: Math.round(b * 255),\n a: 255\n };\n }",
"function rgbToHsv(r, g, b){\n r = r/255, g = g/255, b = b/255;\n var max = Math.max(r, g, b), min = Math.min(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max == 0 ? 0 : d / max;\n\n if(max == min){\n h = 0; // achromatic\n }else{\n switch(max){\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n\n return [h, s, v];\n }",
"function sixToRgb(s) {\n return s * 51;\n}",
"function RGBA_TO_HSLA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var sum = max + min;\n var h;\n var s;\n var l;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n l = sum / 2;\n\n if (l === 0 || max === min) {\n s = 0;\n } else if (0 < l && l <= 0.5) {\n s = diff / sum;\n } else { // l > 0.5\n s = diff / (2 - sum);\n }\n\n return kolor.hsla(h, s, l, a);\n }",
"function HWB_TO_HSVA() {\n var h = this.h();\n var w = this.w();\n var b = this.b();\n var a = this.a();\n return kolor.hsva(h, 1 - w / (1 - b), 1 - b, a);\n }",
"function RGBA_TO_HSVA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var h;\n var s;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n if (max === 0) {\n s = 0;\n } else {\n s = diff / max;\n }\n\n var v = max;\n return kolor.hsva(h, s, v, a);\n }",
"function HSLA_TO_HSVA() {\n var h = this.h();\n var s = this.s();\n var l = this.l();\n var a = this.a();\n\n l *= 2;\n s *= (l <= 1) ? l : 2 - l;\n var v = (l + s) / 2;\n var sv = (2 * s) / (l + s);\n return kolor.hsva(h, sv, v, a);\n }",
"function rgbToSix(r) {\n return r / 51;\n}",
"function hslToHex(h ,s ,l){\n let rgb = Vibrant.Util.hslToRgb(h, s, l);\n let hex = Vibrant.Util.rgbToHex(rgb[0], rgb[1], rgb[2]);\n // console.log(hex)\n return hex;\n}",
"function rgbToCmy(n) {\n return Math.round((rgbInvert(n) / 255) * 100);\n}",
"function hslToHex(h, s, l) {\n var color = hslToRgb(h, s, l);\n\n color = color.map(function pad(v) {\n\n v = v.toString(16);\n v.length < 2 ? (v = \"0\" + v) : v; // Add zero before hex number to keep constant length of hex color string\n\n return v;\n });\n\n return color;\n }",
"function nm2rgb(h) {\n var wavelength = 380 + h * 400;\n var Gamma = 0.80,\n IntensityMax = 255,\n factor, red, green, blue;\n\n if((wavelength >= 380) && (wavelength < 440)) {\n red = -(wavelength - 440) / (440 - 380);\n green = 0.0;\n blue = 1.0;\n } else if((wavelength >= 440) && (wavelength < 490)) {\n red = 0.0;\n green = (wavelength - 440) / (490 - 440);\n blue = 1.0;\n } else if((wavelength >= 490) && (wavelength < 510)) {\n red = 0.0;\n green = 1.0;\n blue = -(wavelength - 510) / (510 - 490);\n } else if((wavelength >= 510) && (wavelength < 580)) {\n red = (wavelength - 510) / (580 - 510);\n green = 1.0;\n blue = 0.0;\n } else if((wavelength >= 580) && (wavelength < 645)) {\n red = 1.0;\n green = -(wavelength - 645) / (645 - 580);\n blue = 0.0;\n } else if((wavelength >= 645) && (wavelength < 781)) {\n red = 1.0;\n green = 0.0;\n blue = 0.0;\n } else {\n red = 0.0;\n green = 0.0;\n blue = 0.0;\n };\n\n // Let the intensity fall off near the vision limits\n\n if((wavelength >= 380) && (wavelength < 420)){\n factor = 0.3 + 0.7*(wavelength - 380) / (420 - 380);\n } else if((wavelength >= 420) && (wavelength < 701)){\n factor = 1.0;\n } else if((wavelength >= 701) && (wavelength < 781)){\n factor = 0.3 + 0.7*(780 - wavelength) / (780 - 700);\n } else{\n factor = 0.0;\n };\n\n if(red !== 0){\n red = Math.round(IntensityMax * Math.pow(red * factor, Gamma));\n }\n if(green !== 0){\n green = Math.round(IntensityMax * Math.pow(green * factor, Gamma));\n }\n if(blue !== 0){\n blue = Math.round(IntensityMax * Math.pow(blue * factor, Gamma));\n }\n\n return {\n r: red,\n g: green,\n b: blue,\n a: 255\n };\n }",
"function buildHueState(hue, bri, trans) {\n return JSON.stringify({\n on: true,\n bri: bri,\n hue: hue,\n sat: 254,\n transitiontime: trans/100\n })\n}",
"function hexToRGB(h, cell) {\n let r = 0,\n g = 0,\n b = 0;\n let rgb = '';\n h = colorPicker.value;\n // 3 digits\n if (h.length == 4) {\n r = \"0x\" + h[1] + h[1];\n g = \"0x\" + h[2] + h[2];\n b = \"0x\" + h[3] + h[3];\n // 6 digits\n } else if (h.length == 7) {\n r = \"0x\" + h[1] + h[2];\n g = \"0x\" + h[3] + h[4];\n b = \"0x\" + h[5] + h[6];\n }\n rgb = \"rgb(\" + +r + \", \" + +g + \", \" + +b + \")\";\n colorCheck(rgb, cell)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A Track of quaternion keyframe values. | function QuaternionKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrackConstructor.call( this, name, times, values, interpolation );
} | [
"function QuaternionKeyframeTrack( name, times, values, interpolation ) {\n \n KeyframeTrack.call( this, name, times, values, interpolation );\n \n }",
"function Quaternion() {\n this.data = new Float32Array(4);\n this.data[0] = 0;\n this.data[1] = 0;\n this.data[2] = 0;\n this.data[3] = 1;\n }",
"function tracks() {\n var geom = new THREE.TorusGeometry(30,1,16,100,0);\n var material = new THREE.MeshPhongMaterial( {color: \"rgb(0,0,0)\", ambient: \"rgb(0,0,0)\"});\n var tracks = new THREE.Mesh(geom, material);\n tracks.rotation.x = (Math.PI/2);\n tracks.position.set(0,-50,0);\n return tracks;\n}",
"addKeyframeTrack(name){\n this.setKeyframeTrack(name, new AKeyframeTrack({name: name, title: name}))\n }",
"static Zero() {\n return new Quaternion(0.0, 0.0, 0.0, 0.0);\n }",
"static LookRotation(forward, up = preallocatedVariables_1$2.MathTmp.staticUp) {\n const forwardNew = Vector3_1$5.Vector3.Normalize(forward);\n const right = Vector3_1$5.Vector3.Normalize(Vector3_1$5.Vector3.Cross(up, forwardNew));\n const upNew = Vector3_1$5.Vector3.Cross(forwardNew, right);\n const m00 = right.x;\n const m01 = right.y;\n const m02 = right.z;\n const m10 = upNew.x;\n const m11 = upNew.y;\n const m12 = upNew.z;\n const m20 = forwardNew.x;\n const m21 = forwardNew.y;\n const m22 = forwardNew.z;\n const num8 = m00 + m11 + m22;\n const quaternion = new Quaternion();\n if (num8 > 0) {\n let num = Math.sqrt(num8 + 1);\n quaternion.w = num * 0.5;\n num = 0.5 / num;\n quaternion.x = (m12 - m21) * num;\n quaternion.y = (m20 - m02) * num;\n quaternion.z = (m01 - m10) * num;\n return quaternion;\n }\n if (m00 >= m11 && m00 >= m22) {\n const num7 = Math.sqrt(1 + m00 - m11 - m22);\n const num4 = 0.5 / num7;\n quaternion.x = 0.5 * num7;\n quaternion.y = (m01 + m10) * num4;\n quaternion.z = (m02 + m20) * num4;\n quaternion.w = (m12 - m21) * num4;\n return quaternion;\n }\n if (m11 > m22) {\n const num6 = Math.sqrt(1 + m11 - m00 - m22);\n const num3 = 0.5 / num6;\n quaternion.x = (m10 + m01) * num3;\n quaternion.y = 0.5 * num6;\n quaternion.z = (m21 + m12) * num3;\n quaternion.w = (m20 - m02) * num3;\n return quaternion;\n }\n const num5 = Math.sqrt(1 + m22 - m00 - m11);\n const num2 = 0.5 / num5;\n quaternion.x = (m20 + m02) * num2;\n quaternion.y = (m21 + m12) * num2;\n quaternion.z = 0.5 * num5;\n quaternion.w = (m01 - m10) * num2;\n return quaternion;\n }",
"static get Identity() {\n return new Quaternion(0.0, 0.0, 0.0, 1.0);\n }",
"getClassName() {\n return 'Quaternion';\n }",
"get ticksPerQuarterNote() {\n\t\treturn this._ticksPerQuarterNote;\n\t}",
"get eulerAngles() { return new Graphic_1.GL.Euler().setFromQuaternion(this).toVector3(); }",
"equals(otherQuaternion) {\n return (otherQuaternion &&\n this.x === otherQuaternion.x &&\n this.y === otherQuaternion.y &&\n this.z === otherQuaternion.z &&\n this.w === otherQuaternion.w);\n }",
"parseTrack() {\n\t\tlet done = false;\n\t\tif (this.fetchString(4) !== 'MTrk') {\n\t\t\tconsole.log('ERROR: No MTrk');\n\t\t\tthis.error = { code: 4, pos: ppos, msg: 'Failed to find MIDI track.' };\n\t\t\treturn;\n\t\t}\n\t\t// this.trks.push(new MIDItrack());\n\t\tlet len = this.fetchBytes(4);\n\t\t// console.log('len = '+len);\n\t\twhile (!done) {\n\t\t\tdone = this.parseEvent();\n\t\t}\n\t\tthis.labelCurrentTrack();\n\t\t// console.log('Track '+tpos);\n\t\t// console.log(this.trks[tpos].events);\n\t\t// console.log(trackDuration);\n\t\tif (trackDuration > this.duration) {\n\t\t\tthis.duration = trackDuration;\n\t\t}\n\t\ttrackDuration = 0;\n\t\tnoteDelta.fill(0);\n\t}",
"scale(value) {\n return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);\n }",
"len() {\n return quat.length(this);\n }",
"static FromArray(array, offset = 0) {\n return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }",
"function dir2quat(dir) {\n\tvar ret = quat.create();\n\tvec3.normalize(vectornorm,dir);\n\tvec3.cross(vectorcross,vectormasterdir,vectornorm);\n\tif (vec3.sqrLen(vectorcross) < epsilon*epsilon) {\n\t\tif (dir[1] >= 0)\n\t\t\tquat.set(ret,0,0,0,1);\n\t\telse\n\t\t\tquat.set(ret,1,0,0,0); // some quat at 180\n\t} else {\n\t\tvec3.normalize(vectorcross,vectorcross);\n\t\tvar d = vec3.dot(vectormasterdir,vectornorm);\n\t\tvar ang = Math.acos(d);\n\t\tquat.setAxisAngle(ret,vectorcross,ang);\n\t}\n\treturn ret;\n}",
"set ticksPerQuarterNote(v) {\n\t\t// Prevent invalid values from being set.\n\t\tif (!v) {\n\t\t\tthrow new Error(`Invalid value for ticksPerQuarterNote: ${v}.`);\n\t\t}\n\n\t\tthis._ticksPerQuarterNote = v;\n\t}",
"function MusicTimeSignatureInputComponent() {\n this.type = 'timeSignature';\n }",
"updateAudioTrack(state, track) {\n\t\tVue.set(state.self.tracks, 'audio', track)\n\t}",
"conjugate() {\n const result = new Quaternion(-this.x, -this.y, -this.z, this.w);\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To add all parent directories of the given filePath to the given Ancestors object until an parent is reached which already exists in the given Paths object | function traverseUp( filePath, Paths, Ancestors ){
var index, start, end,
split = filePath.split('^');
//Throw an error if there is more than one ^ in the given filePath
if( split.length > 2 ){
throw new Error('Invalid File Path : ' + filePath)
}
//Get the start directory and the end string
start = path.parse( split[0] ).dir;
end = split[1];
//If Ancestors has a Base which does not equal the current start directory, then collect all stored Ancestors values
if( Ancestors.Base && Ancestors.Base !== start ){
collectAncestors( Ancestors, Paths );
}
//Add each parent directory until one is reached that has already been added
while( walkIfUnique( start, end, Paths, Ancestors ) ){
//Get the parent directory
start = path.parse( start ).dir;
}
} | [
"function collectAncestors( Ancestors, Paths ){\n\tAncestors.Starts.forEach(function( start, i ){\n\t\tAncestors.Ends[i].forEach(function( end ){\n\t\t\taddIfUnique( path.normalize(path.resolve(start+end)), Paths );\n\t\t})\n\t});\n\tAncestors.Starts = [];\n\tAncestors.Ends = [];\n\tAncestors.Base = '';\n}",
"function traverse(basedir, ancestors, current, fn) {\n var abs, stat;\n\n abs = path.join(basedir, ancestors, current);\n stat = fs.statSync(abs);\n\n if (stat.isDirectory()) {\n ancestors = ancestors ? path.join(ancestors, current) : current;\n fs.readdirSync(abs).forEach(function (child) {\n traverse(basedir, ancestors, child, fn);\n });\n }\n\n if (stat.isFile()) {\n fn(basedir, ancestors, current);\n }\n}",
"ancestors(path) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n reverse = false\n } = options;\n var paths = Path.levels(path, options);\n\n if (reverse) {\n paths = paths.slice(1);\n } else {\n paths = paths.slice(0, -1);\n }\n\n return paths;\n }",
"function walkIfUnique( start, end, Paths, Ancestors ){\n\tvar index;\n\n\tif( Paths.indexOf( path.normalize(path.resolve(start + '/' + end)) ) >= 0 ){\n\t\treturn false;\n\t}\n\t\n\tindex = Ancestors.Starts.indexOf( start );\n\tif( index === -1 ){\n\t\tAncestors.Starts.push( start );\n\t\tAncestors.Ends.push( [end] );\n\t}\n\telse{\n\t\tif( Ancestors.Ends[index].indexOf( end ) >= 0 ){\n\t\t\treturn false;\n\t\t}\n\t\tAncestors.Ends[index].push( end );\n\t}\n\t\n\t//Store the start string as the 'Base' if there is not already a base\n\tif( !Ancestors.Base ) Ancestors.Base = start;\n\t\n\treturn true;\n}",
"*ancestors(root, path) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n for (var p of Path.ancestors(path, options)) {\n var n = Node$1.ancestor(root, p);\n var entry = [n, p];\n yield entry;\n }\n }",
"function getFileParents() {\n var gSheetId = createSheetAndAddToFolder(),\n file = DriveApp.getFileById(gSheetId), \n gSheetParentsIt = file.getParents(),\n parentFolder;\n while(gSheetParentsIt.hasNext()) {\n parentFolder = gSheetParentsIt.next();\n Logger.log(parentFolder.getName());\n }\n}",
"function goThroughSubdirs(err, subdirs) {\n if (err) throw err;\n subdirs.forEach(populateSubrfid); \n}",
"findFsParents () {\n for (const path of this.linkTargets) {\n const node = this.cache.get(path)\n if (!node.parent && !node.fsParent) {\n for (let p = dirname(path); p;) {\n if (this.cache.has(p)) {\n node.fsParent = this.cache.get(p)\n p = null\n } else {\n // walk up the tree until p === dirname(p)\n const pp = dirname(p)\n if (pp === p)\n p = null\n else\n p = pp\n }\n }\n }\n }\n }",
"function addIfUnique( filePath, Paths ){\n\tif( Paths.indexOf( filePath ) === -1 ){\n\t\tPaths.push( filePath );\n\t}\n}",
"function addPath(filePath) {\n if (relativePath) {\n if (inRelativePath(filePath)) {\n const relative = path.relative(relativePath, filePath);\n result.push(relative);\n }\n }\n else {\n result.push(filePath);\n }\n }",
"function _expandPaths(paths, callback) {\n var expandedPaths = [],\n basedir = this.basedir;\n \n function notHidden(file) {\n return !reHidden.test(file);\n }\n \n async.forEach(\n paths,\n function(inputPath, itemCallback) {\n debug('expanding path: ' + inputPath);\n \n // resolve the path against the base directory\n var realPath = path.resolve(basedir, inputPath);\n \n // first attempt to read the path as a directory\n fs.readdir(realPath, function(err, files) {\n // if it errored, then do an exists check on the file\n if (err) {\n path.exists(realPath, function(exists) {\n if (exists) {\n debug('found file: ' + realPath);\n expandedPaths.push(inputPath);\n } // if\n \n itemCallback();\n });\n }\n // otherwise, add each of the valid files in the directory to the expanded paths\n else {\n debug('looking for files in: ' + realPath);\n files.filter(notHidden).forEach(function(file) {\n var stats = fs.statSync(path.join(realPath, file));\n \n if (stats.isFile()) {\n expandedPaths.push(path.join(inputPath, file));\n }\n });\n \n // trigger the callback\n itemCallback();\n }\n });\n },\n function(err) {\n callback(err, expandedPaths);\n }\n );\n}",
"function insertNode(currentPath, remainingPath, parent, firstLevel) {\n var remainingDirectories = remainingPath.split('/');\n var nodeName = remainingDirectories[0];\n var newPath = firstLevel ? nodeName : (currentPath + '/' + nodeName);\n // console.log('=== inserting: '+ nodeName);\n if (remainingDirectories.length === 1) { // actual file to insert\n // console.log('last item');\n var node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n return;\n }\n else {\n // path consists of multiple directories and a file\n // console.log('not last item')\n var node = findAndGetChild(nodeName, parent);\n remainingDirectories.shift();\n var pathToGo = remainingDirectories.join('/');\n if (node) {\n // directory already exists\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n else {\n // create the directory and insert on it\n node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n }\n}",
"listOfAncestorsToBeLoadedForLevel(numGens = 10) {\n let theList = [];\n let maxNum = this.list.length;\n let maxNumInGen = 2 ** numGens;\n let theMax = Math.min(maxNum, maxNumInGen);\n\n let minNum = 1;\n let minNumInGen = 2 ** (numGens - 1);\n let theMin = Math.max(minNum, minNumInGen);\n\n for (var i = theMin; i < theMax; i++) {\n if (this.list[i] && this.list[i] > 0 && thePeopleList[this.list[i]]) {\n let thePeep = thePeopleList[this.list[i]];\n if (thePeep._data.Father && thePeep._data.Father > 0 && theList.indexOf(thePeep._data.Father) == -1) {\n if (thePeopleList[thePeep._data.Father]) {\n // father already exists, so don't need to re-load him\n } else {\n theList.push(thePeep._data.Father);\n }\n }\n if (thePeep._data.Mother && thePeep._data.Mother > 0 && theList.indexOf(thePeep._data.Mother) == -1) {\n if (thePeopleList[thePeep._data.Mother]) {\n // Mother already exists, so don't need to re-load her\n } else {\n theList.push(thePeep._data.Mother);\n }\n }\n\n // condLog(\"--> PUSHED !\",thisAncestor.ahnNum, thisAncestor.person._data.Id);\n }\n }\n condLog(\"listOfAncestorsToBeLoadedForLevel has \", theList.length, \" ancestors.\");\n return theList;\n }",
"pathList(){\n let pathList = []\n let current = this\n while(current){\n if(current.pathId()) pathList.unshift(current.pathId())\n current = current.parent\n }\n return pathList\n }",
"function makePathsRelative (dirPath, ramlPaths) {\n return ramlPaths.map((pth) => {\n return path.relative(dirPath, pth)\n })\n}",
"addToTree({ state, commit, getters }, { parentPath, newDirectory }) {\n // If this directory is not the root directory\n if (parentPath) {\n // find parent directory index\n const parentDirectoryIndex = getters.findDirectoryIndex(parentPath);\n\n if (parentDirectoryIndex !== -1) {\n // add a new directory\n commit('addDirectories', {\n directories: newDirectory,\n parentId: state.directories[parentDirectoryIndex].id,\n });\n\n // update parent directory property\n commit('updateDirectoryProps', {\n index: parentDirectoryIndex,\n props: {\n hasSubdirectories: true,\n showSubdirectories: true,\n subdirectoriesLoaded: true,\n },\n });\n } else {\n commit('fm/messages/setError', { message: 'Directory not found' }, { root: true });\n }\n } else {\n // add a new directory to the root of the disk\n commit('addDirectories', {\n directories: newDirectory,\n parentId: 0,\n });\n }\n }",
"function buildTree(paths) {\n\n var i,path, subTree;\n\n subTree = tree;\n // JS5 forEach loop\n paths.forEach(function(path /*, index, originalArray */) {\n\n // Loop over each directory in the given path\n path.split('/').forEach(function(folder /*, index, originalArray */) {\n // Check to see if this folder was initialized already or not\n if (!subTree[folder] && folder !== \".\") {\n\n }\n });\n\n });\n for (i = 0; path = paths[i]; ++i) {\n var pathParts = path.split('/');\n var subObj = tree;\n for (var j = 0, folderName; folderName = pathParts[j]; ++j) {\n if (!subObj[folderName] && folderName != '.') {\n subObj[folderName] = j < pathParts.length - 1 ? {} : null;\n }\n subObj = subObj[folderName];\n }\n }\n return tree;\n }",
"function getEarliestCommonAncestorFrom(paths) {\n\t return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {\n\t var earliest = undefined;\n\t var keys = t.VISITOR_KEYS[deepest.type];\n\n\t var _arr = ancestries;\n\t for (var _i = 0; _i < _arr.length; _i++) {\n\t var ancestry = _arr[_i];\n\t var path = ancestry[i + 1];\n\n\t // first path\n\t if (!earliest) {\n\t earliest = path;\n\t continue;\n\t }\n\n\t // handle containers\n\t if (path.listKey && earliest.listKey === path.listKey) {\n\t // we're in the same container so check if we're earlier\n\t if (path.key < earliest.key) {\n\t earliest = path;\n\t continue;\n\t }\n\t }\n\n\t // handle keys\n\t var earliestKeyIndex = keys.indexOf(earliest.parentKey);\n\t var currentKeyIndex = keys.indexOf(path.parentKey);\n\t if (earliestKeyIndex > currentKeyIndex) {\n\t // key appears before so it's earlier\n\t earliest = path;\n\t }\n\t }\n\n\t return earliest;\n\t });\n\t}",
"function get_parent_urls(path) {\n\tvar templates = []\n\tvar path_bits = path.split('/').splice(1)\n\n\tfunction get_frame_chunks(path_bits) {\n\t\t\n\t\tif ( path_bits.length === 0 ) {\n\t\t\t// Reverse them to be in order of topmost parent to last parent\n\t\t\treturn templates\n\t\t}\n\t\t\n\t\tpath_bits.splice(path_bits.length - 1)\n\t\ttemplates.unshift('/' + path_bits.join('/'))\n\t\treturn get_frame_chunks(path_bits) \n\t\t\n\t}\n\treturn get_frame_chunks(path_bits) \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add boxes to Lines GameField | function addBoxesToLineIds(id){
var BoxesNumber = Number(Boxes);
var BoxesArray = [];
var someNumber = 0;
if (id<BoxesNumber){
/**
* fill only Horizontal lines
*/
for (var i=(id*BoxesNumber);i<(BoxesNumber+(id*BoxesNumber));i++){
BoxesArray.push(GameBoxes[i]);
}
} else if ((id>=BoxesNumber)&&(id<BoxesNumber*2)){
/**
* fill only Vertical lines
*/
for (var i=0;i<BoxesNumber;i++){
someNumber = (i*BoxesNumber)+(id-BoxesNumber);
BoxesArray.push(GameBoxes[someNumber]);
}
} else if (id==BoxesNumber*2) {
for (var i=0;i<BoxesNumber;i++){
someNumber = (BoxesNumber+1)*i;
BoxesArray.push(GameBoxes[someNumber]);
}
} else {
for (var i=0;i<BoxesNumber;i++){
someNumber = (BoxesNumber-1)*(i+1);
BoxesArray.push(GameBoxes[someNumber]);
}
}
GameLines[id].boxesIds = BoxesArray;
} | [
"fields() {\n // sets \"this.current\" to fields\n this.current = \"fields\";\n // draws the grass\n background(104, 227, 64);\n \n // draws a path\n this.path(width/2, 0);\n \n // draws a pile of rocks or a well\n if (this.well) {\n this.makeWell();\n } else {\n this.rocks();\n }\n\n // this draws a flower patch\n for (let i = 0; i < 200; i += 25) {\n for (let j = 0; j < 100; j += 20) {\n this.flower(i + 100, j + 450);\n }\n }\n }",
"function drawBoxes(boxes) {\n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#000000',\n strokeWeight: 2,\n map: map\n });\n }\n}",
"function drawBoxes(boxes) {\n console.log(boxes);\n \n boxpolys = new Array(boxes.length);\n for (var i = 0; i < boxes.length; i++) {\n boxpolys[i] = new google.maps.Rectangle({\n bounds: boxes[i],\n fillOpacity: 0,\n strokeOpacity: 1.0,\n strokeColor: '#FF0000',\n strokeWeight: 1,\n map: map\n });\n }\n }",
"grow()\n {\n let box = this.createSnakeBox();\n this.placeBoxAtEnd(box);\n this.boxes.push(box);\n }",
"_addParts() {\n this._wheel.anchor.set(0.5, 1);\n this._wheel.y = + 5;\n\n this._flap.anchor.set(0.5);\n this._flap.y = -this._wheel.height + 60;\n \n this._prompt.y = -this._wheel.height - 70;\n this._particles.y = -(this._wheel.height / 2);\n\n this.addChild(this._particles);\n this.addChild(this._wheel);\n this._addSectors();\n this.addChild(this._flap);\n this.addChild(this._prompt);\n\n this.idleSpin();\n }",
"function addShapes() {\n scene.add(camera);\n scene.add(ambientLight);\n}",
"function ConstructHitBoxes() {\n\t\tfunction CreateHitBox(w, h, d, x, y, z, rotx = 0.0, roty = 0.0, rotz = 0.0, area = \"\") {\n\t\t\tvar geo = new THREE.BoxGeometry(w, h, d);\n\t\t\tvar mat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF });\n\t\t\tmat.transparent = true;\n\t\t\tmat.opacity = 0.0;\n\n\t\t\tvar cube = new THREE.Mesh(geo, mat);\n\t\t\tcube.name = \"hitbox\";\n\t\t\tcube[\"selected\"] = false;\n\t\t\tcube[\"hovering\"] = true;\n\t\t\tcube[\"area\"] = area;\n\t\t\tcube.frustumCulled = false;\n\t\t\tscene.add(cube);\n\n\n\t\t\tcube.rotation.x = rotx;\n\t\t\tcube.rotation.y = roty;\n\t\t\tcube.rotation.z = rotz;\n\n\t\t\tcube.position.x = x;\n\t\t\tcube.position.y = y;\n\t\t\tcube.position.z = z;\n\n\t\t}\n\n\t\tCreateHitBox(3.5, 3.2, 0.1, 0.01, 0.5, 1.2, 0.1, 0, 0.0, \"front\"); // front\n\t\tCreateHitBox(3.4, 2.6, 0.1, 0.2, 0.6, -0.17, 0.2, 0.0, 0.0, \"back\"); // back\n\t\tCreateHitBox(0.5, 2.5, 2.4, -1.90, 0.1, 0.4, 0, 0, 0.21, \"frills\"); // left\n\t\tCreateHitBox(0.5, 2.7, 2.4, 2.095, 0.80, 0.4, 0, 0, 0, \"frills\"); // right\n\t\tCreateHitBox(3.4, 1.0, 2.4, 0.2, -1.0, 0.4, 0.0, 0.0, 0.1, \"frills\"); // bottom\n\t}",
"function updateBoxes(newFrame) {\n\t\tconsole.log(newFrame);\n\t\tclearCustomBoxes();\n\t\tframe = newFrame;\n\n\t\tupdateStandardBoxes(newFrame);\n\t\tvar boxesData = boxes.custom[frame];\n\t\tif (boxesData != null) {\t\t\t//creates custom boxes\n\t\t\tfor (var i = 0; i < boxesData.length; i++) {\n\t\t\t\tmakeCustomBox(boxesData[i]);\n\t\t\t}\n\t\t}\n\t}",
"buildTeamBoxes(){\n new TeamBox(this, \"team goes here\", 80, 70).create()\n .setInteractive().on('pointerup', ()=>{\n this.scene.sleep('battle')\n this.scene.launch('switch')\n },this);\n new TeamBox(this, \"enemy team goes here\", 530, 70).create();\n }",
"function addBox(lat1, lng1, lat2, lng2, color) {\n var loc1=new google.maps.LatLng(lat1, lng1)\n var loc2=new google.maps.LatLng(lat2, lng2)\n var rectangle = new google.maps.Rectangle({\n strokeColor: color,\n strokeOpacity: 0.7,\n strokeWeight: 1,\n fillColor: color,\n fillOpacity: 0.19,\n map: map,\n bounds: new google.maps.LatLngBounds(loc1, loc2)\n });\n var index = makeIndex(lat1, lng1, lat2, lng2)\n boxes[index] = rectangle\n}",
"function prepareWalls() {\n\n // Retrieve the lines from the editor\n linesArray = getLinesFromEditor();\n for (var i = 0; i < linesArray.length; i++) {\n\n // Sets the needed variables\n var line = linesArray[i],\n x1 = line.x1,\n x2 = line.x2,\n y1 = line.y1,\n y2 = line.y2,\n xStart = line.left,\n xStop = line.width,\n zStart = line.top,\n zStop = line.height,\n floorNumber = line.floorNumber,\n material = line.material;\n\n // Checks if the line is drawn from bottom-left corner to top-right corner\n if ((x2 > x1 && y2 < y1) || (x2 < x1 && y2 > y1)) {\n zStart = line.top + line.height,\n zStop = -line.height;\n }\n\n // Refactors the values to match the scene setup\n xStart /= refactor,\n zStart /= refactor,\n xStop /= refactor,\n zStop /= refactor;\n\n // Calls the drawWall method\n drawWall(xStart, zStart, xStop, zStop, floorNumber, material);\n }\n}",
"function mouseClicked(){\n coll.push(new collectionLines([mouseX, mouseY],30));\n}",
"function drawField() {\n\n // Do not stroke arrows.\n field.noStroke();\n \n // Iterate through the field.\n for (var x = 0; x < 14; x += ARROW_STEP) {\n for (var y = 0; y < 8; y += ARROW_STEP) {\n\n var k = 20;\n \n // Calculate the field at coordinates (x, y).\n switch (operation) {\n case \"left\":\n vectors.arrow_field.setMag(RIGHT_E_FIELD, p$.PI);\n break;\n case \"right\":\n vectors.arrow_field.setMag(RIGHT_E_FIELD, 0);\n break;\n default:\n var f1 = calculateField(q1.position, {x: x, y: y}, Q1_CHARGE * Q_UNITS);\n var f2 = calculateField(q2.position, {x: x, y: y}, Q2_CHARGE * Q_UNITS);\n k = effectOnPoint(f1, Q1_CHARGE) + effectOnPoint(f2, Q2_CHARGE);\n vectors.arrow_field.set(f1);\n vectors.arrow_field.add(f2);\n }\n \n // Draw arrow field.\n field.fill(fieldColor(k));\n drawArrow(field, x, y, vectors.arrow_field.angle());\n\n }\n }\n\n ;\n // Redraw.\n calculate = true;\n\n}",
"function addFields() {\r\n\taddFieldCounter++;\r\n\r\n\t//make the dashes the same number of the chosen fruit:\r\n\tvar fruitLengthSentence = document.getElementById(\"output\");\r\n\tdocument.getElementById(\"categoryTitle\").innerHTML = \"The Category is: \" + selectRandomCategory;\r\n\tdocument.getElementById(\"categoryTitle\").style.fontSize = \"large\";\r\n\r\n\tdocument.getElementById(\"output\").innerHTML = \"The Length of the category is: \" + categoryLength;\r\n\tdocument.getElementById(\"output\").style.fontSize = \"large\";\r\n\r\n\tdisplayFields();\r\n\tvar str = [];\r\n\tvar x;\r\n\tfor (var i = 0; i < categoryLength; i++) {\r\n\t\tinputField[i] = document.createElement(\"INPUT\");\r\n\t\tvar x = document.getElementById(\"textBox\").appendChild(inputField[i]).size = \"5\"; //set the physical size of each field\r\n\t\tdocument.getElementById(\"textBox\").appendChild(inputField[i]).readOnly = true; // make the field boxes read-only\r\n\t}\r\n}",
"drawToolRow() {\n let $Div = $('<div />').attr({ id: 'top-row'});\n let $MineCount = $('<input/>').attr({ type: 'text', id: 'mine-count', name: 'mine-count', readonly: true}).val(25);\n let $Timer = $('<input/>').attr({ type: 'text', id: 'timer', name: 'timer', readonly: true}).val('0000');\n let $GridSize = $('<input/>').attr({ type: 'text', id: 'grid-size', name: 'grid-size'}).val(15); // value is the size of the grid. Always a square\n let $Reset = $('<input />').attr({ type: 'button', id: 'reset-button'}).val('Reset').addClass('reset-button');\n let $Music= $('<input />').attr({ type: 'button', id: 'music-button'}).val('Music').addClass('music-button');\n let $gameScreen = $('#game-screen');\n\n $Div.append($MineCount).append($Timer).append($GridSize).append($Reset).append($Music);\n $gameScreen.prepend($Div);\n \n }",
"function addLabelAndBox(name) {\n addLabel(name);\n addTextBox(name);\n}",
"function addLinesAcrossLeftRight() {\n\n\tconst corners = [\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: 0\n\t\t},\n\t\t{\n\t\t\tx: editorSize, \n\t\t\ty: editorSize\n\t\t},\n\t\t{\n\t\t\tx: 0, \n\t\t\ty: editorSize\n\t\t},\n\t];\n\n\tcorners.forEach(linesAcrossLRForCorner);\n}",
"createInteractionZones() {\n this.r3a1_graphics = this.add.graphics({fillStyle: {color: 0xFFFFFF, alpha: 0.0}});\n //this.graphicsTest = this.add.graphics({fillStyle: {color: 0x4F4F4F, alpha: 1.0}});\n //TOP ZONES\n //xpos ypos x y\n this.r3a1_increaseAssets = new Phaser.Geom.Rectangle(425,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseAssets);\n\n this.r3a1_decreaseAssets = new Phaser.Geom.Rectangle(425,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseAssets);\n\n this.r3a1_increaseLiabilities = new Phaser.Geom.Rectangle(525,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseLiabilities);\n\n this.r3a1_decreaseLiabilities = new Phaser.Geom.Rectangle(525,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseLiabilities);\n\n this.r3a1_increaseStock = new Phaser.Geom.Rectangle(625,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseStock);\n\n this.r3a1_decreaseStock = new Phaser.Geom.Rectangle(625,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseStock);\n\n this.r3a1_increaseRevenue = new Phaser.Geom.Rectangle(725,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseRevenue);\n\n this.r3a1_decreaseRevenue = new Phaser.Geom.Rectangle(725,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseRevenue);\n\n this.r3a1_increaseExpenses = new Phaser.Geom.Rectangle(825,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseExpenses);\n\n this.r3a1_decreaseExpenses = new Phaser.Geom.Rectangle(825,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseExpenses);\n\n this.r3a1_increaseDividend = new Phaser.Geom.Rectangle(925,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseDividend);\n\n this.r3a1_decreaseDividend = new Phaser.Geom.Rectangle(925,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseDividend);\n\n //this.r3a1_holeInteract = new Phaser.Geom.Rectangle(1300, 400, 100, 100);\n //this.r3a1_graphics.fillRectShape(this.r3a1_holeInteract);\n\n this.r3a1_exitDoor_zone = new Phaser.Geom.Rectangle(113,320,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_exitDoor_zone);\n }",
"function createBoxes(amount) {\n for (let i = 0; i < amount; i += 1) {\n const newDiv = document.createElement('div');\n newDiv.style.height = `${30 + i * 10}px`;\n newDiv.style.width = `${30 + i * 10}px`;\n newDiv.style.backgroundColor = colorForBoxes();\n getBoxes.appendChild(newDiv);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME: buildDialogTable DESCRIPTION: builds and defines structure of dialog displayed when user mouse overs a Work Order event/transaction CALLED FROM: drawChart CALLS: n/a REQUIRES: info a singular JSON object containing all the value added information relating to the WO transaction selected on teh upper interactive chart RETURNS: n/a | function buildDialogTable(info){
// declare local array defininf table column header names
var rowSubjects = [ "Item Description:" , "MGBC:" , "SSCC:" , "Local Pallet ID:" , "BBD:" , "Date and Time:" , "Transaction Type:" , "Quantity:" , "UOM:"];
// append a simple HTML table to the new instance of dialog created shen user mouse overs WO transaction
dialog.append("table")
.attr( "class" , "dialogTable dialogTable-"+WONumber )
.attr( "id" , "dialogTable-"+WONumber );
// append a table body to the new table
d3.selectAll( ".dialogTable-"+WONumber )
.append( "tbody" )
.attr( "class" , "dialogTable tbody-"+WONumber );
// for each fieldname element in the local array
rowSubjects.forEach(function(d,i){
// append a new table row
d3.selectAll(".dialogTable.tbody-"+WONumber )
.append("tr")
.attr("width" , "100%")
.attr("class" , "dialogTableRow Row item-"+i+"-"+WONumber);
// append a new table data cell. the is the left hand column of two in the table. This column lists the values in array rowSubjects
d3.selectAll(".dialogTableRow.Row.item-"+i+"-"+WONumber)
.append("td")
.attr("width" , "50%")
.attr("class", "dialogfillers")
.style("font-weight" ,"bold")
.text(rowSubjects[i]);
// append a new table data cell. the is the left hand column of two in the table. This column lists the values specific to the sleected WO transaction relating to the values in array rowSubjects
d3.selectAll(".dialogTableRow.Row.item-"+i+"-"+WONumber)
.append("td")
.attr("width" , "50%")
.attr("class", "dialogfillers")
.style("text-anchor" ,"end")
.text(function(){
switch (d) {
case "Item Description:":
return info["Item Description"];
break;
case "MGBC:":
return info["MGBC"];
break;
case "FG Item:":
return info["MGBC"];
break;
case "SSCC:":
return info["SSCC"];
break;
case "Local Pallet ID:":
return info["Local Pallet ID"];
break;
case "BBD:":
return info["BBD"];
break;
case "Date and Time:":
return info["Date and Time"];
break;
case "Transaction Type:":
return info["Transaction Type"];
break;
case "Quantity:":
return info["Quantity"];
break;
case "UOM:":
return info["UOM"];
break;
}
})
});
return;
}// end function buildDialogTable(d) | [
"function buildInfoTable(rows) {\n var itable = { \n rows: rows,\n dataShape: {\n fieldDefinitions: {\n value: {aspects: {}, baseType: \"STRING\", name: \"value\" }, \n pressed: {aspects: {}, baseType: \"BOOLEAN\", name: \"pressed\" }\n }\n }\n }; \n return itable;\n }",
"function buildInfoTemplate(popupInfo) {\n var json = {\n content: \"<table>\"\n };\n\n dojo.forEach(popupInfo.fieldInfos, function (field) {\n if (field.visible) {\n json.content += \"<tr><td valign='top'>\" + field.label + \": <\\/td><td valign='top'>${\" + field.fieldName + \"}<\\/td><\\/tr>\";\n }\n });\n json.content += \"<\\/table>\";\n return json;\n}",
"function printInfoVoucher(tableInfo, report, docNumber, date, totalPages) {\n\n //Title\n tableRow = tableInfo.addRow();\n tableRow.addCell(getValue(param, \"voucher\", \"chinese\"), \"heading1 alignCenter\", 11);\n\n tableRow = tableInfo.addRow();\n tableRow.addCell(getValue(param, \"voucher\", \"english\"), \"heading2 alignCenter\", 11);\n\n\n //Date and Voucher number\n var d = Banana.Converter.toDate(date);\n var year = d.getFullYear();\n var month = d.getMonth()+1;\n var day = d.getDate();\n\n tableRow = tableInfo.addRow();\n \n var cell1 = tableRow.addCell(getValue(param, \"page\", \"chinese\") + \" \" + currentPage + \" / \" + totalPages, \"\", 1);\n cell1.addParagraph(getValue(param, \"page\", \"english\"), \"\");\n\n var cell2 = tableRow.addCell(\"\", \"alignRight border-top-double\", 1);\n cell2.addParagraph(getValue(param, \"date\", \"chinese\") + \": \");\n\n var cell3 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell3.addParagraph(year, \"text-black\");\n\n var cell4 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell4.addParagraph(getValue(param, \"year\", \"chinese\"), \"\");\n cell4.addParagraph(getValue(param, \"year\", \"english\"), \"\");\n \n var cell5 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell5.addParagraph(month, \"text-black\");\n\n var cell6 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell6.addParagraph(getValue(param, \"month\", \"chinese\"), \"\");\n cell6.addParagraph(getValue(param, \"month\", \"english\"), \"\");\n\n var cell7 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell7.addParagraph(day, \"text-black\");\n\n var cell8 = tableRow.addCell(\"\", \"alignCenter border-top-double\", 1);\n cell8.addParagraph(getValue(param, \"day\", \"chinese\"), \"\");\n cell8.addParagraph(getValue(param, \"day\", \"english\"), \"\");\n\n var cell9 = tableRow.addCell(\"\", \"\", 1); \n cell9.addParagraph(\" \", \"\");\n\n var cell10 = tableRow.addCell(\"\", \"padding-left alignCenter\", 1);\n cell10.addParagraph(getValue(param, \"voucherNumber\", \"chinese\"), \"\");\n cell10.addParagraph(getValue(param, \"voucherNumber\", \"english\"), \"\");\n \n var cell11 = tableRow.addCell(\"\", \"padding-left\", 1);\n cell11.addParagraph(\" \", \"\");\n cell11.addParagraph(docNumber, \"text-black\");\n\n report.addParagraph(\" \", \"\");\n}",
"function CreateTblRow(tblName, field_setting, data_dict, col_hidden) {\n //console.log(\"========= CreateTblRow =========\", tblName);\n //console.log(\"data_dict\", data_dict);\n\n const field_names = field_setting.field_names;\n const field_tags = field_setting.field_tags;\n const field_align = field_setting.field_align;\n const field_width = field_setting.field_width;\n const column_count = field_names.length;\n\n //const col_left_border = (selected_btn === \"btn_overview\") ? cols_overview_left_border : cols_stud_left_border;\n const col_left_border = field_setting.cols_left_border;\n\n// --- lookup index where this row must be inserted\n const ob1 = (data_dict.lastname) ? data_dict.lastname.toLowerCase() : \"\";\n const ob2 = (data_dict.firstname) ? data_dict.firstname.toLowerCase() : \"\";\n // ordering of table overview is doe on server, put row at end\n const row_index = (selected_btn === \"btn_result\") ? b_recursive_tblRow_lookup(tblBody_datatable, setting_dict.user_lang, ob1, ob2) : -1;\n\n// --- insert tblRow into tblBody at row_index\n const tblRow = tblBody_datatable.insertRow(row_index);\n if (data_dict.mapid) {tblRow.id = data_dict.mapid};\n\n// --- add data attributes to tblRow\n tblRow.setAttribute(\"data-pk\", data_dict.id);\n\n// --- add data-sortby attribute to tblRow, for ordering new rows\n tblRow.setAttribute(\"data-ob1\", ob1);\n tblRow.setAttribute(\"data-ob2\", ob2);\n\n// --- add EventListener to tblRow\n tblRow.addEventListener(\"click\", function() {HandleTblRowClicked(tblRow)}, false);\n\n// +++ insert td's into tblRow\n for (let j = 0; j < column_count; j++) {\n const field_name = field_names[j];\n\n // skip columns if in columns_hidden\n if (!col_hidden.includes(field_name)){\n const field_tag = field_tags[j];\n const class_width = \"tw_\" + field_width[j];\n const class_align = \"ta_\" + field_align[j];\n\n // --- insert td element,\n const td = tblRow.insertCell(-1);\n\n // --- create element with tag from field_tags\n const el = document.createElement(field_tag);\n\n // --- add data-field attribute\n el.setAttribute(\"data-field\", field_name);\n\n // --- add text_align\n el.classList.add(class_width, class_align);\n\n // --- add left border before each group\n if(col_left_border.includes(j)){td.classList.add(\"border_left\")};\n\n // --- append element\n td.appendChild(el);\n\n// --- add EventListener to td\n if (field_name === \"withdrawn\") {\n if(permit_dict.permit_crud && permit_dict.requsr_same_school){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n // this is done in add_hover: td.classList.add(\"pointer_show\");\n };\n } else if (field_name === \"gl_status\") {\n if(permit_dict.permit_approve_result && permit_dict.requsr_role_insp){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n };\n //} else if ([\"diplomanumber\", \"gradelistnumber\"].includes(field_name)){\n // td.addEventListener(\"change\", function() {HandleInputChange(el)}, false)\n // el.classList.add(\"input_text\");\n };\n // --- put value in field\n UpdateField(el, data_dict)\n } // if (!columns_hidden[field_name])\n } // for (let j = 0; j < 8; j++)\n return tblRow\n }",
"function drawLibSelWin(lib_ind) {\r\n\r\n var pO = CurProgObj;\r\n\r\n // STEP:\r\n // Create the list of all libraries to select\r\n //\r\n var str = \"<table class='selectWin'>\"\r\n str += \"<tr><td> Select Library: <select id='selWin' \" +\r\n \" onchange='drawLibSelWin(this.selectedIndex)'> \";\r\n //\r\n for (var i = 0; i < pO.libModules.length; i++) {\r\n str += \"<option value='\" + i + \"'\";\r\n if (i == lib_ind)\r\n str += \"selected\";\r\n\r\n str += \">\" + pO.libModules[i].name + \"</option>\";\r\n }\r\n\r\n //\r\n str += \"</select>\";\r\n str += \"<BR><BR><div></div>\";\r\n str += \"</td></tr>\"\r\n\r\n\r\n\r\n // STEP:\r\n // Create a list of all functions in the selected library\r\n // \r\n str += \"<tr><td> Select Function: <select id='selWin2'>\";\r\n\r\n //\t+ \" onc='libFuncPicked(\"+ lib_ind + \",this.selectedIndex)'> \";\r\n //\r\n var libM = pO.libModules[lib_ind];\r\n\r\n for (var i = 0; i < libM.allFuncs.length; i++) {\r\n str += \"<option value='\" + i + \"'\";\r\n str += \">\" + getFuncCallStr(libM.allFuncs[i].funcCallExpr) +\r\n \"</option>\";\r\n }\r\n //\r\n str += \"</select>\";\r\n\r\n\r\n str += \"<BR><BR><div></div>\";\r\n str +=\r\n \"<input type='button' value='Cancel' onclick='cancelLibFunc()'>\";\r\n str +=\r\n \"<input type='button' value='Insert' onclick='insertLibFunc()'>\";\r\n\r\n\r\n str += \"<BR><BR><div></div>\";\r\n str += \"</td></tr>\"\r\n\r\n\r\n str += \"</table>\";\r\n\r\n displayAtLastGrid(str);\r\n\r\n // change the innerHTML of the HTML object \r\n //\r\n\r\n\r\n\r\n}",
"function createStyledTable(){\r\n if (!validateMode()) return;\r\n\r\n if (cl!=null)\r\n { \r\n if (cl.tagName==\"TD\")\r\n obj = cl.parentElement.parentElement.parentElement;\r\n }else{\r\n elem=getEl(\"TABLE\",Composition.document.selection.createRange().parentElement());\r\n\tif(elem!=null) obj = elem;\r\n }\r\n \r\n if (!obj)\r\n {\r\n alert(\"Установите курсор в ячееку таблицы!\");\r\n\r\n }else{\r\n\tdtbl = showModalDialog(\"/images/mifors/ws/w_stable.htm\", tables,\"dialogWidth:250px; dialogHeight:200px; center:1; help:0; resizable:0; status:0\");\r\n\tif(dtbl==null) return;\r\n\tvar xsltTable = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\txsltTable.async = false;\r\n\txsltTable.load(dtbl);\r\n\tif (xsltTable.parseError.errorCode != 0) {\r\n\t var myErr = xsltTable.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\tvar sxmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\tsxmlDoc.async=false;\r\n\ttra=new String(obj.outerHTML);\r\n\tstate=0;\r\n\tout=\"\";\r\n\tfor(i=0;i<tra.length;i++){\r\n\t\tch=tra.charAt(i);\r\n\t\tswitch (state){\r\n\t\t\tcase 0:if(ch=='<') state=1; break;\r\n\t\t\tcase 1:if(ch=='>') state=0;\r\n\t\t\t\tif(ch=='=') state=2;break;\r\n\t\t\tcase 2:if(ch!='\"'){ out+='\"'; state=4} else state=3;break;\r\n\t\t\tcase 3:if(ch=='\"') state=1;break;\r\n\t\t\tcase 4:if(ch==' ') {out+='\"';state=1}\r\n\t\t\t\tif(ch=='>') {out+='\"';state=0};break\r\n\t\t}\r\n\t\tout+=ch;\r\n\t}\r\n\tsxmlDoc.loadXML(out);\r\n\tif (sxmlDoc.parseError.errorCode != 0) {\r\n\t var myErr = sxmlDoc.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\treplacement=sxmlDoc.transformNode(xsltTable);\r\n\tobj.outerHTML=replacement;\r\n\tComposition.document.recalc();\r\n\tComposition.focus();\r\n }\r\n}",
"function makeTable () {\n\tconsole.log('At start makeTable()...tableExists = ' + tableExists + '. edit = ' + edit);\n\tfromMakeTable = 1;//to keep warning to create a table first if displayTable btn tapped after a table has been created\n\tif(edit === 1) {\n\t\tadditionalFields.value = numberOfDynamicFields;\n\t\theadNameFirstColumn.value = fieldNamesArray[0] ;\n\t\tthirdFieldNameInput.value = fieldNamesArray[2] ;\n\t\tfourthFieldNameInput.value = fieldNamesArray[3] ;\n\t\t//editBtn.setAttribute('class', 'normalBtn');\n\t\t\n\t}//end if edit\n\n\t//show create table window\n\tcreateTableWindow.setAttribute('class', 'showing');\t\n\t\n\t//Check if screenDark mode\ncheckScreenMode();\nif(screenDark) {\n\tcreateTableWindow.style.backgroundColor = \"black\";\n\tcreateTableWindow.style.color = \"white\";\n} else {\n\tcreateTableWindow.style.backgroundColor = \"#eee\";\n\tcreateTableWindow.style.color = \"black\";\n}//end if else screenDark\n\t//window.onload = function() {\n\t\t//error 'the object can not be found here if comimg from edit make changes'\n\t// \tif (edit === 0) {\n\t// \t\t//leave new or edit option bar so it can be used for future edits\n\t// createTableWindow.removeChild(newOrEdit);\n // }//end if edit === 0\n\tsubmitBtn.setAttribute('class','attentionBtn');\n\tsubmitBtn.disabled = false;\n\tif(edit === 1) {\n\t\tsubmitBtn.setAttribute('class','normalBtn');\n\t\t\tsubmitBtn.disabled = true;\n\t}//end if edit = 1\n\tsubmitBtn.onclick = function () {\n\t\n\t//scroll to bottom of window\n\tcreateTableWindow.scrollTop = createTableWindow.scrollHeight;\n\t//scroll to bottom of window\n\t\tconsole.log('At submitBtn.onclick. ..edit = '+ edit);\n\t\tif(edit === 1) {\n\t\teditBtn.setAttribute('class', 'attentionBtn');\t\n\t\t}//end if edit = 1\n\t\t//e.stopPropagation();//remove if trouble \n\t//alert('dbTableName.value = ' + dbTableName.value);\n\t\ttableName.textContent = \"Table for Database named : \" + dbTableName.value;\n\tnumberOfFields = Number(additionalFields.value) + 4;\n\t//alert('numberOfFields = ' + numberOfFields);\n\t// if(edit) {\n\t// \tadditionalFields.value = numberOfDynamicFields;\n\t// }//end if edit\n\t//numberOfFields is the total number of fields which includes the initial static 4 plus all other fields added to the initial 4...fieldNamesArray.length\n\t//originalNumberOfFields = fieldNamesArray.length before any edit!\n\t//numberOfDynamicFields = THE NUMBER OF FIELDS BEYOND THE INITIAL STATIC 4. This number can keep increasing as you add more fields, so is a dynamic number. This currently is the number entered into the green input line 'number of additional fields. '\n\tnumberOfDynamicFields = additionalFields.value;\n\t//alert('numberOfDynamicFields = ' + numberOfDynamicFields);\n\t// if(edit) {\n\t// \theadNameFirstColumn.value = fieldNamesArray[0] ;\n\t// }//end if edit\n\theadName.textContent = headNameFirstColumn.value;//listName header first column..I.e. Locomotive\n\t//add headName to fieldNamesArray\n\tfieldNamesArray[0] = headName.textContent;\n\ttableHeader.setAttribute('style', 'colspan: numberOfFields', 'simulator','width: 100%');\n\t//alert('thirdFieldNameInput.value = ' + thirdFieldNameInput.value);\n\t//\tfirstDataNameTd.value =\n\n\t//thirdFieldNameInput.value;//3rd field name title info taken from cursor.body.value in cursor iteration of current database\n\tfieldNamesArray[1] = ' DATE ';\n\t// if(edit) {\n\t// \tthirdFieldNameInput.value = fieldNamesArray[2] ;\n\t// }//end if edit\n\tfirstDataNameTd.textContent = thirdFieldNameInput.value;\n\tfieldNamesArray[2] = firstDataNameTd.textContent;//I.e. Location\n\tsubmitBtn.setAttribute('class','normalBtn ');\n\tsubmitBtn.disabled = true;\n\t//headRow.appendChild(firstDataNameTd);not needed because already appended in HTML????\n\t// if(edit) {\n\t// \tfourthFieldNameInput.value = fieldNamesArray[3] ;\n\t// }//end if edit\n\tsecondDataNameTd.textContent = fourthFieldNameInput.value;\n\tfieldNamesArray[3] = secondDataNameTd.textContent;//I.e.Decoder \n\t//headRow.appendChild(secondDataNameTd);this line not needed because secondDataNameTd is already in the HTML\n\t\n\t\n//\tthirdFieldP.textContent = thirdFieldNameInput.value;\n\t//\talert('firstDataNameTd.value = ' +firstDataNameTd.value);\n//}//end submitBtn.onclick\n// \tthirdFieldNameInput.onclick = function () {\n\t\t\n// \t};\n\t\n// \tthirdFieldNameInput.addEventListener('input', function () {\n// \tsecondDataNameTd.value = fourthFieldNameInput.value;//4th field name title info taken from cursor.body.value in cursor iteration of current database\n// });\n\t//directions info P..h3 declared as global variable\n//\tconst addFieldsDirectionP = document.createElement('h4');\nif(edit === 1) {\n\taddFieldsDirectionP.textContent = 'Make changes to the Dynamic Field titles below: ⬇️';\n} else if (edit === 0) {\n\taddFieldsDirectionP.textContent = 'Enter the added field/column titles below: ';\n}//end if else if edit construct\n\tcreateTable.appendChild(addFieldsDirectionP);\n\t//create the inputs for added fields required\n\tfor (let j = 1; j <= numberOfDynamicFields; j++) {\n\t//alert('i = ' + i);\n\tlet k = 3+j;//for fieldNamesArray\nconst nextFieldHeadingInput = document.createElement('input');//the headings for the added fielDs..I.e. the fieldNames Array\nconst submitButton = document.createElement('button');//small green filled red dot\ncreateTable.appendChild(nextFieldHeadingInput);\ncreateTable.appendChild(submitButton);\nsubmitButton.setAttribute('class','borderBlinkGrn');//was attentionBtn\nif(edit === 1) {\n\t\t\n\t\tnextFieldHeadingInput.value = fieldNamesArray[k] ;\n\t}//end if edit\n\t\tsubmitButton.onclick = function () {\n\t\t//scroll to bottom of window\n\tcreateTableWindow.scrollTop = createTableWindow.scrollHeight;\n\t\n\t//scroll to bottom of window\n\t\t\t//alert('edit variable = '+ edit);\n\t\t\t//if the if statement is here the append to headRow does not happen. why??\n\t\t//\tif (edit === 0) {\n\t\t\t//\talert('creating element nextFieldHeading td');\n\t\t\tconst nextFieldHeading = document.createElement('td');\n\t\t//\t}//end if !edit\n\t\t\t\n\t\t\tnextFieldHeading.textContent = nextFieldHeadingInput.value;\n\t\t\tfieldNamesArray[k] = nextFieldHeading.textContent;\n\t\t\t\n\t\t\tsubmitButton.setAttribute('class','normalBtn ');\n\t\tif (edit === 0) {\n\t\t//alert('About to append nextFieldHeading to headRow');\n\t\theadRow.appendChild(nextFieldHeading);\n\t\t\n\t\t}//end if edit = 0\n\t\tcreateTable.removeChild(nextFieldHeadingInput);\n\t\t\tcreateTable.removeChild(submitButton);\n\t\t\t\n\t\t}//end submitButton.onclick\n\t}//end of for loop\n\t\n\t//const buildRecordsP = document.createElement('p');//at top\n\t\ncreateTable.appendChild(buildRecordsP);\nbuildRecordsP.setAttribute('class', 'simulator');\n//buildRecordsP.disabled = false;\nbuildRecordsP.textContent = ' Enter titles of '+ numberOfDynamicFields + ' dynamic fields (By tapping the green buttons). When satisfied with entries tap here to continue!';\n\tblockEdit = true;//ADDED Oct10 2022 to nitialize table before doing a double tap on the edited field title REMOVE IF MESSES UPflag to prevent savedTablesArray getting messed up\n\t\n\thomeScreenBtn.setAttribute('class','borderBlink');\n\thomeScreenBtn2.setAttribute('class','borderBlink');\n\t\n\t}//end submitBtn.onclick needs to be here instead of higher up\n\n//create tableArray variable 2D array\n// now create the vertical rows for records\n//the number of row iterations will be = counter\n//var additionalFieldsArray = Create2DArray(counter,numberOfDynamicFields);\n\nbuildRecordsP.onclick = function () {\n//WOULD BE NICE IF i could scroll to bottom!\nconst scrollToBottom = (id) => {\n\t const element = document.getElementById(id);\n element.scrollTop = element.scrollHeight;\n}\t\nscrollToBottom('createTable');//this is a function expression..element id is passed as a parameter to the scrollToBottom function expression.\n//WOULD BE NICE IF i could scroll to bottom!\n//code line below does not seem to work?\n//createTable.scrollTop = createTable.scrollHeight;\n//line below did not work either\n//createTableWindow.scrollTop = createTableWindow.scrollHeight;\n\ncreateTableWindow\n\tconsole.log('At buildRecordsP.onclick');\n\tif (edit === 1) {\n\t\taddFieldsDirectionP.textContent = 'Make changes to labels of added fields below.';\n\t\t//removeChild(buildRecordsP if edit === 1??)\n\t\tbuildRecordsP.textContent = 'Make changes to added field titles/labels! When finished tap here to SAVE TABLE';\n\t\t//might have to remove this line\n\t\tcreateTable.removeChild(buildRecordsP);\n\t} else {\n\taddFieldsDirectionP.textContent = 'Now enter data into the added fields.';\n\tbuildRecordsP.textContent = 'Now enter data into the fields! When finished tap here to SAVE TABLE';\n}//end if edit === 1\n\t//remove fieldName entry inputs\n\t//while (createTable.nextFieldHeadingInput) {\n\t//buildRecordsP.disabled = true;\t//this does not disable the buildRecordsP why??\n\t//}//end while submitBtn\n\tif (tappedOnce) {saveTable();}//end if tappedOnce\n\tif (!tappedOnce) {\n\tbuildRecordRows();\n\t}//end if !tappedOnce\n\ttappedOnce = 1;\n\t//Nov12\n\tif(edit === 1) {\n\t\tsaveTable();\n\t}//end if edit = 1\n\t//Nov 12\n}//end buildRecordsP.onclick\n\t\n\n\n//}//end function createTable\n\nfunction saveTable () {\n\t//save table variable values in some kind of array\n\tconsole.log('At start saveTable');\n\tsaveTableP.setAttribute('class','simulator');\n\tsaveTableP.textContent = 'Table is SAVED! Tap here to see results.';\n\t//may need to put line below in if (edit===0) statement\n\tcreateTable.appendChild(saveTableP);\n\tsaveTableP.onclick = function () {\n\t\tif (edit === 1) {\n\t\t\tconsole.log('In makeTable()..edit is currently 1 and about to be set to 0. saveTableP(Table is saved Tap here to see results) is about to be removed. If edit is made 0 here how does that effect displayTable later? tappedOnce = '+ tappedOnce);\n\t\t\t//might remove edit = 0 NOPE!!program stops running if you remove edit =0!line 2892 so displayTable works?\n\t\t\tedit = 0;//Nov12 necessary to have field label inputs to appear\n\t\t\t//may need to removeline below??\n\t\tcreateTable.removeChild(saveTableP);\t\n\t\t}//end of if edit\n\t\t//change color of to make changes direction to green from pink\n\t\tsaveTableP.setAttribute('class','edBan');\n\t\tsaveTableP.textContent ='To make changes or add columns go back to Edit from the displayed table. Scroll ⬇️';// Make Changes button!'; \n\t\t//tableArray[1][4] = ' + tableArray[1][4];\n\t\t// alert('255 .. tableArray[0][6] = ' + tableArray[0][6]);\n\t\t// alert('In SAVE table function : 190? tableArray[2][6] = ' + tableArray[2][6]);\n\t\t\n\t// for(let i = 0;i<counter;i++) {\n\t// \t\tfor(let j=0;j<numberOfFields;j++) {\n\t// \t\t\tconsole.log('tableArray[' +i + '][' + j +'] = ' + tableArray[i][j]);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t// \t\t\t//statement above gave an undefined is not an object error when evaluating tableArray[i] [j] and resolved when I commented it out?? array worked after that??\n\t// \t\t\t//console.log('tableArray[' +i + '][' + j +'] = ' + tableArray[i][j]);\n\t\t\t\t\n\t// \t\t}//end for j =\n\t\t\t\n\t\t\t\n\t// \t}//end for i =\n\t\t\n\t\t//give option to make changes\t\t\n\n\tconst showOrEdit = document.createElement('p');\n\tconst anl = document.createElement('br');\nshowOrEdit.setAttribute('class', 'simulator');\nshowOrEdit.textContent = 'Tap DISPLAY TABLE to show the finished Table. ';//or use EDIT to Make CHANGES.'\nconst showBtn = document.createElement('button');\nconst changesBtn = document.createElement('button');\n//show tn goes to displayTable function\n//changes button goes to makeTableFunction with edit=1\nshowBtn.textContent = 'DISPLAY TABLE';\nchangesBtn.textContent = 'Make CHANGES';\ncreateTable.appendChild(showOrEdit);\nshowOrEdit.appendChild(anl);\nshowOrEdit.appendChild(showBtn);\n//disabled makeChanges Btn as can't get display to work,!\n// if (!fromNew) {\n// showOrEdit.appendChild(changesBtn);\n// }//end if !fromNew\n//showOrEdit.appendChild(changesBtn);\n//showBtn from createTable goes to displayTable function\nshowBtn.onclick = function () {\n\n//alertx(\"ShowBtn.onclick..tableID = \"+ tableID + \". loadFromTableOptions = \" + loadFromTableOptions + \". makeContactsTable = \" + makeContactsTable + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[tableID][1] = \" + newTableSpecificVariables[tableID][1] + \". savedTablesArray[loadTableIndex] = \" + savedTablesArray[loadTableIndex] + \". savedTablesArray[tableID] = \" + savedTablesArray[tableID]);\n\nconsole.log(\"ShowBtn.onclick..tableID = \"+ tableID + \". loadFromTableOptions = \" + loadFromTableOptions + \". makeContactsTable = \" + makeContactsTable + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[tableID][1] = \" + newTableSpecificVariables[tableID][1] + \". savedTablesArray[loadTableIndex] = \" + savedTablesArray[loadTableIndex] + \". savedTablesArray[tableID] = \" + savedTablesArray[tableID]);\n\n\n\t//code to disable goToHomeScreen btn so table is not messed up if user taps returnToHome screen after having entered a number into the add dynamic fields input..forces finish of this process\n\tgoHomeBtn.disabled = false;\n\tconsole.log('At showBtn.onclick..DISPLAY TABLE');\n\tcreateTable.removeChild(showOrEdit);\n\t//should I clear all rows be here if coming from edit? To prevent repeat of all records\n\t//!!!!!REMOVE CODE BELOW IF SCREW UP!\n\t//Nov 12\n\tif (editCurrentTable === 1){\n\t\t//removeFieldHeaders();//removed this line because'object not found here' error...this was after I added the add more dynamic fields code Nov 26. Now works. Not sure what the issue is?\n\t\t//delete field has used a removeFieldHeaders();function at this point then remove STRows\n\twhile (STrows.firstChild) {\n STrows.removeChild(STrows.firstChild);\n\t}//end while\t\n\t\n\t\t//to force displayTable to recreate STHeadRow set displayedTable varial even to 0;if removing edit =0 at line 2902\n\t\tdisplayedTable = 0;//Nov12\n\t\t//not sure refreshed = 0 is necessary here Nov 15?\n\t\trefreshed = 0;//Nov 13 to make sure displayTable tacks on the extra fields in case an edit data cell was performed prior to being here.\n\t\t//why tableConstructed = 0 here? INitial intention to force a STHeadRow display? But tableConstructed set to 1 immediately in displayTable so not sure the line below does anything? REMOVED NOV 16 \n\t\t//tableConstructed = 0;\n\t\tedit = 0;\n\t\tSTtableHeader.textContent = dbTableName.value;\n\t\t//STrows.removeChild(STheadRow);//NotFoundError: The object can not be found here.\n// STtableHeader.setAttribute('class','attentionBtn');\n// STrows.appendChild(STtableHeader);\n// STrows.appendChild(STheadRow);\n\t}//end if editCurrentTable =1\n\t//!!!!!!!!REMOVE CODE ABOVE IF SCREW UP!\n\t//Nov 13\n\t//displayTable();\n//DON'T SAVE TABLEARRAY IF IN NEWTABLE MODE!\nif(!loadFromTableOptions) {\n\tdataVobj.tableArray = tableArray;\n\t\tconsole.log('At saving current table values! and going to saveVariables. dataVobj.tableArray = ' + dataVobj.tableArray);\n\t\tsaveVariables();\n\t//deleteField has this line here:\n\t//changeDBtable();//to keep field names from getting messed up Date: Feb13\n\tchangeDB = true;//this puts field headers in place after an edit of main db then going to new table\n\t\tdisplayTable();\n\t}//end if(!loadFromTableOptions) \n\t\t\nif (loadFromTableOptions) {\n\t\n\t\t\n\t\t\n\t\tnewTableFieldsArray = fieldNamesArray.slice();\n\t\tnewTableSpecificVariables[loadTableIndex][1] = newTableFieldsArray.slice();\n\t\t\n\t\tnumberOfNewTableAddedFields = numberOfDynamicFields;\n\t\t//numberOfNewTableAddedFields = newTableVariablesArray[4];\n\t\tsavedTablesArray[loadTableIndex]=tableArray.slice();\n\t\t\n\t\t//alertx(\"Display Table btn has been tapped! (showBtn.onclick)..Edited newtable: tableArray = \" + tableArray + \". savedTablesArray[loadTableIndex] = \" +savedTablesArray[loadTableIndex] + \". newTableFieldsArray = \" + newTableFieldsArray + \". numberOfNewTableAddedFields = \" + numberOfNewTableAddedFields + \". newTableSpecificVariables[loadTableIndex][1] = \" + newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\tconsole.log(\"Display Table btn has been tapped! (showBtn.onclick)..Edited newtable: tableArray = \" + tableArray + \". savedTablesArray[loadTableIndex] = \" +savedTablesArray[loadTableIndex] + \". newTableFieldsArray = \" + newTableFieldsArray + \". numberOfNewTableAddedFields = \" + numberOfNewTableAddedFields + \". newTableSpecificVariables[loadTableIndex][1] = \" + newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\t//deleteField does not have this line here but puts it above in if(!loadFromTableOptions\n\t\t\n\t\t//- ?\n\t\tchangeDBtable();//to keep field names from getting messed up Date: Feb13\n\t\tchangeDB = true;//this puts field headers in place after an edit of main db then going to new table\n/*\t\tTable is cleared above\n\t\tREMOVE HEAD ROW THEN RECONSTRUCT HEAD ROW..BUT NOT ADDED TO STROWS…CHANGEdb set to false\n\t\t\n\t*/\t\n\t\t\n\t\t/***********************/\n\t\t//edit = 1;\n\t\t//ADD A FLAG AND ADD THE FIXED FIELDS JUST BEFORE ADDING THE DYNAMIC FIELDS\n\t//***************************//\n\t\t//flag to correct messed up fieldHeaders from a newTable edit\n\t\t\n\tadjustFields = true;\t\n\t\t\n\t//*****************************\n\t\t//setUpFieldHeaders();\n\t\t//changeDB = true;//added Feb14 trying to msake field headers behave\n\t\t\n\t\t//***************************//\n\t\tdisplayTable();\n\t\t\n\t\t//alertx(\"In showTable edit routine: After call to displayTable: loadFromTableOptions = \" + loadFromTableOptions + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[loadTableIndex][1] = \" +newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\t//alertx(\"loadFromTableOptions = \" + loadFromTableOptions + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[loadTableIndex][1] = \" + newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\tconsole.log(\"In showTable edit routine: After call to displayTable: loadFromTableOptions = \" + loadFromTableOptions + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[loadTableIndex][1] = \" +newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\tconsole.log(\"loadFromTableOptions = \" + loadFromTableOptions + \". loadTableIndex = \" + loadTableIndex + \". newTableSpecificVariables[loadTableIndex][1] = \" + newTableSpecificVariables[loadTableIndex][1]);\n\t\t\n\t\t\n//return false;\t\t\n\t\t//clearTableRows();\n/*\tWHICH VERSION?\t\nif(loadFromTableOptions) {\n\tsavedTablesArray[loadTableIndex]=tableArray.slice();\n\tnewTableFieldsArray = fieldNamesArray.slice();\n\tnumberOfNewTableAddedFields = numberOfDynamicFields;\n\t\n\talert(\"deleteFields completed: tableArray = \" + tableArray + \". loadTableIndex = \" + loadTableIndex + \". savedTablesArray: savedTablesArray[loadTableIndex] = \" + savedTablesArray[loadTableIndex] + \"newTableFieldsArray = \" + newTableFieldsArray);\n\tchangeDBtable();//to keep field names from getting messed up Date: Feb13\n}//end if loadTableFromOptions\n\n*/\t\t\n//at this point tableArray = Tablevariables edited! dataVobj.tableArray now = Doug Dyer,2022-02-02,(250) 658-5645,addyer@telus.net trainee45.dd@gmail.com ,Janet Dyer,2022-02-02,(250) 658-5645,jandyer@telus.net,Sandra Ramezani,2022-02-02, (604) 505-6650,slramezani@gmail.comdataVobj.newTableVariables = 4,Fantastic,Working well,Engine Hostlers,From ContactsBtn,From NameCreateNew Table,true,CONTACT NAME, DATE ,TELEPHONE,EMAIL,ADDRESS,\n\n//NOTE newTableVariablesArray[4] = numberOfNewTableAddedFields; NUMBER OF NEWTABLEADDED FIELDS IS NOT LISTED\n\tresetFromContacts();\n\t\t\n\t//REMOVE ATRIMHEADROW???\t\n\t\t//trimHeadRow();\n\t//tableArray will now be back in main db mode!!\t\n\t\t\n\t//alertx(\"Preparing to save after edit: Need to know that tableArray has been set back to main db data before save! tableArray = \" + tableArray + \"SO DON'T EDIT A TD CELL BY DBLCLICK IF YOU HAVE JUST EDITED THE TABLE LAYOUT BECAUSE AT THIS POINT tableArray is in main db mode and if you are still in newTable mode you will mess things up\");\t\n\t\n\tconsole.log(\"Preparing to save after edit: Need to know that tableArray has been set back to main db data before save! tableArray = \" + tableArray + \"SO DON'T EDIT A TD CELL BY DBLCLICK IF YOU HAVE JUST EDITED THE TABLE LAYOUT BECAUSE AT THIS POINT tableArray is in main db mode and if you are still in newTable mode you will mess things up\");\t\n\t\n\t\n\t//removeDynamicFields();\n\t//removeFieldHeaders();\n\t\n\t//return false;\n\t\tsaveVariables();\n\t\t\n\t\t//removeHeadRow();//VERY IMPORTANT LINE..MAKES IT WORK!!!Date: Feb12 2022..new function\n\t\t\n/*\t\t\n\tneed to adjust savedTablesArray numberOfFields (numberOfFields = savedTablesArray[indexTable].length) \t\n\tdon't saveVariables until all table edits are made so goto displayTable first then return here to saveVariables and return to mainDB table as you do when creating a contactsTable. In displatTable numberOfFields will have to be set to savedTablesArray[indexTable].length if in loadFromTableOptions mode. Then after display and returning to saveVariables will need to return to originakNumberOfFields and tableTitle.length etc.\n\t*/\nhomeScreenBtn.setAttribute('class','borderBlink');\nhomeScreenBtn2.setAttribute('class','borderBlink');\n}//end if loadFromTableOptions\n\t\n/*\nif(!loadFromTableOptions) {\n\tsaveVariables();\n\tdisplayTable();\n\t//createTableWindow.setAttribute('class', 'hidden');\n\t}//end if(!loadFromTableOptions)\n\t*/\n}//end showBtn.onclick?displayTable?\n\nchangesBtn.onclick = function () {\n\tcreateTable.removeChild(showOrEdit);\n\tcreateTable.removeChild(buildRecordsP);\n\tsaveTableP.textContent = 'You can edit the Table Column Labels here, but not the data. To edit data go to DISPLAY TABLE and double tap the desired cell.';\n\taddFieldsDirectionP.textContent = 'Make changes to the added field Labels: ';\n\t\n\tedit = 1;\n\tmakeTable();\n}//end changesBtn.onclick\t\n\t\t\n\t}//end saveTableP.onclick\n}//end function saveTable\n\n}//end function makeTable starts at line 232",
"function constructExportEdit(ref, row, right, left, logs, log, mapDiv) {\n\tvar div = document.createElement(\"div\");\n\tdiv.style.textAlign = \"right\";\n\tvar estimatedWTLbl = document.createElement(\"p\");\n\testimatedWTLbl.setAttribute(\"id\", \"estimatedWTLbl\");\n\testimatedWTLbl.innerHTML = \"<b>Estimated Wait Time Sent to Users: - min. </b>\";\n\tvar exportRange = document.createElement(\"BUTTON\");\n\texportRange.innerHTML = \"Export Old Data\";\n\texportRange.style.cssFloat = \"center\";\n\texportRange.addEventListener(\"click\", function() { exportRangeAction(ref) });\n\tvar finish = document.createElement(\"BUTTON\");\n\tfinish.innerHTML = \"Finish session and download spreadsheet\";\n\tfinish.style.cssFloat = \"center\";\n\tfinish.addEventListener(\"click\", function() { exportAction(ref) });\n\ttopDiv.appendChild(div);\n\tvar editVehicles = document.createElement(\"BUTTON\");\n\teditVehicles.innerHTML = \"Edit Vehicles\";\n\teditVehicles.style.cssFloat = \"center\";\n\teditVehicles.addEventListener(\"click\", function() { editVehiclesAction(ref) });\n\tvar editEmp = document.createElement(\"BUTTON\");\n\teditEmp.innerHTML = \"Edit Employees\";\n\teditEmp.style.cssFloat = \"center\";\n\teditEmp.addEventListener(\"click\", function() { editEmpAction(ref) });\n\tvar editLocations = document.createElement(\"BUTTON\");\n\teditLocations.innerHTML = \"Edit Locations\";\n\teditLocations.style.cssFloat = \"center\";\n\teditLocations.addEventListener(\"click\", function() { editLocationsAction(ref) })\n\tdiv.appendChild(document.createElement(\"p\"));\n\tdiv.appendChild(finish);\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tdiv.appendChild(exportRange);\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tdiv.appendChild(editEmp);\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tdiv.appendChild(editVehicles);\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tdiv.appendChild(editLocations);\n\tvar switcher = document.createElement(\"BUTTON\");\n\tswitcher.disabled = true;\n\tswitcher.innerHTML = \"Map View\";\n\tswitcher.addEventListener(\"click\", function() { switchView(switcher, ref, row, right, left, logs, log, mapDiv) });\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tdiv.appendChild(switcher);\n\tdiv.appendChild(document.createTextNode(\" \"));\n\tconstructStatus(ref, div);\n\tdiv.appendChild(estimatedWTLbl);\n}",
"function showComps(idx) {\n\tconsole.log(\"Row \" + idx + \" clicked!\");\n\t\n\tvar comps = orders[idx - 1].components;\n\n\tvar compDiv = document.getElementById('componentlist');\n\tif (document.getElementById('componenttable') !== null) {\n\t var compTable = document.getElementById('componenttable')\n\t compDiv.removeChild(compTable);\n\t}\n\tif (document.getElementById('componenthistorytable') !== null) {\n\t var histTable = document.getElementById('componenthistorytable')\n\t histTable.parentNode.removeChild(histTable);\n\t}\n\tvar compTable = document.createElement('table');\n\tcompTable.id = 'componenttable';\n\n\tcompDiv.innerHTML = 'Components';\n\t\n\tvar topRow = compTable.insertRow();\n\ttopRow.classList.add('toprow');\n\tvar idCell = topRow.insertCell();\n\tidCell.innerHTML = 'ID';\n\tvar compCell = topRow.insertCell();\n\tcompCell.innerHTML = 'Color';\t\n\tvar histCell = topRow.insertCell();\n\thistCell.innerHTML = 'History';\n\t\n\tfor (var i in comps) {\n\t console.log(i);\n\t console.log(comps[i]);\n\t var row = compTable.insertRow();\n\t row.addEventListener('click', function() {\n\t\tshowCompHist(idx, this.rowIndex);\n\t });\n\t var cells = [];\n\t for (var key in comps[i]) {\n\t\tcells.push(row.insertCell());\n\t\tif (!(Array.isArray(comps[i][key]))) { \n\t\t cells[cells.length -\n\t\t\t 1].appendChild(document.createTextNode(comps[i][key]));\n\t\t} else {\n\t\t cells[cells.length -\n\t\t\t 1].appendChild(document.createTextNode(comps[i][key].length));\n\t\t}\n\t }\n\t}\n\tcompDiv.appendChild(compTable);\n }",
"function drawDataInTable( data, prop, value ) {\r\n var response = \"<div class='tableHeader'>\" + prop + \": \" + value + \"</div>\";\r\n response += \"<table style='width:100%;text-align:left;border:1px solid black;'><tr><th>Date</th><th>App Version</th><th>Test Case ID</th><th>OBS ID</th></tr>\";\r\n for( var index = 0; index < data.length; index++ ) {\r\n response += \"<tr>\";\r\n response += \"<td>\" + data[index].Date + \"</td>\";\r\n response += \"<td>\" + data[index].App_Version + \"</td>\";\r\n response += \"<td>\" + data[index].Test_Case_Id + \"</td>\";\r\n response += \"<td>\" + data[index].OBS_ID + \"</td>\";\r\n response += \"</tr>\";\r\n }\r\n response += \"</table>\";\r\n return response;\r\n }",
"buildDsModal() {\n\n const self = this;\n const tslist = self.data.filter(function(ts,i){ \n return self.d3.visibleCurves[i];\n }).map(item => item.tsuid);\n\n if (tslist.length === 0) {\n notify().error(\"You might have forgot selecting TS to save in the DS\", \"oops !\");\n return;\n }\n\n $(\"#\" + self.container + \"_algoConfirmSaveDs\").remove();\n $(\"#body\").append(\n `<div class='modal fade' id='${self.container}_algoConfirmSaveDs' tabindex='-1' role='dialog' aria-labelledby='Dataset_creator'>\n <div class='modal-dialog' role='document'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-label='Close'>\n <span aria-hidden='true'>×</span>\n </button>\n <h4 class='modal-title' id='Dataset_creator'>Assistant for dataset definition</h4>\n </div>\n <div class='modal-body' id=\"modalDsBody\">\n <div class='row'>\n <div class='col-xs-12'>\n <label>Confirm creation of a new Dataset with:</label>\n </div>\n </div>\n <div class='row' style='padding-top:10px'>\n <div class='col-xs-1'></div>\n <div class='col-xs-3' style='top:5px;'>\n <label>Name</label>\n </div>\n <div class='col-xs-8'>\n <input type='text' id='${self.container}_dataset_name' class='form-control' placeholder='...'\n value='my_new_dataset'> </input>\n </div>\n </div>\n <div class='row' style='padding-top:10px'>\n <div class='col-xs-1'></div>\n <div class='col-xs-3' style='top:5px;'>\n <label>Description</label>\n </div>\n <div class='col-xs-8'>\n <input type='text' id='${self.container}_description' class='form-control' placeholder='...'\n value='Desc'> </input>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n `);\n\n $(\"#modalDsBody\").append(`\n <div class='row' style='padding-top:10px'>\n <div class='col-xs-12'>\n <button id='${self.container}_confirm_save_ds' class='btn btn-default' style='float:right'>Save</button>\n </div>\n </div>\n `);\n $(\"#\" + self.container + \"_confirm_save_ds\")\n .on(\"click\", function () {\n self.sendDsToApi(tslist);\n });\n $(\"#\" + self.container + \"_algoConfirmSaveDs\").modal(\"show\");\n }",
"function popupTableau()\n{\n var popup = window.open('','name','height=400,width=500');\n \n javaCode = '<script type=\"text\\/javascript\">function insertCode(){';\n javaCode += 'var row = parseInt(document.paramForm.inputRow.value); '\n javaCode += 'var col = parseInt(document.paramForm.inputCol.value); '\n javaCode += 'var bord = parseInt(document.paramForm.inputBorder.value); '\n javaCode += 'var styleHeader = document.paramForm.inputHeader.checked; '\n javaCode += 'var styleLine = document.paramForm.inputLine.checked; '\n javaCode += 'window.opener.generateTableau(col,row,bord,styleHeader,styleLine); '\n javaCode += '}<\\/script>';\n \n popup.document.write('<html><head><title>表格參數</title>');\n popup.document.write('<script type=\"text\\/javascript\" src=\"\\/skins-1.5\\/common\\/wikibits.js\"><!-- wikibits js --><\\/script>');\n popup.document.write('<style type=\"text\\/css\" media=\"screen,projection\">/*<![CDATA[*/ @import \"\\/skins-1.5\\/monobook\\/main.css?5\"; /*]]>*/<\\/style>');\n popup.document.write(javaCode); \n popup.document.write('</head><body>');\n popup.document.write('<p>請輸入想要生成表格的參數:</p>');\n popup.document.write('<form name=\"paramForm\">');\n popup.document.write('行數:<input type=\"text\" name=\"inputRow\" value=\"3\" ><p>');\n popup.document.write('列數:<input type=\"text\" name=\"inputCol\" value=\"3\" ><p>');\n popup.document.write('邊框寬度:<input type=\"text\" name=\"inputBorder\" value=\"1\" ><p>');\n popup.document.write('灰色表頭:<input type=\"checkbox\" name=\"inputHeader\" checked=\"1\" ><p>');\n popup.document.write('灰色斑馬表:<input type=\"checkbox\" name=\"inputLine\" checked=\"1\" ><p>');\n popup.document.write('</form\">');\n popup.document.write('<p><a href=\"javascript:insertCode()\"> 將代碼插入到編輯窗口中</a></p>');\n popup.document.write('<p><a href=\"javascript:self.close()\"> 關閉</a></p>');\n popup.document.write('</body></html>');\n popup.document.close();\n}",
"function iniBuildTable() {\n\tvar req = new XMLHttpRequest();\n\treq.open(\"GET\", \"http://52.26.106.49:3000/table\", true);\n\treq.addEventListener(\"load\", function() {\n\t\t\n\tif(req.status >=200 && req.status < 400) {\n\t\tvar oldTable = document.getElementById(\"workData\");\n\t\tvar child = document.getElementsByTagName(\"tbody\");\n\t\tfor(var i=0; i<child.length; i++) {\n\t\t\toldTable.removeChild(child[i]);\n\t\t\t\n\t\t}\n\t\t\n\t \tvar response = JSON.parse(req.responseText);\n\t\tvar data = JSON.parse(response.results);\n\t\t\t\t\n\t\tvar tableBody = document.createElement(\"tbody\");\n\t\tfor(var i=0; i<data.length; i++) {\n\t\t\tvar newRow = document.createElement(\"tr\");\n\t\t\t\n\t\t\t\n\t\t\tvar newCellName = document.createElement(\"td\");\n\t\t\tnewCellName.textContent = data[i].name;\n\t\t\tvar newCellRep = document.createElement(\"td\");\n\t\t\tnewCellRep.textContent = data[i].reps;\n\t\t\tvar newCellWeight = document.createElement(\"td\");\n\t\t\tnewCellWeight.textContent = data[i].weight;\n\t\t\tvar newCellDate = document.createElement(\"td\");\n\t\t\tnewCellDate.textContent = data[i].date;\n\t\t\tvar newCellUnits = document.createElement(\"td\");\n\t\t\t/*assign lbs or kgs to units depending on bool value*/\n\t\t\tif(data[i].lbs == 1) {\n\t\t\t\tnewCellUnits.textContent = \"lbs\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnewCellUnits.textContent = \"kgs\";\n\t\t\t}\n\t\t\t\n\t\t\tnewRow.appendChild(newCellName);\n\t\t\tnewRow.appendChild(newCellRep);\n\t\t\tnewRow.appendChild(newCellWeight);\n\t\t\tnewRow.appendChild(newCellDate);\n\t\t\tnewRow.appendChild(newCellUnits);\n\t\t\ttableBody.appendChild(newRow);\n\t\t\toldTable.appendChild(tableBody);\n\t\t\t/*Create form with hidden id of data id and \n\t\t\t delete button with event listener to \n\t\t\t submit data id to delete function */\n\t\t\tvar newDelete = document.createElement(\"td\");\n\t\t\tnewRow.appendChild(newDelete);\n\t\t\t\n\t\t\tvar deleteButton = document.createElement(\"input\");\n\t\t\tdeleteButton.type = \"submit\";\n\t\t\tdeleteButton.name = \"delete\";\n\t\t\t\n\t\t\tnewDelete.appendChild(deleteButton);\n\t\t\tvar deleteCell = document.getElementsByName(\"delete\");\n\t\t\tdeleteCell[i].addEventListener('click', function (event) {\n\t\t\t\tvar sib = this.nextSibling;\n\t\t\t\tdeleteRow(sib.value);\n\t\t\t});\t\n\t\t\tvar formInHide = document.createElement(\"input\");\n\t\t\tformInHide.type = \"hidden\";\n\t\t\tformInHide.name = \"id\";\n\t\t\tformInHide.value = data[i].id;\n\t\t\tnewDelete.appendChild(formInHide);\n\t\t\t\n\t\t\t/*create update form with hidden id holding the\n\t\t\t value of the data id. Add update button with \n\t\t\t event listener to submit a get request with\n\t\t\t the data id */\n\t\t\tvar newUpdate = document.createElement(\"td\");\n\t\t\tnewRow.appendChild(newUpdate);\n\t\t\tvar updateForm = document.createElement(\"form\");\n\t\t\tvar query = {id: null};\n\t\t\tupdateForm.method = 'GET';\n\t\t\tupdateForm.action = \"http://52.26.106.49:3000/logID?\" + query.id;\n\t\t\t\n\t\t\tnewUpdate.appendChild(updateForm);\n\t\t\tvar updateButton = document.createElement(\"input\");\n\t\t\tupdateButton.type = \"submit\";\n\t\t\tupdateButton.name = \"update\";\n\t\t\t\n\t\t\tupdateForm.appendChild(updateButton);\n\t\t\tvar updateCell = document.getElementsByName(\"update\");\n\t\t\tupdateCell[i].addEventListener('click', function (event) {\n\t\t\t\tvar sib = this.nextSibling;\n\t\t\t\tvar sibString = String(sib.value);\n\t\t\t\tquery.id = sibString;\n\t\t\t\tevent.stopPropagation();\n\t\t\t});\t\n\t\t\tvar formUpHide = document.createElement(\"input\");\n\t\t\tformUpHide.type = \"hidden\";\n\t\t\tformUpHide.name = \"id\";\n\t\t\tformUpHide.value = data[i].id;\n\t\t\tupdateForm.appendChild(formUpHide);\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\t\n\t}\n\telse {\n\t\t console.log(\"Error in network request: \" );\n\t}\n\t\n\t});\n\treq.send(null);\n}",
"function MDUO_FillSelectRow(tblName, data_dict, tblBody_select) {\n //console.log( \"===== MDUO_FillSelectRow ========= \");\n //console.log( \" data_dict: \", data_dict);\n\n//--- loop through data_map\n let pk_int = null, lvl_pk = null;\n let col_txt_list = [];\n\n const is_selected_pk = (mod_MDUO_dict.exam_pk != null && exam_pk_int === mod_MDUO_dict.exam_pk)\n\n let ob1 = \"---\";\n if (tblName === \"subject\") {\n pk_int = data_dict.subj_id;\n lvl_pk = data_dict.lvl_id;\n ob1 = (data_dict.subj_name_nl) ? data_dict.subj_name_nl : \"---\";\n col_txt_list = [ob1];\n\n } else if (tblName === \"ntermentable\") {\n pk_int = data_dict.ntb_id;\n ob1 = (data_dict.ntb_omschrijving) ? data_dict.ntb_omschrijving : \"---\";\n col_txt_list = [ob1];\n\n } else if (tblName === \"linked\") {\n pk_int = data_dict.subj_id;\n ob1 = (data_dict.subj_name_nl) ? data_dict.subj_name_nl : \"---\";\n const ntb_omschrijving = (data_dict.ntb_omschrijving) ? data_dict.ntb_omschrijving : \"\";\n col_txt_list = [ob1, ntb_omschrijving];\n };\n\n// --- lookup index where this row must be inserted\n const row_index = b_recursive_tblRow_lookup(tblBody_select, setting_dict.user_lang, ob1);\n\n// --- insert tblRow //index -1 results in that the new row will be inserted at the last position.\n let tblRow = tblBody_select.insertRow(row_index);\n\n tblRow.setAttribute(\"data-pk\", pk_int);\n tblRow.setAttribute(\"data-ob1\", ob1);\n\n if (tblName === \"ntermentable\"){\n tblRow.title = ob1;\n } else if (tblName === \"subject\") {\n tblRow.title = data_dict.subj_name_nl;\n };\n\n// - add class with background color\n const selected_class = (tblName === \"linked\") ? \"awp_mod_exam_linked_selected\" : \"awp_mod_exam_selected\" ;\n const default_class = (tblName === \"linked\") ? \"awp_mod_exam_linked\" : \"awp_mod_exam\";\n let just_linked_unlinked = false;\n if (tblName === \"ntermentable\"){\n if (mod_MDUO_dict.just_linked_ntb_id === pk_int){\n just_linked_unlinked = true;\n mod_MDUO_dict.just_linked_ntb_id = null;\n };\n } else {\n if (mod_MDUO_dict.just_linked_unlinked_subj_id === pk_int) {\n just_linked_unlinked = true;\n mod_MDUO_dict.just_linked_unlinked_subj_id = null;\n };\n };\n\n const cls_str = (is_selected_pk || just_linked_unlinked) ? selected_class : default_class;\n tblRow.classList.add(cls_str);\n // just_linked_unlinked will be highlighted for 1 second, remobeve highlighted after 1 second\n if (just_linked_unlinked){\n setTimeout(function () {\n add_or_remove_class (tblRow, default_class, true, selected_class);\n }, 1000);\n };\n// --- add EventListener to tblRow\n tblRow.addEventListener(\"click\", function() {MDUO_handleTblrowClicked(tblName, tblRow)}, false )\n\n const col_width_list = (tblName === \"subject\") ? [\"tw_280\"] :\n (tblName === \"ntermentable\") ? [\"tw_320\"] : [\"tw_360\", \"tw_360\"];\n\n// loop through columns\n for (let i = 0, td, el_div, col_width; col_width = col_width_list[i]; i++) {\n // --- add first td to tblRow.\n td = tblRow.insertCell(-1);\n td.classList.add(col_width)\n td.innerText = col_txt_list[i];\n };\n } // MDUO_FillSelectRow",
"function intlInstruAddRow() {\n var tables = document.getElementsByClassName(\"interinstruments\");\n var noOfTables = tables.length;\n var arrayIndex = noOfTables;\n var indexOfLastTable = arrayIndex - 1;\n var idOfLastTable = \"intltable\" + indexOfLastTable;\n var row = \"\";\n\n // If there are no instruments in the database then set everything to zero.\n if (indexOfLastTable < 0) {\n arrayIndex = 0;\n idOfLastTable = \"intltable0\";// I think I can remove this.\n row = row + \"<div class='showhidediv'>\";\n row = row + \"<input class='expandbutton' type='button' name='show' value='Expand All' onclick='expandAllIntl()'> \";\n row = row + \"<input class='collapsebutton' type='button' name='hide' value='Collapse All' onclick='collapseAllIntl()'>\";\n row = row + \"</div> \";\n\n } else {\n row = row + \"<br>\";\n }\n\n // Create the empty instrument table.\n row = row + \"<table id='intltable\" + arrayIndex + \"' class='interinstruments'>\";\n row = row + \"<thead onclick=\\\"intltoggletablebody('intltable\" + arrayIndex + \"','intlinputtable\" + arrayIndex + \"')\\\">\";\n row = row + \"<tr> \";\n row = row + \"<th class='tablehead' colspan='2'> \";\n row = row + \"<input class='inputinstrumenthead' id='intlinputtable\" + arrayIndex + \"' type='text' value='' onfocus='this.blur()' readonly>\";\n row = row + \"<span class='tooltiptext'>Click to Expand/Collapse</span>\";\n row = row + \"</th> \";\n row = row + \"</tr> \";\n row = row + \"</thead> \";\n row = row + \"<tbody class='intltablebody'> \";\n row = row + \"<tr> \";\n row = row + \"<td class='col1' >Name of the instrument:</td> \";\n row = row + \"<td class='col2'> \";\n row = row + \"<input id='intlinputtable\" + arrayIndex + \"a' name='intlinstruname[\" + arrayIndex + \"]' type='text' value='' size='90'> \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"<tr> \";\n row = row + \"<td>Type of instrument:</td> \";\n row = row + \"<td> \";\n row = row + \"<select name='intlinstrutype[\" + arrayIndex + \"]'> \";\n row = row + \"<option value=''></option> \";\n row = row + \"<option value='international'>International </option> \";\n row = row + \"<option value='regional'>Regional </option> \";\n row = row + \"<option value='bilateral'>Bilateral</option> \";\n row = row + \"</select> \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"<tr> \";\n row = row + \"<td>The instrument has been ratified:</td> \";\n row = row + \"<td> \";\n row = row + \"<select name='intlinstruratified[\" + arrayIndex + \"]'> \";\n row = row + \"<option value=''></option> \";\n row = row + \"<option value='ratified'>Ratified</option> \";\n row = row + \"<option value='signed'>Signed</option> \";\n row = row + \"<option value='notaparty'>Not a Party</option> \";\n row = row + \"<option value='notgeo'>Not Geographically Applicable</option> \";\n row = row + \"</select> \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"<tr> \";\n row = row + \"<td>Articles from the instrument related to the rights:</td> \";\n row = row + \"<td> \";\n row = row + \"<textarea name='intlinstruarticles[\" + arrayIndex + \"]'></textarea> \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"<tr> \";\n row = row + \"<td>Reservations related to the right have been taken:</td> \";\n row = row + \"<td> \";\n row = row + \"<input type='radio' name='intlinstrures[\" + arrayIndex + \"]' value='yes'>Yes \";\n row = row + \"<input type='radio' name='intlinstrures[\" + arrayIndex + \"]' value='no'>No \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"<tr> \";\n row = row + \"<td>Nature and scope of the reservations (if any):</td> \";\n row = row + \"<td> \";\n row = row + \"<textarea name='intlinstruresnature[\" + arrayIndex + \"]'></textarea> \";\n row = row + \"</td> \";\n row = row + \"</tr> \";\n row = row + \"</tbody> \";\n row = row + \"</table> \";\n\n // If there are no instruments in the database, then add the empty\n // instrument after the hidden rights group input element.\n if (indexOfLastTable < 0) {\n jQuery('#question1para').after(row);\n } else {\n jQuery('#' + idOfLastTable).after(row);\n }\n\n // Expand the table once it has been added.\n $(\"#intltable\" + arrayIndex + \" tbody\").toggle();\n}",
"function drawCodeWindow(sO) {\r\n\r\n // STEP:\r\n // if we are currently editing an index expression in a grid -- e.g.,\r\n // row+4 -- we just need to redraw that expression -- we do not need\r\n // to redraw the entire code window.\r\n //\r\n if (sO.focusBoxId == CodeBoxId.Index) {\r\n redrawGridIndexExpr(sO);\r\n return;\r\n }\r\n\r\n // .....................................................................\r\n // STEP: Start drawing the code window table\r\n //\r\n var str = \"<table class='codeWin'>\";\r\n //\r\n // Small Vertical spaces between boxes\r\n //\r\n var vspace = \"<tr><td><div style='height:4px'> </div></td></tr>\";\r\n //\r\n // Find correct auto indentation AND total # of tab indents for table\r\n // Total columns is total indents + 1 + 1 (for 'let column')\r\n //\r\n var totcols = setCodeWindowIndentation(sO) + 1;\r\n\r\n\r\n // STEP: Draw Index names. Each index name is for a dimension.\r\n //\r\n var inames = getIndNames4Step(sO);\r\n //\r\n str += \"<tr>\" + \"<td></td>\" + \"<td colspan=\" + totcols +\r\n \" style='text-align:center'>\" + inames +\r\n \"<div style='height:10px'></div></td>\" + \"</tr>\" + vspace\r\n\r\n\r\n // STEP: Go thru each box and draw it\r\n //\r\n for (var box = CodeBoxId.Range; box < sO.boxAttribs.length; box++) {\r\n\r\n var expr = sO.boxExprs[box];\r\n var exprstr = \"\";\r\n var hasfocus = (sO.focusBoxId == box);\r\n //\r\n if (expr) {\r\n\r\n // If the box has focus always show expression. Otherwise, \r\n // show the expression only if the statment is 'not empty' --\r\n // i.e., just 'if' is an empty statement.\r\n //\r\n var deleted = (expr.deleted == DeletedState.Deleted)\r\n\r\n if (!deleted && (hasfocus || !isEmptyStmt(expr))) {\r\n\r\n sO.curBox = box; // pass box # to getHtmlExprStmt\r\n //\r\n exprstr = getHtmlExprStmt(expr, sO, \"\");\r\n }\r\n }\r\n\r\n // Onclick function to change the focus to this box if the user\r\n // clicks on it. If the user has already clicked on this box (hasfocus)\r\n // then draw a glowing shadow.\r\n //\r\n var oncBox = \" onclick='changeCWInputBox(\" + box + \")' \";\r\n //\r\n var glow = (!hasfocus) ? \"\" :\r\n \" style='box-shadow: -3px 3px 3px #dcffed' \";\r\n\r\n // Start a new row with label\r\n //\r\n var type = sO.boxAttribs[box].type;\r\n //\r\n var label = \"Index Range\";\r\n if (type == CodeBoxId.Mask) label = \"Condition\";\r\n if (type == CodeBoxId.Formula) label = \"Formula\";\r\n //\r\n str += \"<tr>\" + \"<td>\" + label + \":</td>\";\r\n\r\n // print empty cells for proper indentation AND find column span\r\n // for the expression\r\n //\r\n for (var t = 0; t < sO.boxAttribs[box].indent; t++) {\r\n str += \"<td></td>\";\r\n }\r\n var colspan = totcols - sO.boxAttribs[box].indent;\r\n\r\n // FIX: Unique id needed\r\n //\r\n var commentId = getCommentHtmlId(CommentType.StepBox, box);\r\n var cur_comment = sO.boxAttribs[box].comment;\r\n var comment = getCommentStr('span', commentId, \"\", cur_comment);\r\n //\r\n\r\n var letstr = \"\";\r\n /*\r\n\tif (box == 3) {\r\n\r\n\t letstr = \"<span onclick='letClicked()'>let</span>\";\r\n\t}\r\n\t*/\r\n\r\n // Draw the codebox containing expression\r\n //\r\n str += \"<td class='formula' colspan=\" + colspan + oncBox + glow +\r\n \">\"\r\n\r\n + letstr\r\n + exprstr + \"</td>\" + \"<td>\" + comment + \"</td>\" // comment\r\n + \"</tr>\" + vspace;\r\n }\r\n\r\n\r\n // ......................................................................\r\n // STEP: Draw operator buttons at the BOTTOM of code window (same table)\r\n //\r\n var hsep = \"<span>   </span>\";\r\n\r\n // default input button description\r\n //\r\n var bstr = \"<input type='button' class='opbutton' \"; \r\n var bstr2 = \"<button type='submit' class='opbutton' \";\r\n\r\n str += \"<tr><td><div style='height:10px'> </div></td></tr>\";\r\n str += \"<tr>\" + \"<td></td>\" // skip label cell\r\n\r\n\t+ \"<td style='text-align:center' colspan=\" + totcols + \"> \" \r\n\t+ bstr + \"value='+' onclick='addOpExpr(\\\"+\\\")'>\" \r\n\t+ bstr + \"value='-' onclick='addOpExpr(\\\"-\\\")'>\" \r\n\r\n\t+ bstr + \"value='*' onclick='addOpExpr(\\\"*\\\")'>\"\r\n\t+ bstr + \"value='/' onclick='addOpExpr(\\\"/\\\")'>\" \r\n\t+ hsep\r\n\r\n + bstr + \"value='<' onclick='addOpExpr(\\\"<\\\")'>\" \r\n + bstr + \"value='>' onclick='addOpExpr(\\\">\\\")'>\" \r\n + bstr + \"value='<' onclick='addOpExpr(\\\"<\\\")'>\" \r\n + bstr + \"value='=' onclick='addOpExpr(\\\"=\\\")'>\" \r\n + bstr + \"value='!=' onclick='addOpExpr(\\\"!=\\\")'>\" \r\n + bstr + \"value='<-' onclick='addOpExpr(\\\"<-\\\")'>\"\r\n\r\n\r\n\t+ bstr + \"value='OR' onclick='addOpExpr(\\\"OR\\\")'>\" \r\n\t+ bstr + \"value='AND' onclick='addOpExpr(\\\"AND\\\")'>\" \r\n\t+ bstr + \"value='NOT' onclick='addOpExpr(\\\"NOT\\\")'>\" \r\n\t+ hsep\r\n\r\n + bstr + \"value='(' onclick='addOpExpr(\\\"(\\\")'>\" \r\n + bstr + \"value=')' onclick='addOpExpr(\\\")\\\")'>\" \r\n + hsep\r\n \r\n\t// Buttons for functions. To create subscripts, we use 'bstr2'\r\n\t//\r\n\t+ bstr2 + \"onclick='addNewFuncExpr()' title='new function'> \" \r\n\t+ \"f<sub>new</sub></button>\"\r\n\t//\r\n\t+ bstr2 + \"onclick='addExistFuncExpr()' title='existing function'> \" \r\n\t+ \"f<sub> </sub></button>\"\r\n\t//\r\n\t+ bstr2 + \"onclick='addLibFuncExpr()' title='library function'> \" \r\n\t+ \"f<sub>lib</sub></button>\"\r\n\t//\r\n\t+ hsep\r\n\r\n\t// Note: number expression is useful for adding a numeric func arg\r\n\t// \r\n + bstr + \" title='number' \" \r\n\t+ \"value='123' onclick='addNumExpr(\\\"123\\\")'>\" \r\n\r\n + bstr + \" title='string (characters)' \" \r\n\t+ \"value='abc' onclick='addStrExpr(\\\"abc\\\")'>\" \r\n\r\n + bstr + \" title='index end' \" + \"value='end' onclick='addEndExpr()'>\" \r\n + hsep;\r\n\r\n str += bstr + \"value='Delete' onclick='delOpExpr()'>\" \r\n\t+ \"</td></tr>\";\r\n\r\n\r\n // Does the Code Window has the focus (the CW may not have focus when\r\n // we are editing something else like an dim name\r\n //\r\n var cwFocus = (sO.focusBoxId != CodeBoxId.INVALID);\r\n\r\n // Add additional buttons for condition processing (if/else/...) if\r\n // the focus is on a mask box\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isMask() &&\r\n (sO.activeChildPos == ROOTPOS)) {\r\n\r\n str += \"<tr><td></td>\" \r\n\t + \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n var onc = \" onclick='changeCondKeyword(\\\"if\\\",\" + ExprType.If + \")'\";\r\n str += bstr + \"value='if' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeCondKeyword(\\\"else\\\",\" + ExprType.Else +\r\n \")'\";\r\n str += bstr + \"value='else' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeCondKeyword(\\\"else if\\\",\" +\r\n ExprType.ElseIf + \")'\";\r\n str += bstr + \"value='else if' \" + onc + \">\";\r\n //\r\n //var onc = \" onclick='changeCondKeyword(\\\"break if\\\",\" + \r\n // ExprType.BreakIf + \")'\";\r\n //str += bstr + \"value='break if' \" + onc + \">\";\r\n\r\n str += \"</td></tr>\";\r\n }\r\n\r\n\r\n // Add additional buttons for formula processing (break/return) if\r\n // the focus is on a formula box AND we are at the start of the formula\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isFormula() &&\r\n sO.activeParentExpr && sO.activeParentExpr.isExprStmt() &&\r\n (sO.activeChildPos == 0)) {\r\n\r\n str += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n // Let\r\n //\r\n var onc = \" onclick='addLetExpr()' \";\r\n str += bstr + \"value='let' \" + onc + \">\";\r\n //\r\n // Continue\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"continue\\\",\" +\r\n ExprType.Continue + \")'\";\r\n str += bstr + \"value='continue' \" + onc + \">\";\r\n //\r\n // Return\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"return\\\",\" +\r\n ExprType.Return + \")'\";\r\n str += bstr + \"value='return' \" + onc + \">\";\r\n //\r\n // Break\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"break\\\",\" +\r\n ExprType.Break + \")'\";\r\n str += bstr + \"value='break' \" + onc + \">\";\r\n //\r\n str += \"</td></tr>\";\r\n }\r\n\r\n // Add additional buttons for keywords if the focus is on a range box\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isRange() &&\r\n ((sO.activeChildPos == ROOTPOS) ||\r\n (sO.isSpaceActive && !sO.activeChildPos))) {\r\n\r\n str += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n var onc = \" onclick='changeLoopToForeach()' \";\r\n str += bstr + \"value='foreach' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeLoopToForever()' \";\r\n str += bstr + \"value='forever' \" + onc + \">\";\r\n\r\n str += \"</td></tr>\";\r\n }\r\n // STEP: Show/hide step options\r\n if(sO.showOptions) {\r\n\r\n\t// Show checkbox for user to specify enabling converting to OpenCL.\r\n\t// Example: for simple initializations the data transfer and OpenCL\r\n\t// overhead may outweigh the benefits (so don't transform step to\r\n\t// OpenCL kernel).\r\n\tvar onc = \"onclick='markOCLstep(this.checked)'\";\r\n if (sO.potOCLstep) onc += \" checked \";\r\n\tstr += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n str += \"<input type='checkbox' \" + onc + \">\" +\r\n\t \"Enable OpenCL (if step parallelizable)\" +\r\n\t \"</td></tr\";\r\n\r\n }\r\n \r\n //\r\n str += \"</table>\";\r\n\r\n // Write to code window HTML element\r\n //\r\n var cw1 = document.getElementById('codeWindow');\r\n cw1.innerHTML = str;\r\n\r\n\r\n // .....................................................................\r\n // STEP: Draw Action Buttons to the right of the window\r\n //\r\n var but1 = \"\",\r\n but2 = \"\",\r\n but3 = \"\";\r\n\r\n // buttons appear after grid selection\r\n //\r\n var has_but = sO.stageInStep >= StageInStep.GridSelectDone;\r\n //\r\n if (has_but) {\r\n\r\n var onc = \" onclick='addSource()' \";\r\n but1 = bstr + \"value='Add Source Grid' \" + onc;\r\n //\r\n }\r\n //\r\n var focusbox = sO.focusBoxId;\r\n var prop = \" type='button' class='formulabut' \"\r\n\r\n //\r\n str = \"<table class='operatorWin'>\"\r\n\r\n + \"<tr><td>\" + but1 + \"</td></tr>\"\r\n //+ \"<tr><td><div style='height:10px'></div></td></tr>\"\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Add Formula' onclick='addFormulaBox()'>\" + \"</td></tr>\"\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Add Condition' onclick='addMaskBox()'>\" + \"</td></tr>\";\r\n\r\n // Delete Box (don't allow deleting first 3 boxes -- TODO: relax this)\r\n //\r\n if (sO.focusBoxId > CodeBoxId.Range) {\r\n\r\n var val = (sO.boxAttribs[sO.focusBoxId].isMask()) ?\r\n \"Delete Condition\" : \"Delete Formula\";\r\n str += \"<tr><td>\" + \"<input\" + prop + \"value='\" + val +\r\n \"' onclick='deleteBox()'>\" + \"</td></tr>\";\r\n }\r\n\r\n\r\n str += \"<tr><td>\" + \"<input\" + prop +\r\n \"value='<=' onclick='updateBoxIndent(-1)' \";\r\n var dis = isBoxIndentLegal(focusbox, -1) ? \"\" : \" disabled \"\r\n str += dis + \">\"\r\n\r\n + \"<input\" + prop + \"value='=>' onclick='updateBoxIndent(1)' \";\r\n var dis = isBoxIndentLegal(focusbox, 1) ? \"\" : \" disabled \"\r\n str += dis + \"></td></tr>\"\r\n\r\n /*\r\n str += \"<tr><td>\"\r\n\t+ \"<img src='images/refresh.png' width=20px height=20px \" \r\n\t+ \" title='refresh step' onclick='refreshCurStep()'>\"\r\n\t+ \"</td></tr>\";\r\n */\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Options' onclick='showHideOptions()'>\" + \"</td></tr>\"\r\n + \"</table>\";\r\n\r\n var opw1 = document.getElementById('operatorWindow');\r\n opw1.innerHTML = str;\r\n\r\n}",
"function buildPromotionTable(filter_promotion) {\n\n $(\"#promotion_container\").empty();\n \n //greater than 480px viewport- Background Gradient \n $(\"#promotion_container\").addClass(\"details\");\n $(\"body\").addClass(\"bg\");\n\n //Index URL Promotion \n var promotion = promotion_data.promotion_objects.filter(function (promo) { return promo.promo_id == filter_promotion; })[0]\n console.log(promotion);\n //Index page \n var the_promohtml = $(\"<div>\").addClass(\"landing-page-promo-container\").addClass(\"holder\");\n\t//Back Button\n\tthe_promohtml.append($(\"<a/>\").addClass(\"return_state\").addClass(\"back\").attr(\"href\", \"./index.html\").attr(\"id\", \"home\").html(\"< Back\"));\n //Entry Deadline Date \n the_promohtml.append($(\"<div/>\").addClass(\"next-entry-deadline\").addClass(\"promotion-less\").html(\"The Next Entry Deadline is \" + new Date(promotion.drawings[0].entry_deadline).toLocaleString(\"en-us\", datetime_format) + \"!\"));\n //Banner Images calling \n the_promohtml.append($(\"<figure/>\").append($(\"<img/>\").attr(\"src\", promotion.promo_image_url).addClass(\"millionaire-madness\").attr(\"alt\", \"Millionaire-Madness\")));\n //define greater than 480px viewport and 480px or less viewport\n var promo_content_area = $(\"<div/>\").attr(\"id\", \"drawingdate-above480\");\n var promo_content_area_less = $(\"<div/>\").attr(\"id\", \"drawingdate-less480\").addClass(\"promotion-less\");\n \n //Add body-promotion content \n buildPromoInnerTable(promo_content_area, promotion,false)\n buildPromoInnerTable(promo_content_area_less, promotion,true)\n the_promohtml.append(promo_content_area);\n the_promohtml.append(promo_content_area_less);\n $(\"#promotion_container\").append(the_promohtml);\n\n}",
"function showMoreDetails(assocMenuTitle, thisObjId, nPageCurRowNo, nActualCurRowNo)\r\n{\r\n var nTssButtonsCnt = getElemnt(\"nTssButtonsCnt\").value;\r\n // 18 is the size of the Image to represent the curved button, adding 60 to take care of the extra space\r\n // occupied by the Dialog\r\n var height = (nTssButtonsCnt == 0 ? 80 : ((parseInt(nTssButtonsCnt) * 18) + 60) );\r\n var width = (nTssButtonsCnt == 0 ? 150 : 175);\r\n var thisObj = getElemnt(thisObjId);\r\n var posX = _findPosX(thisObj);\r\n var posY = _findPosY(thisObj);\r\n var assoc = $(\"#_assocmenupopup\"); \r\n // Destroy only this Div retain the assocmenypopup html as this will be needed to show again for\r\n // another row.\r\n var assocPopUpDiv = document.createElement(\"div\");\r\n assocPopUpDiv.id = \"assocPopUpDiv\";\r\n var assocPopUpHTML = assoc.html();\r\n\r\n assocPopUpDialog = $(assocPopUpDiv).dialog({\r\n \t\t\ttitle: assocMenuTitle,\r\n height: height,\r\n\t\t\twidth : width,\r\n\t\t\tzIndex: 900,\r\n position:[posX, posY],\r\n modal : true,\r\n\t\t\tclose : function(event, ui) {\r\n\r\n \t\t\t\t\t\tif(newCommentsDiv) {\r\n \t\t\t\t\t\t\tnewCommentsDiv.dialog(\"close\");\r\n \t\t\t\t\t\t}\r\n\r\n $(\"#nActualCurRowNoObj\").val('');\r\n $(\"#nPageCurRowNo\").val('');\r\n $(this).html('');\r\n \t\t\t$(this).dialog('destroy');\r\n \t\t\t$(this).remove();\r\n \t\t\t}\r\n \t\t});\r\n // --------------------------------------------------------------\r\n // Make the background white instead of greying.\r\n var overlay = $(\".ui-widget-overlay\");\r\n baseBackground = overlay.css(\"background\");\r\n baseOpacity = overlay.css(\"opacity\");\r\n overlay.css(\"background\", \"#FFF\").css(\"opacity\", \"0\");\r\n // --------------------------------------------------------------\r\n\r\n // --------------------------------------------------------------\r\n // Close Button functionality\r\n var titleBar = $(\".ui-dialog-titlebar a.ui-dialog-titlebar-close\");\r\n titleBar.removeClass(\"ui-corner-all\");\r\n titleBar.find(\".ui-icon\").html(\"<IMG id=closeImg src='images/close_top.gif' border=0>\").removeClass();\r\n\r\n assocPopUpDialog.html(assocPopUpHTML);\r\n $('#nav').collapsible({xoffset:'-12',yoffset:'10', imagehide: 'images/arrowdown.gif',\r\n imageshow: 'images/Rarrow.gif', defaulthide: false});\r\n\r\n var divObject = $(\"div.ui-helper-clearfix\");\r\n divObject.removeClass(\"ui-widget-header\");\r\n divObject.addClass(\"clsPopUpTitleBar\");\r\n divObject.removeClass(\"ui-dialog-titlebar\");\r\n\r\n var spanObject = $(\"span.ui-dialog-title\");\r\n spanObject.html(\"<label style='white-space: nowrap;font-weight: bold '>\" + assocMenuTitle+\"</label>\" ); \r\n\r\n // Set the nActualCurRowNo and nPageCurRowNo to hidden html objects so that these will be available\r\n // when user clicks any of the association.\r\n var nPageCurRowNoObj = getElemnt(\"nPageCurRowNo\");\r\n nPageCurRowNoObj.value = nPageCurRowNo;\r\n\r\n var nActualCurRowNoObj = getElemnt(\"nActualCurRowNo\");\r\n nActualCurRowNoObj.value = nActualCurRowNo;\r\n}",
"function buildTable() {\n var table = document.getElementById(\"propertiesTable\");\n for (var i = 0; i < Properties.size; i++) {\n var eth = 1000000000000000000;\n var row = table.insertRow(i+1);\n var cell0 = row.insertCell(0);\n var cell1 = row.insertCell(1);\n var cell2 = row.insertCell(2);\n var cell3 = row.insertCell(3);\n cell0.innerHTML = \"<b><font size=\\\"4\\\"><i class=\\\"ni ni-building\\\"></i> \" + Properties.get(i)[0] + \"</b></font>\";\n cell1.innerHTML = Properties.get(i)[1];\n var boughtTokens = Properties.get(i)[1] - Properties.get(i)[3];;\n cell2.innerHTML = boughtTokens;\n cell3.innerHTML = boughtTokens * Properties.get(i)[2].toNumber()/eth;\n\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using Helper function takes two values string s and start value Check if map has s if so get the value Iterate through the s with end being start + 1 so we can get the words in wordDict trim the s string with start and end Recursively ensure if trim is in dict set If so set the trimmed value in map and return true Else set the trimmed value is not in map and return false; | function helperMethod(s, start) {
if (start === s.length) return true;
if (map.has(s)) return map.get(s);
for (let end = start + 1; end <= s.length; end++) {
let trim = s.slice(start, end);
if (dict.has(trim) && helperMethod(s, end)) {
map.set(start, true);
return true;
}
}
map.set(start, false);
return false;
} | [
"function isPrefix(trie, word){ \n for(let temp_word of trie){\n if( temp_word.substr(0, word.length) == word){\n return true;\n }\n }\n return false; \n}",
"function checkInclusion(s1, s2) {\n let k = s1.length;\n let s1Count = new Map();\n let s2Count = new Map();\n\n for (let i = 0; i < k; i++) {\n if (!s1Count.has(s1[i])) {\n s1Count.set(s1[i], 1);\n } else {\n s1Count.set(s1[i], s1Count.get(s1[i]) + 1);\n }\n }\n\n // sliding window\n let i = 0, j = 0;\n\n while (j < s2.length) {\n if (!s2Count.has(s2[j])) {\n s2Count.set(s2[j], 1);\n } else {\n s2Count.set(s2[j], s2Count.get(s2[j]) + 1);\n }\n\n if (j - i + 1 == k) {\n if (mapsAreEqual(s1Count, s2Count)) {\n return true;\n } else {\n s2Count.set(s2[i], s2Count.get(s2[i]) - 1);\n\n if (s2Count.get(s2[i]) == 0) {\n s2Count.delete(s2[i]);\n }\n\n i++;\n }\n }\n\n j++;\n }\n\n return false;\n}",
"function isWord(\n sourceDoc,\n begin,\n end,\n isDelimiterFunc\n ) {\n const precedingChar = sourceDoc.charAt(begin - 1)\n const followingChar = sourceDoc.charAt(end)\n\n return isDelimiterFunc(precedingChar) && isDelimiterFunc(followingChar)\n } // CONCATENATED MODULE: ./src/lib/Editor/AnnotationData/getReplicationRanges/index.js",
"search(word) {\n let root = this.root \n while (word.length > 0) {\n let char = ward[0]\n if (root[char]) {\n word = word.substr(1)\n root = root[char]\n } else {\n return false;\n }\n }\n\n // Returns if there is any word in the trie that starts with the given prefix\n //startsWith(prefix) {}\n}",
"static evalLowerRangeIsEmpty(dict) {\n return libVal.evalIsEmpty(dict.LowerRange);\n }",
"function canMatchBegin(word1, word2) {\n \t\t\tif(word1[0] == \"*\" || word2[0] == \"*\") {\n \t\t\t\treturn true;\n \t\t\t}\n \t\t\tlet toCompare = Math.min(word1.indexOf(\"*\"), word2.indexOf(\"*\"));\n \t\t\treturn word1.slice(0, toCompare) == word2.slice(0, toCompare);\n \t\t}",
"function isBalanced(substr){\n if(!substr) return false;\n let seen=new Set(substr);\n\n \n for(let [cur] of seen){\n let lower=cur.slice(0).toLowerCase();\n let upper=cur.slice(0).toUpperCase();\n if(!seen.has(lower) || !seen.has(upper)){ // if either upper or lowercase of the character is missing its not balanced\n return false;\n }\n }\n \n return true;\n }",
"function trimSubStr(trimStr, subStr,aWay){ \r\n var tTrLength,tSbLength,tempLength; \r\n var tempString; \r\n var i; \r\n\r\n tTrLength = trimStr.length; \r\n tSbLength = subStr.length; \r\n\r\n if(tSbLength == 0){return trimStr;} \r\n if(tSbLength > tTrLength){return trimStr;} \r\n \r\n tempString = trimStr; \r\n switch(aWay){ \r\n case 0://all \r\n do{ \r\n tempLength = tempString.length; \r\n tempString = tempString.replace(subStr, \"\"); \r\n }while(tempLength != tempString.length); \r\n break; \r\n case 1://from left \r\n while(true){ \r\n if(tempString.length < tSbLength) \r\n \tbreak; \r\n for(i = 0; i < tSbLength; i++) \r\n if(subStr.charAt(i) != tempString.charAt(i)) \r\n return tempString; \r\n tempString = tempString.replace(subStr,\"\"); \r\n }; \r\n case 2://from right \r\n while(true){ \r\n tempLength = tempString.length; \r\n if(tempLength < tSbLength){\r\n \treturn tempString;\r\n } \r\n for(i = 0; i < tSbLength; i++){ \r\n if(subStr.charAt(i) != tempString.charAt(tempLength - tSbLength + i)){ \r\n return tempString; \r\n } \r\n } \r\n tempString = tempString.substr(0,tempLength-tSbLength); \r\n }; \r\n default: \r\n return tempString; \r\n } \r\n return tempString; \r\n}",
"areWordsAnagrams(words) {\n if(words.length === 0) {\n return true;\n }\n\n //All words need to be the same length in order to anagrams\n let length = words[0].length;\n for(let word of words) {\n if(word.length !== length) {\n return false;\n }\n }\n //Bah the worst! Lets go ahead and check the words\n let wordsMap = {};\n for(let word of words) {\n wordsMap[word] = word;\n }\n let localDictionary = new Dictionary(words);\n let anagrams = this.findAnagramsWithoutCache(words[0], localDictionary);\n return (anagrams.length === (words.length - 1));\n }",
"buildWordsMapAndSentences(recordingData) {\n let index = 0, start;\n\n // skip if recording data is same as before\n if (JSON.stringify(recordingData) === JSON.stringify(this.recordingData)) return;\n\n this.mapWords = {};\n this.sentences = [];\n this.recordingData = recordingData;\n\n if (!this.isValidRecordingData()) return;\n\n start = this.getIndexOfFirstWord();\n\n while (start !== -1) {\n let word = recordingData[start][0];\n\n if (typeof this.mapWords[word] === 'undefined') {\n this.mapWords[word] = [];\n }\n\n this.mapWords[word].push(index);\n this.sentences.push(word);\n\n start = recordingData[start][2];\n index += 1;\n }\n }",
"function isValidDictionaryKey(key){\n if(key == \"\") return false;\n if(key.indexOf(\"\\\"\") != -1) return false;\n return true;\n}",
"function isPrefix(word, prefix) {\n\treturn word.startsWith(prefix.slice(0, -1));\n}",
"function removeStopWords(wordArr) {\n return function(stopWordsString) {\n var stopWords = new Set(stopWordsString.split(\",\"));\n var filteredList = [];\n for (var word in wordArr) {\n wordArr[word] = wordArr[word].toLowerCase();\n if (!(stopWords.has(wordArr[word])) && wordArr[word].length >= 2) {\n filteredList.push(wordArr[word]);\n }\n }\n return filteredList;\n }\n \n}",
"mapStart() {\n return this.txt.match(/^\\[\\s*/i);\n }",
"function startend(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.startsWith(\"saya\"));\n\tconsole.log(aku.endsWith(\"di\"));\n\t}",
"function compareSet(base,arr){\r\n\tvar tot = 0;\r\n\tvar matched_any = false;\r\n\tvar breakable = false;\r\n\tvar invalid = false;\r\n\t\r\n\tvar words = base.words;\r\n\tvar in_arr = arr;\r\n\t\r\n\tvar a = 0;\r\n\tvar b = 0;\r\n\t\r\n\tfor (b in words) {\r\n\t\tvar b_w = words[b];\r\n\t\t\t\r\n\t\tfor(a in in_arr){\r\n\t\t\tvar in_w = in_arr[a];\r\n\t\t\t\r\n\t\t\tif(typeof(b_w) == \"object\"){\r\n\t\t\t\tconsole.log(\"checkList in keylist - \" + base.action);\r\n\t\t\t\tif(iterateCheckList(b_w,in_w)){\r\n\t\t\t\t\tvar invalid = false;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar invalid = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(typeof(b_w) == \"function\"){\r\n\t\t\t\tconsole.log('function in keylist - ' + base.action);\r\n\t\t\t\tvar b = b_w(in_w); //TODO if match => userInput.check[base.id] = in_w\r\n\t\t\t\tif(b == true){\r\n\t\t\t\t\t//userInput.check[base.id] = in_w;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(b_w == in_w){\r\n\t\t\t\ttot += 1;\r\n\t\t\t\tif (base.any) {\r\n\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(breakable)\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\tvar tot_a = tot/in_arr.length; \t// the % of matched words in 'arr'\r\n\tvar tot_b = typeof(words) == \"object\" ? tot/words.length : 0.5; \t// the % of matched words in 'base'\r\n\t\r\n\t// if base.any && matched_any => return 1.0 else return median of tot_a & tot_b\r\n\tvar p = matched_any ? 1.0 : (tot_a+tot_b)*0.5;\r\n\tif (invalid)\r\n\t\tp = 0;\r\n\t\r\n\t//var f = p < 0.5 ? 0 : p;\r\n\t\r\n\t/* console.log(\"tot_matched: \" + tot,\r\n\t\t\t\t\"percent: \" + (tot_a+tot_b)*0.5,\r\n\t\t\t\t\"final score: \" + p); */\r\n\t\r\n\treturn p;\r\n}",
"_createPhraseMap(paragraph) {\n this.map = {};\n // poor Big O notation, but gets job done for now\n for(let sentence of paragraph) {\n // array of each word per sentence\n this.words = sentence.match(/\\w+/g);\n\n // starting with first word\n for(let i = 0; i < this.words.length; i ++) {\n // and continuing to 3rd to 10th word in string\n for(let j = i + 2; j < this.words.length && j <= i + 9; j++) {\n this.currentPhrase = this.words.slice(i, j + 1).join(' ');\n\n // add phrase as property to map if it doesn't already exist\n if(!this.map[this.currentPhrase]) this.map[this.currentPhrase] = 0;\n // then increment its occurrence\n this.map[this.currentPhrase] ++;\n }\n }\n }\n }",
"function findWordsOnBoard()\n{\n var x,y;\n resetFoundWordList();\n heatMapReset();\n\n // Make sure a dictionary is loaded\n if (wordTree != null) {\n for (x = 0; x < boardTiles.length; x++) {\n for (y = 0; y < boardTiles[x].length; y++) {\n\n // Feed in :\n // * current tile (x,y)\n // * root node of the radix/trie word tree\n // * word length 0\n // * blank working string\n checkBoardTile(x, y, wordTree, 0, \"\");\n }\n }\n }\n\n debugLogFoundWords();\n\n if (foundWordCount > 0)\n {\n setStatusItemState('statusWords','success');\n return (true);\n }\n else\n {\n setStatusItemState('statusWords','error');\n return (false);\n }\n\n}",
"function isPrefix(sub,str) {\n return str.lastIndexOf(sub,0)===0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes the ISR for the fs with the create flag. | function krnDiskCreate(fileName, callBack)
{
_KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,
[FS_OPS.CREATE,fileName, null, callBack ? callBack : krnPutAndDrop]));
} | [
"function krnDiskDelete(fileName, callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.DELETE, fileName, null, callBack ? callBack : krnPutAndDrop]));\n}",
"function krnDiskLS(callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.LS, null, null, callBack ? callBack : krnPutAndDrop]));\n}",
"function krnDiskWrite(fileName, data, callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.WRITE, fileName, data, callBack ? callBack : krnPutAndDrop]));\n}",
"function krnDiskRead(fileName, literal, callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.READ, fileName, literal, callBack ? callBack : krnPutAndDrop]));\n}",
"function adminService(msg, callback) {\n\n switch (msg['cmd']) {\n case 'REGISTER':\n var rdevid = msg['actarg'];\n msg['cmd'] = 'REGISTER-ACK';\n msg['actid'] = deviceParams.getItem('deviceId');\n // Changes\n cNodeCount++;\n if (devTable[rdevid] === undefined) {\n // Registration request is for a new device\n msg['opt'] = 'NEW';\n devTable[rdevid] = {time: Date.now(), tag: \"none\"};\n callback(msg);\n }\n else\n {\n // Request for a devices already registered\n msg['opt'] = 'OLD';\n callback(msg);\n }\n break;\n case 'REF-CF-INFO':\n var rdevid = msg['actarg'];\n var drecord = devTable[rdevid];\n if (drecord !== undefined && drecord.tag === \"registered\")\n ebus.trigger();\n break;\n case 'GET-CF-INFO':\n var rdevid = msg['actarg'];\n // Check whether we have already registered the callbacks.\n // If we don't do this.. we will end up getting many callbacks to a C\n // node and it will go crazy!\n var drecord = devTable[rdevid];\n if (drecord !== undefined && drecord.tag === \"none\") {\n drecord.tag = \"registered\";\n } else {\n break;\n }\n\n if (machtype === globals.NodeType.DEVICE) {\n msg['cmd'] = 'PUT-CF-INFO';\n\n ebus.on('fog-up', function(fogId, connInfo) {\n // console.log('(adminService) FOG UP: id: ' + fogId + ', ip: ' + connInfo.ip + ', port: ' + connInfo.port);\n msg['opt'] = 'ADD';\n msg['actarg'] = globals.NodeType.FOG;\n msg['actid'] = fogId;\n msg['args'] = [getURL(connInfo.ip, connInfo.port)];\n callback(msg);\n });\n ebus.on('fog-down', function(id, info) {\n // console.log('(adminService) FOG DOWN: id: ' + id);\n msg['opt'] = 'DEL';\n msg['actarg'] = globals.NodeType.FOG;\n msg['actid'] = id;\n msg['args'] = [getURL(info.ip, info.port)];\n callback(msg);\n });\n ebus.on('cloud-up', function(cloudId, connInfo) {\n console.log('(adminService) CLOUD UP: id: ' + cloudId + ', ip: ' + connInfo.ip + ', port: ' + connInfo.port);\n msg['opt'] = 'ADD';\n msg['actarg'] = globals.NodeType.CLOUD;\n msg['actid'] = cloudId;\n msg['args'] = [getURL(connInfo.ip, connInfo.port)];\n callback(msg);\n });\n ebus.on('cloud-down', function(id, info) {\n console.log('(adminService) CLOUD DOWN: id: ' + id);\n msg['opt'] = 'DEL';\n msg['actarg'] = globals.NodeType.CLOUD;\n msg['actid'] = id;\n msg['args'] = [getURL(info.ip, info.port)];\n callback(msg);\n });\n ebus.on('data-up', function(dinfo) {\n msg['opt'] = 'ADD';\n msg['actarg'] = 'redis';\n msg['actid'] = '-';\n msg['args'] = [dinfo.host, dinfo.port];\n callback(msg);\n });\n ebus.trigger();\n var rinfo = jsys.getRedis();\n if (rinfo !== undefined) {\n msg['opt'] = 'ADD';\n msg['actarg'] = 'redis';\n msg['actid'] = '-';\n msg['args'] = [rinfo.host, rinfo.port];\n callback(msg);\n }\n }\n break;\n default:\n console.log('AdminService:: UNKNOWN CMD: ' + msg['cmd'] + ' received.. ');\n throw('UNKNOWN COMMAND');\n }\n\n}",
"function krnDiskFormat(callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.FORMAT, null, null, callBack ? callBack : krnPutAndDrop]));\n}",
"function createCFC()\n{\n\tMM.CFCfileToOpen = \"\";\n\n\tdw.runCommand(\"Create Component.htm\");\n\n\t// If all went well in this command, then we are told (through a MM variable) the\n\t// path to the new CFC file... which we can now open. We avoid opening this CFC\n\t// file in the command itself because doing so tickles a problem in the internal\n\t// mechanism the Kojak uses for suspending/continuing edit ops.\n\n\tif (MM.CFCfileToOpen.length > 0)\n\t{\n\t\tvar newDOM = dreamweaver.openDocumentFromSite(MM.CFCfileToOpen);\n\n\t\t// There is no longer any need to switch into code view here because we have fixed\n\t\t// Dreamweaver to automatically switch into code view whenever a CFC file is opened\n\t\t// regardless of how that file is opened.\n\t\t/***********************************\n\t\tif (newDOM != null)\n\t\t{\n\t\t newDOM.setView(\"code\");\n\t\t}\n\t\t***********************************/\n\n\t\tFWLaunch.bringDWToFront();\n\t\tMM.CFCfileToOpen = \"\";\n\n\t\tclickedRefresh();\n\t}\n}",
"function createKernel(options, id) {\n return new Promise(function (resolve, reject) {\n var kernel = new Kernel(options, id);\n var callback = function (sender, status) {\n if (status === ikernel_1.KernelStatus.Starting || status === ikernel_1.KernelStatus.Idle) {\n kernel.statusChanged.disconnect(callback);\n runningKernels.set(kernel.id, kernel);\n resolve(kernel);\n }\n else if (status === ikernel_1.KernelStatus.Dead) {\n kernel.statusChanged.disconnect(callback);\n reject(new Error('Kernel failed to start'));\n }\n };\n kernel.statusChanged.connect(callback);\n });\n}",
"async startIpfs () {\n try {\n console.log('Setting up instance of IPFS...')\n this.statusLog('Setting up instance of IPFS...')\n\n // Use DHT routing and ipfs.io delegates.\n const ipfsOptions = {\n config: {\n Bootstrap: [\n '/dns4/ipfs-service-provider.fullstackcash.nl/tcp/443/wss/ipfs/QmbyYXKbnAmMbMGo8LRBZ58jYs58anqUzY1m4jxDmhDsjd',\n '/dns4/go-ipfs-wss.fullstackcash.nl/tcp/443/wss/ipfs/QmTtXA18C6sg3ji9zem4wpNyoz9m4UZT85mA2D2jx2gzEk'\n ],\n Swarm: {\n ConnMgr: {\n HighWater: 30,\n LowWater: 10\n },\n AddrFilters: []\n },\n Routing: {\n Type: 'dhtclient'\n }\n },\n libp2p: {\n config: {\n dht: {\n enabled: true,\n clientMode: true\n }\n }\n }\n }\n\n this.ipfs = await IPFS.create(ipfsOptions)\n this.statusLog('IPFS node created.')\n\n // Set a 'low-power' profile for the IPFS node.\n await this.ipfs.config.profiles.apply('lowpower')\n\n // Generate a new wallet.\n // this.wallet = new BchWallet()\n // console.log(\"this.wallet: \", this.wallet);\n\n if (!this.wallet) {\n throw new Error('Wallet Not Found.! . Create or import a wallet')\n }\n // Wait for the wallet to initialize.\n await this.wallet.walletInfoPromise\n\n // Instantiate the IPFS Coordination library.\n this.ipfsCoord = new IpfsCoord({\n ipfs: this.ipfs,\n type: 'browser',\n statusLog: this.statusLog, // Status log\n bchjs: this.wallet.bchjs,\n mnemonic: this.wallet.walletInfo.mnemonic,\n privateLog: this.privateLog,\n announceJsonLd\n })\n this.statusLog('ipfs-coord library instantiated.')\n\n // Wait for the coordination stuff to be setup.\n await this.ipfsCoord.isReady()\n\n const nodeConfig = await this.ipfs.config.getAll()\n console.log(\n `IPFS node configuration: ${JSON.stringify(nodeConfig, null, 2)}`\n )\n\n // subscribe to the 'chat' chatroom.\n await this.ipfsCoord.ipfs.pubsub.subscribeToPubsubChannel(\n CHAT_ROOM_NAME,\n this.handleChatLog\n )\n\n // Pass the IPFS instance to the window object. Makes it easy to debug IPFS\n // issues in the browser console.\n if (typeof window !== 'undefined') window.ipfs = this.ipfs\n\n // Get this nodes IPFS ID\n const id = await this.ipfs.id()\n this.ipfsId = id.id\n this.statusLog(`This IPFS node ID: ${this.ipfsId}`)\n\n console.log('IPFS node setup complete.')\n this.statusLog('IPFS node setup complete.')\n _this.statusLog(' ')\n } catch (err) {\n console.error('Error in startIpfs(): ', err)\n this.statusLog(\n 'Error trying to initialize IPFS node! Have you created a wallet?'\n )\n }\n }",
"function startNew(options) {\n return __awaiter(this, void 0, void 0, function* () {\n let settings = options.serverSettings || __1.ServerConnection.makeSettings();\n let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);\n let init = {\n method: 'POST',\n body: JSON.stringify({ name: options.name })\n };\n let response = yield __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n throw new __1.ServerConnection.ResponseError(response);\n }\n let data = yield response.json();\n validate.validateModel(data);\n return new DefaultKernel(Object.assign({}, options, { name: data.name, serverSettings: settings }), data.id);\n });\n }",
"visitCreate_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function create(e) {\n\t\tvar fullPath = path.join(e.watch, e.name), i;\n\n\t\t// if it's in a watched directory or in the set of watches\n\t\tif (watches[e.watch] || watches[fullPath]) {\n\t\t\t// TODO: not sure if this will ever fail\n\t\t\tif (createQueue.indexOf(fullPath) < 0) {\n\t\t\t\tcreateQueue.push(fullPath);\n\t\t\t}\n\t\t\t\n\t\t\t// just in case the file was moved onto\n\t\t\ti = removeQueue.indexOf(fullPath);\n\t\t\tif (i >= 0) {\n\t\t\t\tremoveQueue.splice(i, 1);\n\t\t\t}\n\n\t\t\tcreateWatches(createQueue);\n\t\t}\n\t}",
"function launchVMSimple2() {\n\n getSubnetInfo(function(err, subnetInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n createNIC(subnetInfo, null, function(err, nicInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n\n createVirtualMachine(nicInfo.id, function(err, vmInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n\n console.log('Created VM: ', util.inspect(vmInfo, {\n depth: null\n }));\n\n });\n });\n });\n\n}",
"async function fnStartRemoteAPI(){\n if (fs.existsSync(\"/share/config.json\") !== true && fs.existsSync(\"/share/config.gen.js\") !== true && fs.existsSync(\"/share/remote-api.json\")){\n try {\n if (fs.existsSync(\"/startup/remote-api.started\") !== true || fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n console.log(`[LOG] EasySamba Remote API is enabled and is starting...`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n fnSpawn(\"node\", [\"/startup/remote-api/index.js\"]);\n await fnSleep(2000);\n if (fs.existsSync(\"/startup/remote-api.started\")){\n console.log(`[LOG] EasySamba Remote API started successfully.\\n`);\n }\n else {\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n catch (error){\n if (fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n fnDeleteFile(\"/startup/remote-api.started\");\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n else {\n if (fs.existsSync(\"/startup/remote-api.started\") || fnIsRunning(\"node /startup/remote-api/index.js\")){\n console.log(`[LOG] EasySamba Remote API is not enabled and won't be started.\\n`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n }\n }\n}",
"function systemOn (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"async start () {\n log('starting')\n\n // start the daemon\n this._ipfs = await IPFS.create(\n Object.assign({}, { start: true, libp2p: getLibp2p }, this._options)\n )\n\n // start HTTP servers (if API or Gateway is enabled in options)\n this._httpApi = new HttpApi(this._ipfs)\n await this._httpApi.start()\n\n this._httpGateway = new HttpGateway(this._ipfs)\n await this._httpGateway.start()\n\n const config = await this._ipfs.config.getAll()\n\n if (config.Addresses && config.Addresses.RPC) {\n this._grpcServer = await gRPCServer(this._ipfs)\n }\n\n log('started')\n }",
"toggleSidenavNewFile() {\n if (this._sidenavExtra.newFile.opened) {\n this._sidenavExtra.newFile.opened = false;\n\n $('#hidden-new-file').hide();\n $('#new-file-name').val('');\n $('#hidden-new-file-info').empty();\n } else {\n this._sidenavExtra.newFile.opened = true;\n $('#hidden-new-file').fadeIn('fast');\n }\n }",
"function CreateSystemFile(systemName)\r\n{\r\n\ttry {\r\n\t\tvar sysFile = FSO.CreateTextFile(systemName, true); // Make new system file\r\n\t\t} catch(e) {\r\n\t\t\tthrow \"**Failed to create system file: \" + systemName + \" : \" +\r\n\t\t\t(e.description ? e.description : e);\r\n\t\t}\t\r\n\tsysFile.WriteLine(\"BrewSystemSwap Version: \" + SCRIPTVERSION); \r\n\r\n\tsysFile.Close();\r\n}",
"performedUserAction() {\n this.autoScanManager_.restartIfRunning();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method will disconnect socket Return promise or callback | disconnect(callback) {
return new promise(
(resolve, reject) => {
// Make sure socket exist and status is connected
if (this.socket && this.isConnected === true) {
// Socket exists
this.isConnected = false
this.socket.disconnect()
return callback ? callback(null, true) : resolve(true)
} else {
this.isConnected = false
let err = new Error('Socket is not connected to disconnect.')
return callback ? callback(err, null) : reject(err)
}
}
)
} | [
"function disconnect(){\n if(socket.connected){\n socket.disconnect();\n }\n}",
"disconnect() {\n\t\tthis.debug('Requesting disconnect from peer');\n\t}",
"close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }",
"close(callback) {\r\n debugLog(\"ServerSecureChannelLayer#close\");\r\n // close socket\r\n this.transport.disconnect(() => {\r\n this._abort();\r\n if (_.isFunction(callback)) {\r\n callback();\r\n }\r\n });\r\n }",
"destroy(callback) {\n const connections = Object.keys(this.namespace.connected);\n\n\n let self = this;\n this.print(`Disconnecting all sockets`);\n connections.forEach((socketID) => {\n this.print(`Disconnecting socket: ${socketID}`);\n self.namespace.connected[socketID].disconnect();\n });\n\n this.print(`Removing listeners`);\n this.namespace.removeAllListeners();\n callback(this.endpoint);\n }",
"function disconnect() {\n return waitForRPCs(/*disconnectFromServers*/ true);\n}",
"function onSocketClose() {\n this[owner_symbol].destroy();\n}",
"unbind() {\n return this._send(new UnbindRequest(), () => this._socket.close());\n }",
"disconnect() {\n\t\t\tthis.connected = false;\n\t\t\t// Emitting event 'disconnect', 'exit' and finally 'close' to make it similar to Node's childproc & cluster\n\t\t\tthis._emitLocally('disconnect');\n\t\t}",
"function wsCloseConnection(){\n\twebSocket.close();\n}",
"onChromeVoxDisconnect_() {\n this.port_ = null;\n this.log_('onChromeVoxDisconnect', chrome.runtime.lastError);\n }",
"disconnectBroker$() {\n return Rx.fromPromise(this.mqttClient.end());\n }",
"destroy(error) {\n // If the QuicSocket is already destroyed, do nothing\n if (this.#state === kSocketDestroyed)\n return;\n\n // Mark the QuicSocket as being destroyed.\n this.#state = kSocketDestroyed;\n\n // Immediately close any sessions that may be remaining.\n // If the udp socket is in a state where it is able to do so,\n // a final attempt to send CONNECTION_CLOSE frames for each\n // closed session will be made.\n for (const session of this.#sessions)\n session.destroy(error);\n\n this[kDestroy](error);\n }",
"close(callback) {\n if (this.#state === kSocketDestroyed)\n throw new ERR_QUICSOCKET_DESTROYED('close');\n\n // If a callback function is specified, it is registered as a\n // handler for the once('close') event. If the close occurs\n // immediately, the close event will be emitted as soon as the\n // process.nextTick queue is processed. Otherwise, the close\n // event will occur at some unspecified time in the near future.\n if (callback) {\n if (typeof callback !== 'function')\n throw new ERR_INVALID_CALLBACK();\n this.once('close', callback);\n }\n\n // If we are already closing, do nothing else and wait\n // for the close event to be invoked.\n if (this.#state === kSocketClosing)\n return;\n\n // If the QuicSocket is otherwise not bound to the local\n // port, destroy the QuicSocket immediately.\n if (this.#state !== kSocketBound) {\n this.destroy();\n }\n\n // Mark the QuicSocket as closing to prevent re-entry\n this.#state = kSocketClosing;\n\n // Otherwise, gracefully close each QuicSession, with\n // [kMaybeDestroy]() being called after each closes.\n const maybeDestroy = this[kMaybeDestroy].bind(this);\n\n // Tell the underlying QuicSocket C++ object to stop\n // listening for new QuicServerSession connections.\n // New initial connection packets for currently unknown\n // DCID's will be ignored.\n if (this[kHandle]) {\n this[kHandle].stopListening();\n }\n this.#serverListening = false;\n\n // If there are no sessions, calling maybeDestroy\n // will immediately and synchronously destroy the\n // QuicSocket.\n if (maybeDestroy())\n return;\n\n // If we got this far, there a QuicClientSession and\n // QuicServerSession instances still, we need to trigger\n // a graceful close for each of them. As each closes,\n // they will call the kMaybeDestroy function. When there\n // are no remaining session instances, the QuicSocket\n // will be closed and destroyed.\n for (const session of this.#sessions)\n session.close(maybeDestroy);\n }",
"async function endSession() {\n updateStatus(\"Ending Call\");\n console.log(`Ending session: ${internal_call_id}`);\n\n try {\n var res = await fetch(\"/endSession?room_name=\" + internal_call_id);\n\n // basic error handling\n if (res.status !== 200) {\n console.log(res);\n alert(\"Failed to end your session: \" + res.status);\n return;\n } else {\n updateStatus(\"Call Ended\");\n }\n } catch (error) {\n console.log(`failed to end the session ${error}`);\n console.log(\"we'll keep cleaning up though\");\n }\n\n // clear out any remaining connections\n other_callers.forEach(function (caller) {\n disconnectEndpoint(caller);\n });\n}",
"disconnectBoard(event){\n event.preventDefault();\n setLedBoardColour(this.state.socket, this.state.deviceName, 0, 0, 0);\n this.setState({ boardConnected: false });\n this.props.updateBoardDeviceName(undefined);\n\n clearInterval(this.state.socketPingInterval);\n disconnectWebSocket(this.state.socket);\n this.setState({socket: undefined, socketPingInterval: undefined});\n this.props.updateSocket(undefined);\n }",
"get destroyed() {\n return this.#state === kSocketDestroyed;\n }",
"close() {\r\n // clear recorder cache\r\n return new Promise((resolve, reject) => {\r\n if (this.httpProxyServer) {\r\n // destroy conns & cltSockets when closing proxy server\r\n for (const connItem of this.requestHandler.conns) {\r\n const key = connItem[0];\r\n const conn = connItem[1];\r\n logUtil.printLog(`destorying https connection : ${key}`);\r\n conn.end();\r\n }\r\n\r\n for (const cltSocketItem of this.requestHandler.cltSockets) {\r\n const key = cltSocketItem[0];\r\n const cltSocket = cltSocketItem[1];\r\n logUtil.printLog(`closing https cltSocket : ${key}`);\r\n cltSocket.end();\r\n }\r\n\r\n if (this.socketPool) {\r\n for (const key in this.socketPool) {\r\n this.socketPool[key].destroy();\r\n }\r\n }\r\n\r\n this.httpProxyServer.close((error) => {\r\n if (error) {\r\n logUtil.printLog(`proxy server close FAILED : ${error.message}`, logUtil.T_ERR);\r\n } else {\r\n this.httpProxyServer = null;\r\n this.status = PROXY_STATUS_CLOSED;\r\n logUtil.printLog(`proxy server closed at ${this.proxyHostName}:${this.proxyPort}`);\r\n resolve(\"CLOSED\");\r\n }\r\n reject(error);\r\n });\r\n } else {\r\n resolve();\r\n }\r\n })\r\n }",
"async function onDisconnect(socket) {\n // socket.rooms is at this moment already emptied (by socket.IO)\n const mapping = registry.getMapping(socket.id);\n\n if (!mapping) {\n // this happens if user is on landing page, socket was opened, then user leaves - socket disconnects, user never joined a room. Perfectly fine.\n return;\n }\n\n const {userId, roomId} = mapping;\n\n if (registry.isLastSocketForUserId(userId)) {\n // we trigger a \"leaveRoom\" command\n const leaveRoomCommand = {\n id: uuid(),\n roomId: roomId,\n userId,\n name: 'leaveRoom',\n payload: {\n connectionLost: true // user did not send \"leaveRoom\" command. But connection was lost (e.g. browser closed)\n }\n };\n await handleIncomingCommand(socket, leaveRoomCommand);\n } else {\n // we have another socket mapped for that userId (e.g. multiple tabs open)\n // just remove the mapping for this socketId\n registry.removeSocketMapping(socket.id);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
6c Create a validate integer function that takes a number as a parameter and returns true if it is an integer. | function validateInteger(value) {
return Number.isInteger(value);
} | [
"function isInteger(test) {\n\tif ( !isNaN(parseInt(test,10)) && parseInt(Number(test)) == test ) {\n\t\treturn ( test > 0 );\n\t}\n\treturn false;\n\n}",
"function isNumeric(input) {\n return Number.isInteger(input)\n}",
"function safeParseInt(value) {\n if (!value) {\n return 0;\n }\n if (ok(value, tyString)) {\n return parseInt(value, 10);\n }\n if (ok(value, tyNumber)) {\n return value;\n }\n return 0;\n }",
"function isNumber (input) {\n \t\treturn typeof input === \"number\" && !isNaN(input); \n }",
"function ValidateIntField(id, name, min, max, allowempty) {\n fieldvalue = document.getElementById(id).value;\n\n if (validation == false) {\n return;\n }\n\n if ( (fieldvalue == '') && (allowempty) ) {\n return true;\n }\n\n if (isNumber(fieldvalue)) {\n if ((fieldvalue < min) || (fieldvalue > max)) {\n alert(\"The field \" + name + \" needs to be within \" + min + \" and \" + max);\n setFocus(id);\n return false;\n }\n }\n else {\n alert(\"The field \" + name + \" needs to be an integer (whole number) value.\");\n setFocus(id);\n return false;\n }\n return true;\n}",
"function isUserNumberValid(v) {\n return v <= 100 && v >= 1 && v != NaN && v % 1 == 0;\n}",
"positiveInteger(value = null) {\n if(value > 0 && Number.isInteger(value) == true)\n return value;\n\n return false;\n }",
"function chkIntegerMinValue(str,val)\r\n{\r\n\tif(typeof(val) != \"string\")\r\n\t\tval = val + \"\";\r\n\tif(chkIsInteger(str) == true)\r\n\t{\r\n\t\tif(parseInt(str,10)>=parseInt(val,10))\r\n\t\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n\t}\r\n\telse\r\n\t\treturn false;\r\n}",
"function isValid(string) {\n var str = string.replace(/[^0-9]/g, '');\n if (str.length !== 0) {\n var value = parseInt(str, 10);\n return value >= 0 && value <= 100 ? value : -1;\n }\n return -1;\n }",
"function chkIntegerMaxValue(str,val)\r\n{\r\n\tif(typeof(val) != \"string\")\r\n\t\tval = val + \"\";\r\n\tif(chkIsInteger(str) == true)\r\n\t{\r\n\t\tif(parseInt(str,10)<=parseInt(val,10))\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\telse\r\n\t\treturn false;\r\n}",
"function isBetweenZeroAnd10(number) {\n return typeof 0 < number < 10;\n}",
"function makeInt(n) {\n return parseInt( n, 10);\n}",
"function numGreaterThan10v2(n) {\n if (n > 10) {\n alert(\"true\");\n }\n else {\n alert(\"number is less than 10\");\n }\n}",
"function intWithinBounds(n, lower, upper) {\n\treturn n >= lower && n < upper && Number.isInteger(n);\n}",
"isBigInt() {\n return !!(this.type.match(/^u?int[0-9]+$/));\n }",
"[symbols.call](obj=0, base=null)\n\t{\n\t\tlet result;\n\t\tif (base !== null)\n\t\t{\n\t\t\tif (typeof(obj) !== \"string\" || !_isint(base))\n\t\t\t\tthrow new TypeError(\"int() requires a string and an integer\");\n\t\t\tresult = parseInt(obj, base);\n\t\t\tif (result.toString() == \"NaN\")\n\t\t\t\tthrow new TypeError(\"invalid literal for int()\");\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (typeof(obj) === \"string\")\n\t\t\t{\n\t\t\t\tresult = parseInt(obj);\n\t\t\t\tif (result.toString() == \"NaN\")\n\t\t\t\t\tthrow new TypeError(\"invalid literal for int()\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\telse if (typeof(obj) === \"number\")\n\t\t\t\treturn Math.floor(obj);\n\t\t\telse if (obj === true)\n\t\t\t\treturn 1;\n\t\t\telse if (obj === false)\n\t\t\t\treturn 0;\n\t\t\tthrow new TypeError(\"int() argument must be a string or a number\");\n\t\t}\n\t}",
"function valid_num(n) {\n var msg = '';\n\n switch (true) {\n //The empty string is valid - it's the current comic.\n case (n == ''):\n break;\n case (parseInt(n, 10) != n || n < 1):\n msg = \"'\" + n + \"' is not a positive integer\";\n setnum(1);\n break;\n case (n > hinum):\n msg = n + \" is too high.\\nThe current comic is \" + hinum;\n setnum(-1);\n break;\n case (n == 404):\n t = document.getElementById(\"x-img\");\n t.src = \"img/404-square-2.png\";\n t.alt = \"404\";\n t.title = \"Not Found\";\n document.getElementById(\"x-title\").innerHTML = \"Not Found\";\n break;\n }\n\n return msg;\n}",
"function isPositiveInteger(theString) \r\n\t{ \r\n\tvar theData = new String(theString) \r\n\tif (!isDigit(theData.charAt(0))) \r\n\t\t{\r\n\t\tif (!(theData.charAt(0)== '+')) \r\n\t\t\t{\r\n\t\t\treturn false \r\n\t\t\t}\r\n\t\t}\r\n\tfor (var i = 1; i < theData.length -1; i++) \r\n\t\t{\r\n\t\tif (!isDigit(theData.charAt(i))) \r\n\t\t\t{\r\n\t\t\treturn false \r\n\t\t\t}\r\n\t\t}\r\n\treturn true \r\n}",
"function numbers() {\n return Array.prototype.every.call(arguments, function(argument) {\n return typeof argument === 'number';\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets a new task from the words distribution and updates the distribution accordingly | function getNewTask() {
var random_menu = Math.round(Math.random()*2);
var random_word_index = Math.round(Math.random()*7);
while(words_and_distributions[random_menu][random_word_index][1] === 0) {
random_menu = Math.round(Math.random()*2);
random_word_index = Math.round(Math.random()*7);
}
words_and_distributions[random_menu][random_word_index][1] -= 1;
return [random_menu, words_and_distributions[random_menu][random_word_index][0]]
} | [
"function createNewTask(task) {\n storeTaskLocalStorage(task);\n appendToList(task);\n}",
"function impact(task){\r\n\r\n }",
"generate() {\n document.querySelector(\".modal-window__task_media\").innerHTML = \"\";\n document.getElementById(\"answer\").value = \"\";\n const tasks = [\n this.arithmetics,\n this.translate,\n this.listening,\n this.capitals,\n this.sort,\n this.redundant,\n this.equation,\n this.triangle,\n this.animals\n ];\n const currentTask = _mylib__WEBPACK_IMPORTED_MODULE_0__[\"default\"]\n .getRandomArrayElement(tasks)\n .bind(this);\n currentTask();\n }",
"function assignTaskToBox() {\n let urgency;\n let importance;\n for (i = 0; i < allTasks.length; i++) {\n if (allTasks[i].urgency == null ) urgency = checkUrgency(i);\n else urgency = allTasks[i].urgency;\n\n importance = allTasks[i].importance;\n if (urgency == \"High\" && importance == \"High\") compileTaskMatrixHTML(\"do-blue-box\", i + 1, i, \"Low\");\n else if (urgency == \"High\" && importance == \"Low\") compileTaskMatrixHTML(\"delegate-blue-box\", i + 1, i, \"High\");\n else if (urgency == \"Low\" && importance == \"High\") compileTaskMatrixHTML(\"schedule-blue-box\", i + 1, i, \"Low\");\n else if (urgency == \"Low\" && importance == \"Low\") compileTaskMatrixHTML(\"eliminate-blue-box\", i + 1, i, \"High\");\n assignCategory(allTasks[i].category, i + 1, i);\n }\n}",
"updateTask(e) {\n const taskValue = e.target.value;\n const keyForTask = Math.round(Math.random() * Math.floor(999999));\n\n const updatedTask = {};\n \n updatedTask[keyForTask] = taskValue; \n\n this.setState({\n [e.target.name]: updatedTask\n });\n\n }",
"function generateWordDistribution() {\t\t\t\n\t\tvar zipf = [15,8,5,4,3,3,2,2];\n\t\tvar words_and_distributions = [[],[],[]];\n\t\tfor (var ma = 0; ma < 3; ma++) {\n\t\t\tfor (var iq = 0; iq < 8; iq++) {\n\t\t\t\twords_and_distributions[ma].push([selected_words[ma][iq], zipf[iq]]);\n\t\t\t}\n\t\t}\t\n\t\treturn words_and_distributions\n\t}",
"function randomAssigner(unassignedTasks) {\n let shuffledDesigners = shuffleArray(config.designers);\n let numDesigners = shuffledDesigners.length;\n // We will use an interval to control how quickly requests are sent\n // in order to avoid being rate limited. The interval uses the\n // const delay, which determines how long to wait between requests.\n let index = 0;\n let interval = setInterval(function() {\n assignTask(unassignedTasks[index].gid, shuffledDesigners[index % numDesigners]);\n index++;\n if (index >= unassignedTasks.length) {\n clearInterval(interval);\n console.log(\"You've assigned \" + unassignedTasks.length + \" new design requests\");\n }\n }, delay);\n}",
"function addWord () {\n if (guide.choices().length > 0) {\n var choices = guide.choices();\n var choice = choices[Math.floor(Math.random() * choices.length)];\n guide.choose(choice);\n $scope.sentence += ' ' + choice;\n } else {\n $interval.cancel(sentenceInterval);\n if (guide.isComplete()) {\n $scope.sentence += '.'; // if complete, add period.\n }\n }\n }",
"set task (value) {\n if (this._mem.work === undefined) {\n this._mem.work = {};\n }\n this._mem.work.task = value;\n }",
"function updateTask() {\n\t$('#tasks-list').on('keyup', '#taskBox-title', function(){ \n\t\tvar title = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\t\tTaskManager.update(ref, title, null);\n\t});\n\n\t$('#tasks-list').on('keyup', '#taskBox-body', function(){ \n\t\tvar body = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\n\t\tTaskManager.update(ref, null, body);\n\t});\n\n}",
"function createTask(task = {}) {\n\tif (task.promise) return task\n\ttask.promise = new Promise((resolve, reject) => {\n\t\ttask.resolvers = {resolve, reject};\n\t});\n\ttask.id = `${Date.now()}-${Math.floor(Math.random() * 100000)}`;\n\treturn task\n}",
"function CreateTaskController(task){\n this.task = [] \n}",
"function adjustTask( task, state, handicap, highesthandicap ) {\n //\n if( state.adjustments ) {\n return state.adjustments;\n }\n\n // Make a new array for it\n var newTask = state.adjustments = _clonedeep(task);\n\n // reduction amount (%ish)\n var maxhtaskLength = task.distance / (highesthandicap/100);\n var mytaskLength = maxhtaskLength * (handicap/100);\n var mydifference = task.distance - mytaskLength;\n var spread = 2*(newTask.legs.length-1)+2; // how many points we can spread over\n var amount = mydifference/spread;\n\n // how far we need to move the radius in to achieve this reduction\n var adjustment = Math.sqrt( 2*(amount*amount) );\n\n // Now copy over the points reducing all symmetric\n newTask.legs.slice(1,newTask.legs.length-1).forEach( (leg) => {\n if( leg.type == 'sector' && leg.direction == 'symmetrical') {\n leg.r2 += adjustment;\n }\n else {\n console.log( \"Invalid handicap distance task: \"+leg.toString() );\n }\n });\n\n // For scoring this handicap we need to adjust our task distance as well\n newTask.distance = mytaskLength;\n return newTask;\n}",
"function createTask(){\n\n let title = document.getElementById(\"new-task-title\").value;\n let description = document.getElementById(\"new-task-description\").value;\n let due = document.getElementById(\"new-task-due\").value;\n\n if(!emptyValues(title, description, due)){\n let task = {\n title,\n description,\n due,\n created : new Date()\n }\n tasks++;\n\n //success, insert created task into DOM\n insertTask(task);\n displayPopupMessage(\"Gjøremål opprettet\");\n displayListSection();\n\n }else{\n\n //error, user input not valid\n displayPopupMessage(\"Alle felter må fylles ut.\", false);\n }\n}",
"function suggestions(word, wordpool) {\n var suggs = [];\n var iters = wordpool.length;\n var getidx = function (i) { return i; };\n\n // setup random selection\n if (wordpool.length > MAXITERS) {\n iters = MAXITERS;\n getidx = function () {\n return getRandomInt(0, wordpool.length - 1);\n };\n }\n\n for (var i = 0; i < iters; i++) {\n var idx = getidx(i);\n var randword = wordpool[idx];\n suggs.push({word: randword,\n dist: editdist(word, randword)});\n }\n\n return suggs;\n}",
"onTaskUpdated(task, updatedData) {\n const tasks = this.tasks.slice();\n const oldTask = tasks.splice(tasks.indexOf(task), 1, Object.assign({}, task, updatedData))[0];\n this.tasksUpdated.next(tasks);\n // Creating an activity log for the updated task\n this.activityService.logActivity(\n this.activitySubject.id,\n 'tasks',\n 'A task was updated',\n `The task \"${limitWithEllipsis(oldTask.title, 30)}\" was updated on #${this.activitySubject.document.data._id}.`\n );\n }",
"function taskStarting() {\n tasksRunning += 1;\n return null;\n}",
"async function buildArray(task) {\n let tasksList = await checkTasksList();\n tasksList.tasks.push(task);\n fs.writeFile(todoPath, JSON.stringify(tasksList));\n console.log('Task engadida');\n}",
"function addTask() {\n let taskToSend = {\n task: $('#taskIn').val(),\n };\n\n saveTask(taskToSend);\n clearInputs();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if an object is a Cheerio instance. | function isCheerio(maybeCheerio) {
return maybeCheerio.cheerio != null;
} | [
"function isMochaObject(obj)\n{\n return (obj instanceof mocha.Test || obj instanceof mocha.Suite || obj instanceof mocha.Hook);\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Bot.__pulumiType;\n }",
"function isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Host.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DisasterRecoveryConfig.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineResource.__pulumiType;\n }",
"function instanceExists(objType) {\n for (var i = 0; i < objects.length; i++) {\n if (objects[i] instanceof objType) {\n return objects[i];\n }\n }\n return false;\n}",
"function instanceOf(obj, base) {\n while (obj !== null) {\n if (obj === base.prototype)\n return true;\n if ((typeof obj) === 'xml') { // Sonderfall mit Selbstbezug\n return (base.prototype === XML.prototype);\n }\n obj = Object.getPrototypeOf(obj);\n }\n\n return false;\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrivateLinkService.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Key.__pulumiType;\n }",
"function isObject(element) {\n if (!element) return false\n if (typeof element !== 'object') return false\n if (element instanceof Array) return false\n return true\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EipAssociation.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === UserGroup.__pulumiType;\n }",
"static isObject(input) {\n return input !== null && !this.isArray(input) && typeof (input) === 'object';\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServiceLinkedRole.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ContainerPolicy.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NotificationRecipientEmail.__pulumiType;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the scrollbar offset distance. TODO: Remove in 1.0 (we used this in public examples) | function getScrollbarOffset() {
try {
if (window.innerWidth > document.documentElement.clientWidth) {
return window.innerWidth - document.documentElement.clientWidth;
}
} catch (err) {}
return 0;
} | [
"function get_actual_scroll_distance() {\n return $document.innerHeight() - $window.height();\n }",
"function getScrollOffset() {\n return {\n x: main.scrollLeft,\n y: main.scrollTop };\n\n}",
"function verticalScrollbarPos() {\n\t\tvar top = offset.y + height * pixelSize;\n\t\tvar bottom = canvas.height - offset.y;\n\t\treturn [canvas.width - 15, (top / (top + bottom)) * (canvas.height - 100)];\n\t}",
"yOffset() {\n const minY = -this.h/2;\n let maxY = -this.requiredHeight + this.h/2;\n if(this.requiredHeight <= this.h) {\n maxY = minY;\n }\n\n return this.scrollPos * (maxY - minY);\n }",
"function horizontalScrollbarPos() {\n\t\tvar left = offset.x + width * pixelSize;\n\t\tvar right = canvas.width - offset.x;\n\t\treturn [(left / (left + right)) * (canvas.width - 100), canvas.height - 15];\n\t}",
"function get_current_scroll_addage() {\n return $window.height() * get_current_scroll_percentage();\n }",
"function get_current_scroll_percentage() {\n return $window.scrollTop() / get_actual_scroll_distance();\n }",
"function getOffset() {\n var axisProto = this.constructor.prototype;\n // Call the Axis prototype method (the method we're in now is on the\n // instance)\n axisProto.getOffset.call(this);\n // Title or label offsets are not counted\n this.chart.axisOffset[this.side] = 0;\n }",
"_calculateHeight() {\n\t\tif (this.options.height) {\n\t\t\treturn this.jumper.evaluate(this.options.height, { '%': this.jumper.getAvailableHeight() });\n\t\t}\n\n\t\treturn this.naturalHeight() + (this.hasScrollBarX() ? 1 : 0);\n\t}",
"function calcScrollValues() {\n\t\twindowHeight = $(window).height();\n\t\twindowScrollPosTop = $(window).scrollTop();\n\t\twindowScrollPosBottom = windowHeight + windowScrollPosTop;\n\t} // end calcScrollValues",
"function icinga_get_scroll_position() {\n\n\tvar scroll_pos;\n\n\t//most browsers\n\tif (typeof window.pageYOffset != 'undefined') {\n\t\tscroll_pos = window.pageYOffset;\n\t}\n\t//IE6\n\telse if (typeof document.documentElement.scrollTop != 'undefined') {\n\t\tscroll_pos = document.documentElement.scrollTop;\n\t}\n\t//DOM (IE quirks mode)\n\telse {\n\t\tscroll_pos = document.body.scrollTop;\n\t}\n\n\t//debug - overwrite the title with the current scroll position\n\t//document.title = 'icinga_get_scroll_position=' + window.scroll_pos;\n\n\treturn scroll_pos;\n}",
"function getAxisOffset() {\n return this._axisOffset;\n }",
"@computed\n get maxDistancePx() {\n return Math.sqrt(\n Math.pow(this.windowDimensions.width / 2, 2) +\n Math.pow(this.windowDimensions.height / 2, 2),\n );\n }",
"function getScrollTop() {\n if (document.querySelector(\"body\").scrollTop != 0) {\n return document.querySelector(\"body\").scrollTop;\n } else if (document.querySelector(\"html\").scrollTop != 0) {\n return document.querySelector(\"html\").scrollTop;\n } else {\n return 0;\n }\n}",
"getPageY() {\n return this.__event.pageY || 0;\n }",
"function getOffsets() {\n // Set a static position before getting the offsets\n $articleHeading.css('position', 'static');\n $articleHeading.each(function (idx) {\n articleHeadingOffset[idx] = $(this).offset().top;\n })\n // Clear style attr\n $articleHeading.attr('style', '');\n }",
"getDeltaY() {\n return (this.getPageY() - ((this.__prevState.pageY !== undefined)\n ? this.__prevState.pageY : this.getPageY())) * this.getScaleY();\n }",
"function calculateOffsetTop(r){\n return absolute_offset(r,\"offsetTop\")\n}",
"function _calcScrollToOffset(size, scrollOffset) {\n\t var scrollToRenderNode = this._scroll.scrollToRenderNode || this._scroll.ensureVisibleRenderNode;\n\t if (!scrollToRenderNode) {\n\t return;\n\t }\n\t\n\t // 1. When boundary is reached, stop scrolling in that direction\n\t if ((this._scroll.boundsReached === Bounds.BOTH) ||\n\t (!this._scroll.scrollToDirection && (this._scroll.boundsReached === Bounds.PREV)) ||\n\t (this._scroll.scrollToDirection && (this._scroll.boundsReached === Bounds.NEXT))) {\n\t return;\n\t }\n\t\n\t // 2. Find the node to scroll to\n\t var foundNode;\n\t var scrollToOffset = 0;\n\t var node = this._nodes.getStartEnumNode(true);\n\t var count = 0;\n\t while (node) {\n\t count++;\n\t if (!node._invalidated || (node.scrollLength === undefined)) {\n\t break;\n\t }\n\t if (this.options.alignment) {\n\t scrollToOffset -= node.scrollLength;\n\t }\n\t if (node.renderNode === scrollToRenderNode) {\n\t foundNode = node;\n\t break;\n\t }\n\t if (!this.options.alignment) {\n\t scrollToOffset -= node.scrollLength;\n\t }\n\t node = node._next;\n\t }\n\t if (!foundNode) {\n\t scrollToOffset = 0;\n\t node = this._nodes.getStartEnumNode(false);\n\t while (node) {\n\t if (!node._invalidated || (node.scrollLength === undefined)) {\n\t break;\n\t }\n\t if (!this.options.alignment) {\n\t scrollToOffset += node.scrollLength;\n\t }\n\t if (node.renderNode === scrollToRenderNode) {\n\t foundNode = node;\n\t break;\n\t }\n\t if (this.options.alignment) {\n\t scrollToOffset += node.scrollLength;\n\t }\n\t node = node._prev;\n\t }\n\t }\n\t\n\t // 3. Update springs\n\t if (foundNode) {\n\t if (this._scroll.ensureVisibleRenderNode) {\n\t if (this.options.alignment) {\n\t if ((scrollToOffset - foundNode.scrollLength) < 0) {\n\t this._scroll.springPosition = scrollToOffset;\n\t this._scroll.springSource = SpringSource.ENSUREVISIBLE;\n\t }\n\t else if (scrollToOffset > size[this._direction]) {\n\t this._scroll.springPosition = size[this._direction] - scrollToOffset;\n\t this._scroll.springSource = SpringSource.ENSUREVISIBLE;\n\t }\n\t else {\n\t if (!foundNode.trueSizeRequested) {\n\t this._scroll.ensureVisibleRenderNode = undefined;\n\t }\n\t }\n\t }\n\t else {\n\t scrollToOffset = -scrollToOffset;\n\t if (scrollToOffset < 0) {\n\t this._scroll.springPosition = scrollToOffset;\n\t this._scroll.springSource = SpringSource.ENSUREVISIBLE;\n\t }\n\t else if ((scrollToOffset + foundNode.scrollLength) > size[this._direction]) {\n\t this._scroll.springPosition = size[this._direction] - (scrollToOffset + foundNode.scrollLength);\n\t this._scroll.springSource = SpringSource.ENSUREVISIBLE;\n\t }\n\t else {\n\t if (!foundNode.trueSizeRequested) {\n\t this._scroll.ensureVisibleRenderNode = undefined;\n\t }\n\t }\n\t }\n\t }\n\t else { // scrollToSequence\n\t this._scroll.springPosition = scrollToOffset;\n\t this._scroll.springSource = SpringSource.GOTOSEQUENCE;\n\t }\n\t return;\n\t }\n\t\n\t // 4. When node not found, keep searching\n\t if (this._scroll.scrollToDirection) {\n\t this._scroll.springPosition = scrollOffset - size[this._direction];\n\t this._scroll.springSource = SpringSource.GOTONEXTDIRECTION;\n\t\n\t }\n\t else {\n\t this._scroll.springPosition = scrollOffset + size[this._direction];\n\t this._scroll.springSource = SpringSource.GOTOPREVDIRECTION;\n\t }\n\t\n\t // 5. In case of a VirtualViewSequnce, make sure all the view-sequence nodes are touched, so\n\t // that they are not cleaned up.\n\t if (this._viewSequence.cleanup) {\n\t var viewSequence = this._viewSequence;\n\t while (viewSequence.get() !== scrollToRenderNode) {\n\t viewSequence = this._scroll.scrollToDirection ? viewSequence.getNext(true) : viewSequence.getPrevious(true);\n\t if (!viewSequence) {\n\t break;\n\t }\n\t }\n\t }\n\t }",
"get DisplayOffset() { return this.native.DisplayOffset; }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A bounded interval that emits events when its range changes. / / If max or min is `null`, that dimension is unbounded. / / low Number / high Number / min Number or null, min <= low / max Number or null, high <= max / / Events: / zoom(low, high) / pan:move(low, high) / pan:done(low, high) / / Other classes use a shared Interval (e.g. the synced X interval) to / propagate an event (e.g. `hover:x`) to many charts. | function Interval(low, high, min, max) {
this.low = low; this.high = high
this.min = min; this.max = max
this.dirty = false
// A dashboard's X interval can have quite a lot of listeners, since it is
// shared between member charts.
this.setMaxListeners(0)
} | [
"function geneBaseBounds(gn, min, max) {\n var gd = genedefs[gn];\n var gg = guigenes[gn];\n if (gd === undefined) return;\n if (gd.basemin === gd.min) {\n gd.min = min;\n gg.minEle.value = min;\n gg.sliderEle.min = min;\n }\n gd.basemin = min;\n if (gd.basemax === gd.max) {\n gd.max = max;\n gg.maxEle.value = max;\n gg.sliderEle.max = max;\n }\n gd.basemax = max;\n\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n}",
"function bound (n, min, max) {\n return Math.min(max, Math.max(min, n))\n}",
"function geneBounds(gn, min, max) {\n var gd = genedefs[gn];\n if (gd === undefined) return;\n min = min !== undefined ? min : gd.basemin;\n max = max !== undefined ? max : gd.basemax;\n gd.min = min;\n gd.max = max;\n var gg = guigenes[gn];\n if (gg) {\n gg.minEle.value = min;\n gg.maxEle.value = max;\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n gg.sliderEle.min = min;\n gg.sliderEle.max = max;\n }\n}",
"minMaxConditionsHandler() {\n if (\n (this.min || this.min === 0) &&\n (this.value < this.min || this._previousValue < this.min)\n ) {\n this._value = this.min;\n }\n if (\n this.max &&\n (this.value > this.max || this._previousValue > this.max)\n ) {\n this._value = this.max;\n }\n }",
"function wideYAxisRange(min, max, tickInterval) {\n let y_widing = (max * (dataRangeWidingFactor - 1) - min * (dataRangeWidingFactor - 1)) / 2;\n let y_min, y_max;\n\n if (tickInterval === 0) {\n y_max = max * dataRangeWidingFactor;\n y_min = min - min * (dataRangeWidingFactor - 1);\n tickInterval = (y_max - y_min) / 2;\n } else {\n y_max = Math.ceil((max + y_widing) / tickInterval) * tickInterval;\n y_min = Math.floor((min - y_widing) / tickInterval) * tickInterval;\n }\n\n // Don't wide axis below 0 if all values are positive\n if (min >= 0 && y_min < 0) {\n y_min = 0;\n }\n\n return {y_min, y_max};\n }",
"function Range() {\n\tthis.minCells = 2 // Can operate on a minimum of 2 cells\n\tthis.maxCells = 4 // Can operate on a maximum of 4 cells\n\tthis.symbol = 'range'\n}",
"function minMaxSet() {\n min = parseInt(minRange.value);\n max = parseInt(maxRange.value);\n}",
"function computeTickInterval(xMin, xMax) \n {\n var zoomRange = xMax - xMin;\n \n if (zoomRange <= 2)\n currentTickInterval = 0.5;\n if (zoomRange < 20)\n currentTickInterval = 1;\n else if (zoomRange < 100)\n currentTickInterval = 5;\n }",
"function getRegionBounds(def) {\n var _getHistRange = getHistRange(def);\n\n var _getHistRange2 = _slicedToArray(_getHistRange, 2);\n\n var minRange = _getHistRange2[0];\n var maxRange = _getHistRange2[1];\n\n return [minRange].concat(def.dividers.map(function (div) {\n return div.value;\n }), maxRange);\n }",
"function restrictToRange(val,min,max) {\r\n if (val < min) return min;\r\n if (val > max) return max;\r\n return val;\r\n }",
"function valueInBounds(v, [min, max]) {\n return v >= min && (max === undefined || v <= max);\n }",
"function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }",
"function DragIntRange2(label, v_current_min, v_current_max, v_speed = 1.0, v_min = 0, v_max = 0, format = \"%d\", format_max = null) {\r\n const _v_current_min = import_Scalar(v_current_min);\r\n const _v_current_max = import_Scalar(v_current_max);\r\n const ret = bind.DragIntRange2(label, _v_current_min, _v_current_max, v_speed, v_min, v_max, format, format_max);\r\n export_Scalar(_v_current_min, v_current_min);\r\n export_Scalar(_v_current_max, v_current_max);\r\n return ret;\r\n }",
"function setTickInterval(event) \n {\n var xMin = event.xAxis[0].min;\n var xMax = event.xAxis[0].max;\n computeTickInterval(xMin, xMax);\n\n chart1.xAxis[0].options.tickInterval = currentTickInterval;\n chart1.xAxis[0].isDirty = true;\n chart2.xAxis[0].options.tickInterval = currentTickInterval;\n chart2.xAxis[0].isDirty = true;\n chart3.xAxis[0].options.tickInterval = currentTickInterval;\n chart3.xAxis[0].isDirty = true;\n chart4.xAxis[0].options.tickInterval = currentTickInterval;\n chart4.xAxis[0].isDirty = true; \n }",
"function clamp(value, lowerBound, upperBound) {\n\t\treturn Math.min(Math.max(value, lowerBound), upperBound);\n\t}",
"function makeRangeMapper(oMin, oMax, nMin, nMax ){\n\t//range check\n\tif (oMin == oMax){\n\t\tconsole.log(\"Warning: Zero input range\");\n\t\treturn undefined;\n\t};\n\n\tif (nMin == nMax){\n\t\tconsole.log(\"Warning: Zero output range\");\n\t\treturn undefined\n\t}\n\n\t//check reversed input range\n\tvar reverseInput = false;\n\tlet oldMin = Math.min( oMin, oMax );\n\tlet oldMax = Math.max( oMin, oMax );\n\tif (oldMin != oMin){\n\t reverseInput = true;\n\t}\n\n\t//check reversed output range\n\tvar reverseOutput = false; \n\tlet newMin = Math.min( nMin, nMax )\n\tlet newMax = Math.max( nMin, nMax )\n\tif (newMin != nMin){\n\t reverseOutput = true;\n\t}\n\n\t// Hot-rod the most common case.\n\tif (!reverseInput && !reverseOutput) {\n\t\tlet dNew = newMax-newMin;\n\t\tlet dOld = oldMax-oldMin;\n \t\treturn (x)=>{\n\t\t\treturn ((x-oldMin)* dNew / dOld) + newMin;\n\t\t}\n\t}\n\n\treturn (x)=>{\n\t\tlet portion;\n\t\tif (reverseInput){\n\t\t\tportion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);\n\t\t} else {\n\t\t\tportion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)\n\t\t}\n\t\tlet result;\n\t\tif (reverseOutput){\n\t\t\tresult = newMax - portion;\n\t\t} else {\n\t\t\tresult = portion + newMin;\n\t\t}\n\t\t\n\t\treturn result;\n\t}\t\n}",
"function VersionRange(lowerBound, upperBound)\n{\n\tthis.lowerBound = lowerBound;\n\tthis.upperBound = upperBound;\n}",
"function keepWithin(value, min, max) {\n if (value < min) value = min;\n if (value > max) value = max;\n return value;\n }",
"function range (min, max) {\n var arr = []\n for (var i = min; i <= max; i++) {\n arr.push(i) \n }\n return arr\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the leaderboard. Uses helper function to get the top scores and the current users rank. | function init() {
currUser = sessionStorage.getItem(cUserId);
getTopScores();
getCurrentUserRank();
} | [
"function init() {\n scores = {\n p: 0,\n t: 0,\n c: 0\n };\n results = {\n p: '',\n c: ''\n };\n winner = null;\n}",
"function Leaderboard() {}",
"function prepareLeaderboard() {\r\n\t\t var fsq = require('node-foursquare')(context.foursquare.config);\r\n\t\t fsq.Users.getLeaderboard(\r\n\t\t { neighbors: 2 },\r\n\t\t r.oat,\r\n\t\t function (err,res) {\r\n\t\t if (err) {\r\n\t\t clientResults.log(\"Couldn't get the leaderboard from fsq.\");\r\n\t\t // move on anyway.\r\n\t\t } else {\r\n\r\n\t\t \t// TODO: Sometimes these results are not sorted!\r\n\r\n\t\t var leaders = [];\r\n\t\t if (res && res.leaderboard && res.leaderboard.items) {\r\n\t\t for (var t = 0; t < res.leaderboard.items.length; t++) {\r\n\t\t var item = res.leaderboard.items[t];\r\n\t\t if (item.user && item.scores && item.rank && item.scores.recent) {\r\n\t\t \r\n\t\t // Localization.\r\n\t\t // ---\r\n\t\t // TODO: Note that for localization to work, the \"Me\" \r\n\t\t // string will need to be slightly localized.\r\n\r\n\t\t var leader = {\r\n\t\t name: item.user.relationship == 'self' ? 'Me' : item.user.firstName,\r\n\t\t rank: '#' + item.rank,\r\n\t\t score: item.scores.recent + ' pts',\r\n\t\t photo: item.user.photo,\r\n\t\t id: item.user.id\r\n\t\t };\r\n\t\t leaders.push(leader);\r\n\t\t }\r\n\t\t }\r\n\t\t }\r\n\t\t if (leaders.length > 0) {\r\n\t\t var u = 'http://www.4thandmayor.com/leaderTile.php?';\r\n\t\t for (var y = 0; y < leaders.length; ) {\r\n\t\t var ldr = leaders[y];\r\n\t\t y++;\r\n\r\n\t\t u += \"l\" + y + \"=\" + querystring.escape(ldr.rank + \" \" + ldr.name);\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"u=\" + ldr.id;\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"p=\" + querystring.escape(ldr.photo);\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"score=\" + querystring.escape(ldr.score);\r\n\t\t u += \"&\";\r\n\t\t }\r\n\r\n\t\t // TODO: Consider storing this using task.storage.* instead.\r\n\t\t clientResults.leaderboardImageUri = u;\r\n\r\n\t\t var nextLeaderboardPingTime = dateutil.returnNewDatePlusMinutes(new Date(), context.configuration.constants.REFRESH_LEADERBOARD_MINUTES);\r\n\t\t r.lp = nextLeaderboardPingTime;\r\n\r\n\t\t clientResults.isDirty = true;\r\n\t\t }\r\n\t\t }\r\n\r\n\t\t // should be ready if it worked, let's get the tile out next.\r\n\t\t callback(null, null);\r\n\t\t });\r\n\t\t}",
"function init() {\n var savedLeaderboard = JSON.parse(localStorage.getItem(\"leaderboard\"));\n if (savedLeaderboard === null) {\n return;\n }\n else {\n leaderboardArr = savedLeaderboard;\n } \n}",
"function initScoreboard() {\n\tvar header = '<h3>Deck Overview</h3>';\n\t$(overview).append(header);\n\tfor (var i = 0; i < myDecks[currentDeck].cards.length; i++) {\n\t\tvar cardOverview = '<li data-index=\"' + i + '\"><span class=\"overview-status\"><i class=\"fa fa-square-o\" aria-hidden=\"true\"></i></span><span class=\"overview-value\">. . .</span></li>';\n\t\t$(overview).append(cardOverview);\n\t}\n}",
"function loadLeaderBoard() {\n var leaderRef = firebase.database().ref().child(\"highscores\");\n leaderRef.child(\"p0\").child('name').on('value', snap => {\n $(\"#p0\").text(snap.val());\n leaderName0 = snap.val();\n });\n leaderRef.child(\"p0\").child('score').on('value', snap => {\n $(\"#p0score\").text(snap.val());\n leaderScore0 = parseInt(snap.val());\n });\n leaderRef.child(\"p1\").child('name').on('value', snap => {\n $(\"#p1\").text(snap.val());\n leaderName1 = snap.val();\n });\n leaderRef.child(\"p1\").child('score').on('value', snap => {\n $(\"#p1score\").text(snap.val());\n leaderScore1 = parseInt(snap.val());\n });\n leaderRef.child(\"p2\").child('name').on('value', snap => {\n $(\"#p2\").text(snap.val());\n leaderName2 = snap.val();\n });\n leaderRef.child(\"p2\").child('score').on('value', snap => {\n $(\"#p2score\").text(snap.val());\n leaderScore2 = parseInt(snap.val());\n });\n }",
"function displayLeaderboard() { \n hideAll();\n clearTable();\n displayElement(leaderboardPageDiv);\n\n if (leaderboardArr.length > 0) {\n // sorts the leaderboardArr from highest \n // to lowest by score\n leaderboardArr.sort((a, b) => b.score - a.score);\n\n var rank = 1;\n\n // for each element create a new row in leaderboardTable\n for (var i = 0; i < leaderboardArr.length; i++) {\n var curr = leaderboardArr[i];\n // insert row at the bottom of the table\n var row = leaderboardTable.insertRow();\n \n\n // checks if the score is already on the leaderboard so if it \n // is everyone of that score has the same rank\n if (i !== 0 && curr.score !== leaderboardArr[i - 1].score) {\n rank++;\n }\n\n // create cell data for each heading in the table\n createCell(row, rank);\n createCell(row, curr.name);\n createCell(row, curr.score);\n }\n }\n}",
"function init(){\n var storedScores = JSON.parse(localStorage.getItem(\"scoreArray\"));\n var storedInitials = JSON.parse(localStorage.getItem(\"arrayInitials\"))\n\n if (storedScores !== null){\n scoreArray = storedScores;\n }\n\n if (storedInitials !== null){\n arrayInitials = storedInitials;\n }\n logScore()\n}",
"sortLeaderboard () {\n // Build the array to be sorted that will contain all the leaderboard information\n let sortedLeaderboard = []\n const leaderboard = this.state.leaderboard\n\n for (var key in leaderboard) {\n if (leaderboard.hasOwnProperty(key)) {\n if (this.checkFilters(leaderboard[key])) {\n sortedLeaderboard.push(leaderboard[key])\n }\n }\n }\n\n sortedLeaderboard.sort((a, b) => b.score - a.score)\n\n for (var i in sortedLeaderboard) {\n sortedLeaderboard[i].position = parseInt(i, 10) + 1\n }\n if (!this.state.showAll) {\n sortedLeaderboard = this.snipTableData(sortedLeaderboard)\n }\n return sortedLeaderboard\n }",
"function populateLeaderboardTable() {\n\t// Ordeno el json dependiendo del score y los partidos ganados, perdidos o empatados\n\tleaderboardJson = leaderboardSorted(leaderboardJson);\n\t// imprimo las 5 primeras posiciones\n\tleaderboardTable.innerHTML = \"\";\n\tleaderboardJson.slice(0, 5).forEach(player => {\n\t\tleaderboardTable.innerHTML += \"<tr><th>\" + player.playerName + \"</th><td>\" + player.score + \"</td><td>\" +\n\t\t\tplayer.won + \"</td><td>\" + player.lost + \"</td><td>\" + player.tied + \"</td></tr>\"\n\t});\n}",
"init() {\n console.log('from init')\n\n this._placeCards(this.cards, this.element.cards);\n this._setStats();\n this._updateGameState(gameState.GAME);\n }",
"function init() {\n \n grid.init(EMPTY, COLS, ROWS);\n\n // startPos defines the starting position for the snake.\n var startPos = {x: Math.floor(COLS / 2), y: Math.floor(ROWS / 2)};\n\n // Initialize the snake.\n snake.init(UP, startPos.x, startPos.y);\n\n // Set the snake on the grid.\n grid.set(SNAKE, startPos.x, startPos.y);\n\n // Set food on the grid.\n setFood();\n\n snakeMovingSpeed = 10;\n\n score = 0;\n}",
"function InitBoardVars()\n{\n\t//Initializing history table\n\tfor(let i = 0; i < MAXGAMEMOVES; i++) \n\t{\n\t\tGameBoard.history.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tcastlePerm: 0,\n\t\t\tenPas: 0,\n\t\t\tfiftyMove: 0,\n\t\t\tposKey: 0\n\t\t});\n\t}\t\n\t//Initializing Pv Table\n\tfor (let i = 0; i < PVENTRIES; i++)\n\t{\n\t\tGameBoard.PvTable.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tposKey: 0\n\t\t});\n\t}\n}",
"_initializeGameValues() {\n this.currentFPS = GameConfig.STARTING_FPS;\n this.scoreBoard.resetScore();\n\n this.player = new Player(this.gameView.getPlayerName(), \"white\");\n this.food = new Food(this.boardView.getRandomCoordinate(this.player.segments), \"lightgreen\");\n this.gameView.hideChangeNameButton();\n }",
"function updateLeaderboard(data) {\n\n // Remove previous scores\n $('.score_row').remove();\n\n for (var i = 0; i < 10; i++) {\n\n if (data.player_rank == i) {\n\n $('#leaderboard table tr:last').after('<tr class=\"score_row user_score\"><td>' + (i + 1) + '</td><td>You</td><td>' + data.player_score + '</td></tr>');\n\n } else if (data.top_ten[i]) {\n\n var row = $('<tr class=\"score_row\">')\n .append($('<td>').text(i+1))\n .append($('<td>').text(data.top_ten[i].player_name))\n .append($('<td>').text(data.top_ten[i].score))\n\n $('#leaderboard table tr:last').after(row);\n\n }\n\n }\n\n if(data.player_rank >= 10) {\n\n $('#leaderboard table tr:last').after('<tr class=\"score_row user_score\"><td>' + (data.player_rank + 1) + '</td><td>You</td><td>' + data.player_score + '</td></tr>');\n\n }\n\n}",
"function requestLeaderboardData() {\n\tsocket.emit(\"req_lb_data\")\n\tsocket.on(\"lb_data_req_ack\", (data) => {\n\t\tif (data != null) {\n\t\t\t// populate the leaderboard with data.response\n\t\t\tdrawLeaderboard(data)\n\t\t} else {\n\t\t\t// leaderboard currently unavailable\n\t\t\tconsole.log(\"No data:\", data)\n\t\t}\n\t})\n}",
"getUserRankings() {\n\n let thisUser = this;\n\n // Creates a new document is the user doesn't exist, then stops the loading of data\n userRef.doc(this.state.email).get()\n .then(function(doc) {\n if(!doc.exists) {\n userRef.doc(thisUser.state.email).set({name: thisUser.state.name, userLists: new Set()})\n thisUser.setState({userExists: false, loaded: true})\n return;\n }\n });\n\n // Sets reference variables for abstractions in this method\n let userDoc = userRef.doc(this.state.email)\n let rankRef = userDoc.collection('rankings');\n\n // Loads in the names of the lists that each user has ranked.\n this.getUserLists(userDoc).then(function(results) {\n if (!results) {\n return\n }\n thisUser.setState({lists: new Set(results.userLists)});\n })\n\n // Loads the rankings that the User has created, in the form of a map of \n // the list name and then the list info.\n this.getUserRankingsFromFS(rankRef).then(function(results) {\n thisUser.setState({rankingData: results, loaded: true});\n thisUser.renderLists();\n });\n }",
"function initGameBoard() {\n document.querySelector('.title').remove();\n\n document.getElementById('startBtn').remove();\n\n var board = document.querySelector('.gameboard');\n board.setAttribute(\"id\", \"liveBoard\");\n\n console.log(\"game board has been initialized\");\n // This for loop creates 20 rows in the gameboard\n for (i = 0; i < 20; i++) {\n var boardRow = document.createElement(\"div\");\n boardRow.setAttribute(\"class\", \"row boardRow\");\n boardRow.setAttribute(\"id\", \"row\" + i);\n\n\n document.getElementById(\"liveBoard\").appendChild(boardRow);\n boardStatus.push([]);\n\n // This for loop creates 10 cells in each row\n for (j = 0; j < 10; j++) {\n var rowCell = document.createElement(\"div\");\n rowCell.setAttribute(\"class\", \"col-sm\")\n rowCell.setAttribute(\"id\", \"cell\" + i + \"-\" + j);\n\n document.getElementById(\"row\" + i).appendChild(rowCell)\n boardStatus[i].push(0);\n }\n }\n\n var scoreBoard = document.createElement(\"div\");\n scoreBoard.setAttribute(\"class\", \"scoreBoard\");\n document.body.appendChild(scoreBoard);\n document.querySelector('.scoreBoard').innerHTML = '<p class=\"scoreLabel\"> SCORE </p>';\n\n var scoreDisp = document.createElement(\"div\");\n scoreDisp.setAttribute(\"class\", \"score\")\n document.querySelector('.scoreBoard').appendChild(scoreDisp)\n document.querySelector('.score').innerHTML = '0';\n\n}",
"function showScoreBoard(){\n console.log()\n console.log(chalk.bold.cyan(\"Your Score:\"),scoreCount,\"/15\")\n console.log(chalk.bold.red(\"-------------LEADERBOARD--------------\"));\n console.log()\n\n //Check if player has beat the highest score.\n leaderBoard.map((person)=>{\n if(person.score<scoreCount){\n console.log(chalk.bold.green(\"------CONGRATULATIONS!!You have beat the previous highest score----------\"))\n console.log()\n console.log(chalk.bold.white(\"Previous leaderboard\"))\n console.table(leaderBoard)\n console.log()\n console.log(chalk.bold.cyan(\"Send me your score screenshot so I can update the leaderboard.\"))\n }\n else{\n console.log(chalk.bold.white(\"LEADERBOARD\"))\n console.table(leaderBoard)\n }\n })\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
util method. a: option groups, b: field name to access product components, c: field name to access product Id within product component. | function getAllProductsinCurrentOptiongroups(a, b, c){
// return a list of bundle product Id's. based on flag provided.
var res = [];
_.each(a, function (group) {
res.push(_.pluck(group[b], c));
});
res = _.flatten(res);// Flattens a nested array.
res = _.filter(res, function(prodId){return !_.isUndefined(prodId)});
return res;
} | [
"function verifyExtraFieldsFromProduct() {\n if ($scope.device.product.extraFields) {\n\n }\n }",
"function setOptionLabels(mthis) {\n var products = [];\n var optVal = mthis.val();\n var attrId = parseInt(mthis.prop(\"id\").replace(/[^\\d.]/g, \"\"));\n var data = JSON.parse(getAllData());\n var options = data.attributes[attrId].options;\n options.forEach(function (cObj) {\n if (cObj.id == optVal) {\n cObj.products.forEach(function (cPro) {\n var selectIndex = jQuery(\"select\").index(mthis);\n if (selectIndex > 0) {\n var prevSelect = jQuery(\"select\").eq(selectIndex - 1);\n var prevSelectAttrId = parseInt(\n prevSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n if (!isNaN(prevSelectAttrId)) {\n var prevSelectOptions = data.attributes[prevSelectAttrId].options;\n prevSelectOptions.forEach(function (subObj) {\n if (subObj.id == prevSelect.val()) {\n if (subObj.products.indexOf(cPro) != -1) {\n products.push(cPro);\n }\n }\n });\n }\n } else {\n products.push(cPro);\n }\n });\n }\n });\n var selectIndex = jQuery(\".input-box select\").index(mthis);\n var nextSelect = jQuery(\".input-box select\").eq(selectIndex + 1);\n if (nextSelect.length > 0) {\n var nextSelectAttrId = parseInt(\n nextSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n var nextSelectOptions = data.attributes[nextSelectAttrId].options;\n nextSelect.empty();\n nextSelect.append(\"<option value>Choose an Option...</option>\");\n nextSelect.removeAttr(\"disabled\");\n nextSelectOptions.forEach(function (cObj) {\n cObj.products.forEach(function (cPro) {\n if (products.indexOf(cPro) != -1) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length <= 0) {\n nextSelect.append(\n '<option value=\"' + cObj.id + '\">' + cObj.label + \"</option>\"\n );\n }\n }\n });\n });\n }\n}",
"function setCCID(attributeGroups, bundleProductName, bundlePav){\n\t\t\tvar CGE_PRODUCT_NAME = 'CenturyLink Ethernet';\n\t\t\tvar L3PP_PRODUCT_NAME = 'L3 IQ Networking Private Port';\n\t\t\t\n\t\t\tvar BUNDLE_PRODUCT_NAME = (bundleProductName == CGE_PRODUCT_NAME) ? CGE_PRODUCT_NAME : L3PP_PRODUCT_NAME;\n\n\t\t\tif (bundleProductName.toLowerCase() === BUNDLE_PRODUCT_NAME.toLowerCase()) {\n\n\t\t\t\tif (!_.isEmpty(attributeGroups)) {\n\t\t\t\t\tvar CGE_ATTRIBUTES_ATTRIBUTE_GROUP_NAME = 'CenturyLink Ethernet';\n\t\t\t\t\tvar L3PP_ATTRIBUTES_ATTRIBUTE_GROUP_NAME = 'Layer 3 IQ Networking Private Port';\n\t\t\t\t\tvar BUNDLE_ATTRIBUTES_ATTRIBUTE_GROUP_NAME = (bundleProductName == CGE_PRODUCT_NAME) ? CGE_ATTRIBUTES_ATTRIBUTE_GROUP_NAME : L3PP_ATTRIBUTES_ATTRIBUTE_GROUP_NAME;\n\t\t\t\t\t\n\t\t\t\t\t_.each(attributeGroups, function(attributeGroup) {\n\t\t\t\t\t\tif (attributeGroup.groupName.toLowerCase() === BUNDLE_ATTRIBUTES_ATTRIBUTE_GROUP_NAME.toLowerCase()) {\n\n\t\t\t\t\t\t\tvar CCID_API_NAME = 'CONTROL_CENTRAL_ID__c';\n\t\t\t\t\t\t\t_.each(attributeGroup.productAtributes, function(productAttribute) {\n\t\t\t\t\t\t\t\tif (productAttribute.fieldName.toLowerCase() == CCID_API_NAME.toLowerCase()) {\n\n\t\t\t\t\t\t\t\t\tvar bundleServiceType = bundlePav['Service_Type_CGE__c'];\n\t\t\t\t\t\t\t\t\tif (bundleProductName.toLowerCase() === L3PP_PRODUCT_NAME.toLowerCase())\n\t\t\t\t\t\t\t\t\t\tbundleServiceType = bundlePav['Service_Type_L3__c'];\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (bundleServiceType === 'EPLAN' || bundleServiceType === 'EPLINE') {\n\t\t\t\t\t\t\t\t\t\tproductAttribute.isReadOnly = true;\n\t\t\t\t\t\t\t\t\t\tproductAttribute.isHidden = true;\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tproductAttribute.isReadOnly = false;\n\t\t\t\t\t\t\t\t\t\tproductAttribute.isHidden = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\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}",
"GetMultipleComponentsInfo() {\n\n }",
"function show_supplier_selector(product_id)\n{\n\n\n}",
"function product(obj){\n\n\tthis.product = obj;\n\n\tthis.searchAttr = function (str, subStr){\n\n\t\t\t\t\t\tvar escapeWords = ['℮'];\n\n\t\t\t\t\t\tvar searchValue=_.chain(subStr)\n\t\t\t\t\t\t .upperCase()\n\t\t\t\t\t\t .words()\n\t\t\t\t\t\t .without(_.join(escapeWords,','))\n\t\t\t\t\t\t .value();\n\n\t\t\t\t\t\tvar searchInString=_.chain(str)\n\t\t\t\t\t\t .upperCase()\n\t\t\t\t\t\t .words()\n\t\t\t\t\t\t .intersection(searchValue)\n\t\t\t\t\t\t .join('')\n\t\t\t\t\t\t .value();\n\n\n\t\t\t\t\t var match = function (){ \n\t\t\t\t\t \t\t\t\tif (searchInString.length>0) {return true} else {return false }\n\t\t\t\t\t };\n\t\t\t\t\t\t \n\t\t\t\t\t\treturn {matched: match(), matchedString: searchInString} \n\t\t\t\t\t\t \n\t\t\t\t\t}\n\tthis.attrExist = function() { \n\t\t\t\t\t\t\t\t\tvar attrs = ['digitalContent','gda','nutrition','allergenAdvice','calcNutrition','marketingText'];\n\t\t\t\t\t\t\t\t\tvar missingAttrs=[];\n\n\t\t\t\t\t\t\t\t\tfor (attr in attrs){\n\t\t\t\t\t\t\t\t\t\tif (obj[attrs[attr]]==undefined) {missingAttrs.push (attrs[attr]);}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t if(missingAttrs.length>0) return \"Missing Attributes : \"+_.join(missingAttrs,\",\");\n\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t else return \"\";\n\t\t\t\t\t\t\t\t }\n\n\tthis.getCountryAttr = function (obj,countryCode,attribute){\n\n\t\t\t\t\t\t\t\t\tvar compareObj ={};\n\t\t\t\t\t\t\t\t\tcompareObj[\"code\"]=countryCode;\n\t\t\t\t\t\t\t\t\tcountryObj=_.filter(obj,compareObj);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (countryObj.length>0) {return (countryObj[0][attribute]);} \n\t\t\t\t\t\t\t\t else { return undefined;}\n\n\t\t\t\t\t\t\t }\n\n\tthis.brandEval = function (brandVal,label){\n\n\t\t\t\t\t\t\t\t\tif (brandVal = null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(label === true){\n\t\t\t\t\t\t\t\t\t\treturn \"Tesco branded\";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\treturn \"Supplier Branded\";\n\t\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t\t};\n\n\tthis.output = function() { \n\n\t\t return (obj.uniqueKey + '|'\n\t\t\t\t\t\t\t + (obj.gtin||na ) + '|'\n\t\t\t\t\t\t\t + (obj.tpnb||na ) + '|'\n\t\t\t\t\t\t\t + (obj.tpna||na ) + '|'\n + (obj.tpnc||na ) + '|'\n + (obj.description||na ) + '|'\n + (obj.brand||na ) + '|'\n + (JSON.stringify(obj.commercialHierarchy)||na ) + '|' \n + (obj.commercialHierarchy.subclassCode||na ) + '|' \n + (obj.commercialHierarchy.subclassName||na ) + '|'+ (obj.commercialHierarchy.className||na ) + '|'\n + (obj.commercialHierarchy.sectionName||na ) + '|'+ (obj.commercialHierarchy.departmentName||na ) + '|'\n \t\t + (this.getCountryAttr(obj.country,\"GB\",'code')||na) + '|'\n \t\t + (this.getCountryAttr(obj.country,\"GB\",'custFriendlyDesc')||na) + '|'\n \t\t + (this.getCountryAttr(obj.country,\"GB\",'launchDate')||na) + '|'\n \t\t + (this.getCountryAttr(obj.country,\"GB\",'authorised')) + '|'\n\t\t\t\t\t\t\t + (this.getCountryAttr(obj.country,\"GB\",'deactivated')) + '|'\n\t\t\t\t\t\t\t + (this.getCountryAttr(obj.country,\"GB\",'epw')) + '|'\n \t\t\t\t\t\t\t + (obj.rmsStatus||na) + '|'\t\n\t\t\t\t\t\t\t + (obj.sellByType||na) + '|'\n\t\t\t\t\t\t\t + (JSON.stringify(((obj.productCharacteristics)||{}).isFood)||na) + '|'\n\t\t\t\t\t\t\t + (JSON.stringify(((obj.productCharacteristics)||{}).isDrink)||na) + '|'\n\t\t\t\t\t\t\t + (JSON.stringify(((obj.qtyContents)||{}).netContents)||na) + '|'\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t + (this.searchAttr(obj.description,((obj.qtyContents)||{}).netContents).matched) + '|'\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t + (this.searchAttr(obj.description,((obj.qtyContents)||{}).netContents).matchedString) + '|'\n\t\t\t\t\t\t\t + (this.attrExist()||na ) + '|'\n\t\t\t\t\t\t\t + (this.brandEval((obj.brand||\" \"),obj.isOwnLabel)) + '|'\n\t\t\t\t\t\t\t + (JSON.stringify(obj.gda)||na ) + '|' \n\t\t\t\t\t\t\t + (JSON.stringify(obj.digitalContent)||na ) + '|' \n\t\t\t\t\t\t\t + (JSON.stringify(obj.nutrition)||na ) + '|' \t\n\t\t\t\t\t\t\t + (JSON.stringify(obj.allergenAdvice)||na ) + '|' \t\t\n\t\t\t\t\t\t\t + (JSON.stringify(obj.calcNutrition)||na ) + '|'\n\t\t\t\t\t\t\t + (JSON.stringify(obj.marketingText)||na) \n\t\t\t\t\t\t\t ); // replacing line charecter wirh space);\n };\n}",
"function getDependentOptions (apiKey, objName, ctrlFieldName, depFieldName, namespace) {\n\tsforce.connection.sessionId = apiKey\n if(namespace){\n objName = namespace + objName;\n ctrlFieldName = namespace + ctrlFieldName;\n depFieldName = namespace + depFieldName;\n }\n\n // Isolate the Describe info for the relevant fields\n var objDesc = sforce.connection.describeSObject(objName);\n var ctrlFieldDesc, depFieldDesc;\n var found = 0;\n for (var i=0; i<objDesc.fields.length; i++) {\n var f = objDesc.fields[i];\n if (f.name == ctrlFieldName) {\n ctrlFieldDesc = f;\n found++;\n } else if (f.name == depFieldName) {\n depFieldDesc = f;\n found++;\n }\n if (found==2) break; \n }\n \n // Set up return object\n var dependentOptions = {};\n\n var ctrlValues = ctrlFieldDesc.picklistValues;\n for (var i=0; i<ctrlValues.length; i++) {\n dependentOptions[ctrlValues[i].label] = [];\n }\n \n var base64 = new sforce.Base64Binary(\"\");\n function testBit (validFor, pos) {\n var byteToCheck = Math.floor(pos/8);\n var bit = 7 - (pos % 8);\n return ((Math.pow(2, bit) & validFor.charCodeAt(byteToCheck)) >> bit) == 1;\n }\n \n // For each dependent value, check whether it is valid for each controlling value\n var depValues = depFieldDesc.picklistValues;\n for (var i=0; i<depValues.length; i++) {\n var thisOption = depValues[i];\n var validForDec = base64.decode(thisOption.validFor);\n for (var ctrlValue=0; ctrlValue<ctrlValues.length; ctrlValue++) {\n if (testBit(validForDec, ctrlValue)) {\n dependentOptions[ctrlValues[ctrlValue].label].push(thisOption.label);\n }\n }\n }\n return dependentOptions;\n}",
"loadFieldInfo(){\n let fieldInfo = [];\n this.props.orderStore.currentOrder.templateFields.fieldlist.field.forEach(field =>\n this.props.orderStore.fieldInfo.push([field, '']));\n this.props.orderStore.fieldInfo.forEach(field =>\n {\n if(field[0].type == \"SEPARATOR\"){\n field[1] = \"**********\";\n }\n });\n }",
"function getProductDetails(thisProduct){\n\t\n\tvar product = \"\";\n\t\n\tproduct = {\n\t\t\t\n\t\t\tid : $(thisProduct).parent().parent().find(\"#product_id\").val(),\n\t\t\timagePath : $(thisProduct).parent().parent().find(\".image img\").attr(\"src\"),\n\t\t\tcategory : $(thisProduct).parent().parent().find(\"#category\").val(),\n\t\t\tprice : $(thisProduct).parent().parent().find(\"#price\").text(),\n\t\t\tname : $(thisProduct).parent().parent().find(\".name\").text(),\n\t\t\tmanufacturer : $(thisProduct).parent().parent().find(\".manufacturer\").text(),\n\t\t\tunits : $(thisProduct).parent().parent().find(\"#available\").text(),\n\t\t\tstatus : $(thisProduct).parent().parent().find(\".status\").text(),\n\t\t\tdescription : $(thisProduct).parent().parent().find(\"#description\").val()\n\t}\n\t\n\treturn product;\n}",
"function ShowSelectedFieldInputForm(field_title, field_type, field_id){\n \n}",
"renderSeqReplaceFieldOptions()\n\t{\n\n\t\tif(this.state.data.type == \"sequentialreplace\" && (this.state.target == undefined || this.state.target instanceof StructuredData))\n\t\t{\n\n\t\t\tif(this.state.data.settings.fields == undefined)\n\t\t\t{\n\n\t\t\t\tthis.state.data.settings.fields = []\n\n\t\t\t}\n\n\t\t\treturn(<div>\n\t\t\t\t\t<Form.Group inline>\n\t\t\t\t\t\t<Form.Select \n\t\t\t\t\t\tmultiple selection \n\t\t\t\t\t\terror={this.genIsErrorSettings(\"field\",\"Please select a field\")}\n\t\t\t\t\t\tplaceholder='Choose Field'\n\t\t\t\t\t\tname='fields'\n\t\t\t\t\t\toptions={this.state.fieldTypes}\n\t\t\t\t\t\tvalue={this.state.data.settings.fields}\n\t\t\t\t\t\tlabel=\"Fields:\"\n\t\t\t\t\t\tonChange={this.handleSettingChange.bind(this)}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t </Form.Group>\n\t\t\t\t {this.renderSeqReplaceFieldWarningMessage()}\n\t\t\t\t </div>)\n\n\t\t}\n\n\t}",
"static getFieldProps(key, props){\n return {\n iconmap: IconMap[key],\n id : key,\n name : key,\n value : props.values?.[key],\n error : props.errors?.[key],\n };\n }",
"function getMatchingDeOption(\n deObjects, group, clusterName, annotation, comparison='one_vs_rest', groupB=null\n) {\n const deObject = deObjects.find(deObj => {\n return (\n deObj.cluster_name === clusterName &&\n deObj.annotation_name === annotation.name &&\n deObj.annotation_scope === annotation.scope\n )\n })\n\n const matchingDeOption = deObject.select_options[comparison].find(option => {\n if (comparison === 'one_vs_rest') {\n return option[0] === group\n } else if (comparison === 'pairwise') {\n // Pairwise comparison. Naturally sort group labels, as only\n // naturally-sorted option is available, since combinations are not\n // ordered and we don't want to pass and store 2x the data.\n const [groupASorted, groupBSorted] = [group, groupB].sort((a, b) => {\n return a[0].localeCompare(b[0], 'en', { numeric: true, ignorePunctuation: true })\n })\n return option[0] === groupASorted && option[1] === groupBSorted\n }\n })\n\n return matchingDeOption\n}",
"function getProductFromTemplate(string) {\n if (string.indexOf('governance') >= 0) {\n return 'idg';\n }\n else if (string.indexOf('commons') >= 0) {\n return 'commons';\n }\n else if (string.indexOf('access-request') >= 0) {\n return 'access-request';\n }\n else {\n __.requestError(\"template ids must include 'governance', 'access-request', or 'commons' in them.\", 500);\n }\n}",
"function getProductOptionsHtml(products) {\n let result = '';\n\n products.forEach(product => {\n return result += `<li> <a href=\"#\" name=\"${product}\">${productsMap[product].name}</a> </li>`;\n });\n\n return result;\n}",
"resolveValues(item, field, index_as, cf) {\n if( index_as !== field ) {\n this.logger.debug(`resolveValues for ${item[\"@id\"]} ${field} ${index_as}`);\n }\n const resolved = this.resolveAndFlatten(item, field, index_as, cf);\n\n if( cf['multi'] ) {\n return resolved;\n } else {\n if( Array.isArray(resolved) ) {\n if( resolved.length > 1 ) {\n this.logger.warn(`${field} resolves to multiple values, but isn't configured as multi`);\n this.logger.warn(`config = ${JSON.stringify(cf)}`);\n }\n return resolved[0];\n }\n }\n }",
"function updateAnalyticsProdObj(data, evtIndex) {\n if (typeof s_setP !== 'undefined' && typeof data !== 'undefined') {\n\n if(data.product && data.product.length > 0) {\n s_setP('digitalData.event['+evtIndex+'].attributes.product', data.product);\n }\n }\n}",
"function loadPropertySelectData() {\n \"use strict\";\n var i;\n //depend on how many select tap.\n for (i = 0; i < getSelectID.length; i++) {\n createP_Option(getSelectID[i]);\n }\n}",
"get fields() {\n return tag.configure(SharePointQueryableCollection(this, \"fields\"), \"ct.fields\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The `const` funs returns its first argument and ignores the second. | function $const(x, y) /* forall<a,b> (x : a, y : b) -> a */ {
return x;
} | [
"function ConstantFunction()\r\n{\r\n const Pi=3.142;\r\n //Pi=5; // we cannot update the values in const variables\r\n console.log(Pi);\r\n}",
"function protoIsConst2() {\n return {b: 3, __proto__: 10};\n}",
"function getConstOrRandomColor(constValOrRandomizer, returnNullIfUndefined)\n{\n if (!constValOrRandomizer) {\n return (returnNullIfUndefined) ? null : new Color(1, 1, 1);\n } else if (constValOrRandomizer.generate) {\n return constValOrRandomizer.generate();\n }\n return constValOrRandomizer.clone();\n}",
"function passConst(input) {\n const out = xex.exp(input).root;\n const ref = evalInput(input);\n\n if (typeof out !== \"number\")\n throw new Error(`Expression '${input}': Should reduce to '${ref}'`);\n\n if (!bineq(out, ref))\n throw new Error(`Expression '${input}': Should reduce to '${ref}', not ${out}`);\n}",
"function pure(x, y) {\n return x + y;\n}",
"function two() { return s; return t;}",
"function foo({ x, y }) {\n return { x, y };\n }",
"function car(pair){\n return pair[0];\n}",
"function keepFirst(str) {\n return str.slice(0, 2);\n}",
"function myFun() \n{\n console.log(const_v,let_v,var_n);\n}",
"function isConst(varDecl) {\n return Boolean(varDecl && varDecl.parent &&\n ts.isVariableDeclarationList(varDecl.parent) &&\n varDecl.parent.flags & ts.NodeFlags.Const);\n}",
"function rest(input) {\n return input.substring(1);\n}",
"function firstVal(arg, func) {\n if(Array.isArray(arg) == Array) {\n func(arr[0], index, arr);\n }\n if(arr.constructor == Object) {\n func(arg[key], key, arg);\n}\n}",
"function smallestValue(){\n return Math.min(...arguments)\n}",
"function analyze_constant_declaration(stmt) {\n const name = constant_declaration_name(stmt);\n const value_func = analyze(constant_declaration_value(stmt));\n\n return (env, succeed, fail) => {\n value_func(env,\n (value, fail2) => {\n set_name_value(name, value, env, false);\n succeed(\"constant declared\", fail2);\n },\n fail);\n };\n\n}",
"function firstVal(arr, func) {\n func(arr[0], index, arr);\n}",
"function blockScopeBasicLetConstTestFunc() {\r\n let integer = 1;\r\n let string = \"2\";\r\n let object = { p1: 3, p2: 4 };\r\n const constInteger = 5;\r\n const constString = \"6\";\r\n const constObject = { cp1: { cp2: 7, cp3: 8 }, cp4: 9 };\r\n return 0;// /**bp:locals(2)**/\r\n}",
"function gather_w_def(def = \"no args passed\", ...rest){ \n console.log(\"first value passed: \", def );\n console.log(\"remaining values: \", rest);\n}",
"static One() {\n return new Vector2(1, 1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function kills the fullScreen instance. | function killFullScreen() {
toggleFullScreen();
_self = null;
if (_eventListenerElement)
_eventListenerElement.removeEventListener("click", toggleFullScreen);
} | [
"exitFullscreen() {\n if (this.isFullscreenEnabled()) {\n exitFullscreen();\n }\n }",
"function _hideEndScreen() {\r\n hideEndScreen();\r\n }",
"async hideSplashScreen() {\n\t\ttry {\n\t\t\tif (!this.splashScreenWindow) return;\n\t\t\tthis.splashScreenWindow.close();\n\t\t\tthis.splashScreenWindow = null;\n\t\t} catch (err) {\n\t\t\tlogger.error(`Unable to hide splash screen ${err.message}`);\n\t\t\tconst error = new Error('Error hiding splash screen.');\n\t\t\tthrow (error);\n\t\t}\n\t}",
"quit()\n\t{\n\t\t// stop game from listening for player input\n\t\tthis.input.shutdown();\n\n\t\t// blank screen\n\t\tthis.clearCanvas(\"#888\");\n\t}",
"removePauseScreen() {\n\t\tgameState.pauseOverlay.destroy();\n\t\tgameState.pauseText.destroy();\n\t\tgameState.resumeText.destroy();\n\t}",
"deactivate() {\n // Deactivate prompt.\n this.prompt.deactivate();\n this.prompt = null;\n\n // Deactivate display.\n this.display.deactivate();\n this.display = null;\n\n // Free up DOM element.\n this._app = null;\n }",
"async function exitFocus() {\n xapi.Command.UserInterface.Extensions.Panel.Update({ PanelId: 'focus_on_me', Visibility: 'Auto' })\n xapi.Command.UserInterface.Message.Alert.Display({ Title: 'System Lost Focus', Text: 'Access to Webex Assistant and Ultrasound Pairing disabled', Duration: 5 })\n await GMM.write('inFocus', false)\n xapi.Config.Audio.Ultrasound.MaxVolume.set(0)\n xapi.Config.VoiceControl.Wakeword.Mode.set('Off')\n console.log({ Message: 'System Exited Focus' })\n}",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"goFullScreen(name) {\r\n if (name && this._windows.has(name)) {\r\n this._windows.get(name).native.setFullScreen(true);\r\n return;\r\n }\r\n this._windows.forEach(win => win.native.setFullScreen(true));\r\n }",
"function clearScreen(){ displayVal.textContent = null}",
"function stopGame(){\n\tresetGame();\n\tgoPage('result');\n}",
"function outOfFocus(){\n if(playGame) env.pause(true);\n }",
"exitXR() {\n if ( this.chatLog ) {\n this.chatLog.input.virtualKeyboardEnabled = false;\n }\n }",
"function stop(exitCode) {\n server.close();\n rimraf.sync('webdriver-screenshots*/**/*+(full|regression).png', {});\n if (seleniumChild) {\n seleniumChild.kill();\n }\n }",
"_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }",
"function remove() {\n if (isVisible()) {\n var extendedSplashScreen = document.getElementById(\"extendedSplashScreen\");\n WinJS.Utilities.addClass(extendedSplashScreen, \"hidden\");\n }\n }",
"quitInteraction() {\n this.r3a1_map.alpha = 0.0;\n this.r3a1_notebook.alpha = 0.0;\n this.hideActivities();\n this.r3a1_activityLocked.alpha = 0.0;\n this.character.alpha = 1;\n this.r3a1_characterMoveable = true;\n //this.r3a1_activityOneOpened = false;\n //this.r3a1_activityTwoOpened = false;\n //this.r3a1_activityThreeOpened = false;\n //this.r3a1_activityFourOpened = false;\n //this.r3a1_activityFiveOpened = false;\n //this.r3a1_activitySixOpened = false;\n this.r3a1_help_menu.alpha = 0.0;\n this.r3a1_activatedQuiz = false;\n }",
"function powerOff() {\n setVisible(powerOffButton, false);\n setVisible(powerOnButton, true);\n if (fmRadio.isPlaying()) {\n fmRadio.stop();\n }\n saveCurrentStation();\n saveVolume();\n }",
"function dismissPrompt() {\n $('#powerPrompt').hide();\n $('#faded').hide();\n}",
"function gameLose() {\n gameState.active = false;\n gameReset();\n var startBtn = \"Retry\";\n var startText = \"<div class=\\\"splashtext\\\">You died :(</div>\";\n gamescreen(startBtn, startText);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the object representing yourself (person) to this array of people (if your name key does not have the same 'shape' as the ones above, change it to look like these). Write a function that, when passed people as an argument, returns an array of their full names. Can you use your formatName function here? | function returnName(people){
var arrayOfNames = [];
for (var i = 0; i < people.length; i++){
arrayOfNames.push(people[i].name.first + ' ' + people[i].name.last);
}
return arrayOfNames;
} | [
"function formatName(person){\n\treturn person.fullName;\n}",
"function appendListOfMaleEmployees(name) {\n listOfMaleEmployees.push(name);\n}",
"function fullName(array, index) {\n if (array[index].name.middle === undefined) {\n return array[index].name.first + \" \" + array[index].name.last;\n } else {\n return (\n array[index].name.first +\n \" \" +\n array[index].name.middle +\n \" \" +\n array[index].name.last\n );\n }\n}",
"function getFullNames(runners) {\n /* CODE HERE */\n let name = [];\n runners.forEach((index) => {\n name.push(index.last_name + \", \" + index.first_name);\n })\n return name;\n}",
"function createNamesArray(array) {\n const nameArray = [];\n array.map(item => nameArray.push(` ${item.item_name}`))\n return nameArray;\n}",
"function changeMe(arr) {\n var list = [];\n for (var i = 0; i < arr.length; i++) {\n var person = {\n // firstName;\n // lastName;\n // gender;\n // age;\n };\n person.firstName = arr[i][0];\n person.lastName = arr[i][1];\n person.gender = arr[i][2];\n\n if (arr[i][3] !== undefined){\n var agePerson = 2018 - arr[i][3];\n person.age = agePerson;\n } else{\n person.age = 'Invalid Birth Year';\n }\n list.push(person)\n }\n for (var j = 0; j < list.length; j++) {\n console.log(String(j+1)+'. '+ list[j].firstName +' '+ list[j].lastName +':');\n console.log(list[j]);\n }\n}",
"function addPerson() {\n const name = personName.value.trim();\n if (name && !persons.includes(name)) {\n persons.push(name);\n const person = new Person(name);\n selectedTeam.appendChild(person);\n }\n personName.value = \"\";\n}",
"function makeName() {\n let prefixArr = [];\n let suffixArr = [];\n let name;\n\n if (mySpecies.length < 1) return; // Don't make a name if there are no traits\n // Populate the prefix and suffix arrays\n for ( let i = 0; i < mySpecies.length; i ++ ) {\n for ( let j = 0; j < mySpecies[i].prefixes.length; j ++ ) {\n prefixArr.push(mySpecies[i].prefixes[j]);\n }\n for ( let k = 0; k < mySpecies[i].suffixes.length; k ++ ) {\n suffixArr.push(mySpecies[i].suffixes[k]);\n }\n }\n // Get random values from the prefix and suffix arrays\n let pre1 = getRandom(prefixArr);\n let pre2;\n let suf = getRandom(suffixArr);\n if (mySpecies.length <= 2) {\n name = pre1 + suf;\n } else {\n let pre2 = getRandom(prefixArr);\n // Ensure unique prefixes\n while ( pre2 == pre1 ) {\n pre2 = getRandom(prefixArr);\n }\n name = pre1 + pre2 + suf;\n }\n name = name.charAt(0).toUpperCase() + name.slice(1);\n document.getElementById(\"name\").innerHTML = name;\n}",
"function getPerson(name){\r\n let peopleList = filter_people(name, people)\r\n if(peopleList.length === 0){\r\n return null;\r\n }\r\n\r\n for(let i = 0; i < peopleList.length; i++){\r\n if(name === peopleList[i].name){\r\n return peopleList[i];\r\n }\r\n }\r\n return peopleList[0];\r\n}",
"function personsArrayToString(authorsArray) {\n /* jshint camelcase: false */\n /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */\n authorsArray = Array.isArray(authorsArray) ? authorsArray : [];\n\n return authorsArray.map(function (author) {\n if (author.first_name && 0 !== author.first_name.length) {\n return author.last_name + ', ' + author.first_name;\n } else {\n return author.last_name;\n }\n }).join('\\n');\n}",
"function add2List(me, friends) {\n var myName = me.name.substring(0, 20).toLowerCase();\n \n for (var i=0; i<friends.length; i++) {\n if (myName === friends[i].name.substring(0,20).toLowerCase()) {\n friends[i] = me;\n return;\n } \n }\n friends.push(me);\n }",
"function greetPeople(names) {\n\tconst a = [];\n\tfor (let i = 0; i < names.length; i++) {\n\t\ta.push(\"Hello \" + names[i]);\n\t}\n\treturn a.join(\", \");\n}",
"function displayPerson(person, people) {\n // print all of the information about a person:\n // height, weight, age, name, occupation, eye color.\n let personInfo = \"Name: \" + person.firstName + \" \" + person.lastName + \"\\n\";\n personInfo += \"Gender: \" + person.gender + \"\\n\";\n personInfo += \"DOB: \" + person.dob + \"\\n\";\n personInfo += \"Height: \" + person.height + \"\\n\";\n personInfo += \"Weight: \" + person.weight + \"\\n\";\n personInfo += \"Eye Color: \" + person.eyeColor + \"\\n\";\n personInfo += \"Occupation: \" + person.occupation + \"\\n\";\n personInfo += \"Parents: \" + retrievePersonName(person.parents[0], people) + \", \" + retrievePersonName(person.parents[1], people) + \"\\n\";\n personInfo += \"Current Spouse: \" + retrievePersonName(person.currentSpouse, people) + \"\\n\";\n\n // Craig DONE: finish getting the rest of the information to display\n\n alert(personInfo);\n}",
"getNames( fullName ) {\n \"use strict\";\n // Return firstName, middleName and lastName based on fullName components ([0],[1],[2])\n }",
"function getArtist(obj, people) {\n var artist = [];\n\n people.forEach(function (person) {\n var duplicate = false\n if (person.role === \"Artist\" && artist.length === 0) {\n artist.push(person.name)\n }\n if (person.role === \"Artist\" && artist.length !== 0) {\n for (var i = 0; i < artist.length; i++) {\n if (person.name === artist[i]) {\n duplicate = true\n }\n if (duplicate === true) {\n break\n }\n }\n if (duplicate === false) {\n artist.push(person.name)\n }\n }\n })\n\n artist.forEach(function (person, index) {\n if (person === \"Unidentified Artist\") {\n artist[index] = \"Unknown Artist\"\n }\n })\n\n if (artist.length === 0) {\n obj.artist = \"Unknown Artist\"\n }\n if (artist.length === 1) {\n obj.artist = artist[0];\n }\n if (artist.length > 1) {\n var artists = artist[0]\n for (var i = 1; i < artist.length; i++) {\n if (i !== artist.length - 1 && artist.length > 2) {\n artists += (\" and \" + artist[i])\n }\n if (i === artist.length - 1 && artist.length > 2) {\n artists += artist[artist.length - 1]\n }\n if (i === artist.length - 1 && artist.length === 2){\n artists += (\" and \" + artist[artist.length - 1])\n }\n }\n obj.artist = artists\n }\n}",
"function alphabetizer(names) {\n var alphabetNames = [];\n for (var name in names) { // iterate over each name\n var splitName = names[name].split(\" \"); // split into first and last name\n var lastname = splitName[1];\n splitName.unshift(lastname); // add last name to first index (now has 3 values in array)\n splitName.pop(); // remove duplicate last name\n nameSwitched = switchNames(splitName);\n alphabetNames.push(nameSwitched);\n }\n return alphabetNames.sort(); // alphabatize array\n}",
"function firstNamePrinter1(arr) {\n arr.forEach(item => {\n document.write(item.firstName + ' '+item.tattoos + '<br>')\n })\n }",
"function changePersonToBart(person) {\n //changes the property of firstName to be 'Bart'\n person.firstName = 'Bart'\n\n //changes the property of 'favorite color' to be orange\n person[\"favorite color\"] = \"orange\"\n \n //removes the last item in the hobbies array\n person.hobbies.pop()\n \n //adds a new item to the hobbies array\n person.hobbies.push('Skateboarding')\n \n //returns the object with the updated properties\n return person\n}",
"function splitNames(fullName){\n let names = fullName.split(\" \");\n let obj = {};\n obj.firstName = names[0];\n obj.lastName = names[names.length - 1];\n return obj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Functions For generating random color from Chroma | function generateHex() {
return chroma.random();
} | [
"function generateRGB() {\n\tvar r = Math.floor(Math.random() * 256);\n\tvar g = Math.floor(Math.random() * 256);\n\tvar b = Math.floor(Math.random() * 256);\n\treturn \"rgb(\" + r + \", \" + g + \", \" + b + \")\";\n}",
"function randomColourGen()\r\n{\r\n var colour = 'rgb(' + (Math.floor(Math.random() * 256)) +\r\n ',' + (Math.floor(Math.random() * 256)) +\r\n ',' + (Math.floor(Math.random() * 256)) + \r\n ',';\r\n var bright=colour+'1.0)';\r\n var light=colour+'0.7)';\r\n return [light,bright];\r\n}",
"function randomColorGenerator() {\n\t\treturn Math.floor(Math.random() * backgroundColors.length);\n}",
"function rgbColor()\n{\n\tvar string = \"rgb(\";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \")\";\n\treturn string;\n}",
"function randLightColor() {\r\n\tvar rC = Math.floor(Math.random() * 256);\r\n\tvar gC = Math.floor(Math.random() * 256);\r\n\tvar bC = Math.floor(Math.random() * 256);\r\n\twhile (Math.max(rC, gC, bC) < 200) {\r\n\t\trC = Math.floor(Math.random() * 256);\r\n\t\tgC = Math.floor(Math.random() * 256);\r\n\t\tbC = Math.floor(Math.random() * 256);\r\n\t}\r\n\treturn tColor(rC, gC, bC, 1.0);\r\n}",
"static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }",
"function rndColor() {\n var iRed = Math.floor((Math.random() * 255) + 1);\n var iGreen = Math.floor((Math.random() * 255) + 1);\n var iBlue = Math.floor((Math.random() * 255) + 1);\n\n $(\"#red\").slider(\"value\", iRed);\n $(\"#green\").slider(\"value\", iGreen);\n $(\"#blue\").slider(\"value\", iBlue);\n }",
"function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}",
"function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}",
"function randomColor(){\n\tlet selectedColor = content[Math.floor(Math.random()*(content.length-1))];\n\tlet line = selectedColor.split(',');\n\tlet hexCode = line[1].trim();\n\t// console.log(hexCode);\n\tlet red = hexCode.slice(1,3);\n\tlet green = hexCode.slice(3,5);\n\tlet blue = hexCode.slice(5);\n\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\tred = parseInt(\"\"+red, 16);\n\tgreen = parseInt(\"\"+green, 16);\n\tblue = parseInt(\"\"+blue, 16);\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\n\t// console.log('random hex is ' + hexCode);\n\tlet randomColor = new color(red, green, blue);\n\t// console.log(randomColor);\n\treturn randomColor;\n}",
"function winningColorGenerator(){\r\n\tfor (var i = 0; i < colors.length; i++){\r\n\t\tvar randNum = Math.floor(Math.random() * numSquare);\r\n\t}\r\n\treturn colors[randNum];\r\n}",
"function getHexColor() {\n if (Math.round(Math.random())) {\n return \"ff\";\n } else {\n return \"00\";\n }\n}",
"function colorGenerator(numbox) {\n // create a set of 6 randon colour array\n arrayCol = [];\n // set num parameter form fix number of game colour box\n for (let i = 0; i < numbox; i++) {\n arrayCol.push(rbgColor());\n }\n // return the colour array to colors variable\n return arrayCol;\n}",
"function randomizeColors() {\n for (let i = ORIGINAL_COLORS.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = ORIGINAL_COLORS[i];\n ORIGINAL_COLORS[i] = ORIGINAL_COLORS[j];\n ORIGINAL_COLORS[j] = temp;\n }\n}",
"function color() {\n\tfor (var i = 0; i < num; i++) {\n\t\tcoloring.push(randomize());\n\t}\n}",
"function randomValue () {\n var random = Math.floor(Math.random()*4);\n progressComputer.push(colors[random]);\n }",
"function getLikeColor(a_color) {\n let its_red = p5.red(a_color);\n let its_green = p5.green(a_color);\n let its_blue = p5.blue(a_color);\n let total_colors = its_red + its_green + its_blue;\n if (total_colors == 0) {\n //if it's black, need to set so that total isn't zero\n its_red = 10;\n its_green = 10;\n its_blue = 10;\n total_colors = its_red + its_green + its_blue;\n }\n //if it's a light color, get a like color that's darker\n let new_total_colors = p5.int(p5.random(0, 255 * 3));\n //set same proportions of each color in the old color for the new color\n let new_color = p5.color(\n (its_red * new_total_colors) / total_colors,\n (its_green * new_total_colors) / total_colors,\n (its_blue * new_total_colors) / total_colors\n );\n return new_color;\n }",
"static randomP5Color(hasRandomAlpha: boolean = false): $FlowIgnore {\n return w.color(Color.randomRGBATuple(hasRandomAlpha));\n }",
"_generatePaletteRandom( palette, firstHue )\t{\r\n\t\tlet colorHsv = { \r\n\t\t\th : firstHue, \r\n\t\t\ts : this._options.palette.saturation, \r\n\t\t\tv : this._options.palette.brightness,\r\n\t\t\ta : 1 // alpha\r\n\t\t};\r\n\r\n\t\tconst bgToFgFunction = z42easing[ this._options.palette.easeFunctionBgToFg ];\r\n\t\tconst fgToBgFunction = z42easing[ this._options.palette.easeFunctionFgToBg ];\r\n\t\t\r\n\t\tlet palIndex = 0;\r\n\t\tconst palRange = palette.length / this._paletteColorCount / 2;\r\n\t\t\r\n\t\tfor( let i = 0; i < this._paletteColorCount; ++i ){\r\n\t\t\tconst colorRGBA = z42color.nextGoldenRatioColorRGBA( colorHsv ); \r\n\t\t\r\n\t\t\tpalIndex = z42color.makePaletteGradientRGBA( palette, palIndex, palRange, this._options.palette.bgColor, colorRGBA, bgToFgFunction );\r\n\t\t\tpalIndex = z42color.makePaletteGradientRGBA( palette, palIndex, palRange, colorRGBA, this._options.palette.bgColor, fgToBgFunction );\t\t\t\r\n\t\t}\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
END Google Books Dynamic Display Display the returned data to dynamically change page based on the Marvel function returns. | function marvelDisplay(data) {
pageData = data.data.results;
//data row from HTML, tagged data-row-show in html
var dataRow = document.getElementById('data-row-show');
var rowDataShow = ``;
//this is the data to get from API call to display for character search
for (var i = 0; i < pageData.length; i++) {
var name = pageData[i].name;
var description = pageData[i].description;
var thumbnail = pageData[i].thumbnail.path;
var extension = pageData[i].thumbnail.extension;
// This filters to only show items that have thumbnail
if (!pageData[i].thumbnail.path.includes('image_not_available')) {
rowDataShow += `
<div class="column">
<div class="card">
<div class="card-section">
<img src="${thumbnail}.${extension}">
</div>
<div class="card-section">
<h4>${name}</h4>
<p>${description}</p>
</div>
</div>
</div>
`;
}
}
//this is the dynamic to show is rowDataShow area
dataRow.innerHTML = rowDataShow;
} | [
"function renderGoogleBookData(results){\n $(\".bookcls\").html(\"\");\n $(\".bookcls\").html(`<h2 class=\"conHead\">Books</h2>`);\n\n let html = '<ul class=\"content-list\">';\n results.forEach(function(value){\n \n html += `\n <li class=\"book-cls content-list-item\">\n <h1 class=\"booktitle\">${value.volumeInfo.title}</h1>\n <img src =\"${value.volumeInfo.imageLinks.thumbnail}\" alt=\"book-image\">\n </a>\n <p class=\"bkdes\">${value.volumeInfo.description}</p>\n <a href=\"${value.accessInfo.webReaderLink}\" target=\"_blank\"> See ${value.volumeInfo.title} Here</a>\n </li>\n `\n \n\n })\n\n html += '</ul>';\n $(\".bookcls\").append(html);\n}",
"function showCatalouge() {\n\tfor (var i = 0; i <= bookCatalouge.length - 1; i++) {\n\t\tbookCatalouge[i].getTitleShow();\n\t\tbookCatalouge[i].getAuthorShow();\n\t\tbookCatalouge[i].getPageCountShow();\n\t\tconsole.log(\"-----------------------------------------------------------\");\n\t}\n}",
"function displayBook(){\n document.getElementById(\"reviews\").innerHTML = \"\";\n document.getElementById(\"singlebook\").style.display = \"block\";\n document.getElementById(\"allbooks\").innerHTML = \"\";\n getInfo(this.id);\n getDescription(this.id);\n getReviews(this.id);\n }",
"function displayResult() {}",
"function Show() {\n var CurrentHttpParameterMap = request.httpParameterMap;\n var CurrentForms = session.forms;\n\n CurrentForms.giftregistry.clearFormElement();\n\n\n var ProductListID = CurrentHttpParameterMap.ID.stringValue;\n\n var ProductList = null;\n var Status = null;\n\n if (typeof(ProductListID) !== 'undefined' && ProductListID !== null) {\n var GetProductListResult = new Pipelet('GetProductList', {\n Create: false\n }).execute({\n ProductListID: ProductListID\n });\n if (GetProductListResult.result === PIPELET_ERROR) {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'notfound');\n } else {\n ProductList = GetProductListResult.ProductList;\n\n if (ProductList.public) {\n CurrentForms.giftregistry.items.copyFrom(ProductList.publicItems);\n CurrentForms.giftregistry.event.copyFrom(ProductList);\n } else {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'private');\n ProductList = null;\n }\n }\n } else {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'notfound');\n }\n\n\n ISML.renderTemplate('', {\n ProductList: ProductList,\n Status: Status\n });\n}",
"function FetchTitlesCallBack(data) \n{\n $(\"#movieListingContainer\").empty();\n HideLoading();\n var results = data;\n $.get('scripts/templates/moviedisplay.txt', function (template) \n //$.get('moviedisplay.txt', function (template) \n {\n $.tmpl(template, results, \n {\n runtime: function () \n {\n var runTime = this.data[\"Runtime\"];\n if (runTime == null)\n return \"N/A\";\n else\n return GetRunTimeInMinutes(runTime);\n }\n }).appendTo('#movieListingContainer');\n }\n );\n SetListingCriteria();\n \n setTimeout(ApplyRating, 500)\n\n SetPager(startPage, results.length);\n}",
"function executeOnPage_Book(){\r\n\tgetCallButton();\r\n\r\n\tloadValues();\r\n\r\n\tgetsCallSelects();\r\n}",
"function bookRecommendations () {\n \n fetch(\n 'https://api.nytimes.com/svc/books/v3/lists/current/e-book-fiction.json?api-key=HXMcUKu4hWhoZPQBW99bGZ9An0FdbWEl'\n )\n .then(function(res) {\n return res.json();\n })\n .then(function(res) {\n console.log(res);\n displayRecommendations(res);\n });\n }",
"function displayFilmsData(data) {\r\n cartegoriesCounter = 0;\r\n var listBox = document.getElementById(\"searchResults\");\r\n listBox.innerHTML = \"\";\r\n listBox.innerHTML = \"<p>Title: \" + data.results[0].title + \"</p>\" +\r\n \"<br><p>Episode: \" + data.results[0].episode_id + \"</p><br>\" +\r\n \"<p>Opening Crawl:</p><br><p>\" + data.results[0].opening_crawl +\r\n \"<br><p>Director: \" + data.results[0].director + \"</p><br>\" +\r\n \"<p>Producer(s): \" + data.results[0].producer + \"</p>\";\r\n }",
"function displayParkSearchData(item) {\n const campgroundStringArray = [];\n if (item.data.length == 0) {\n campgroundStringArray.push(`<div class=\"expanded-info\"><p class=\"no-info\">This park does not have any campgrounds.</p></div>`);\n } else {\n $.each(item.data, function (itemkey, itemvalue) {\n let code = itemvalue.parkCode;\n let water = [];\n let toilets = [];\n let showers = [];\n let reservationUrl = itemvalue.reservationUrl ?? 'google.com';\n console.log(itemvalue);\n\n // create array for result for each amenity\n if (itemvalue.amenities && itemvalue.amenities.potableWater) {\n for (let i = 0; i < itemvalue.amenities.potableWater.length; i++) {\n water.push(itemvalue.amenities.potableWater[i]);\n };\n }\n\n let resUrl;\n\n // create array for result for each amenity\n // for (let i = 0; i < itemvalue.amenities.potableWater.length; i++) {\n // water.push(itemvalue.amenities.potableWater[i]);\n // };\n\n for (let i = 0; i < itemvalue.amenities.toilets.length; i++) {\n toilets.push(itemvalue.amenities.toilets[i]);\n };\n\n for (let i = 0; i < itemvalue.amenities.showers.length; i++) {\n showers.push(itemvalue.amenities.showers[i]);\n };\n\n campgroundStringArray.push(`\n <h3>${itemvalue.name}</h3>\n <div class=\"expanded-info\">\n <p>${itemvalue.description}</p>\n <p>Potable Water: ${water}<br>\n Toilets: ${toilets}<br>\n Showers: ${showers}<br>\n Campsites:<br>\n Total sites: ${itemvalue.campsites.totalSites}<br>\n Electrical Hookups: ${itemvalue.campsites.electricalHookups}<br>\n Group sites: ${itemvalue.campsites.group}<br>\n RV only sites: ${itemvalue.campsites.rvOnly}<br>\n Tent only sites: ${itemvalue.campsites.tentOnly}</p>\n <br>\n <br>\n <a href=${itemvalue.reservationUrl} target=\"_blank\">Make a reservation at: ${itemvalue.reservationUrl}</a>\n </div>`);\n });\n };\n\n renderParkResult(campgroundStringArray);\n}",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}",
"function ShowVerse (call) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// call is path to json api //\n\t$.getJSON(call, function( data ) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Json Call to api //\n \tvar items = [];\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Place holder for verse array //\n \tvar verses = data.nodes.length // Number of Verse passed through JSON to display.\t\t\t// Count the number of verses from call //\n \tvar verseLoop=0; // Counter for display verses.\t\t\t\t\t\t\t\t\t\t\t\t// Counter for while loop //\n \ttranslation = data.nodes[0].node.Synonyms;\t\t\t\n \tbook = data.nodes[0].node.field_book;\n \tchapter = data.nodes[0].node.field_chapter;\n \tverse = data.nodes[0].node.field_verse;\n \twhile (verseLoop < verses) {\n \t\titems.push( '<h2 class=\"verse\">' + data.nodes[verseLoop].node.title + '</h2><p>' + data.nodes[verseLoop].node.body + '</p><span>' + data.nodes[verseLoop].node.field_translation + '</span>');\n \t\tverseLoop++ }\n\t$( \".flip\" ).empty().append(items);\t\n\t\thistory.pushState(null, \"\", \"?&verse&\" + translation + \"&\" + book + \"&\" + chapter + \"&\" + verse );\t\n\t\t$(document).prop('title', data.nodes[0].node.title + ' | HolyFlip!'); \t\t\t\t// Change the Page title //\n\t\t\n\t\t\n\n});\n\n\n}",
"function fetchBooks() {\n fetch('https://anapioficeandfire.com/api/books').then(respfrombooks => respfrombooks.json()).then(respfrombooksjson => renderBooks(respfrombooksjson))\n}",
"function displayPetals() {\n const start = (currentPage - 1)\n}",
"function showList(a_oItems, g_nLoc){\n \n var s_List = \"\"; \n for (var i=0; i< a_oItems.length; i++){\n s_List = s_List + \"\\n\" + a_oItems[i].Name(g_nLoc); \n } \n return s_List; \n}",
"function _drawResults() {\n\n let template = \"\";\n store.state.songs.forEach(song => {\n template += song.SearchTemplate;\n });\n document.getElementById(\"songs\").innerHTML = template;\n}",
"function loadDatafromSPAGEBER() {\n\n // SP Services get list items - get all for list\n var CamlQuery = \"<Query>\";\n CamlQuery += \"<Where/>\";\n CamlQuery += \"<OrderBy>\";\n CamlQuery += \"<FieldRef Name=\\'\" + AGEBERKirchenkreisColumn + \"\\' />\";\n CamlQuery += \"<FieldRef Name=\\'\" + AGEBERNameColumn + \"\\' />\";\n CamlQuery += \"</OrderBy>\";\n CamlQuery += \"</Query>\";\n\n //var CamlViewFields = \"<ViewFields/>\";\n\n var CamlViewFields = \"<ViewFields>\";\n CamlViewFields += \"<FieldRef Name=\\'\" + AGEBERNameColumn + \"\\' />\";\n CamlViewFields += \"<FieldRef Name=\\'\" + AGEBERKirchenkreisColumn + \"\\' />\";\n CamlViewFields += \"</ViewFields>\";\n\n // this let me know that the function is getting called and passed the correct parameter value\n $().SPServices({\n operation: \"GetListItems\",\n webURL: ListURL,\n async: false,\n listName: AGEBERListname,\n CAMLViewFields: CamlViewFields,\n CAMLQuery: CamlQuery,\n completefunc: ProcessResultAGEBER\n });\n}",
"function showBookShelf() {}",
"function recommendations() {\r\n\tdisplayResult(\"genreMessage\", \"IMDb Recommendations for \" + selectedGenre + \" films\");\r\n\t\r\n\t//Create the table definition - making it dynamic so that any number of films per genre will be catered for\r\n\tvar tableDef = \"<tr><th></th><th></th><th>Title</th><th>Description</th><th>Director</th><th>Staring</th><th>Age</th></tr>\";\t\r\n\t\r\n\tfor (var i = 0; i < genreArray.length; i++) {\r\n\t\ttableDef += \"<tr><td rowspan='2' width='3%' align='center'>\";\r\n\t\ttableDef += genreArray[i].starRating;\r\n\t\ttableDef += \"</td><td rowspan='2' width='5%'>\";\r\n\t\ttableDef += genreArray[i].filmImage;\r\n\t\ttableDef += \"</td><td rowspan='2' width='12%' align='center'>\";\r\n\t\ttableDef += genreArray[i].title;\r\n\t\ttableDef += \"</td><td width='45%'>\";\r\n\t\ttableDef += genreArray[i].description;\r\n\t\ttableDef += \"</td><td width='10%' align='center'>\";\r\n\t\ttableDef += genreArray[i].director;\r\n\t\ttableDef += \"</td><td rowspan='2' width='20%'>\";\r\n\t\ttableDef += genreArray[i].staring;\r\n\t\ttableDef += \"</td><td rowspan='2' width='5%' align='center'>\";\r\n\t\ttableDef += genreArray[i].ageRating;\r\n\t\ttableDef += \"</td></tr>\";\r\n\t\ttableDef += \"<tr><td>\";\t\t\t\t\r\n\t\ttableDef += \"<strong>IMDb Review: </strong>\" + genreArray[i].review;\r\n\t\ttableDef += \"</td><td align='center'>\";\t\r\n\t\ttableDef += \"<strong>Year Recorded: </strong>\" + genreArray[i].yearRecorded;\t\r\n\t\ttableDef += \"</td></tr>\";\r\n\t}\r\n\tdisplayResult(\"recommended\", tableDef);\t\t\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save all coins in cache | function saveCoinsInCache(coins) {
state.cacheAllCoins = coins;
} | [
"function saveSpecifCoinInCache(coinInfo) {\n let coinFullInfo = {\n coinInfo: coinInfo,\n //add cache time\n cacheTime: +new Date(Date.now()),\n };\n state.cachesSpecificCoin.set(coinInfo.id, coinFullInfo);\n //return id to show more info in UI\n return coinInfo.id;\n }",
"function showAllCoins() {\n let allCoins = state.getAllCacheCoins();\n showCoinsUI(allCoins);\n $(\".loading-spinner-page\").hide();\n }",
"function AddCoins() {\n if (ircClient && ircClient.chans && ircClient.chans[channel] && ircClient.chans[channel].users) {\n _.each(_.keys(ircClient.chans[channel].users), function (u) {\n userDB.findOne({ channel: channel, nick: u }, function (e, r) {\n if (e) {\n console.log(e);\n }\n else if (!r) {\n var baby = new userDB({\n channel: channel,\n nick: u,\n coins: config.coinAcc.amount + config.coinAcc.firstTimeBonus,\n });\n baby.save();\n }\n else {\n r.coins += config.coinAcc.amount;\n r.save();\n }\n });\n });\n }\n setTimeout(AddCoins, config.coinAcc.frequency);\n }",
"flush () {\n this.cacheStore = {}\n }",
"async function update() {\n try {\n let coins = await fetchStablecoins();\n DATA.stablecoins = updateStablecoinData(coins, DATA.stablecoins);\n DATA.metrics = calcMetrics(DATA.stablecoins);\n DATA.platform_data = calcPlatformData(DATA.stablecoins);\n console.info('Data Updated.');\n } catch (e) {\n console.error(` ***CRITICAL*** Could not update data: ${e}`);\n }\n}",
"function setCredits() {\n console.log('check setCredits ', cache);\n let credits_by_id = cache['credits'];\n\n let credits = groupBy(Object.values(credits_by_id), 'day_id'); // TODO: sql join add date field\n\n // Count sum for each date\n let data_pre = {};\n for (let day_id in cache['days']) { // TODO: load days\n data_pre[cache['days'][day_id].date] = 0;\n }\n\n let total_sum = 0;\n for (let day_id in credits) {\n let sum = 0;\n let date = cache['days'][day_id].date;\n\n for (let credit of credits[day_id]) {\n sum += (credit.value === undefined ? 0 : credit.value);\n }\n\n data_pre[date] = sum;\n total_sum += sum;\n }\n\n // Setup progress bar\n console.log(total_sum +\" - \"+ cache['user'].total);\n bar.animate(total_sum / cache['user'].total ); // Number from 0.0 to 1.0\n\n document.querySelector('.credits__title').innerText = total_sum + ' / ' + cache['user'].total;\n\n // Correct setup.sh of zeros values (future days)\n data = [];\n dataShort = [];\n days = [];\n let flag = false;\n for (let day_id of Object.keys(cache['days']).reverse()) {\n // console.log(day_id);\n let date = cache['days'][day_id].date;\n\n if (data_pre[date] !== 0) {\n flag = true;\n }\n\n if (flag) {\n dataShort.unshift(data_pre[date]);\n }\n data.unshift(data_pre[date]);\n days.unshift(cache['days'][day_id].date);\n }\n\n\n // Load text data of credits\n let html_history = '';\n for (let day_id in credits) {\n html_history += '<div class=\"credits__history_day img-div\">';\n\n html_history += '<h3>' + cache['days'][day_id].date + '</h3>';\n\n for (let credit of credits[day_id]) {\n html_history += '<div class=\"credits__history_item\">' +\n '<div>'+\n '<i class=\"mobile__item__icon large material-icons\">' + (credit.type == 1 ? 'edit' : credits.type == 2 ? 'school' : 'event') + '</i>' +\n '<p>' + credit.title + '</p>' +\n '</div>' +\n '<p class=\"' + (credit.value > 0 ? 'credits_positive' : 'credits_negative') + '\">' + (credit.value > 0 ? '+' : '-') + credit.value + '</p>' +\n '</div>';\n }\n\n html_history += '</div>';\n }\n\n document.querySelector('.credits__history').innerHTML = html_history;\n\n console.log(days, data, dataShort);\n setupCreditsChart(days, data, dataShort);\n}",
"getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }",
"makeCoin(){\n for (let i = 0; i < this.numberOfCoins; i++){\n this.randX = Math.floor(random(this.mapSize));\n this.randY = Math.floor(random(this.mapSize));\n if (this.gameMap[this.randY][this.randX] === 0) {this.gameMap[this.randY][this.randX] = 4;}\n else {i--;}\n }\n \n }",
"function updateGold(){\n //update gold counter\n $(\".cashCounter\").html('');\n $(\".cashCounter\").html(\"$\"+totalGold);\n //update goldcounting cookie to save your progress \n document.cookie = \"gold=\"+totalGold+\"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/\";\n }",
"async getAllHolders() {\n // get the current total supply of cats\n const totalSupply = await this.contract.methods.totalSupply().call();\n\n // create an object to hold all holders\n const holder = {};\n\n // iterate through all cats\n for(let i = 0; i < totalSupply; i++){\n\n // ask the contract who the current holder is\n let ownerAddress = await this.contract.methods.ownerOf(i).call();\n // normalise addresses to avoid duplicates\n ownerAddress = ownerAddress.toLowerCase();\n\n // use holder addresses as object keys\n if(!holder[ownerAddress]){\n holder[ownerAddress] = 1;\n } else {\n holder[ownerAddress]++;\n }\n }\n\n // flatten the data and save\n const flatData = JSON.stringify(holder);\n fs.writeFile('./finalSnapShot/holders.json', flatData,{ flag: 'w' },function (err) {\n if (err) return console.log(err);\n });\n }",
"function getCoins(){\n\n\t$.getJSON(\"https://min-api.cryptocompare.com/data/all/coinlist\", function(data) {\n\n\t\t// Update the CRYPTOCODES dictionary with the data from the API\n\t\tfor (var key in data[\"Data\"]) {\n\t\t\tif($.inArray(data[\"Data\"][key][\"Symbol\"], TOPCOINS) != -1){\n\t\t\t\tCRYPTOCODES[data[\"Data\"][key][\"FullName\"]] = data[\"Data\"][key][\"Symbol\"];\t\n\t\t\t}\n\t\t}\n\n\t\tupdateDropdowns();\n\t\t// Start getting all the coin prices\n\t getMorePrices();\n\t});\n}",
"function getCoins() {\r\n console.log(\"checking if getCoins works\");\r\n $.get(\"/api/coins\", function(data){\r\n\r\n var rowsToAdd = [];\r\n var coinPriceArray = [];\r\n for (var i = 0; i <data.length; i++) {\r\n rowsToAdd.push(createCoinRow(data[i]));\r\n }\r\n renderCoinList(rowsToAdd);\r\n console.log(\"rows to add are \" + rowsToAdd);\r\n });\r\n \r\n }",
"function getCoinsFromServer() {\n const url = \"https://api.coingecko.com/api/v3/coins/\";\n let promise = $.get(url);\n return promise;\n }",
"function updateCache() {\n request('https://hypno.nimja.com/app', function (error, response, body) {\n if (error) {\n console.log(error);\n }\n var data = JSON.parse(body);\n if (data) {\n cache = data;\n parseCacheForSearchAndLookup();\n }\n });\n}",
"async doSaveCacheHistory() {\n\t\tlet theUnsaved = this.historyCache.getUnSaved();\n\t\tif (!$.isEmptyObject(theUnsaved)) { await this.doAddToDB('searching', 'history', Object.values(theUnsaved)); }\n\t}",
"function clearWalletCache() {\n _.forIn(allWallets, function(wallet) {\n walletCache.remove(wallet.data.id);\n console.assert(_.isUndefined(walletCache.get(wallet.data.id)), wallet.data.id + ' was not removed from walletCache');\n });\n initEmptyWallets();\n }",
"function setPazzleCoins(){\r\n while(true){\r\n to_next_coin = Math.floor(Math.random() * (COIN_DISTANCE_MAX+1-COIN_DISTANCE_MIN)) + COIN_DISTANCE_MIN;\r\n total_coin_length = total_coin_length + to_next_coin;\r\n if(total_coin_length > total_cource_length){\r\n break;\r\n }\r\n // TODO: Get Lat Long\r\n long = 0.0;\r\n lat = 0.0;\r\n\r\n PazzleCoins[i] = new PazzleCoin(total_coin_length,long,lat);\r\n i ++;\r\n }\r\n }",
"function collectCoin(player, Coin){\n \tCoinPU.play();\n Coin.kill();\n coinsCollected+=1;\n }",
"'players.reduceVentureCoins'(num_coins){\n var current_coins = Players.findOne({'owner': Meteor.userId()}).goldCoin;\n if(current_coins < num_coins){\n return false;\n }\n \n Players.update(\n { 'owner': Meteor.userId()},\n { $inc:{'goldCoin': -1 * num_coins}}\n );\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The use an observable for a disposable object, use it a DisposableOwner: D.create(obs, ...args) // Preferred obs.autoDispose(D.create(null, ...args)) // Equivalent Either of these usages will set the observable to the newly created value. The observable will dispose the owned value when it's set to another value, or when it itself is disposed. | autoDispose(value) {
this.setAndTrigger(value);
this._owned = value;
return value;
} | [
"function throttled(delay, initialValue) {\n var timeout = void 0;\n var data = initialValue;\n var subscriptions = new Set();\n var updateValue = function updateValue(value) {\n data = value;\n clearTimeout(timeout);\n timeout = setTimeout(function () {\n subscriptions.forEach(function (subscription) {\n return subscription(data);\n });\n }, delay);\n };\n var observableContainer = function observableContainer(value) {\n if (arguments.length) {\n if (!equals(data, value)) {\n updateValue(value);\n }\n return this;\n } else {\n return data;\n }\n };\n observableContainer.subscribe = function (subscription) {\n subscriptions.add(subscription);\n };\n observableContainer.unsubscribe = function (subscription) {\n subscriptions.delete(subscription);\n };\n observableContainer.unsubscribeAll = function () {\n subscriptions.clear();\n };\n observableContainer.subscriptionsCount = function () {\n return subscriptions.size;\n };\n return observableContainer;\n}",
"function wrap(observable) { return new Wrapper(observable); }",
"createEventObservable(eventName, infoWindow) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._infoWindows.get(infoWindow).then(i => {\n i.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }",
"function create(fetchFn, subscribe) {\n // Convert to functions that returns RelayObservable.\n var observeFetch = convertFetch(fetchFn);\n\n function execute(request, variables, cacheConfig, uploadables, logRequestInfo) {\n if (request.operationKind === 'subscription') {\n !subscribe ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: This network layer does not support Subscriptions. ' + 'To use Subscriptions, provide a custom network layer.') : invariant(false) : void 0;\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while subscribing.') : invariant(false) : void 0;\n return subscribe(request, variables, cacheConfig);\n }\n\n var pollInterval = cacheConfig.poll;\n\n if (pollInterval != null) {\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while polling.') : invariant(false) : void 0;\n return observeFetch(request, variables, {\n force: true\n }).poll(pollInterval);\n }\n\n return observeFetch(request, variables, cacheConfig, uploadables, logRequestInfo);\n }\n\n return {\n execute: execute\n };\n}",
"_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }",
"function make(x, options = {}) {\n var {debug = DEBUG_ALL} = options;\n var u;\n\n debug = DEBUG && debug;\n\n if (x === undefined) u = makeUndefined();\n else if (x === null) u = makeNull();\n else {\n u = Object(x);\n if (!is(u)) {\n add(u, debug);\n defineProperty(u, 'change', { value: change });\n }\n }\n if (debug) console.debug(...channel.debug(\"Created upwardable\", u._upwardableId, \"from\", x));\n return u;\n}",
"function Lazy(create) {\n this.value = create\n this.get = this.init\n}",
"function observer(name, view) {\n\t// If no name provided for the observer:\n\tif (view === undefined) {\n\t\tview = name;\n\n\t\t// Generate friendly name for debugging (See: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/src/observer.ts#L105)\n\t\tname = view.displayName || view.name || (view.constructor && (view.constructor.displayName || view.constructor.name)) || '<View>';\n\t}\n\n\t// The name for the MobX Reaction, for debugging:\n\tvar reactionName = name + \".render()\";\n\n\n\t// We need to hook into the init() of the vm, just after that init() is executed,\n\t// so that all the vm.config(...) have been executed on the vm.\n\t// This is a bit complex depending on the type of the view.\n\t// Refer to the ViewModel constructor for details:\n\t//\t https://github.com/domvm/domvm/blob/3.4.8/src/view/ViewModel.js#L48\n\n\tif (isPlainObj(view)) {\n\t\t// view is an object: just set our own init on it.\n\t\twrapInit(view, reactionName);\n\t}\n\telse {\n\t\t// view is a function: we can't do anything before it is executed, so we wrap it\n\t\t// with a function that will set our own init later.\n\t\tview = (function(view) {\n\t\t\treturn function(vm) {\n\t\t\t\tvar out = view.apply(this, arguments);\n\n\t\t\t\tif (isFunc(out))\n\t\t\t\t\twrapInit(vm, reactionName);\n\t\t\t\telse {\n\t\t\t\t\t// In case multiple executions of view() returns the same object,\n\t\t\t\t\t// we want to wrap init only once:\n\t\t\t\t\twrapInitOnce(out, reactionName);\n\t\t\t\t}\n\n\t\t\t\treturn out;\n\t\t\t};\n\t\t})(view);\n\t}\n\n\treturn view;\n}",
"dispose() {\n const iterator = this.observers;\n while (iterator.length) {\n iterator.shift().unsubscribe();\n }\n }",
"disconnectBroker$() {\n return Rx.fromPromise(this.mqttClient.end());\n }",
"makeObservable(propertyNames) {\n var that = this;\n for (var propertyName of propertyNames) {\n // wrap into anonymous function to get correct closure behavior\n (function(pn) {\n const fieldName = \"_\" + pn;\n that[fieldName] = that[pn]; // ensure initial value is set to created field\n Object.defineProperty(that, pn, {\n enumerable: true,\n configurable: true,\n get() { return that[\"_\" + pn]; },\n set(value) {\n const oldValue = that[fieldName];\n that[fieldName] = value;\n that._firePropertyChanged(pn, oldValue, value);\n }\n });\n const subscribeFunctionName = pn + \"Changed\";\n that[subscribeFunctionName] = (listenerFunction) => that._listen(pn, listenerFunction);\n })(propertyName);\n }\n }",
"gr(t) {\n return e => {\n this.Oe.enqueueAndForget(() => this.sr === t ? e() : (k(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), Promise.resolve()));\n };\n }",
"function dispense() {\n var obj = null,\n objWithTimeout = null,\n err = null,\n clientCb = null,\n waitingCount = waitingClients.size();\n\n log(\"dispense() clients=\" + waitingCount + \" available=\" + availableObjects.length, 'info');\n if (waitingCount > 0) {\n while (availableObjects.length > 0) {\n log(\"dispense() - reusing obj\", 'verbose');\n objWithTimeout = availableObjects[0];\n if (!factory.validate(objWithTimeout.obj)) {\n me.destroy(objWithTimeout.obj);\n continue;\n }\n availableObjects.shift();\n clientCb = waitingClients.dequeue();\n return clientCb(err, objWithTimeout.obj);\n }\n if (count < factory.max) {\n createResource();\n }\n }\n }",
"extendRxObservables() {\n return require('nylas-observables');\n }",
"createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(d => {\n d.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }",
"setUserInput (gate, observable) {\n if (userInputsSubscriptions.has(gate.id)) {\n userInputsSubscriptions.get(gate.id).unsubscribe()\n }\n userInputsSubscriptions.set(\n gate.id,\n observable.subscribe((...args) => {\n getUserInput(gate).next(...args)\n })\n )\n }",
"render(source, host, hostBindingTarget) {\n if (typeof host === \"string\") {\n host = document.getElementById(host);\n }\n if (hostBindingTarget === void 0) {\n hostBindingTarget = host;\n }\n const view = this.create(hostBindingTarget);\n view.bind(source, _observation_observable__WEBPACK_IMPORTED_MODULE_3__.defaultExecutionContext);\n view.appendTo(host);\n return view;\n }",
"function autoHideTips(tips, templet, timeout) {\n /*\n export function autoHideTips(tips: IObservableValue<boolean|string|JSX.Element>, timeout?:number):React.FunctionComponentElement<any>;\n export function autoHideTips(tips: IObservableValue<boolean|string|JSX.Element>, templet:(tips: boolean|string|JSX.Element) => JSX.Element, timeout?:number):React.FunctionComponentElement<any>;\n \n export function autoHideTips(tips: IObservableValue<boolean|string|JSX.Element>, ...params:any[]) {\n */\n var timer;\n return react_1.default.createElement(mobx_react_1.observer(function () {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n var t = tips.get();\n if (!t)\n return null;\n if (timeout === undefined)\n timeout = 3000;\n //let p0 = params[0];\n //let timeout = 3000;\n //let templet: (tips: boolean|string|JSX.Element) => JSX.Element;\n /*\n switch (typeof p0) {\n case 'number':\n timeout = p0;\n break;\n case 'function':\n templet = p0;\n let p1 = params[1];\n if (typeof p1 === 'number') {\n timeout = p1;\n }\n break;\n }\n */\n if (timeout > 0) {\n timer = setTimeout(function () {\n tips.set(null);\n }, timeout);\n }\n switch (typeof templet) {\n case 'undefined': return react_1.default.createElement(react_1.default.Fragment, null, t);\n case 'function': return templet(t);\n case 'string': return react_1.default.createElement(react_1.default.Fragment, null, templet);\n default: return templet;\n }\n }));\n}",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(m => {\n m.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public function `nonEmptyArray`. Returns true if `data` is a nonempty array, false otherwise. | function nonEmptyArray (data) {
return array(data) && greater(data.length, 0);
} | [
"function isZeroArray(arr) {\r\n\t\tif (!arr[0] && !arr[1] && !arr[2] && !arr[3]) return true;\r\n\t}",
"function nonEmpty(jqObject) {\n return jqObject && jqObject.length;\n}",
"function IsArrayLike(x) {\r\n return x && typeof x.length == \"number\" && (!x.length || typeof x[0] != \"undefined\");\r\n }",
"function empty( mixed_var ) {\r\n\treturn (mixed_var===\"\"||mixed_var===0||mixed_var===\"0\"||mixed_var===null||mixed_var===false||(is_array(mixed_var)&&mixed_var.length===0)||(mixed_var === undefined));\r\n}",
"function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n }",
"function notempty_ques_(slice0) /* (slice : sslice) -> bool */ {\n return ((len(slice0))>0);\n}",
"function hasData(cell)\n{\n if (cell == null) return 0;\n return cell.length != 0;\n}",
"function isEmpty(value) {\n if (typeof value === 'undefined') {\n return true;\n }\n\n if (value === null) {\n return true;\n }\n\n if ((typeof value === 'string' || value instanceof String) && value.length === 0) {\n return true;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return true;\n }\n\n if (typeof value === 'object' && value.constructor === Object && Object.keys(value).length === 0) {\n return true;\n }\n\n return false;\n }",
"isEmpty() {\n return ((this.front === -1) && (this.rear === -1));\n }",
"function ISARRAY(value) {\n return Object.prototype.toString.call(value) === '[object Array]';\n}",
"static #checkIfObjectIsFound(array) {\n\n\t\t// Check if input is defined.\n\t\tif (!array) {\n\t\t\treturn console.log(`${array} is undefined or null.`)\n\t\t}\n\n\t\treturn array.length !== 0;\n\t}",
"function empty_ques_(slice0) /* (slice : sslice) -> bool */ {\n return !((((len(slice0))>0)));\n}",
"function validator(terms_array) {\n\tfor (var i = 0; i < terms_array.length; i++) {\n\t\tif (isNaN(terms_array[i]) || terms_array[i].length == 0) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function removeEmptyArrays(arr) {\n\treturn arr.filter(x => x.length !== 0)\n}",
"function isEmptyCollection(obj){\n\treturn isCollection(obj) && (\t\t\t\t\t//if it is a non-nullable object AND\n\t\t(Array.isArray(obj) && obj.length == 0) ||\t//it is an empty array, OR\n\t\tjQuery.isEmptyObject(obj)\t\t\t\t\t//it is an empty hashmap\n\t);\n}",
"function ServerBehavior_getIsEmpty()\n{\n if ( (this.parameters && this.parameters.length > 0)\n || (this.applyParameters && this.applyParameters.length > 0)\n )\n {\n return false;\n }\n else\n {\n return true;\n }\n}",
"function isNumericArray(array) {\n var isal = true;\n for (var i = 0; i < array.length; i++) {\n if (!$.isNumeric(array[i])) {\n isal = false;\n }\n }\n return isal;\n }",
"function verifyTeleportDataNotEmpty(data) {\n return !jQuery.isEmptyObject(data._embedded[`city:search-results`]);\n }",
"checkNotesEmpty(notes) {\n for (let i = 0; i < notes.length; i++) {\n if (notes[i]) {\n return false;\n }\n }\n return true;\n }",
"static isArray(input) {\n return input instanceof Array;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Widgets: Combo Box The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it. The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. IMGUI_API bool BeginCombo(const char label, const char preview_value, ImGuiComboFlags flags = 0); | function BeginCombo(label, preview_value = null, flags = 0) {
return bind.BeginCombo(label, preview_value, flags);
} | [
"function combo(){\n for(k in combos){\n // debugger\n if(Object.keys(currentSelection).sort().join() === combos[k][\"keys\"].sort().join()){\n init()\n combos[k].change()\n // debugger\n }\n }\n\n}",
"function _createCombo(data) {\n var retorno = {};\n retorno.comboIds = data;\n retorno.comboNames = data;\n var comboValues = Array();\n\n for (var i = 0; i < data.length; i++) {\n comboValues.push({\n id: data[i],\n name: data[i]\n });\n }\n\n retorno.comboValues = comboValues;\n retorno.dataType = \"string\";\n retorno.disabled = false;\n retorno.label = \"Composer\";\n retorno.name = \"Composer\";\n retorno.selectedId = data[0];\n retorno.type = \"combo\";\n return retorno;\n }",
"incrementCombo() {\n this.combo++;\n this.comboDisplay.setText(\"X\" +this.combo);\n }",
"function createReadonlyValueCombo(store,comboName,fieldLabel,tabIndex,anchor){\r\n\tanchor = anchor || '100%';\r\n\t\t \r\n\tvar combo = new Ext.form.ComboBox({\t\r\n\t\txtype:\"combo\",\t\r\n\t\tfieldLabel: fieldLabel,\t\r\n\t\tname: comboName+\"_display\",\t\t\r\n\t\tstore:store,\r\n\t\tmode: 'local', \r\n\t\teditable:false,\r\n\t\treadonly:true,\r\n\t\tforceSelection: true,\r\n\t\thiddenName:comboName,\t\r\n\t\tvalueField:'value',\t\t\r\n\t\tdisplayField:'value',\t\r\n\t\tanchor: anchor\r\n\t});\r\n\r\n\treturn combo;\r\n}",
"function createReadonlyCombo(store,comboName,fieldLabel,tabIndex,anchor){\r\n\tanchor = anchor || '100%';\r\n\t\t\t \r\n\tvar combo = new Ext.form.ComboBox({\t\r\n\t\txtype:\"combo\",\t\r\n\t\tfieldLabel: fieldLabel,\t\r\n\t\tname: comboName+\"_display\",\t\t\r\n\t\tstore:store,\r\n\t\tmode: 'local', \r\n\t\teditable:false,\r\n\t\treadonly:true,\r\n\t\tforceSelection: true,\r\n\t\thiddenName:comboName,\t\r\n\t\tvalueField:'id',\t\t\r\n\t\tdisplayField:'value',\t\r\n\t\tanchor: anchor\r\n\t});\r\n\r\n\treturn combo;\r\n}",
"function populateCombo(aobjParentCmb,\n aobjChildCmb,aobjHiddenCmb,aarrstrParentCode, aintFlag)\n {\n // dealerBranch - a hidden combo\n comboHidden = eval(aobjHiddenCmb);\n comboChild = eval(aobjChildCmb);\n for(lintI=0; lintI < comboChild.length; lintI++)\n {\n aobjChildCmb.options[lintI] = null;\n lintI = -1;\n }\n //Enter default record\n if(aintFlag == 1) {\n comboChild.options[comboChild.options.length]= new Option(\"Select One...\", \"\");\n } else if(aintFlag == 99) {\n \tcomboChild.options[comboChild.options.length]= new Option(\"\", \"\");\n } else {\n comboChild.options[comboChild.options.length]= new Option(document.AppJsp.allLabel.value, \"\");\n }\n\n for(lintCtr=0; lintCtr < aarrstrParentCode.length; lintCtr++)\n {\n for(lintI=0; lintI < comboHidden.length; lintI++)\n {\n var opt= aobjHiddenCmb[lintI].text;\n var value= aobjHiddenCmb[lintI].value;\n var lintPos = value.indexOf(\"~\");\n if (lintPos > -1) {\n var childCode = value.substring(0, lintPos);\n var parentCode = value.substring(lintPos+1);\n if(parentCode == aarrstrParentCode[lintCtr] || parentCode == '')\n {\n with(aobjChildCmb)\n {\n options[options.length] = new Option(opt, childCode);\n }\n }\n }\n /* else\n {\n if(lintCtr == 0) {\n aobjChildCmb.options[aobjChildCmb.options.length] = new Option();\n }\n }*/\n }\n }\n }",
"resetCombo(){\n if(this.combo > 10)\n this.playFailSound();\n if(this.combo > this.maxCombo)\n this.maxCombo = this.combo;\n this.combo = 0;\n this.comboDisplay.setText(\"X\" +this.combo);\n }",
"function geraComboAnexosSubmetidos()\r\n{\r\n\tvar combo;\r\n\t\r\n\tcombo = populateComboBox('', 'comboAnexosSubmetidos', 'Anexos', anexosSubmetidos, '');\r\n\t\r\n\treturn combo;\r\n}",
"function ShowProviderBarPopup(cmb) {\n Cmb = cmb;\n ProviderSelected = cmb.val() * 1;\n ProviderRenderPopup();\n var dialog = $(\"#dialogProvider\").removeClass(\"hide\").dialog({\n \"resizable\": false,\n \"modal\": true,\n \"title\": \"<h4 class=\\\"smaller\\\">\" + Dictionary.Item_Providers + \"</h4>\",\n \"title_html\": true,\n \"width\": 600,\n \"buttons\": \n [\n {\n \"id\": \"BtnProviderSave\",\n \"html\": \"<i class=\\\"icon-ok bigger-110\\\"></i> \" + Dictionary.Common_Add,\n \"class\": \"btn btn-success btn-xs\",\n \"click\": function () { ProviderInsert(); }\n },\n {\n \"html\": \"<i class=\\\"icon-remove bigger-110\\\"></i> \" + Dictionary.Common_Cancel,\n \"class\": \"btn btn-xs\",\n \"click\": function () { $(this).dialog(\"close\"); }\n }\n ]\n });\n}",
"function coinCombo(cents) {\n return 'TODO'\n}",
"function setCurrencyList(currency, defval) {\r\n var obj = {}\r\n for (var key in currency) {\r\n obj[currency[key]] = null\r\n }\r\n $('#ddcurrlist').material_chip({\r\n placeholder: \"Enter Currency Pair\",\r\n data: defval,\r\n autocompleteLimit: 5,\r\n autocompleteOptions: {\r\n data: obj,\r\n limit: 7,\r\n minLength: 1\r\n }\r\n });\r\n $('.chips').on('chip.add', function(e, chip) {\r\n socket.emit('subscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n subscribeCurrency(chip.tag);\r\n });\r\n\r\n $('.chips').on('chip.delete', function(deleted, chip) {\r\n var tag = chip.tag.replace(\"/\", \"\");\r\n socket.emit('unsubscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n $(\"#\" + tag + \"block\").remove();\r\n if ($('#ddcurrlist').material_chip(\"data\").length== 0) $(\"#norecord\").show()\r\n else $(\"#norecord\").hide() \r\n });\r\n}",
"function populateComboBox(){\r\n $('#select-matchday').empty();\r\n $('#select-matchday-map').empty();\r\n i = 1;\r\n while(i <= 38){\r\n var currentMatchdayString = i;\r\n if (i == storage.currentMatchday) {\r\n currentMatchdayString = i + ' (current)' \r\n }\r\n var optionText = '<option value='+ i + '>' + currentMatchdayString +'</option>'\r\n $('#select-matchday').append(optionText);\r\n $('#select-matchday-map').append(optionText);\r\n i++;\r\n };\r\n $(\"#select-matchday\").val(storage.currentMatchdayView).change();\r\n $(\"#select-matchday-map\").val(storage.currentMatchdayView).change();\r\n}",
"function AddItem(Text, Value, control) {\n // Create an Option object \n var opt = document.createElement(\"option\");\n var obj = document.getElementById(control); // Drop Down control object\n\n // Assign text and value to Option object\n opt.text = Text;\n opt.value = Value;\n \n // Add an Option object to Drop Down/List Box\n obj.options.add(opt);\n \n\n obj.selectedIndex = obj.options.length - 1; // focusing again to new value added in drop down control\n obj.options[obj.options.length - 1].selected=true;\n obj.value=Value;\n \n //$(obj).addClass(\"focus\");\n \n}",
"function cargaCombo(nombreCombo, variableOculta ){\n\t\t\t\tvar nuevosValores = new Array();\n\t\t\t\tvar seleccion = new Array();\n\t\n\t\t\t\tcombo = form + nombreCombo;\n\t\t\t\tvar valores = get(form + variableOculta);\n\t\t\t\t\t//alert(variableOculta + \": \" + valores);\n\t\t\t\tif( valores == '' ){\n\t\t\t\t\tset(form + nombreCombo, '');\n//\t\t\t\t\tdeshabilitar(nombreCombo);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tvar valoresSeparados = valores.split('|');\n//\t\t\t\tif( variableOculta == 'tipoDespacho' )\n//\t\t\t\t\talert(\"ValoresSeparados: \" + valoresSeparados);\n\t\t\t\tfor(i=0, j=0; i < valoresSeparados.length; i++){\n\t\t\t\t\tif( valoresSeparados[i] != '' ){\n\t\t\t\t\t\tseleccion[j] = valoresSeparados[i];\n\t\t\t\t\t\tj++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(seleccion.length > 0){\n\t\t\t\t\tset(combo, seleccion);\n\t\t\t\t}\n\t\t\t}",
"function populateCombo() {\n\tvar strDay = '';\n\tfor (var a=0; a<365; a++) {\n\t\tif (!a) {\n\t\t\tstrDay += \"<option value='dd'>dd</option>\";\n\t\t} else {\n\t\t\tstrDay += \"<option value='\"+a+\"'>\"+a+\"</option>\";\n\t\t}\n\t}\n\t$('#durationD').empty().append(strDay);\n\n\tvar strHour = '';\n\tfor (var a=0; a<24; a++) {\n\t\tif (!a) {\n\t\t\tstrHour += \"<option value='hh'>hh</option>\";\n\t\t}else if(a == 2){\n\t\t\tstrHour += \"<option value='\"+a+\"' selected>\"+a+\"</option>\";\n\n\t\t} else {\n\t\t\tstrHour += \"<option value='\"+a+\"'>\"+a+\"</option>\";\n\t\t}\n\t}\n\t$('#durationH').empty().append(strHour);\n\n\tvar strMin = '';\n\tfor (var a=0; a<60; a++) {\n\t\tif (!a) {\n\t\t\tstrMin += \"<option value='mm'>mm</option>\";\n\t\t} else {\n\t\t\tstrMin += \"<option value='\"+a+\"'>\"+a+\"</option>\";\n\t\t}\n\t}\n\t$('#durationM').empty().append(strMin);\n\n}",
"requestContentUpdate() {\n if (!this.renderer) {\n return;\n }\n\n const model = {\n index: this.index,\n item: this.item,\n focused: this.focused,\n selected: this.selected\n };\n\n this.renderer(this, this._comboBox, model);\n }",
"function seleccionarUG(combo){\n //var combo=window.event.srcElement;\n //alert('Combo seleccionado ' + combo);\n //combo.name //nombre combo\n //combo.value //devuelve ultimo oid del combo seleccion\n //guardar en un hidden hUltimoOidUG\n //if ( get( 'frmDatos.comboUnidad1', 'T' ) == '' ){\n\t\tif (combo == 0) {\n //alert(\"combo 1\");\n deshabilitarResto(1);\n\t\t cargarCombo1();\n }else \n\t\tif (combo == 1) {\n deshabilitarResto(2);\n if ( get( 'frmDatos.comboUnidad1', 'T' ) != '' ) \n\t\t\t cargarCombo2();\n\t\t else\n\t\t\t comboUnidad2.disabled = true;\n }else \n\t\tif (combo == 2) {\n deshabilitarResto(3);\n\t\t\tif ( get( 'frmDatos.comboUnidad2', 'T' ) != '' )\n\t\t\t\tcargarCombo3();\n\t\t\telse\n\t\t\t comboUnidad3.disabled = true;\n }\n else \n\n\t\tif (combo == 3) {\n deshabilitarResto(4);\n if ( get( 'frmDatos.comboUnidad3', 'T' ) != '' ) \n\t\t\t cargarCombo4();\n\t\t else\n\t\t\t comboUnidad4.disabled = true;\n }\n else \n\n\t\tif (combo == 4) {\n\n deshabilitarResto(5);\n if ( get( 'frmDatos.comboUnidad4', 'T' ) != '' ) \n\t\t\t cargarCombo5();\n\t\t else\n\t\t\t comboUnidad5.disabled = true;\n }\n else \n\n\t\tif (combo == 5) {\n\n deshabilitarResto(6);\n if ( get( 'frmDatos.comboUnidad5', 'T' ) != '' ) \n\t\t\t cargarCombo6();\n\t\t else\n\t\t\t comboUnidad6.disabled = true;\n\n }\n else \n\n\t\tif (combo == 6) {\n\n deshabilitarResto(7);\n if ( get( 'frmDatos.comboUnidad6', 'T' ) != '' ) \n\t\t\t cargarCombo7();\n\t\t else\n\t\t\t comboUnidad7.disabled = true;\n\n }\n else \n\n\t\tif (combo == 7) {\n\n deshabilitarResto(8);\n if ( get( 'frmDatos.comboUnidad7', 'T' ) != '' ) \n\t\t\t cargarCombo8();\n\t\t else\n\t\t\t comboUnidad8.disabled = true;\n }\n else \n\n\t\tif (combo == 8) {\n\n deshabilitarResto(9);\n if ( get( 'frmDatos.comboUnidad8', 'T' ) != '' ) \n\t\t\t cargarCombo9();\n\t\t else\n\t\t\t comboUnidad9.disabled = true;\n\n }\n\n}",
"function FillVersionCombo(){\n var objVersionsCombo= document.getElementById(\"ddlWfVersions\");\n \n //Empty version combo.\n for (var i = objVersionsCombo.options.length; i >=0; i--){\n objVersionsCombo.options[i] = null; \n }\n \n\n //Fill version combo:\n //The \"HidWfVersions\" hidden field contains a string with all workflows (idWfClass, idWorkflow, wfVersion) separated by the '|' char.\n //Include in combo only those wfs which have idWfClass equal to current WFClass combo selection\n var curIdWfClass= document.getElementById(\"ddlWorkflows\").value; //WFClass combo\n var sAllWorkflows = document.getElementById(\"HidWfVersions\").value; \n \n var arrWorkflows= sAllWorkflows.split(\"|\");\n for(var i= 0; i<arrWorkflows.length; ++i){\n var arrOneWorkflow = arrWorkflows[i].split(\",\");\n var idWfClass = arrOneWorkflow[0];\n var idWorkflow = arrOneWorkflow[1];\n var wfVersion = arrOneWorkflow[2];\n \n if(idWfClass == curIdWfClass){ \n objVersionsCombo.options[objVersionsCombo.options.length] = new Option(wfVersion, idWorkflow); \n }\n }\n ApplySelectmenuPlugin();\n}",
"function newBOListContainerWidget(id,w,h,image,layout,changeCB,dblClickCB,moveCB,deleteCB,noText,focusCB,addQuickFilterCB,help)\n// CONSTRUCTOR\n// id [String] the id for DHTML processing\n// w [int] widget width, including borders\n// h [int] widget height, including borders\n// changeCB [function] callback when selecting items\n// dblClickCB [function] callback when double clicking on items\n// moveCB [function] callback a node is moved from the container buttons up & down\n// parameters elem,node,idx. return false if all move performed by function\n// noText [boolean] display buttons with no text if true\n// deleteCB [function] callback when delete key pressed\n// focusCB [function] callback when key pressed on the widget\n// Return [AndOrBOListWidget] the instance\n{\n\tvar o=newWidget(id),v=layout==_vertBOList,l=null\n\t\n\to.w=w\n\to.h=h\n\to.andOrList=newBOListWidget(\"andOrList_\"+id,Math.max(0,w-18),h,image,layout,changeCB,dblClickCB,moveCB,deleteCB,focusCB,help)\n\t\n\to.noText=noText?noText:false\n\t\n\tl=(v?_lstMoveUpLab:_lstMoveLeftLab)\n\to.up=newButtonWidget(\"andOrList_up_\"+id,noText?null:l,AndOrContainerWidget_upDownCb,null,null,noText?l:null,null,null,_skin+'buttonIcons.gif',16,16,0,v?64:32,null,16,v?64:32)\n\tl=(v?_lstMoveDownLab:_lstMoveRightLab)\n\to.down=newButtonWidget(\"andOrList_down_\"+id,noText?null:l,AndOrContainerWidget_upDownCb,null,null,noText?l:null,null,null,_skin+'buttonIcons.gif',16,16,0,v?80:48,null,16,v?80:48)\n\to.up.lst=o\n\to.up.isUp=true\n\to.down.lst=o\n\to.down.isUp=false\n\to.down.extraStyle=o.up.extraStyle=\"margin-top:2px;\"\n\t\t\n\tif(addQuickFilterCB)\n\t{\n\t\tl=_lstQuickFilterLab\n\t\to.quickFilter=newButtonWidget(\"andOrList_quickFilter_\"+id,noText?null:l,addQuickFilterCB,null,null,noText?l:null,null,null,_skin+'buttonIcons.gif',16,16,0,160,null,16,160)\n\t\to.quickFilter.lst=o\n\t\to.quickFilter.extraStyle=\"margin-top:2px;\"\n\t}\t\n\to.getList=AndOrContainerWidget_getList\n\to.getHTML=AndOrContainerWidget_getHTML\n\to.oldResize=o.resize\n\to.resize=AndOrContainerWidget_resize\n\to.moveElem=AndOrContainerWidget_moveElem\n\to.prvInit=o.init\n\to.init=AndOrContainerWidget_init\n\to.chgLayout=BOListContainerWidget_chgLayout\n\treturn o\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable type submit elements for current form | disableSubmitInputs() {
this.jqueryForm.find('[type=submit]').each(function () {
$(this).prop('disabled', true);
});
} | [
"function disableAgencySubmit(disable) {\n $('#agencySubmit').attr('disabled', disable);\n}",
"function enableFieldsForSubmit(theform) {\r\n var elems = theform.elements;\r\n\r\n for (var i = 0; i < elems.length; i++) {\r\n if (elems[i].disabled) {\r\n elems[i].style.visibility = \"hidden\";\r\n elems[i].disabled = false;\r\n }\r\n }\r\n}",
"function disableAttendeeSubmit(disable) {\n $('#attendeeSubmit').attr('disabled', disable);\n}",
"function disableEditing() {\n disableForm(true);\n}",
"function disableAttendeeHourSubmit(disable) {\n $('#attendeeHourSubmit').attr('disabled', disable);\n}",
"function formDoNothing() {\n}",
"function submitOnClick (objSubmitBtn) {\n objSubmitBtn.disabled = true;\n objSubmitBtn.value = 'Adding...';\n saveMembers();\n}",
"function disable_button() {\n allow_add = false;\n}",
"function Enable_Place_Forms(){\n $(\".place\").removeAttr('disabled');\n}",
"function btnDisable() {\n // add disable attribute to the add button \n $(\"#add-topic-btn\").attr('disabled', true);\n $('input').keyup(function () {\n var disable = false;\n $('input:text').each(function () {\n if (userInput.val() == \"\") {\n disable = true;\n }\n });\n $('#add-topic-btn').prop('disabled', disable);\n });\n }",
"function disableAllButtons() {\n disableOrEnableButtons(false);\n }",
"function disableControls() {\n $(\"button.play\").attr('disabled', true);\n $(\"select\").attr('disabled', true);\n $(\"button.stop\").attr('disabled', false);\n }",
"handleSubmit(e) {\n e.preventDefault();\n \n this.handleClick();\n }",
"function buttondeact()\n{\n\tfor(i=0;i<document.all.btn.length;i++)\n\t{document.all.btn[i].disabled = true;}\n}",
"function enableDisableRegisterBtn(frmElementDivId, submitBtnId){\n\tvar buttonStatusEnabled = true;\n\tvar $inputFields = $('#' + frmElementDivId + ' :input');\n\t$inputFields.each(function() {\n\t\tvar inputType = $(this).attr('type');\n\t\tvar inputId= $(this).attr('id');\n\t\tif(inputId != 'promoCodeDiscount1'){\n\t\t\tif(inputType && inputType != 'checkbox') {\n\t\t\t\tif($(this).hasClass('error_red_border') || !$(this).val()) {\n\t\t\t\t\tbuttonStatusEnabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\tif(buttonStatusEnabled) {\n\t\tsubmitBtnEnableUI(submitBtnId);\n\t} else {\n\t\tsubmitBtnDisableUI(submitBtnId);\n\t}\n}",
"function blockTheMainButtons() {\n buttons.forEach((button) => {\n button.classList.add('disable');\n });\n}",
"function handleFormSubmit(evt) {\n const form = evt.currentTarget;\n const fileInput = form.elements.namedItem('file');\n if (fileInput.hidden) {\n fileInput.value = '';\n }\n }",
"function disableEnterButton()\n{\n\t$('html').on('keypress', function(e)\n\t{\n\t\tif (e.keyCode == 13)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t});\n}",
"function disable_button_ask_hint(){\n $('#button_ask_hint').attr('disabled', true);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Advance the L system any number of generations | advanceGenerations(numGenerations) {
for(let i = 0; i < numGenerations; i++) {
this.nextGeneration();
}
} | [
"learn(steps){\n steps = Math.max(1, steps || 0)\n while (steps--){\n this.currentState = this.randomState()\n this.step()\n }\n }",
"function runBatch() {\n if (visitationFn === \"deterministic\") {\n for (let y = 0; y < gridSize; y++) {\n for (let x = 0; x < gridSize; x++) {\n updateSpin(x, y);\n }\n }\n }\n else if (visitationFn === \"random\") {\n for (let i = 0; i < N; i++) {\n let x = Math.floor(Math.random() * gridSize);\n let y = Math.floor(Math.random() * gridSize);\n updateSpin(x, y);\n }\n }\n drawLattice();\n}",
"levelMaker(floorCount, offsetArray, widthArray)\n { \n //Formula: firstPlat.XPos + firstPlat.width / 2 + 21 + secondPlat.width / 2 = secondPlat.XPos\n //Each floor is offset by 760 - 100 * floor number.\n let storeyHeight = 140;\n let floorY = 790;\n for(let i = 1; i <= floorCount; i++)\n {\n let floorPlans = widthArray[i - 1];\n let lastXPos = offsetArray[i - 1] + floorPlans[0] / 2;\n this.addPlatformConfiguration(lastXPos, floorY - storeyHeight * i, i, false, true, floorPlans[0] - this.PlatformOffset);\n for(let j = 1; j < floorPlans.length; j++)\n {\n //The ladder's position is determined from the gaps left in the floor.\n //Place the ladder 25 + firstPlat.XPos + firstPlat.width in x...\n //and 50 below the current floor's yPos. (in js, + 50)\n this.addLadderConfiguration(10 + lastXPos + floorPlans[j - 1] / 2, floorY - storeyHeight * i + 65, i - 1,j);\n\n lastXPos = lastXPos + floorPlans[j-1] / 2 + this.ladderWidth + floorPlans[j] / 2;\n this.addPlatformConfiguration(lastXPos, floorY - storeyHeight * i, i, false, true, floorPlans[j] - this.PlatformOffset);\n }\n }\n }",
"moveAnts(step)\n {\n let j;\n for(j = 0; j < step; j++)\n {\n let i;\n // For each ant\n for(i = this.ants.length - 1; i >= 0; i--)\n {\n if(this.ants[i].isAlive() || this.infiniteLifeTimeEnabled)\n {\n this.ants[i].move({\n shiftX: this.shiftX,\n shiftY: this.shiftY,\n width: this.sizeRectX,\n height: this.sizeRectY,\n nbRectX: this.map.width,\n nbRectY: this.map.height\n });\n }\n else\n {\n this.ants.splice(i, 1);\n }\n }\n\n this.antsStep += 1;\n\n document.getElementById(\"antsStep\").innerHTML = this.antsStep;\n document.getElementById(\"antsNb\").innerHTML = this.ants.length;\n }\n }",
"spawnMore(){\n this.hitPoints =0;\n for(let i=0; i<levelData.sections+1; i++)\n this.spawnOne(i);\n }",
"function increaseStepCount() {\n lx.stepCount++;\n }",
"function levelUpLeech(){\n if(protein >= upgradeLeechCost)\n {\n protein -= upgradeLeechCost;\n levelLeech += 1;\n\n performCalculations();\n updateLabels();\n }\n}",
"generateSticks() {\n let numberOfSticks = Math.ceil(this.steps);\n for(let i = 0; i <= numberOfSticks; i++)\n new Stick();\n }",
"function generate_level() {\r\n startposx = randomNbr(1, 12)\r\n startposy = randomNbr(1, 11)\r\n let endposx = randomNbr(startposx + 1, 13)\r\n let endposy = randomNbr(1, 11)\r\n let posX_table = [startposx, endposx]\r\n let posY_table = [startposy, endposy]\r\n\r\n //save new position for x,y\r\n function incrementposX(x, y) {\r\n if (x < endposx) {\r\n x++;\r\n posX_table.unshift(x)\r\n posY_table.unshift(y)\r\n // console.log('incremented x', x);\r\n } else {\r\n x--;\r\n posX_table.unshift(x)\r\n posY_table.unshift(y)\r\n // console.log('decremented x', x);\r\n }\r\n }\r\n \r\n //save new position for y,x\r\n function incrementposY(x, y) {\r\n if (y < endposy) {\r\n y++;\r\n posY_table.unshift(y)\r\n posX_table.unshift(x)\r\n // console.log('incremented y', y);\r\n } else {\r\n y--;\r\n posY_table.unshift(y)\r\n posX_table.unshift(x)\r\n // console.log('decremented y', y);\r\n }\r\n }\r\n\r\n //bit of math to calculate maximum amount of moves possible, so that random path generator won't be stuck by wall\r\n let dist = (endposx - startposx) + (Math.abs((endposy - startposy))) + Math.abs((endposx + endposy) - (startposx + startposy))\r\n console.log('this is dist', dist);\r\n\r\n //generates solution path based on distances using both posX and posY tables, and will randomly increment x or y \r\n for (i = 0; i <= (dist); i++) {\r\n if (posX_table[0] != endposx && posY_table[0] != endposy) {\r\n let rand = Math.floor(Math.random() * 2)\r\n if (rand < 1) {\r\n incrementposX(posX_table[0], posY_table[0])\r\n } else {\r\n incrementposY(posX_table[0], posY_table[0])\r\n }\r\n } else if (posX_table[0] != endposx) {\r\n incrementposX(posX_table[0], posY_table[0])\r\n } else if (posY_table[0] != endposy) {\r\n incrementposY(posX_table[0], posY_table[0])\r\n } else {\r\n i = dist;\r\n }\r\n //console.log('i =', i)\r\n }\r\n\r\n //generates random walls or paths for reste of map (excluding solution)\r\n let arr = [];\r\n for (i = 0; i < 143; i++) {\r\n // console.log('path Normal at ' + i);\r\n let random = randomNbr(1,3);\r\n random < 2 ? arr.push('*') : arr.push('.');\r\n }\r\n for (y = 0; y < posX_table.length; y++) {\r\n if (y == posX_table.length - 2) {\r\n let res = posX_table[y] + ((posY_table[y] * 13) - 13)\r\n arr.splice(res - 1, 1, 'S')\r\n } else if (y == posX_table.length - 1) {\r\n let res = posX_table[y] + ((posY_table[y] * 13) - 13)\r\n arr.splice(res - 1, 1, 'T')\r\n } else {\r\n let res = posX_table[y] + ((posY_table[y] * 13) - 13)\r\n console.table(posX_table[y], posY_table[y], res)\r\n arr.splice(res - 1, 1, '.')\r\n }\r\n }\r\n \r\n //converts array to proper string with spaces so load_level() can interpret it\r\n let arr_splitter_counter = 0\r\n const multi_arr = [];\r\n for (elem of arr) {\r\n arr_splitter_counter < 13 ? multi_arr.push(elem) + arr_splitter_counter++ : multi_arr.push('\\n', elem) + (arr_splitter_counter = 1);\r\n }\r\n const final_arr = multi_arr.join(\"\");\r\n return final_arr;\r\n}",
"function initCodeOfStep(sO) {\r\n\r\n var fO = CurFuncObj;\r\n\r\n // if we have alredy intialized code of the setp, nothing to do.\r\n //\r\n if (sO.boxExprs.length)\r\n return;\r\n\r\n var gId = sO.allGridIds[0];\r\n var gO = fO.allGrids[gId]; // gO = output grid object\r\n\r\n var ind = \"\";\r\n var numind = 0;\r\n\r\n // 3 bins are used for range/mask/formula. Push null expressions for those\r\n //\r\n sO.boxExprs.push(null); // index (grid obj index editing)\r\n sO.boxExprs.push(null); // range\r\n sO.boxExprs.push(null); // mask\r\n sO.boxExprs.push(null); // formula\r\n\r\n sO.boxAttribs.push(new BoxAttribs(0, CodeBoxId.Index)); // index editing \r\n sO.boxAttribs.push(new BoxAttribs(0, CodeBoxId.Range)); // range\r\n sO.boxAttribs.push(new BoxAttribs(1, CodeBoxId.Mask)); // mask\r\n sO.boxAttribs.push(new BoxAttribs(2, CodeBoxId.Formula)); \r\n\r\n\r\n // Foreach root expression. We add this for ALL grids -- even for \r\n // scalars. If the index expressions are not added, the keyword\r\n // \"foreach\" is not displayed.\r\n //\r\n sO.boxExprs[CodeBoxId.Range] =\r\n new ExprObj(false, ExprType.Foreach, \"foreach\");\r\n\r\n if (gO.numDims > 0) { // if output gO is not a simple scalar\r\n\r\n\r\n\r\n // Create the main 'foreach' root expression \r\n //\t\r\n // Create shortcut name \r\n //\r\n var rangeExpr = sO.boxExprs[CodeBoxId.Range];\r\n\r\n for (var d = 0; d < gO.numDims; d++) {\r\n\r\n if (!gO.dimHasTitles[d]) {\r\n\r\n // create a new sub expression (range) for each range\r\n // -- i.e., new range for dim with default output grid \r\n //\r\n var gO = fO.allGrids[sO.allGridIds[0]];\r\n var rangeChild = newRangeExpr(sO, d, gO);\r\n //\r\n // add it to the rangeExpr of the step\r\n //\r\n rangeExpr.addSubExpr(rangeChild);\r\n }\r\n }\r\n }\r\n\r\n // STEP:\r\n // (1) Create default 'if' statement. A standalone if is displayed only if\r\n // the mask box has focs\r\n // (2) Create the default expression statement for a formula\r\n //\r\n sO.boxExprs[CodeBoxId.Mask] = new ExprObj(false, ExprType.If, \"if\");\r\n sO.boxExprs[CodeBoxId.Formula] = new ExprObj(false, ExprType.ExprStmt,\r\n \"\");\r\n\r\n setFocusToDefaultBox();\r\n\r\n}",
"buildIncrementalRoleLinks(rm, op, sec, ptype, rules) {\n var _a, _b;\n return __awaiter(this, void 0, void 0, function* () {\n if (sec === 'g') {\n yield ((_b = (_a = this.model\n .get(sec)) === null || _a === void 0 ? void 0 : _a.get(ptype)) === null || _b === void 0 ? void 0 : _b.buildIncrementalRoleLinks(rm, op, rules));\n }\n });\n }",
"GenerateBoardTiles() { for(let iterator = 0; iterator < this.number_of_riverbank_instances; iterator++) { this.GenerateTile(false); this.GenerateTile(true);} }",
"function LUDecomp(k) {\n\t\t// Assuming k is square matrix in Yale format\n\t\t// k = [A,IA,JA]\n\t\t// U =k;\n\t\tvar N = k[1].length-1;\n\t\t/**var U_A = k[0];\n\t\tvar U_IA = k[1];\n\t\tvar U_JA = k[2];**/\n\t\tvar upper = k;\n\t\t//alert(\"N = \"+N);\n\t\t//set first 1 in place\n\t\tvar L_A = new Array();\n\t\tvar L_IA = new Array(N+1);\n\t\tL_IA[N]=0;\n\t\tvar L_JA = new Array();\n\t\tvar lower = [L_A,L_IA,L_JA];\n\t\t/**var n = 0; \n\t\twhile(n < N){\n\t\t\t// Insert ones along the diagonal in L_A \n\t\t\t// L_IA to be formed later\n\t\t\t\n\t\t}**/\n\t\t// Do decomposition\n\t\tfor(var j=0; j<N; j++){\n\t\t\t\n\t\t\tlower = yaleInsert(lower, 1, j, j);\n\t\t\tfor(var i=(j+1);i<N; i++){\n\t\t\t\t\n\t\t\t\t\tvar U_ij = yaleGet(upper,i,j);\n\t\t\t\t\tif(U_ij!=0){\n\t\t\t\t\t\t// L[i][j] = U[i][j] / U[j][j];\n\t\t\t\t\t\tvar U_jj = yaleGet(upper,j,j);\n\t\t\t\t\t\t//alert(\"denominator = \"+xD);\n\t\t\t\t\t\tvar L_ij=U_ij/U_jj;\n\t\t\t\t\t\tlower = yaleInsert(lower, L_ij, i, j);\n\t\t\t\t\t\t//alert(\"made it\"+lower[0]);\n\t\t\t\t\t\tfor(var z=j; z<N; z++){\n\t\t\t\t\t\t\t//U[i][z] = U[i][z]-L[i][j]*U[j][z];\n\t\t\t\t\t\t\t//alert(\"z = \"+z);\n\t\t\t\t\t\t\tvar U_iz=yaleGet(upper,i,z);\n\t\t\t\t\t\t\t//alert(\"U_iz = \"+U_iz);\n\t\t\t\t\t\t\tvar U_jz = yaleGet(upper,j,z);\n\t\t\t\t\t\t\t//alert(\"U_jz = \"+U_jz);\n\t\t\t\t\t\t\tU_iz-=L_ij*U_jz;\n\t\t\t\t\t\t\t//alert(\"new U_iz = \"+U_iz);\n\t\t\t\t\t\t\tupper = yaleInsert(upper,U_iz, i, z);\t\n\t\t\t\t\t\t}\t\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t\t/** // Do decomposition\n\t\t\tfor(var j=0; j<(N-1); j++){\n\t\t\t\tfor(var i=(j+1);i<N; i++){\n\t\t\t\t\tif(U[i][j] != 0){\n\t\t\t\t\t\tL[i][j] = U[i][j] / U[j][j];\n\t\t\t\t\t\tfor(var z=j; z<N; z++){\n\t\t\t\t\t\t\tU[i][z] = U[i][z]-L[i][j]*U[j][z];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{ L[i][j]=0;}\n\t\t\t\t}\n\t\t\t} **/\n\t\t//L & U should be done\n\t\t// create an object to return upper and lower matrices\n\t\t\tvar ULpair = new Object();\n\t\t\t\n\t\t\tvar L = lower;\n\t\t\tvar U = upper;\n\t\t\t//alert(\"end U_A = \"+U_A);\n\t\t\t//alert(\"end U_IA = \"+U_IA);\n\t\t\t//alert(\"end U_JA = \"+U_JA);\n\t\t\tULpair.L = L;\n\t\t\tULpair.U = U;\n\t\t\treturn ULpair;\n\t\t\n\t}",
"async getNextGeneration() {\n const {i, nextGen} = await this.fetchNextGeneration();\n canvasScript.displayNewGeneration(i, nextGen);\n }",
"linearRockGenerator(collisionGroup, lvlArray, orbNumber, orbStartPosition, orbPositionY, interval) {\n\t\tvar orbSpawnPosition = orbStartPosition;\n\t\tvar loopLimit = lvlArray.length+orbNumber;\n\n\t\tfor (var i = lvlArray.length; i < loopLimit; i++) {\n\t\t\tlvlArray.push(new Rock(this.game, orbSpawnPosition, orbPositionY, 1, collisionGroup));\n\t\t\torbSpawnPosition+=interval;\n\t\t}\n\n\t\treturn lvlArray;\n\t}",
"function generateGameLoop() {\n \t\treturn setInterval(function() {\n \t\t\tgameState = gameTick(gameState);\n \t\t\tcurrentGameView = paintGameView(gameState, currentGameView);\n \t\t\tupdateGenerationCounter();\n \t\t}, speed);\n \t}",
"iterate() {\n var i;\n var link_id;\n var exp_id;\n var link_from, link_to;\n var link;\n var lx, ly, df;\n\n\n for (i = 0; i < this.EXP_LOOPS; i++) {\n for (exp_id = 0; exp_id < this.experiences.length; exp_id++) {\n link_from = this.experiences[exp_id];\n\n for (link_id = 0; link_id < link_from.links_from.length; link_id++) {\n //% //% experience 0 has a link to experience 1\n link = this.links[link_from.links_from[link_id]];\n link_to = this.experiences[link.exp_to_id];\n\n //% //% work out where e0 thinks e1 (x,y) should be based on the stored\n //% //% link information\n lx = link_from.x_m + link.d * Math.cos(link_from.th_rad + link.heading_rad);\n ly = link_from.y_m + link.d * Math.sin(link_from.th_rad + link.heading_rad);\n\n //% //% correct e0 and e1 (x,y) by equal but opposite amounts\n //% //% a 0.5 correction parameter means that e0 and e1 will be fully\n //% //% corrected based on e0's link information\n link_from.x_m += (link_to.x_m - lx) * this.EXP_CORRECTION;\n link_from.y_m += (link_to.y_m - ly) * this.EXP_CORRECTION;\n link_to.x_m -= (link_to.x_m - lx) * this.EXP_CORRECTION;\n link_to.y_m -= (link_to.y_m - ly) * this.EXP_CORRECTION;\n\n //% //% determine the angle between where e0 thinks e1's facing\n //% //% should be based on the link information\n df = gri.get_signed_delta_rad(link_from.th_rad + link.facing_rad, link_to.th_rad);\n\n //% //% correct e0 and e1 facing by equal but opposite amounts\n //% //% a 0.5 correction parameter means that e0 and e1 will be fully\n //% //% corrected based on e0's link information\n link_from.th_rad = gri.clip_rad_180(link_from.th_rad + df * this.EXP_CORRECTION);\n link_to.th_rad = gri.clip_rad_180(link_to.th_rad - df * this.EXP_CORRECTION);\n }\n }\n }\n\n return true;\n }",
"function addHealth(N : int)\n{\n if (currentHealth + N > maxHealth)\n {\n N = maxHealth - currentHealth;\n }\n for (var i : int = 0; i < N; i++)\n {\n Invoke(\"incrementHealth\", multipleSpeed*i);\n }\n}",
"function transitionSequence() {\r\n let interval = setInterval(() => {\r\n while (tranGen.done !== true) {\r\n tranGen.next()\r\n return\r\n }\r\n clearInterval(interval)\r\n }, 500)\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a permission item object using its ID. | static get(permissionItemId){
let kparams = {};
kparams.permissionItemId = permissionItemId;
return new kaltura.RequestBuilder('permissionitem', 'get', kparams);
} | [
"getPermission(permissionId, region) {\n if (typeof permissionId !== 'string') {\n return this.promise.reject('permissionId must be a string');\n }\n return this.getPermissions([permissionId], region).then((permissions) =>\n permissions.find((permission) => permission.id === permissionId)\n );\n }",
"findItem(id) {\n if (this.manifest && id) {\n return this.manifest.items.find((item) => {\n if (item.id !== id) {\n return false;\n }\n return true;\n });\n }\n return null;\n }",
"function getItemInfo(id) {\n if (id in item)\n return item[id]\n else\n throw new Error (\"No item with id \" + id)\n }",
"getPermissionFromRole (roleId, action) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n assert.equal(typeof action, 'string', 'action must be string')\n return this._apiRequest(`/role/${roleId}/permission/${action}`)\n }",
"static getMenuItem(id) {\n return menuItemById[id];\n }",
"getById(id) {\n // verify required parameter 'id' is not null or undefined\n if (id === null || id === undefined) {\n throw new Error('Required parameter id was null or undefined when calling getById.');\n }\n let queryParameters = {};\n if (id !== undefined)\n queryParameters['id'] = id;\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('GET', '/api/user/v1/account/get-by-id', queryParameters, headerParams, formParams, isFile, false, undefined);\n }",
"function findCanById(id) {\n return db('cans').where({ id }).first()\n}",
"function get_member(id){\n return guild.member(id);\n}",
"static deleteAction(permissionItemId){\n\t\tlet kparams = {};\n\t\tkparams.permissionItemId = permissionItemId;\n\t\treturn new kaltura.RequestBuilder('permissionitem', 'delete', kparams);\n\t}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'get', kparams);\n\t}",
"function extractItem(items, id) {\n for (var i = 0; i < items.length; i++)\n if (items[i].id == id)\n return items.splice(i, 1)[0];\n }",
"static get(name, id, state, opts) {\n return new SigningProfilePermission(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"async function getQItem() {\n const bearer = await helpers.getBearerToken();\n const item = await helpers.getItem(itemUrl, bearer);\n return item;\n}",
"function getAlbum (id) {\n return $http({\n url: 'local.json',\n method: 'GET'\n }).then(function(response) {\n return _.find(response.data, {'id': parseInt(id, 10)});\n });\n }",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('category', 'get', kparams);\n\t}",
"getById(id) {\n return this._openDialogs.find(ref => ref.id === id);\n }",
"getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }",
"function get(id) {\n return axios.get(MATERIALS_API + \"/\" + id).then(response => response.data)\n}",
"getById(id) {\n return ContentType(this).concat(`('${id}')`);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
populates the form with a list of supported clients and when selected with appointments. parameters from the form are used to create a appointment meeting. | function openClientMeetingForm() {
document.getElementById("ClientMeetingForm").style.display = "block";
//populate list of clients.
populateClientList("clientAtMeeting");
} | [
"function addClient() {\n s = \"<form name='addClient'>\";\n s += \"<div class='cell'>*Codice Fiscale</div><div class='cell' text-align=left><input type=text name=cf size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Nome </div><div class='cell' text-align=left><input type=text name=nome size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Cognome</div><div class='cell' text-align=left><input type=text name=cognome size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Indirizzo, numero civico</div><div class='cell' text-align=left><input type=text name=indirizzo size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Cellulare</div><div class='cell' text-align=left><input type=text name=telefono size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Città</div><div class='cell' text-align=left><input type=text name=citta size=30></div>\";\n s += \"<div class='row'></div>\";\n s += \"<div class='cell'>*Provincia</div><div class='cell' text-align=left><select name=provincia><option value=null>---</option>\";\n s += \"<option value=AG>AGRIGENTO</option><option value=AL>ALESSANDRIA</option><option value=AN>ANCONA</option><option value=AO>AOSTA</option><option value=AR>AREZZO</option><option value=AP>ASCOLI PICENO</option><option value=AT>ASTI</option><option value=AV>AVELLINO</option><option value=BA>BARI</option><option value=BL>BELLUNO</option><option value=BN>BENEVENTO</option><option value=BG>BERGAMO</option><option value=BI>BIELLA</option><option value=BO>BOLOGNA</option><option value=BZ>BOLZANO</option><option value=BS>BRESCIA</option><option value=BR>BRINDISI</option><option value=CA>CAGLIARI</option><option value=CL>CALTANISSETTA</option><option value=CB>CAMPOBASSO</option><option value=CE>CASERTA</option><option value=CT>CATANIA</option><option value=CZ>CATANZARO</option><option value=CH>CHIETI</option><option value=CO>COMO</option><option value=CS>COSENZA</option><option value=CR>CREMONA</option><option value=KR>CROTONE</option><option value=CN>CUNEO</option><option value=EN>ENNA</option><option value=FE>FERRARA</option><option value=FI>FIRENZE</option><option value=FG>FOGGIA</option><option value=FC>FORLI-CESENA</option><option value=FR>FROSINONE</option><option value=GE>GENOVA</option><option value=GO>GORIZIA</option><option value=GR>GROSSETO</option><option value=IM>IMPERIA</option><option value=IS>ISERNIA</option><option value=SP>LA SPEZIA</option><option value=AQ>AQUILA</option><option value=LT>LATINA</option><option value=LE>LECCE</option><option value=LC>LECCO</option><option value=LI>LIVORNO</option><option value=LO>LODI</option><option value=LU>LUCCA</option><option value=MC>MACERATA</option><option value=MN>MANTOVA</option><option value=MS>MASSA-CARRARA</option><option value=MT>MATERA</option><option value=ME>MESSINA</option><option value=MI>MILANO</option><option value=MO>MODENA</option><option value=NA>NAPOLI</option><option value=NO>NOVARA</option><option value=NU>NUORO</option><option value=OR>ORISTANO</option><option value=PD>PADOVA</option><option value=PA>PALERMO</option><option value=PR>PARMA</option><option value=PV>PAVIA</option><option value=PG>PERUGIA</option><option value=PU>PESARO E URBINO</option><option value=PE>PESCARA</option><option value=PC>PIACENZA</option><option value=PI>PISA</option><option value=PT>PISTOIA</option><option value=PN>PORDENONE</option><option value=PZ>POTENZA</option><option value=PO>PRATO</option><option value=RG>RAGUSA</option><option value=RA>RAVENNA</option><option value=RC>REGGIO DI CALABRIA</option><option value=RE>REGGIO NELL EMILIA</option><option value=RI>RIETI</option><option value=RN>RIMINI</option><option value=RM>ROMA</option><option value=RO>ROVIGO</option><option value=SA>SALERNO</option><option value=SS>SASSARI</option><option value=SV>SAVONA</option><option value=SI>SIENA</option><option value=SR>SIRACUSA</option><option value=SO>SONDRIO</option><option value=TA>TARANTO</option><option value=TE>TERAMO</option><option value=TR>TERNI</option><option value=TO>TORINO</option><option value=TP>TRAPANI</option><option value=TN>TRENTO</option><option value=TV>TREVISO</option><option value=TS>TRIESTE</option><option value=UD>UDINE</option><option value=VA>VARESE</option><option value=VE>VENEZIA</option><option value=VB>VERBANO-CUSIO-OSSOLA</option><option value=VC>VERCELLI</option><option value=VR>VERONA</option><option value=VV>VIBO VALENTIA</option><option value=VI>VICENZA</option><option value=VT>VITERBO</option></select>\";\n s += \"</div><div class='row'></div>\";\n s += \"<div class='button'><br><input type=button onclick=makeAddClientJson() value=Registra>\";\n s += \"<br><p>* Campi Obbligatori</p></div>\";\n s += \"<div class='row'></div></form>\";\n $(\"#post\").html(s);\n}",
"function submitForm(){\n let form = document.querySelector(Form.id);\n let appointment = Object.create(Appointment);\n appointment.who = form.querySelector(\"[name=who]\").value;\n appointment.about = form.querySelector(\"[name=about]\").value;\n appointment.agenda = form.querySelector(\"[name=agenda]\").value;\n let day = form.querySelector(\"[name=day]\").value;\n appointment.day = day;\n // Create a random id if it is a new appointment\n appointment.id = form.querySelector(\"[name=id]\").value || \n 'appointment-'+\n form.querySelector(\"[name=day]\").value+'-'+\n (1+Math.random()).toString(36).substring(7)\n ;\n Calendar.appointments[day] = appointment;\n closeForm();\n showNewAppointment(appointment);\n showMessage(\"Success\", \"Your appointment has been sucessfully saved.\");\n}",
"function buildForm(dayId){\n // Validate input\n if (dayId === undefined){\n showMessage(\"An error occurred.\", \"Please, select a day in order to edit an appointment.\");\n return;\n }\n let app = document.querySelector('#application');\n // Create form from template if it doesn't exist\n let form = document.querySelector(Form.id);\n if (form == null){\n app.innerHTML = document.querySelector(Form.tpl).innerHTML+app.innerHTML;\n form = document.querySelector(Form.id);\n }\n // Fill the day -- it should always be filled\n form.querySelector(\"[name='day']\").value = dayId;\n let day = id2Day(dayId);\n let daynum = day.getDate();\n let monthName = day.toLocaleString( 'en-us', {'month': 'long'});\n let daysuf = daynum == 1 ? 'st' : daynum == 2 ? 'nd' : daynum == 3 ? 'rd' : 'th';\n // Fill in the form values for the current appointment\n let appointment = Calendar.appointments[dayId] || Appointment;\n if (appointment.id){\n form.querySelector(\"header\").innerHTML = `<strong class=\"editing\">Editing appointment for ${monthName} ${daynum}${daysuf}</strong>`;\n }else{\n form.querySelector(\"header\").innerHTML = `Appointment for ${monthName} ${daynum}${daysuf}`;\n }\n Object.keys(appointment).forEach(\n function(key){\n if (key!='day' ){\n form.querySelector(`[name='${key}']`).value = appointment[key] || '';\n }\n }\n );\n setTimeout(()=>{ form.style.maxHeight = '500px'; }, 0);\n}",
"function addOperationForm(clienti, manodopera, articoli) {\n if (clienti === \"NON CI SONO CLIENTI\") {\n out = \"<p>Non ci sono clienti, non è possibile aggiungere alcuna Operazione! <br>\" +\n \"<br><input type='button' onclick= addClient() value='Aggiungi Cliente'>\";\n //genero il menu per i clienti\n } else {\n client = \"<select id=select name=codCliente><option value=null>---</option>\";\n for (i = 0; i < clienti.length; i++) {\n client += \"<option value=\" + clienti[i].cf + \">\" + clienti[i].cf + \"</option>\";\n }\n client += \"</select>\";\n //genero il menu per gli articoli se sono presenti\n art = \"<select id=select name=codArticolo><option value=null>---</option>\";\n if (articoli !== \"NON CI SONO ARTICOLI\") {\n for (i = 0; i < articoli.length; i++) {\n art += \"<option value=\" + articoli[i].codice + \">\" + articoli[i].codice + \"</option>\";\n }\n }\n art += \"</select>\";\n //creo il menu per la quantita\n quantita = \"<select id=select name=numArt><option value=1>1</option>\";\n for (i = 2; i <= 10; i++) {\n quantita += \"<option value=\" + i + \">\" + i + \"</option>\";\n }\n quantita += \"</select>\";\n //creo il menu per la manodopera \n man = \"<select id=select name=codMan><option value=null>---</option>\";\n for (i = 0; i < manodopera.length; i++) {\n man += \"<option value=\" + manodopera[i].id_manodopera + \">\" + manodopera[i].id_manodopera + \"</option>\";\n }\n man += \"</select>\";\n //collego i campi del form con i menu creati\n out = \"<form name='addOperation'>\";\n out += \"<div class='cell'>*Scegli Cliente</div><div class='cell'>\" + client + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Scegli Articolo</div><div class='cell'>\" + art + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Scegli Quantità</div><div class='cell'>\" + quantita + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Tipo Prestazione</div><div class='cell'>\" + man + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='button'><br><input type=button onclick=makeAddOperationJson() value='Salva'>\";\n out += \"<p>* Campi Obbligatori</p></div>\";\n out += \"<div class='row'></div></form>\";\n }\n $(\"#post\").html(out);\n}",
"function book_appointment() \n{\t\t\n\treset_form();\t\t\n\t$(\"input:text:visible:first\").focus();\t\n\t$(\".view_appointments\").hide();\n\t$(\".appointment_form\").show();\n\t\n\t\t/**\n\t\t** Function call: on load() - \n\t\t** Function call: current_date() - \n\t\t*/\n\t\t\n\t\t$(\"#appointment_time\").val(current_date()); //yyyy-MM-ddThh:mm\n\t\n\t\n}",
"function searchClientByID() {\n hideAllOptions();\n\n //Show the resources loading view\n $scope.loadingResources = true;\n\n //get user input from form\n var clientId = $scope.clientID;\n\n //if they don't chose a client, start over\n if (clientId === null || clientId === '' || typeof(clientId) === 'undefined') {\n checkClientInForms();\n return;\n }\n\n //array to store clients\n $scope.clients = [];\n\n $http.get('webapi/client/searchID/' + clientId)\n .then(function (response) {\n for (var client in response.data['clients']) {\n //loop through the response data and make clients\n $scope.clients.push(response.data['clients'][client]);\n }\n //hide the loading banner\n $scope.loadingResources = false;\n\n //show the clients to choose from\n $scope.clientList = true;\n\n }, function () {\n $scope.loadingResources = false;\n $scope.kitchenError = true;\n });\n }",
"function registerAppointment() {\n const submittedData = {};\n\n // Make a timestamp with date and time and add it to json\n let dateTimestampInSeconds = convertDateToTimestamp(document.getElementById(\"appointment-date\").value);\n let timepickerValue = document.getElementById(\"appointment-time\").value;\n if (!timepickerValue) {\n alert(\"Wybierz godzinę wizyty\");\n return;\n }\n\n let timeInSeconds = convertTimepickerValueToSeconds(timepickerValue);\n if (!validateTimepickerValue(timeInSeconds)) {\n return;\n }\n let dateTimeInSeconds = dateTimestampInSeconds + timeInSeconds;\n submittedData.startDate = dateTimeInSeconds;\n\n let selectDuration = document.getElementById(\"select-duration\");\n let appointmentDuration = selectDuration.options[selectDuration.selectedIndex].value;\n // Appointment duration should be presented in seconds\n if (appointmentDuration == 1) {\n submittedData.duration = 3600;\n } else if (appointmentDuration == 2) {\n submittedData.duration = 7200;\n } else submittedData.duration = 0;\n\n // Doctor email\n let selectDoctor = document.getElementById(\"select-doctor\");\n let doctorValue = selectDoctor.options[selectDoctor.selectedIndex].value;\n submittedData.mail = doctorValue;\n\n if (!validateFormInput(submittedData)) {\n // Data is not valid, don't send it\n return;\n }\n\n // Send data to sever and react to responses\n let xhr = new XMLHttpRequest();\n xhr.open(\"POST\", chooseProtocol() + window.location.host + \"/api/appointment/new\", true);\n xhr.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n xhr.addEventListener('load', function () {\n if (this.status === 200) {\n const response = this.response;\n\n // Show message to user, after user clicks 'OK', redirecting to login screen\n alert(\"Wizyta została poprawnie utworzona\");\n\n } else if (this.status === 400) {\n const response = JSON.parse(this.responseText);\n // Sent data was wrong, show message to user\n alert(response.error);\n }\n });\n xhr.send(JSON.stringify(submittedData));\n}",
"function addSendingForm(itemId) {\r\n\tdocument.getElementById(\"formSend\" + itemId).innerHTML = \"<div>\" +\r\n\t\"<form id=\\\"sendingItemsForm\\\" method=\\\"patch\\\" action=\\\"\\\">\" +\r\n\t\"<b>Send item:</b><br>\" +\r\n\t\"Amount: <input type=\\\"text\\\" name=\\\"amount\\\" class=\\\"amountSendingItems\\\"><br>\" +\r\n\t\"Destination: <select id=\\\"locations\\\" name=\\\"location\\\" class=\\\"destinationSendingItems\\\">\" + \r\n\t\"</select><br>\" +\r\n\t\"<input type=\\\"button\\\" value=\\\"Send\\\" onclick=\\\"javascript:sendForm(\" + itemId + \");\\\">\" +\r\n\t\"</form></div>\";\r\n\tgetLocationsList(); \r\n}",
"function tripDSOnLoad() {\n var form = TripViewForm.getForm();\n form.setValues(tripDS.getAt(0).data);\n form.findField('eventsDisplayField').setValue(buildStringFromArray(tripDS.getAt(0).data.events, \"name\", \"<br/>\"));\n form.findField('contractsDisplayFieldTrip').setValue(buildStringFromArray(tripDS.getAt(0).data.contracts, \"name\", \"<br/>\"));\n form.findField('locationsDisplayField').setValue(buildStringFromArray(tripDS.getAt(0).data.locations, \"name\", \"<br/>\"));\n\n}",
"function calendarAppointment(results, calendarId) { // results is returned from getResults()\r\n for (i = 0; i < results.length; i++) {\r\n // Set start and end times based on results inputted to Google Forms\r\n let time = results[i][3]; // Format: '2021-02-04 15:00'\r\n let timeStart = time.substring(0,10) + 'T' + time.substring(11,16) + ':00'; // Format: '2021-02-04T15:00'\r\n let timeEnd = time.substring(0,10) + 'T' + time[11] + (parseInt(time[12]) + 1).toString() + ':00:00'; // 1 hour after start\r\n \r\n // Create the Google Calendar event\r\n let event = {\r\n \"summary\": 'This is the Google Calendar event for your tutoring appointment.',\r\n \"start\": {\r\n \"dateTime\": timeStart,\r\n \"timeZone\": \"America/New_York\"\r\n },\r\n \"end\": {\r\n \"dateTime\": timeEnd,\r\n \"timeZone\": \"America/New_York\",\r\n },\r\n \"conferenceData\": {\r\n \"createRequest\": {\r\n \"conferenceSolutionKey\": {\r\n \"type\": \"hangoutsMeet\"\r\n }, \r\n \"requestId\": generateId()\r\n }\r\n }\r\n };\r\n \r\n // Add the event to the Google Calendar\r\n event = Calendar.Events.insert(event, calendarId, {\"conferenceDataVersion\": 1});\r\n \r\n // Display Google Meet link\r\n Logger.log(event.hangoutLink)\r\n }\r\n}",
"function makeAddClientJson() {\n var request;\n var x = document.forms['addClient'];\n //Controllo se tutti i campi sono stati compilati\n if (x.cf.value === \"\" || x.nome.value === \"\" || x.cognome.value === \"\"\n || x.indirizzo.value === \"\" || x.telefono.value === \"\" || x.citta.value === \"\"\n || x.provincia.value === \"null\") {\n alert(\"Non sono stati riempiti tutti i campi\");\n } else {\n //creo l'oggetto Json\n request = {\n \"operation\": \"addClient\",\n \"cf\": x.cf.value,\n \"nome\": x.nome.value,\n \"cognome\": x.cognome.value,\n \"indirizzo\": x.indirizzo.value,\n \"cellulare\": x.telefono.value,\n \"citta\": x.citta.value,\n \"provincia\": x.provincia.value\n };\n //Converto l'oggetto Json in stringa per inviarlo al server.\n req = JSON.stringify(request);\n ajaxEvent(req);\n }\n}",
"function renderWishListSelector() {\n //getWishListSelectorObjects returns array ready to be added to selectWidget\n var selectorObj = cCProductLists.getWishListSelectorObjects();\n\n removeWishListSelector();\n\n wishListSelectorController = Alloy.createController('components/selectWidget', {\n valueField : 'wishListId',\n textField : 'wishListName',\n values : selectorObj,\n messageWhenSelection : '',\n messageWhenNoSelection : _L('Select Wish List'),\n selectListTitleStyle : {\n backgroundColor : Alloy.Styles.color.background.white,\n font : Alloy.Styles.tabFont,\n color : Alloy.Styles.accentColor,\n disabledColor : Alloy.Styles.color.text.light,\n width : Ti.UI.FILL,\n height : Ti.UI.FILL,\n disabledBackgroundColor : Alloy.Styles.color.background.light,\n textAlign : Ti.UI.TEXT_ALIGNMENT_CENTER,\n accessibilityValue : 'wish_list_selector'\n },\n selectListStyle : {\n width : 320,\n left : 20,\n height : 40,\n top : 5,\n bottom : 5,\n font : Alloy.Styles.textFieldFont,\n selectedFont : Alloy.Styles.textFieldFont,\n unselectedFont : Alloy.Styles.textFieldFont,\n color : Alloy.Styles.color.text.darkest,\n selectedOptionColor : Alloy.Styles.color.text.darkest,\n disabledColor : Alloy.Styles.color.text.light,\n backgroundColor : Alloy.Styles.color.background.white,\n selectedOptionBackgroundColor : Alloy.Styles.color.background.light,\n disabledBackgroundColor : Alloy.Styles.color.background.light,\n borderColor : Alloy.Styles.accentColor\n },\n needsCallbackAfterClick : true,\n });\n\n $.listenTo(wishListSelectorController, 'itemSelected', function(event) {\n if (event.item) {\n selectedWishListId = event.item.wishListId;\n loadInitSelectedWishList(selectedWishListId);\n }\n });\n $.listenTo(wishListSelectorController, 'dropdownSelected', function() {\n wishListSelectorController.continueAfterClick();\n });\n\n wishListSelectorController.updateItems(selectorObj);\n wishListSelectorController.setEnabled(true);\n $.wish_list_selector_container.add(wishListSelectorController.getView());\n $.wish_list_selector_container.show();\n //reposition email_wish_list_button if there a select widget\n $.email_wish_list_button.setRight(20);\n}",
"createAppointment(event) {\n event.preventDefault()\n const selectedDate = this.refs.selectedDate.value;\n const selectedTime = this.refs.selectedTime.value;\n var patientDescription = this.refs.selectedPatient.value;\n var patient = this.findPatientIndex(patientDescription, this.state.patientsList);\n var fullTime = selectedDate + \" \" + selectedTime;\n var finalTime = moment(fullTime, \"YYYY-MM-DD hh:mm A\").unix();\n\n if(!patient){\n alert(\"Please select a valid patient!\");\n }else if(moment(selectedDate).isValid() === false\n || moment(selectedDate).isSameOrAfter(moment(), 'day') === false){\n alert(\"Please check if the date is valid and not in the past!\");\n }else if(moment.unix(finalTime).isSameOrAfter(moment(), 'minute') === false){\n alert(\"Please select a valid time!\");\n }else{\n var appt = {\n patientUuid: patient.patientUUID,\n doctorUuid: sessionStorage.userUUID,\n dateScheduled: finalTime\n }\n\n requests.postFutureAppointment(appt)\n .then((res) => {\n console.log(\"created future appointment sucessfully\");\n location.reload();\n })\n .catch((e) =>{\n console.log(\"Could not create future appointment\");\n });\n }\n }",
"function updateClinicianList() {\r\n\r\n // Null out current selected item and clear list.\r\n $scope.exportDataFormBean.clinicianId = \"\";\r\n //console.log(\">> \"+ $scope.exportDataFormBean.clinicianId);\r\n $scope.clinicanList = [];\r\n\r\n // Create the request parameters we will post.\r\n var requestPayload = {};\r\n if ($scope.exportDataFormBean.showDeletedClinicians) {\r\n requestPayload = $.param({\"includeAll\": true});\r\n }\r\n else {\r\n requestPayload = $.param({\"includeAll\": false});\r\n }\r\n\r\n // Call the web service and update the model.\r\n $http({\r\n method: \"POST\",\r\n url: \"exportData/services/user/clinicians\",\r\n responseType: \"json\",\r\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\r\n data: requestPayload\r\n })\r\n .success(function (data, status, headers, config) {\r\n $scope.clinicanList = data;\r\n })\r\n .error(function (data, status) {\r\n //\r\n });\r\n }",
"function seleccionarPartido() {\n\n const di_padre = document.getElementById(\"directo\")\n const di_form = document.createElement(\"div\")\n di_form.setAttribute(\"id\", \"form\")\n const formu = document.createElement(\"form\")\n const l1 = document.createElement(\"label\")\n l1.setAttribute(\"for\", \"npartido\")\n l1.innerHTML = \"NUMERO DE PARTIDO\"\n const inp1 = document.createElement(\"input\")\n inp1.setAttribute(\"type\", \"text\")\n inp1.setAttribute(\"id\", \"npartido\")\n inp1.setAttribute(\"name\", \"npartido\")\n inp1.setAttribute(\"required\", \"\")\n\n const l2 = document.createElement(\"label\")\n l2.setAttribute(\"for\", \"local\")\n l2.innerHTML = \"EQUIPO LOCAL\"\n const inp2 = document.createElement(\"select\")\n inp2.setAttribute(\"id\", \"local\")\n inp2.setAttribute(\"name\", \"local\")\n\n const l3 = document.createElement(\"label\")\n l3.setAttribute(\"for\", \"visitante\")\n l3.innerHTML = \"EQUIPO VISITANTE\"\n const inp3 = document.createElement(\"select\")\n inp3.setAttribute(\"id\", \"visitante\")\n inp3.setAttribute(\"name\", \"visitante\")\n\n const l4 = document.createElement(\"label\")\n l4.setAttribute(\"for\", \"id_liga\")\n l4.innerHTML = \"SELECCIONA LIGA\"\n const sel1 = document.createElement(\"select\")\n sel1.setAttribute(\"name\", \"id_liga\")\n sel1.setAttribute(\"id\", \"liga\")\n const opt1 = document.createElement(\"option\")\n opt1.setAttribute(\"value\", \"SM\")\n opt1.innerHTML = \"SM\"\n const opt2 = document.createElement(\"option\")\n opt2.setAttribute(\"value\", \"SF\")\n opt2.innerHTML = \"SF\"\n const opt3 = document.createElement(\"option\")\n opt3.setAttribute(\"value\", \"SM2\")\n opt3.innerHTML = \"SM2\"\n const opt4 = document.createElement(\"option\")\n opt4.setAttribute(\"value\", \"SF2\")\n opt4.innerHTML = \"SF2\"\n const bt = document.createElement(\"button\")\n bt.setAttribute(\"id\", \"datosform\")\n bt.innerHTML = \"Enviar\"\n\n sel1.appendChild(opt1)\n sel1.appendChild(opt2)\n sel1.appendChild(opt3)\n sel1.appendChild(opt4)\n formu.appendChild(l4)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(sel1)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(l1)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(inp1)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(l2)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(inp2)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(l3)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(inp3)\n formu.appendChild(document.createElement(\"br\"))\n formu.appendChild(bt)\n di_form.appendChild(formu)\n di_padre.appendChild(di_form)\n\n damEquipos(sel1.value, inp2, inp3)\n /**\n * Este evento lo que hace es que al clickear recoge los valores\n * y crea el partido en la base de datos.\n */\n bt.addEventListener(\"click\", function (e) {\n e.preventDefault()\n const dat1 = document.getElementById(\"npartido\").value\n const dat2 = document.getElementById(\"local\").value\n const dat3 = document.getElementById(\"visitante\").value\n const dat4 = document.getElementById(\"liga\").value\n const info = { \"npartido\": dat1, \"local\": dat2, \"visitante\": dat3, \"liga\": dat4 }\n localStorage.setItem(\"partido\", JSON.stringify(info))\n\n localStorage.setItem(\"set\", 1)\n\n const partido = JSON.parse(localStorage.getItem(\"partido\"))\n\n buscarEquipo(partido[\"local\"])\n buscarEquipo(partido[\"visitante\"])\n num_partido = parseInt(JSON.parse(localStorage.getItem(\"partido\"))[\"npartido\"])\n let arrayP = [parseInt(dat2), parseInt(dat3), parseInt(dat1), dat4]\n \n addPartido(arrayP)\n di_form.remove()\n })\n\n /**\n * Este evento lo que hace es que al haber un cambio se cambien los equipos \n */\n sel1.addEventListener(\"change\", function () {\n damEquipos(sel1.value, inp2, inp3)\n })\n}",
"function validateGetCalendarForm() {\r\n //TODO: Check valid years, etc.\r\n}",
"function installCheckboxes(){\n\t\tvar form = \"<form name=conferences>\\n\";\n\t\tfor (confName in conferences){\n\t\t\tform += \"<label><input type=\\\"checkbox\\\" \";\n\t\t\tform += \"id=\\\"\" + confName + \"\\\" \";\n\t\t\tform += \"checked onclick='pcminer.confSelected(\\\"\" + confName + \"\\\")'> \";\n\t\t\tform += \"<font id=\\\"\" + confName + \"color\\\" \";\n\t\t\tform += \"class=\\\"conf\\\">\" + confName + \"</font></label>\\n\";\n\t\t}\n\t\tform += \"</form>\\n\";\n\t\tdocument.getElementById(\"checkboxes\").innerHTML = form;\n\t\tfor (conf in confColors){\n\t\t\tdocument.getElementById(conf + \"color\").style.color = confColors[conf];\n\t\t}\n\t\t\n\t}",
"function loadAppList() {\n //Start the loading indicator\n $('#pcs-applist-overlay').addClass('pcs-common-load-overlay');\n\n\t\t\t\t// clear all the old data\n\t\t\t\tself.startFormList.removeAll();\n\t\t\t\tself.processList = [];\n\t\t\t\tself.searchedStartFormList.removeAll();\n\n //trigger service to fetch data for appNameList\n services.getStartFormList().done(\n function(data) {\n self._populateStartFormListData(data);\n\n // Hide the loading indicator\n $('#pcs-applist-overlay').removeClass('pcs-common-load-overlay');\n\n\t\t\t\t\t\t$('#pcs-applist-error', self.rootElement).hide();\n }\n ).fail(\n function(jqXHR) {\n var msg = self.bundle.pcs.applist.load_error;\n\n if (jqXHR && jqXHR.status === 0) {\n msg = self.bundle.pcs.common.server_not_reachable;\n }\n\n if (jqXHR && jqXHR.status === 500) {\n msg = self.bundle.pcs.common.internal_server_err;\n } else if (jqXHR && jqXHR.status === 401) {\n // reset valid authInfo as the current auth is invalid\n msg = self.bundle.pcs.common.access_error_msg;\n }\n\n $('#pcs-applist-error', self.rootElement).show();\n $('#pcs-applist-error-msg', self.rootElement).text(msg);\n\n // Hide the loading indicator\n $('#pcs-applist-overlay').removeClass('pcs-common-load-overlay');\n }\n );\n\n //fetchDynamicProcess\n\t\t\t\tself.fetchDynamicProcess();\n }",
"function formSetup() {\n let sheet = SpreadsheetApp.getActiveSpreadsheet();\n if (sheet.getFormUrl()) {\n let ui = SpreadsheetApp.getUi();\n ui.alert(\n 'ℹ️ A Form already exists',\n 'Unlink the form and try again.\\n\\n' +\n 'From the top menu:\\n' +\n 'Click \"Form\" > \"Unlink form\"',\n ui.ButtonSet.OK\n );\n return;\n }\n\n // Create the form.\n let form = FormApp.create('Request time off')\n .setCollectEmail(true)\n .setDestination(FormApp.DestinationType.SPREADSHEET, sheet.getId())\n .setLimitOneResponsePerUser(false);\n\n form.addTextItem().setTitle(Header.Name).setRequired(false);\n form.addDateItem().setTitle(Header.StartDate).setRequired(true);\n form.addDateItem().setTitle(Header.EndDate).setRequired(true);\n form.addListItem().setTitle(Header.Reason).setChoiceValues(Object.values(Reason)).setRequired(true);\n form.addTextItem().setTitle(Header.AdditionalInformation).setRequired(false);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
turn wheel function that starts the wheel turn by comparing the currentAngle stored in the global variable and compares it to the target angle in order initiate turning if the current Angle is not within tolorance. | function turnWheelTo(angle) {
global.target = angle;
var difference = (global.currentAngle - global.target);
// NOTE, js treats '+' as string concatination by default, + in front of globa.target forces int typing
if (Math.abs(difference) < global.SLOW_TOLORANCE) {
var forceCoefficient = global.PROPORTIONAL_CONSTANT * difference / (2 * global.SLOW_TOLORANCE); // max value = 0.5
// console.log(forceCoefficient);
if (difference > global.TOLORANCE) {
// g.forceConstant(0.3);
g.forceConstant(0.5 - forceCoefficient);
global.turning = 0;
}
else if(difference < (-global.TOLORANCE)) {
// g.forceConstant(0.7);
g.forceConstant(0.5 - forceCoefficient);
global.turning = 1;
} else {
g.forceConstant(.5);
}
}
else if (global.currentAngle > (+ global.target + global.TOLORANCE)) {
// console.log('turned wheel left to ' + angle);
g.forceConstant(.1);
global.turning = 0; // turning left
}
else if (global.currentAngle < (+ global.target - global.TOLORANCE)) {
// console.log('turned wheel right to' + angle);
g.forceConstant(.9);
global.turning = 1; // turning right
}
} | [
"function angleReset() {\n\tturnWheelTo(50); // 50 is the middle angle of the G27 wheel. \n\tglobal.turnCounter = 0;\n}",
"function toggleSpinning() {\n\t// Toggle the spinning animation\n\tif (isSpinning) {\n\t\t// Stop the arrow\n\t\tisSpinning = false;\n\t\tclearInterval(toggleSpinning.spinInt);\n\t\tspinButton.removeAttribute(\"disabled\");\n\t\tvar result = currentSlice+1;\n\t\tconsole.log(result);\n\t\tif (result == 1){\n\t\t\tthis_game.spin = result;\n\t\t} else {\n\t\t\tthis_game.spin = result;\n\t\t}\n\t\tthis_game.Determine_Route();\n\t\t$('#start_turn_button').prop('disabled', false);\n\t\t$('#spinner-button').prop('disabled', true);\n\t}\n\telse {\n\t\t// Start spinning the arrow\n\t\tisSpinning = true;\n\t\ttoggleSpinning.spinInt = setInterval(spinWheel, 1000/60);\n\t\t// Set how long the wheel will be spinning\n\t\tvar duration = Math.floor(Math.random() * 2000) + 1000;\n\t\tsetTimeout(toggleSpinning, duration);\n\t\t// Disable the spin button\n\t\tspinButton.setAttribute(\"disabled\", \"true\");\n\t}\n}",
"function turnVinyl(){\n console.log(\"Turn vinyl\");\n turn = true;\n counter = setInterval(function(){\n if(degree>=360){degree=0;}\n degree++;\n $('#vinyle').css('-webkit-transform', 'rotate('+degree*4+'deg)');\n },10)\n }",
"onOpenSpinningWheel() {\n Actions.SpinningWheel();\n }",
"turnAround() {\n this.left(180);\n }",
"_changeTurn() {\n this._currentTurn =\n this._currentTurn === this._redBigPlanet\n ? this._blueBigPlanet\n : this._redBigPlanet;\n if (this._targetPlanet === this._currentTurn) {\n this._changeTarget();\n }\n }",
"static MoveTowardsAngle(current, target, maxDelta) {\n const num = Scalar.DeltaAngle(current, target);\n let result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n result = Scalar.MoveTowards(current, current + num, maxDelta);\n }\n return result;\n }",
"static RotateTowards(from, to, maxDegreesDelta) {\n const num = Quaternion.Angle(from, to);\n if (num === 0) {\n return to;\n }\n const t = Math.min(1, maxDegreesDelta / num);\n return Quaternion.Slerp(from, to, t);\n }",
"function rotationLeft() {\n var deg = 36;\n rotation = rotation - deg;\n //wheel.style.transform = rotate(\"rotation\" - \"deg\")\n wheel.style.transform =`rotate(${rotation}deg)`;\n}",
"changeTurn() {\n this.setupFog(false);\n super.changeTurn();\n }",
"function lerpAngle(a, b, t) {\n const d = b - a;\n let num = d - floor(d / 360) * 360;\n if (num > 180.0) num -= 360;\n return a + num * constrain(t, 0, 1);\n}",
"function tract_toggle() {\n console.log(\"tract_toggle\");\n if (tract_counter%2 == 0) {\n click_tract_off();\n } else {\n click_tract_on();\n }\n}",
"function incAngle(increment) {\n setAngle(Math.min(Math.max(angle + increment, config.angle_min), config.angle_max), true);\n }",
"function flipping_spinning_bitcoin_rotation_movements() {\n \n var flipping_spinning_bitcoin_rotation_speed = ( flipping_spinning_bitcoin_motion_factor * 1 * 28 );\n \n if(is_bitcoin_flipping) {\n \n bitcoin_flipping_factor_counter += flipping_spinning_bitcoin_rotation_speed;\n flipping_spinning_bitcoin_collada.rotation.x += flipping_spinning_bitcoin_rotation_speed;\n \n }\n \n if(is_bitcoin_spinning) {\n \n bitcoin_spinning_factor_counter += flipping_spinning_bitcoin_rotation_speed;\n flipping_spinning_bitcoin_collada.rotation.z += flipping_spinning_bitcoin_rotation_speed;\n \n }\n \n}",
"function clickevent(TorF)\n{\n\t//The startend value will only activate until it becomes true. This will happen when the button is pressed and calls RandVal().\n\t//Will allow the rest of the code inside to continue while true, but when time ends, will stop the function from running.\n\tif (startEnd) \n\t{\n\t\t//This if statement is checking if the parameter value from the onclick is the same as the rand value.\n\t\tif (TorF == rand)\n\t\t{\n\t\t\tclicked=TorF; //Assigns the TorF value to clicked. clicked will act as a container of the last parameter clicked.\n\t\t\tscore++; //Will increment the score once the if statement activates.\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\t//Will activate the while statement as long as clicked equals rand.\n\t\t//Clicked is the previous parameter value, so in this statement, it will make sure that the 'mole' will not be in the same place.\n\t\twhile (clicked == rand)\n\t\t{\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\tdocument.getElementById(clicked).src= 'images/hole.png'; //Will change the src of img on clicked back to a hole.\n\t}\n}",
"function moveArmToInitialPosition(){\n var servoIndex = 0;\n var moveFunc = function(err, script){\n\tservoIndex++;\n\tif(servoIndex < servoCount)\n\t setServo(servoIndex, 1.5).on(python_close, moveFunc);\n }\n\n setServo(servoIndex, 1.5).on(python_close, moveFunc);\n}",
"function SetWheelParams(wheel : Transform, maxSteer : float, motor : boolean, rad : float) {\n\tvar result : WheelData = new WheelData();\t// the container of wheel specific data\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// we create a new gameobject for the collider and move, transform it to match\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the position of the wheel it represents. This allows us to do transforms\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// on the wheel itself without disturbing the collider.\n\tvar go : GameObject = new GameObject(\"WheelCollider\");\n\tgo.transform.parent = transform;\t\t\t\t\t// the car, not the wheel is parent\n\tgo.transform.position = wheel.position; \t\t// match wheel pos\n\t\n\tvar col : WheelCollider = go.AddComponent.<WheelCollider>();\t// create the actual wheel collider in the collider game object\n\tcol.motorTorque = 0.0;\n\t\n\t// store some useful references in the wheeldata object\n\tresult.transform = wheel; // access to wheel transform \n\tresult.go = go; // store the collider game object\n\tresult.col = col; // store the collider self\n\tresult.startPos = go.transform.localPosition; // store the current local pos of wheel\n\tresult.maxSteer = maxSteer; // store the max steering angle allowed for wheel\n\tresult.motor = motor; // store if wheel is connected to engine\n\tresult.radius = rad;\n\t\n\treturn result; // return the WheelData\n}",
"handleRotateClick() {\n this.player.setSetUpRotate(!this.player.getSetUpRotate());\n }",
"calculateTurnMeter() {\n this.turnMeter += this.tickRate;\n if (this.turnMeter >= 100) {\n this.turnMeter -= 100;\n this.isTurn = true;\n } \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
detect if str is register | isRegisterName(str) {
return this.architecture.hasRegisterName(str);
} | [
"function validateType(tstr){\n let retVal = Type.NOT_A_TYPE;\n if(tstr != Type.NOT_A_TYPE){\n for(const t in Type){\n // If a valid type (not NOT_A_TYPE) and symbol string matches given string:\n if(Type[t] && String(Type[t]).slice(7, -1) == tstr){\n retVal = Type[t];\n break;\n }\n }\n }\n\n return retVal;\n} // #validateType",
"function get (str) {\n if (registers.hasOwnProperty(str))\n return Number(registers[str]);\n else if (str === \"$zero\")\n return 0;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\n}",
"function sc_isString(s) { return (s instanceof sc_String); }",
"function isSymbolString(s) {\n return symbolValues[s] || isPrivateSymbol(s);\n }",
"function set (str, value) {\n if (registers.hasOwnProperty(str))\n registers[str] = Number(value);\n else if (str === \"$zero\")\n return;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\n}",
"isString() {\n return (this.type === \"string\");\n }",
"function checkForOneVar(str) {\n for(var i=0;i<str.length;i++){\n if(isOperator(str[i]) || isBrackets(str[i])){\n printError(\"invalid left hand side expression !\");\n return 0;\n }\n }\n return 1;\n}",
"function isCallerID (s) {\n\tvar i;\n if (isEmpty(s))\n if (isCallerID.arguments.length == 1) return defaultEmptyOK;\n else return (isCallerID.arguments[1] == true);\n\n\n for (i = 0; i < s.length; i++) {\n var c = s.charAt(i);\n if (! (isCallerIDChar(c) ) )\n return false;\n }\n\n return true;\n}",
"function checkType(str) {\n var obj = {\n datatype: typeof str,\n length: str.length,\n }\n return obj;\n}",
"function isError(str){\n if(str.startsWith(\"Error: \")){\n return true;\n }\n return false;\n}",
"function isHexPrefixed(str){return str.slice(0,2)==='0x';}",
"function minilang(tokenString) {\n let stack = [];\n let register = 0;\n let tokens = tokenString.split(' ');\n\n for (let i = 0; i < tokens.length; i += 1) {\n let currentToken = tokens[i];\n if (Number.isNaN(Number(currentToken))) {\n switch (currentToken) {\n case 'PUSH': \n stack.push(register);\n break;\n case 'ADD': \n register = stack.pop() + register;\n break;\n case 'SUB':\n register -= stack.pop();\n break;\n case 'MULT':\n register *= stack.pop();\n break;\n case 'DIV':\n register = Math.floor(register / stack.pop());\n break;\n case 'MOD':\n register %= stack.pop();\n break;\n case 'POP':\n register = stack.pop();\n break;\n case 'PRINT':\n console.log(register);\n break;\n }\n } else {\n register = Number(currentToken);\n }\n }\n\n}",
"function checkName(str) {\n for (var i=0; i < trains.length; i++) {\n if (trains[i]===str) {\n return false;\n }\n }\n return true;\n}",
"isValid(string) {\n\t\tvar words = string.match(/\\w+/g);\n\t\tif (!words) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let w of words) {\n\t\t\tif (!this.isMember(w)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"function validate(str) {\n return !str.includes('|||')\n}",
"function getRegCode()\n{\n\t// TODO: Remove this hard coded registration code\n\t//regCode = \"66fb4d8ef9ccd0cd2d3dc8107199380d470b7c32250bb0b93922c7efbef074ae\";\n\ttry\n\t{\n\t\t// Get the registration code from the current account \n\t\tvar params = {};\n\t\tawsIot.getRegistrationCode(params, function(err, data)\n\t\t{\n\t\t\tif (err)\n\t\t\t{\n\t\t\t\t// an error occurred\n\t\t\t\tconsole.log(err, err.stack);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// successful response\n\t\t\t\tregCode = data.registrationCode;\n\t\t\t}\n\t\t});\n\t}\n\tcatch (ex)\n\t{\n\t\talert(\"getRegCode Exception: \" + ex);\n\t\treturn false;\n\t}\n\t// Log the registration code. Return false if it is undefined.\n\tconsole.log('regCode: ' + regCode);\n\tif (regCode == null) return false;\n\t\n\t// If we got here, then everything is ok\n\treturn true;\n}",
"function checkIf({ string }) {\n return (string.substr(0, 2).toLowerCase() === \"if\");\n}",
"function didYouSayFortnite(str) {\n return str.includes('fortnite')\n}",
"function isValidHexCode(str) {\n\treturn /^#[a-f0-9]{6}$/i.test(str);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get data related to this chart_id only | function filter_by_chart_id(value) {
return value.chart_id == chart_id;
} | [
"function getDatasetInfoById(ds_id) {\n var ds_info, i;\n for (i = 0; i < entry.datasets.length; i++) {\n ds_info = entry.datasets[i];\n if (ds_info[\"id\"] == ds_id) {\n ds_info[\"ref\"] = i; //reference for pulling out datasetinfo from coresponding lists like colorbars\n return ds_info;\n break;\n }\n }\n}",
"dataPoints () {\n let dimension = this;\n \n // Get the data points for this user for this dimension\n return DataPoints.find({\n dimensionId: dimension._id\n });\n }",
"function getChartResource() {\n\tif (isFirstTime) {\n\t\tisFirstTime = false;\n\t\t$.ajax({\n\t\t\ttype : \"GET\",\n\t\t\turl : \"getChartSourceContent\",\n\t\t\tsuccess : function(data) {\n\t\t\t\t$('#chartContents').html(data);\n\t\t\t},\n\t\t\tfailure : function(errMsg) {\n\t\t\t\talert(errMsg);\n\t\t\t}\n\t\t});\n\t}\n}",
"function getDataset(groupedData, currentGender, currentGroup) { \n var genderData = groupedData.filter(function(d) {\n return d.key == currentGender;\n })\n \n return genderData[0].values.filter(function(d) {\n return d.key == currentGroup;\n }) \n}",
"function chartClickData () {\n var data = [];\n for (var i = 0; i < allProducts.length ; i++) {\n data.push(allProducts[i].timesClicked);\n }\n return data;\n}",
"function getAllDashboardData() {\n Dashboard.getAllDashboardData({fId: vm.facility.id}).$promise\n .then(function (data) {\n vm.bashboardData = data;\n //Pie BEd Availability\n vm.pieChartDataBeds = [{\n key: 'Female',\n y: data.bedAvailability.female\n }, {\n key: 'Male',\n y: data.bedAvailability.male\n }];\n\n //Pie level of care\n vm.pieChartDataLevelOfCares = _.chain(data.typeLevelCare)\n .map(function (value, index) {\n return {\n key: index,\n y: value\n }\n })\n .filter(function (val) {\n return val.y > 0;\n })\n .value();\n\n //Pie payment methods\n vm.pieChartDataPaymentMethods = _.chain(data.typePaymentMethod)\n .map(function (value, index) {\n return {\n key: index,\n y: value\n }\n })\n .filter(function (val) {\n return val.y > 0;\n })\n .value();\n\n //Pie missing authorization\n vm.pieChartDataPatientsMissingAuth = [{\n key: 'Missing',\n y: data.concurrentReviews.no_concurrent_review\n }, {\n key: 'Authorized',\n y: data.concurrentReviews.concurrent_review\n }];\n })\n }",
"function obtainChartValues(arg)\r\n{\r\n var script = atob(arg);\r\n var chartId = script.split(\"'\")[1];\r\n var temp = \"\";\r\n var values = new Array();\r\n values[0] = chartId;\r\n \r\n if(chartId == \"ch_cr\" || chartId == \"ch_recycle\" || chartId == \"ch_extensions_all\" || chartId == \"ch_autopay\" || chartId == \"ch_cliques\" || chartId == \"ch_cdd\")\r\n {\r\n temp = script.split(\"data:[\")[1];\r\n temp = temp.substring(0,temp.indexOf(']')).split(',');\r\n }\r\n\r\n return values.concat(temp);\r\n}",
"function getChartPoints() {\n \n var chartDataDiv = $(\"#chartData\");\n\n $.getJSON('/Main/GetGraphPoints',\n {\n end: chartDataDiv.attr(\"data-graph-end\"),\n numTicks: chartDataDiv.attr(\"data-graph-ticks\"),\n sensor: chartDataDiv.attr(\"data-graph-sensor\"),\n dataType: chartDataDiv.attr(\"data-graph-data\"),\n scale: chartDataDiv.attr(\"data-graph-scale\")\n },\n function (data) {\n chartProperties.xAxis = data.xAxis;\n chartProperties.yAxis = data.yAxis;\n drawChart();\n });\n}",
"loadGraph(){\n\n var current = this;\n var servicePathAPI = baseURL+'/api/transactions/all/'+ this.dataToken;\n \n $.getJSON(servicePathAPI, function (data) {\n\n var result = data;\n if(result){ \n \n var series = [];\n var categories = [];\n for(var i=0;i < result.length;i++){\n var item = result[i];\n var transDate = new Date(item[0]);\n var transAmount = item[1];\n categories.push( moment( transDate.getTime() ).format(\"MM/DD/YYYY\") );\n current._chartData.push( [ transDate, transAmount] );\n }\n\n }\n\n // Create the transactions chart\n this._transactionChart = Highcharts.chart('mainChart', {\n rangeSelector : {\n selected : 1,\n allButtonsEnabled: true\n },\n chart: {\n zoomType: 'x',\n alignTicks: false\n },\n title : {\n text : 'Transaction Volume'\n },\n xAxis: {\n type: 'datetime',\n categories: categories\n },\n yAxis: {\n title: {\n text: 'USD'\n }\n },\n tooltip: {\n formatter: function() {\n return 'Date: <b>' + moment(this.x).format(\"MM/DD/YYYY\") + '</b> <br/> Amount: <b>$' + accounting.format(this.y) + '</b>';\n }\n },\n series : [{\n name : 'Transactions',\n fillColor : {\n linearGradient : {\n x1: 0,\n y1: 0,\n x2: 0,\n y2: 1\n },\n stops : [\n [0, Highcharts.getOptions().colors[0]],\n [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]\n ]\n },\n data : current._chartData\n }]\n\n });\n\n });\n }",
"function data(model, id) {\n if (!metaData || !metaData[model] || !metaData[model][id]) {\n return false;\n }\n\n return metaData[model][id];\n }",
"function get(id) {\n return axios.get(MATERIALS_API + \"/\" + id).then(response => response.data)\n}",
"drawChart() {\n // create google pie chart with categories data\n var data = new google.visualization.DataTable();\n data.addColumn('string', \"Category\");\n data.addColumn('number', \"Count\");\n data.addRows(JSON.parse(localStorage.getItem(\"categoryPieData\")));\n var options = {\n is3D: true, \n legend :\"bottom\"\n };\n var div = document.getElementById(\"chart_div\");\n while (div != null && div.firstChild) {\n div.removeChild(div.firstChild);\n }\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }",
"function chartRenderedData () {\n var data = [];\n for (var i = 0; i < allProducts.length ; i++) {\n data.push(allProducts[i].timesrendered);\n }\n return data;\n\n}",
"function getClickedCoinDataFromStorage(id) { \n let clickedMoreInfoCoinsArray = JSON.parse(sessionStorage.getItem((\"Clicked More info coins\")));\n if (clickedMoreInfoCoinsArray == null) {\n return null;\n }\n for (let index = 0; index < clickedMoreInfoCoinsArray.length; index++) {\n if (id == clickedMoreInfoCoinsArray[index].id) {\n return clickedMoreInfoCoinsArray[index];\n }\n }\n return null; /* Means that the clicked coin wasnt on the storage */\n }",
"function chartDataCreator() {\n for (var i = 0; i < products.length; i++) {\n chartData.push(products[i].votes);\n chartData.push(products[i].views);\n }\n}",
"getCrowdChildStats(id) {\n return this.data.childStats[id];\n }",
"function getData() {\n // let toDate = e;\n // console.log(toDate.target.value)\n console.log(to.onchange)\n\n\n axios.get(`http://api.coindesk.com/v1/bpi/historical/close.json?start=${fromDateValue}&end=${toDateValue}`)\n .then(res => {\n let labels = Object.keys(res.data.bpi)\n let values = Object.values(res.data.bpi)\n printChart(res.data, labels, values)\n })\n}",
"function getDataByIcd(icd) {\r\n\r\n\toverviewData = [];\r\n\toverviewDataSVG = [];\r\n\r\n\tconst queryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Fjahr+%3Fpe+%3Fpt+%3Fpg%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%3Fjahr+.%0A++%3Fx+med%3Adiagnose_icd+%22\" + icd + \"%22+.%0A++%3Fx+med%3Apatienten_entlassen+%3Fpe+.%0A++%3Fx+med%3Apatienten_gestorben+%3Fpt+.%0A++%3Fx+med%3Apatienten_gesamt+%3Fpg%0A%7D\";\r\n\r\n\t$.getJSON(queryString, function (data) {\r\n\t\t$.each(data.results, function (key, val) {\r\n\t\t\t$.each(val, function (m, n) {\r\n\t\t\t\t$.each(n.jahr, function (jahrkey, jahrval) {\r\n\t\t\t\t\tif (jahrkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tjahr = jahrval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pe, function (pekey, peval) {\r\n\t\t\t\t\tif (pekey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpe = peval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pt, function (ptkey, ptval) {\r\n\t\t\t\t\tif (ptkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpt = ptval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pg, function (pgkey, pgval) {\r\n\t\t\t\t\tif (pgkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpg = pgval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\toverviewDataSVG.push({jahr: jahr, patienten_entlassen: pe, patienten_gestorben: pt});\r\n\t\t\t\toverviewData.push({jahr: jahr, patienten_entlassen: pe, patienten_gestorben: pt, patienten_gesamt: pg});\r\n\t\t\t})\r\n\t\t});\r\n\r\n\t\tfillTable(overviewKeysJahre, overviewData);\r\n\t\tcreateStackedBarChart(overviewDataSVG);\t\t\r\n\t\t\r\n\t});\r\n}",
"renderliveOperationalStatisticsPie() {\n let me = this;\n this.loadingliveOperationalStatistics = true;\n this.loadingliveOperationalStatisticsPie = true;\n this.client.get('/statistics/liveoperationalstatistic').then(res => {\n if (res) {\n if (res.data) {\n this.opStatistics = res.data.current;\n this.opStatisticsPrevious = res.data.previous\n ? res.data.previous\n : null;\n //render pie chart\n let ctx = document.getElementById('operationalPie');\n me.cards.liveoperationalstatistics = new Chart(ctx, {\n type: 'pie',\n data: {\n labels: ['Not Operational', 'Operational', 'Unknown'],\n datasets: [\n {\n data: [\n me.opStatistics.notOperational,\n me.opStatistics.operational,\n me.opStatistics.unknown\n ],\n backgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa'],\n hoverBackgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa']\n }\n ]\n }\n });\n }\n }\n this.loadingliveOperationalStatisticsPie = false;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calls the showMenuItem function to determine if the Book Transfer request should be displayed on the Scheduled Requests pages | function checkBookReq(id)
{
var rc;
var temp;
rc = showMenuItem('book');
if (rc == '0'){
temp = document.getElementById(id);
temp.style.display = 'none';
}
}//end checkBookReq | [
"function checkFundsReq(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showMenuItem('funds');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkFundsReq",
"function _showModifyTileMenu() {\n //topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n var item = lv_cockpits.winControl._selection.getItems()._value[0].data;\n item.idDashboard = CockpitHelper.currentDashboard.id;\n if (item.widgetType == CockpitHelper.TileType.Numerique) {\n RightMenu.showRightMenu(Pages.modifyKpiResumeStep, { \"tile\": item });\n }\n else if (item.widgetType == CockpitHelper.TileType.Exploration) {\n RightMenu.showRightMenu(Pages.modifyExploration, { \"tile\": item });\n }\n }",
"function showBookShelf() {}",
"function checkLoanReq(id)\r\n{\r\n\tvar rc;\r\n\tvar rc1='0';\r\n\tvar temp;\r\n\r\n\trc = showMenuItem('loan');\r\n\tif (rc == '1'){\r\n\t\trc1 = showLoanItem('payment');\r\n\t}\r\n if ((rc == '0') || (rc1 == '0')){\r\n \ttemp = document.getElementById(id);\r\n \ttemp.style.display = 'none';\r\n\t}\r\n}//end checkLoanReq",
"function showHoldingsAndLocations(mReq, result, showLocations) {\n var msg = \"\";\n var isAvailable = false;\n for (var i = 0; i < result.holdings.length; i++) {\n msg += (i == 0 ? \"\" : \", \") + result.holdings[i].toLowerCase();\n if (showLocations && result.locations[i]) {\n msg += \" (\"+result.locations[i]+\") \";\n }\n if (result.holdings[i].match(isAvailableRegex)) {\n isAvailable = true;\n }\n }\n switch (result.holdings.length) {\n case 0:\n msg = noCopiesFound;\n if (result.marc.f856 && result.marc.f856.u)\n msg = \"\";\n break;\n case 1:\n msg = singleCopyStatus.replace(/%s/, msg);\n break;\n default:\n msg = multipleCopyStatus.replace(/%n/, result.holdings.length).replace(/%s/, msg);\n break;\n }\n mReq.span.appendChild(document.createTextNode(msg));\n // XXX: if !isAvailable && bibnumber given, add request button\n }",
"buttonCheck(){\n this.visibility(document.getElementById(\"add-list-button\"), this.currentList == null);\n this.visibility(document.getElementById(\"undo-button\"), this.tps.hasTransactionToUndo());\n this.visibility(document.getElementById(\"redo-button\"), this.tps.hasTransactionToRedo());\n this.visibility(document.getElementById(\"delete-list-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"add-item-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"close-list-button\"), !(this.currentList == null));\n }",
"function writeUserAssignedServices(id, name)\r\n{\r\n\tvar rc;\r\n\r\n\trc = showMenuItem(id);\r\n\tif (rc != \"1\"){\r\n\t document.getElementById(name).style.display = 'none';\r\n\t}\r\n\telse\r\n\t{\r\n\t if((name == \"positivepayexceptionreporting\" || name == \"positivepayissuereporting\") && showMenuItem('positive') != '1')\r\n\t {\r\n\t document.getElementById(name).style.display = 'none';\r\n\t }\r\n\t}\r\n\r\n}",
"function showLoadingStatus() {\n console.log(\"[menu_actions.js] Showing loading status\");\n showElementById(\"loading-status\");\n}",
"function _showAddTileMenu() {\n topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n RightMenu.showRightMenu(Pages.formatTileStep, null);\n }",
"_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }",
"function openNewTask(evtData) {\n // Display Reports as a New Task Doc Item\n if (evtData.indexOf(\"isReport\") >= 0) {\n\n var postMessageData = evtData.split(\" \");\n targetUrl = postMessageData[1];\n var reportName = postMessageData.splice(0, 2);\n var screenName, parentId, menuid;\n\n var urlParser = $('<a>', { href: postMessageData[postMessageData.length - 1] })[0];\n var a = $(\"#xmlMenuDiv li > a[data-url='\" + urlParser.pathname + \"']\");\n var isReport = a.data(\"isreport\");\n\n //Check if maximum number of screens reached\n var isScreenOpen = isScreenAlreadyOpen(targetUrl);\n if (!isScreenOpen && $('#dvWindows').children().length >= numberOfActiveWindows) {\n $('#dvWindowsExceedLimitErrorMessage').show();\n return;\n }\n\n if ($('#dvWindows').children().length <= numberOfActiveWindows) {\n clearIframes();\n }\n\n //do not show the breadcrumb for printed reports\n $('#breadcrumb').hide();\n // Checking isKPI so that reportName is appended to show in windows doc when opened from KPI.\n if (isKPI == true) {\n var windowText = kpiReportName;\n isKPI = false;\n } else {\n postMessageData.splice(postMessageData.length - 1, 1);\n var windowText = postMessageData.join(\" \");\n }\n\n if ((isReport === 'True' || isReport === 'true') && windowText.indexOf(portalBehaviourResources.Report) === -1) // only add Report to the window name if it is a report page and it does not have one\n {\n windowText = portalBehaviourResources.ReportNameTemplate.format(windowText, portalBehaviourResources.Report);\n }\n windowText = windowText + \" - \" + portalBehaviourResources.Printed;\n\n menuid = reportScreenHelp;\n\n menuid = reportScreenHelp;\n\n //Method To Load Into Task Doc\n assignUrl(windowText, parentId, menuid);\n\n //Update Help Menu after Report Generated from a Screen\n screenId = reportScreenHelp;\n }\n // Display Screen as a New Task Doc Item\n else if (evtData.indexOf(\"isScreen\") >= 0) {\n var postMessageData = evtData.split(\" \");\n targetUrl = postMessageData[1];\n\n //Check if maximum number of screens reached\n var isScreenOpen = isScreenAlreadyOpen(targetUrl);\n if (!isScreenOpen && $('#dvWindows').children().length >= numberOfActiveWindows) {\n $('#dvWindowsExceedLimitErrorMessage').show();\n return;\n }\n\n if ($('#dvWindows').children().length <= numberOfActiveWindows) {\n clearIframes();\n }\n\n /*\n Sample targetUrl\n \"/Sage300/OnPremise/AP/InvoiceEntry/Index?batchNumber=25&toAction=/Sage300/OnPremise/AP/InvoiceBatchList&actionType=EditBatch\"\n */\n\n var screenName;\n var parentScreenID;\n var screenID;\n var menuUrl = targetUrl.split(\"?\")[0];\n\n // Get ScreenId, ParentScreenId and Menu Name for Requested Url\n jQuery.each(MenuList, function (i, val) {\n if (menuUrl.indexOf(val.Data.ScreenUrl) >= 0) {\n screenID = val.Data.MenuId;\n parentScreenID = val.Data.ParentMenuId;\n screenName = val.Data.ModuleName == null ?\n val.Data.MenuName :\n portalBehaviourResources.PagetitleInManager.format(val.Data.ModuleName, val.Data.MenuName);\n }\n });\n\n loadBreadCrumb(parentScreenID);\n\n //Method To Load Into Task Doc\n assignUrl(screenName, parentScreenID, screenID);\n }\n }",
"function menuHandler(){\n if(command.getChecked()){\n command.setChecked(false);\n prefs.set('enabled',false);\n return;\n }\n command.setChecked(true); \n prefs.set('enabled',true);\n var st = startTabEx();\n }",
"function testShowMenuWithActionsOpensContextMenu() {\n sendContextMenu('#file-list');\n assertFalse(contextMenu.hasAttribute('hidden'));\n}",
"async function booking_nav() {\n console.log(selectedPark);\n if (selectedParkCAP > 0) {\n navigate('/booking', false, {selectedPark: selectedPark});\n }\n else {\n toast.error(\"Oops!!! No space available in this parking lot!\");\n }\n }",
"function checkArchive ( )\n {\n\tvar title = getElementValue(\"arc_title\");\n\tvar btn = myGetElement(\"btn_download\");\n\t\n\tif ( title && visible.o2 )\n\t{\n\t btn.textContent = \"Create Archive\";\n\t btn.onclick = archiveMainURL;\n\t}\n\t\n\telse\n\t{\n\t btn.textContent = \"Download\";\n\t btn.onclick = downloadMainURL;\n\t}\n }",
"function inspectBehavior(upStr){\n var timelineName,menuLength,i;\n var argArray = new Array;\n var found = false;\n\n argArray = extractArgs(upStr); //get args\n if (argArray.length == 2) { //should be exactly 2 args\n timelineName = argArray[1];\n menuLength = document.theForm.menu.options.length;\n for (var i=0; i<menuLength; i++) { //search menu for matching timeline name\n if (document.theForm.menu.options[i].text == timelineName) { //if found\n document.theForm.menu.selectedIndex = i; //make it selected\n found = true;\n break;\n }\n }\n if (!found) alert(errMsg(MSG_TimelineNotFound,timelineName));\n }\n}",
"static start_job_menu_item_action() {\n let full_src = Editor.get_javascript()\n let selected_src = Editor.get_javascript(true)\n let sel_start_pos = Editor.selection_start()\n let sel_end_pos = Editor.selection_end()\n let start_of_job_maybe = Editor.find_backwards(full_src, sel_start_pos, \"new Job\")\n let start_of_job_pos\n let end_of_job_pos\n let job_src = null //if this is not null, we've got a valid job surrounds (or is) the selection.\n let sel_is_instructions = false\n if(start_of_job_maybe !== null){\n [start_of_job_pos, end_of_job_pos] = Editor.select_call(full_src, start_of_job_maybe)\n }\n if(end_of_job_pos && (end_of_job_pos > sel_start_pos)){ //sel is within a job, but we don't know if its\n //instruction selection or just within the job yet.\n job_src = full_src.substring(start_of_job_pos, end_of_job_pos)\n let do_list_start_pos = full_src.indexOf(\"do_list:\", start_of_job_pos)\n if((do_list_start_pos === -1) || (do_list_start_pos > end_of_job_pos)) {} //weird, looks like Job has no do_list,\n //but ok, we just have the whole Job to execute.\n else if (do_list_start_pos < sel_start_pos) { //our selected_src should be instructions in the do_list\n sel_is_instructions = true\n }\n }\n if (job_src === null) { //no job def so we're going to make our own.\n //warning(\"There's no Job definition surrounding the cursor.\")\n var selection = Editor.get_javascript(true).trim()\n if (selection.endsWith(\",\")) { selection = selection.substring(0, selection.length - 1) }\n if (selection.length > 0){\n //if (selection.startsWith(\"[\") && selection.endsWith(\"]\")) {} //perhaps user selected the whole do_list. but\n //bue we can also have a single instr that can be an array.\n //since it's ok for a job to have an extra set of parens wrapped around its do_list,\n //just go ahead and do it.\n //else {\n //plus\n selection = \"[\" + selection + \"]\"\n sel_start_pos = sel_start_pos - 1\n //}\n var eval2_result = eval_js_part2(selection)\n if (eval2_result.error_type) {} //got an error but error message should be displayed in output pane automatmically\n else if (Array.isArray(eval2_result.value)){ //got an array, but is it a do_list of multiple instructions?\n let do_list\n if(!Instruction.is_instructions_array(eval2_result.value)){ //might never hit, but its an precaution\n do_list = [eval2_result.value]\n }\n if (Job.j0 && Job.j0.is_active()) {\n Job.j0.stop_for_reason(\"interrupted\", \"Start Job menu action stopped job.\")\n setTimeout(function() {\n Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos,\n do_list, selection)},\n (Job.j0.inter_do_item_dur * 1000 * 2) + 10) //convert from seconds to milliseconds\n }\n else {\n Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos,\n eval2_result.value, selection)\n }\n }\n else {\n shouldnt(\"Selection for Start job menu item action wasn't an array, even after wrapping [].\")\n }\n }\n else {\n warning(\"When choosing the Eval&Start Job menu item<br/>\" +\n \"with no surrounding Job definition,<br/>\" +\n \"you must select exactly those instructions you want to run.\")\n }\n }\n //we have a job.\n else {\n const eval2_result = eval_js_part2(job_src)\n if (eval2_result.error_type) { } //got an error but error message should be displayed in Output pane automatically\n else {\n let job_instance = eval2_result.value\n if(!sel_is_instructions){\n job_instance.start()\n }\n else if (selected_src.length > 0){ //sel is instructions\n let do_list_result = eval_js_part2(\"[\" + selected_src + \"]\") //even if we only have one instr, this is still correct, esp if that one starts with \"function().\n //if this wraps an extra layer of array around the selected_src, that will still work pretty well.\n if (do_list_result.error_type) { } //got an error but error message should already be displayed\n else {\n job_instance.start({do_list: do_list_result.value})\n }\n }\n else { //no selection, so just start job at do_list item where the cursor is.\n const [pc, ending_pc] = job_instance.init_show_instructions(sel_start_pos, sel_end_pos, start_of_job_pos, job_src)\n job_instance.start({show_instructions: true, inter_do_item_dur: 0.5, program_counter: pc, ending_program_counter: ending_pc})\n }\n }\n }\n }",
"isButtonShouldBeHidden() {\n const { state, entriesType } = this.props;\n\n const selectedEntries = state.selected;\n const currentEntries = state[entriesType];\n\n let isButtonHidden = false;\n\n // Check current entries, if exists, check selected entries\n if(!currentEntries || !currentEntries.items || currentEntries.items.length === 0) {\n isButtonHidden = true;\n } else {\n for(const index in selectedEntries) {\n const entry = selectedEntries[index];\n\n const status = entry.status || entry.status_code;\n\n // If status is `active`\n // if(status === Statuses.ENTRY_ACTIVE) {\n // isButtonHidden = true;\n // break;\n // }\n }\n }\n\n return isButtonHidden;\n }",
"function showHideCompleted(button) {\n\t\tif (showCompleted) {\n\t\t\tshowCompleted = false;\n\t\t\tbutton.innerText = 'Show completed items';\t\n\t\t} else {\n\t\t\tshowCompleted = true;\n\t\t\tbutton.innerText = 'Hide completed items';\n\t\t}\n\t\twriteList();\n\t\tevent.preventDefault();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The label for the previous button. | get prevButtonLabel() {
return {
'month': this._intl.prevMonthLabel,
'year': this._intl.prevYearLabel,
'multi-year': this._intl.prevMultiYearLabel
}[this.calendar.currentView];
} | [
"function showPreviousPreview()\r\n {\r\n if ($label == null)\r\n return;\r\n\r\n log(\"Preview.showPreviousPreview()\");\r\n\r\n // get current label\r\n var prevIndex = $previews.index($label) - 1;\r\n if (prevIndex >= 0)\r\n showPreview(prevIndex);\r\n }",
"prev() {\n\t\tconst prev = this.disabled.previousElementSibling || this.nav.lastElementChild;\n\t\tthis.current = this.navButtons.indexOf(prev);\n\t}",
"function previousClicked() {\n if (currentFeed && currentItemIndex > 0) {\n currentItemIndex--;\n displayCurrentItem();\n }\n }",
"prev() {\n\t\t\tif (this.currPage > 1) {\n\t\t\t\tthis.currPage--;\n\t\t\t\tthis._loadPage();\n\t\t\t}\n\t\t}",
"function onPrevButtonClick() {\n\t\tgotoPrevSlide()\n\t}",
"prevSibling() {\n return this.sibling(-1)\n }",
"_prevHeading() {\n const headings = this._allHeadings();\n // Use `findIndex` to find the index of the currently\n // selected element and subtracts one to get the index of the previous\n // element.\n let newIdx =\n headings.findIndex(headings =>\n headings === document.activeElement) - 1;\n // Add `headings.length` to make sure the index is a positive number\n // and get the modulus to wrap around if necessary.\n return headings[(newIdx + headings.length) % headings.length];\n }",
"function _buildPreviousLink(options, tp){\n\t\tif (options.cp == 1) return '';\n\t\tvar optionsPaging = {};\n\t\tdicUtilObj.deepCopyProperty(options, optionsPaging);\n\t\toptionsPaging.cp = parseInt(optionsPaging.cp) - 1;\n\t\tconsole.log(options);\n return '<a id=\"dic-edi-mailbox-previous\" href=\"'+dicUtilUrl.buildUrlObjQuery(null, optionsPaging)+'\" class=\"navig-prev\" aria-label=\"Previous\">' +\n\t\t\t\t\t'<span class=\"content\" style=\"right: -14px;\">' +\n\t\t\t\t\t'<b>' +\n\t\t\t\t\t\t'Prev: '+ (parseInt(options.ps, 10) * (optionsPaging.cp - 1) + 1) + ' - ' + (parseInt(options.ps, 10) * (optionsPaging.cp)) + \n\t\t\t\t\t '</b>'+\n\t\t\t\t\t'<span/>'+\n\t\t\t\n\t\t\t\t\t'</span>' +\n\t\t\t\t'</a>';\n\t\t\n\t\t\n\t}",
"function previous() {\n // if month equals to the value of 0 so the year will subtracts 1 then month will go to 11 that the value of Dec\n // else just only subtract the month and keep year in the same year\n if (month == 0) {\n year = year - 1;\n month = 11;\n } else {\n month = month - 1;\n }\n showCalendar(month, year);\n}",
"getButtonText() {\n return defaultValue(this.buttonText, this.pointEntities.entities.values.length >= 2\n ? i18next.t(\"models.userDrawing.btnDone\")\n : i18next.t(\"models.userDrawing.btnCancel\"));\n }",
"function setCancelButtonTitle(name) {\n\t\t$cancelButton.html(name);\n\t}",
"selectPrevious() {\n\n // select the previous, or if it is the first entry select the last again\n if (this.selected <= 0) {\n this.selected = this.sequence.length -1;\n }\n else {\n this.selected--;\n }\n\n // highlight the selected entry\n this.highlightSelected();\n\n }",
"getLabel() { return this.labelP.innerText; }",
"get previousVersion() {\n return this._cliConfig.get('previous-version', null);\n }",
"function build_prev_nav(item) {\n\t\t\tif (item.prev_index >= 0) {\n\t\t\t\treturn nav_link(options.prev_link_class, item.prev_href, options.prev_link_text);\n\t\t\t} else {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}",
"function previousQuestion(QuestionID){\n\n\t\tif (!inaction) {\n var currentID = QuestionID.substring(1);\n var nextID = currentID--;\n nextID--;\n\n //Check if next question is answered\n // if ($('#q' + currentID).find('input').hasClass('checked')) {\n // activateNextButton();\n // }else {\n // deactivateNextButton();\n // }\n\n if (nextID <= 1) {\n \tdeactivatePreviousButton();\n } \n \n slideFeature('#' + QuestionID, '#q' + nextID, 500); \n }\n\t}",
"_focusPreviousTab () {\n this.tabs[this.previousTabIndex]\n ? this.tabs[this.previousTabIndex].focus()\n : this.tabs[this.tabs.length - 1].focus()\n }",
"setBackButtonText(text) {\n this._backText = text;\n }",
"goToPreviousSlide() {\n this._goToSlide(this.previousSlideIndex, false, false);\n }",
"function getPreviousQuote() {\n quoteHistory.pop();\n let lastIndex = quoteHistory.pop();\n let lastQuote = quotes[lastIndex.index];\n lastQuote.rgbValue = lastIndex.rgbValue;\n\n // Validation for back button\n if (quoteHistory.length < 1) {\n btnPrevious.setAttribute(\"disabled\", \"true\");\n }\n quoteHistory.push({index: lastIndex.index, rgbValue: lastIndex.rgbValue});\n\n return lastQuote;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Master Server Module Sends the lists of known game servers to game clients, using TCP. Behaviour :: TCP PASSIVE Generates the string to be sent to a game client querying us for game servers list | function generateClientServerList(game){
var response = "\\basic\\\\";
// Servers which reported to us
for(var svr in knownGameServers){ // svr is the key in which the server info is stored into the HashMap
// but the key was stored in the format address:port, therefore,
// svr is already equal to knownGameServers[svr].address + ":" + knownGameServers[svr].port
if(knownGameServers[svr].game == game){
response += "ip\\" + svr + "\\";
}
}
// Servers from other master servers lists
for(var svr in knownGameServersSynced){
if(knownGameServersSynced[svr].game == game && knownGameServers[svr] == null){ // Prevents duplicates
response += "ip\\" + svr + "\\";
}
}
response += "final\\";
return response;
} | [
"function syncWithKnownMasterServer(server){\r\n var VALIDATION = '\\\\gamename\\\\' + server.game +'\\\\location\\\\0\\\\validate\\\\OPNSRCUP\\\\final\\\\'; // Validation answer\r\n var QUERYREQST = '\\\\list\\\\gamename\\\\' + server.game + '\\\\final\\\\' // Query for games list\r\n\r\n var conn = new tcp.Socket();\r\n\r\n conn.setTimeout(10000); // 10 seconds before giving up this connection (should take much less).\r\n\r\n // Connection established\r\n conn.connect(server.port, server.addr, function() {\r\n logMessage(SYNCSYS,\"Syncing with :: \" + server.addr);\r\n });\r\n\r\n // Connection error\r\n conn.on('error', function(err){\r\n logMessage(SYNCSYS,\"Error when querying known master server :: \" + err.toString());\r\n conn.destroy(); // Ends communication\r\n });\r\n\r\n // Data received from queried master server\r\n conn.on('data', function(data) {\r\n var receivedData = data.toString().split('\\\\');\r\n if(receivedData[3] == 'secure'){ // First step, server is challenging us, like this: \\basic\\secure\\XDWAOR\r\n conn.write(VALIDATION); // Answers anything (DeusEx won't mind)\r\n conn.write(QUERYREQST); // Sends the query\r\n }else if(receivedData[receivedData.length - 2] == 'final'){ // Server sent game servers list, like this: \\ip\\255.255.255.255:7778\\ip\\255.255.255.255:7778\\...\\final\r\n for(var entry of receivedData){\r\n var gameSvrAddr = entry.split(':');\r\n if(gameSvrAddr.length == 2){ // Every part of the answer that is a valid game server can be split in two parts with ':'\r\n knownGameServersSynced[entry] = new UnrealGameServer(gameSvrAddr[0], gameSvrAddr[1], server.game, 0);\r\n }\r\n }\r\n conn.destroy(); // We got what we want, let's bail (this is actually how the protocol works)\r\n logMessage(SYNCSYS,\"Success with :: \" + server.addr);\r\n }\r\n });\r\n\r\n conn.on('close', function() {\r\n logMessage(SYNCSYS,\"Ending sync connection with :: \" + server.addr);\r\n });\r\n}",
"static sendAllPlayersMulti(SOCKET_LIST, fullPack){\n for(let i in SOCKET_LIST){\n let socket = SOCKET_LIST[i];\n for(let j in fullPack){\n socket.emit(fullPack[j].message, fullPack[j].data);\n }\n }\n }",
"function send_teams(){\n\t\n\t//Call redis and get the list of teams\n\tvar teams = [];\n\n\n\tsocket.emit('team:list', { data: teams });\n}",
"listSockets() {\n var list = this.players.map(player => player.socketID);\n list.push(this.hostID);\n return list;\n }",
"end(clientList) {\n // Stringifying the json data is an overhead we don't really want.\n // Once we have updated to use binary data this should no longer be an issue.\n const jsonData = JSON.stringify(this.data);\n for (const client of clientList) {\n client.send(jsonData);\n }\n }",
"broadcastPlayerList() {\n var response = [];\n // prepare the data\n this._players.forEach(p => {\n response.push(p.getPublicInfo());\n });\n // Send to all users\n this.emitToRoom(\"player-list\", response);\n }",
"updateHostList() {\n\t\tlet joinableGames = new Map();\n\t\tfor (var [socketID, game] of this.games) {\n\t\t\tif (game && !game.isPlaying && game.players.length < Game.maxPlayers) {\n\t\t\t\tjoinableGames.set(game.id, game.getInfo());\n\t\t\t}\n\t\t}\n\t\tthis.io.to('lobby').emit(ActionNames.UPDATE_HOST_LIST, [...joinableGames.values()].sort((a, b) => {\n\t\t\treturn a.id - b.id;\n\t\t}));\n\t}",
"function masterServer_ConnectWithRequestType(msgType) {\n var wsProtocol = window.location.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n var wsPort = wsProtocol == \"wss://\" ? 7501 : 7500;\n var masterServerIP = \"45.77.216.41\"; //\"0.0.0.0\";//\"master1.mope.io\";\n var conUrl = wsProtocol + masterServerIP + \":\" + wsPort;\n console.log(\"Master server: connecting \" + conUrl + \"...\");\n //console.log(\"Protocol is \" + wsProtocol + \", window protocol is \" + window.location.protocol);\n var masterWs = new WebSocket(conUrl);\n masterWs.binaryType = \"arraybuffer\";\n masterWs.onopen = function() {\n //console.log(\"MasterServer: Connected!\");\n\n //authenticate as client, with correct data request\n var authmsg = new MsgWriter(1);\n var masterServerRequestType = 1; //1- get stats, 2- get best BR server\n authmsg.writeUInt8(msgType);\n //send msg\n masterWs.send(authmsg.dataView.buffer);\n };\n masterWs.onmessage = function(msg) {\n //handle message\n var msg = new MsgReader(new DataView(msg.data));\n var msgType = msg.readUInt8();\n //console.log(\"MasterServer: Msg of type \"+msgType);\n\n switch (msgType) {\n case KMasterServMsg_serverPlayerCounts:\n masterServer_gotReponse_getServerStats(msg);\n break;\n case KMasterServMsg_bestBrServer:\n masterServer_gotRespose_getBestBRServer(msg);\n break;\n\n default:\n console.log(\"Unknown master server msg type \" + msgType);\n break;\n }\n };\n masterWs.onerror = function(err) {\n console.log(\"MasterServer: error connecting!\");\n };\n masterWs.onclose = function(evt) {\n //console.log(\"Disconnected from master server!\");\n };\n}",
"getNodes() {\n this.privKey = tools.createPrivKey();\n this.publicKey = tools.getPublicKey(this.privKey);\n const serverSocket = io_cli.connect(config.mainServer, {\n query: {\n \"link_type\":\"miner\",\n \"port\":this.port,//for test\n \"publickey\":this.publicKey\n }\n });\n serverSocket.on('connect', () => {\n console.log('bootstrapServer is connected');\n serverSocket.emit('allNodes');\n })\n serverSocket.on('disconnect', () => {\n console.log(\"bootstrapServer is disconnected.\")\n })\n serverSocket.on('allNodes_response', (nodes) => {//addresses of nodes\n var isNodes = false;\n for(var each of nodes) {\n if(each == null || each == this.address) continue;\n isNodes = true;\n ((each) => {\n if(this.nodeRoom[each.address]) return;\n var eachSocket = io_cli.connect(each.address, {\n query: {\n \"link_type\":\"miner\",\n \"port\":this.port,//for test\n \"publickey\":this.publicKey\n }\n });\n eachSocket.on('connect', () => {\n console.log(each.address+\" is connected.\");\n this.nodeRoom[each.address] = {socket: eachSocket, publicKey: each.publickey};\n this.setNodeSocketListener(eachSocket, each.address, each.publickey);\n eachSocket.on('disconnect', () => {\n console.log(each.address+\" disconnected\");\n delete this.nodeRoom[each.address];\n delete this.sendBlockchainNode[each.address];\n eachSocket.removeAllListeners();\n })\n })\n })(each)\n }\n if(isNodes == false && this.blockchain.length == 0) {\n this.createGenesisBlock();\n }\n else {\n this.getBlockchain();\n }\n console.log('blockchainState:'+this.blockchainState);\n })\n }",
"function updateGamesList() {\n\tsendMsgToServer(\"games\");\n}",
"function Server() {\n this.sources = [];\n this.buffer_size = NaN; //from server to clients\n this.latency = NaN; //from server to clients\n}",
"function sendServerMsgAll(msg)\n {\n io.sockets.emit('serverMsg', msg);\n }",
"sendUserlist() {\n this.print('Current Users');\n this.print(JSON.stringify(this.users, null, 2));\n this.namespace.emit('username list', this.getUsernames());\n }",
"function syncVideoList()\n { \n io.sockets.emit('videoListSync', videoList);\n }",
"function displayConnections() {\n console.log(\"\\nid:\\tIP Address\\t\\tPort No.\");\n for (i = 0; i < clientSockets.length; i++) {\n var ip = clientSockets[i].request.connection._peername.address;\n\n if (ip == '127.0.0.1') {\n ip = clientIP;\n }\n var port = clientSockets[i].request.connection._peername.port;\n console.log((i + 1) + \"\\t\" + ip + \"\\t\\t\" + port);\n }\n console.log(\"\\n\");\n} // End displayConnections()",
"function syncWithAll(){\r\n for(var svr of knownMasterServers){\r\n syncWithKnownMasterServer(svr);\r\n }\r\n}",
"function send_tcp(addr, path, args) {\n\tvar toks = addr.split('.');\n\tif (toks[toks.length-1] == '255') {\n\t\tfor (var dev_id in dev_dict) {\n \t\tif (dev_dict.hasOwnProperty(dev_id)) {\n\t \tfor (var node_id in dev_dict[dev_id]) {\n\t\t\t\t\tif (dev_dict[dev_id].hasOwnProperty(node_id))\n\t\t\t\t\t\tsend_tcp(dev_dict[dev_id][node_id], path, args);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\toutlet(0, 'host', '127.0.0.1');\n\t\toutlet(0, 'port', pyport);\n\t\toutlet(0, '/tcp', addr, iotport, path, args)\n\t}\n}",
"sendBeakers()\n {\n this.socket.emit('sendRandomBeaker', { beakerC: this.randomBeaker.getBeakerContents() });\n\n this.socket.emit('sendPlayerBeaker', { beakerC: this.beaker.getBeakerContents() });\n\n this.socket.emit(\"sendTime\", {timeArray: this.stopwatch.digit_values});\n\n }",
"_updateGame() {\n this.playerMap.emitCustomToAll('updateGame', (socket) => {\n return this.serverState.toCompressedClientState(socket, this.currentSocketEvent);\n });\n this.serverState.clearEphemeralFields();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if a and b are of equal nonzero length, and their contents are equal, or false otherwise. Note that unlike in compare() zerolength inputs are considered _not_ equal, so this function will return false. | function equal(a, b) {
if (a.length === 0 || b.length === 0) {
return false;
}
return compare(a, b) !== 0;
} | [
"static equal(b1, b2) {\n\n var i,j;\n\n if (b1.size != b2.size) {\n console.log('b1 and b2 are of different sizes');\n return false;\n }\n\n for (i=0; i<b1.size; i++) {\n\n for (j=0; j<b1.size; j++) {\n\n if (b1.board[i][j] !== b2.board[i][j]) {\n return false;\n }\n }\n }\n\n console.log('b1 and b2 are equal');\n return true;\n }",
"function sameLength(string1,string2){\n if(string1.length===string2.length)return true\n return false\n}",
"function arrayOfObjectsEquals(a, b) {\n\n if (a === null || b === null) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n\n a.sort();\n b.sort();\n\n\n for (var i = 0; i < a.length; ++i) {\n if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) {\n return false;\n }\n }\n\n return true;\n}",
"function sameAscii(a, b) {\n\tc = 0;\n\td = 0;\n\t\n\tfor (let i = 0; i < a.length; i++) {\n\t\tc += a.charCodeAt(i);\n\t}\n\t\n\t\tfor (let i = 0; i < b.length; i++) {\n\t\td += b.charCodeAt(i);\n\t}\n\t\n\treturn c === d;\n}",
"function assertEqual(a, b){\n return a_equals_b(a, b);\n }",
"function arePalindromes(a, b) {\n const sortedA = a\n .split(\" \")\n .join(\"\")\n .split(\"\")\n .sort()\n .join(\"\");\n const sortedB = a\n .split(\" \")\n .join(\"\")\n .split(\"\")\n .sort()\n .join(\"\");\n\n return sortedA === sortedB;\n}",
"function sameValueExact(a, b) { // flag for exaxt? which ignores eg 0\n var type = a.type\n\n if (type === \"Dimension\") {\n if (a.val === b.val && a.unit === b.unit)\n return true\n }\n if (type === \"Number\") { // dont exists, only 0?\n // we know b exists, only prop can give us undefined back, so no need to check if b.unit exists\n if (a.val === b.val)\n return false\n }\n if (type === \"Percentage\") {\n if (a.val === b.val)\n return false\n }\n // need to comapre args too..\n if (type === \"Function\") {\n if (isFunctionSame()) // pass arg?\n return false\n }\n\n // value can be auto - so can be ident?\n if (type === \"Identifier\") { // custom or not, WL, trust user.\n return false\n }\n\n}",
"function signaturesAreEqual(a, b) {\n if (a === b) return true;\n if (isprimitive(a) || isprimitive(b)) return a === b;\n\n for (let key in a)\n if (a.hasOwnProperty(key)) {\n if (!b.hasOwnProperty(key)) return false;\n if (!signaturesAreEqual(a[key], b[key])) return false;\n }\n\n for (let key in b)\n if (b.hasOwnProperty(key)) {\n if (!a.hasOwnProperty(key)) return false;\n }\n\n return true;\n}",
"function eqArrs_QMRK_(a1, a2) {\n let ok_QMRK_ = true;\n if( (a1.length == a2.length) ) {\n if (true) {\n a1.forEach(function(v, k) {\n return ((!eq_QMRK_(a2[k], v)) ?\n (ok_QMRK_ = false) :\n null);\n });\n }\n }\n return ok_QMRK_;\n}",
"function isSameLength(word1, word2) {\n // your code here\n return (word1.length === word2.length) ? true : false;\n}",
"function check_eq(a, b) {\n\tcheck_args(a, b);\n\ttoAInt(a).check_eq(b);\n}",
"function sameLength(g1,g2) {\n return g1.hasOwnProperty('coordinates') ? \n g1.coordinates.length === g2.coordinates.length\n : g1.length === g2.length;\n}",
"equals(path, another) {\n return path.length === another.length && path.every((n, i) => n === another[i]);\n }",
"function assertWebNFCMessagesEqual(a, b) {\n assert_equals(a.url, b.url);\n assert_equals(a.data.length, b.data.length);\n for(let i in a.data) {\n let recordA = a.data[i];\n let recordB = b.data[i];\n assert_equals(recordA.recordType, recordB.recordType);\n assert_equals(recordA.mediaType, recordB.mediaType);\n\n if (recordA.data instanceof ArrayBuffer) {\n assert_array_equals(new Uint8Array(recordA.data),\n new Uint8Array(recordB.data));\n } else if (typeof recordA.data === 'object') {\n assert_object_equals(recordA.data, recordB.data);\n }\n\n if (typeof recordA.data === 'number'\n || typeof recordA.data === 'string') {\n assert_true(recordA.data == recordB.data);\n }\n }\n }",
"function xor(a, b) {\n\n if (!!a ^ !!b == 1) {\n return true;\n }\n}",
"function isEqualPass(obj1,obj2){\r\n\t var pw1 = obj1.value;\r\n\t var pw2 = obj2.value;\r\n\t \r\n\t if(pw1.length ==0 || pw2.length ==0){\r\n\t\t return true;\r\n\t }\r\n\t if(pw1 == pw2){\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t return true;\r\n }",
"function equivalent(x,y){\n\tif(JSON.stringify(clone(x)) == JSON.stringify(clone(y))){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n}",
"function statesEqual (a, b) {\n return deepEquals(a, b)\n}",
"static areIdentical(){\n let temp\n\n for(let i = 0; i < arguments.length; i++){\n let argument = arguments[i]\n\n // handle NaN\n if(isNaN(argument.h)) argument.h = argument.h.toString()\n if(isNaN(argument.m)) argument.m = argument.m.toString()\n\n // handle string input\n if(typeof argument.h === \"string\") argument.h = parseInt(argument.h)\n if(typeof argument.m === \"string\") argument.m = parseInt(argument.m)\n\n // if temp is empty -> this is the first argument, store the first temp\n if(!temp){\n temp = argument\n continue\n }\n\n // if the temp and the current argument are not identical, return false\n if(argument.h !== temp.h || argument.m !== temp.m || argument.pm !== temp.pm) return false\n\n // store the current argument as the new temp\n temp = argument\n }\n\n return true\n }",
"function expressionsAreEqual(a, b) {\n if (null == a || \"object\" != typeof a) return a === b;\n if (a instanceof Array && b instanceof Array) {\n if (a.length != b.length) return false;\n for (var i = 0, len = a.length; i < len; i++) {\n if (!expressionsAreEqual(a[i], b[i])) return false;\n }\n return true;\n } else if (a instanceof Object && b instanceof Object) {\n let l = ['oper',\n 'impl',\n 'args',\n 'ctype',\n 'stack',\n 'name',\n 'modifs',\n 'arglist',\n 'value',\n 'real',\n 'imag',\n 'key',\n 'obj',\n 'body'\n ]\n for (let i = 0; i < l.length; i++) {\n let attr = l[i];\n if (!expressionsAreEqual(a[attr], b[attr])) return false;\n }\n return true;\n }\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
makes the yellow cross given a "line" yellow setup | function solveYellowLine(cube) {
F(cube);
R(cube);
U(cube);
Ri(cube);
Ui(cube);
Fi(cube);
//console.log("front, right, up, right inverse, up inverse, front inverse (yellow cross created)");
commandSolveYellowCross += "<br>Solves yellow 'line': front, right, up, right inverse, up inverse, front inverse, ";
commandSolveAllEnd += "front, right, up, right inverse, up inverse, front inverse, ";
} | [
"function dibujarLinea(color, x_inicial, y_inicial, x_final, y_final)\n{\n lienzo.beginPath();\n lienzo.strokeStyle = color;\n lienzo.moveTo(x_inicial, y_inicial);\n lienzo.lineTo(x_final, y_final);\n lienzo.stroke();\n lienzo.closePath();\n}",
"function drawCross(x, y, color){\n\tctx.strokeStyle = color;\n\tctx.beginPath();\n\tctx.moveTo(x,y+4);\n\tctx.lineTo(x,y-4);\n\tctx.closePath();\n\tctx.stroke();\n\tctx.beginPath();\n\tctx.moveTo(x-4,y);\n\tctx.lineTo(x+4,y);\n\tctx.closePath();\n\tctx.stroke();\n\tctx.fillStyle = \"black\";\n\tctx.strokeStyle = \"black\";\n}",
"function diagonal(x,y){\nif (x < 300 && y < 200){\n ctx.strokeStyle = 'green'\n} else {\n ctx.strokeStyle = 'red'\n}\nctx.beginPath();\nctx.moveTo(x,y);\nctx.lineTo(x+100,y+100);\nctx.stroke();\n}",
"function hiliteEmlLine(docObj, line) {\n var bgColor;\n if (top.HiliteCodeStatus)\n bgColor = \"#66CCFF\";\n else\n bgColor = \"#E8D152\";\n // unhighlight\n if (typeof docObj.HiliteLine != \"undefined\") {\n\ttrObj = docObj.getElementById(\"LN_\"+docObj.HiliteLine);\n\tif (trObj != null) {\n\t trObj.style.backgroundColor = \"\";\t\t\t\n\t}\n }\t\n // hilighlight\n trObj = docObj.getElementById(\"LN_\"+line);\n if (trObj != null) {\n\ttrObj.style.backgroundColor = bgColor;\n\tdocObj.HiliteLine = line;\n }\n}",
"function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}",
"static line(spec) {\n return new LineDecoration(spec);\n }",
"vShelf(x, y) {\n noStroke();\n for (let i = 0; i < 3; i++) {\n fill(51, 32, 0);\n rect(x, y + this.pxl * i, this.pxl, this.pxl);\n }\n }",
"function lineSegment(x, y, w, h) {\r\n fill(255, 234, 0);\r\n rect(x, y - 4, w, h);\r\n}",
"function eyeBlink(x,y,eyeSize,pupilSize,color_type){\n\t\n //draw eyelid\n fill(color_type);\n ellipse(x,y,eyeSize,eyeSize);\n \n}",
"function toggleLine(selectedLineData, clickedOn, newThickness) {\n lines = d3.selectAll('polyline')\n for (i = 0; i < lines.length; i++) {\n for (j = 0; j < lines[i].length; j++) {\n if (lines[i][j].__data__['State'] == selectedLineData['State']) {\n if (clickedOn) {\n lines[i][j].style.stroke = mouseOverColor\n } else {\n lines[i][j].style.stroke = getStroke(lines[i][j].__data__)\n }\n lines[i][j].style.strokeWidth = newThickness\n }\n }\n }\n}",
"function yellowSquare() {\n if(mouseX <= 375 && mouseX >= 25 && mouseY >= 425 && mouseY <= 775 && mouseIsPressed) {\n fill(255, 230, 128);\n } else {\n fill(235, 190, 0);\n }\n rect(displacement, height/2 + displacement, 350, 350);\n}",
"function dashedLine(value,index,arg){\n tl.to(value,2,{opacity:1},0)\n .to(value,1.5,{opacity:0},2.5);\n\n }",
"function dottedLine(x, y, w, h) {\r\n fill(\"grey\");\r\n rect(x, y - 4, 800, 5);\r\n for (line = 0; line < 15; line++) {\r\n lineSegment(line * 80 + 1, y, 40, 5);\r\n }\r\n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"setCrosshairsColor(color) {\n if (this._crossHairs) {\n let [res_, clutterColor] = Clutter.Color.from_string(color);\n this._crossHairs.setColor(clutterColor);\n }\n }",
"function placeYellowCross(cube) {\n if ((cube[up][0][1] != 'Y') && (cube[up][1][0] != 'Y') && (cube[up][2][1] != 'Y') && (cube[up][1][2] != 'Y')) {\n solveYellowDot(cube);\n }\n else if ((cube[up][0][1] != 'Y') && (cube[up][2][1] != 'Y') && (cube[up][1][0] == 'Y') && (cube[up][1][2] == 'Y')) {\n U(cube);\n //console.log(\"up\");\n commandSolveYellowCross += \"<br> Rotates top to align yellow 'line': up, \";\n commandSolveAllEnd += \"up, \";\n solveYellowLine(cube);\n }\n else if ((cube[up][0][1] == 'Y') && (cube[up][2][1] == 'Y') && (cube[up][1][0] != 'Y') && (cube[up][1][2] != 'Y')) {\n solveYellowLine(cube);\n }\n else if ((cube[up][0][1] == 'Y') && (cube[up][1][0] == 'Y') && (cube[up][2][1] != 'Y') && (cube[up][1][2] != 'Y')) {\n solveYellowV(cube);\n }\n else if ((cube[up][0][1] != 'Y') && (cube[up][1][0] == 'Y') && (cube[up][2][1] == 'Y') && (cube[up][1][2] != 'Y')) {\n Ui(cube);\n //console.log(\"up inverse\");\n commandSolveYellowCross += \"<br>Rotates top to align yellow 'V': up inverse, \";\n commandSolveAllEnd += \"up inverse, \";\n solveYellowV(cube);\n }\n else if ((cube[up][0][1] != 'Y') && (cube[up][1][0] != 'Y') && (cube[up][2][1] == 'Y') && (cube[up][1][2] == 'Y')) {\n U(cube); U(cube);\n //console.log(\"up, up\");\n commandSolveYellowCross += \"<br>Rotates top to align yellow 'V': up, up, \";\n commandSolveAllEnd += \"up, up, \";\n solveYellowV(cube);\n }\n else if ((cube[up][0][1] == 'Y') && (cube[up][1][0] != 'Y') && (cube[up][2][1] != 'Y') && (cube[up][1][2] == 'Y')) {\n U(cube);\n //console.log(\"up\");\n commandSolveYellowCross += \"<br>Rotates top to align yellow 'V': up, \";\n commandSolveAllEnd += \"up, \";\n solveYellowV(cube);\n }\n}",
"makeWell() {\n stroke(116, 122, 117);\n strokeWeight(2);\n fill(147, 153, 148);\n ellipse(125, 75, this.pxl, this.pxl);\n fill(0, 0, 255);\n ellipse(125, 75, this.pxl - 10, this.pxl - 10);\n }",
"function ToggleLineDisplay( done ){\n\n var active = done.active ? false : true;\n var opacity = active ? 0 : 1;\n d3.select( '#line_' + done.key ).style( 'opacity', opacity );\n done.active = active;\n\n}",
"function hLine(i){\n var x1 = scaleUp(0);\n var x2 = scaleUp(boardSize - 1);\n var y = scaleUp(i); \n drawLine(x1, x2, y, y);\n //alert(\"i:\" + i+ \" x1:\"+x1+ \" x2:\"+x2+\" y1:\"+y+ \" y2:\"+y);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function performs the fake local storage update, so the IE gets the latest token instead of returning the cached localStorageValue | function performFakeLocalStorageUpdate() {
var dummy_key = 'dummy_key';
localStorage.setItem(dummy_key, dummy_key);
localStorage.removeItem(dummy_key);
} | [
"function getLocalStorage() {\n return localStorage;\n}",
"function getToken() {\n return localStorage.getItem('token');\n}",
"function getToken() {\n\treturn localStorage.getItem('token')\n}",
"function updateLocalStorage(){\r\n localStorage.setItem(\"savedTask\",JSON.stringify(currentTasks));\r\n return JSON.parse(localStorage.getItem(\"savedTask\"));\r\n}",
"function fetchTokens() {\n _.each(['fbtoken', 'dropboxtoken', 'livetoken'], function(key) {\n var token = localStorage.getItem(key);\n if (token != null) {\n Storage.getInstance().set(key, token);\n } \n Storage.getInstance().get(key).then(function (value) {\n console.log(key + \" \" + value);\n })\n });\n }",
"function setLocalStorage(key, value) {\n var ood_key = KEY_PREFIX + key;\n localStorage.setItem(ood_key, value);\n return null;\n}",
"renewTokens() {\n return new Promise((resolve, reject) => {\n const isUserLoggedIn = localStorage.getItem(localStorageKey);\n if (isUserLoggedIn !== \"true\") {\n return reject(\"Not logged in\");\n }\n\n webAuth.checkSession({}, (err, authResult) => {\n if (err) {\n reject(err);\n } else {\n this.localLogin(authResult);\n resolve(authResult);\n }\n });\n });\n }",
"checkToken() {\n if(localStorage.getItem(\"token_time\") != null) {\n if(new Date().getTime() - new Date(localStorage.getItem(\"token_time\")).getTime() > 60000) {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n console.log(\"update token\");\n this.updateToken();\n }\n } else {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n this.updateToken();\n }\n }",
"function getStorage(key) {\n\n var now = Date.now(); //epoch time, lets deal only with integer\n // set expiration for storage\n var expiresIn = localStorage.getItem(key+'_expiresIn');\n if (expiresIn===undefined || expiresIn===null) { expiresIn = 0; }\n\n if (expiresIn < now) {// Expired\n removeStorage(key);\n return {};\n } else {\n try {\n var value = JSON.parse(localStorage.getItem(key)) || {};\n return value;\n } catch(e) {\n console.log('getStorage: Error reading key ['+ key + '] from localStorage: ' + JSON.stringify(e) );\n return null;\n }\n }\n}",
"function getToken() {\n oldToken = token;\n var request = new XMLHttpRequest();\n request.open(\"POST\", \"_assets/php/getToken.php\", true);\n request.send();\n request.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n token = request.responseText;\n }\n };\n}",
"function removeCurrentUserIDFromLocalStorage() \r\n{\r\n localStorage.removeItem(\"currentUserID\");\r\n}",
"static async setLocalStorageJson(key, value) {\n return await window.localStorage.setItem(key, JSON.parse(value));\n }",
"function updateLocalStorage() {\n\tlocalStorage.setItem('transactions', JSON.stringify(transactions));\n}",
"function AuthToken($window){\n var authTokenFactory = {}\n\n //get the token out of local storage\n authTokenFactory.getToken = function(){\n return $window.localStorage.getItem('token')\n }\n\n //set the token or clear the token\n authTokenFactory.setToken = function(token){\n if(token)\n $window.localStorage.setItem('token', token)\n else {\n $window.localStorage.removeItem('token')\n }\n }\n\n return authTokenFactory\n }",
"function loginStatusToStorage() {\n\tlocalStorage.loggedIn = loggedIn;\n\tlocalStorage.loggedInID = loggedInID;\n}",
"function browserCacheRestore() \n\t{\n\t\t// Browser based presistance local storage\n\t\t// Retrieve the object from storage\n\t\tvar retrievedObject = localStorage.getItem('savedObject');\n\t\tif(retrievedObject)\n\t\t{\n\t\t\t// JSON.parse => Converts string form of object in to original Json object form\n\t\t\traceData = JSON.parse(retrievedObject);\n\t\t\t// console.log('retrievedObject: ', JSON.parse(retrievedObject));\n\t\t\tpageNoTotal = raceData.length;\n\t\t}\t\t\n\t}",
"function getStoredToken() {\n return authVault.getToken();\n }",
"localLogin(authResult) {\n this.idToken = authResult.idToken;\n this.profile = authResult.idTokenPayload;\n\n // convert the JWT expiry time from seconds to milliseconds\n this.tokenExpiry = new Date(this.profile.exp * 1000);\n\n // save the access token\n this.accessToken = authResult.accessToken;\n this.accessTokenExpiry = new Date(Date.now() + authResult.expiresIn * 1000);\n\n localStorage.setItem(localStorageKey, \"true\");\n\n this.emit(loginEvent, {\n loggedIn: true,\n profile: this.profile,\n state: authResult.appState || {}\n });\n }",
"function storeAccessToken(token) {\n console.log('Storing access token');\n chrome.storage.local.set({token: token}, function() {\n if (chrome.runtime.lastError) {\n console.log('Error: unable to store access token');\n console.log(chrome.runtime.lastError);\n document.getElementById('oauthMessage').innerHTML=\n \"<p>Unable to store Access Token.</p>\";\n }\n else {\n console.log('Successfully stored access token');\n document.getElementById('oauthMessage').innerHTML=\n \"<p>Successfully authenticated with Intercom.</p>\"+\n \"<p>Click the OAuth button if you'd like to generate a new Access Token:</p>\";\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans the FM band upwards. Called when the 'Scan >>' button is pressed. | function scanUp() {
fmRadio.scan(
upconvert(band.getMin()),
upconvert(band.getMax()),
band.getStep());
} | [
"function scanDown() {\n fmRadio.scan(\n upconvert(band.getMin()),\n upconvert(band.getMax()),\n -band.getStep());\n }",
"onScanFinished_() {\n this.scanner_ = null;\n }",
"onScanCompleted_() {\n if (this.scanCancelled_) {\n return;\n }\n\n this.processNewEntriesQueue_.run(callback => {\n // Call callback first, so isScanning() returns false in the event\n // handlers.\n callback();\n dispatchSimpleEvent(this, 'scan-completed');\n });\n }",
"function scanOff() {\n clearTimeout(scanTime);\n oneSwitchGoing = false;\n}",
"function update() {\n // populate the analyser buffer with frequency bytes\n analyser.getByteFrequencyData(buffer);\n // look for trigger signal\n for (var i = 0; i < analyser.frequencyBinCount; i++) {\n var percent = buffer[i] / 256;\n // TODO very basic / naive implementation where we only look\n // for one bar with amplitude > threshold\n // proper way will be to find the fundamental frequence of the square wave\n if (percent > config.threshold) {\n events.dispatch('signal');\n return;\n }\n }\n}",
"function scan() {\n var scanner = cordova.require(\"cordova/plugin/BarcodeScanner\");\n\n scanner.scan(\n function (result) {\n if(result.cancelled){ //Go back to the main page if no luck scanning\n // Stop the currently playing song if one is playing\n stopAudio(); \n $.mobile.changePage('#home');\n } else {\n // Stop the currently playing song if one is playing\n stopAudio(); \n // retrieve the state url from the \"song\" string via AJAX call (TODO).\n state = result.text; \n // Navigate to the page specified by first part of string. \n $.mobile.changePage( '#second' ); \n // Automatically start playback of the state song (from local asset.)\n updateState();\n }\n }, \n function (error) {\n alert(\"Scanning failed: \" + error);\n }\n );\n}",
"function skipAhead(event) {\n var skipTo = event.target.dataset.seek\n ? event.target.dataset.seek\n : event.target.value;\n moveTo(skipTo);\n }",
"function switchBand() {\n saveCurrentStation();\n var bands = Bands[settings['region']];\n var bandNames = [];\n for (var n in bands) {\n if (bands.hasOwnProperty(n)) {\n if (!bands[n].getMode()['upconvert']\n || settings['useUpconverter']\n || n == band.getName()) {\n bandNames.push(n);\n }\n }\n }\n if (bandNames.length == 1) {\n return;\n }\n bandNames.sort();\n for (var i = 0; i < bandNames.length; ++i) {\n if (!band || bandNames[i] == band.getName()) {\n selectBand(bands[bandNames[(i + 1) % bandNames.length]]);\n return;\n }\n }\n }",
"cancelScan() {\n if (this.scanCancelled_) {\n return;\n }\n this.scanCancelled_ = true;\n if (this.scanner_) {\n this.scanner_.cancel();\n }\n\n this.onScanFinished_();\n\n this.processNewEntriesQueue_.cancel();\n dispatchSimpleEvent(this, 'scan-cancelled');\n }",
"slideBack() {\n this.slideBy(-this.getSingleStep());\n }",
"function rew_OnClick()\n{\n\ntry {\n\tDVD.PlayBackwards(DVDOpt.BackwardScanSpeed);\n}\n\ncatch(e) {\n e.description = L_ERRORUnexpectedError_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}",
"function moveDown (){\n\t\tunDraw();\n\t\tcurrentPosition += width;\n\t\tdraw();\n\t\tfreeze();\n\t}",
"function beforeMove(){\n sumInFront = 0;\n numInFront = 0;\n }",
"function fwd_OnClick()\n{\n\ntry {\n\tDVD.PlayForwards(DVDOpt.ForwardScanSpeed);\n}\n\ncatch(e) {\n e.description = L_ERRORUnexpectedError_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}",
"function findAndDisplay(event) {\r\n searchBluetoothDevices();\r\n displayDevices();\r\n}",
"start() {\n // Play song, running samples through a bitcrusher under user control.\n this.song_ =\n new AudioBufferSourceNode(this.context_, {buffer: this.songBuffer});\n this.song_.connect(this.bitcrusher_.input);\n\n this.song_.onended = () => {\n this.sourceButton_.enable();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }\n this.song_.start();\n this.bitDepthSlider_.enable();\n this.reductionSlider_.enable();\n }",
"upSlider() {\n this.y -= this.sliderSpeed;\n this.y = (this.y < 0 ? 0 : this.y);\n }",
"scan_() {\n const fxElements = this.root_.querySelectorAll('[amp-fx]');\n iterateCursor(fxElements, fxElement => {\n if (this.seen_.includes(fxElement)) {\n return;\n }\n\n // Don't break for all components if only a subset are misconfigured.\n try {\n this.register_(fxElement);\n this.seen_.push(fxElement);\n } catch (e) {\n rethrowAsync(e);\n }\n });\n }",
"function previousClicked() {\n if (currentFeed && currentItemIndex > 0) {\n currentItemIndex--;\n displayCurrentItem();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: Q Description: Q is a vectorbased functional paradigm programming language built into the kdb+ database. (K/Q/Kdb+ from Kx Systems) | function q(hljs) {
const KEYWORDS = {
$pattern: /(`?)[A-Za-z0-9_]+\b/,
keyword:
'do while select delete by update from',
literal:
'0b 1b',
built_in:
'neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum',
type:
'`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid'
};
return {
name: 'Q',
aliases: [
'k',
'kdb'
],
keywords: KEYWORDS,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
]
};
} | [
"function getIndexQ() {\n for (let i = d.length - 1; i >= 0; i--) {\n if (d.substring(i, i + 1) === 'Q') {\n return i\n }\n }\n return 0\n }",
"function QingVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}",
"async query(context, q) {\n return new Promise((resolve) => {\n axios({\n method: \"post\",\n url: `${process.env.VUE_APP_MAIN_URL}/${process.env.VUE_APP_GRAPHQL_URL}`,\n data: { query: `query { ${q} }` }\n }).then((res) => {\n resolve(res.data.data)\n }).catch((err) => {\n console.error(err.response)\n })\n })\n }",
"function qeval(expression) {\n \"use strict\";\n return evaluate(expressionToTree(expression)).toString();\n}",
"qp(val) {\n this._qp = val;\n return this;\n }",
"function update()\n{\n\tq = document.getElementById(\"queries\").value;\n\tyasgui.current().yasqe.setValue(queries[q]);\n}",
"function askQ(qArray,toc,sections){\n let ans = [];\n inquirer.prompt(qArray).then((ans) => {\n createReadme(ans,toc,sections);\n}).catch(err => {console.log(err)})\n}",
"function MEXQ_InputQuestion(el_input){\n console.log(\"--- MEXQ_InputQuestion ---\")\n //console.log(\"el_input.id: \", el_input.id)\n // el_input.id = el_input.id: idMEXq_1_1\n //const q_number_str = (el_input.id) ? el_input.id[10] : null;\n const el_id_arr = el_input.id.split(\"_\")\n const partex_pk = (el_id_arr && el_id_arr[1]) ? Number(el_id_arr[1]) : null;\n const q_number = (el_id_arr && el_id_arr[2]) ? Number(el_id_arr[2]) : null;\n\n if (partex_pk && q_number){\n // open-question input has a number (8)\n // multiplechoice-question has one letter, may be followed by a number as score (D3)\n let new_max_char = \"\", new_max_score_str = \"\", new_max_score = \"\", msg_err = \"\";\n const input_value = el_input.value;\n\n console.log(\" input_value: \", input_value)\n // lookup assignment, create if it does not exist\n const p_dict = mod_MEX_dict.partex_dict[partex_pk];\n if (!(q_number in p_dict.a_dict)){\n p_dict.a_dict[q_number] = {};\n };\n const q_dict = p_dict.a_dict[q_number];\n\n// - split input_value in first charactes and the rest\n const first_char = input_value.charAt(0);\n const remainder = input_value.slice(1);\n\n console.log(\" first_char: \", first_char)\n console.log(\" remainder: \", remainder)\n// check if first character is a letter or a number => is multiple choice when a letter\n // !!Number(0) = false, therefore \"0\" must be filtered out with Number(first_char) !== 0\n const is_multiple_choice = (!Number(first_char) && Number(first_char) !== 0 );\n\n if(is_multiple_choice){\n new_max_char = (first_char) ? first_char.toUpperCase() : \"\";\n const remainder_int = (Number(remainder)) ? Number(remainder) : 0;\n new_max_score_str = (remainder_int > 1) ? remainder : \"\";\n } else {\n new_max_score_str = input_value;\n };\n\n console.log(\" is_multiple_choice: \", is_multiple_choice)\n console.log(\" >> new_max_score_str: \", new_max_score_str)\n// +++++ when input is question:\n if (!mod_MEX_dict.is_keys_mode){\n if (new_max_char){\n // Letter 'A' not allowed, only 1 choice doesn't make sense,\n // also X,Y,Z not allowed because 'x' value is used for blank\n if(!\"BCDEFGHIJKLMNOPQRSTUVW\".includes(new_max_char)){\n msg_err = loc.err_list.Character + \" '\" + first_char + \"'\" + loc.err_list.not_allowed +\n \"<br>\" + loc.err_list.character_mustbe_between;\n };\n };\n// - validate max_score\n if (new_max_score_str){\n new_max_score = Number(new_max_score_str);\n // the remainder / modulus operator (%) returns the remainder after (integer) division.\n if (!new_max_score || new_max_score % 1 !== 0 || new_max_score < 1 || new_max_score > 99) {\n if (msg_err) {msg_err += \"<br><br>\"}\n msg_err += loc.Maximum_score + \" '\" + new_max_score_str + \"'\" + loc.err_list.not_allowed +\n \"<br>\" + loc.err_list.maxscore_mustbe_between;\n };\n };\n\n// - show message when error, restore input in element\n if (msg_err) {\n const old_max_char = (q_dict.max_char) ? q_dict.max_char : \"\";\n const old_max_score = (q_dict.max_char) ?\n // '1' is default max_score when max_char, don't show a_dict\n (q_dict.max_score > 1) ? q_dict.max_score : \"\" :\n (q_dict.max_score) ? q_dict.max_score : \"\";\n const old_value = old_max_char + old_max_score;\n el_input.value = (old_value) ? old_value : null;\n\n el_mod_message_container.innerHTML = msg_err;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n } else {\n\n// - put new value in element\n const new_value = new_max_char + ( (new_max_score) ? new_max_score : \"\" );\n\n el_input.value = new_value;\n add_or_remove_class(el_input, \"border_invalid\", !el_input.value)\n\n// - put new value in mod_MEX_dict.p_dict.a_dict.q_dict\n q_dict.max_char = (new_max_char) ? new_max_char : \"\";\n q_dict.max_score = (new_max_score) ? new_max_score : 0;\n }\n\n MEXQ_calc_max_score(partex_pk);\n\n// +++++ when input is keys:\n // admin mode - keys - possible answers entered by requsr_role_admin\n } else {\n\n //console.log(\"q_dict: \", q_dict)\n\n const max_char_lc = (q_dict.max_char) ? q_dict.max_char.toLowerCase() : \"\";\n\n //console.log(\"max_char_lc\", max_char_lc)\n //console.log(\"is_multiple_choice\", is_multiple_choice)\n //console.log(\"mod_MEX_dict.partex_dict\", mod_MEX_dict.partex_dict)\n\n// answer only has value when multiple choice question. one or more letters, may be followed by a number as minimum score (ca3)\n if (!q_dict.max_char){\n el_mod_message_container.innerHTML = loc.err_list.This_isnota_multiplechoice_question;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n } else {\n\n if (input_value){\n let new_keys = \"\", min_score = null, pos = -1;\n for (let i = 0, len=input_value.length; i < len; i++) {\n const char = input_value[i];\n // !!Number(0) = false, therefore \"0\" must be filtered out with Number(first_char) !== 0\n const is_char = (!Number(char) && Number(char) !== 0 )\n if(!is_char){\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else {\n const char_lc = char.toLowerCase();\n //console.log(\"char_lc\", char_lc)\n //console.log(\"max_char_lc\", max_char_lc)\n // y, z are not allowed because 'x' value is used for blank\n if(!\"abcdefghijklmnopqrstuvwx\".includes(char_lc)){\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else if ( new_keys.includes(char_lc)) {\n msg_err += loc.Key + \" '\" + char + \"' \" + loc.err_list.exists_multiple_times + \"<br>\";\n } else if (char_lc > max_char_lc ) {\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else {\n new_keys += char_lc;\n }\n }\n } // for (let i = 0, len=input_value.length; i < len; i++) {\n// - show message when error, delete input in element and in mod_MEX_dict.keys_dict\n if (msg_err){\n msg_err += loc.err_list.key_mustbe_between_and_ + max_char_lc + \"'.\";\n el_input.value = null;\n q_dict.keys = \";\"\n\n el_mod_message_container.innerHTML = msg_err;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n\n } else {\n// - put new new_keys in element and in mod_MEX_dict.keys_dict\n el_input.value = (new_keys) ? new_keys : null;\n q_dict.keys = (new_keys) ? new_keys : \"\";\n }\n// - delete if input_value is empty\n } else {\n q_dict.keys = \"\";\n };\n }; // if (!is_multiple_choice)\n };\n MEXQ_calc_amount_maxscore()\n } ; // if (q_number)\n }",
"measure(q, b) {\n if (q >= this.numQubits) {\n throw 'Index for qubit out of range.';\n }\n if (b >= this.numClbits) {\n throw 'Index for output bit out of range.';\n }\n this.data.push('m', q, b);\n return this;\n}",
"function getQuestion() {\n \n \n }",
"function qexpr(expr) {\n if( expr instanceof Expr ) {\n return expr.toString();\n } else {\n return quoteIdentifier(expr);\n }\n}",
"confirm(q) {\n var res;\n\n //(1) arguments\n if (typeof(q) == \"string\") q = {name: q};\n\n //(2) prompt\n if (this.responses.hasOwnProperty(q.name)) res = ([true, \"true\", \"yes\"].indexOf(this.responses[q.name]) >= 0);\n else res = inquirer.confirm(Object.assign(getQOptions(this.params[q.name]), q));\n\n this.answers[q.name] = res;\n\n //(3) return\n return res;\n }",
"async function test_14_in_params()\n{\n // TODO not expecting this to work yet.\n console.log(\"*** test_14_in_params ***\");\n // initialize a new database\n let [ db, retrieve_root ] = await TU.setup();\n\n // insert data\n const statements = [\n [ DT.addK, \"bob\", K.key(\":name\"), \"Bobethy\" ],\n [ DT.addK, \"bob\", K.key(\":likes\"), \"sandra\" ],\n [ DT.addK, \"sandra\", K.key(\":name\"), \"Sandithan\"]];\n\n db = await DB.commitTxn( db, statements );\n\n // query the data\n const q = Q.parseQuery(\n [Q.findK, \"?a\", \"?b\", \"?c\",\n Q.inK, \"$\", \"?b\", \"?c\",\n Q.whereK, \n [\"?a\", \"?b\", \"?c\"],\n ]\n );\n const r = await Q.runQuery( db, q, K.key( \":name\" ), \"Bobethy\" );\n\n console.log(\"r14\", r);\n assert(\n r.length === 1 && \n r[0][2] === \"Bobethy\", \n \"Query returned an unexpected value\");\n console.log(\"*** test_14_in_params PASSED ***\");\n\n}",
"function eq_ques_(order0) /* (order : order) -> bool */ {\n return (order0 === 2);\n}",
"function formVector(p, q)\n{\n var pq = {lantitude: 0.0, longitude: 0.0, height: 0.0};\n pq.lantitude = q.lantitude - p.lantitude;\n pq.longitude = q.longitude - p.longitude;\n pq.height = q.height - p.height;\n return pq;\n}",
"toggleQ(x){\n if(this.questypes.indexOf(x)!==-1){\n this.selectedQuesTypes.push(x);//add to selectedQuesTypes\n this.questypes.splice(this.questypes.indexOf(x),1);//pop from total questypes\n }\n else{\n this.questypes.push(x);//add to all questypes\n this.selectedQuesTypes.splice(this.selectedQuesTypes.indexOf(x),1);//pop from selectedQuesTypes\n }\n }",
"h(q) {\n this.data.push('h', q);\n return this;\n }",
"function pochisq(x, df) {\n var a, y, s;\n var e, c, z;\n var even; /* True if df is an even number */\n\n var LOG_SQRT_PI = 0.5723649429247000870717135; /* log(sqrt(pi)) */\n var I_SQRT_PI = 0.5641895835477562869480795; /* 1 / sqrt(pi) */\n\n if (x <= 0.0 || df < 1) {\n return 1.0;\n }\n\n a = 0.5 * x;\n even = !(df & 1);\n if (df > 1) {\n y = ex(-a);\n }\n s = (even ? y : (2.0 * poz(-Math.sqrt(x))));\n if (df > 2) {\n x = 0.5 * (df - 1.0);\n z = (even ? 1.0 : 0.5);\n if (a > BIGX) {\n e = (even ? 0.0 : LOG_SQRT_PI);\n c = Math.log(a);\n while (z <= x) {\n e = Math.log(z) + e;\n s += ex(c * z - a - e);\n z += 1.0;\n }\n return s;\n } else {\n e = (even ? 1.0 : (I_SQRT_PI / Math.sqrt(a)));\n c = 0.0;\n while (z <= x) {\n e = e * (a / z);\n c = c + e;\n z += 1.0;\n }\n return c * y + s;\n }\n } else {\n return s;\n }\n }",
"visitStorage_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function startQuizz() {\n setPreviousTime(currentDate.getTime())\n addTimers();\n setQuestionNumber(0);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Submit, format and append winner input data | function submitWinners () {
// Reset winners beyond the initial call, and set the new contestants for the new bracket
if (winners[0] != null) {
contestants = winners.slice(0);
winners = [];
}
// Gather up checkbox data
var tempWinners = $("input[type|='radio']");
// Build up the winners array with those contestants who correspond to the checked boxes
for (var i = 0; i < tempWinners.length; i++) {
if (tempWinners[i].checked === true) {
winners.push(contestants[i]);
// Highlight the winner's position in the old bracket with a nice green
$(tempWinners[i]).parent().css("background-color", "#b0ef1c");
}
}
// Get rid of the old boxes
$("input[type|='radio']").remove();
var newQual = "";
// Set bracket id
qual_id += 1;
// If there's only one victor, apply some special formatting to congratulate them!
if (winners.length === 1) {
// Append a div to display the bracket data in
$("#bracketField").append('<p class="round">Winner</p><div class="qualField" id="qual_' + qual_id +'"></div>');
newQual += '<h1 class="winner">CONGRATULATIONS</h1>';
//newQual += '<div class="vsPair"><p>' + winners[0] + '</p></div>'
newQual += '<h1 class="winner">' + winners[0].toUpperCase() + '!</h1>';
var losers = "";
// Check for the unfortunate loser(s) of the final battle
for (var i = 0; i < contestants.length; i++) {
if (winners[0] != contestants[i]) {
losers += ", " + contestants[i];
}
}
// Give your heartfelt condolences
newQual += '<h1 class="loser">TOO BAD FOR YOU' + losers.toUpperCase() + '.</h1>';
// Append the formatted data to the bracket, and display the appropriate buttons
$('#qual_' + qual_id).append(newQual);
$("#submitWinners").hide();
}
// If not, format winner data in a plain manner
else {
// Append a div to display the bracket data in
$("#bracketField").append('<p class="round">Round ' + qual_id + '</p><div class="qualField" id="qual_' + qual_id +'"></div>');
for (var i = 0; i < winners.length; i++) {
// Determine if it's the first contestant of a pair, or not
// And then apply the proper formatting for it
if (i % 2 === 0) {
newQual += ' <div class="vsPair"><p>' + winners[i] + '<input type="radio" name="vsBtn_' + i + '" checked /></p>'
}
else {
newQual += '<span>vs</span><p>' + winners[i] + '<input type="radio" name="vsBtn_' + (i - 1) + '" /></p></div>'
// We add an invisible box between pairings
// This is just for spacing reasons
if (winners.length > 2 && i != (winners.length - 1)) {
newQual += '<div class="invisibleBox"></div>';
}
}
}
// Append the formatted data to the bracket
$('#qual_' + qual_id).append(newQual);
}
} | [
"function processOpnFrmData(event) {\r\n\r\n\r\n event.preventDefault();\r\n\r\n let nopBoughgame = \"Never Bought Game\"\r\n // Read and adjust data from the form\r\n const nopOpn = document.getElementById(\"story\").value.trim();\r\n const nopName = document.getElementById(\"name\").value.trim();\r\n const nopEmail = document.getElementById(\"email\").value.trim();\r\n const nopGender = document.getElementById(\"Gender\").value.trim();\r\n const nopDoyoubuygames = document.getElementById(\"Doyoubuygames\").checked;\r\n if (document.getElementById(\"Doyoubuygames\").checked) {\r\n nopBoughgame = document.querySelector('input[name=\"Boughtgame\"]:checked').value;\r\n }\r\n const game = document.querySelector('input[name=\"Typeofgame\"]:checked').value;\r\n const nopWhatgamedoyouplathemost = document.querySelector('input[name=\"Gameplayedthemost\"]:checked').value;\r\n\r\n\r\n // var rates = document.getElementsByName('Boughtgame'); da sa aj takto\r\n // var rate_value;\r\n // for(var i = 0; i < rates.length; i++){\r\n // if(rates[i].checked){\r\n // rate_value = rates[i].value;\r\n // }\r\n // }\r\n\r\n if (nopOpn == \"\" || nopName == \"\" || nopEmail == \"\") {\r\n window.alert(\"Please, enter both your name and opinion\");\r\n return;\r\n }\r\n const newOpinion =\r\n {\r\n Name: nopName,\r\n Email: nopEmail,\r\n Gender: nopGender,\r\n Gameplayedmost: nopWhatgamedoyouplathemost,\r\n Typeofgame: game,\r\n Boughtgame: nopDoyoubuygames,\r\n RadioBoughtgame: nopBoughgame,\r\n Textbox: nopOpn,\r\n Created: new Date()\r\n };\r\n\r\n opinions.push(newOpinion);\r\n localStorage.myTreesComments = JSON.stringify(opinions);\r\n\r\n\r\n // opinionsElm.innerHTML += opinion2html(newOpinion);\r\n\r\n\r\n // window.alert(\"Your opinion has been stored. Look to the console\");\r\n // console.log(\"New opinion added\");\r\n // console.log(opinions);\r\n let myFrmElm = document.getElementById(\"router-view\");\r\n myFrmElm=myFrmElm.getElementsByClassName(\"formenu\")[0];\r\n\r\n myFrmElm.reset(); //resets the form\r\n\r\n\r\n}",
"function saveClubChanges() {\n const params = new URLSearchParams(window.location.search);\n\n const newDesc = document.getElementById(\"description\").innerHTML;\n const newWebsite = document.getElementById(\"website-input\").innerText;\n\n var newOfficers = [];\n const officerListElement = document.getElementById('officers-list');\n const officerList = officerListElement.getElementsByTagName('li');\n for (const officer of officerList) {\n newOfficers.push(officer.innerText);\n }\n \n var newLabels = [];\n const labelsListElement = document.getElementById('labels');\n const labelsList = labelsListElement.getElementsByTagName('li');\n for (const label of labelsList) {\n newLabels.push(label.innerText.replace(/\\s+/g, '')); // Get rid of whitespaces\n }\n\n document.getElementById('new-desc').value = newDesc;\n document.getElementById('new-web').value = newWebsite;\n document.getElementById('new-officers').value = newOfficers;\n document.getElementById('new-labels').value = newLabels;\n document.getElementById('new-name').value = params.get('name');\n document.forms['edit-form'].submit();\n alert('Changes submitted!');\n}",
"function handleSubmit(event) {\n event.preventDefault(); // When event happens page refreshed, this function prevents the default reaction\n const currentValue = input.value;\n paintGreeting(currentValue);\n saveName(currentValue);\n}",
"function handleSubmit(button_type) {\n\n // check if there are no more unranked items\n unranked_items = document.getElementById('unranked-items').children;\n if (unranked_items.length > 0) {\n window.alert('Please sort in all items first.');\n }\n else {\n //get the ranking and save it\n var item_ids = [];\n var ranked_items = document.getElementById(\"ranked-items\").children;\n for (var j=0, item; item = ranked_items[j]; j++) {\n item_ids.push(ranked_items[j].getAttribute('id'));\n }\n document.getElementsByName(\"rankingResult\")[0].value = item_ids;\n\n var btn = document.getElementsByName('buttonType')[0];\n if (btn) {\n btn.value = button_type;\n }\n\n // now submit the form\n document.getElementById(\"subForm\").submit();\n }\n\n}",
"function submitGuess() {\n if (!currentGuess.includes(0)) {\n guesses.push(currentGuess);\n\n $('#row' + guesses.length).find('.col1').html(currentGuess[0]);\n $('#row' + guesses.length).find('.col2').html(currentGuess[1]);\n $('#row' + guesses.length).find('.col3').html(currentGuess[2]);\n $('#row' + guesses.length).find('.col4').html(currentGuess[3]);\n\n result = guessResult();\n\n if (result[0] == 2 && result[1] == 2 && result[2] == 2 && result[3] == 2) {\n $('#result').html(\"YOU WIN\");\n } else {\n $('#row' + guesses.length).find('.result').html(result.toString());\n }\n\n currentGuess = [0, 0, 0, 0];\n updateGuessedDisplay();\n setSelected(0);\n updateDisplay();\n if (guesses.length >= 12) {\n $('#result').html(\"YOU LOSE!\");\n }\n\n }\n }",
"async function newStoryFormSubmit() {\n console.debug(\"newStoryFormSubmit\");\n\n // grab the author, title, and url\n let author = $(\"#author-input\").val();\n let title = $(\"#title-input\").val();\n let url = $(\"#url-input\").val();\n\n // put newStory data into object\n let newStory = { author, title, url };\n\n // add newStory to API\n await StoryList.addStory(currentUser, newStory);\n\n // clear author, title, and url\n $(\"#author-input\").val(\"\");\n $(\"#title-input\").val(\"\");\n $(\"#url-input\").val(\"\");\n\n putStoriesOnPage();\n\n // hide story form\n $newStoryForm.hide();\n}",
"async function addNewScore(e) {\n e.preventDefault();\n const response = await fetch(\"/scoreboard\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(gatherInputData()),\n });\n const data = await response.json();\n console.log(data);\n getAllScores();\n clearInputFields();\n}",
"function addWorkout() {//when called will submit form data to database, return form data and place in table.\n document.getElementById(\"submit\").addEventListener(\"click\", function(event){ //wait for click on AddWorkout button\n var req = new XMLHttpRequest(); //get name, reps, weight, date, lbs from form and set to variables\n var name = document.getElementById(\"name\").value;\n var reps = document.getElementById(\"reps\").value;\n var weight = document.getElementById(\"weight\").value;\n var date = document.getElementById(\"date\").value;\n var lbs = document.getElementById(\"lbs\").value;\n var query = queryMake(reps, weight, date, lbs); // Set query string except for name portion\n\n\t\t//input validation. Check name reps weight and lbs. Won't hit if statement if not in right format\n if (name !== '' && (reps >= 0 || reps == '') && (weight >= 0 || weight == '') && (lbs == 0 || lbs == 1 || lbs == '')) {\n req.open(\"GET\", \"/insert?n=\" + name + query, true); //calls to insert route or insertion into database and callback\n\t\t\t//once recieved row is added to table with form data\n\t\t\t//response recieved loads new row. Also calls createEdit and createDelete for buttons\n req.addEventListener(\"load\", function() { //response\n var response = JSON.parse(req.responseText); //parse through text from Ajax documentation as JSON object\n var tbody = document.getElementById(\"table-body\"); //find table body\n var row = document.createElement('tr'); //create row\n var td = document.createElement('td'); //create column within row\n td.textContent = response[0].name; //place in first column name\n row.appendChild(td); //append\n td = document.createElement('td'); //recreate next column for reps, weight, date, and lbs in similar logic\n td.textContent = response[0].reps;\n row.appendChild(td);\n td = document.createElement('td');\n td.textContent = response[0].weight;\n row.appendChild(td);\n td = document.createElement('td');\n td.textContent = response[0].date;\n row.appendChild(td);\n td = document.createElement('td');\n td.textContent = response[0].lbs;\n row.appendChild(td);\n\t\t\t\t\n\t\t\t\t//once all form data has been added we create buttons in the row\n var edit = createEdit(); //create edit button\n td = document.createElement('td'); //create column\n td.setAttribute(\"class\", \"edit-delete\");\n var form = document.createElement('form'); //form so we can do something IE edit\n form.setAttribute(\"action\", \"/edit\"); //give action /edit route\n form.setAttribute(\"method\", \"GET\"); //with GET method type\n var input = document.createElement('input'); //create input for form\n input.setAttribute(\"type\", \"hidden\"); //create hidden Id so can be referenced and changed\n input.setAttribute(\"name\", \"editId\"); //id\n input.setAttribute(\"value\", response[0].id); //give id that matches its row number\n form.appendChild(input); //finally append\n form.appendChild(edit); //append with edit button to our form\n td.appendChild(form); //append form to column\n row.appendChild(td); //append column to row\n\t\t\t\t\n\t\t\t\tvar del = createDelete(); //create delete button similar to edit logic for ID\n td = document.createElement('td'); //column\n td.setAttribute(\"class\", \"edit-delete\");\n form = document.createElement('form'); //form\n input = document.createElement('input'); //input\n input.setAttribute(\"type\", \"hidden\");\n input.setAttribute(\"name\", \"id\");\n input.setAttribute(\"value\", response[0].id);\n\t\t\t\tdel.setAttribute(\"onclick\", \"deleteWorkout(event, 'workoutTable')\"); //on click calls deleteWorkout function on the table\n form.appendChild(input);\n form.appendChild(del); //same appending as the edit but instead give del button\n td.appendChild(form); //set button to column\n row.appendChild(td); //set column to row\n tbody.appendChild(row); //set row to table\n });\n req.send(null);// from ajax documentation\n\t\t\t\n\t\t\t//reset form data except today's date because that hasn't changed\n document.getElementById(\"name\").value = '';\n document.getElementById(\"reps\").value = '';\n document.getElementById(\"weight\").value = '';\n\t\t\tdocument.getElementById(\"lbs\").value = '';\n document.getElementById(\"date\").value = todaysDate();\n\n event.preventDefault(); //prevent default so no reload. From Ajax documentation\n }\n })\n}",
"function saveBallot(){\n\tif (\n\t\tconfirm(\"Are you sure you want to save your ballot?\\n Click 'OK' to submit or 'Cancel' to revise.\")\n\t){\n\t\tsavedBallot.above = [];\n\t\tsavedBallot.below = [];\n\n\t\tinputs.forEach(function(inputs, key, map){\n\t\t\tvar pName = inputs.partyName.value;\n\t\t\tvar canNames = [];\n\t\t\tfor (var i = 0; i < inputs.candidates.length; i++){\n\t\t\t\tcanNames.push(inputs.candidates[i].value);\n\t\t\t}\n\t\t\tsavedBallot.above.push(pName);\n\t\t\tsavedBallot.below.push({party:pName, candidates:canNames});\n\t\t});\n\n\t\t// Send vote to server\n\t\t$.post('/api/ballot',savedBallot);\n\t}\n}",
"function createFormHandler(e) {\n e.preventDefault()\n// Add innerHTML apending to Brainstormer in this section\n const characterInput = document.querySelector(\"#user-edit-character\").value\n const setupInput = document.querySelector(\"#user-edit-setup\").value\n const twistInput = document.querySelector(\"#user-edit-twist\").value\n const genreInput = document.querySelector(\"#user-edit-genre_id\").value\n \n postIdea(characterInput, setupInput, twistInput, genreInput)\n }",
"function submitScores() {\n scoresSubmissions = JSON.parse(localStorage.getItem(\"LastScoreBoard\")); // get LastScoreBoard from local storage and parse it\n if (scoresSubmissions == undefined) {\n // if there's nothing in local storage for it\n scoresSubmissions = []; // set it to an empty array\n }\n if (\n scoresDiv.classList.contains(\"hidden\") &&\n !qz11Div.classList.contains(\"hidden\") // make sure the Score Tally div is the one currently displayed\n ) {\n currentInitials = initialsInputField.value.toUpperCase(); // set the currentInitials var to the current initials/score submission and convert to UpperCase\n if (initialsInputField.value !== \"\") {\n let scoresObjectNext = {\n weighted: weightedScore,\n numCorrect: correctCount,\n timeLeft: finalTimeRemaining,\n initials: currentInitials,\n }; // create an object that fills the currect submission's weighted score, # correct, time left, and initials\n scoresSubmissions.push(scoresObjectNext); // push the new object into the scoresSubmissions array\n }\n initialsInputField.value = \"\"; // Reset initials textfield for other quiz submissions\n }\n function compare(a, b) {\n // comparison function to act on the scoresSubmissions sort that follows the function\n const scoreA = a.weighted; // set the weighted key's value of a to scoreA\n const scoreB = b.weighted; // set the weighted key's value of b to scoreB\n let comparison = 0; // set comparison var to 0 for starters, if the values are equal to each other, the sort order stays the same.\n if (scoreA > scoreB) {\n // if a > b, return 1 => the larger value will come after the smaller (order smallest to largest)\n comparison = -1; // typically this is reversed (= 1 usually), but multiplied by neg. 1 here (e.g. * -1) to sort largest to smallest.\n } else if (scoreA < scoreB) {\n // if a < b, return -1 => the larger value will come before the smaller (order largest to smallest)\n comparison = 1; // typically this is reversed (= 1 usually), but multiplied by neg. 1 here (e.g. * -1) to sort largest to smallest.\n }\n return comparison;\n }\n scoresSubmissions.sort(compare); // then sort the array (order of elements in object allows for table to be populated in correct order)\n localStorage.setItem(\"LastScoreBoard\", JSON.stringify(scoresSubmissions)); // set the scoreSubmissions array to local storage\n qz11Div.classList.add(\"hidden\"); // hides the score tally/results div\n scoresDiv.classList.remove(\"hidden\"); // displays the score board\n for (i = 0; i < scoresSubmissions.length; i++) {\n // run a loop for all the scores submissions stored in local storage\n let scoresTableRow = document.createElement(\"tr\"); // create a row element\n scoresTableRow.innerHTML =\n \"<td><strong>\" +\n (i + 1) +\n \"</strong></td><td><strong>\" +\n scoresSubmissions[i].initials +\n \"</strong></td><td><strong>\" +\n scoresSubmissions[i].numCorrect +\n \"</strong></td><td>\" +\n scoresSubmissions[i].timeLeft +\n \"</strong></td><td>\" +\n scoresSubmissions[i].weighted +\n \"</strong></td>\"; // make the row's inner HTML align with the col info and headers\n scoresTableBody.appendChild(scoresTableRow); // add the row to the table\n }\n}",
"function submitPlayers(form){\n\tplayers[0] = form.player1.value;\n\tplayers[1] = form.player2.value;\n\tplayers[2] = form.player3.value;\n\tplayers[3] = form.player4.value;\n\t$(document).ready(function(){\n\t\t$(\".players\").hide();\n\t\t$(\"#hands\").show();\n\t\t$(\"#round1\").show();\n\t\tsetPlayer(players[turn]);\n\t});\n}",
"finishGame(streak){\n let winner = this.currentPlayer;\n if(streak){\n for(let i=0; i<streak.length; i++){\n this.field[streak[i][0]][streak[i][1]] = \"<span class='winner'>\"+winner.toUpperCase()+\"</span>\";\n }\n this.winningStreak = streak;\n }\n else winner = true;\n this.winner = winner;\n $(this).trigger('finish');\n }",
"function saveReview() {\n // Get the information entered by the user\n const theName = document.getElementById('name');\n const theTitle = document.getElementById('title');\n const theRating = document.getElementById('rating');\n const theReview = document.getElementById('review');\n\n const newReview = {\n reviewer: theName.value,\n title: theTitle.value,\n rating: theRating.value,\n review: theReview.value\n };\n\n reviews.push(newReview);\n\n displayReview(newReview);\n\n showHideForm();\n}",
"function postCoffee() {\r\n let name = document.getElementById(\"coffeetitle\");\r\n let combo = {};\r\n let text = document.getElementById(\"dynamictext\");\r\n\r\n // Build JSON.\r\n combo[\"name\"] = name.value.substring(0,21);\r\n combo[\"color\"] = coffeeColor;\r\n combo[\"sugar\"] = sugarContent;\r\n combo[\"cream\"] = creamerContent;\r\n\r\n // Conditional for adding a post.\r\n if (name.value !== \"\") {\r\n // Clear name.\r\n name.value = \"\";\r\n let url = \"https://coffeemakerservice.herokuapp.com/\";\r\n // Build the fetchOptions to be used.\r\n let fetchOptions = {\r\n method : 'POST',\r\n headers : {\r\n 'Accept': 'application/json',\r\n 'Content-Type' : 'application/json'\r\n },\r\n body : JSON.stringify(combo)\r\n };\r\n // Attempt to post the message.\r\n fetch(url, fetchOptions)\r\n .then(checkStatus)\r\n .then(function(responseText) {\r\n text.innerHTML = responseText;\r\n \t\t})\r\n \t\t.catch(function(error) {\r\n \t\t\ttext.innerHTML = error;\r\n \t\t});\r\n }\r\n }",
"function storeReviewData() {\n const data = []\n $('.review-button').each(function(index, element) {\n const effect = element.classList.contains('approved') ? element.dataset.effect : 'nochange'\n data.push({ id: element.dataset.id, effect: effect })\n })\n\n $('#review-input').val(JSON.stringify({\n details: getApprovedDetailChanges(),\n content: data,\n }))\n}",
"function addNewData(){\n \n //Get the Band Name and Band Genre\n $('#band-name').val('');\n $('#band-genre').val('');\n \n //Fire off functions when Submit and Reset buttons are clicked.\n $('#submit').on('click', addData)\n $('#reset').on('click', showData);\n \n //Hide table and show input form.\n $('#band-info').hide();\n $('#data-values').show();\n \n function addData(evt){\n //Holds form data from Band Name and Band Genre input fields.\n var newData = {\n name: $('#band-name').val(),\n genre: $('#band-genre').val()\n };\n \n bandData.push(newData);\n \n evt.preventDefault();\n \n showData();\n }//End of addData\n}//End of addNewData",
"function submitAnswer() {\n let answer = app.form.convertToData('#survey-form');\n answer.answerer = loggedInUser.email;\n answer.survey_id = openSurvey.id;\n if (!answered(openSurvey.id)) {\n newAnswer(answer);\n } else {\n updateAnswer(answer);\n }\n}",
"function submitBookRoom() {\n var newBooking = {},\n localBookings = [];\n newBooking.number = $(\"#roomSelection\").val();\n newBooking.checkin = $(\"#checkinDate\").val();\n newBooking.checkout = $(\"#checkoutDate\").val();\n newBooking.name = $.trim($(\"#bookingName\").val());\n $(\"#nameError\").text(\"\");\n localBookings = loadLocalBookings();\n localBookings.push(newBooking);\n saveLocalBookings(localBookings);\n $(\"bookRoomForm\").hide();\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Broadcasts a session update message by updating local storage | function broadcastSessionUpdate() {
if (localStorage) {
localStorage.setItem('sessionUpdate', true);
localStorage.removeItem('sessionUpdate');
}
} | [
"function broadcastSessionDialogResponse(response) {\n if (localStorage) {\n localStorage.setItem('sessionDialogResponse', response);\n localStorage.removeItem('sessionDialogResponse');\n }\n}",
"function sendWebsocketUpdate() {\n io.emit('updateMessages', messageContainer);\n}",
"function ServerViewerBroadcastUserUpdate(ws) {\n var returnMessage = {}\n returnMessage[\"type\"] = \"user-update\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"user-id\"] = ws.userId;\n returnMessage.data[\"user-name\"] = ws.userName;\n returnMessage.data[\"lobby-id\"] = ws.lobbyId;\n returnMessage.data[\"gamemode\"] = ws.gamemode;\n ServerViewerBroadcastExclude(ws, returnMessage);\n}",
"updateUserToShell() {\n const user = this.authService.readUserFromSessionStorage();\n this.postMessageToShell(MessageType.user, user);\n }",
"function updateUI() {\n setInterval(() => {\n serverClient.getSession().then(session => {\n const /** Array */ listOfAttendeeScreenNames = [];\n session.getListOfAttendees().forEach(attendee => {\n listOfAttendeeScreenNames.push(attendee.getScreenName());\n });\n updateSessionAttendees(listOfAttendeeScreenNames,\n session.getScreenNameOfController());\n updateController(session.getScreenNameOfController());\n }).catch(error => {\n window.alert('No contact with the server!');\n });\n }, sessionScriptConstants.SESSION_REFRESH_CADENCE_MS);\n}",
"loadUserSession() {\n const storedUserSession = localStorage.getItem('userSession');\n const userSession = storedUserSession\n ? UserSession.deserialize(storedUserSession)\n : null;\n\n this.userSession = userSession;\n this.resetRenewalTimer(userSession);\n this.emit('user-session-changed', userSession);\n }",
"_updateSessionMetadataOnStart() {\n const sessionMetadata = {\n matchSpectatorInfo: this.sessionData.currentMatchInfo,\n summonerData: this.sessionData.summonerData,\n matchTime: this.sessionData.matchTime,\n status: this.sessionData.status,\n startTime: this.sessionData.startTime,\n };\n GameSessionService.updateSessionMetadata(this.sessionId, sessionMetadata);\n }",
"touch (sessionId, session, callback) {\n\t\t\tlet now = new Date ();\n\t\t\tlet update = {\n\t\t\t\tupdatedAt: now\n\t\t\t};\n\n\t\t\tif (session && session.cookie && session.cookie.expires) {\n\t\t\t\tupdate.expiresAt = new Date (session.cookie.expires);\n\t\t\t} else {\n\t\t\t\tupdate.expiresAt = new Date (now.getTime () + this.options.expiration);\n\t\t\t}\n\n\t\t\tthis.collection.update ({_id: sessionId}, {$set: update}, {multi: false, upsert: false}, (error, numAffected) => {\n\t\t\t\tif (!error && numAffected === 0) {\n\t\t\t\t\terror = new Error (`Failed to touch session for ID ${JSON.stringify (sessionId)}`);\n\t\t\t\t}\n\n\t\t\t\tcallback (error);\n\t\t\t});\n\t\t}",
"function fetchAndSendUpdatedTime() {\n if (windowOpen) {\n chrome.storage.local.get(\"timeLeft\", (data) => {\n var timeLeft = data.timeLeft;\n var timeObj = {\n minutes: timeLeft.minutes.toString(),\n seconds: timeLeft.seconds.toString(),\n };\n savePort.postMessage({\n status: \"time update\",\n time: stringifyTime(timeObj),\n });\n });\n }\n}",
"enqueueUpdate(sessionDataUpdate) {\n // If update is a no-op, don't enqueue it.\n if (sessionDataUpdate.isNoOp()) {\n return;\n }\n\n // If \"queue\" is empty, initialize it.\n if (!this.sessionData) {\n this.sessionData = new SessionData();\n this.mergeStrategyForNextServerUpdate = sessionDataUpdate.mergeStrategy;\n }\n\n // Update data in the \"queue\".\n this.sessionData.update(sessionDataUpdate);\n\n // If this was a 'replace' update, set 'replace' as the strategy for the\n // next server update, regardless of incoming client updates until then.\n if (sessionDataUpdate.mergeStrategy === REPLACE_STRATEGY) {\n this.mergeStrategyForNextServerUpdate = REPLACE_STRATEGY;\n }\n }",
"function update(){\n\tvlc.status().then(function(status) {\n\t\tvar newPlaying={\n\t\t state: escapeHtml(status.artist+\" - \"+status.album),\n\t\t details: escapeHtml(status.title),\n\t\t largeImageKey: \"vlc\",\n\t\t smallImageKey: status.state,\n\t\t instance: true,\n\t\t}\n\t\tif(newPlaying.state!==nowPlaying.state || newPlaying.details!==nowPlaying.details || newPlaying.smallImageKey!==nowPlaying.smallImageKey){\n\t\t\tconsole.log(\"Changes detected; sending to Discord\")\n\t\t\tif(status.state===\"playing\"){\n\t\t\t\tnewPlaying.startTimestamp=Date.now()/1000\n\t\t\t\tnewPlaying.endTimestamp=parseInt(parseInt(Date.now()/1000)+(parseInt(status.duration)-parseInt(status.time)))\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}else{\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}\n\t\t\tdelete newPlaying.startTimestamp\n\t\t\tdelete newPlaying.endTimestamp\n\t\t\tnowPlaying=newPlaying\n\t\t}\n\t});\n}",
"function updateLastViewed(element) {\n sessionStorage.setItem('lastviewed', element);\n}",
"_updateGame() {\n this.playerMap.emitCustomToAll('updateGame', (socket) => {\n return this.serverState.toCompressedClientState(socket, this.currentSocketEvent);\n });\n this.serverState.clearEphemeralFields();\n }",
"save() {\n var string = JSON.stringify(this[PINGA_SESSION_STATE]);\n\n localStorage.setItem(this.userId, string);\n }",
"function ServerViewerBroadcastLobbyUpdate(lobbyId, status) {\n // currently the lobby updates are sent to all users //\n\n var returnMessage = {}\n returnMessage[\"type\"] = \"lobby-update\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"lobby-id\"] = lobbyId\n returnMessage.data[\"status\"] = status;\n // ServerViewerBroadcast(returnMessage);\n\n wss.clients.forEach(function each(client) {\n client.send(JSON.stringify(returnMessage));\n });\n}",
"function checkForSessionUpdate(event) {\n // if another page was refreshed reset the session timers for this page\n if ((event.key == 'sessionUpdate') && (event.newValue == true)) {\n resetSessionTimers();\n }\n\n // if the user responded to a session dialog in another page, we need to reset the timers (in the case of continue)\n // and close the session dialogs for this page if any are displaying\n if (event.key == 'sessionDialogResponse') {\n if ((activeDialogId == kradVariables.SESSION_TIMEOUT_WARNING_DIALOG)\n || (activeDialogId == kradVariables.SESSION_TIMEOUT_DIALOG)) {\n closeLightbox();\n }\n\n if (event.newValue == 'continue') {\n resetSessionTimers();\n }\n else if (event.newValue == 'logout') {\n logoutUser();\n }\n }\n}",
"async updateUserInformations() {\n try{\n this.user = await this.get(\"users/me/\");\n store.dispatch('updateUser', this.user);\n window.sessionStorage.setItem(\"user\", JSON.stringify(this.user));\n } catch(error){\n console.log(\"Error while updating user info \" + error);\n }\n }",
"_store() {\n try {\n window.sessionStorage.setItem('playQueue', JSON.stringify(this._array));\n } catch(e) {}\n }",
"feedSubmit() {\n sessionStorage.setItem(\"feedsub\",true);\n this.setState({\n feedSub: true\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function shows the specific picture from the main page that the user wants to delete in a div element, or hides the div element if needed | function showPictureToDelete()
{
if (document.forms[1].deletePics.value == "")
{
$('#showPicture').empty();
}
else
{
$('#showPicture').empty();
var picture = document.forms[1].deletePics.value;
var pictureScript = '<p><img src="../mainPictures/' + picture + '"width="50" height="76" />';
$('#showPicture').append(pictureScript);
}
} | [
"function hideSmIm(){\r\ndocument.getElementById('smallImage').style.display = 'none';\r\n$(\"#savPicBlk\").hide();\r\n}",
"function del_entrypic( entry_id, pic_id ) {\r\n\t\t\r\n\t\tforward_func = del_entrypic_confirmed.bind( null, entry_id, pic_id );\r\n\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t'message': c['sure_to_delete']\r\n\t\t\t,'ok_btn': forward_func\r\n\t\t});\r\n\t\t\r\n\t}",
"function hidePicture() {\n document.querySelector('.sika').style.display = 'none';\n document.getElementById('sika-points').textContent = '';\n}",
"function close_image() {\n image_viewer.style.display = \"none\";\n}",
"printUploadedImageToBeDeleted() {\n if (this.state.showDeleteConfirmation) { //So the page doesn't crash after deleting an image\n var toeIndex = this.state.toDeleteInfo.toeIndex;\n var toe = this.state.toeData.feet[this.state.toDeleteInfo.selectedFootIndex].toes[this.state.toDeleteInfo.toeIndex];\n var toeImageData = toe.images[this.state.toDeleteInfo.imageIndex];\n\n return (\n this.printUploadedImage(toeIndex, false, //No need to show the delete and rotate buttons in the modal\n toeImageData.name, toeImageData.date, toeImageData.fongiqueCoverage, 0)\n );\n }\n\n return \"\";\n }",
"function show_image_upload_form() {\n let profile_upload = document.getElementById(\"profile-image-upload-form\");\n profile_upload.style.display = \"\";\n let profile_info = document.getElementById(\"profile-info-form\");\n profile_info.style.display = \"none\";\n}",
"function hideDeleteFilm() {\n\t$(\"#delete-film-result\").empty();\n\t$(\"#delete-film-success\").empty();\n\t$(\"#delete-film-boxes\").toggle(\"slow\");\n\t}",
"function hideImagePopup(){\n\tdocument.getElementById('popupImage').style.visibility = \"hidden\";\n}",
"function removePhoto(){\n\tdocument.getElementById(\"PhotoField\").disabled = true;\n\t$(\"#PhotoField\").val(\"\");\n\t$(\"#PhotoParentDiv\").hide();\n\t$(\"#imageIcon\").css('color',\"#9ba1a7\");\n\t// for edit page\n\tdocument.getElementById(\"fileRemovedStatus\").disabled = false;\n}",
"function showOriginal() {\n const showOriginalBtn = document.querySelector('#show-original');\n if (originalImage.style.display == 'none') {\n originalImage.style.display = 'block';\n showOriginalBtn.style.color = '#CD343A';\n \n }\n else {\n originalImage.style.display = 'none';\n showOriginalBtn.style.color = '#ededed';\n } \n}",
"function ImageError(image)\n{\n image.style.display = \"none\";\n}",
"function viewOriginalImg() {\r\n\tvar linePics = [\"org1_line\",\"org2_line\",\"org3_line\",\"org4_line\",\"org5_line\"];\r\n\tvar barPics = [\"org1_bar\",\"org2_bar\",\"org3_bar\",\"org4_bar\",\"org5_bar\"];\r\n\r\n\tvar pic; //pic = pic id name\r\n\t\r\n\tif(document.getElementById(\"lineBtn\").style.background === \"white\") { //line chart\r\n\t\tpic = linePics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t} else { //bar chart\r\n\t\tpic = barPics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t}\r\n\r\n\t//hide all other pictures and display selected one\r\n\tif(element.style.display == 'none'){\r\n\t\telement.style.display='block';\r\n\t\telement.style.border='1px solid black';\r\n\t\telement.style.position='absolute';\r\n\t\telement.style.right='150px';\r\n\t\telement.style.background='black';\r\n\t\t\r\n\t\tfor(var i = 0; i < linePics.length; i++) {\r\n\t\t\tif(linePics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(linePics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tfor(var i = 0; i < barPics.length; i++) {\r\n\t\t\tif(barPics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(barPics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"white\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"black\"\r\n\t} else {\r\n\t\tcloseAllScreenshots();\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"rgba(255,255,255,0.4)\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"white\"\r\n\t}\r\n}",
"function findImgId(e) {\n setPicId(e.target.id);\n handleShow();\n }",
"function showmain_img(btnsw,hid1,hid2,hid3,hid4,hid5,hid6,shwmain){\n\n\tbtnsw.click(function(){\n\n\t\thid1.hide(\"fast\");\n\n\t\thid2.hide(\"fast\");\n\n\t\thid3.hide(\"fast\");\n\n\t\thid4.hide(\"fast\");\n\n\t\thid5.hide(\"fast\");\n\n\t\thid6.hide(\"fast\");\n\n\t\tshwmain.show(\"fast\");\n\n\t});\n\n}",
"function hideImage(img) {\n background = img;\n background.style.display = \"none\";\n}",
"function quitardivs(nombrediv)\n{\n if(document.getElementById(nombrediv))\n {\n \tobj=document.getElementById(nombrediv);\n \tobj.innerHTML=\"\";\n \tobj.style.display=\"none\";\n }\n\t//alert(obj)\n\t//var padre=obj.parentNode;\n\t//padre.removeChild(obj);\n}",
"function deleteFavori(id, type, element) {\r\r\n jQuery(element).prev().hide();\r\r\n jQuery(element).hide();\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxLike',\r\r\n 'type' : 'dislike',\r\r\n 'post_id': id,\r\r\n 'post_type': type\r\r\n },\r\r\n function(){\r\r\n }\r\r\n );\r\r\n}",
"function removeCover() {\n document.getElementById('covering-div').className = 'hide';\n}",
"function hideStartupDiv() {\n // Appending Preview to Page2\n $(\"#page2\").empty();\n $(\"#page2\").html($(\"#importPage3Preview\").html());\n\n // Remove preview to prevent conflict\n $(\"#importPage3Preview\").empty();\n\n // Close the startup div\n createNew();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates an 'usuario' on the database | function updateUsuario(req, res, next) {
/* Finding the user document based on query */
Usuario.findOne({ 'nome': req.body.old.nome }, function(err, userDoc) {
/* Checking for errors */
if (err) { return next(err); }
/* Checking if the user was found */
if (!userDoc) {
return res.status(404).json({
success: false,
message: 'Usuário não encontrado'
});
}
/* Tries to update the user's fields */
try {
/* Checking each field ('nome') */
if (req.body.new.nome) {
userDoc.nome = req.body.new.nome;
}
} catch (err) {
/* There was an error */
return res.json({
success: false,
message: 'Confira se todos os campos foram preenchidos corretamente'
});
}
/* Saving the updated 'usuario' document */
userDoc.save(function(err) {
/* Checking for errors */
if (err) { return next(err); }
/* Returning the success message */
return res.json({
success: true,
message: userDoc.nome + ' alterado(a) com sucesso'
});
});
});
} | [
"function saveUser() {\n UserService.Update(vm.user)\n .then(function () {\n FlashService.Success('Usuario modificado correctamente');\n })\n .catch(function (error) {\n FlashService.Error(error);\n });\n }",
"function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_success, updateUser_error);\n}",
"function updateUser(tableSvc, username, amount) {\n const userEntry = {\n PartitionKey: ENTGEN.String(username),\n RowKey: ENTGEN.String('1'),\n schreefstock: ENTGEN.Int32(amount),\n };\n\n tableSvc.insertOrReplaceEntity(TABLENAME, userEntry, null, (error) => {\n if (!error) {\n // Entity updated\n } else {\n LOG.error(error);\n }\n });\n}",
"function UpdateUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n user.name = 'Hyper!'\n\t\tdebugger;\n return client.UpdateUser(user, 'administrator', 'Welcome1');\n })\n .then(function (user) {\n debugger;\n });\n}",
"function inserirUsuario() {\n if ($scope.novoUsuario.Id > 0) {\n atualizarModelUsuario();\n\n } else {\n inserirModelUsuario();\n }\n }",
"function updateItemsAscensorValoresFinales(k_codusuario,k_codinspeccion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_finales SET o_observacion = ?\"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ?\"; \n tx.executeSql(query, [o_observacion,k_codusuario,k_codinspeccion], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresFinales: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de observación...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"updateUser (id, email, newEmail, username, password) {\n return apiClient.updateUser(\n storage.getToken(),\n id,\n email,\n newEmail,\n username,\n password\n )\n }",
"update(userInfo) {\n const userID = this.findIdBySlug(userInfo.username);\n this._collection.update(userID, { $set: userInfo });\n }",
"function addUpdateUser (req,res) {\n const { userId } = req.body;\n // console.log(req.body);\n if (userId) {\n User.findOneAndUpdate({ _id: userId },\n req.body,\n { new: true },\n )\n .exec()\n .then(user => {\n // user.password = undefined;\n return res.json({ status: 0, data: {} });\n })\n .catch(err => {\n return res.status(500).json({})\n })\n } else {\n const user = new User(req.body);\n user.save((error, user) => {\n if (error) {\n return res.status(500).json({})\n }\n res.json({\n status: 0,\n data: {}\n });\n })\n }\n}",
"async updateUser () {\n\t\tconst email = this.request.body.toEmail;\n\t\tconst op = {\n\t\t\t$set: {\n\t\t\t\temail,\n\t\t\t\tsearchableEmail: email.toLowerCase(),\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t}\n\t\t};\n\t\tthis.updateOp = await new ModelSaver({\n\t\t\trequest: this,\n\t\t\tcollection: this.data.users,\n\t\t\tid: this.user.id\n\t\t}).save(op);\n\t}",
"function put() {\n let data = {\n name: userInfo.elements.name.value,\n firstname: userInfo.elements.firstname.value,\n lastname: userInfo.elements.lastname.value,\n email: userInfo.elements.email.value,\n password: userInfo.elements.password.value\n };\n\n let postData = JSON.stringify(data);\n\n fetch(`https://smackfly-2fd1.restdb.io/rest/users-fly-smacker/${id}`, {\n method: \"put\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"x-apikey\": \"5de40f274658275ac9dc2152\",\n \"cache-control\": \"no-cache\"\n },\n body: postData\n }\n)\n.then(d => d.json())\n.then( updatedUser => {\n userInfo.elements.name.value=updatedUser.name,\n userInfo.elements.firstname.value=updatedUser.firstname;\n userInfo.elements.lastname.value=updatedUser.lastname;\n userInfo.elements.email.value=updatedUser.email;\n userInfo.elements.password.value=updatedUser.password;\n\n updateUserBtn.textContent = \"Success!\";\n updateUserBtn.style.backgroundColor = \"#fca91f\";\n});\n}",
"editUser( id ) {\n fluxUserManagementActions.editUser( id );\n }",
"function userUpdate(fname, lname, email, pswrd) {\n return $.ajax({\n method: \"PUT\",\n url: \"/api/user\",\n dataType: \"json\",\n contentType: \"application/json\",\n data: JSON.stringify({\n id: userInfo.id,\n fname: fname,\n lname: lname,\n email: email,\n password: pswrd\n })\n });\n}",
"function createUsuario(req, res, next) {\n /* Checking if there's already an user with the provided 'nome' */\n Usuario.findOne({ 'nome': req.body.new.nome }, function(err, userDoc) {\n /* Checking for errors */\n if (err) { return next(err); }\n\n /* Checking if user exists with provided 'nome' */\n if (userDoc) {\n return res.json({\n success: false,\n message: 'Já existe um usuário cadastrado com este nome'\n });\n }\n\n /* Tries to update the user's fields */\n try {\n var userObject = {};\n\n userObject.nome = req.body.new.nome;\n } catch (err) {\n /* There was an error creating the hash */\n return res.json({\n success: false,\n message: 'Confira se todos os campos foram preenchidos corretamente'\n });\n }\n\n /* Sending the create request to the database */\n Usuario.create(userObject, function(err) {\n /* Checking for errors */\n if (err) { return next(err); }\n\n /* Returning the success message */\n return res.json({\n success: true,\n message: userObject.nome + ' cadastrado com sucesso'\n });\n });\n });\n}",
"function updateUserData(id, userData) {\n var stringified = JSON.stringify(userData);\n var props = { userData: stringified};\n Entities.editEntity(id, props);\n}",
"updateUser (id, name, email, disable = undefined, refreshPassword = undefined) {\n // TODO: change this to take a user id and an object containing the update payload\n assert.equal(typeof id, 'number', 'id must be number')\n assert.equal(typeof name, 'string', 'name must be string')\n assert.equal(typeof email, 'string', 'email must be string')\n if (disable) assert.equal(typeof disable, 'boolean', 'disable must be boolean')\n if (refreshPassword) assert.equal(typeof refreshPassword, 'boolean', 'refreshPassword must be boolean')\n return this._apiRequest(`/user/${id}`, 'PUT', {\n name,\n email,\n is_disabled: disable,\n new_password: refreshPassword\n })\n }",
"function updateInfo(req, res) {\n User.findOne({_id: req.params.id}, function(err, user) {\n if (err || !user) {\n return res.send({error: 'Could not update user.'});\n }\n \n user.extendedInfo = req.body;\n\n user.save(function(saveErr) {\n if (saveErr) {\n return res.send({error: 'Could not update user'});\n }\n return res.send({success: 'Successfully updated user!'});\n });\n });\n}",
"function updateItemsAscensorValoresFoso(k_codusuario,k_codinspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_foso SET n_calificacion = ?,\"+\n \"v_calificacion = ?,\"+\n \"o_observacion = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ? \"+\n \"AND k_coditem = ?\";\n tx.executeSql(query, [n_calificacion,v_calificacion,o_observacion,k_codusuario,k_codinspeccion,k_coditem], function(tx, res) {\n console.log(\"rowsAffected ascensor_valores_foso: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de foso...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"function updateItemsAscensorValoresElementos(k_codusuario,k_codinspeccion,k_coditem, o_descripcion,v_seleccion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_elementos SET o_descripcion = ?,\"+\n \"v_selecion = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ? \"+\n \"AND k_coditem = ?\"; \n tx.executeSql(query, [o_descripcion,v_seleccion,k_codusuario,k_codinspeccion,k_coditem], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresElementos: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos elementos...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse nonfn call: literal array or literal value | function parseGenVal(expr) {
return _.chain(expr)
.map(function(e){
if (_.isString(e)) return e;
if (_.isArray(e)) return parseGenExpr(e); // array but not fn call
throw {expr: expr, e: e, msg: "Cannot parse, only supports string/array here, got " + (typeof e)};
})
.value();
} | [
"function parseFuncInstrArguments(signature) {\n var args = [];\n var namedArgs = {};\n var signaturePtr = 0;\n\n while (token.type === _tokenizer.tokens.name || isKeyword(token, _tokenizer.keywords.offset)) {\n var key = token.value;\n eatToken();\n eatTokenOfType(_tokenizer.tokens.equal);\n var value = void 0;\n\n if (token.type === _tokenizer.tokens.number) {\n value = t.numberLiteralFromRaw(token.value);\n } else {\n throw new Error(\"Unexpected type for argument: \" + token.type);\n }\n\n namedArgs[key] = value;\n eatToken();\n } // $FlowIgnore\n\n\n var signatureLength = signature.vector ? Infinity : signature.length;\n\n while (token.type !== _tokenizer.tokens.closeParen && ( // $FlowIgnore\n token.type === _tokenizer.tokens.openParen || signaturePtr < signatureLength)) {\n if (token.type === _tokenizer.tokens.identifier) {\n args.push(t.identifier(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.valtype) {\n // Handle locals\n args.push(t.valtypeLiteral(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.string) {\n args.push(t.stringLiteral(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.number) {\n args.push( // TODO(sven): refactor the type signature handling\n // https://github.com/xtuc/webassemblyjs/pull/129 is a good start\n t.numberLiteralFromRaw(token.value, // $FlowIgnore\n signature[signaturePtr] || \"f64\")); // $FlowIgnore\n\n if (!signature.vector) {\n ++signaturePtr;\n }\n\n eatToken();\n } else if (token.type === _tokenizer.tokens.openParen) {\n /**\n * Maybe some nested instructions\n */\n eatToken(); // Instruction\n\n if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // $FlowIgnore\n args.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in nested instruction\" + \", given \" + tokenToString(token));\n }();\n }\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken();\n }\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in instruction argument\" + \", given \" + tokenToString(token));\n }();\n }\n }\n\n return {\n args: args,\n namedArgs: namedArgs\n };\n }",
"function parseFuncParam() {\n var params = [];\n var id;\n var valtype;\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = token.value;\n eatToken();\n }\n\n if (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: id,\n valtype: valtype\n });\n /**\n * Shorthand notation for multiple anonymous parameters\n * @see https://webassembly.github.io/spec/core/text/types.html#function-types\n * @see https://github.com/xtuc/webassemblyjs/issues/6\n */\n\n if (id === undefined) {\n while (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: undefined,\n valtype: valtype\n });\n }\n }\n } else {// ignore\n }\n\n return params;\n }",
"function evaluate_array_literal(stmt,env) {\n var array = [];\n var elements = stmt.elements;\n var len = length(elements);\n for (var i = 0; i < len; i = i + 1) {\n array[i] = evaluate(head(elements), env);\n elements = tail(elements);\n }\n return array;\n}",
"function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}",
"visitTestlist_star_expr(ctx) {\r\n console.log(\"visitTestlist_star_expr\");\r\n let length = ctx.getChildCount();\r\n if (length === 1) {\r\n if (ctx.test() !== null) {\r\n return this.visit(ctx.test(0));\r\n } else {\r\n return this.visit(ctx.star_expr(0));\r\n }\r\n } else {\r\n let valuelist = [this.visit(ctx.getChild(0))];\r\n for (var i = 1; i < length; i++) {\r\n if (ctx.getChild(i).getText() !== \",\") {\r\n valuelist.push(this.visit(ctx.getChild(i)));\r\n }\r\n }\r\n return { type: \"TestListStarExpression\", value: valuelist };\r\n }\r\n }",
"function parseArrayInitializer() {\n\t var elements = [], node = new Node(), restSpread;\n\t\n\t expect('[');\n\t\n\t while (!match(']')) {\n\t if (match(',')) {\n\t lex();\n\t elements.push(null);\n\t } else if (match('...')) {\n\t restSpread = new Node();\n\t lex();\n\t restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\t\n\t if (!match(']')) {\n\t isAssignmentTarget = isBindingElement = false;\n\t expect(',');\n\t }\n\t elements.push(restSpread);\n\t } else {\n\t elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\t\n\t if (!match(']')) {\n\t expect(',');\n\t }\n\t }\n\t }\n\t\n\t lex();\n\t\n\t return node.finishArrayExpression(elements);\n\t }",
"function exp (arr){\n\tif (Array.isArray(arr)){\n\t\treturn arr[0](arr[1], arr[2]);\n\t\t}\n\treturn arr;\n}",
"function parseFuncInstr() {\n var startLoc = getStartLoc();\n maybeIgnoreComment();\n /**\n * A simple instruction\n */\n\n if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) {\n var _name2 = token.value;\n var object;\n eatToken();\n\n if (token.type === _tokenizer.tokens.dot) {\n object = _name2;\n eatToken();\n\n if (token.type !== _tokenizer.tokens.name) {\n throw new TypeError(\"Unknown token: \" + token.type + \", name expected\");\n }\n\n _name2 = token.value;\n eatToken();\n }\n\n if (token.type === _tokenizer.tokens.closeParen) {\n var _endLoc = token.loc.end;\n\n if (typeof object === \"undefined\") {\n return t.withLoc(t.instruction(_name2), _endLoc, startLoc);\n } else {\n return t.withLoc(t.objectInstruction(_name2, object, []), _endLoc, startLoc);\n }\n }\n\n var signature = t.signatureForOpcode(object || \"\", _name2);\n\n var _parseFuncInstrArgume = parseFuncInstrArguments(signature),\n _args = _parseFuncInstrArgume.args,\n _namedArgs = _parseFuncInstrArgume.namedArgs;\n\n var endLoc = token.loc.end;\n\n if (typeof object === \"undefined\") {\n return t.withLoc(t.instruction(_name2, _args, _namedArgs), endLoc, startLoc);\n } else {\n return t.withLoc(t.objectInstruction(_name2, object, _args, _namedArgs), endLoc, startLoc);\n }\n } else if (isKeyword(token, _tokenizer.keywords.loop)) {\n /**\n * Else a instruction with a keyword (loop or block)\n */\n eatToken(); // keyword\n\n return parseLoop();\n } else if (isKeyword(token, _tokenizer.keywords.block)) {\n eatToken(); // keyword\n\n return parseBlock();\n } else if (isKeyword(token, _tokenizer.keywords.call_indirect)) {\n eatToken(); // keyword\n\n return parseCallIndirect();\n } else if (isKeyword(token, _tokenizer.keywords.call)) {\n eatToken(); // keyword\n\n var index;\n\n if (token.type === _tokenizer.tokens.identifier) {\n index = identifierFromToken(token);\n eatToken();\n } else if (token.type === _tokenizer.tokens.number) {\n index = t.indexLiteral(token.value);\n eatToken();\n }\n\n var instrArgs = []; // Nested instruction\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n instrArgs.push(parseFuncInstr());\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (typeof index === \"undefined\") {\n throw new Error(\"Missing argument in call instruciton\");\n }\n\n if (instrArgs.length > 0) {\n return t.callInstruction(index, instrArgs);\n } else {\n return t.callInstruction(index);\n }\n } else if (isKeyword(token, _tokenizer.keywords.if)) {\n eatToken(); // Keyword\n\n return parseIf();\n } else if (isKeyword(token, _tokenizer.keywords.module) && hasPlugin(\"wast\")) {\n eatToken(); // In WAST you can have a module as an instruction's argument\n // we will cast it into a instruction to not break the flow\n // $FlowIgnore\n\n var module = parseModule();\n return module;\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected instruction in function body\" + \", given \" + tokenToString(token));\n }();\n }\n }",
"function parseType() {\n var id;\n var params = [];\n var result = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = identifierFromToken(token);\n eatToken();\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) {\n eatToken(); // (\n\n eatToken(); // func\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken(); // function with an empty signature, we can abort here\n\n return t.typeInstruction(id, t.signature([], []));\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) {\n eatToken(); // (\n\n eatToken(); // param\n\n params = parseFuncParam();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) {\n eatToken(); // (\n\n eatToken(); // result\n\n result = parseFuncResult();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.typeInstruction(id, t.signature(params, result));\n }",
"function parseFuncResult() {\n var results = [];\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n if (token.type !== _tokenizer.tokens.valtype) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in func result\" + \", given \" + tokenToString(token));\n }();\n }\n\n var valtype = token.value;\n eatToken();\n results.push(valtype);\n }\n\n return results;\n }",
"function parseExpression(program) {\n program = skipSpace(program);\n let match, expr;\n // using 3 regex to spot either strings, #s or words\n if (match = /^\"([^\"]*)\"/.exec(program)) {\n expr = {type: \"value\", value: match[1]};\n } else if (match = /^\\d+\\b/.exec(program)) {\n expr = {type: \"value\", value: Number(match[0])};\n } else if (match = /^[^\\s(),#\"]+/.exec(program)) {\n expr = {type: \"word\", name: match[0]};\n } else {\n // if the input does not match any of the above 3 forms, it's not a valid expression\n // throw an error, specifically Syntax Error\n throw new SyntaxError(\"Unexpected syntax: \" + program);\n }\n// return what is matched and pass it along w/ the object for the expression to parseApply\n return parseApply(expr, program.slice(match[0].length));\n}",
"function primaryExpr(stream, a) {\n var x = stream.trypopliteral();\n if (null == x) x = stream.trypopnumber();\n if (null != x) {\n return x;\n }\n var varRef = stream.trypopvarref();\n if (null != varRef) return a.node('VariableReference', varRef);\n var funCall = functionCall(stream, a);\n if (null != funCall) {\n return funCall;\n }\n if (stream.trypop('(')) {\n var e = orExpr(stream, a);\n if (null == e) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected expression after (.');\n if (null == stream.trypop(')')) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected ) after expression.');\n return e;\n }\n return null;\n }",
"visitVarargslist(ctx) {\r\n console.log(\"visitVarargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }",
"ArgumentList() {\n const argumentList = [];\n do {\n argumentList.push(this.AssignmentExpression());\n } while (this._lookahead.type === \",\" && this._eat(\",\"));\n\n return argumentList;\n }",
"function tokensToFunction (tokens, options) {\n // Compile all the tokens into regexps.\n const matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (let i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options))\n }\n }\n\n return function (obj, opts) {\n let path = ''\n const data = obj || {}\n const options = opts || {}\n const encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n const value = data[token.name || 'pathMatch']\n let segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (Array.isArray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (let j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}",
"function literalToValue(literal) {\n return literal.value;\n}",
"function ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}",
"function firstVal(arg, func) {\n if(Array.isArray(arg) == Array) {\n func(arr[0], index, arr);\n }\n if(arr.constructor == Object) {\n func(arg[key], key, arg);\n}\n}",
"Literal() {\n switch (this._lookahead.type) {\n case \"NUMBER\":\n return this.NumericLiteral();\n case \"STRING\":\n return this.StringLiteral();\n case \"true\":\n case \"false\":\n return this.BooleanLiteral(this._lookahead.type);\n case \"null\":\n return this.NullLiteral();\n }\n throw new SyntaxError(`Literal: unexpected literal production`);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a base64encoded string of "numberBytes" random bytes | function randomBytes(numberBytes) {
return crypto.randomBytes(numberBytes).toString('base64');
} | [
"function randomInt64() {\n var halfOne = crypto_1.randomBytes(4).readUInt32LE(0, true);\n var halfTwo = crypto_1.randomBytes(4).readUInt32LE(0, true);\n var str = \"\" + halfOne + halfTwo;\n var len = str[0] === \"9\" ? 18 : 19;\n return str.slice(0, len); // postgres max int64 == 9223372036854775808\n}",
"function getRandomNumber () {\n return String.fromCharCode(Math.floor(Math.random()*26) + 48)\n}",
"function randomPassword() {\n\tvar password = new Buffer(24);\n\tfor (var i = 0; i < 24; i++) {\n\t\tpassword[i] = Math.floor(Math.random() * 256);\n\t}\n\treturn password.toString('base64');\n}",
"function random128() {\n var result = \"\";\n for (var i = 0; i < 8; i++)\n result += String.fromCharCode(Math.random() * 0x10000);\n return result;\n}",
"function generateUID() {\n return String(~~(Math.random()*Math.pow(10,8)))\n}",
"base64() {\n\t\tif (typeof btoa === 'function') return btoa(String.fromCharCode.apply(null, this.buildFile()));\n\t\treturn new Buffer(this.buildFile()).toString('base64');\n\t}",
"toBase64() {\n return this._byteString.toBase64();\n }",
"generatePrivateKey() {\n // Generates 64 hexadecimal values then concatenates all 64 values\n let r = [];\n for (let i = 0; i < 64; i++) {\n r.push(this.random.integer(0, 15).toString(16));\n }\n return r.join('');\n }",
"function randomHexNumberGenerator() {\n return '#' + Math.random().toString(16).substr(2, 6).toUpperCase();\n}",
"function makeRandomNumber() {\n\t\treturn Math.floor( Math.random() * 9 );\n\t}",
"function makeInviteCode() {\n const random = crypto.randomBytes(5).toString('hex');\n return base32.encode(random);\n}",
"function generate_unique_number(){\n var current_date = (new Date()).valueOf().toString();\n var random = Math.random().toString();\n return generate_hash(current_date + random);\n}",
"function generateSignature() {\n let sig = \"\";\n\n for (let i = 0; i < 16; i++) {\n let c = Math.floor(Math.random() * 3);\n sig += whitespace_chars[c];\n }\n return nms + sig + nms;\n}",
"function base64(data) {\n\tif (typeof data === 'object') data = JSON.stringify(data);\n\treturn Buffer.from(data).toString('base64');\n}",
"function generateGuid() {\n var buf = new Uint16Array(8);\n buf = crypto.randomBytes(8);\n var S4 = function(num) {\n var ret = num.toString(16);\n while(ret.length < 4){\n ret = \"0\"+ret;\n }\n return ret;\n };\n\n return (\n S4(buf[0])+S4(buf[1])+\"-\"+S4(buf[2])+\"-\"+S4(buf[3])+\"-\"+\n S4(buf[4])+\"-\"+S4(buf[5])+S4(buf[6])+S4(buf[7])\n );\n}",
"function makeTuid() {\n return crypto.randomBytes(16).toString('hex')\n}",
"function DigitGenerator(MaxMinGenerator) {\n var Digits = \"\";\n for (var i = 0; i < MaxMinGenerator; i++) {\n Digits = Digits + Math.round(Math.random() * (9 - 1) + 1).toString();\n }\n return Digits;\n}",
"generateCode() {\n return (Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4)).toUpperCase();\n }",
"function createToken(){\n\t\t\treturn crypto.randomBytes(16).toString(\"hex\");\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples the unit space based on p Breaks into fs.length equally spaces units centers a Stepf on each unit hfLut[i] represents the height fraction for sample i | function createHfLut(fs, hfLut, n) {
//var n = 1 + Math.ceil(1.0 / p);
var b = 0.65;
var u0 = 0.0;
var u1 = 1.0;
var nn = 1;
// var fsn = fs.length;
var fis = (u1 - u0) / functionSummaries.length;
for (var i = 0; i < n; ++i) {
var u = (1.0 * i) / n;
var fic = Math.floor(functionSummaries.length * u);
var v = 0;
var fi0 = Math.max(0, fic - nn), fi1 = Math.min(functionSummaries.length - 1, fic + nn);
for (var fi = fi0;
fi <= fi1; ++fi) {
var ficu = u0 + fis / 2 + fis * fi;
var su = b * (u - ficu) * 2.0 / fis;
// alert("" + fi + ":" + su);
v += fs[fi] * (su < 0 ? stepf(-su) : stepf(su));
}
hfLut[i] = v;
}
hfLut[n] = hfLut[n - 1];
// alert(hfLut);
} | [
"function determineFrequency(f) {\n var qstate = new jsqubits.QState(numInBits + numOutBits).hadamard(inputBits);\n qstate = qstate.applyFunction(inputBits, outBits, f);\n // We do not need to measure the outBits, but it does speed up the simulation.\n qstate = qstate.measure(outBits).newState;\n return qstate.qft(inputBits)\n .measure(inputBits).result;\n }",
"function heatPerUnitArea$1 (rxi, taur) {\n return rxi * taur\n}",
"function initFilters(N,E,mbuffer,T,K,Z,Y, mfilter_bits,P,leveltier, isOptimalFPR) {\n\n var filter_array = [];\n var remainingKeys=N-mbuffer/E;\n var level=0;\n //Calculate the number of keys per level in a almost-full in each level LSM tree\n while (remainingKeys>0)\n {\n level++;\n var levelKeys=Math.ceil(Math.min(Math.pow(T,level)*mbuffer/E,N));\n var newFilter = new Filter();\n newFilter.nokeys=levelKeys;\n newFilter.fp=0.0;\n // console.log(\"New remaining keys: \"+(remainingKeys-levelKeys))\n if (remainingKeys-levelKeys<0)\n newFilter.nokeys=remainingKeys;\n //console.log(newFilter.nokeys)\n filter_array.push(newFilter);\n remainingKeys=remainingKeys-levelKeys;\n // console.log(levelKeys)\n }\n\t\tvar mem_level = filter_array.length - Y;\n\t\tfor (var i=0;i<mem_level;i++)\n\t\t{\n\t\t\t\tfilter_array[i].mem=mfilter_bits/mem_level;\n\t\t}\n\t\tfor (var i=mem_level;i<filter_array.length;i++){\n\t\t\tfilter_array[i].mem= 0;\n\t\t}\n/*\n //Initialize the memory per level to be equal\n\t\tif(!isOptimalFPR){\n\t\t\tfor (var i=0;i<filter_array.length;i++)\n\t {\n\t filter_array[i].mem=mfilter_bits/filter_array.length;\n\t }\n\t return filter_array;\n\t\t}else{\n\t\t\tvar EULER = 2.71828182845904523536;\n\t\t\tvar C = Math.pow(Math.log(2), 2);\n\t\t\tvar L = filter_array.length;\n\t\t\tvar X = 1.0/C*(Math.log(T/(T - 1)) + Math.log(K/Z)/T)\n\t\t\tvar Y = Math.ceil(Math.log(N*X/mfilter_bits)/Math.log(T))\n\t\t\tif(Y > 0){\n\t\t\t\tL -= Y;\n\t\t\t}\n\t\t\tvar tmp = 0;\n\t\t\tfor(var i=1;i<=L;i++){\n\t\t\t\tif(i == L){\n\t\t\t\t\ttmp += Z*filter_array[i-1].nokeys*Math.log(Z);\n\t\t\t\t}else{\n\t\t\t\t\ttmp += K*filter_array[i-1].nokeys*Math.log(K*Math.pow(T, L - i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar t = Math.pow(EULER, (tmp - mfilter_bits*C)/N);\n\t\t\tvar equal_flag = false;\n\t\t\tvar eqaul_mem = 0;\n\t\t\tvar left_levels = 1;\n\t\t\tfor(var i=1;i<=L;i++){\n\t\t\t\tvar fpr_i;\n\t\t\t\tvar runs;\n\t\t\t\tif(equal_flag){\n\t\t\t\t\tfilter_array[i-1].mem = eqaul_mem;\n\t\t\t\t}else{\n\t\t\t\t\tif(i==L){\n\t\t\t\t\t\tfpr_i = Math.max(mfilter_bits, 0);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tfpr_i = t/K/Math.pow(T, L-i);\n\t\t\t\t\t}\n\t\t\t\t\tif(fpr_i > 1){\n\t\t\t\t\t\tequal_flag = true;\n\t\t\t\t\t\tleft_levels = L - i + 1;\n\t\t\t\t\t\teqaul_mem = mfilter_bits/left_levels;\n\t\t\t\t\t\tfilter_array[i-1].mem = eqaul_mem;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tfilter_array[i-1].mem=-filter_array[i-1].nokeys*Math.log(fpr_i)/C;\n\t\t\t\t\t\tmfilter_bits -= filter_array[i-1].mem;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}*/\n\n\t\treturn filter_array;\n}",
"function flameLengthThomas (fli) {\n return fli <= 0 ? 0 : 0.2 * Math.pow(fli, 2 / 3)\n} // Active crown fire heat per unit area,",
"function makePerceptualFluencyTrials() {\n\n var pfA = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,\n 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,\n 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];\n var pfB = pfA;\n pfA = shuffleArray(pfA);\n pfB = shuffleArray(pfB);\n var r = Math.floor(Math.random() * 2);\n if (r==0) {\n for (var i=0; i<pfA.length; i++) {\n pfTaskAtargets[i] = pstimsetA[pfA[i]];\n pfTaskBtargets[i] = pstimsetB[pfB[i]];\n } \n } else {\n for (var i=0; i<pfA.length; i++) {\n pfTaskAtargets[i] = pstimsetB[pfB[i]];\n pfTaskBtargets[i] = pstimsetA[pfA[i]];\n }\n }\n pfTypeA = pstimsetA[0].slice(0,4);\n pfTypeB = pstimsetB[0].slice(0,4);\n}",
"function surface(p) {\n\t\tvar sx, sy, d;\n\t\t// normalize the point into a unit vector pointing\n\t\t// away from the center of a sphere at (0, 0, 0)\n\t\ttemp.norm.copy(p).norm();\n\t\t// calculate mock \"surface coordinates\" based on that sphere\n\t\tsx = Math.acos(temp.norm.z) / Math.PI;\n\t\tsy = Math.atan2(temp.norm.y, temp.norm.x) / (Math.PI * 2);\n\t\t// avoid discontinuity in arctangent when we cross x-axis\n\t\tsy = (temp.norm.y < 0) ? sy + 1 : sy;\n\t\t// use the noise function to modulate the unit vector\n\t\td = 1.0 + noise.get(sx, sy) - noise.amplitude * 0.5;\n\t\treturn temp.norm.mul(d);\n\t}",
"function displaysFSSData()\n{\n\tvar i;\n\tfssVal.FSS_TextDisplay();\n\tfor (i = 0; i < fuzzySubsetNumber; i++)\n\t{\n\t\tmodellingFSS[i].FSS_TextDisplay();\n\t}\n}",
"function compute_LF_finings(ibu) {\n var finingsMlPerLiter = 0.0;\n var LF_finings = 0.0;\n var postBoilVolume = 0.0;\n\n LF_finings = 1.0;\n if (!isNaN(ibu.finingsAmount.value)) {\n postBoilVolume = ibu.getPostBoilVolume();\n finingsMlPerLiter = ibu.finingsAmount.value / postBoilVolume;\n if (ibu.finingsType.value == \"gelatin\") {\n // exponential decay factor from 'gelatin' subdirectory, data.txt\n LF_finings = Math.exp(-0.09713 * finingsMlPerLiter);\n }\n }\n if (SMPH.verbose > 5) {\n console.log(\"LF finings : \" + LF_finings.toFixed(4) + \" from \" +\n ibu.finingsAmount.value.toFixed(3) + \" ml of \" +\n ibu.finingsType.value + \" in \" +\n postBoilVolume.toFixed(2) + \" l post-boil\");\n }\n return LF_finings;\n}",
"function PHSK_BFeld( draht, BPoint) {\n\tif ( GMTR_MagnitudeSquared( GMTR_CrossProduct( GMTR_VectorDifference(draht.a ,draht.b ),GMTR_VectorDifference(draht.a ,BPoint ) )) < 10E-10)\n\t\treturn new Vec3 (0.0, 0.0, 0.0);\n\n\n\tlet A = draht.a;\n\tlet B = draht.b;\n\tlet P = BPoint;\n\t\n\tlet xd = -(GMTR_DotProduct(A,A) - GMTR_DotProduct(A,B) + GMTR_DotProduct(P , GMTR_VectorDifference(A,B))) / (GMTR_Distance(A,B));\n\tlet x = xd / (GMTR_Distance(A,B));\n\tlet yd = xd + GMTR_Distance(A,B);\n\t\n\tlet F1 = (yd / GMTR_Distance(P,B)) - (xd / GMTR_Distance(P,A));\n\tlet F2 = 1 / (GMTR_Distance(P,GMTR_VectorAddition(A,GMTR_ScalarMultiplication( GMTR_VectorDifference(B,A), x))));\n\tlet F3 = GMTR_CrossProductNormal( GMTR_VectorDifference(A,B),GMTR_VectorDifference(A,P) );\n\n\treturn GMTR_ScalarMultiplication(F3,F1*F2);\n}",
"function getIndexAndK(w,data) {\n var hiWavelength = 0;\n var hiIndex = 0;\n var loWavelength = 0; \n var loIndex = 0;\n var hiExtinction = 0;\n\tvar loExtinction = 0;\n\t\t\t\t\n for (j = 0; j < data.Indices.length; j++) {\n \n if (data.Indices[j].lambda <= w && (loWavelength === 0 || loWavelength < data.Indices[j].lambda)) {\n loWavelength = data.Indices[j].lambda;\n loIndex = data.Indices[j].n;\n loExtinction = data.Indices[j].k;\t\t\n\t }\n\n if (data.Indices[j].lambda >= w && (hiWavelength === 0 || hiWavelength > data.Indices[j].lambda)) {\n hiWavelength = data.Indices[j].lambda;\n hiIndex = data.Indices[j].n;\n hiExtinction = data.Indices[j].k;\t\t\t\t\n }\n };\n\n\t// Closer data point is the wavelength, higher proportion used.\n\t// But if LoWavelength is the highest number, It's proportion should be 1. \n\tif (hiIndex == 0) {\n loWavelength = w;\n\t}\n\t\n if (loIndex == 0) {\n hiWavelength = w;\n }\n\t\n\tvar diff = hiWavelength - loWavelength;\n\t// if difference is 0 (i.e. loWavelength = hiWavelength). We can just\n\t// take either hiIndex or loIndex as the final Index\n if (diff != 0) {\n var Index1 = (1 - (( w - loWavelength ) / diff)) * loIndex;\n var Extinction1 = ((loWavelength/ w) * loExtinction);\n var Index2 = (1 - (( hiWavelength - w ) / diff)) * hiIndex;\n var Extinction2 = ((1-(loWavelength/ w)) * hiExtinction);\n var Index = Index1 + Index2;\n var Extinction = Math.round((Extinction1 + Extinction2)*1000000)/1000000;\n \t \n } else {\n var Index = hiIndex;\n var Extinction = hiExtinction;\n } \n return [Index, Extinction];\n}",
"function compute_LF_ferment(ibu) {\n var LF_ferment = 0.0;\n var LF_flocculation = 0.0;\n\n // The factors here come from Garetz, p. 140\n if (ibu.flocculation.value == \"high\") {\n LF_flocculation = 0.95;\n } else if (ibu.flocculation.value == \"medium\") {\n LF_flocculation = 1.00;\n } else if (ibu.flocculation.value == \"low\") {\n LF_flocculation = 1.05;\n } else {\n console.log(\"ERROR: unknown flocculation value: \" + ibu.flocculation.value);\n LF_flocculation = 1.00;\n }\n\n LF_ferment = SMPH.fermentationFactor * LF_flocculation;\n if (SMPH.verbose > 5) {\n console.log(\"LF ferment : \" + LF_ferment.toFixed(4));\n }\n return LF_ferment;\n}",
"function drawWaveAndIntensitySS() {\n\tlet canvas = document.getElementById(\"diffraction\");\n\tlet ctx = canvas.getContext(\"2d\");\n\n\tlet alpha, I, sin, b, c;\n\tlet lambda = Number(parseFloat(document.form.lambda.value));\n\tlet colours = wavelengthToColor(lambda);\n\tlet screen = Number(parseFloat(document.form.L.value));\n\n\tlet gap = Number(parseFloat(document.form.gap.value));\n\n\tctx.fillStyle = colours[0];\n\tctx.strokeStyle = colours[0];\n\n\tctx.beginPath();\n\tctx.moveTo(570, 150);\n\tc = 1.5 + (screen * 2 - 100) * 0.5 / 50.;\n\n\tfor (i = 150; i >= 0; i--) {\n\t\tb = 0.18 * (1 - (i - 10) / 140.);\n\t\tsin = b / Math.sqrt(Math.pow(b, 2) + Math.pow(c, 2));\n\t\talpha = sin * Math.PI * gap * 500. / lambda;\n\t\tI = Math.pow(Math.sin(alpha) / alpha, 2);\n\t\tctx.lineTo(sinToCoords(I), i);\n\t\tI = Math.pow(I, 1 / 2);\n\t\tctx.fillStyle = rgbToHex(Math.round(colours[1] * I), Math.round(colours[2] * I), Math.round(colours[3] * I));\n\t\tctx.fillRect(383, i, 57, 1);\n\n\t}\n\n\tctx.stroke();\n\tctx.beginPath();\n\tctx.moveTo(570, 150);\n\n\tfor (i = 149; i <= 300; i++) {\n\t\tb = 0.18 * (1 - (i - 10) / 140.);\n\t\tsin = b / Math.sqrt(Math.pow(b, 2) + Math.pow(c, 2));\n\t\talpha = sin * Math.PI * gap * 500. / lambda;\n\t\tI = Math.pow(Math.sin(alpha) / alpha, 2);\n\n\t\tctx.lineTo(sinToCoords(I), i);\n\t\tI = Math.pow(I, 1 / 2);\n\t\tctx.fillStyle = rgbToHex(Math.round(colours[1] * I), Math.round(colours[2] * I), Math.round(colours[3] * I));\n\t\tctx.fillRect(383, i, 57, 1);\n\t}\n\n\tctx.stroke();\n\tlambda /= 100;\n\tctx.fillStyle = colours[0];\n\n\tfor (i = 4; i < 250 - screen * 2 - 1; i += 8 * lambda)\n\t\tctx.fillRect(i, 100, 2, 100);\n\n\tfor (i = 20; i < 280 - (75 - screen) * 2; i += 8 * lambda) {\n\t\tctx.beginPath();\n\t\tctx.arc(250 - screen * 2, 150 - gap, i, 1.75 * Math.PI, 0.25 * Math.PI);\n\t\tctx.stroke();\n\t\tctx.beginPath();\n\t\tctx.arc(250 - screen * 2, 150 + gap, i, 1.75 * Math.PI, 0.25 * Math.PI);\n\t\tctx.stroke();\n\t}\n}",
"function initFeatures() {\n\n features.push(function(s) { // v0 left knee\n var val = 0.8*(s.lk_ang + 0.25);\n return val;\n });\n\n features.push(function(s) { // v1 right knee\n var val = 0.8*(s.rk_ang + 0.25);\n return val;\n });\n\n features.push(function(s) { // v2 left hip\n var val = 0.5*(s.lh_ang + 1);\n return val;\n });\n\n features.push(function(s) { // v3 right hip\n var val = 0.5*(s.rh_ang + 1);\n return val;\n });\n\n features.push(function(s) { // v4 torso ang\n var val = 0.4*(1.25+max(-1.25,min(1.25,s.T_ang)));\n return val;\n });\n\n features.push(function(s) { // v5 feet heights\n var val = min(max(floor(s.LF_y/20),0),SQRTRES-1);\n val = (val*SQRTRES) + min(max(floor(s.RF_y/20),0),SQRTRES-1);\n return val/RESOLUTION;\n });\n}",
"updateFrequency() {\n const freq = this.channel.frequencyHz;\n const block = this.channel.block;\n const fnum = this.channel.fnumber;\n // key scaling (page 29 YM2608J translated)\n const f11 = fnum.bit(10), f10 = fnum.bit(9), f9 = fnum.bit(8), f8 = fnum.bit(7);\n const n4 = f11;\n const n3 = f11 & (f10 | f9 | f8) | !f11 & f10 & f9 & f8;\n const division = n4 << 1 | n3;\n\n // YM2608 page 26\n if (this.freqMultiple === 0) {\n this.frequency = freq / 2;\n } else {\n this.frequency = freq * this.freqMultiple;\n }\n\n this.keyScalingNote = block << 2 | division;\n\n const FD = this.freqDetune & 3;\n const detune = DETUNE_TABLE[this.keyScalingNote][FD] * MEGADRIVE_FREQUENCY / 8000000;\n if (this.freqDetune & 4) {\n this.frequency -= detune;\n } else {\n this.frequency += detune;\n }\n }",
"function sampleTable(){\n var htm=[];\n htm.push(\"<table id='samples' class='table table-condensed table-hover'>\");\n htm.push(\"<thead>\");\n htm.push(\"<th>#</th>\");\n //htm.push(\"<th>Sample name</th>\");\n htm.push(\"<th>Size</th>\");\n //htm.push(\"<th>Finetune</th>\");\n //htm.push(\"<th>Vol</th>\");\n htm.push(\"<th>loop</th>\");\n htm.push(\"<th>len</th>\");\n htm.push(\"</thead>\");\n htm.push(\"<tbody>\");\n var totalbytes=0;\n var totalsamples=0;\n for(var i=0;i<31;i++){\n //if(module.sample[i].length<1)continue;\n totalsamples++;\n totalbytes+=module.sample[i].length;\n htm.push(\"<tr id='smpl_\"+i+\"'>\");\n htm.push(\"<td>\"+hb(i+1));\n //htm.push(\"<td>\"+module.sample[i].name);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].length);\n //htm.push(\"<td>\"+module.sample[i].finetune);\n //htm.push(\"<td>\"+module.sample[i].volume);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].loopstart);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].looplength);\n \n //console.log(this.sample[i].name,this.sample[i].length,this.sample[i].finetune,this.sample[i].volume,this.sample[i].loopstart,this.sample[i].looplength);\n }\n //\n htm.push(\"</tbody>\");\n htm.push(\"<tfoot>\");\n htm.push(\"<tr>\");\n htm.push(\"<td>\");\n htm.push(\"<td>\"+totalsamples+\" sample(s)\");\n //htm.push(\"<td style='text-align:right'><b>Total bytes :\");\n htm.push(\"<td style='text-align:right'><b>\"+totalbytes+\"b\");\n htm.push(\"<td></td>\");\n htm.push(\"</tr>\");\n htm.push(\"</tfoot>\");\n htm.push(\"</table>\");\n return htm.join(\"\");\n}",
"function getFreq(name,un_name) //get frequncy in Hz\n{\n\tvar x=getVar(name);\n\tvar unit=getVtext(un_name);\n\tif(\"GHz\"==unit) return x*=1e9;\n\tif(\"MHz\"==unit) return x*=1e6;\n\tif(\"kHz\"==unit) return x*=1e3;\n\treturn x;\n}",
"function pws(t) {\r\n var T = t + 459.67;\r\n var C1 = -1.0214165e4;\r\n var C2 = -4.8932428;\r\n var C3 = -5.3765794e-3;\r\n var C4 = 1.9202377e-7;\r\n var C5 = 3.5575832e-10;\r\n var C6 = -9.0344688e-14;\r\n var C7 = 4.1635019;\r\n var C8 = -1.0440397e4;\r\n var C9 = -1.129465e1;\r\n var C10 = -2.7022355e-2;\r\n var C11 = 1.289036e-5;\r\n var C12 = -2.478068e-9;\r\n var C13 = 6.5459673;\r\n if (t >= -148 && t <= 32) {\r\n var fpws = C1 / T + C2 + C3 * T + C4 * T ** 2 + C5 * T ** 3 + C6 * T ** 4 + C7 * Math.log(T);\r\n } else if (t > 32 && t <= 392) {\r\n var fpws = C8 / T + C9 + C10 * T + C11 * T ** 2 + C12 * T ** 3 + C13 * Math.log(T);\r\n } else {\r\n window.alert(\"Temperature is out of range\");\r\n }\r\n return Math.exp(fpws);\r\n}",
"getInitialValue() {\n const [real, imag] = this._getRealImaginary(this._type, 0);\n\n let maxValue = 0;\n const twoPi = Math.PI * 2;\n const testPositions = 32; // check for peaks in 16 places\n\n for (let i = 0; i < testPositions; i++) {\n maxValue = Math.max(this._inverseFFT(real, imag, i / testPositions * twoPi), maxValue);\n }\n\n return (0, _Math.clamp)(-this._inverseFFT(real, imag, this._phase) / maxValue, -1, 1);\n }",
"function normalize(fftData, N){\n\tvar N2 = N*N;\n\tvar mr = 0;\n\tvar midN = Math.floor(N/2);\n\tvar midCell = N*midN+midN;\n\tfor (var i=0; i<N2; i++){\n\t\tvar r = fftData[i].r;\n\t\tvar ri = fftData[i].ri;\n\t\tvar g = fftData[i].g;\n\t\tvar gi = fftData[i].gi;\n\t\tvar b = fftData[i].b;\n\t\tvar bi = fftData[i].bi;\n\t\tif(i!==midCell){\n\t\t\tmr = Math.max(mr,r*r+ri*ri,g*g+gi*gi,b*b+bi*bi);\n\t\t}\n\t}\n\tmr = 256/(Math.sqrt(mr+.0000001));\n\tfor (var i=0; i<N2; i++){\n\t\tvar r = fftData[i].r;\n\t\tvar ri = fftData[i].ri;\n\t\tvar g = fftData[i].g;\n\t\tvar gi = fftData[i].gi;\n\t\tvar b = fftData[i].b;\n\t\tvar bi = fftData[i].bi;\n\t\tfftData[i].r = Math.floor(Math.sqrt(r*r+ri*ri)*mr);\n\t\tfftData[i].g = Math.floor(Math.sqrt(g*g+gi*gi)*mr);\n\t\tfftData[i].b = Math.floor(Math.sqrt(b*b+bi*bi)*mr);\n\t}\n\tfftData[midCell].r = 255;\n\tfftData[midCell].g = 255;\n\tfftData[midCell].b = 255;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter of the link attribute. | set link(aValue) {
this._logger.debug("link[set]");
this._link = aValue;
let uri;
try {
uri = this._ioService.newURI(this._link, null, null);
} catch (e) {
uri = this._ioService.newURI("http://" + this._link, null, null);
}
this._domain = uri.host;
} | [
"set link(aValue) {\n this._logService.debug(\"gsDiggEvent.link[set]\");\n this._link = aValue;\n\n var uri;\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n this._domain = uri.host;\n }",
"set href(aValue) {\n this._logger.debug(\"href[set]\");\n this._href = aValue;\n }",
"set href(aValue) {\n this._logService.debug(\"gsDiggEvent.href[set]\");\n this._href = aValue;\n }",
"function updateLink(value) {\n var item = new Array;\n\n //! Update Link\n item.modified = new Date();\n item.id = 1\n item.link = value;\n Storage.updateLink(item);\n strLink = value;\n}",
"get link() {\n this._logger.debug(\"link[get]\");\n return this._link;\n }",
"function markLink( link ) {\r\n\t\t$( link ).addClass( linkCurrentClass );\r\n\t}",
"function unmarkLink( link ) {\r\n\t\t$( link ).removeClass( linkCurrentClass ); \r\n\t}",
"function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}",
"function promptLinkAttrs(pm, callback) {\n\t new FieldPrompt(pm, \"Create a link\", {\n\t href: new TextField({\n\t label: \"Link target\",\n\t required: true,\n\t clean: function clean(val) {\n\t if (!/^https?:\\/\\//i.test(val)) val = 'http://' + val;\n\t return val;\n\t }\n\t }),\n\t title: new TextField({ label: \"Title\" })\n\t }).open(callback);\n\t}",
"function updateFeedLink() {\n var bounds = map.getPixelBounds(),\n nwTilePoint = new L.Point(\n Math.floor(bounds.min.x / markers.options.tileSize),\n Math.floor(bounds.min.y / markers.options.tileSize)),\n seTilePoint = new L.Point(\n Math.floor(bounds.max.x / markers.options.tileSize),\n Math.floor(bounds.max.y / markers.options.tileSize));\n\n $('#feed_link').attr('href', $.owlviewer.owl_api_url + 'changesets/'\n + map.getZoom() + '/'\n + nwTilePoint.x + '/' + nwTilePoint.y + '/'\n + seTilePoint.x + '/' + seTilePoint.y + '.atom'\n );\n}",
"_getLinkURL() {\n let href = this.context.link.href;\n\n if (href) {\n // Handle SVG links:\n if (typeof href == \"object\" && href.animVal) {\n return this._makeURLAbsolute(this.context.link.baseURI, href.animVal);\n }\n\n return href;\n }\n\n href = this.context.link.getAttribute(\"href\") ||\n this.context.link.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\");\n\n if (!href || !href.match(/\\S/)) {\n // Without this we try to save as the current doc,\n // for example, HTML case also throws if empty\n throw \"Empty href\";\n }\n\n return this._makeURLAbsolute(this.context.link.baseURI, href);\n }",
"function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}",
"function getLinkRef(link) {\n return link ? link.link : false;\n}",
"function resetLink() {\n var instruction = gettext(\"This link will open the default version of this interactive:\");\n var link = window.location.href.split('?', 1)[0].replace(/^\\/+|\\/+$/g, '');\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${link}>${link}</a>`);\n}",
"function setLinkId(){\r\n var linkid = -1;\r\n if(document.global_search.area.value == \"earthlink-ss\"){ linkid = \"1010729\"; }\r\n else { linkid = \"1010730\"; }\r\n}",
"_addLink(r1, r2) {\n this.elements.push({\n group: \"edges\",\n data: {\n id: `${r1.id}_${r2.id}`,\n source: r1.id,\n target: r2.id\n } \n })\n }",
"function setLinkOpacity(){\n model.linkDataArray.forEach(link => {\n if (hasTransparentNode(link)){\n setOpacity(link, 0.15)\n } else {\n setOpacity(link, 1)\n }\n })\n}",
"function updateStatsLink() {\n const statsLink = document.getElementById(\"stats-link\")\n let statsLinkUrl = statsLink.getAttribute(\"href\")\n let query = statsLinkUrl.indexOf('?');\n if (query > 0) {\n var statsLinkUrlNew = statsLinkUrl.substring(0, query);\n } else {\n var statsLinkUrlNew = statsLinkUrl;\n }\n statsLinkUrlNew = statsLinkUrlNew + \"?\" + \"operator_name\" + \"=\" + settings.elements.operator_name.value\n + \"&\" + \"a_digits\" + \"=\" + settings.elements.a_digits.value\n + \"&\" + \"b_digits\" + \"=\" + settings.elements.b_digits.value\n statsLink.setAttribute(\"href\",statsLinkUrlNew)\n}",
"set imageURL(aValue) {\n this._logger.debug(\"imageURL[set]\");\n this._imageURL = aValue;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the sites dropdown box with the specified values | function loadSites(values, selectAll) {
require(["dojo/ready", "dijit/form/MultiSelect", "dijit/form/Button", "dojo/dom", "dojo/_base/window"], function(ready, MultiSelect, Button, dom, win){
ready(function(){
if (sitesMultiSelect != null) sitesMultiSelect.destroyRecursive(true);
selSites = dom.byId('selectSites');
selSites.innerHTML = '';
$.each(values, function(i, val) {
var c = win.doc.createElement('option');
if (connectionStatus[val] == 'Up') {
$(c).css('color', 'green');
} else if (connectionStatus[val] == 'Down') {
$(c).css('color', 'red');
$(c).attr('disabled', 'disabled');
} else if (connectionStatus[val] == null) {
$(c).css('color', 'blue');
}
c.innerHTML = val;
c.value = val;
selSites.appendChild(c);
});
sitesMultiSelect = new MultiSelect({ name: 'selectSites'}, selSites);
sitesMultiSelect.watch('value', function () {
loadMethods(emptyValue);
loadLibraries(emptyValue);
var selValues = sitesMultiSelect.get('value');
$('#analysisSpecifications').css('display', 'none');
$('#statusQueryWrapperDiv').css('display', 'none');
$('#queryDiv').css('display', 'none');
if (selValues != null) {
if (selValues.length == 1 && selValues[0] == emptySelectionString) {
sitesMultiSelect.set('value', '');
} else if (selValues.length >= 1) {
renderAvailableLibraries();
}
}
});
if (!selectAll) {
sitesMultiSelect.set('value', '');
} else {
sitesMultiSelect.set('value', values);
}
sitesMultiSelect.startup();
});
});
} | [
"function setOptions(domains) {\n $(\"#edit-field-domain-source option\").each(function(index, obj) {\n if (jQuery.inArray(obj.value, domains) == -1 && obj.value != '_none') {\n // If the current selection is removed, reset the selection to _none.\n if ($(\"#edit-field-domain-source\").val() == obj.value) {\n $(\"#edit-field-domain-source\").val('_none');\n }\n $(\"#edit-field-domain-source option[value=\" + obj.value + \"]\").hide();\n }\n else {\n $(\"#edit-field-domain-source option[value=\" + obj.value + \"]\").show();\n // If we reselected the initial value, reset the select option.\n if (obj.value == initialOption) {\n $(\"#edit-field-domain-source\").val(obj.value);\n }\n }\n });\n }",
"function admin_post_edit_load_univ() {\n get_univ(faculty_selector_vars.countryCode, function (response) {\n\n var stored_univ = faculty_selector_vars.univCode;\n var obj = JSON.parse(response);\n var len = obj.length;\n var $univValues = '';\n\n $(\"select[name*='univCode']\").fadeIn();\n for (i = 0; i < len; i++) {\n var myuniv = obj[i];\n var current_univ = myuniv.country_code + '-' + myuniv.univ_code;\n if (current_univ == stored_univ) {\n var selected = ' selected=\"selected\"';\n } else {\n var selected = false;\n }\n $univValues += '<option value=\"' + myuniv.country_code + '-' + myuniv.univ_code + '\"' + selected + '>' + myuniv.univ_name + '</option>';\n\n }\n $(\"select[name*='univCode']\").append($univValues);\n\n });\n }",
"function load_drives_dropdown(){\n\tif ( $(\".assembly_constituency_dropdown\").val() != '' )\n\t{\n\t\tif (typeof(loadMyDrives) === 'function') {\n\t\tloadMyDrives()\n\t\t}\n\t}\n\t}",
"function populateListbox() {\n\t\t\tvar select = document.getElementById(\"statesListbox_by_country\");\n\t\t\tvar select2 = document.getElementById(\"statesListbox_by_commody\");\n\t\t\tstateAbbreviationsDB().each(function (s) {\n\t\t\t\tselect.options[select.options.length] = new Option(s.State, s.Abbreviation);\n\t\t\t\tselect2.options[select2.options.length] = new Option(s.State, s.Abbreviation);\n\t\t\t\t//Make the first option selected by default\n\t\t\t\t$(\"#statesListbox_by_country\")[0].selectedIndex = 0\n\t\t\t\t$(\"#statesListbox_by_commody\")[0].selectedIndex = 0\n\t\t\t});\n\t\t}",
"function loadStudies(values) {\n\trequire([\"dojo/ready\", \"dijit/form/MultiSelect\", \"dijit/form/Button\", \"dojo/dom\", \"dojo/_base/window\"], function(ready, MultiSelect, Button, dom, win){\n\t\tready(function(){\n\t\t\tif (studiesMultiSelect != null) studiesMultiSelect.destroyRecursive(true);\n\t\t\tselStudies = dom.byId('selectStudies');\n\t\t\tselStudies.innerHTML = '';\n\t\t\t$.each(values, function(i, val) {\n\t\t\t\tvar c = win.doc.createElement('option');\n\t\t\t\tc.innerHTML = val;\n\t\t\t\tc.value = val;\n\t\t\t\tselStudies.appendChild(c);\n\t\t\t});\n\t\t\tstudiesMultiSelect = new MultiSelect({ name: 'selectStudies', value: '' }, selStudies);\n\t\t\tstudiesMultiSelect.watch('value', function () {\n\t\t\t\tloadDatasets(emptyValue);\n\t\t\t\tloadLibraries(emptyValue);\n\t\t\t\tloadMethods(emptyValue);\n\t\t\t\tloadSites(emptyValue, false);\n\t\t\t\t$('#analysisSpecifications').css('display', 'none');\n\t\t\t\t$('#statusQueryWrapperDiv').css('display', 'none');\n\t\t\t\t$('#queryDiv').css('display', 'none');\n\t\t\t\tvar selValues = studiesMultiSelect.get('value');\n\t\t\t\tif (selValues != null) { \n\t\t\t\t\tif (selValues.length == 1) {\n\t\t\t\t\t\trenderAvailableDatasets();\n\t\t\t\t\t\t$('#continueButton').removeAttr('disabled');\n\t\t\t\t\t} else if (selValues.length > 1) {\n\t\t\t\t\t\tstudiesMultiSelect.set('value', '');\n\t\t\t\t\t\t$('#continueButton').attr('disabled', 'disabled');\n\t\t\t\t\t} else if (selValues.length == 0) {\n\t\t\t\t\t\t$('#continueButton').attr('disabled', 'disabled');\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t\tstudiesMultiSelect.startup();\n\t\t});\n\t});\n}",
"function GetDropDownList() {\n var typeCodeList = [\"WMSYESNO\", \"WMSRelationShip\", \"INW_LINE_UQ\", \"PickMode\"];\n var dynamicFindAllInput = [];\n\n typeCodeList.map(function (value, key) {\n dynamicFindAllInput[key] = {\n \"FieldName\": \"TypeCode\",\n \"value\": value\n }\n });\n var _input = {\n \"searchInput\": dynamicFindAllInput,\n \"FilterID\": appConfig.Entities.CfxTypes.API.DynamicFindAll.FilterID\n };\n\n apiService.post(\"eAxisAPI\", appConfig.Entities.CfxTypes.API.DynamicFindAll.Url + authService.getUserInfo().AppPK, _input).then(function (response) {\n if (response.data.Response) {\n typeCodeList.map(function (value, key) {\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value] = helperService.metaBase();\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value].ListSource = response.data.Response[value];\n });\n }\n });\n }",
"function loadTagsIntoSelect() {\n dropdown.length = 0;\n \n let defaultOption = document.createElement('option');\n defaultOption.text = 'Add Tags';\n \n dropdown.add(defaultOption);\n dropdown.selectedIndex = 0;\n \n fetch(`${BASEURL}/tags`) \n .then( \n function(response) { \n if (response.status !== 200) { \n console.warn('Looks like there was a problem. Status Code: ' + \n response.status); \n return; \n }\n response.json().then(function(data) { \n let option;\n \n for (let i = 0; i < data.length; i++) {\n option = document.createElement('option');\n option.text = data[i].name;\n option.value = data[i].id;\n option.id = data[i].name\n \n dropdown.add(option);\n } \n }); \n } \n ) \n .catch(function(err) { \n console.error('Fetch Error -', err); \n });\n }",
"function initierDropDowns() {\r\n console.log(\"initierDropDowns\");\r\n // Fyll inn dropdown for våpen\r\n initierDropDown(\"vaapen\", \"#selectVaapen\");\r\n initierListView(\"vaapen\", \"#vaapenList\");\r\n\r\n}",
"function initDropdown(){\n $.ajax({\n url: '/playlists',\n type: 'GET',\n contentType: 'application/json',\n success: function(res) {\n var pDrop = ``;\n for(var i=0; i<res.length; i++){\n pl = res[i]\n var addD = `<option id=${pl._id}>${pl.name}</option>`\n pDrop = pDrop.concat(addD);\n }\n $('select#selectPlaylist').html(pDrop);\n }\n }); //close ajax brack\n \n }",
"function fetchCountryList() {\n fetch('https://api.covid19api.com/countries')\n .then((response) => {\n return response.json();\n })\n .then((countries) => {\n countries.forEach((country) => {\n const option = document.createElement('option');\n option.value = country.Slug;\n option.innerText = country.Country;\n countryList.append(option);\n });\n // set default country value as india\n countryList.value = 'india';\n });\n}",
"function getDomains() {\n var domains = new Array();\n $(\"#edit-field-domain-access :checked\").each(function(index, obj) {\n domains.push(obj.value);\n });\n setOptions(domains);\n }",
"function initAdminAgencyDropdown() {\n\t\n\tvar dropdown = document.getElementById(\"agencyDropdown\");\n\t//if the dropdown box exists\n\tif(dropdown) {\n\t\t//clear the dropdown box\n\t\tdropdown.options.length = 0;\n\n\t\t//add every agency to the dropdown box\n\t\tvar i;\n\t\tfor(i in agencies) {\n\t\t\tvar agency = agencies[i];\n\t\t\tdropdown.add(new Option(agency.name), null);\n\t\t}\n\t}\n}",
"function initAdminProgramDropdown() {\n\tvar dropdown = document.getElementById(\"programDropdown\");\n\t//if the dropdown box exists\n\tif(dropdown) {\n\t\t//clear the dropdown box\n\t\tdropdown.options.length = 0;\n\t\t\n\t\t//add every program to the dropdown box\n\t\tvar i;\n\t\tfor(i in programs) {\n\t\t\tvar program = programs[i];\n\t\t\tdropdown.add(new Option(program.name), null);\n\t\t}\n\t}\n}",
"function newDeviceAvailableDom(){\n\tvar userid = userInformation[0].userId \n\tvar userinfo = userInformation[0].resourceDomain\n\tvar ctr = 0;var str = \"\";\n\tfor(var a =0; a< userinfo.length; a++){\n\t\tvar resource = userinfo[a];\n\t\tif (userinfo[a]==\"Default\"){var ctr =1;}\n\t\tstr += \"<option value='\"+resource+\"'>\"+resource+\"</option>\";\n\t}\n\tvar val = \"\"\n\tif (ctr==0){\n\t\tval += \"<option value='Default'>Default</option>\";\n\t\tval += str\n\t\t$(\"#dropdowndomain\").append(val);\n\t}else{\n\t\t$(\"#dropdowndomain\").append(str);\n\t}\n}",
"function loadSelect(select,data){\n\tvar options = buildOption(data);\n\tselect.html(options);\n}",
"function loadSolutionSelectData() {\n \"use strict\";\n createS_Option();\n}",
"function makeDropDownList(){\n fetchInfluencers.then(response => {\n response.json().then(data => {\n var dropdownlist = document.getElementById(\"dropdownlist\");\n for (i = 0; i <= data.data.length; i++) {\n var option = document.createElement(\"option\");\n option.setAttribute(\"label\",data.data[i])\n option.setAttribute(\"value\",data.data[i])\n dropdownlist.add(option);\n }\n })\n })\n}",
"function brand()\r\n{\r\n selBrand= def.options[def.selectedIndex].text;\r\n}",
"function loadcityshop(val)\n{\n\n\tif(document.getElementById('cityshopdetails')!=null)\n\t{\n\t\tdocument.getElementById('cityshopdetails').innerHTML=''; \n\t}\n\n\tif(val!='')\n\t{ \n\t\tif(document.getElementById('shoptag')!=null)\n\t\t{\n\t\t\tdocument.getElementById('shoptag').innerHTML=''; \n\t\t}\n\n\tloadurl(this.hostname+\"/site-admin/pages/loadstate.php?citycode=\"+val,\"cityshopdetails\");\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a configuration for the given `version` of a package at `packagePath`. | getPackageConfig(packageName, packagePath, version) {
const rawPackageConfig = this.getRawPackageConfig(packageName, packagePath, version);
return new ProcessedNgccPackageConfig(this.fs, packagePath, rawPackageConfig);
} | [
"get configVersion() {\n return '0.0.0'\n }",
"async function getConfigFromPackageJson() {\n const { repository } = await utils_1.loadPackageJson();\n if (!repository) {\n return;\n }\n const { owner, name } = parse_github_url_1.default(typeof repository === \"string\" ? repository : repository.url) || {};\n if (!owner || !name) {\n return;\n }\n return {\n repo: name,\n owner,\n };\n}",
"function getTsConfig(tsConfigPath) {\n if (tsConfigPath !== tsConfigPathCache) {\n tsConfigPathCache = tsConfigPath;\n tsConfigCache = readConfiguration(tsConfigPath);\n }\n return tsConfigCache;\n}",
"function ConfigPackageProvider(settings, params) {\n var self = Object.create(ConfigPackageProvider.prototype)\n self.config = params.config\n\n return self\n}",
"function getPackageInfo(installPackage) {\n if (installPackage.match(/^.+\\.(tgz|tar\\.gz)$/)) {\n return getTemporaryDirectory()\n .then(obj => {\n let stream;\n if (/^http/.test(installPackage)) {\n stream = hyperquest(installPackage);\n } else {\n stream = fs.createReadStream(installPackage);\n }\n return extractStream(stream, obj.tmpdir).then(() => obj);\n })\n .then(obj => {\n const { name, version } = require(path.join(obj.tmpdir, 'package.json'));\n obj.cleanup();\n return { name, version };\n })\n .catch(err => {\n // The package name could be with or without semver version, e.g. init-nose-server-0.2.0-alpha.1.tgz\n // However, this function returns package name only without semver version.\n log(`Could not extract the package name from the archive: ${err.message}`);\n const assumedProjectName = installPackage.match(/^.+\\/(.+?)(?:-\\d+.+)?\\.(tgz|tar\\.gz)$/)[1];\n log(`Based on the filename, assuming it is \"${chalk.cyan(assumedProjectName)}\"`);\n return Promise.resolve({ name: assumedProjectName });\n });\n } else if (installPackage.startsWith('git+')) {\n // Pull package name out of git urls e.g:\n // git+https://github.com/MohamedJakkariya/ins-template.git\n // git+ssh://github.com/mycompany/ins-template.git#v1.2.3\n return Promise.resolve({\n name: installPackage.match(/([^/]+)\\.git(#.*)?$/)[1]\n });\n } else if (installPackage.match(/.+@/)) {\n // Do not match @scope/ when stripping off @version or @tag\n return Promise.resolve({\n name: installPackage.charAt(0) + installPackage.substr(1).split('@')[0],\n version: installPackage.split('@')[1]\n });\n } else if (installPackage.match(/^file:/)) {\n const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];\n const { name, version } = require(path.join(installPackagePath, 'package.json'));\n return Promise.resolve({ name, version });\n }\n return Promise.resolve({ name: installPackage });\n}",
"function getVersion() {\n var contents = grunt.file.read(\"formulate.meta/Constants.cs\");\n var versionRegex = new RegExp(\"Version = \\\"([0-9.]+)\\\";\", \"gim\");\n return versionRegex.exec(contents)[1];\n }",
"function loadConfigurationFromPath(configFilePath) {\n if (configFilePath == null) {\n return exports.DEFAULT_CONFIG;\n }\n else {\n var resolvedConfigFilePath = resolveConfigurationPath(configFilePath);\n var rawConfigFile = void 0;\n if (path.extname(resolvedConfigFilePath) === \".json\") {\n var fileContent = utils_1.stripComments(fs.readFileSync(resolvedConfigFilePath)\n .toString()\n .replace(/^\\uFEFF/, \"\"));\n rawConfigFile = JSON.parse(fileContent);\n }\n else {\n rawConfigFile = require(resolvedConfigFilePath);\n delete require.cache[resolvedConfigFilePath];\n }\n var configFileDir_1 = path.dirname(resolvedConfigFilePath);\n var configFile = parseConfigFile(rawConfigFile, configFileDir_1);\n // load configurations, in order, using their identifiers or relative paths\n // apply the current configuration last by placing it last in this array\n var configs = configFile.extends.map(function (name) {\n var nextConfigFilePath = resolveConfigurationPath(name, configFileDir_1);\n return loadConfigurationFromPath(nextConfigFilePath);\n }).concat([configFile]);\n return configs.reduce(extendConfigurationFile, exports.EMPTY_CONFIG);\n }\n}",
"function package_info() {\n try {\n var pkg = require('../../package.json');\n return pkg;\n }\n catch (err) {\n return {\n name: 'aws-crt-nodejs',\n version: 'UNKNOWN'\n };\n }\n}",
"function readConfig (argv) {\n return new BB((resolve, reject) => {\n const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm'\n const child = spawn(npmBin, [\n 'config', 'ls', '--json', '-l'\n // We add argv here to get npm to parse those options for us :D\n ].concat(argv || []), {\n env: process.env,\n cwd: process.cwd(),\n stdio: [0, 'pipe', 2]\n })\n\n let stdout = ''\n if (child.stdout) {\n child.stdout.on('data', (chunk) => {\n stdout += chunk\n })\n }\n\n child.on('error', reject)\n child.on('close', (code) => {\n if (code === 127) {\n reject(new Error('`npm` command not found. Please ensure you have npm@5.4.0 or later installed.'))\n } else {\n try {\n resolve(JSON.parse(stdout))\n } catch (e) {\n reject(new Error('`npm config ls --json` failed to output json. Please ensure you have npm@5.4.0 or later installed.'))\n }\n }\n })\n })\n}",
"function getPackageInfoUrl(packageName) {\n const parts = packageName.split('/')\n if (parts.length !== 2) {\n throw new Error(`Invalid package name: \"${ packageName }\"`)\n }\n const vendor = parts[0]\n const name = parts[1]\n return `https://packagist.org/packages/${ vendor }/${ name }.json`\n}",
"function getFontAwesomeVersion() {\n return new Promise((resolve, reject) => {\n fs.readFile('node_modules/@fortawesome/fontawesome-pro/less/_variables.less', (e, data) => {\n if (e) {\n reject(e);\n } else {\n const match = data.toString().match(/fa-version:\\s+\"(.+)\";/);\n if (match) {\n resolve(match[1]);\n } else {\n reject('Pattern not found');\n }\n }\n });\n });\n}",
"function requireTailwindConfig(configPath) {\n try {\n const config = configPath\n ? require(configPath)\n : require(\"tailwindcss/defaultConfig\");\n return config;\n }\n catch (err) {\n throw new Error(`Tailwind config file not found '${configPath}' | ${err}`);\n }\n}",
"static getConfig(key) {\n return vscode.workspace.getConfiguration(constants_1.Constants.CONFIG_PREFIX).get(key);\n }",
"function retrieveConfiguration(url) {\n console.log(\"Configuration loading started\");\n console.log(\"Configuration loaded\");\n let result = axios.get(url);\n return result;\n}",
"get manifest(){\n if(fs.existsSync(path.join(this.root, 'package.json'))){\n return JSON.parse(fs.readFileSync(path.join(this.root, 'package.json')))\n }\n }",
"function resolveWithMinVersion(packageName, minVersionStr, probeLocations, rootPackage) {\n\t if (rootPackage && !packageName.startsWith(rootPackage)) {\n\t throw new Error(`${packageName} must be in the root package`);\n\t }\n\t const minVersion = new Version(minVersionStr);\n\t for (const location of probeLocations) {\n\t const nodeModule = resolve(packageName, location, rootPackage);\n\t if (nodeModule && nodeModule.version.greaterThanOrEqual(minVersion)) {\n\t return nodeModule;\n\t }\n\t }\n\t throw new Error(`Failed to resolve '${packageName}' with minimum version '${minVersion}' from ` +\n\t JSON.stringify(probeLocations, null, 2));\n\t}",
"function discoverPackageName(manifestPath, buildGradlePath) {\n if (manifestPath) {\n const androidManifest = _fs().default.readFileSync(manifestPath, 'utf8');\n const packageNameFromManifest = parsePackageNameFromAndroidManifestFile(androidManifest);\n // We got the package from the AndroidManifest.xml\n if (packageNameFromManifest) {\n return packageNameFromManifest;\n }\n }\n if (buildGradlePath) {\n // We didn't get the package from the AndroidManifest.xml,\n // so we'll try to get it from the build.gradle[.kts] file\n // via the namespace field.\n const buildGradle = _fs().default.readFileSync(buildGradlePath, 'utf8');\n const namespace = parseNamespaceFromBuildGradleFile(buildGradle);\n if (namespace) {\n return namespace;\n }\n }\n throw new (_cliTools().CLIError)(`Failed to build the app: No package name found. \n We couldn't parse the namespace from neither your build.gradle[.kts] file at ${_chalk().default.underline.dim(`${buildGradlePath}`)} \n nor your package in the AndroidManifest at ${_chalk().default.underline.dim(`${manifestPath}`)}\n `);\n}",
"function read(pathIn) {\n var myConfig = configObjectFromParamsOptions(getConfig());\n var myPath = pathIn.split('.');\n for (var i = 0; i < myPath.length; i++) {\n myConfig = typeof myConfig[myPath[i]] !== 'undefined' ? myConfig[myPath[i]] : myConfig[myPath[i]] = {};\n }\n var x = {};\n x[pathIn] = myConfig;\n return typeof myConfig === 'object' ? list(x) : pathIn + '=' + myConfig;\n }",
"getTargetProduct() {\n return this.getConfigId().then(() => {\n return this._edge.get(URIs.GET_CONFIGS, [false, false]).then(configs => {\n const config = configs.configurations.find(cfg => cfg.id === this._configId);\n if (config) {\n return config.targetProduct;\n } else {\n logger.error('No security configurations exist for this config ID - ' + this._configId);\n throw `No security configurations exist for this config ID - ${this._configId}`;\n }\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a new waypoint element after given waypoint index | function addWaypointAfter(idx, numWaypoints) {
//for the current element, show the move down button (will later be at least the next to last one)
var previous = $('#' + idx);
previous.children()[3].show();
//'move' all successor waypoints down from idx+1 to numWaypoints
for (var i = numWaypoints - 1; i >= idx + 1; i--) {
var wpElement = $('#' + i);
if (i < numWaypoints - 1) {
//this is not the last waypoint, show move down button
wpElement.children()[3].show();
}
wpElement.attr('id', i + 1);
}
//generate new id
var newIndex = parseInt(idx) + 1;
var predecessorElement = $('#' + idx);
var waypointId = predecessorElement.attr('id');
waypointId = waypointId.replace(idx, newIndex);
//generate DOM elements
var newWp = $('#Draft').clone();
newWp.attr('id', waypointId)
newWp.insertAfter(predecessorElement);
newWp.show();
//decide which buttons to show
var buttons = newWp.children();
//show remove waypoint + move up button
buttons[1].show();
buttons[2].show();
//including our new waypoint we are constructing here, we have one more waypoint. So we count to numWaypoints, not numWaypoints-1
if (newIndex < numWaypoints) {
//not the last waypoint, allow moving down
buttons[3].show();
} else {
buttons[3].hide();
}
//add event handling
newWp = newWp.get(0);
newWp.querySelector('.searchWaypoint').addEventListener('keyup', handleSearchWaypointInput);
newWp.querySelector('.moveUpWaypoint').addEventListener('click', handleMoveUpWaypointClick);
newWp.querySelector('.moveDownWaypoint').addEventListener('click', handleMoveDownWaypointClick);
newWp.querySelector('.removeWaypoint').addEventListener('click', handleRemoveWaypointClick);
newWp.querySelector('.searchAgainButton').addEventListener('click', handleSearchAgainWaypointClick);
newWp.querySelector('.waypoint-icon').addEventListener('click', handleZoomToWaypointClick);
theInterface.emit('ui:addWaypoint', newIndex);
} | [
"function handleAddWaypointClick(e) {\n //id of prior to last waypoint:\n var waypointId = $(e.currentTarget).prev().attr('id');\n var oldIndex = parseInt(waypointId);\n addWaypointAfter(oldIndex, oldIndex + 1);\n theInterface.emit('ui:selectWaypointType', oldIndex);\n var numwp = $('.waypoint').length - 1;\n }",
"function add_elem(element, index) {\n //Get old element and copy to new element\n var ul = document.getElementById(element);\n var li_old = ul.children[ul.children.length-1];\n var li_new = li_old.cloneNode(true); \n\n //Empty values and change index\n EmptyValues(li_new);\n ChangeIndex(li_new, index+1);\n\n //Change index of all following elements in list.\n for (var i=index+1; i<ul.children.length; i++)\n ChangeIndex(ul.children[i], i+1);\n \n //Insert element at given position.\n InsertIntoList(ul, li_new, index);\n}",
"function addLocation()\r\n{\r\n let newWaypoint = currentRoute.routeMarker.getPosition();\r\n currentRoute.waypoints.push(newWaypoint);\r\n currentRoute.displayPath();\r\n}",
"function handleMoveUpWaypointClick(e) {\n //index of waypoint\n var waypointElement = $(e.currentTarget).parent();\n var index = parseInt(waypointElement.attr('id'));\n var prevIndex = index - 1;\n var previousElement = $('#' + prevIndex);\n waypointElement.insertBefore(previousElement);\n //adapt IDs...\n previousElement.attr('id', index);\n waypointElement.attr('id', prevIndex);\n //define the new correct order\n var currentIndex = prevIndex;\n var succIndex = index;\n //-1 because we have an invisible draft waypoint\n var numWaypoints = $('.waypoint').length - 1;\n //decide which button to show\n if (currentIndex === 0) {\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).hide();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n } else {\n //show both\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n if (succIndex == (numWaypoints - 1)) {\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).hide();\n } else {\n //show both\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:movedWaypoints', {\n id1: currentIndex,\n id2: succIndex\n });\n theInterface.emit('ui:routingParamsChanged');\n }",
"function setWaypointType(wpIndex, type) {\n //Keep this in order to not cause any bugs in functions relying on this\n var el = $('#' + wpIndex);\n // var el = $('#' + wpIndex);\n el.removeClass('unset');\n el.removeClass('start');\n el.removeClass('via');\n el.removeClass('end');\n el.addClass(type);\n el = $('#' + wpIndex).children('.waypoint-icon');\n // var el = $('#' + wpIndex);\n el.removeClass('unset');\n el.removeClass('start');\n el.removeClass('via');\n el.removeClass('end');\n el.addClass(type);\n }",
"function movewagon (wagonidx, railidx, whendone) {\n whendone = whendone || function(){};\n var domrail = document.getElementById('p' + railidx);\n wagons[wagonidx].railidx = railidx;\n alongsegment(wagons[wagonidx], datafrompath(domrail),\n airport.wagons[wagonidx].speed, function () {\n whendone(wagonidx, railidx);\n });\n}",
"function handleRemoveWaypointClick(e) {\n var numWaypoints = $('.waypoint').length - 1;\n var currentId = parseInt($(e.currentTarget).parent().attr('id'));\n var featureId = $(e.currentTarget).parent().get(0);\n featureId = featureId.querySelector('.address');\n if (featureId) {\n featureId = featureId.id;\n } else {\n featureId = null;\n }\n //we want to show at least 2 waypoints\n if (numWaypoints > 2) {\n //'move' all successor waypoints up from currentId to currentId-1\n for (var i = currentId + 1; i < numWaypoints; i++) {\n var wpElement = $('#' + i);\n wpElement.attr('id', (i - 1));\n }\n $(e.currentTarget).parent().remove();\n } else {\n var wpElement = $(e.currentTarget).parent();\n var wpIndex = wpElement.attr('id');\n //delete waypoint\n wpElement.remove();\n //generate an empty waypoint\n var draftWp = $('#Draft');\n var newWp = draftWp.clone();\n newWp.attr('id', wpIndex);\n if (wpIndex > 0) {\n newWp.insertAfter($('#' + (wpIndex - 1)));\n } else {\n newWp.insertAfter(draftWp);\n }\n newWp.show();\n //decide which buttons to show\n var buttons = newWp.children();\n //show remove waypoint\n buttons[1].show();\n if (wpIndex == 1) {\n //show only move down button\n buttons[3].hide();\n buttons[2].show();\n } else if (wpIndex == 0) {\n //show only move up button\n buttons[2].hide();\n buttons[3].show();\n }\n //add event handling\n newWp = newWp.get(0);\n newWp.querySelector('.searchWaypoint').addEventListener('keyup', handleSearchWaypointInput);\n newWp.querySelector('.moveUpWaypoint').addEventListener('click', handleMoveUpWaypointClick);\n newWp.querySelector('.moveDownWaypoint').addEventListener('click', handleMoveDownWaypointClick);\n newWp.querySelector('.removeWaypoint').addEventListener('click', handleRemoveWaypointClick);\n newWp.querySelector('.searchAgainButton').addEventListener('click', handleSearchAgainWaypointClick);\n newWp.querySelector('.waypoint-icon').addEventListener('click', handleZoomToWaypointClick);\n }\n theInterface.emit('ui:removeWaypoint', {\n wpIndex: currentId,\n featureId: featureId\n });\n }",
"function handleReorderWaypoints() {\n var j = 1;\n var i = $('.waypoint').length - 1;\n // last waypoint is inserted before first and j is incremented\n // so in the second run last waypoint is inserted before second item etc.\n // this is repeated as long as j is smaller i\n while (j < i) {\n var waypointElement = $('.waypoint').last();\n var swapElement = $('.waypoint').eq(j);\n waypointElement.insertBefore(swapElement);\n // internal ids are updated\n $('.waypoint').each(function(index) {\n if ($(this).attr('id') != 'Draft') {\n $(this).attr('id', index - 1);\n }\n });\n j++;\n }\n // create object with indices\n var indices = {};\n $('.waypoint').each(function(index) {\n if ($(this).attr('id') != 'Draft') {\n indices[index] = index - 1;\n }\n });\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $('#' + 0 + '> .moveUpWaypoint').hide();\n $('#' + 0 + '> .moveDownWaypoint').show();\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n var lastWp = $('.waypoint').length - 2;\n $('#' + lastWp + '> .moveUpWaypoint').show();\n $('#' + lastWp + '> .moveDownWaypoint').hide();\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:inverseWaypoints', indices);\n theInterface.emit('ui:routingParamsChanged');\n }",
"addAtIndex(task, index) {\n if(index === 0) {\n this.addToFront(task);\n } else if(index === this._taskArr.length) {\n this.addToBack(task);\n } else if(index < this._taskArr.length) {\n this._taskArr.splice(index,0, task);\n this.adjustTaskStartTime(index + 1);\n }\n }",
"function buildWaypoint(mapLayer, wpType, address, viaCounter, distance, duration) {\n var directionsContainer = new Element('div', {\n 'class': 'directions-container clickable',\n 'data-layer': mapLayer,\n });\n var icon;\n if (wpType == 'start') {\n icon = new Element('i', {\n 'class': 'fa fa-map-marker'\n });\n } else if (wpType == 'via') {\n icon = new Element('span', {\n 'class': 'badge badge-inverse'\n }).update(numStopovers);\n } else {\n icon = new Element('i', {\n 'class': 'fa fa-flag'\n });\n }\n var wayPoint = new Element('div', {\n 'class': 'instr-waypoint',\n });\n wayPoint.appendChild(icon);\n var shortAddress = new Element('div', {\n 'class': 'address',\n 'waypoint-id': viaCounter\n }).update(address);\n // modeContainer\n var directionsModeContainer = new Element('div', {\n 'class': 'directions-mode-container'\n });\n var directionsBorder = new Element('div', {\n 'class': 'line'\n });\n directionsContainer.appendChild(wayPoint);\n // add info if via or endpoint\n if (wpType == 'end' || wpType == 'via') {\n var pointInfo = new Element('div', {\n 'class': 'info'\n }).update(Number(duration / 60).toFixed() + ' min' + ' / ' + Number(distance / 1000).toFixed(2) + ' km');\n directionsContainer.appendChild(pointInfo);\n }\n directionsContainer.appendChild(shortAddress);\n directionsModeContainer.appendChild(directionsBorder);\n directionsContainer.appendChild(directionsModeContainer);\n return directionsContainer;\n }",
"function reorderPlus(id){\n x= id, y= id-1;\n yourtourids[x] = yourtourids.splice(y, 1, yourtourids[x])[0];\n updateTour();\n}",
"function adjustIndex(index) {\r\n if(index > 806) { // Any index after 806 is when PokeAPI starts numbering pokemon starting with 10001\r\n index -= 806;\r\n index += 10000;\r\n return index;\r\n }\r\n\r\n return index + 1;\r\n}",
"addNewImageToSlider(idx) {\n let addedImagedata = this.images[idx];\n let slide = '<div class=\"swiper-slide\"><img src=\"' +\n addedImagedata +\n '\" alt=\"Image\"/></div>';\n this.mySwiper.appendSlide(slide);\n }",
"insertAt(idx, val) {\n if(idx>this.length||idx<0){\n throw new Error(\"invalid index\");\n }\n\n if(idx===0) return this.unshift(val);\n if(idx===this.length) return this.push(val);\n\n let prev=this._get(idx-1);\n let newNode=new Node(val);\n newNode.next=prev.next;\n prev.next=newNode;\n this.length+=1;\n }",
"function addNextWord() {\n let words = controller.words.split(\", \"),\n nextWord = words[controller.currentWordIndex]\n\n // Create Points\n pnts = createPoints(nextWord)\n\n // Add Word\n drawingLetters = new Letter(nextWord, pnts)\n\n if (words.length - 1 > controller.currentWordIndex) {\n controller.currentWordIndex++\n } else {\n controller.currentWordIndex = 0\n }\n}",
"insertAt(idx, val) {\n try {\n if (idx > this.length || idx < 0) throw new Error('Index is invalid!');\n\n //case add before first node (unshift)\n if (idx === 0) {\n this.unshift(val);\n //case add after last node (push)\n } else if (idx === this.length) {\n this.push(val)\n //case update in middle of list\n } else {\n let newNode = new Node(val);\n let previousNode = this._getNode(idx - 1);\n \n newNode.next = previousNode.next;\n previousNode.next = newNode;\n\n this.length += 1;\n }\n } catch (e) {\n console.warn(e);\n }\n }",
"function genWayPoints()\n{\n\tvar ix = 0;\n\n\tvar numWayPoints = waypoints.length\n\tvar bounds = new google.maps.LatLngBounds();\n\tvar iw = new google.maps.InfoWindow();\n\tvar totDistance = 0;\t\t// Total distance for trip\n\tvar aryPrevWpt;\n\tconsole.log(\"Starting new Waypoints:\");\n\t\n\tfor (var kx in waypoints)\n\t{ \n\t\tif(++ix >= 26) ix = 0 // 26 letters in the alphabet\n\t\tvar thisCode = String.fromCharCode(65 + ix) + \".png\"\t// Create the waypoint alphabetic label\n\t\tvar thisPath = \"icons/markers/\";\n\t\n\t\t// Assume a normal marker\n\t\tvar wptColor = thisPath + \"green_Marker\" + thisCode \n\t\n\t\t// If there was a tag associated with this, make it BLUE, unless it was queued\n\t\tif(waypoints[kx][\"tag\"] != \"0\") wptColor = thisPath + \"blue_Marker\" + thisCode\n\n\t\t// If it was queued, we lose the BLUE tag - / Indicates queued/deferred item\n\t\tif(waypoints[kx][\"flg\"] == \"1\") wptColor = thisPath + \"red_Marker\" + thisCode\n\n\t\t // Indicates first after queued/deferred items, use Yellow\n\t\t if(waypoints[kx][\"flg\"] == \"3\") wptColor = thisPath + \"yellow_Marker\" + thisCode \n\t \n\t\t // Generate the WayPoint\n\t\t var latlng = {lat: Number(waypoints[kx][\"gpslat\"]), lng: Number(waypoints[kx][\"gpslng\"])};\n\t\t bounds.extend(latlng)\n\t \n\t\t var latlngA = waypoints[kx][\"gpslat\"] + \", \" + waypoints[kx][\"gpslng\"];\n\n\t\t var wpt = new google.maps.Marker({icon: wptColor, \n\t\t\t\t\t\t\t\t\t\t position: latlng, \n\t\t\t\t\t\t\t\t\t\t title: latlngA}) \n\t\t wpt.setMap(map);\t\t// Display the waypoint\t\t \n\t\t markers.push(wpt);\t\t// Save the Waypoint\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now make sure we have the Cell Tower\n\t\t genCellTower(waypoints[kx][\"cid\"], kx);\n\t \n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now generate the info for this point\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\t\t// Get distance to cell tower and between waypoints\n\t\tvar arycel = {lat: Number(waypoints[kx][\"gsmlat\"]) , lng: Number(waypoints[kx][\"gsmlng\"])}\n\t\tvar distToCell = distCalc(latlng, arycel)\n\t\n\t\tvar thisDist = (aryPrevWpt == null ? 0 : distance(Number(waypoints[kx][\"gpslat\"]), Number(waypoints[kx][\"gpslng\"]), Number(aryPrevWpt[\"lat\"]), Number(aryPrevWpt[\"lng\"]), \"M\"))\n\n\t\ttotDistance += thisDist\n\t\taryPrevWpt = latlng\n\t\n\t\tif(LOG_DS == true)\n\t\t{\n\t\t\tconsole.log(\"thisDist \",thisDist);\n\t\t\tconsole.log(\"totDist \",totDistance);\n\t\t}\n\t\n\t\t// This is a function type called \"closure\" - no idea how it works, but it does\n\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\taryInfoVars[\"iv\" + kx] = \n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\"</div></div>\"\n\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.setContent(aryInfoVars[\"iv\" + kx]);\n\n\t\t\t// Generate the Listener\n\t\t\twpt.addListener('click', function() {iw.open(map, wpt)})\n\t\t})(kx, wpt);\n\t\t//\n\t\t/*\n\t\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\tgoogle.maps.event.addListener(wpt, 'click',\n\t\t\t\tfunction() {\n\t\t\t\t\tvar iw = \n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\t\"</div></div>\"\n\t\t\t\t});\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.open(map, wpt);\n\t\t\tbacs0 ----})(kx, wpt);\n\t\t*/\n\t}\t// End of For Loop\n\n\t// Now adjust the map to fit our waypoints\n\tmap.fitBounds(bounds);\n\n\t// Generate the pathways to the cell towers\n\tgenPathways(waypoints);\n\n}",
"move(field, index) {\n return spPost(ViewFields(this, \"moveviewfieldto\"), request_builders_body({ field, index }));\n }",
"function updateLiveAtStart(index) {\n let limit = (index + 3 < startlist.length)?(index + 3):startlist.length;\n\n var row = 1;\n // load ranking data\n for(i = limit - 1 ; i >= index ; i--) {\n startlist[i].rank = i + 1; // it is pos value\n addToRankingList(\"live-atstart\", row++, startlist[i]);\n }\n clearRankingRemains(\"live-atstart\", row);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the dialog to create a new virtual folder | newVirtualFolder(aName, aSearchTerms, aParent) {
let folder = aParent || GetSelectedMsgFolders()[0];
if (!folder)
folder = GetDefaultAccountRootFolder();
let name = folder.prettyName;
if (aName)
name += "-" + aName;
window.openDialog("chrome://messenger/content/virtualFolderProperties.xul",
"", "chrome,modal,centerscreen",
{folder: folder, searchTerms: aSearchTems,
newFolderName: name});
} | [
"function createNewFolder() {\n var id = $(this).parent().attr(\"data-id\");\n fileSystem.createFileOrFolder(id, \"folder\");\n updateUI();\n }",
"editVirtualFolder(aFolder) {\n let folder = aFolder || GetSelectedMsgFolders()[0];\n\n function editVirtualCallback(aURI) {\n // we need to reload the folder if it is the currently loaded folder...\n if (gMsgFolderSelected && aURI == gMsgFolderSelected.URI) {\n // force the folder pane to reload the virtual folder\n gMsgFolderSelected = null;\n FolderPaneSelectionChange();\n }\n }\n window.openDialog(\"chrome://messenger/content/virtualFolderProperties.xul\",\n \"\", \"chrome,modal,centerscreen\",\n {folder: folder, editExistingFolder: true,\n onOKCallback: editVirtualCallback,\n msgWindow:msgWindow});\n }",
"function newFolderActionHandle(_container, _context, _fileTablePanel){\n\t\t\ton(registry.byId(\"da_newFolderMenuItem\"), \"click\", function(){\n\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\tdialog.show();\n\t\t\t});\n\n\t\t\t//new folder\n\t\t\ton(registry.byId(\"de_dialog_newFolder_okBtn\"), \"click\", function(){\n\t\t\t\tvar inputValue = registry.byId(\"de_dialog_newFolder_dirName\").value;\n\t\t\t\t\n\t\t\t\tvar cHost = _fileTablePanel.getHost();\n\t\t\t\tvar cPath = _fileTablePanel.getPath();\n\t\t\t\t\n\t\t\t\tvar url = _context.contextPath + \"/webservice/pac/data/action/mkdir?rnd=\" + (new Date()).getTime();\n\t\t\t\tvar path = encodeURIComponent(cPath + \"/\" + inputValue);\n\t\t\t\tvar postData = \"filePath=\" + path + \"&hostName=\" + cHost;\n\n\t\t\t\trequest.post(url, {\n\t\t\t\t\tdata : postData\n\t\t\t\t}).then(function(data) {\n\t\t\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\t\t\tif(data != null && data != \"\"){\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t\tshowMessage(data);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t//close the dialog and refrsh the file table\n\t\t\t\t\t\t\t_fileTablePanel.refresh(cHost, cPath);\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, function(err) {\n\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t}, function(evt) {\n\t\t\t\t\t\t//console.log(evt);\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"function setupCreateNewPathwayButton() {\n var newItem;\n $(\"div[name='createNewPathway']\").click(function(){\n if ( newItem == undefined )\n newItem = \n\t\tcreateDialog(\"div.createPathway\", \n\t\t\t\t{position:[250,150], width: 700, height: 350, \n\t\t\t\ttitle: \"Create a New Pathway Analysis\"});\n $.get(\"pathway.jsp\", function(data){\n newItem.dialog(\"open\").html(data);\n\t\tcloseDialog(newItem);\n });\n });\n}",
"function NewFilePrompt() {\n $(\"div#overlay-header\").html(\"New File\");\n $(\"div#overlay-body\").html($(\"div#overlay-templates div.overlay-new-file\").html());\n $(\"div#force-overlay\").css(\"display\", \"block\");\n}",
"newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)\n\t\t\t\treturn\n\t\t\t\n\t\t\tlet ws = wmaster.addWorkspace(result)\n\t\t\tthis.setWorkspace(ws)\n\t\t\t\n\t\t\t// display loading indicator\n\t\t\tthis.body.innerHTML = `<div class=\"abs-fill flex-col\" style=\"justify-content: center\"><div style=\"align-self: center\">...</dib></div>`\n\t\t})\n\t}",
"function FilesDlg(form, element,directory, tag_id) {\n tag_id = parseInt(\"0\"+tag_id)*1;\n window.open('?page=filestoragedlg&isOpen=1&form=' + form + '&element=' + element + '&directory=' + directory + '&tag_id=' + tag_id,\n 'FilesDlg', 'menubar=no,width=400,height=400,scrollbars=yes,resizable=no');\n }",
"function KeyCreateFolder(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n CreateFolder();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}",
"function setupCreateNewList() {\n\tvar newList;\n\t// setup create new gene list button\n\t$(\"div[name='createGeneList']\").click(function(){\n \tif ( newList == undefined ) {\n\t\t\tvar dialogSettings = {width: 800, height: 600, title: \"<center>Create Gene List</center>\"};\n\t\t\t/* browser.safari true means the browser is Safari */\n\t\t\t//if ($.browser.safari) $.extend(dialogSettings, {modal:false});\n\t\t\tnewList = createDialog(\"div.newGeneList\", dialogSettings); \n\t\t}\n \t$.get(\"createGeneList.jsp\", function(data){\n\t\t\tnewList.dialog(\"open\").html(data);\n \t});\n\t});\n}",
"function onNewPugClick() {\n Global.pageHandler.doRedirectToPage( \"new\" );\n }",
"function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}",
"createProject(event) {\n const controller = event.data.controller;\n const warning = new WarningDialog(() => {\n controller.createNewProject();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.createAfterWarning = false;\n }",
"createLibrary(event) {\n const controller = event.data.controller;\n InputDialog.type = 'createLibrary';\n const dialog = new InputDialog((input) => {\n if (null == controller.createLibrary(input)) {\n InfoDialog.showDialog('A library' +\n ' with this name already exists!');\n }\n }, 'New Library', null);\n dialog.show();\n }",
"function onDirectoryClick()\n\t{\n\t\tmoveToDirectory( this.getAttribute('data-path') + '/', true );\n\t}",
"function showOpenSeed (opts) {\n setTitle(opts.title)\n const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts)\n resetTitle()\n if (!Array.isArray(selectedPaths)) return\n windows.main.dispatch('showCreateTorrent', selectedPaths)\n}",
"toggleSidenavNewFile() {\n if (this._sidenavExtra.newFile.opened) {\n this._sidenavExtra.newFile.opened = false;\n\n $('#hidden-new-file').hide();\n $('#new-file-name').val('');\n $('#hidden-new-file-info').empty();\n } else {\n this._sidenavExtra.newFile.opened = true;\n $('#hidden-new-file').fadeIn('fast');\n }\n }",
"function openAddNewDriveWindow() {\n activateOverlay()\n document.getElementById(\"drive-list\").style.pointerEvents = \"none\";\n document.getElementById(\"add-new-drive-window\").style.display = \"block\"\n document.getElementById(\"close-add-drive-window\").addEventListener(\"click\", closeAddNewDriveWindow)\n getUnaddedDrivList()\n}",
"function createFolder(auth) {\r\n\tconst drive = google.drive({version: 'v3', auth}); \r\n\t\r\n\tvar fileMetadata = {\r\n\t\t'name': DRIVE_PATH,\r\n\t\tmimeType: 'application/vnd.google-apps.folder'\r\n\t};\r\n\r\n\tdrive.files.create(\r\n\t\t{\r\n\t\t\tresource: fileMetadata,\r\n\t\t\tfields: 'id'\r\n\t\t}, \r\n\t\t(err, folder) => {\r\n\t\t\tif (err) {\r\n\t\t\t console.error(err);\r\n\t\t\t} else {\r\n\t\t\t DRIVE_PATH_ID = folder.data.id;\r\n\t\t\t console.log('Created folder with id: ', folder.data.id);\r\n\t\t\t}\r\n\t\t}\r\n\t);\r\n}",
"function newRobotWindow() {\n\tvar robotWindow = window.open(\"Images/robot.png\", \"robotWindow\", \"resizable=no,width=400,height=300\");\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET Recupera todas las notas que sean favoritas | function getAllFavNotes(req, res) {
//Query a mongoDB
Note.find({favorite:1}, (err, notes) => {
//Compruebo si hay algun error en el callback
if (err) return res.status(500)
.send({
message: `Se ha producido un error: ${err}`
})
//Comprueba si trae valores
if (!notes) return res.status(404)
.send({
message: 'La consulta no a recuperado ningún valor.'
})
//Respuesta con valores
res.status(200).send({
notes
})
})
} | [
"getFavorites() {\n\t\treturn apiFetch(\n\t\t\t{\n\t\t\t\tpath: '/vtblocks/v1/layouts/favorites',\n\t\t\t\tmethod: 'GET',\n\t\t\t}\n\t\t).then(\n\t\t\tfavorite_keys => {\n\t\t\t\tlet favorites = [];\n\n\t\t\t\tObject.values( this.state.all ).forEach( function( item ) {\n\t\t\t\t\tif ( favorite_keys.includes( item.key ) ) {\n\t\t\t\t\t\tfavorites.push( item );\n\t\t\t\t\t}\n\t\t\t\t} );\n\n\t\t\t\treturn favorites;\n\t\t\t}\n\t\t).catch(\n\t\t\terror => console.error( error )\n\t\t);\n\t}",
"getFavoriteKeys() {\n\t\treturn apiFetch(\n\t\t\t{\n\t\t\t\tpath: '/vtblocks/v1/layouts/favorites',\n\t\t\t\tmethod: 'GET',\n\t\t\t}\n\t\t).then(\n\t\t\tfavorite_keys => {\n\t\t\t\treturn favorite_keys;\n\t\t\t}\n\t\t).catch(\n\t\t\terror => console.error( error )\n\t\t);\n\t}",
"async function list(req, res, next) {\n try {\n const data = await moviesService.list();\n const { is_showing } = req.query;\n const byResult = is_showing\n ? (movie) => movie.is_showing == true\n : () => true; // if given query parameter is_showing, return only movies with is_showing == true\n res.json({ data: data.filter(byResult) });\n } catch (error) {\n next(error);\n }\n}",
"function isRemoveFromFavoriets(req,res)\n{\n return checkTable(req,'favorites')\n}",
"static getFavoriteRestaurants() {\r\n return DBHelper.goGet(\r\n `${DBHelper.RESTAURANT_DB_URL}/?is_favorite=true`,\r\n \"❗💩 Error fetching favorite restaurants: \"\r\n );\r\n }",
"function getFavorites(username){\n\t$.ajax({\n\t url: Url+'/getfavs?Username='+username,\n\t type: \"GET\",\n\t success: listFavorites,\n\t error: displayError,\n\t})\n}",
"function getFavorites(success, error){\n let baseUrl = \"/favorites\";\n baseXHRGet(baseUrl, success, error);\n }",
"function getFavoriteFact(number) {\n const resp = axios.get(`${BASE_URL}/${number}?json`);\n return resp;\n}",
"getFavoriteBooks(userId) {\n this.userId = userId;\n // Check if user is in database\n const usersData = readData(usersFile);\n const userIndex = findUser(userId);\n if (userIndex < 0) return { statusCode: '402', message: 'Unauthenticated user' };\n\n // Check if user has favorite books\n if (!usersData.users[userIndex].favorites) return { statusCode: '404', message: 'Favorites not found' };\n\n // Push each favorite book to favorites book array\n const booksData = readData(booksFile);\n const favoritesArray = usersData.users[userIndex].favorites;\n let favoriteBooks = [];\n favoritesArray.forEach((fav) => {\n const bookObject = booksData.books.filter(book => book.id === fav);\n favoriteBooks = [...favoriteBooks, ...bookObject];\n });\n return { statusCode: '200', message: favoriteBooks };\n }",
"function get_badgesNoOtorgados() {\n fct_MyLearn_API_Client.query({ type: 'Proyectos', extension1: 'BadgesNoOtorgados', extension2: $routeParams.IdCurso, extension3: $routeParams.IdTrabajo }).$promise.then(function (data) {\n $scope.ls_badgesSA = data;\n });\n }",
"requested(userId) {\n return this.getList(userId, STATE_KEY.requested);\n }",
"function checkIfFavourite() {\n const url = '/albumFavourite';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json()\n } else {\n }\n })\n .then((favouriteAlbum) => { // the resolved promise with the JSON body\n for( let i = 0; i < favouriteAlbum.length; i++ )\n {\n if(favouriteAlbum[i]._id == album._id )\n {\n isFavourite = true\n }\n }\n styleFavouriteButton();\n }).catch((error) => {\n })\n}",
"function getFavoriteMovies() {\n\t\tlet movieId = $('.movie-id').val();\n\n\t\t$.ajax({\n\t\t\turl: \"/favorites/all\",\n\t\t\tmethod: \"GET\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: 'json',\n\n\t\t\tcomplete : function(data){ \t\n\t\t\t\tjQuery.each(data.responseJSON, function(index, item) {\n\t\t\t\t\t//favoriteMovies(item.movieId, item.user.id);\n\n\t\t\t\t\tif (item.movieId == movieId && item.user.id == myId) {\n\t\t\t\t\t\t$('.add-to-favorite').addClass(\"is-favorite\")\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},fail : function(){\n\t\t\t\tconsole.log(\"Failed getting favorite movies\");\n\t\t\t}\n\t\t});\n\t}",
"function filterFavoritesIfAppliable() {\n const favs = $('#favs');\n if (favs.text().localeCompare('My favorites') == 0) {\n const favorites = User.getFavoritesText();\n $('#fixtures tr').filter(function() {\n // The league and teams infos are only on the 3 first tds\n const arrayOfDisplayed = $(this).children('td').slice(0, 3).map(function() { // eslint-disable-line no-invalid-this\n return $(this).text().trim(); // eslint-disable-line no-invalid-this\n }).get();\n $(this).toggle(favorites.some((element) => arrayOfDisplayed.includes(element))); // eslint-disable-line no-invalid-this\n });\n } else {\n $('#fixtures tr').toggle(true);\n }\n}",
"function getFavorito(req,res){\n var favoritoId= req.params.id;\n //para buscar ese favorito\n Favorito.findById(favoritoId,function(err,favorito){\n if(err){\n res.status(500).send({message:'error al devolver marcador'})\n }\n else{\n if (!favorito){\n res.status(404).send({message:'No existe el marcador'})\n }\n else{\n res.status(200).send({ favorito})\n }\n }\n \n })\n \n}",
"async function getOtherUsersFavorites(userId){\n const query = \"SELECT DISTINCT b.bname AS 'Band' FROM Bands b JOIN Favorites f ON f.band_id = b.bid JOIN `User` u ON u.uid = f.uid WHERE u.uid IN (SELECT u.uid FROM `User` u2 JOIN Favorites f2 ON f2.uid = u2.uid JOIN Bands b2 ON b2.bid = f2.band_id WHERE u2.uid != ? AND b2.bname IN (SELECT b2.bname FROM `User` u3 JOIN Favorites f3 ON f3.uid = u3.uid JOIN Bands b3 ON b3.bid = f3.band_id WHERE u3.uid = ?)) AND b.bname NOT IN (SELECT b4.bname FROM `User` u4 JOIN Favorites f4 ON f4.uid = u4.uid JOIN Bands b4 ON b4.bid = f4.band_id WHERE u4.uid = ?);\";\n try {\n const [rows] = await conn.execute(query, [userId, userId, userId]);\n return rows;\n } catch (err) {\n console.error(err);\n return [];\n }\n }",
"getItemsUnsaved(){ return this.state.list.filter(function(el){ return el.saved == false})}",
"accepted(userId) {\n return this.getList(userId, STATE_KEY.accepted);\n }",
"getUnseen() {\n\t\tlet unseen = [];\n\t\tfor (let question of this.conv.user.storage.history.history) {\n\t\t\tif (!question || !question.seenCount || question.seenCount === 0) {\n\t\t\t\tunseen.push(question.questionNumber);\n\t\t\t}\n\t\t}\n\t\treturn unseen;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manage billing groups [BETA] [See on api.ovh.com]( | CreateANewBillingGroup(payload) {
let url = `/me/billing/group`;
return this.client.request('POST', url, payload);
} | [
"postV3GroupsIdAccessRequests(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group ID\napiInstance.postV3GroupsIdAccessRequests(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function entityGroups() {\n // Define the data object and include needed parameters.\n // Make the groups API call and assign a callback function.\n}",
"getV3GroupsIdAccessRequests(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group I\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3GroupsIdAccessRequests(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3GroupsId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The ID of a grou\n/*let opts = {\n 'UNKNOWN_BASE_TYPE': new Gitlab.UNKNOWN_BASE_TYPE() // UNKNOWN_BASE_TYPE | \n};*/\napiInstance.putV3GroupsId(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3GroupsIdMembers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3GroupsIdMembers(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3GroupsIdNotificationSettings(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group ID or project ID or project NAMESPACE/PROJECT_NAME\napiInstance.getV3GroupsIdNotificationSettings(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3GroupsIdNotificationSettings(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group ID or project ID or project NAMESPACE/PROJECT_NAM\n/*let opts = {\n 'UNKNOWN_BASE_TYPE': new Gitlab.UNKNOWN_BASE_TYPE() // UNKNOWN_BASE_TYPE | \n};*/\napiInstance.putV3GroupsIdNotificationSettings(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"listAllGroups () {\n return this._apiRequest('/groups/all')\n }",
"postV3GroupsIdProjectsProjectId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The ID of a grou\n/*let projectId = \"projectId_example\";*/ // String | The ID or path of the project\napiInstance.postV3GroupsIdProjectsProjectId(incomingOptions.id, incomingOptions.projectId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"userGroups (id) {\n return this._apiRequest(`/user/${id}/groups`)\n }",
"deleteV3GroupsIdAccessRequestsUserId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The group I\n/*let userId = 56;*/ // Number | The user ID of the access requester\napiInstance.deleteV3GroupsIdAccessRequestsUserId(incomingOptions.id, incomingOptions.userId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"function createPaymentGroup() {\n if (vm.new_payment_group_form.$valid) {\n Merchant.create('payment_group',vm.new_payment_group).then(function(response) {\n vm.payment_groups.push(response.data.new_payment_group);\n $(\"#add-payment-group-modal\").modal(\"toggle\");\n });\n }\n }",
"function add_group_response() {\n var group_number = $groups.children().length + 1;\n var button = '<input type=\"button\" class=\"btn btn-md btn-primary \" style=\"margin: 0em 1em 1em 0em\" id=\"grp' + group_number + '\" value=\"Group ';\n button += group_number + ' - '+ 0;\n button += '\" />';\n $groups.append(button);\n}",
"getGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`)\n }",
"function generateButtons(edit = false){\n chrome.storage.local.get(\"groups\", function(data) {\n sortedGroupNames(function(groupNames) {\n let groups = data[\"groups\"]; //Enter groups object\n let openGroupButtons = document.getElementById(\"openGroupButtons\");\n if (groupNames.length === 0){\n document.getElementById(\"openGroupButtons-empty\").style.display = \"block\";\n }\n let animDelay = 0;\n for (groupName of groupNames) {\n //A holder for a group's buttons\n let groupDiv = generateGroupDiv(groupName, groups, animDelay, edit);\n let dropDown = generateDropdown(groupName, groups, edit);\n groupDiv.appendChild(dropDown);\n //Append the div to the document\n openGroupButtons.appendChild(groupDiv);\n if (edit){\n for (element of document.getElementsByClassName(\"editGroups\")) {\n element.style.display = \"table-cell\";\n }\n }\n animDelay = animDelay + 1;\n }\n });\n });\n}",
"function dwscripts_applyGroup(groupName, paramObj)\n{\n // queue the group edits\n dwscripts.queueDocEditsForGroup(groupName, paramObj);\n\n // Commit all scheduled edits\n dwscripts.applyDocEdits();\n}",
"async getDiseaseGroups({ commit }) {\n let json = await fetch(\n `${BIO_INDEX_HOST}/api/portal/groups`\n ).then(resp => resp.json());\n\n // set the portal list\n commit(\"setDiseaseGroups\", json.data);\n }",
"getV3GroupsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The ID of a grou\n/*let opts = {\n 'state': \"'opened'\", // String | Return opened, closed, or all issues\n 'labels': \"labels_example\", // String | Comma-separated list of label names\n 'milestone': \"milestone_example\", // String | Return issues for a specific milestone\n 'orderBy': \"'created_at'\", // String | Return issues ordered by `created_at` or `updated_at` fields.\n 'sort': \"'desc'\", // String | Return issues sorted in `asc` or `desc` order.\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3GroupsIdIssues(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function deletePaymentGroup() {\n Merchant.delete('payment_group', vm.delete_payment_group.id).then(function(response){\n vm.payment_groups.splice(delete_payment_group_index, 1);\n $(\"#delete-payment_group-modal\").modal('toggle');\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the function where all the data is accessed and put into arrays. Those arrays are also updated and removed as new data is received. New data is checked through the "listeningFirebaseRefs" array, as this is where database locations are stored and checked on regularly. | function databaseQuery() {
userInitial = firebase.database().ref("users/");
userInvites = firebase.database().ref("users/" + user.uid + "/invites");
var fetchData = function (postRef) {
postRef.on('child_added', function (data) {
onlineInt = 1;
var i = findUIDItemInArr(data.key, userArr);
if(userArr[i] != data.val() && i != -1){
checkGiftLists(data.val());
//console.log("Adding " + userArr[i].userName + " to most updated version: " + data.val().userName);
userArr[i] = data.val();
}
if(data.key == user.uid){
user = data.val();
console.log("User Updated: 1");
}
});
postRef.on('child_changed', function (data) {
var i = findUIDItemInArr(data.key, userArr);
if(userArr[i] != data.val() && i != -1){
checkGiftLists(data.val());
console.log("Updating " + userArr[i].userName + " to most updated version: " + data.val().userName);
userArr[i] = data.val();
}
if(data.key == user.uid){
user = data.val();
console.log("User Updated: 2");
}
});
postRef.on('child_removed', function (data) {
var i = findUIDItemInArr(data.key, userArr);
if(userArr[i] != data.val() && i != -1){
console.log("Removing " + userArr[i].userName + " / " + data.val().userName);
userArr.splice(i, 1);
}
});
};
var fetchInvites = function (postRef) {
postRef.on('child_added', function (data) {
inviteArr.push(data.val());
inviteNote.style.background = "#ff3923";
});
postRef.on('child_changed', function (data) {
console.log(inviteArr);
inviteArr[data.key] = data.val();
console.log(inviteArr);
});
postRef.on('child_removed', function (data) {
console.log(inviteArr);
inviteArr.splice(data.key, 1);
console.log(inviteArr);
if (inviteArr.length == 0) {
console.log("Invite List Removed");
inviteNote.style.background = "#008222";
}
});
};
fetchData(userInitial);
fetchInvites(userInvites);
listeningFirebaseRefs.push(userInitial);
listeningFirebaseRefs.push(userInvites);
} | [
"async function collectData(){\n let favs = [];\n\n await firebase.database().ref('recommenderData').child('favourite')\n .once('value', x => {\n x.forEach(data => {\n favs.push(data.val());\n checkSkill(data.val().preferenceType, data.val().favouritedAmount);\n })\n })\n}",
"function getWorldTemp(){\n var tempsDataRequest = firebase.database().ref(\"/Temps/\");\n tempsDataRequest.on(\"child_added\", function(data, prevChildkey)\n{\n let tempData = data.val();\n for (var i = 0; i < Object.keys(tempData).length; i++) {\n worldTemperatures.push(tempData.Temp);\n };\n loadGraph();\n});\n}",
"forEach(callback) {\n const mutations = this.val();\n return mutations.every(mutation => {\n const ref = mutation.target.reduce((ref, key) => ref.child(key), this.ref);\n const snap = new DataSnapshot(ref, mutation.val, false, mutation.prev);\n return callback(snap);\n });\n }",
"function watchGameList() {\n\n //watch game added, this happens also on initalization for each game in list\n gameList.on('child_added', function(dataSnapshot) {\n\n // console.log('new game added');\n\n var game = dataSnapshot.ref();\n game.child('name').on('value', function(dataSnapshot) {\n // console.log('user!!!!!!!');\n // console.log(dataSnapshot);\n })\n game.child('info/state').on('value', function(dataSnapshot) {\n\n //watch state switching to over or playing\n if(dataSnapshot.val() == 'over' || dataSnapshot.val() == 'playing') {\n game.child('info/state').off('value');\n handleGameListChange();\n }\n });\n\n handleGameListChange();\n });\n\n //watch game removed\n gameList.on('child_removed', handleGameListChange);\n\n }",
"function handleReadAllRelativesInfo() {\n\n // Payload base\n var localBasePayload = fbBasePayload;\n var senderID = getSenderID();\n return admin.database().ref('pazienti/' + senderID + '/parenti/').once('value').then((snapshot) => {\n\n let relatives = snapshot.val();\n console.log('snapshot.val() : ' + JSON.stringify(relatives));\n\n if(relatives !== null) {\n let i;\n let elements = [];\n\n for (i=0; i < relatives.length; i++) {\n let relName = snapshot.child(i.toString() + '/nome').val();\n let relAffinity = snapshot.child(i.toString() + '/parentela').val();\n let relAge = snapshot.child(i.toString() + '/eta').val();\n let relPhotoURL = snapshot.child(i.toString() + '/foto').val();\n let tempBirtdate = snapshot.child(i.toString() + '/dataNascita').val();\n let relBirthDate = getDate(tempBirtdate);\n\n console.log(\n 'relName: ' + relName + '\\n' +\n 'relAffinity: ' + relAffinity + '\\n' +\n 'relAge: ' + relAge + '\\n' +\n 'relPhotoURL: ' + relPhotoURL + '\\n' +\n 'relBirthDate: ' + relBirthDate + '\\n');\n\n let title = relName + ', ' + relAge + ' anni e ti è ' + relAffinity;\n let subtitle = 'E\\' nato il ' + relBirthDate;\n elements[i] = element(title, relPhotoURL, subtitle);\n\n localBasePayload.facebook.attachment.payload.elements[i] = elements[i];\n }\n //agent.add('Ecco a lei la sua terapia giornaliera:');\n agent.add(new Payload('FACEBOOK', localBasePayload, {rawPayload: true, sendAsMessage: true}));\n } else {\n let question = 'Non mi hai parlato dei tuoi parenti. Vuoi aggiungerli?';\n let suggestions = [\n \"Parenti\",\n 'Più tardi',\n \"No grazie\",\n \"Cancella\"\n ];\n setSuggestions(question, suggestions, senderID);\n }\n });\n }",
"viewFavourites() {\n const userId = this.state.UserId;\n const list = this.state.favourites;\n if (userId != []) {\n const dbref = firebase.database().ref('SavedNews');\n this.favourite = [];\n if (list == '') {\n dbref.child(userId).once('value', (snapshot) => {\n const favourites = snapshot.val();\n for (const prop in favourites) {\n this.favourite.push(favourites[prop]);\n }\n this.setState({\n favourites: this.favourite\n });\n });\n }\n }\n }",
"function transferCards(num) {\n console.log(\"New Transfer\");\n var ccardsDealt = new Array();\n var ccardsHeld = new Array();\n // Pull all values first from the 'held' ref and add to 'held' array\n communityCardRef.child('held').once('value', function (snapshot){\n snapshot.forEach(function (eachSnapshot){\n ccardsHeld.push(eachSnapshot.val());\n });\n // Then pull all values from the 'dealt' ref and add to 'dealt' array\n // There is probably a better way to do this but Firebase was making things screwy \n communityCardRef.child('dealt').once('value', function (snapshot){\n snapshot.forEach(function (eachSnapshot){\n ccardsDealt.push(eachSnapshot.val());\n });\n\n // removes the card from Firebase\n communityCardRef.child('held').child(num).remove();\n // removes the card from the Community Cards Array Held\n var card = ccardsHeld.shift();\n // adds card to the Community Cards Array dealt\n ccardsDealt.push(card);\n // adds the card to the player's hand\n communityCardRef.child('dealt').child(num).set({ rank: card['rank'], suit: card['suit'] });\n \n console.log(\"Done transferring: \");\n console.log(card);\n\n });\n });\n}",
"function fireQuestionary() {\n //Fills list if user has chosen level 1, level 2 or level 3.\n dbRefCourses.orderByKey().equalTo(value).on(\"child_added\", snap => {\n for(var key in snap.val().questions){\n if(levelid != \"random\") {\n dbRefPoints.child(value + \"/questions/\" + key).once('value', snap => {\n if (snap.hasChild(\"levelData\")) {\n if(snap.val().levelData.level == parseInt(levelid)) {\n list.push(key);\n }\n } else {\n if(parseInt(levelid) == 1) {\n list.push(key);\n }\n }\n });\n } else {\n //Own lists if user has chosen the knowledge based test\n dbRefPoints.child(value + \"/questions/\" + key).once('value', snap => {\n if (snap.hasChild(\"levelData\")) {\n if(snap.val().levelData.level == 1) {\n lvl1.push(key);\n } else if(snap.val().levelData.level == 2) {\n lvl2.push(key);\n } else if(snap.val().levelData.level == 3) {\n lvl3.push(key);\n }\n list.push(key);\n }\n else {\n lvl1.push(key);\n }\n });\n }\n }\n //Checks for various scenarios\n if(list.length > 10 || (lvl1.length + lvl2.length + lvl3.length) > 10) {\n total = 10;\n questions();\n } else if(list.length == 0 && lvl1.length == 0 && lvl2.length == 0 && lvl3.length == 0) {\n const h2 = document.createElement('h2');\n h2.innerText = \"There are no questions on this level yet\";\n h2.style.marginLeft = \"10%\";\n question.appendChild(h2);\n } else {\n total = list.length;\n questions();\n }\n });\n}",
"function getSankeyDataAndRender(){\n var phaseList = $firebaseArray(new Firebase(\"https://viridian-49902.firebaseio.com/phases/\"));\n\n phaseList.$loaded().then(function(list){\n $scope.phases = list;\n\n $scope.sankeyTime($scope.phases);\n });\n/*\n var phaseNames = ['ROOT', 'VEG', 'FLOWER', 'TAKEDOWN', 'PROCESSING'],\n nodes = [],\n phasesRef = new Firebase(\"https://viridian-49902.firebaseio.com/phases/\"),\n fbObj = $firebaseObject(phasesRef),\n returnedArr = [],\n deferred = $q.defer(),\n phasesSyncObject = $firebaseObject(phasesRef),\n i = 0,\n phasesLength = phaseNames.length;\n\n for (i = 0; i < phasesLength; i++){\n var valueRef = new Firebase(\"https://viridian-49902.firebaseio.com/phases/\" + phaseNames[i]),\n valueSyncObj = $firebaseObject(valueRef);\n\n valueSyncObj.$loaded().then(function(data){\n console.log(data.$id + ' has value at line 842 of ' + data.$value);\n returnedArr.push({\n 'phase': data.$id,\n 'value': data.$value\n });\n return returnedArr;\n }).then(function(sortedArray){\n console.log(sortedArray);\n });\n }\n\n\n // make a sync object and wait for it to be loaded, guaranteeing that the above operation has also concluded\n phasesSyncObject.$loaded().then(function(data){\n console.log(returnedArr);\n\n $scope.sankeyTime(returnedArr);\n\n });\n*/\n/*\n // get a snapshot of the data at this location\n phasesRef.on('value', function(snapshot){\n $scope.phases = snapshot.val();\n deferred.resolve(phases);\n return $scope.phases;\n });\n\n // make a sync object and wait for it to be loaded, guaranteeing that the above operation has also concluded\n phasesSyncObject.$loaded().then(function(data){\n console.log(data);\n\n $scope.sankeyTime(Object.keys(data));\n\n });\n*/\n }",
"getEmails(callback) {\n this.emailTracking\n .orderBy(\"created_at\")\n .onSnapshot(snapshot => {\n snapshot.docChanges().forEach(change => {\n if(change.type === \"added\") {\n // do stuff with all emails in the database (check for time, check for seats, etc)\n // console.log(\"going through emails\");\n callback(change.doc.data());\n }\n })\n })\n }",
"async function getAllSnaps(){\n \n //timetablesOut.forEach(rt=>{\n\n let {route,direction} = timetablesOut[9];\n\n timetablesOut[9].stops.forEach(async stop=>{\n\n let bestopid = stop.bestopid;\n\n //get snapshots from old db\n let theBusStop = await BusRoute.aggregate([\n {$match: {route:route,direction:direction}},\n {$unwind: '$stops'},\n {$match: {'stops.bestopid':bestopid}},\n {$replaceRoot: { newRoot: \"$stops\" }}\n ])\n\n //avoid errors there's no time for!\n if(theBusStop[0]){\n if(!theBusStop[0].snapshots.length){\n //console.log(\"empty\")\n return;\n }\n \n //here it will be the snapshots array from the old db route.stops[x].snapshots... need to go through each one and add the stopref.\n\n //the stopRef is the _id of the busstop (in the new db), get that first\n let stopRef = await newDBFile.getUnderscoreIdOfStop(route,direction,bestopid);\n\n //add the stop ref as a field in the snapshot\n let newSnapshots = theBusStop[0].snapshots;\n newSnapshots.map(async snap=>{\n snap.stopRef = stopRef;\n\n //save the snapshot\n let fingersCrossed = await newDBFile.saveNewSnap(snap);\n //console.log(fingersCrossed)\n })\n\n }else{\n console.log(route,direction,bestopid + ' no snaps ')\n }\n console.log(\"saving... \", route,direction,stop.name)\n })\n //})\n\n}",
"getMapData(mapID){\n\n\tthis.showMapUI(); \n this.setState({ loadedImage: [] })\n this.setState({ mapNameField: mapID });\n mapName = mapID + \"\";\n\t\n\t//Store data for each type in a single string to be parsed\n var markerDataString;\n var routeDataString;\n\n\tvar markerNameDataString;\n\tvar markerDescriptionDataString;\n\tvar markerNoteDataString;\n\tvar markerTagDataString;\n\n\tvar routeNameDataString;\n\tvar routeDistanceDataString;\n\tvar routeNoteDataString;\n\tvar routeTagDataString;\n\n var db = firebase.database();\n\tvar routeRef;\n\n\t//Use different (public) path for loading public maps\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/lines/');\n\t} else {\n\t\trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/lines/');\n\t}\n\n routeRef.orderByChild(\"markers\").on(\"child_added\", function (snapshot) {\n routeDataString+=snapshot.val(); \n });\n \n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/markers/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/markers/');\t\n\t}\n\n routeRef.orderByChild(\"markers\").on(\"child_added\", function (snapshot) {\n markerDataString+=snapshot.val(); \n });\n\n\t//Retrieve pin/route Names, Descriptions, and Notes\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/markerNameData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/markerNameData/');\t\n\t}\n\n routeRef.orderByChild(\"name\").on(\"child_added\", function (snapshot) {\n markerNameDataString+=snapshot.val()+(\"#\"); \n });\n\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/routeNameData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/routeNameData/');\t\n\t}\n\n routeRef.orderByChild(\"name\").on(\"child_added\", function (snapshot) {\n routeNameDataString+=snapshot.val()+(\"#\"); \n });\n\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/markerDescriptionData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/markerDescriptionData/');\t\n\t}\n\n routeRef.orderByChild(\"desc\").on(\"child_added\", function (snapshot) {\n markerDescriptionDataString+=snapshot.val()+(\"#\"); \n });\n\t\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/routeDistanceData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/routeDistanceData/');\t\n\t}\n\n routeRef.orderByChild(\"desc\").on(\"child_added\", function (snapshot) {\n routeDistanceDataString+=snapshot.val()+(\"#\"); \n });\n\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/markerNotesData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/markerNotesData/');\t\n\t}\n\n routeRef.orderByChild(\"notes\").on(\"child_added\", function (snapshot) {\n markerNoteDataString+=snapshot.val()+(\"#\"); \n });\n\n\tif (publicMap) {\n \trouteRef = db.ref(mapID + '/routeNotesData/');\n\t} else {\n \trouteRef = db.ref('airports/' + airport + '/maps/' + mapID + '/routeNotesData/');\t\n\t}\n\n routeRef.orderByChild(\"notes\").on(\"child_added\", function (snapshot) {\n routeNoteDataString+=snapshot.val()+(\"#\"); \n });\n \n\t//If firebase data exists for a given attribute, set global references to it and update the form with the first pin's info\n\tif(markerNameDataString){\n \tmarkerNameDataString = markerNameDataString.substr(9);\n \tmarkerNameData = markerNameDataString.split(\"#\"); \n\t\tmarkerNameData.pop();\n\n\t\t//By defalut, start by showing pin info for the first pin added to the loaded map\n\t\tvar createPinPanel = document.getElementById('popup-create-pin-panel');\n createPinPanel.hidden = false;\n\t\tthis.setPinFormData(0);\n }\n\n\tif(markerDescriptionDataString){\n \tmarkerDescriptionDataString = markerDescriptionDataString.substr(9);\n \tmarkerDescriptionData = markerDescriptionDataString.split(\"#\"); //Show pin info for the first pin\n\t\tvar createPinPanel = document.getElementById('popup-create-pin-panel');\n createPinPanel.hidden = false;\n\t\tthis.setPinFormData(0);\n }\n\n\t//First 9 characters are always 'undefined' so remove them, as well as whitespace and seperators\n\tif(markerNoteDataString){\n \tmarkerNoteDataString = markerNoteDataString.substr(9);\n \tmarkerNoteData = markerNoteDataString.split(\"#\"); //Show pin info for the first pin\n\t\tvar createPinPanel = document.getElementById('popup-create-pin-panel');\n createPinPanel.hidden = false;\n\t\tthis.setPinFormData(0);\n }\n\n\t//First 18 characters are always 'undefined' so remove them, as well as whitespace and seperators\n if(markerDataString){\n \tmarkerDataString = markerDataString.substr(18);\n\t\tmarkerDataString = markerDataString.replace(\" \", \"\");\n \tvar markerData = markerDataString;\n \tmarkerData = markerDataString.split(\"#\"); \n \tfor (var i=0;i<markerData.length;i++){\n \tmarkerData[i] = markerData[i].replace(\"(\", \"\");\n \tmarkerData[i] = markerData[i].replace(\")\", \"\");\n \tmarkerData[i] = markerData[i].replace(\" \", \"\");\n \tvar markerDataCoordinate = markerData[i].split(\",\");\n \tvar point = {lat:Number(markerDataCoordinate[0]), lng:Number(markerDataCoordinate[1])};\n \t\twindow.currentMarkerObj.push(point);\n \t}\n }\n\n\tif(routeDataString){\n\t\trouteDataString = routeDataString.substr(18);\n\t\trouteDataString = routeDataString.replace(\"(\", \"\");\n \trouteDataString = routeDataString.replace(\" \", \"\");\n \tvar routeData = routeDataString;\n \trouteData = routeDataString.split(\"#\"); \n\n\t\t//Route data is parsed according to + signs to seperate routes. 2D arrays and loops are needed since each route is a list of markers, and the route data is a list of routes\n \t\tvar routeDataCoordinates1 = [];\n \t\tvar routeDataCoordinates2 = [[],[],[],[],[],[],[],[],[],[],[]];\n\n\t\tvar cntr1 = 0;\n\t\tvar cntr2 = 0;\n\n\t\t//First parse the list of routes\n \t\tfor (var cntr1 = 0; cntr1 < routeData.length; cntr1++){\n \t\trouteDataCoordinates1[cntr1] = routeData[cntr1].split(\")\"); \n\t\t\tfor (var cntr2 = 0; cntr2 < routeDataCoordinates1[cntr1].length; cntr2++){\n \t\trouteDataCoordinates2[cntr1][cntr2] = routeDataCoordinates1[cntr1][cntr2].split(\",\");\n \t\t}\n \t\t}\n\n\t\t//Next parse the list of markers in each route\n \t\tfor (var i = 0; i < routeDataCoordinates2.length-1; ++i){ \n \t\tfor (var j = 0; j<routeDataCoordinates2[i].length-1; ++j){\n \t\t\tif (j!=0){\n \t\t\trouteDataCoordinates2[i][j][0] = routeDataCoordinates2[i][j][1];\n \t\t\trouteDataCoordinates2[i][j][1] = routeDataCoordinates2[i][j][2];\n \t\t\t}\n\n \t\t\tvar point = {lat:routeDataCoordinates2[i][j][0].replace(\"(\", \"\"), lng:routeDataCoordinates2[i][j][1].replace(\"(\", \"\")};\n \t\t\twindow.currentRouteObj.push(point);\n \t\t}\n\n \twindow.currentRouteObj.push(\"new\");\n \t\t}\n\t}\n\n\t//Set global cam variables before loading the map.\n\tvar db = firebase.database();\n\tvar camRef;\n\tif (publicMap){\n \tcamRef = db.ref(mapID + '/camZoom/');\n\t} else {\n\t\tcamRef = db.ref('airports/' + airport+ '/maps/' + mapID + '/camZoom/');\n\t}\n\t\n routeRef.orderByChild(\"camZoom\").on(\"child_added\", function (snapshot) {\n camZoom=snapshot.val(); \n });\n\n\tif (publicMap){\n \tcamRef = db.ref(mapID + '/camTarget/');\n\t} else {\n\t\tcamRef = db.ref('airports/' + airport + '/maps/' + mapID + '/camTarget/');\n\t}\n\n\t//Draw the map\n\tthis.initMap();\n\n\t//Load the pictures of the map\n\tthis.load();\n }",
"function populateMapFromFirebase(){\n usersRef.get().then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n const user = new User();\n // updateUser(user,doc.id, doc.data(\"name\"), doc.data(\"CoX\"), doc.data(\"CoY\"), doc.data(\"blockColour\"), doc.data(\"bot\"), doc.data(\"mining\"));\n updateUser(user);\n Node(user);\n // doc.data() is never undefined for query doc snapshots\n console.log(\"Retrieved User: \"+doc.id+\" -> \"+doc.data(\"name\"));\n });\n });\n}",
"function listeners_(){this.listeners$bq6g=( {});}",
"_fetchSeasons() {\n this.refList.seasons.on(\"child_added\", snap => {\n this._state.seasons[snap.key] = snap.val();\n });\n this.refList.seasons.on(\"child_changed\", snap => {\n this._state.seasons[snap.key] = snap.val();\n });\n this.refList.seasons.on(\"child_removed\", snap => {\n delete this._state.seasons[snap.key];\n });\n }",
"pushRefreshedDatas() {\n var tt = this;\n MongoClient.connect(this.uri, function(err, db) {\n if (err) throw err;\n //Looking for a db called test\n var dbo = db.db(\"test\");\n for (var i = 0; i < tt.collections.length; ++i) {\n dbo.collection(\"rss\").insertOne(tt.collections[i],function(err, result) {\n if (err) throw err;\n });\n }\n db.close();\n });\n }",
"function loadChannels()\n{\n\t// Reset the arrays\n\tgChannels = [];\n\n\t// Load the XML\n\tfirebase.database().ref('/channels').once('value').then( function( snapshot ) {\n\n\t\tvar channels = snapshot.val();\n\t\tvar iChannels = channels.length;\n\n\t\t// Fill out the local copy of our data\n\t\tfor( var i=0; i<iChannels; i++ )\n\t\t{\n\t\t\tgChannels[i] = new Channel( channels[i] );\n\n\t\t\t// If this is a stream, parse the list\n\t\t\tif( gChannels[i].type == 'playlist' ) {\n\t\t\t\tgetStreamList( gChannels[i] );\n\t\t\t}\n\t\t\telse if( gChannels[i].type == 'stream' ) {\n\t\t\t\tgChannels[i].aURLs[0] = new Stream();\n\t\t\t\tgChannels[i].aURLs[0].url = gChannels[i].stream;\n\t\t\t\tgChannels[i].aURLs[0].title = gChannels[i].name;\n\t\t\t\tgChannels[i].valid = true;\n\t\t\t}\n\t\t}\n\t});\n}",
"function initialize() {\n trains = [];\n var query = firebase.database().ref().orderByKey();\n query.once(\"value\")\n .then(function(snapshot) {\n snapshot.forEach(function(childSnapshot) {\n // childData will be the actual contents of the child\n var childData = childSnapshot.val();\n\n // Store train name of current child and remove all spaces\n var childName = childData.name.replace(/\\s+/g, '');\n\n // Store this simplified name into the names array\n trains.push(childName);\n\n var childFirst = childData.firstTime;\n var childFreq = childData.frequency;\n var childMins = calcMins(childFirst, childFreq);\n var childNext = moment(moment().add(childMins, \"minutes\")).format(\"hh:mm A\");\n\n var nextID = \"#next\" + childName;\n var minsID = \"#mins\" + childName;\n\n // Update the current display to show next arrival time and minutes remaining for current train\n $(nextID).text(childNext);\n $(minsID).text(childMins);\n });\n });\n}",
"listenRaces() {\n if (this._listeningForRaces) {\n return;\n }\n this._listeningForRaces = true;\n\n console.log(`Listening races for ${this.key}`);\n\n const ref = Fb.races.child(this.key);\n ref.on(\"child_added\", snap => this.addRace(snap.key, snap.val()));\n ref.on(\"child_changed\", snap => this.updateRace(snap.key, snap.val()));\n ref.on(\"child_removed\", snap => this.removeRace(snap.key));\n ref.orderByChild(\"timestamp\").limitToLast(10).on(\"value\", snap => this.setLatestRaces(snap));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called by IDE when a new behavior type is to be created | function CreateIDEBehaviorType()
{
return new IDEBehaviorType();
} | [
"addNewClassInModel() {\n let model = this.get('selectedValue');\n let modelHash = this.getModelArrayByStereotype(model.data);\n\n if (model.data.get('stereotype') === '«implementation»') {\n modelHash.pushObject({ settings: model, editForms: A(), listForms: A(), parents: A(), bs: null });\n } else {\n modelHash.pushObject(model);\n }\n\n this.get('updateModel')();\n }",
"function createNew(){\n if(gtag) gtag('event', 'new_combat');\n loadCombat(\"\", mode.edit)\n}",
"function ManageObjectTypes() {\n\t}",
"function Window_ModTypeCommand() {\r\n this.initialize.apply(this, arguments);\r\n}",
"initTypeIt() {\n new typeit__WEBPACK_IMPORTED_MODULE_0__[\"default\"](`#${this.typeItContainer.id}`, {\n strings: this.typeItStringArray,\n lifeLike: true,\n loop: true,\n waitUntilVisible: true,\n breakLines: false,\n }).go();\n }",
"addInteraction(config) {\n index = getValue('cmi.interactions._count');\n let newInteraction = new Interaction(index, config);\n this.interactions.push(newInteraction);\n }",
"function newAnnotation(type) {\n \n updateAutori();\n //ricavo il testo selezionato\n selezione = selection();\n \n //differenza tra selezione e fragmentselection: per operare sui nodi serve il primo, poichè è sostanzialmente\n //un riferimento all'interno del documento; il secondo invece estrapola dallo stesso il contenuto selezionato ogni\n //volta che viene rilasciato il tasto sinistro del mouse. dal secondo non si può risalire ai nodi, o almeno non si\n //può con il metodo utilizzato sotto. tuttavia, usando selezione è impossibile detectare se \"esiste\" la selezione\n //stessa o se è vuota, poichè jQuery per qualche motivo non riesce a confrontare l'oggetto con \"\", '', null o \n //undefined; allo stesso tempo, è molto più difficile visualizzare selezione nel modale di inserimento annotazioni.\n //per questo motivo, viene più comodo e semplice usare due variabili separate che prelevano la stessa cosa e che \n //la gestiscono in modo diverso e in momenti diversi.\n if (fragmentselection === '') {\n avviso(\"Attenzione! Nessun frammento selezionato.\");\n } \n else {\n registerAnnotation(type);\n }\n}",
"_createType (name) {\n\n\t\tif ( name !== undefined) AssertUtils.isString(name);\n\n\t\tconst getNoPgTypeResult = NoPgUtils.get_result(NoPg.Type);\n\n\t\treturn async data => {\n\n\t\t\tdata = data || {};\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tdata.$name = '' + name;\n\t\t\t}\n\n\t\t\tconst rows = await this._doInsert(NoPg.Type, data);\n\n\t\t\tconst result = getNoPgTypeResult(rows);\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tawait this.setupTriggersForType(name);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t};\n\n\t}",
"updateTypes() {\n let rawTypesByCategory = this.codenvyAPI.getProjectType().getTypesByCategory();\n this.typesByCategory = [];\n for (let categoryName in rawTypesByCategory) {\n this.typesByCategory.push({ category: categoryName, types: rawTypesByCategory[categoryName] });\n }\n // broadcast event\n this.$rootScope.$broadcast('create-project-blank:initialized');\n\n }",
"_initFormBehaviorManager() {\n FormBehaviorManager.add(MediaChoice);\n }",
"function Window_ModPatchCreate() {\r\n this.initialize.apply(this, arguments);\r\n}",
"addInteraction(interaction) {\n // Maybe have a list of interactions that are all handled??\n this.interactions[interaction.type] = interaction;\n return this;\n }",
"function setActiveWidget(type) {\n switch (type) {\n // if measure distance is clicked\n case \"distance\":\n activeWidget = new DistanceMeasurement2D({\n viewModel: {\n view: view,\n mode: \"geodesic\",\n unit: \"feet\"\n }\n });\n\n // skip the initial 'new measurement' button\n activeWidget.viewModel.newMeasurement();\n \n // add the widget window to the view on the bottom right\n view.ui.add(activeWidget, \"bottom-right\");\n \n setActiveButton(document.getElementById(\"distanceButton\"));\n break;\n \n // if measure area button is clicked \n case \"area\":\n activeWidget = new AreaMeasurement2D({\n viewModel: {\n view: view,\n mode: \"planar\",\n unit: \"square-feet\"\n }\n });\n\n // skip the initial 'new measurement' button\n activeWidget.viewModel.newMeasurement();\n\n view.ui.add(activeWidget, \"bottom-right\");\n setActiveButton(document.getElementById(\"areaButton\"));\n break;\n \n case null:\n if (activeWidget) {\n view.ui.remove(activeWidget);\n activeWidget.destroy();\n activeWidget = null;\n }\n break;\n }\n }",
"function addGraphType(graphType, title, toolbar) {\n let dropdown = document.getElementById('graphdropdown')\n let a = document.createElement('a')\n a.setAttribute('href', '#')\n let t = document.createTextNode(title)\n dropdown.appendChild(a)\n a.appendChild(t)\n a.addEventListener('mousedown', event => {\n graph = graphType\n repaint()\n toolBar = toolbar\n toolBar.add()\n })\n }",
"function editorNewMission() {\n editorDirty = true;\n let mission = {\n name: \"Nuova missione\",\n color: \"#EEEEEE\"\n };\n loadedStory.missions.push(mission);\n addMissionElement(mission);\n}",
"insertNewSynonym() {\n this.data.synonyms.push(new RelationTypeSynonym());\n }",
"_addTypings() {\n\n // reading JSON\n let tsconfig = this.fs.readJSON(\n this.destinationPath('tsconfig.json')\n );\n\n // Add Handlebars entry\n tsconfig.compilerOptions.types.push('handlebars');\n\n // writing json\n fs.writeFileSync(\n this.destinationPath('tsconfig.json'),\n JSON.stringify(tsconfig, null, 2));\n\n\n }",
"function addType(newType, configFunction) {\n OPTION_CONFIGURERS[newType] = configFunction;\n }",
"function onSelectFieldType( type ) {\n\n\n \n /** \n\n switch( type ) {\n\n case 'new':\n\n apiFetch( { path: '/dev/wp-json/wp/v2/posts' } ).then( posts => {\n console.log( 'new', posts );\n } );\n\n break;\n\n case 'existing':\n\n apiFetch( { path: '/dev/wp-json/wp/v2/posts' } ).then( posts => {\n console.log( 'existing', posts );\n } );\n\n \n break;\n }\n\n */\n\n\n setAttributes( { fieldType: type } )\n\n\n }",
"addNodeInDefinition() {\n let node = this.get('selectedNode');\n\n if (isNone(node)) {\n return;\n }\n\n let view = this.get('view.definitionArray');\n\n // Create propertyName\n let propertyName = this.createPropertyName(node, this.get('treeObject').jstree(true));\n \n if (view.findBy('name', propertyName)) {\n return;\n }\n\n let newDefinition;\n switch (get(node, 'type')) {\n case 'property':\n newDefinition = FdViewAttributesProperty.create({\n name: propertyName\n });\n break;\n case 'master':\n newDefinition = FdViewAttributesMaster.create({\n name: propertyName\n });\n break;\n case 'detail':\n newDefinition = FdViewAttributesDetail.create({\n name: propertyName\n });\n break;\n }\n\n let indexOfSelectedProperty = this.getIndexOfSelectedProperty();\n\n if (indexOfSelectedProperty >= 0) {\n view.insertAt(indexOfSelectedProperty + 1, newDefinition);\n } else {\n view.pushObject(newDefinition);\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that checks wether the scroll button has to be displayed | checkScrollButton() {
this.scrollTopButton.current.classList.toggle('hidden', window.scrollY < 300);
} | [
"isVisible() {\n return this.toolbar.is(\":visible\");\n }",
"function scrollCheck() {\n if ($(\"header\").is(\":visible\")) {\n closeMenu();\n }\n}",
"isInViewport() {\n const vm = this;\n\n if(vm.firstTime) {\n // first time set postion of element outside monitor\n vm.firstTime = false\n return true\n } else {\n return vm.offset + vm.height > vm.scroll &&\n vm.offset < vm.scroll + vm.wheight\n }\n\n }",
"function scrollFunction ()\n {\n if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20)\n {\n document.getElementById(\"btn-resume\").style.display = \"block\"\n } else\n {\n document.getElementById(\"btn-resume\").style.display = \"none\"\n }\n }",
"toggleAutoScroll() {\n const ariaPressed = this.ariaPressed;\n\n if (ariaPressed === FALSE_STRING) {\n this.autoScrollOff();\n } else {\n this.autoScrollOn();\n }\n }",
"_hasScrolledAncestor(el, deltaX, deltaY) {\n if (el === this.scrollTarget || el === this.scrollTarget.getRootNode().host) {\n return false;\n } else if (\n this._canScroll(el, deltaX, deltaY) &&\n ['auto', 'scroll'].indexOf(getComputedStyle(el).overflow) !== -1\n ) {\n return true;\n } else if (el !== this && el.parentElement) {\n return this._hasScrolledAncestor(el.parentElement, deltaX, deltaY);\n }\n }",
"checkVisibility () {\n const vTop = window.pageYOffset\n const vHeight = window.innerHeight\n if (vTop + vHeight < this.box.top ||\n this.box.top + this.canvasHeight < vTop) {\n // viewport doesn't include canvas\n this.visible = false\n } else {\n // viewport includes canvas\n this.visible = true\n }\n }",
"function scrollCheck() {\n if (document.body.scrollTop > height) {\n animateHeader = false;\n } else {\n animateHeader = true;\n }\n}",
"onScroll_() {\n if (!this.isActive_()) {\n return;\n }\n this.vsync_.run(\n {\n measure: state => {\n state.shouldBeFullBleed =\n this.getOverflowContainer_()./*OK*/ scrollTop >=\n FULLBLEED_THRESHOLD;\n },\n mutate: state => {\n this.getShadowRoot().classList.toggle(\n FULLBLEED_CLASSNAME,\n state.shouldBeFullBleed\n );\n },\n },\n {}\n );\n }",
"function onScroll() {\n if (scrollContainer.current.scrollTop < 5) {\n setShowTopIndicator(false)\n }\n else {\n setShowTopIndicator(true)\n }\n if (scrollContainer.current.scrollHeight - scrollContainer.current.scrollTop > scrollContainer.current.clientHeight + 5) {\n setShowBottomIndicator(true)\n }\n else {\n setShowBottomIndicator(false)\n }\n }",
"function detectScroll(){\n\tvar percent = _scrollTop() / ( _scrollHeight() - _innerHeight() );\n\tif(oldPercent != percent)\n\t{\n\t\tif(percent >= 0){\n\t\t\toldPercent = percent;\n\t\t\tgetFlash().scrollFlash( percent, 0 );\n\t\t} \n\t}\n}",
"buttonCheck(){\n this.visibility(document.getElementById(\"add-list-button\"), this.currentList == null);\n this.visibility(document.getElementById(\"undo-button\"), this.tps.hasTransactionToUndo());\n this.visibility(document.getElementById(\"redo-button\"), this.tps.hasTransactionToRedo());\n this.visibility(document.getElementById(\"delete-list-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"add-item-button\"), !(this.currentList == null));\n this.visibility(document.getElementById(\"close-list-button\"), !(this.currentList == null));\n }",
"function scrolledUpEnough( firstItem, lastItem ) {\n\t\treturn ( firstItem - lastItem ) > 160;\n\t}",
"function hasScrolled() {\n\tvar scroll = topOfPage();\n\tif (scroll > 1) {\n\t\tdocument.getElementById(\"header\").style.padding = \"0 30px\"; // This style option will shrink the header\n\t\tdocument.getElementById(\"header\").style.boxShadow = \"0 0 5px 0 #ccc\"; // THis style option will create a shadow at the bottom of the header to give a sense of a layered website\n\t\tdocument.getElementById(\"header\").style.background = \"rgba(255,255,255,.98)\"; // This style option will make the header transparent just enough to see a little through it\n\t\t\n\t}\n\telse if (scroll < 1) {\n\t\tdocument.getElementById(\"header\").style.padding = \"15px 30px\"; // this style option is here if the page hasent been scrolled yet, or if you go back to the top of the page.\n document.getElementById(\"header\").style.boxShadow = \"0 0 0 0 #ccc\"; // This is to reset the box shadow style on the header\n \n\t}\n}",
"inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}",
"function inView2() {\n // get window height\n var windowHeight = window.innerHeight;\n // get number of pixels that the document is scrolled\n var scrollY = window.scrollY || window.pageYOffset;\n \n // get current scroll position (distance from the top of the page to the bottom of the current viewport)\n var scrollPosition = scrollY + windowHeight;\n // get section5 position (distance from the top of the page to the bottom of the section5)\n var section5Position = section5.getBoundingClientRect().top + scrollY + (section5Height-100);\n \n // is scroll position greater than section5 position? (is section5 in view?)\n if (scrollPosition > section5Position) {\n return true;\n }\n \n return false;\n }",
"ensureButtonsShown() {\n // TODO(fanlan1210)\n }",
"function checkStickyPosition ()\n\t{\n\t\tvar document_scroll_top = jQuery(document).scrollTop()\n\t\t,\tis_sticked = sticky_button.hasClass('sticked')\n\t\t,\tcurrent_offset = sticky_button.offset().top - padding_offset;\n\n\t\tif (!is_sticked && document_scroll_top >= current_offset)\n\t\t{\n\t\t\tstickIt();\n\t\t}\n\t\telse if(is_sticked && document_scroll_top <= current_offset)\n\t\t{\n\t\t\tunStickIt();\n\t\t}\n\t}",
"isVisible (template) {\n if (template) {\n return QuickPopoverController.popover && QuickPopoverController.contentTemplate === template\n } else {\n return QuickPopoverController.popover !== undefined\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
issueMutation performs two important actions: it optimistically applies a Mutation to the current local state (if this option is not turned off), and issues the Mutation to the server. If the server request is successful, the changes are committed to the local state; if not, the optimistic changes are rolled back. | function issueMutation(mutation, options) {
var executionId;
var target = mutation.target instanceof Id ? mutation.target : new Id(mutation.target, 'local-' + localCount++);
if (!options.waitForServer) {
return performOptimisticMutation(target, mutation, options.batch);
}
return MutationExecutor.execute(mutation, options.batch).then(function (result) {
var subscribers = ObjectStore.fetchSubscribers(target);
var delta = mutation.generateDelta(result);
// Apply it to the data store
var changes = ObjectStore.commitDelta(delta);
return pushUpdates(subscribers, changes);
});
} | [
"async postIssue() {\n if (!this.API || !this.options || this.issue || this.issueId)\n return;\n // login to create issue\n if (!this.isLogined) {\n this.login();\n }\n // only owner/admins can create issue\n // if (!this.isAdmin) return\n try {\n this.isCreatingIssue = true;\n const issue = await this.API.postIssue({\n title: this.issueTitle,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n const issueR = await this.API.postIssue({\n title: this.issueTitleR,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n this.issue = issue;\n this.issueR = issueR;\n this.isIssueNotCreated = false;\n await this.getComments();\n await this.getRatings();\n await this.getTotalRating();\n await this.getUserRating();\n }\n catch (e) {\n this.isFailed = true;\n }\n finally {\n this.isCreatingIssue = false;\n }\n }",
"spawnSimpleMutationSubtask({ namespace, id }, mutateFunc ) {\n return this.spawnSubtask(\n this._simpleMutationSubtask, { mutateFunc, namespace, id });\n }",
"async function commitlint(context) {\n\t// 1. Extract necessary info\n\tconst pull = context.issue();\n\tconst { sha } = context.payload.pull_request.head;\n\tconst repo = context.repo();\n\n\t// GH API\n\tconst { paginate, issues, repos, pullRequests } = context.github;\n\n\t// Hold this PR info\n\tconst statusInfo = { ...repo, sha, context: 'commitlint' };\n\n\t// Pending\n\tawait repos.createStatus({\n\t\t...statusInfo,\n\t\tstate: 'pending',\n\t\tdescription: 'Waiting for the status to be reported'\n\t});\n\n\t// Paginate all PR commits\n\treturn paginate(pullRequests.getCommits(pull), async ({ data }) => {\n\t\t// empty summary\n\t\tconst report = { valid: true, commits: [] };\n\t\tconst { rules } = await load(config);\n\n\t\t// Keep counters\n\t\tlet errorsCount = 0;\n\t\tlet warnsCount = 0;\n\n\t\t// Iterates over all commits\n\t\tfor (const d of data) {\n\t\t\tconst { valid, errors, warnings } = await lint(\n\t\t\t\td.commit.message,\n\t\t\t\trules\n\t\t\t);\n\t\t\tif (!valid) {\n\t\t\t\treport.valid = false;\n\t\t\t}\n\n\t\t\tif (errors.length > 0 || warnings.length > 0) {\n\t\t\t\t// Update counts\n\t\t\t\terrorsCount += errors.length;\n\t\t\t\twarnsCount += warnings.length;\n\n\t\t\t\treport.commits.push({ sha: d.sha, errors, warnings });\n\t\t\t}\n\t\t}\n\n\t\t// Final status\n\t\tawait repos.createStatus({\n\t\t\t...statusInfo,\n\t\t\tstate: report.valid ? 'success' : 'failure',\n\t\t\tdescription: `found ${errorsCount} problems, ${warnsCount} warnings`\n\t\t});\n\n\t\t// Get commit\n\t\tconst comment = await checkComments(issues, pull);\n\n\t\t// Write a comment with the details (if any)\n\t\tif (errorsCount > 0 || warnsCount > 0) {\n\t\t\tconst message = format(report.commits);\n\t\t\tif (comment) {\n\t\t\t\t// edits previous bot comment if found\n\t\t\t\tawait issues.editComment({\n\t\t\t\t\t...pull,\n\t\t\t\t\tid: comment.id,\n\t\t\t\t\tbody: message\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// if no previous comment create a new one\n\t\t\t\tawait issues.createComment({ ...pull, body: message });\n\t\t\t}\n\t\t} else {\n\t\t\tif (comment) {\n\t\t\t\t// edits previous bot comment if found\n\t\t\t\tawait issues.deleteComment({ ...pull, comment_id: comment.id });\n\t\t\t}\n\t\t}\n\t});\n}",
"function modifyQueries(exploreId, modification, index, modifier) {\n return function (dispatch) {\n dispatch(Object(_actionTypes__WEBPACK_IMPORTED_MODULE_6__[\"modifyQueriesAction\"])({ exploreId: exploreId, modification: modification, index: index, modifier: modifier }));\n if (!modification.preventSubmit) {\n dispatch(runQueries(exploreId));\n }\n };\n}",
"handleMutations() {\n // Copy and clear parkedNodes.\n let _parkedNodes = this.parkedNodes.slice()\n this.parkedNodes = []\n // Handle mutations if it probably isn't too much to handle\n // (current limit is totally random).\n if (_parkedNodes.length < 151) {\n this.logger.debug(`${this}processing ${_parkedNodes.length} parked nodes.`)\n let batchSize = 40 // random size\n for (let i = 0; i < Math.ceil(_parkedNodes.length / batchSize); i++) {\n ((index) => {\n setTimeout(() => {\n for (let j = index * batchSize; j < (index + 1) * batchSize; j++) {\n let node = _parkedNodes[j]\n let stillInDocument = document.contains(node) // no lookup costs\n if (stillInDocument) {\n this.insertIconInDom(node)\n }\n }\n }, 0) // Push back execution to the end on the current event stack.\n })(i)\n }\n }\n }",
"async function executeAction(req, res) {\n const { userId } = req.session;\n const { inputFields } = req.body.payload;\n\n try {\n // Retrieve the relevant user's OAuth token from the DB\n const { token } = await connectionModelService.getConnectionByUserId(userId);\n\n // Gets the blocks' required data from the input fields object.\n // You can define the input fields for your block by opening your integration feature and selecting Feature Details > Workflow Blocks\n // Input fields docs: https://developer.monday.com/apps/docs/custom-actions#configure-action-input-fields\n const { repository, issue } = inputFields;\n const owner = repository.value.owner;\n const repo = repository.value.name;\n\n // Call the Github API to create an issue.\n await githubService.createIssue(token, owner, repo, issue);\n\n return res.status(200).send();\n } catch (err) {\n console.error(err);\n return res.status(500).send({ message: 'internal server error' });\n }\n}",
"async function transferIssues() {\n inform('Transferring Issues');\n\n // Because each\n let milestoneData = await githubHelper.getAllGithubMilestones();\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlabApi.Issues.all({\n projectId: settings.gitlab.projectId,\n });\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let githubIssues = await githubHelper.getAllGithubIssues();\n\n console.log(`Transferring ${issues.length} issues.`);\n\n if (settings.usePlaceholderIssuesForMissingIssues) {\n for (let i = 0; i < issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i + 1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid !== expectedIdx) {\n issues.splice(i, 0, createPlaceholderIssue(expectedIdx));\n issueCounters.nrOfPlaceholderIssues++;\n console.log(\n `Added placeholder issue for GitLab issue #${expectedIdx}.`\n );\n }\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // try to find a GitHub issue that already exists for this GitLab issue\n let githubIssue = githubIssues.find(\n i => i.title.trim() === issue.title.trim()\n );\n if (!githubIssue) {\n console.log(`\\nMigrating issue #${issue.iid} ('${issue.title}')...`);\n try {\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await githubHelper.createIssueAndComments(milestoneData, issue);\n console.log(`\\t...DONE migrating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`\\t...ERROR while migrating issue #${issue.iid}.`);\n\n console.error('DEBUG:\\n', err); // TODO delete this after issue-migration-fails have been fixed\n\n if (settings.useReplacementIssuesForCreationFails) {\n console.log('\\t-> creating a replacement issue...');\n const replacementIssue = createReplacementIssue(\n issue.iid,\n issue.title,\n issue.state\n );\n\n try {\n await githubHelper.createIssueAndComments(\n milestoneData,\n replacementIssue\n );\n\n issueCounters.nrOfReplacementIssues++;\n console.error('\\t...DONE.');\n } catch (err) {\n issueCounters.nrOfFailedIssues++;\n console.error(\n '\\t...ERROR: Could not create replacement issue either!'\n );\n }\n }\n }\n } else {\n console.log(`Updating issue #${issue.iid} - ${issue.title}...`);\n try {\n await githubHelper.updateIssueState(githubIssue, issue);\n console.log(`...Done updating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`...ERROR while updating issue #${issue.iid}.`);\n }\n }\n }\n\n // print statistics about issue migration:\n console.log(`DONE creating issues.`);\n console.log(`\\n\\tStatistics:`);\n console.log(`\\tTotal nr. of issues: ${issues.length}`);\n console.log(\n `\\tNr. of used placeholder issues: ${issueCounters.nrOfPlaceholderIssues}`\n );\n console.log(\n `\\tNr. of used replacement issues: ${issueCounters.nrOfReplacementIssues}`\n );\n console.log(\n `\\tNr. of issue migration fails: ${issueCounters.nrOfFailedIssues}`\n );\n}",
"function commit() {\n\tconsole.log(\"COMMIT!\");\n\t$.ajax({\n\t\t\turl: \"nodecron\",\n\t\t\tdata: {action: \"commit\"},\n\t\t\ttype: \"get\",\n\t\t\tsuccess: function(data, status, jqXHR){\n\t\t\t\tif (jqXHR[\"status\"] != \"200\") {\n\t\t\t\t\twindow.alert(\"Something bad happened in 'commit'!\");\n\t\t\t\t\t}\n\t\t\t\tlocation.reload(true);\t// needed, to refresh the page\n\t\t\t\t}\n\t\t\t}\n\t\t\t);\n\t\t}",
"async function submitQuery() {\n\n var credentials = await Auth.currentCredentials();\n\n const redshiftDataClient = new RedshiftData({\n region: state.clusterRegion,\n credentials: Auth.essentialCredentials(credentials)\n });\n\n var params = {\n ClusterIdentifier: state.clusterIdentifier,\n Sql: state.sql,\n Database: state.database,\n //DbUser: state.dbUser,\n SecretArn: state.secretArn,\n StatementName: state.statementName,\n WithEvent: state.withEvent,\n };\n\n console.log('Submitting query to Redshift...');\n var response = await redshiftDataClient.executeStatement(params).promise();\n console.log(`Submission accepted. Statement ID:`, response);\n setTimeout(updateStatementHistory, 2000); // Seems we need to wait a second or two before calling the ListStatements() API, otherwise results don't show latest query:\n}",
"setIssue(issue) {\n this.issue = issue;\n }",
"approve () {\n this.resolve(true);\n let project = store.getters.project(this.project_id);\n new MocaMutationSet(\n 'update', 'project',\n project.id, {\n max: this.content.hours ? project.max + this.content.hours : project.max,\n due: this.content.due ? this.content.due : project.due\n }\n ).commit();\n }",
"function QuestionForm() {\n let perguntaInput, altAInput, altBInput, altCInput,altDInput;\n //hook de mutation\n const [createQuestao, { data }] = useMutation(ADD_QUESTAO);\n\n \n\treturn (\n <div>\n \t\t<form \n onSubmit={e => {\n e.preventDefault();\n //envio da mutation\n createQuestao({ variables: { pergunta: perguntaInput.value,\n alternativaa: altAInput.value,\n alternativab: altBInput.value, \n alternativac: altCInput.value,\n alternativad: altDInput.value} });\n perguntaInput.value = '';\n altAInput.value = '';\n altBInput.value = '';\n altCInput.value = '';\n altDInput.value = '';\n\n alert(\"pergunta enviada!\");\n }}>\n \t\t<h1>Adicionar Questão</h1>\n \t\t<p>Insira a Pergunta:</p>\n \t\t<input\n \t\t\ttype=\"text\"\n \t\t\tclassName=\"pergunta\"\n \t\t\tplaceholder=\"Conteúdo da Pergunta\"\n ref={node => {\n perguntaInput = node;\n }}\n\n \t\t/>\n \t\t<p>Insira alternativa a):</p>\n \t\t<input \n \t\t\ttype=\"text\"\n \t\t\tclassName=\"alternativa\"\n \t\t\tplaceholder=\"Alternativa A\"\n ref={node => {\n altAInput = node;\n }}\n \t\t/>\n \t\t<p>Insira alternativa b):</p>\n \t\t<input\n \t\t\ttype=\"text\"\n \t\t\tclassName=\"alternativa\"\n \t\t\tplaceholder=\"Alternativa B\"\n ref={node => {\n altBInput = node;\n }}\n \t\t/>\n \t\t<p>Insira a alternativa c):</p>\n \t\t<input\n \t\t\ttype=\"text\"\n \t\t\tclassName=\"alternativa\"\n \t\t\tplaceholder=\"Alternativa C\"\n ref={node => {\n altCInput = node;\n }}\n \t\t/>\n \t\t<p>Insira a alternativa d):</p>\n \t\t<input\n \t\t\ttype=\"text\"\n \t\t\tclassName=\"alternativa\"\n \t\t\tplaceholder=\"Alternativa D\"\n ref={node => {\n altDInput = node;\n }}\n \t\t/>\n <button type=\"submit\">Adicionar Questao</button>\n \t\t</form>\n </div>\n\t);\n\n}",
"function wr(t, e) {\n const n = U(t);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", t => (void 0 === e && (e = -1), n.In.getNextMutationBatchAfterBatchId(t, e)));\n}",
"mutate () {\n const mutations = [\n 'addConnection',\n 'addNode',\n 'updateConnectionWeight'\n ]\n this[getRandomItem(mutations)]()\n }",
"function traqlAudit(traql) {\n let aqlsToBeSent = {\n successAqls: [],\n errorAqls: [],\n };\n let open = true;\n if (open) {\n open = false;\n // if there are any untracked traql entries to be sent to the server\n if (Object.keys(traql).length > 2) {\n let postReq = {\n method: 'post',\n url: 'https://www.aqls.io/aqls',\n };\n // loop through the untracked traql entries\n for (let key in traql) {\n // if it's not the subResolver or UserToken property and this mutation had any subscriptions (or subscribers)\n if (\n key !== 'subResolvers' &&\n key !== 'userToken' &&\n traql[key].expectedNumberOfAqls >= 1\n ) {\n traql[key].mutationId = key;\n // if we receive all of the expected Aqls, aka have resolved this traql entry\n if (\n traql[key].expectedNumberOfAqls ===\n traql[key].aqlsReceivedBack.length\n ) {\n // send the traql back to the server so it can be stored in the DB\n aqlsToBeSent.successAqls.push(traql[key]);\n delete traql[key];\n } else {\n // check if traql obj has \"give me one more chance property\"\n if (traql[key].probation) {\n // otherwise send successful aqls to server for entry into the db\n aqlsToBeSent.errorAqls.push(traql[key]);\n delete traql[key];\n } else {\n traql[key].probation = true;\n }\n }\n }\n }\n postReq.data = aqlsToBeSent;\n axios(postReq)\n .then((res) => {\n console.log('successful addition of aqls to db');\n })\n .catch((err) => console.log('err'));\n }\n open = true;\n }\n}",
"function doCommit()\n{\n var api = getAPIHandle();\n var result = \"false\";\n if (api == null)\n {\n message(\"Unable to locate the LMS's API Implementation.\\nCommit was not successful.\");\n }\n else if (!initialized && ! doInitialize())\n {\n var error = ErrorHandler();\n message(\"Commit failed - Could not initialize communication with the LMS - error code: \" + error.code);\n }\n else\n {\n // switch method based on SCORM Version\n if (versionIsSCORM2004)\n {\n result = api.Commit(\"\");\n }\n else\n {\n result = api.LMSCommit(\"\");\n }\n \n if (result != \"true\")\n {\n var err = ErrorHandler();\n message(\"Commit failed - error code: \" + err.code);\n }\n }\n\n return result.toString();\n}",
"function updateIssue() {\n const usId = document.getElementById(\"modal-id\").value.substring(5);\n const nom = document.getElementById(\"modal-nom\").value;\n const description = document.getElementById(\"modal-description\").value;\n const priority = document.getElementById(\"modal-priority\").value;\n const difficulty = document.getElementById(\"modal-difficulty\").value;\n\n let jsonData = {\n \"name\": nom,\n \"description\": description,\n \"priority\": priority,\n \"difficulty\": difficulty\n }\n\n sendAjax(\"/api/issue/\" + usId, 'PUT', JSON.stringify(jsonData)).then(() => {\n document.getElementById(\"issue\" + usId + \"-name\").innerHTML = \"<h4><strong>\" + nom + \"</strong></h4>\";\n document.getElementById(\"issue\" + usId + \"-description\").innerHTML = description;\n document.getElementById(\"issue\" + usId + \"-priority-btn\").value = priority;\n document.getElementById(\"issue\" + usId + \"-priority\").innerHTML = \"<h6>Priorité :\" +\n \"<span class=\\\"label label-default\\\">\" + priority + \" </span>\" +\n \"</h6>\";\n document.getElementById(\"issue\" + usId + \"-difficulty-btn\").value = difficulty;\n document.getElementById(\"issue\" + usId + \"-difficulty\").innerHTML = \"<h6>Difficulté :\" +\n \"<span class=\\\"label label-default\\\">\" + difficulty + \" </span>\" +\n \"</h6>\";\n $(\"#modal\").modal(\"hide\");\n })\n .catch(() => {\n $(\".err-msg\").fadeIn();\n $(\".spinner-border\").fadeOut();\n })\n}",
"function vuexMutation(mutationName, predefinedPayload) {\n return function mutation(callbackPayload) {\n let payload = predefinedPayload ? evaluate(this, [predefinedPayload])[0] : callbackPayload;\n\n return this.$store.commit(makeMethodName(mutationName), payload);\n };\n }",
"async function transferIssues(owner, repo, projectId) {\n inform(\"Transferring Issues\");\n\n // Because each\n let milestoneData = await getAllGHMilestones(owner, repo);\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlab.Issues.all({projectId: projectId});\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let ghIssues = await getAllGHIssues(settings.github.owner, settings.github.repo);\n\n console.log(\"Transferring \" + issues.length.toString() + \" issues\");\n\n //\n // Create Placeholder Issues\n //\n\n for (let i=0; i<issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i+1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid != expectedIdx) {\n issues.splice(i, 0, {\n iid: expectedIdx,\n title: `placeholder issue for issue ${expectedIdx} which does not exist and was probably deleted in GitLab`,\n description: 'This is to ensure the issue numbers in GitLab and GitHub are the same',\n state: 'closed'\n });\n i++;\n console.log(\"Added placeholder issue for GitLab issue #\" + expectedIdx)\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // TODO: get slice from issues instead of condition\n if (issue.iid < start || issue.iid > end) {\n continue\n }\n // try to find a GitHub issue that already exists for this GitLab issue\n let ghIssue = ghIssues.find(i => i.title.trim() === issue.title.trim() + \" - [glis:\" + issue.iid + \"]\");\n if (!ghIssue) {\n console.log(\"Creating: \" + issue.iid + \" - \" + issue.title);\n try {\n\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await createIssueAndComments(settings.github.owner, settings.github.repo, milestoneData, issue);\n\n } catch (err) {\n console.error(\"Could not create issue: \" + issue.iid + \" - \" + issue.title);\n console.error(err);\n process.exit(1);\n }\n } else {\n console.log(\"Already exists: \" + issue.iid + \" - \" + issue.title);\n updateIssueState(ghIssue, issue);\n }\n };\n\n}",
"commit(transaction_id) {\n this.sendCommand('COMMIT', {'transaction': transaction_id});\n this.log.debug(`commit transaction: ${transaction_id}`);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all doctors for an admin profile | function getAllDoctors(req, res, next) {
db.any('select acct_active, active, fname, lname, id, username from users')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL Doctors'
});
})
.catch(function (err) {
return next(err);
});
} | [
"getAllAdmins() {\n return this.getUserSets('ADMIN');\n }",
"function getDoctors() {\n var doctors = document.querySelectorAll('div.detail-data');\n/* used source for help:\n https://stackoverflow.com/questions/41186171/casper-js-links-from-array\n*/\n return Array.prototype.map.call(doctors, function(e) {\n return {\n name: e.querySelector('.doctorTitle').text,\n specialty: e.querySelector('.specialtyMargin').textContent,\n office: e.querySelector('.doctorOffice > span').textContent,\n address: e.querySelector('.doctorAddress > span').textContent,\n city: e.querySelector('.doctorAddress > div :nth-child(1)').textContent,\n state: e.querySelector('.doctorAddress > div :nth-child(2)').textContent,\n zip: e.querySelector('.doctorAddress > div :nth-child(3)').textContent,\n }\n });\n}",
"function doctorsAvailable(){\n\tvar doctors = []\n\tfor (i=0; i<visual.doctors.length; i++){\n\t\tif (visual.doctors[i].state == IDLE){\n\t\t\tdoctors.push(i)\n\t\t}\n\t}\n\treturn doctors;\n}",
"static getAllTenants() {\n return HttpClient.get(`${IDENTITY_GATEWAY_ENDPOINT}tenants/all`).map(toTenantModel);\n }",
"ListOfAuthorizedDeferredPaymentAccountForThisCustomer() {\n let url = `/me/paymentMean/deferredPaymentAccount`;\n return this.client.request('GET', url);\n }",
"function getDirectorList(){\n\t\tvar dlc = 0; // director list counter\n\n\t\tfor (var i = 0; i < teamList.length; i++) {if (distinct.indexOf(teamList[i].director) === -1){distinct.push(teamList[i].director);}}\n\n\t\tdistinct.sort(sortDirector);\n\n\t\tfor(x = 0; x < distinct.length; x++) {\n\t\t\tif (distinct[x] !== null && distinct[x] !== \"\") {\n\t\t\t\tvar dFilter = distinct[x];\n\t\t\t\tmdPop = $('<div id=\"o' + x + '\" onClick=\"oMenu()\" value=\"' + dlc + '\" class=\"highlight\">' + distinct[x] + '</div>');\n\t\t\t\t(function(){\n\t\t\t\t\tvar locallink = distinct[x];\n\t\t\t\t\tmdPop.click(function(){displayFiltered(locallink);});\n\t\t\t\t})();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmdPop = $('<a href=\"#\"><option id=\"all\" value=\"All\" onClick=\"re_displayAll()\" class=\"highlight\">All</option></a>');\n\t\t\t}\n\n\t\t\tfilter4 = distinct[x];\n\t\t\tdlc = dlc + 1;\n\n\t\t\tmdl.append(mdPop);\n\t\t}\n\t}",
"function getAdminProfile() {\n FYSCloud.API.queryDatabase(\n \"SELECT * FROM profile WHERE user_id = ?\",\n [admin[0].user_id]\n\n ).done(function(adminDetails) {\n admin = adminDetails[0];\n // check if there is an avatar\n if(admin.avatar !== null) {\n $('#navbarAvatar').attr('src', admin.avatar);\n }\n }).fail(function(reason) {\n console.log(reason);\n });\n }",
"async getUserList () {\n return await this.Config.userStore.getUserList();\n }",
"getAllChildrenAndStaff() {\n var users = JSON.parse(this.getAllUsers()).data;\n var staff = [];\n var children = [];\n\n users.forEach(user => {\n if (['lowStaff', 'upStaff', 'sysOverseer'].includes(user['permission'])) {\n staff.push(user);\n } else {\n children.push(user)\n }\n })\n\n return {\n children: children,\n staff: staff\n };\n }",
"function getUsers() {\n //get the data from postFactory using API call\n userService.getUsers()\n .then(\n function (data) {\n console.log('getting users data to be used in postController', data);\n postCtrl.postUsers = data;return data;\n },\n function (response) { postCtrl.status = 'unable to load!'; });\n }",
"getAdminInfo() {\n return {\n admin_1: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_1),\n admin_2: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_2),\n signature_1: this.data.config.AG_REGISTER_SIGNATURE_1,\n signature_2: this.data.config.AG_REGISTER_SIGNATURE_2,\n address_pos_left: this.data.config.ADDRESS_POS_LEFT,\n address_pos_top: this.data.config.ADDRESS_POS_TOP,\n }\n }",
"function listAdmins(limit, token, minrole, cb) {\n const q = ds.createQuery([KIND_PLAYER])\n .limit(limit)\n .filter('role', '>=', minrole)\n .order('role', {\n descending: true\n })\n .order('playername')\n .start(token);\n\n ds.runQuery(q, (err, entities, nextQuery) => {\n if (err) {\n cb(err);\n return;\n }\n const hasMore = nextQuery.moreResults !== Datastore.NO_MORE_RESULTS ? nextQuery.endCursor : false;\n cb(null, entities.map(fromDatastore), hasMore);\n });\n}",
"function viewManagers() {\n connection.query(\"SELECT first_name AS First, last_name AS Last, department.name AS Department FROM employee INNER JOIN department ON department.id = employee.department_id WHERE manager_id IS NULL\", function (err, results) {\n if (err) throw err;\n console.table(\"List of Managers:\", results);\n mainMenu();\n });\n}",
"function getCustomerProfileExample() {\n oneapi.getCustomerProfile('me',function(isOk,oResponse) {\n if(!isOk) { // oResponse is DmApiError\n log(\"Error: Unable to get Customer profile:\" + oResponse.getErrorText()); \n } else { // oResponse is DmCustomerProfile\n log(\"Customer profile for <b>\" + oResponse.getAttr(\"username\",\"\") + '</b> :'); \n oResponse.forEachAttr(function(name,value) { // display all attributes of customer profile\n log(name + \" = \" + value);\n return true;\n }); \n log(\"Done.\");\n }\n });\n}",
"daughters(person) {\n var children = person.sons;\n const daughter = [];\n children.forEach(function (kid) {\n if (kid.gender === 'female') {\n daughter.push(kid);\n }\n }, this);\n\n return daughter;\n }",
"function getcustomers(req, res) {\n\t//Query the DB and if no errors, send all the customers\n\tlet query = customer.find({});\n\tquery.exec((err, customers) => {\n\t\tif(err) res.send(err);\n\t\t\n\t\tres.json(customers);\n\t});\n}",
"function getOffices() {\n // Runs function to get all the offices from database\n Office.getOffices().then(function(data) {\n // Check if able to get data from database\n if (data.data.success) {\n // Check which permissions the logged in user has\n if (data.data.permission === 'admin' || data.data.permission === 'moderator') {\n app.offices = data.data.offices; // Assign offices from database to variable\n app.loading = false; // Stop loading icon\n app.accessDenied = false; // Show table\n\n // Check if logged in user is an admin or moderator\n if (data.data.permission === 'admin') {\n app.editAccess = true; // Show edit button\n app.deleteAccess = true; // Show delete button\n } else if (data.data.permission === 'moderator') {\n app.editAccess = true; // Show edit button\n }\n } else {\n app.errorMsg = 'Insufficient Permissions'; // Reject edit and delete options\n app.loading = false; // Stop loading icon\n }\n } else {\n app.errorMsg = data.data.message; // Set error message\n app.loading = false; // Stop loading icon\n }\n });\n }",
"function directorsAgeSum() {\n return _.sumBy(getUsersByDirector(true), 'age');\n}",
"function getDriverNames(admin) {\r\n\tvar query =\r\n`\r\nSELECT FName${(admin ? ', LName' : '')}\r\nFROM DRIVER\r\nORDER BY ${(admin ? 'Lname, ' : '')}FName\r\n`\r\n\r\n\tif (admin) query = 'SELECT * FROM DRIVER'\r\n\r\n\treturn tp\r\n\t.sql(query)\r\n\t.execute()\r\n\t.then(function(results){\r\n\t\treturn Promise.resolve(results)\r\n\t}) // follow up on the results\r\n\t.fail(function(err) {\r\n\t\treturn Promise.reject(err)\r\n\t}) // or do something if it errors\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds zeros to the right of a byte | function addZerosRight(number) {
return number.padEnd(8, "0");
} | [
"function bytePad(binarystr) {\n var padChar = \"0\";\n var pad = new Array(1 + 8).join(padChar);\n return (pad + binarystr).slice(-pad.length);\n}",
"function rotateLeft8Bit(value, n) {\n return ((value << n) | (value >> (8 - n))) & 0xFF;\n}",
"function leftCircularShift(num,bits){\nnum = num.toString(2);\nnum = parseInt(num.substr(1,num.length-1)+num.substr(0,1),2);\nnum = parseInt(num,2);\nreturn num;\n}",
"static bytes9(v) { return b(v, 9); }",
"function padToEven(a){return a.length%2?\"0\"+a:a;}",
"function zeroPad(val, width) {\n width = width || 2;\n while (String(val).length < 2) {\n val = '0' + String(val);\n }\n return val;\n }",
"static bytes11(v) { return b(v, 11); }",
"function append_byte_array(so, val, bytes) {\n if (\"number\" !== typeof val) {\n throw new Error(\"Integer is not a number\");\n }\n if (val < 0 || val >= (Math.pow(256, bytes))) {\n throw new Error(\"Integer out of bounds\");\n }\n var newBytes = [];\n for (var i=0; i<bytes; i++) {\n newBytes.unshift(val >>> (i*8) & 0xff);\n }\n so.append(newBytes);\n}",
"setByte(depth) {\n this.write(\"<\".repeat(depth) + \"[-]\"); // go the value, and zero it\n this.write(\">\".repeat(depth)); // go back to the top of the stack\n this.write(\"[\"); // repeat until the value at tope is 0\n this.write(`-${\"<\".repeat(depth)}+${\">\".repeat(depth)}`); // decrement the stack-top and increment the target byte\n this.write(\"]\"); // end loop.\n this.write(\"<\"); // move pointer one step back.\n }",
"pushByte(value) {\n this.write(\">\" + \"+\".repeat(value));\n this.stack.push(StackEntry(DataType.Byte, 1));\n }",
"function completeBinary(str) {\n\tlet a = str;\n\twhile (a.length % 8 !== 0) {\n\t\ta = \"0\" + a;\n\t}\n\treturn a;\n}",
"static bytes10(v) { return b(v, 10); }",
"function leftPad(pinCode, targetLength) {\n var count = pinCode.length;\n var output = pinCode;\n\n while (count < targetLength) {\n output = '0' + output;\n count++;\n }\n return output;\n}",
"static bytes22(v) { return b(v, 22); }",
"function addPrefixZero(num){\n if(num<10){\n return \"0\"+num;\n }\n return num;\n}",
"function fixedHex(number, length)\n{\n var str = number.toString(16).toUpperCase();\n while(str.length < length) {\n str = \"0\" + str;\n }\n return str;\n}",
"static bytes27(v) { return b(v, 27); }",
"static bytes23(v) { return b(v, 23); }",
"function getByteN(value, n) {\n return ((value >> (8 * n)) & 0b11111111);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Task Cards Render Task card | function renderTaskCards() {
// Clear task cards before rendering
toDoDiv.innerHTML = `<h2>To do</h2>`;
inProgressDiv.innerHTML = `<h2>In Progress</h2>`;
finishedDiv.innerHTML = `<h2>Finished</h2>`;
// Get tasks
const taskArray = getLocalStorage("task");
// Create task card
// Fill task card with info from task obj
let number = 0;
taskArray.forEach(task => {
number++;
let taskHtml = `
<div class="taskCard" id="taskDiv-${number}" draggable="true" ondragstart="drag(event)">
<div id="taskTitle">${task.name}</div>
<div id="taskDescription">${task.description}</div>
<div id="taskCardClickTarget" onclick="clickTaskCard(event)">
</div></div>`;
if (task.phase === "todo") {
toDoDiv.innerHTML += taskHtml;
} else if (task.phase === "inProgress") {
inProgressDiv.innerHTML += taskHtml;
} else {
finishedDiv.innerHTML += taskHtml;
}
// Update progress bar
checkProgress();
});
} | [
"function clickTaskCard(event) {\r\n // Display view task\r\n popUpView.style.display = \"block\";\r\n\r\n // get local storage\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n // Get index of taskcard clicked\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === event.target.previousSibling.previousSibling.previousSibling.previousSibling.innerHTML);\r\n let thisTask = getLocalStorage(\"task\")[index];\r\n // Render clicked task in view task\r\n renderTaskCard(thisTask);\r\n}",
"renderThread() {\n if (this.props.threads.length) {\n return this.props.threads.map((thread, index) => {\n\n return (\n <Card key={thread.data.id} thread={thread} />\n );\n\n });\n } else {\n return (\n <div className=\"progress-container col s12\">\n {this.renderError()}\n </div>\n )\n }\n }",
"function displayCard(tsv, prepend=false) {\n let curId = idCounter++\n let node = createCard(tsv, curId, true)\n if (prepend) {\n $(\"#deck-display\").prepend(node)\n } else {\n $(\"#deck-display\").append(node)\n }\n cards.set(curId, new Card(tsv[0], tsv[1], node))\n }",
"function createCards(json) {\n\t// Get the container element for the todo cards\n\tconst todoContainer = document.getElementById(\"todoContainer\");\n\n\t// Dynamically create one card for each todo object in the json data\n\tjson.forEach(todo => {\n\t\t// Create the 'assigned to' card header\n\t\tvar userId = document.createElement(\"span\");\n\t\tuserId.innerText = \"ASSIGNED TO: \" + nameFromUserId(todo.userId);\n\t\tuserId.className = \"userId\";\n\n\t\t// Create the card title\n\t\tvar title = document.createElement(\"h4\");\n\t\ttitle.innerText = todo.title;\n\n\t\t// Create task completion element\n\t\tvar status = document.createElement(\"span\");\n\n\t\t// Create the card itself\n\t\tvar card = document.createElement(\"div\");\n\t\tcard.classList.add(\"card\");\n\n\t\t// Sets card class and text based on task completion\n\t\tif (todo.completed) {\n\t\t\tcard.classList.add(\"complete\");\n\t\t\tstatus.innerText = \"COMPLETED\";\n\t\t}\n\t\telse {\n\t\t\tcard.classList.add(\"incomplete\");\n\t\t\tstatus.innerText = \"NOT COMPLETED\";\n\t\t}\n\n\t\t// Append the elements to eachother and the card to its container\n\t\tcard.appendChild(userId);\n\t\tcard.appendChild(title);\n\t\tcard.appendChild(status);\n\t\ttodoContainer.appendChild(card);\n\t});\n}",
"function Cards(Scabs) {\n for (let i = 0; i < Scabs.length; i++) {\n let Thread = {\n title: \"\",\n link: \"\",\n id: \"\"\n };\n Thread.title = Scabs[i].title;\n Thread.link = reddit + Scabs[i].link;\n Thread.id = Scabs[i].redditId\n //Creates the card\n $(\".row\").after(\n `<div class=\"col s12 m6\">\\\n <div class=\"card red-grey darken-1\">\\\n <div class=\"card-content white-text\">\\\n <span class=\"card-title\">'+ Thread.title + '</span>\\\n <p>' + Thread.title + '</p>\\\n </div>\\\n <div class=\"card-action\">\\\n <a href=\"' + Thread.link + '\">See the comments on Reddit</a>\\\n </div>\\\n </div >\\\n </div > `);\n }\n}",
"function renderBlackcard(){\n blackCardsContainer.show();\n blackCardsContainer.children().each(function(){\n $(this).on(\"click touch\", function(){\n blackCardsContainer.hide();\n cardPreview.show();\n app();\n });\n });\n }",
"renderNewTrip(newBooking, traveler) {\n let totalCost = traveler.getTripCost(newBooking.id).total;\n let destination = traveler.findDestination(newBooking.destinationID);\n let tripStatus = determineStatus(newBooking);\n cardContainer.innerHTML += `\n <article class=\"travelCard\">\n <div class=\"headerContent\">\n \n <div class=\"headerInfo\">\n <div class=\"locationIconHolder\">\n <img src=\"./images/passport.png\" alt=\"location icon\" class=\"locationIcon\">\n <h2>${destination.destination}</h2>\n </div> \n <div class=\"confirmationHolder\">\n <h3>status: ${newBooking.status}</h3>\n <img src=\"${tripStatus}\" alt=\"confirmation status icon\" class=\"statusIcon\"> \n </div> \n </div>\n <div class=\"destinationImg\">\n <img src=${destination.image} alt=\"${destination.alt}\" class=\"destinationImg\" >\n </div>\n </div>\n <div class=\"bodyContent\">\n <div class=\"departureIconHolder\">\n <img src=\"./images/airplane.png\" alt=\"takeoff icon\" class=\"takeoffIcon\">\n <h3>Departs: ${newBooking.date}</h3>\n </div>\n <h4>Cost: $${totalCost}</h4>\n <h4>number of travelers: ${newBooking.travelers}</h4>\n </div>\n </article>\n `\n\n }",
"function createTaskDiv(task) {\r\n\r\n let taskDiv = $('<div/>', { class: 'task flex', id: task.taskid }) // contains the entire div for the task\r\n\r\n // create the SVGs by using the status of the tasks\r\n let taskDescriptionSpan = createTaskDescription(task.description);\r\n let checkmarkSVG = createCheckMarkSVG();\r\n let helpSVG = createHelpSVG(task.help, task.status);\r\n\r\n // add all the elements\r\n taskDiv.append(taskDescriptionSpan, checkmarkSVG, helpSVG);\r\n\r\n return taskDiv;\r\n}",
"viewCards() {\n this.cardsViewed = true;\n this.viewConfigCards(); // Subjects/Grades, Schedule, and Service Hrs\n this.viewLocationCards();\n }",
"buildPlayingCard(cardFace, suitIcon, faceColor, suitColor) {\n console.log(\"buildCard Log\", cardFace)\n\n\n //return string for playing card divs.\n return `<div class=\"card player-card\" style=\"width:100%\">\n <div class=\"card-title\" style=\"text-align:left; font-size:20px; padding-left:10px; color:${faceColor};\">\n ${cardFace} \n </div>\n <div class=\"card-content\" style=\"font-size:28px; padding-bottom:25px\">\n \n <span class=\"${suitIcon}\" style=\"color:${suitColor}\">\n </span>\n </div>\n </div>`\n }",
"static projectCardTemplate(project) {\r\n const template = `\r\n <div class=\"col-4\">\r\n <div class=\"card\" data-id=\"${project.id}\">\r\n ${project.img ? `<img class=\"card-img-top\" src=\"${project.img}\" alt=\"card img cap\">` : ''}\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\">${project.name}</h5>\r\n <p class=\"card-text\">${project.description}</p>\r\n <a href=\"#\" class=\"btn btn-primary edit ml-5 w-25\" data-toggle=\"modal\" data-target=\"#changeProject\">Edit</a>\r\n <a href=\"#\" class=\"btn btn-danger delete-btn ml-5 w-25\">Delete</a>\r\n </div>\r\n </div>\r\n </div>\r\n `;\r\n return template;\r\n }",
"function makeLoop() {\n const projectCards = document.querySelectorAll('.project-name-card');\n for (let i = 0; i < projectCards.length; i += 1) {\n const card = projectCards[i];\n card.addEventListener('click', () => {\n deleteOtherTasks();\n const taskCard = document.querySelector('#new-task-card');\n const projectTitleInTaskCard = document.querySelector('#new-project-task');\n projectTitleInTaskCard.textContent = card.innerText;\n taskCard.classList.remove('hide');\n document.querySelector('#new-project-section').classList.add('hide');\n document.querySelector('#new-project-section').classList.remove('show');\n taskCard.classList.add('show');\n const project = projectsArray.find((p) => p.title === projectTitleInTaskCard.textContent);\n const index = projectsArray.indexOf(project);\n loadTasks(index);\n });\n }\n}",
"function genCard(fighter, num) {\n const card = genElement(\"<div>\", \"card d-flex flex-row pt-2 px-1\", `card-${fighter}`);\n const row = genElement(\"<div>\", `${fighter === \"lukeSkywalker\" ? \"row no-gutters\" : \"row no-gutters w-96\"}`, null);\n const colAuto = genElement(\"<div>\", \"col-auto\", null);\n const ftrImg = genElement(\"<img>\", \"img-fluid mx-2 mb-2\", null).attr(\"src\", `assets/images/${fighter}.png`);\n const col = genElement(\"<div>\", \"col\", null);\n const crdBlk = genElement(\"<div>\", \"card-block px-2\", null);\n const crdTle = genElement(\"<h2>\", \"card-title mt-3 ml-2\", null).text(fighter)\n const crdTxt = genElement(\"<div>\", \"card-block px-2\", null).html(genStats(fighter));\n const prgTle = genElement(\"<h4>\", \"mt-3 ml-2\", null).text(\"Health\");\n const hlth = genElement(\"<div>\", \"progress\", null);\n const prgsBR = genElement(\"<div>\", \"progress-bar bg-success\", `hlthBr-${num}`).attr(\"aria-valuenow\", fighterObj[fighter].health).attr(\"role\", \"progressbar\").attr(\"style\", ` width: ${fighterObj[fighter].health}%;`).text(`${fighterObj[fighter].health}%`);\n colAuto.append(ftrImg);\n hlth.append(prgsBR);\n col.append(crdBlk, crdTle, crdTxt, prgTle, hlth);\n return card.append(row.append(colAuto).append(col));\n}",
"function getCardTemplate(card){\r\n return `\r\n <article class=\"card ${card.suite}\">\r\n <div class=\"top\">\r\n <p class=\"value\">${card.value}</p>\r\n <p class=\"suite\">${getCardSymbol(card.suite)}</p>\r\n </div>\r\n <div class=\"middle\">\r\n <p class=\"suite\">${getCardSymbol(card.suite)}</p>\r\n </div>\r\n <div class=\"bottom\">\r\n <p class=\"value\">${card.value}</p>\r\n <p class=\"suite\">${getCardSymbol(card.suite)}</p>\r\n </div>\r\n </article>\r\n `\r\n}",
"function makeCards() {\n //clear previous search results\n cardWrapperDiv.innerHTML = ``;\n for (let i = 0; i < recipeList.length; i++) {\n let newCard = document.createElement(`div`);\n newCard.classList.add(`card`);\n newCard.setAttribute(`data-id`, [i]);\n newCard.setAttribute(`style`, `background-image: url(${recipeList[i].image}); background-position: center;`);\n\n newCard.innerHTML = `\n <div >\n <span class=\"card-title\">${recipeList[i].label}</span>\n </div> \n `;\n cardWrapperDiv.append(newCard);\n\n }\n\n }",
"function TaskDetails({ match }) {\n const { task_id } = match.params;\n const { tickets } = useContext(AppContext);\n const [task, setTask] = useState(null);\n\n // find and display the correct task on mount\n useEffect(() => {\n let foundTask = null;\n\n for (const ticket of tickets) {\n if (ticket.tasks) {\n for (const t of ticket.tasks) {\n if (t.id === +task_id) {\n foundTask = t;\n }\n }\n }\n }\n\n setTask(foundTask);\n }, [task_id, tickets]);\n\n return (\n task && (\n <div>\n <div>{task.title}</div>\n <div>{task.description}</div>\n <div>{task.status}</div>\n {task.actions && <ActionList actions={task.actions} />}\n </div>\n )\n );\n}",
"function PostCard(props){\n return <div>\n <div className=\"card fluid\" id={\"post_\"+nextPostId()}>\n <img className=\"section media\" src={props.image} alt=\"\" style={randomColor()}/>\n <div className=\"section\">\n <p className=\"post-text\">{props.text+'.'}</p>\n </div>\n <div className=\"section\">\n <p className=\"posted-by\"> <SvgUser /> Posted by {users[props.userId].login.username}</p>\n </div>\n </div>\n </div>;\n}",
"generateIndexPage(obj, container, types, gradedLevels, statuses, arr) {\n\n /* function for generating edit form inside modal. Calls generateEditForm method defined in class */\n let generateEditForm = () => { return this.generateEditForm(obj, 'main', types, gradedLevels, statuses, arr);}\n\n /* function for toggleing modal, and appending it to div.edit-modal. Calls toggleModal method defined in class */\n let toggleModal = () => { return this.toggleModal('div.edit-modal') }\n\n /* functtion for creating an object in localstorage as a temporary storage soloution. Used to edit information about cards */\n let tempStorage = () => {return this.createTempStorage(obj.getId(), obj.getStatus(), obj.getTitle(), obj.getDesc(), obj.getType(), obj.getImgUrl(), obj.getAlt(), obj.getGradedLevel(), obj.getDate(), obj.getAddress())};\n\n /* function for deleting card object from the object array. Calls deleteCard method defined in class */\n let deleteCard = () => { return this.deleteCard(obj, arr); }\n\n /* function for updating counter for amount of tasks with a certain status. Calls updateCount method defined in class */\n let updateCount = () => { return this.updateCount(arr); }\n \n /* function for formatting status of card */\n let formatStatus = () => {\n /* conditional check if card has status 'Ikke løst' */\n if (obj.getStatus() == 'Ikke løst') {\n\n /* if it have, return css class x-negative */\n return 'case-card-content-status-negative';\n } else {\n\n /* else, return css class x-postivie */\n return 'case-card-content-status-positive'\n }\n }\n \n /* card structure, formatted for readability */\n let generateCard = `<article class=\"case-card-${obj.getId()} case-card\">\n <div>\n <!-- preserves UD by adding alt text -->\n <img class=\"case-card-img\" src=\"${obj.getImgUrl()}\" alt=\"${obj.getAlt()}\">\n </div> \n <div class=\"case-card-content\">\n <div class=\"flex justify-between items-center\">\n <!-- preserved UD by having strong grey color on a white background -->\n <p class=\"case-card-content-type\"> ${obj.getType()} • Sak ${obj.getId()}</p>\n <div>\n <!-- preserves UD by having a strong red color on a light red colored background -->\n <span class=\"${formatStatus()} flex items-center\">${obj.getStatus()}</span>\n </div>\n </div>\n <h2 class=\"case-card-content-title\">${obj.getTitle()}</h2>\n </div>\n <div class=\"case-card-meta\">\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M13 20v-5h-2v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7.59l-.3.3a1 1 0 1 1-1.4-1.42l9-9a1 1 0 0 1 1.4 0l9 9a1 1 0 0 1-1.4 1.42l-.3-.3V20a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2zm5 0v-9.59l-6-6-6 6V20h3v-5c0-1.1.9-2 2-2h2a2 2 0 0 1 2 2v5h3z\"/>\n </svg>\n <span>${obj.getFormattedAddress()}</span>\n </div>\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M13 16v5a1 1 0 0 1-1 1H9l-3-6a2 2 0 0 1-2-2 2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2 0-1.1.9-2 2-2h7.59l4-4H20a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-2.41l-4-4H13zm0-2h1.41l4 4H20V4h-1.59l-4 4H13v6zm-2 0V8H6v2H4v2h2v2h5zm0 2H8.24l2 4H11v-4z\"/>\n </svg>\n <span>Gradert ${obj.getGradedLevel()}</span>\n </div>\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M12 22a10 10 0 1 1 0-20 10 10 0 0 1 0 20zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm1-8.41l2.54 2.53a1 1 0 0 1-1.42 1.42L11.3 12.7A1 1 0 0 1 11 12V8a1 1 0 0 1 2 0v3.59z\"/>\n </svg>\n <span>Opprettet ${obj.getDate()}</span>\n </div>\n </div>\n <div class=\"case-card-action flex items-center justify-between\">\n <div class=\"case-card-action-btn-container w-1\">\n <!-- preserves UD by having a white text color against a dark gray background -->\n <a href=\"edit.html\" class=\"card-${obj.getId()} case-card-action-btn\">Se detaljer</a>\n </div>\n <div class=\"flex justify-end items-center case-card-action-icn-container\">\n <!-- preserves UD by having a white text color against a dark gray background -->\n <button type=\"button\" class=\"delete-card-${obj.getId()} flex items-center mr-2\">\n <svg class=\"icn actions-bar\" viewBox=\"0 0 20 20\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n <circle id=\"Oval\" fill=\"#000000\" cx=\"10\" cy=\"10\" r=\"10\"></circle>\n <path d=\"M5.6,5.8 L14,5.8 L13.466,14.872 C13.4278642,15.5064687 12.9016127,16.0011451 12.266,16.000002 L7.34,16.000002 C6.7043873,16.0011451 6.17813579,15.5064687 6.14,14.872 L5.6,5.8 Z M8.6,8.8 C8.26862915,8.8 8,9.06862915 8,9.4 L8,13 C8,13.3313708 8.26862915,13.6 8.6,13.6 C8.93137085,13.6 9.2,13.3313708 9.2,13 L9.2,9.4 C9.2,9.06862915 8.93137085,8.8 8.6,8.8 Z M11,8.8 C10.6686292,8.8 10.4,9.06862915 10.4,9.4 L10.4,13 C10.4,13.3313708 10.6686292,13.6 11,13.6 C11.3313708,13.6 11.6,13.3313708 11.6,13 L11.6,9.4 C11.6,9.06862915 11.3313708,8.8 11,8.8 Z\" id=\"Shape\" fill=\"#FFFFFF\"></path>\n <path d=\"M7.754,5.2 L8.774,4.18 C8.88624286,4.06548661 9.03965246,4.00066565 9.2,4 L10.4,4 C10.5582616,4.00225423 10.7092217,4.06695144 10.82,4.18 L11.852,5.2 L14,5.2 C14.3313708,5.2 14.6,5.46862915 14.6,5.8 C14.6,6.13137085 14.3313708,6.4 14,6.4 L5.6,6.4 C5.26862915,6.4 5,6.13137085 5,5.8 C5,5.46862915 5.26862915,5.2 5.6,5.2 L7.754,5.2 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n </svg>\n </button>\n <!-- preserves UD by having a white text color against a dark gray background -->\n <button type=\"button\" class=\"card-${obj.getId()} edit-card-${obj.getId()} flex items-center\">\n <svg class=\"icn actions-bar\" viewBox=\"0 0 20 20\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n <circle id=\"Oval\" fill=\"#000000\" cx=\"10\" cy=\"10\" r=\"10\"></circle>\n <path d=\"M6,10.9929286 C6.00187852,10.8610439 6.05579287,10.7352438 6.15,10.6429286 L11.65,5.14292858 C11.8444218,4.95235714 12.1555782,4.95235714 12.35,5.14292858 L13.85,6.64292858 C14.0405714,6.83735033 14.0405714,7.14850682 13.85,7.34292858 L8.35,12.8429286 C8.25768477,12.9371357 8.13188463,12.9910501 8,12.9929286 L6.5,12.9929286 C6.22385763,12.9929286 6,12.769071 6,12.4929286 L6,10.9929286 L6,10.9929286 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n <rect id=\"Rectangle\" fill=\"#FFFFFF\" x=\"5\" y=\"13.9929286\" width=\"10\" height=\"1\" rx=\"0.5\"></rect>\n </svg>\n </button>\n </div> \n </div> \n </article>`;\n\n /* append cards to 'container' */\n $(container).append(generateCard);\n\n /* after all cards are appended, run function for updating status count */\n updateCount();\n\n /* event handler for clicking \"Se detaljer\" button on each card */\n $('a.card-' + obj.getId()).on('click', function() {\n \n tempStorage(); /* call tempStorage to store object for editing */\n });\n\n /* event handler for clicking edit button on each card */\n $('button.card-' + obj.getId()).on('click', function() {\n \n tempStorage(); /* call tempStorage to store object for editing */\n generateEditForm() /* when object is stored in localstorage, generate edit form inside modal */\n toggleModal(); /* when form i generated, open modal populated with information from card clicked */\n });\n\n /* event handler for clicking delete button on each card */\n $('button.delete-card-' + obj.getId()).on('click', function() {\n\n /* send a confirmation alert. If \"yes\" is clicked, proceed */\n if (window.confirm(\"Are you sure you want to delete the card?\") == true) {\n\n /* fade out card deleted */\n $('article.case-card-' + obj.getId()).fadeOut('slow', function() {\n tempStorage();\n deleteCard(); /* delete it from the cards array by running the deleteCard function/method */\n updateCount(); /* update status count */\n });\n }\n });\n }",
"renderRow(todo) {\n return (\n <TaskRow onDone={this.props.onDone} todo={todo}/>\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates state to animate Forward Low Kick | forwardLowKick() {
this.updateState(KEN_SPRITE_POSITION.forwardLowKick, KEN_IDLE_ANIMATION_TIME, false);
this.triggerAttack(DAMAGE, NORMAL_HIT);
} | [
"haduken() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.haduken, KEN_IDLE_ANIMATION_TIME, false);\n\t}",
"animateBrickState() {\n for (let i = 0; i < this.gridState.length; i++) {\n this.gridState[i] = this.gridState[i] >> 1\n // * Mask off the numbers so they don't just continually grow once the bricks are \"off\" the grid\n this.gridState[i] = this.gridState[i] & (Math.pow(2, this.columns) - 1)\n }\n this.updateStateOutput()\n this.detectCollisions()\n this.paintFrame()\n }",
"function SlideState(){\n\tviewState = new stateClass(stk[stkCurr]);\n\tToState(stk[stkCurr].state);\n}",
"update() {\n\t\tlet landmark = landmarks[party.landmarkIndex];\n\t\tif (landmarks[++party.landmarkIndex]) {\n\t\t\tparty.milesToNextMark = landmarks[party.landmarkIndex].distance;\n\t\t\tthis.nextLandMark = landmarks[party.landmarkIndex].name;\n\t\t\tthis.initialDistance = landmarks[party.landmarkIndex].distance;\n\t\t}\n\t\tif (landmark.generateState) {\n\t\t\tstates.push(landmark.generateState());\n\t\t}\n\t\telse {\n\t\t\tstates.push(new ContinueState(\"Error: This landmark doesn't have a defined state yet.\"));\n\t\t}\n\t}",
"animateReducingStatus() {\n this._reducingTime = 0;\n let twn = new mag.IndefiniteTween((t) => {\n stage.draw();\n\n this._reducingTime += t;\n\n if (!this._reducing || !this.stage) twn.cancel();\n });\n twn.run();\n }",
"function trainingRound(signal){\n\texperiment_state = \"Training\";\n\tif(showNodeInSliderDuringInitialTraining){\n\t\tshowMe(\"SlideWhistle\");\n\t\tplaySignalWithNode(signal); // in this case, signal is an array of physical buffer positions\n\t} else{\n\t\tplaySignal(signal);\n\t}\n\tsetTextStimulus(\"Example \"+trainingCount);\n\ttrainingCount += 1;\n}",
"training() {\n const trainingOpponentSelection = TRAINING_SELECTION;\n\n this.setState({\n mode: Modes.ShipSelection,\n trainingOpponentSelection,\n trainingOpponentCommander: 0,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\n }",
"function KlusterAnimator() {\n\n 'use strict';\n\n var self = this;\n\n var app = KLU5TER;\n\n app.stateRebuilds = true;\n\n var stateChangeDuration = 3000;\n\n // var camera = app.camera;\n\n var easingFunc = TWEEN.Easing.Elastic.Out;\n easingFunc = TWEEN.Easing.Circular.Out;\n easingFunc = TWEEN.Easing.Linear.None;\n\n // Cluster Position and Camera Position Also\n var clusterPos = {\n position: {\n x: 0,\n y: 0,\n z: 0\n },\n rotation: {\n x: Math.PI,\n y: 0,\n z: 0\n },\n camera: {\n x: 28,\n y: 0,\n z: 0,\n fov: app.cameraSettings.FOV\n }\n };\n\n // This is the sequence of state id's for animated mode:\n var animationSequence = ['1', 'Sun Side', '2', '3', '6', '8', 'Scene 2 - Look 1', 'Scene 2 - Look 2', 'Scene 3 - Look 1'];\n\n function getRandomChunk() {\n var mr = THREE.Math.randInt;\n var chunk = {\n level: mr(0, app.clusterOptions.levels - 1),\n segment: mr(0, app.clusterOptions.segments - 1),\n circle: mr(0, app.clusterOptions.circles - 1)\n };\n // console.log('random chunk:', chunk);\n return chunk;\n }\n\n function getRandomPos() {\n var k = 1;\n\n var mrfs = THREE.Math.randFloatSpread;\n clusterPos.position.x = mrfs(20 * k);\n clusterPos.position.y = mrfs(20 * k);\n clusterPos.position.z = mrfs(20 * k);\n\n clusterPos.rotation.x = mrfs(Math.PI * k);\n clusterPos.rotation.y = mrfs(Math.PI * k);\n clusterPos.rotation.z = mrfs(Math.PI * k);\n\n clusterPos.camera.x = THREE.Math.randFloat(2, 15) * k;\n clusterPos.camera.y = THREE.Math.randFloat(2, 25) * k;\n clusterPos.camera.z = THREE.Math.randFloat(0, 10) * k;\n }\n\n var states = {\n '1': {\n time: 1000,\n name: 'State 1',\n handler: function() {\n clusterPos.position.y = 0;\n clusterPos.position.x = 0;\n clusterPos.position.z = 0;\n\n clusterPos.rotation.x = 0;\n clusterPos.rotation.y = 0;\n clusterPos.rotation.z = 0;\n\n clusterPos.camera.y = 22;\n clusterPos.camera.x = 2;\n clusterPos.camera.z = 0;\n\n //setPosFromPosMap('Plasma');\n setPosFromPosMap('Step-1');\n // setPosFromPosMap('Demo Start');\n // setPosFromPosMap('Rotor');\n // setPosFromPosMap('Startup One');\n // setPosFromPosMap('Ring Debugger');\n\n // clusterPos.camera.fov = app.cameraSettings.FOV;\n\n tweenCluster(clusterPos);\n }\n },\n '2': {\n name: 'State 2',\n handler: function() {\n\n // setPosFromPosMap('Disks');\n setPosFromPosMap('Step-2');\n\n tweenCluster(clusterPos);\n\n var rChunk = getRandomChunk();\n rChunk.removeOld = true;\n app.clusterFactory.hiliteChunk(rChunk);\n }\n },\n 'Rumb': {\n name: 'Rumb',\n handler: function() {\n setPosFromPosMap('Rumb');\n tweenCluster(clusterPos);\n }\n },\n '3': {\n handler: function() {\n // TWEAK it to get the best result\n // setPosFromPosMap('Initial Two');\n\n setPosFromPosMap('Step-3');\n\n tweenCluster(clusterPos);\n }\n },\n 'DOMAINS_VIEW': {\n name: 'Domains View',\n handler: function() {\n\n setPosFromPosMap('Step-4');\n tweenCluster(clusterPos);\n\n // app.clusterFactory.hiliteChunk({\n // level: 1,\n // segment: 3,\n // circle: 1,\n // removeOld: true\n // });\n\n }\n },\n 'PERSPECTIVE': {\n name: 'Perspective',\n handler: function() {\n setPosFromPosMap('PERSPECTIVE');\n tweenCluster(clusterPos);\n }\n },\n '6': {\n handler: function() {\n setPosFromPosMap('6');\n tweenCluster(clusterPos);\n }\n },\n 'Scene 2 - Look 1': {\n handler: function() {\n setPosFromPosMap('Scene 2 - Look 1');\n tweenCluster(clusterPos);\n }\n },\n 'Scene 2 - Look 2': {\n handler: function() {\n setPosFromPosMap('Scene 2 - Look 2');\n tweenCluster(clusterPos);\n }\n },\n 'Scene 3 - Look 1': {\n handler: function() {\n setPosFromPosMap('Scene 3 - Look 1');\n tweenCluster(clusterPos);\n }\n },\n 'RING_DEBUGGER': {\n // CHUNKS random array creation:\n handler: function() {\n setPosFromPosMap('Ring Debugger');\n tweenCluster(clusterPos);\n }\n },\n '8': {\n handler: function() {\n setPosFromPosMap('Deep Go');\n tweenCluster(clusterPos);\n }\n },\n 'Sun Side': {\n handler: function() {\n setPosFromPosMap('Sun Side');\n tweenCluster(clusterPos);\n }\n },\n 'RANDOMIZE': {\n name: 'State RANDOMIZE',\n handler: function() {\n getRandomPos();\n tweenCluster(clusterPos);\n }\n },\n 'STATE_HILITE': {\n // CHUNKS random array creation:\n handler: function() {\n hiliteChunks();\n }\n },\n 'END_STATE': {\n handler: function() {\n setPosFromPosMap('Overloaded');\n tweenCluster(clusterPos);\n var rChunk = getRandomChunk();\n rChunk.removeOld = true;\n app.clusterFactory.hiliteChunk(rChunk);\n }\n },\n 'SAVE_POSITION': {\n name: 'Save Position',\n handler: function() {\n app.isManualMode = true;\n app.tracePos();\n }\n },\n 'STOP_START_STATE_SEQUENCE': {\n name: 'Play Sequence',\n handler: function() {\n app.isManualMode = !app.isManualMode;\n }\n },\n 'STATE_SCREEN_SAVE': {\n name: 'State of Going to screen saver mode',\n handler: function() {\n app.autoPlayIsOn = !app.autoPlayIsOn;\n console.log('app.autoPlayIsOn =', app.autoPlayIsOn);\n }\n },\n 'MOUSE_SWITCH': {\n name: 'Enable / Disable Mouse',\n handler: function() {\n app.mouseSelectionIsOn = !app.mouseSelectionIsOn;\n app.isManualMode = true;\n }\n },\n 'STATE_PREV': {\n name: 'State Prev',\n handler: function() {\n app.isManualMode = true;\n getPrevState();\n }\n },\n 'STATE_NEXT': {\n name: 'State Next',\n handler: function() {\n app.isManualMode = true;\n getNextState();\n }\n },\n 'IGNORE_REBUILDS': {\n name: 'Ignore Rebuilds',\n handler: function() {\n app.stateRebuilds = !app.stateRebuilds;\n }\n }\n };\n\n function hiliteChunks() {\n app.clusterFactory.unhiliteChunk({\n removeOld: true\n });\n var rChunk;\n var i = 0;\n while (i < 40) {\n rChunk = getRandomChunk();\n rChunk.removeOld = false;\n app.clusterFactory.hiliteChunk(rChunk);\n i++;\n }\n }\n /**\n * Properties Tween\n * @param o Object to tween.\n * @param prop Property to tween.\n * @param newValue Value van be position-like object or plain value like fov = 75\n */\n function tweenObjProp(o, prop, newValue) {\n var op = o[prop];\n\n // by default, we tween complex position-like object of x, y, and z\n var tweenParams = {\n x: newValue.x,\n y: newValue.y,\n z: newValue.z\n };\n\n // but also can tween simple params like camera.fov\n if (typeof op === 'number') {\n tweenParams = newValue;\n console.log('plain:', tweenParams, op);\n }\n\n // console.log('tween params:', tweenParams, op);\n\n new TWEEN.Tween(op).to(tweenParams, stateChangeDuration).easing(easingFunc).start();\n }\n\n /**\n * @param position Object with properties { x, y, z }\n */\n function tweenCluster(position) {\n tweenObjProp(app.clusterAxis, 'position', position.position);\n tweenObjProp(app.clusterAxis, 'rotation', position.rotation);\n tweenObjProp(app.camera, 'position', position.camera);\n // @todo work it out: tweenObjProp( app.camera, 'fov', position.camera.fov);\n }\n\n this.getStateById = function(stateId) {\n var state = states[stateId];\n return state;\n };\n\n this.setState = function(stateId) {\n var state = self.getStateById(stateId);\n\n if (!state) {\n console.log('A: State not found: ', stateId);\n return;\n }\n // console.log('A: Go to State: ', state.name, state.time);\n state.handler();\n };\n\n this.startAnimator = function() {\n var s = 0;\n var stateId = animationSequence[s];\n var state = self.getStateById(stateId);\n\n self.setState(stateId);\n\n function nextState() {\n\n setTimeout(function() {\n if (!app.isManualMode) {\n stateId = animationSequence[s];\n self.getStateById(stateId);\n self.setState(stateId);\n s = s < animationSequence.length - 1 ? ++s : 0;\n console.log( 'seq: ' + s + ', stateId: ' + stateId );\n // return;\n }\n nextState();\n }, stateChangeDuration);\n }\n nextState();\n };\n\n var step = 0;\n\n function getPrevState() {\n step--;\n var stateId = animationSequence[step];\n self.getStateById(stateId);\n self.setState(stateId);\n step = step > 0 ? step : animationSequence.length - 1;\n }\n\n function getNextState() {\n step++;\n var stateId = animationSequence[step];\n self.getStateById(stateId);\n self.setState(stateId);\n step = step < animationSequence.length - 1 ? step : 0;\n }\n\n function setPosFromPosMap(posId) {\n var p = posMap[posId];\n\n if (!p) {\n console.log('position not found: ' + posId);\n return;\n }\n\n // console.log('position: ' + posId)\n\n clusterPos.position.x = p.clusterAxisPosition.x;\n clusterPos.position.y = p.clusterAxisPosition.y;\n clusterPos.position.z = p.clusterAxisPosition.z;\n\n clusterPos.rotation.x = p.clusterAxisRotation._x;\n clusterPos.rotation.y = p.clusterAxisRotation._y;\n clusterPos.rotation.z = p.clusterAxisRotation._z;\n\n clusterPos.camera.x = p.cameraPosition.x;\n clusterPos.camera.y = p.cameraPosition.y;\n clusterPos.camera.z = p.cameraPosition.z;\n\n clusterPos.camera.fov = app.cameraSettings.FOV;\n\n // @todo debug rebuild...\n // We can also rebuild cluster in each separate state \n // which makes it even more crazy :-)\n if (p.clusterOptions) {\n // console.log('rebuildIsNeeded : ', p.clusterOptions);\n for (var prop in p.clusterOptions) {\n if (app.stateRebuilds && app.clusterOptions[prop] !== p.clusterOptions[prop]) {\n app.clusterOptions[prop] = p.clusterOptions[prop];\n app.rebuildIsNeeded = true;\n }\n }\n app.clusterFactory.checkIfRebuildIsNeeded();\n }\n }\n\n var posMap = {\n '4': {\n clusterAxisPosition: {\n x: 6,\n y: 0,\n z: 6\n },\n clusterAxisRotation: {\n _x: 1.5707963267948966,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: -0.06005512073072366,\n y: -7.432246638646143,\n z: 2.9594092797053992\n }\n },\n 'PERSPECTIVE': {\n clusterAxisPosition: {\n x: -7.214533654041588,\n y: -2.4396179197356105,\n z: -6.001599505543709\n },\n clusterAxisRotation: {\n _x: -0.004470624985189575,\n _y: 0.8727285247146759,\n _z: 0.2941807983596372\n },\n cameraPosition: {\n x: 3.4539531590076105,\n y: 6.374730350658294,\n z: 1.723565274004424\n },\n clusterOptions: {\n levels: 7,\n segments: 14,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n '6i': {\n clusterAxisPosition: {\n x: 6,\n y: 0,\n z: 6\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 1.5707963267948966,\n _z: 0\n },\n cameraPosition: {\n x: 6.95129248126769,\n y: -0.8778824404155695,\n z: 3.86119868184483\n }\n },\n '6s': {\n clusterAxisPosition: {\n x: 1.5707963267948966,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 1.5707963267948966,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: -0.060055120730723645,\n y: -7.432246638646141,\n z: 2.9594092797053984\n }\n },\n // othographic:\n '6': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 17.403784587301185,\n y: -0.12254841677667727,\n z: -14.008167078637566\n }\n },\n 'Center Close Up': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 1.028771578588749,\n y: -8.308587640904749,\n z: 11.124279206317121\n },\n clusterOptions: {\n levels: 7,\n segments: 11,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Initial One': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 0.2705519085581147,\n y: 2.9760709941392562,\n z: 1.6566526440945126e-17\n }\n },\n 'Initial Two': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 7.616083989998293,\n y: -0.5361002156843375,\n z: 11.321729010548237\n },\n clusterOptions: {\n levels: 7,\n segments: 11,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Ring Debugger': {\n clusterAxisPosition: {\n x: 2.675469731912017,\n y: -1.3926358567550778,\n z: -0.1531926728785038\n },\n clusterAxisRotation: {\n _x: -0.3389570963864635,\n _y: 1.1449295472769976,\n _z: 0.7135726666172066\n },\n cameraPosition: {\n x: 18.972382109268164,\n y: 0.9649503928964404,\n z: 6.804224685047472\n },\n clusterOptions: {\n levels: 7,\n segments: 11,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Overloaded': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 2.643754331703072,\n y: -0.48247358349057407,\n z: 9.45864986354379\n },\n clusterOptions: {\n levels: 7,\n segments: 14,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Overloaded2': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 2.643754331703072,\n y: -0.48247358349057407,\n z: 9.45864986354379\n },\n clusterOptions: {\n levels: 7,\n segments: 14,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Startup One': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: -1.57\n },\n cameraPosition: {\n x: 0.2769207931575115,\n y: 4.184341999705629,\n z: 18.531448861430537\n },\n clusterOptions: {\n levels: 5,\n segments: 16,\n circles: 3,\n segmentsSpacing: 0.99,\n levelsSpacing: 1,\n ringSpacing: 0.5,\n height: 10,\n radius: 10\n }\n },\n 'Rotor': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: -1.57\n },\n cameraPosition: {\n x: 13.3298470722081945,\n y: 22.280427658470726,\n z: 27.62011200028033\n },\n clusterOptions: {\n levels: 4,\n segments: 16,\n circles: 3,\n segmentsSpacing: 990,\n levelsSpacing: 1.1,\n ringSpacing: 1.1,\n height: 10,\n radius: 10\n }\n },\n 'Demo Start': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 6.651247451081872,\n z: 4.412601953372359\n },\n clusterAxisRotation: {\n _x: 1.0923053542624157,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: -3.3488386564226804,\n y: 5.685156374699902,\n z: -3.4786507378435356\n },\n clusterOptions: {\n levels: app.klusterModel.levels.length || 5,\n segments: app.klusterModel.segments.length || 16,\n circles: app.klusterModel.circles.length || 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 1,\n height: 10,\n radius: 10\n }\n },\n 'Disks': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 10,\n z: 4.412601953372359\n },\n clusterAxisRotation: {\n _x: 1.5707963267948966,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: -3.348838656422682,\n y: 28,\n z: -3.4786507378435365\n },\n clusterOptions: {\n levels: 4,\n segments: 16,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 3,\n height: 10,\n radius: 10\n }\n },\n 'Latter': {\n clusterAxisPosition: {\n x: -4.595486847683787,\n y: 0.2847801288589835,\n z: 3.7462094333022833\n },\n clusterAxisRotation: {\n _x: 0.8990244925501427,\n _y: -0.5514296000219416,\n _z: -1.322576143496501\n },\n cameraPosition: {\n x: -6.443634778338715,\n y: -9.618009412738955,\n z: 2.7964773912157024\n },\n clusterOptions: {\n levels: 1,\n segments: 3,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 3,\n height: 10,\n radius: 10\n }\n },\n 'Step-1': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 6.651247451081872,\n z: 4.412601953372359\n },\n clusterAxisRotation: {\n _x: 1.0923053542624157,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: 0.7738836049164036,\n y: -3.3547227086556353,\n z: 0.29789191939213083\n },\n clusterOptions: {\n levels: 7,\n segments: 12,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 1,\n height: 10,\n radius: 10\n }\n },\n 'Step-2': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 1.651247451081872,\n z: 1.4126019533723593\n },\n clusterAxisRotation: {\n _x: 1.0923053542624157,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: 1.0099593629449577,\n y: -12.702418022763476,\n z: 8.45969915473037\n },\n clusterOptions: {\n levels: 7,\n segments: 12,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 1,\n height: 10,\n radius: 10\n }\n },\n 'Step-3': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 6.651247451081872,\n z: 4.412601953372359\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: 11.52916901138159,\n y: -6.5168099316621,\n z: 7.651627379189595\n },\n clusterOptions: {\n levels: 7,\n segments: 12,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 1,\n height: 10,\n radius: 10\n }\n },\n\n 'Step-4': {\n clusterAxisPosition: {\n x: -5.324477492831647,\n y: 6.651247451081872,\n z: 4.412601953372359\n },\n clusterAxisRotation: {\n _x: 1.0923053542624157,\n _y: 0.934758015554807,\n _z: -1.4502125457792625\n },\n cameraPosition: {\n x: 7.92972933201254,\n y: 16.82606243486852,\n z: 2.5817912622696997\n },\n clusterOptions: {\n levels: 7,\n segments: 12,\n circles: 3,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 1,\n height: 10,\n radius: 10\n }\n },\n\n 'Semi-Kluster': {\n clusterAxisPosition: {\n x: 0,\n y: 0,\n z: 0\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 0,\n _z: 0\n },\n cameraPosition: {\n x: 2.643754331703072,\n y: -0.48247358349057407,\n z: 9.45864986354379\n },\n clusterOptions: {\n levels: 3,\n segments: 5,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Plasma': {\n clusterAxisPosition: {\n x: -7.214533654041588,\n y: -2.4396179197356105,\n z: -6.001599505543709\n },\n clusterAxisRotation: {\n _x: -0.004470624985189575,\n _y: 0.8727285247146759,\n _z: 0.2941807983596372\n },\n cameraPosition: {\n x: 3.4539531590076105,\n y: 6.374730350658294,\n z: 1.723565274004424\n },\n clusterOptions: {\n levels: 7,\n segments: 14,\n circles: 7,\n segmentsSpacing: 1,\n levelsSpacing: 1,\n ringSpacing: 0.96,\n height: 10,\n radius: 10\n }\n },\n 'Deep Go': {\n clusterAxisPosition: {\n x: 3.000586056150496,\n y: 8.68623988237232,\n z: 2.3817217955365777\n },\n clusterAxisRotation: {\n _x: 0.2931119333571194,\n _y: -0.6366476787941227,\n _z: -1.2389387872077564\n },\n cameraPosition: {\n x: 2.4811509435530748,\n y: 12.725914855953306,\n z: 6.682752438355237\n }\n /* , \n clusterOptions: {\n levels: 7,\n segments: 16,\n circles: 3,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.98,\n height: 10,\n radius: 10,\n extrudePathBiasX: 0,\n extrudePathBiasY: 0\n }*/\n },\n 'Rumb': {\n clusterAxisPosition: {\n x: 2.675469731912017,\n y: -1.3926358567550778,\n z: -0.1531926728785038\n },\n clusterAxisRotation: {\n _x: -0.33895709638646354,\n _y: 1.1449295472769976,\n _z: 0.7135726666172066\n },\n cameraPosition: {\n x: -8.049487664329009,\n y: -3.0409176517612693,\n z: -4.774609108369259\n },\n clusterOptions: {\n levels: 4,\n segments: 4,\n circles: 4,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.98,\n height: 20,\n radius: 10,\n extrudePathBiasX: 0,\n extrudePathBiasY: 0\n }\n },\n 'Sun Side': {\n clusterAxisPosition: {\n x: -7.214533654041588,\n y: -2.4396179197356105,\n z: -6.001599505543709\n },\n clusterAxisRotation: {\n _x: -0.004470624985189575,\n _y: 0.8727285247146759,\n _z: 0.2941807983596372\n },\n cameraPosition: {\n x: -5.409922856725515,\n y: -17.82969511590605,\n z: 6.546602568189618\n },\n clusterOptions: {\n levels: 7,\n segments: 14,\n circles: 3,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.98,\n height: 10,\n radius: 10,\n extrudePathBiasX: 1,\n extrudePathBiasY: 1\n }\n },\n\n // \n // \n // \n\n 'Scene 2 - Look 1': {\n clusterAxisPosition: {\n x: -7.214533654041588,\n y: -2.4396179197356105,\n z: -6.001599505543709\n },\n clusterAxisRotation: {\n _x: -0.004470624985189575,\n _y: 0.8727285247146759,\n _z: 0.2941807983596372\n },\n cameraPosition: {\n x: 3.4539531590076105,\n y: 6.374730350658294,\n z: 1.723565274004424\n },\n clusterOptions: {\n levels: 7,\n segments: 16,\n circles: 3,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.98,\n height: 30,\n radius: 30,\n extrudePathBiasX: 1.98,\n extrudePathBiasY: 1.98\n }\n },\n 'Scene 2 - Look 2': {\n clusterAxisPosition: {\n x: -2.214533654041588,\n y: -7.4396179197356105,\n z: -1.001599505543709\n },\n clusterAxisRotation: {\n _x: -0.004470624985189575,\n _y: 0.8727285247146759,\n _z: 0.2941807983596372\n },\n cameraPosition: {\n x: 3.4539531590076105,\n y: 6.374730350658294,\n z: 1.723565274004424\n },\n clusterOptions: {\n levels: 7,\n segments: 16,\n circles: 3,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.98,\n height: 30,\n radius: 30,\n extrudePathBiasX: 5,\n extrudePathBiasY: 5\n }\n },\n 'Scene 3 - Look 1': {\n clusterAxisPosition: {\n x: 10,\n y: 10,\n z: 10\n },\n clusterAxisRotation: {\n _x: 0,\n _y: 1.57,\n _z: 0\n },\n cameraPosition: {\n x: 2.911960344837725,\n y: -12.003705378205993,\n z: -2.5481203970385082\n },\n clusterOptions: {\n levels: 1,\n segments: 14,\n circles: 3,\n segmentsSpacing: 0.98,\n levelsSpacing: 1.03,\n ringSpacing: 0.2,\n height: 10,\n radius: 10,\n extrudePathBiasX: 2.77,\n extrudePathBiasY: 2.77\n }\n }\n\n };\n}",
"onMoleWhacked() {\n this.setState({\n points: this.state.points + 1\n })\n }",
"animate () {\n if (this.multiStep) this.animateSteps()\n this.animateDraws()\n }",
"frontFlip() {\n\t\tsuper.frontFlip(KEN_SPRITE_POSITION.frontFlip, KEN_IDLE_ANIMATION_TIME - 3, false, 2, MOVE_SPEED + 3);\n\t}",
"prepareNextState() {\n this.setGameBoard();\n this.gameOrchestrator.changeState(new ChoosingPieceState(this.gameOrchestrator));\n }",
"apply(state) {\n let newCanvas = state.canvas.clone().drawStep(this)\n return new State(state.target, newCanvas, this.distance)\n }",
"restart() {\n this.snake = new Snake();\n this.arcadeStepIncrease = 0.001;\n this.nExplorationWalls = 0;\n this.play();\n }",
"function fastForward (circuit, n, state) {\n for (let i = 0; i < n; i++) {\n state = nextState(circuit, state)\n }\n return state\n}",
"function resetAnimation(){\n animationSteps = [];\n step = 0;\n resetFlowCounter();\n resetTraceback();\n animationSteps.push({\n network: TOP,\n action: \"reveal\",\n pStep: 0\n });\n}",
"forwardHeavyPunch() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.forwardHeavyPunch, KEN_IDLE_ANIMATION_TIME, false);\n\t\tthis.triggerAttack(DAMAGE, NORMAL_HIT);\n\t}",
"forwardMediumPunch() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.forwardMediumPuch, KEN_IDLE_ANIMATION_TIME, false);\n\t\tthis.triggerAttack(DAMAGE, NORMAL_HIT);\n\t}",
"once () { this.step(); this.draw() }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a map of IDs to their respective balances, finds the reconciliation transactions so that the balances come down to zero. | function solveBalances(balances) {
var remains = balances.entrySeq()
.filter(v => v[1] > 0 || v[1] < 0)
.groupBy(v => v[1] > 0)
var positives = remains.get(true).sort((a, b) => a[1] - b[1]).toArray()
var negatives = remains.get(false).sort((a, b) => b[1] - a[1]).toArray()
var transactions = []
while (positives.length > 0) {
invariant(negatives.length > 0, 'balances do no sum up to zero')
var ps = positives[0]
var ng = negatives[0]
if (ps[1] >= -ng[1]) {
transactions.push({ from: ng[0], to: ps[0], value: -ng[1] })
negatives.shift()
ps[1] += ng[1]
if (ps[1] <= 0.01) {
positives.shift()
}
} else {
transactions.push({ from: ng[0], to: ps[0], value: ps[1] })
positives.shift()
ng[1] += ps[1]
if (ng[1] >= -0.01) {
negatives.shift()
}
}
}
invariant(negatives.length === 0, 'balances do no sum up to zero')
return new Immutable.Set(transactions)
} | [
"function withdraw(clients, balances, client, amount) {\n let name = client;\n\n for (let i = 0; i < clients.length; i++) {\n if (clients[i] == name) {\n if (balances[i] > amount) {\n\n return balances[i] - amount , balances[i] -= amount;\n \n } else {\n return -1;\n }\n }\n }\n}",
"static subtract(map_a, map_b){\n let subtracted = MapSet.deep_copy(map_a)\n for( let key of map_b.keys()){\n if(map_a.has(key)){\n let value = map_a.get(key) - map_b.get(key)\n if(value <= 0)\n subtracted.delete(key)\n else\n subtracted.set(key, value)\n }\n }\n return subtracted\n }",
"async refreshWallets() {\n const gapLimit = 1; //after 20 empty addresse we drop out\n\n //Deposit\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/0/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n //Change\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/1/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n }",
"function bitAddArr2transRefArr(baa, amount, tha, onlyFromAddrs){\r\n var save, res, tot, i, t, ta\r\n save = []\r\n res = []\r\n tot = 0.0\r\n// first sort the unspent transactions with the oldest first\r\n// but skip unconfirmed transactions; where block=0\r\n for(i in Unspent){\r\n t = Unspent[i]\r\n// ta = t.address\r\n if (t.block > 0){\r\n save.push(t)\r\n }\r\n }\r\n save.sort(compareBlockDesc)\r\n // try to pick from the given bitcoin addresses\r\n for (i in save){\r\n t = save[i]\r\n ta = t.address\r\n if (baa.indexOf(ta)>=0){\r\n res.push(t)\r\n tot += parseFloat(t.value)\r\n if (tot >= amount){ return [res, tot] }\r\n }\r\n }\r\n if (onlyFromAddrs) return [res, tot]\r\n // now pick from the other addresses, since the given address did not have enough\r\n for (i in save){\r\n t = save[i]\r\n ta = t.address\r\n if (tha.indexOf(ta) >= 0){ continue; } // skip it if the address is in the don't use list\r\n if (baa.indexOf(ta)<0){\r\n res.push(t)\r\n tot += parseFloat(t.value)\r\n if (tot >= amount){ break }\r\n }\r\n }\r\n if (tot < amount){ return 0 }\r\n // now remove any excess that we picked up\r\n // for example we needed to send 10, we picked up 1, 2, then 12, so we don't need\r\n // the 1 and 2 since 12 has enough. To remove them reverse the order and go through\r\n // until we have enough and any left after than can be removed.\r\n res = res.reverse()\r\n tot = 0.0\r\n enough = 0\r\n i = 0\r\n for (i=0; i<res.length; i++){\r\n t = res[i]\r\n tot += parseFloat(t.value)\r\n if (tot >= amount){\r\n i += 1\r\n if (i<res.length){\r\n res.splice(i)\r\n break\r\n }\r\n }\r\n }\r\n return [res, tot]\r\n}",
"getTransaction(id) {\n\n let match\n for (let block of this.chain.values()) {\n for (let transaction of block.transactions) {\n if (transaction['id'] === id)\n match = { transaction, found: true }\n break\n }\n }\n // test logic.\n return match ? match['transaction'] : `Sorry transaction with ID ${id} not found.`\n }",
"updateReconciledTotals() {\n\t\tconst decimalPlaces = 2;\n\n\t\t// Target is the closing balance, minus the opening balance\n\t\tthis.reconcileTarget = Number((this.closingBalance - this.openingBalance).toFixed(decimalPlaces));\n\n\t\t// Cleared total is the sum of all transaction amounts that are cleared\n\t\tthis.clearedTotal = this.transactions.reduce((clearedAmount, transaction) => {\n\t\t\tlet clearedTotal = clearedAmount;\n\n\t\t\tif (\"Cleared\" === transaction.status) {\n\t\t\t\tclearedTotal += transaction.amount * (\"inflow\" === transaction.direction ? 1 : -1);\n\t\t\t}\n\n\t\t\treturn Number(clearedTotal.toFixed(decimalPlaces));\n\t\t}, 0);\n\n\t\t// Uncleared total is the target less the cleared total\n\t\tthis.unclearedTotal = Number((this.reconcileTarget - this.clearedTotal).toFixed(decimalPlaces));\n\t}",
"function loadBalances() {\n\tfor (var k = 0; k < form.length; k++) {\n\t\tif (form[k][\"gr\"]){\n\t\t\tform[k][\"amount\"] = calculateGr1Balance(form[k][\"gr\"], form[k][\"vatClass\"], param[\"grColumn\"], param[\"startDate\"], param[\"endDate\"]);\n\t\t}\n\t}\n}",
"updateRunningBalances() {\n\t\t// Do nothing for investment accounts\n\t\tif (\"investment\" === this.context.account_type) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.transactions.reduce((openingBalance, transaction) => {\n\t\t\ttransaction.balance = openingBalance + (transaction.amount * (\"inflow\" === transaction.direction ? 1 : -1));\n\n\t\t\treturn transaction.balance;\n\t\t}, this.openingBalance);\n\t}",
"function refundBets(IDArray) {\n\tif (typeof IDArray !== \"object\") {\n\t\tconsole.log(typeof IDArray);\n\t\tIDArray = [IDArray];\n\t}\n\treturn new Promise(resolve => {\n\t\tlet eachID = [];\n\t\tIDArray.forEach(id => {\n\t\t\teachID.push(\n\t\t\t\tnew Promise(resolve => {\n\t\t\t\t\tRace.findOne({ raceID: id }, (err, race) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tthrow Error(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet eachRace = [];\n\t\t\t\t\t\trace.entrants.forEach(entrant => {\n\t\t\t\t\t\t\teachRace.push(\n\t\t\t\t\t\t\t\tnew Promise(resolve => {\n\t\t\t\t\t\t\t\t\tlet eachBet = [];\n\t\t\t\t\t\t\t\t\tentrant.bets.forEach(bet => {\n\t\t\t\t\t\t\t\t\t\teachBet.push(\n\t\t\t\t\t\t\t\t\t\t\tnew Promise((resolve, reject) => {\n\t\t\t\t\t\t\t\t\t\t\t\tUser.findOne(\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\t\ttwitchUsername:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.twitchUsername,\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\t(err, doc) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terr.message =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Could not find user in bet payout\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow Error(err);\n\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\tdoc.betHistory.forEach(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.raceID ===\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trace.raceID &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.entrant ===\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tentrant.name\n\t\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\t\t\tuserBet.result = `race cancelled`;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.points +=\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.amountBet;\n\t\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\t}\n\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\tdoc.markModified(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"betHistory\"\n\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\tdoc.save(err => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terr\n\t\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\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the edited bet as an array for map conversion\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.isPaid = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve([\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.twitchUsername,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet,\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});\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);\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\t\t\t\tPromise.all(eachBet).then(newBets => {\n\t\t\t\t\t\t\t\t\t\t\treturn newBets;\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\tPromise.all(eachRace).then(data => {\n\t\t\t\t\t\t\t\treturn data;\n\t\t\t\t\t\t\t})\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});\n\t\tresolve(\n\t\t\tPromise.all(eachID).then(data => {\n\t\t\t\treturn data;\n\t\t\t})\n\t\t);\n\t});\n}",
"function diffValues(mappedValues, nsInternalId) {\n var output = {};\n\n if (util.isObject(mappedValues) && Object.keys(mappedValues).length > 0) {\n var lookups = search.lookupFields({\n type: 'transaction',\n id: nsInternalId,\n columns: Object.keys(mappedValues)\n });\n\n for (var k in mappedValues) {\n var newVal = mappedValues[k];\n var curVal = lookups[k];\n\n if (util.isArray(curVal)) {\n if (curVal.length == 1) {\n curVal = curVal[0].value;\n } else {\n curVal = null;\n }\n }\n\n if (util.isBoolean(curVal)) {\n newVal = (newVal ? true : false);\n }\n\n if (util.isDate(newVal)) {\n curVal = new Date(curVal);\n }\n\n var isEqual = (curVal == newVal);\n if (util.isDate(curVal) && util.isDate(newVal)) {\n isEqual = (curVal.getTime() === newVal.getTime());\n }\n\n log.debug({\n title: 'diffValues',\n details: {\n k: k,\n curVal: curVal,\n newVal: newVal,\n isEqual: isEqual\n }\n });\n\n if (!isEqual) {\n output[k] = newVal;\n }\n }\n }\n\n\n return output;\n }",
"function mapTx(oldTx) {\n let objectTx = _mapTx(oldTx)\n let txID = objectTx.headerID, txHeader = objectTx.hdr, entries= objectTx.entryMap\n let tx = {\n txHeader: txHeader,\n id: txID,\n entries: entries,\n inputIDs: new Array(oldTx.inputs?oldTx.inputs.length:0),\n gasInputIDs:[]\n }\n\n let spentOutputIDs = new Object()\n let mainchainOutputIDs = new Object()\n for(let id in entries){\n const e = entries[id]\n let ord\n\n if (e instanceof bcSpend) {\n ord = e.ordinal\n spentOutputIDs[e.spentOutputId] = true\n let assetId = e.witnessDestination.value.assetID\n assetId = Buffer.isBuffer(assetId)? assetId.toString(\"hex\"):assetId\n if (assetId == BTMAssetID) {\n tx.gasInputIDs.push(id)\n }\n }\n else if (e instanceof bcVetoInput) {\n ord = e.ordinal\n spentOutputIDs[e.spentOutputId] = true\n let assetId = e.witnessDestination.value.assetID\n assetId = Buffer.isBuffer(assetId)? assetId.toString(\"hex\"):assetId\n if (assetId == BTMAssetID) {\n tx.gasInputIDs.push(id)\n }\n }\n else if (e instanceof bcCrossChainInput) {\n ord = e.ordinal\n mainchainOutputIDs[e.mainchainOutputId] = true\n let assetId = e.witnessDestination.value.assetID\n assetId = Buffer.isBuffer(assetId)? assetId.toString(\"hex\"):assetId\n if (assetId == BTMAssetID) {\n tx.gasInputIDs.push(id)\n }\n }\n else if (e instanceof bcCoinbase) {\n ord = 0\n tx.gasInputIDs.push(id)\n } else {\n continue\n }\n\n if (ord < (oldTx.inputs.length)) {\n tx.inputIDs[ord] = id\n }\n }\n\n tx.spentOutputIDs =[]\n tx.mainchainOutputIDs =[]\n\n for(let id in spentOutputIDs) {\n tx.spentOutputIDs.push(id)\n }\n\n for(let id in mainchainOutputIDs) {\n tx.mainchainOutputIDs.push(id)\n }\n\n return new bcTx(tx)\n}",
"function transactionsMaturingHeights(txs, chainParams) {\n const res = {};\n const addToRes = (height, found) => {\n const accounts = res[height] || [];\n found.forEach((a) =>\n accounts.indexOf(a) === -1 ? accounts.push(a) : null\n );\n res[height] = accounts;\n };\n\n txs.forEach((tx) => {\n const accountsToUpdate = [];\n switch (tx.type) {\n case TransactionDetails.TransactionType.TICKET_PURCHASE:\n checkAccountsToUpdate([tx], accountsToUpdate);\n addToRes(tx.height + chainParams.TicketExpiry, accountsToUpdate);\n addToRes(tx.height + chainParams.SStxChangeMaturity, accountsToUpdate);\n addToRes(tx.height + chainParams.TicketMaturity, accountsToUpdate); // FIXME: remove as it doesn't change balances\n break;\n\n case TransactionDetails.TransactionType.VOTE:\n case TransactionDetails.TransactionType.REVOCATION:\n checkAccountsToUpdate([tx], accountsToUpdate);\n addToRes(tx.height + chainParams.CoinbaseMaturity, accountsToUpdate);\n break;\n }\n });\n\n return res;\n}",
"async getBalances(account) {\n const { options } = this.props;\n const weth_promise = options.contracts.WETH.balanceOf(account);\n const dai_promise = options.contracts.DAI.balanceOf(account);\n const sai_promise = options.contracts.SAI.balanceOf(account);\n const mkr_promise = options.contracts.MKR.balanceOf(account);\n return Promise.all([weth_promise, dai_promise, sai_promise, mkr_promise]);\n }",
"function createTxMap(txs){\n\tvar map = new Map();\n\n\ttxs.forEach(function(tx){\n\t\t\tif (!map.has(tx.from)){\n\t\t\t\tmap.set(tx.from, 1);\n\t\t\t} else {\n\t\t\t\tmap.set(tx.from, map.get(tx.from)+1);\n\t\t\t}\n\t});\n\treturn map;\n}",
"function mergeWallets(wallet1, wallet2) {\n let mergedWallet = copyWallet(wallet1)\n for (let bill in wallet2) {\n if (wallet2[bill] != 0) {\n mergedWallet[bill] = wallet2[bill]\n }\n }\n return mergedWallet\n }",
"function testBalance() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"balance\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const numbers of parameters[0].values) {\n const functionCall = `balance(${format(numbers)})`;\n const expected = staff.balance(numbers);\n const actual = student.balance(numbers);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`balance -- passed ${pass} out of ${tc} test cases.`);\n}",
"function checkDepositAddressSpend(){\n\t\t\t\t\t\t\t\tif (objUnit.authors.length !== 2)\n\t\t\t\t\t\t\t\t\treturn cb();\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// console.log(\"===================Start to check spend deposit balance\");\n\t\t\t\t\t\t\t\tvar supernodes = objUnit.authors.filter( function (author) { return author.address != owner_address });\n\t\t\t\t\t\t\t\tvar coAuthorAddr = supernodes[0].address ;\n\t\t\t\t\t\t\t\t// Check owner address is kind of deposit address \n\t\t\t\t\t\t\t\t// console.log(\"===================coAuthorAddr: \"+ coAuthorAddr +\" | owner_address: \" +owner_address);\n\t\t\t\t\t\t\t\tdeposit.getSupernodeByDepositAddress(conn, owner_address, function(err, supernodeinfo){\n\t\t\t\t\t\t\t\t\tif(err){\n\t\t\t\t\t\t\t\t\t\t// no correspont supernode which indicates owner_address is not deposit address\n\t\t\t\t\t\t\t\t\t\treturn cb();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// console.log(\"===================Deposit address: \" + owner_address + \" supernode address: \"+ supernodeinfo[0].address);\n\t\t\t\t\t\t\t\t\t// owner_address is deposit address\n\t\t\t\t\t\t\t\t\t// deposit.hasInvalidUnitsFromHistory(conn, supernodeinfo[0].address, function (err, isInvalid){\n\t\t\t\t\t\t\t\t\t// \tif(err) //normal tranaction\n\t\t\t\t\t\t\t\t\t// \t\treturn cb(err);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tround.getLastCoinbaseUnitRoundIndex(conn, supernodeinfo[0].address, function(err, lastCoinBaseRound){\n\t\t\t\t\t\t\t\t\t\t\tif(err)\n\t\t\t\t\t\t\t\t\t\t\t\treturn cb(err);\n\t\t\t\t\t\t\t\t\t\t\t// console.log(\"===================got last coin base round is : \"+ lastCoinBaseRound);\n\t\t\t\t\t\t\t\t\t\t\tround.getCurrentRoundIndex(conn, function(latestRoundIndex){\n\t\t\t\t\t\t\t\t\t\t\t\tif (constants.INVALID_ADDRESS === coAuthorAddr){ // foundation spend deposit condition\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn cb(\"asset of invalid address is burned\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t// if(!isInvalid) // supernode is good condition\n\t\t\t\t\t\t\t\t\t\t\t\t\t// \treturn cb(\"supernode [\" + supernodeinfo[0].address + \"] don not submit bad joints, Foundation can not spend its deposit balance \");\n\t\t\t\t\t\t\t\t\t\t\t\t\t// if(lastCoinBaseRound === 0 ) // never participate in minning and no coinbase record\n\t\t\t\t\t\t\t\t\t\t\t\t\t// \treturn cb(\"supernode [\" + supernodeinfo[0].address + \"] don not submit coinbase unit, Foundation can not spend its deposit balance \");\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\t// // console.log(\"===================got current round is : \"+ latestRoundIndex);\n\t\t\t\t\t\t\t\t\t\t\t\t\t// // check if delay n round to spend \n\t\t\t\t\t\t\t\t\t\t\t\t\t// if((latestRoundIndex - lastCoinBaseRound) < constants.COUNT_ROUNDS_FOR_FOUNDATION_SPEND_DEPOSIT){\n\t\t\t\t\t\t\t\t\t\t\t\t\t// \treturn cb(\"Foundation safe address can not spend deposit contract balance before \")\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\t// return cb(); // OK condition\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\telse if(coAuthorAddr === supernodeinfo[0].safe_address){ // condition for supernode spend the deposit balance\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(lastCoinBaseRound === 0 ) // not mine at all, take it anytime\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn cb();\n\t\t\t\t\t\t\t\t\t\t\t\t\t// if(isInvalid)\n\t\t\t\t\t\t\t\t\t\t\t\t\t// \treturn cb(\"supernode [\" + supernodeinfo[0].address + \"] submit bad joints, can not spend its deposit balance \");\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\t// console.log(\"===================got current round is : \"+ latestRoundIndex);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif((latestRoundIndex - lastCoinBaseRound) < constants.COUNT_ROUNDS_FOR_SUPERNODE_SPEND_DEPOSIT){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn cb(\"supernode can not spend deposit contract balance before round \" + (lastCoinBaseRound + constants.COUNT_ROUNDS_FOR_SUPERNODE_SPEND_DEPOSIT));\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t// console.log(\"===================OK to spend deposit balance\");\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn cb(); // OK condition\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\treturn cb(\"unknown user:\" + coAuthorAddr +\" try to spend deposit :\" + owner_address );\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t// });\t\t\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}",
"function transfer(accountFrom, accountTo, transferAmount) {\n console.log(\"Transfering from: \" + accountFrom + \", Transfering to: \" + accountTo + \", Amount: \" + transferAmount.toString());\n\n arrOfUsers.forEach(function(usr){\n if(usr.accountNo == accountFrom){\n //checking available balance...\n if(usr.accountBal < transferAmount){\n console.log(\"Not enough money to transfer!\");\n } else {\n console.log(\"Transfering amount...\");\n //taking money from source\n usr.accountBal -= transferAmount;\n arrOfUsers.forEach(function(usr2){\n if(usr2.accountNo == accountTo){\n //adding money to target\n usr2.accountBal += transferAmount;\n console.log(\"Successfull tranfer to: \" + usr2.accountNo);\n console.log(\"New balance (\" + usr2.accountNo + \"):\" + usr2.accountBal);\n //logging transacion\n arrOfTransacions.push({\n date: getDateTime(),\n sourceAccount: accountFrom,\n targetAccount: accountTo,\n tranType: \"T\",\n amount: transferAmount,\n currentBalance: usr.accountBal\n })\n }\n });\n }\n }\n });\n}",
"function sumBalances(blockNumber, addresses, callback) {\n\tvar total = new BigNumber(0);\n\tasync.eachLimit(addresses, 10, (addr, asyncDone) => {\n\t\tweb3.eth.getBalance(addr, blockNumber, (err, balance) => {\n\t\t\tif (!err)\n\t\t\t\ttotal = total.add(balance);\n\t\t\tasyncDone(err);\n\t\t});\n\t}, (err) => {\n\t\tcallback(err, total);\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update dog to server | function updateDogOnServer(dog) {
fetch(`${dogsURL}/${dog.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(dog)
}).then(() => getDogs())
} | [
"function apiUpdate(req, res) {\n // console.log('PUT /api/breed/:name');\n // console.log(req.params.name);\n // console.log(req.body);\n\n // update the specified breed\n db.Breed.find({'name': req.params.name}, function(err, sheep) {\n //console.log(sheep);\n if (err) {\n res.status(404).send('ERROR: breed not found; you probably need to add this breed');\n } else {\n if (req.body.infoSources) {\n // get the list of new sources\n let infoList = req.body.infoSources.split(', ');\n // we're replacing the current list of sources with the new list\n req.body.infoSources = [];\n for (let i = 0; i < infoList.length; i++) {\n req.body.infoSources.push(infoList[i]);\n }\n //console.log('srcs: ' + req.body.infoSources);\n }\n\n //console.log(sheep[0]._id);\n db.Breed.update({ '_id': sheep[0]._id }, { $set: req.body }, function(err, updatedSheep) {\n if (err) {\n res.status(503).send('ERROR: could not update sheep info');\n } else {\n res.json(updatedSheep);\n }\n });\n }\n\n });\n}",
"function modifyDrinks(args) {\r\n // Update the user with the modified drink\r\n db.get(\"drinks\").find({ drink: args[2] }).assign({ gif: args[3] }).write();\r\n}",
"function update(req, res) {\n const dishId = req.params.dishId\n // create variable that finds the dish with a matching id\n const matchingDish = dishes.find((dish) => dish.id === dishId)\n const { data: { name, description, price, image_url } = {} } = req.body\n // use that variable to define the key-value pairs of the new dish\n matchingDish.description = description\n matchingDish.name = name\n matchingDish.price = price\n matchingDish.image_url = image_url\n // return the new dish's data\n res.json({ data: matchingDish })\n }",
"function update()\n{\n request.open(\"get\", \"update\", true);\n request.send();\n}",
"function update(req, res) {\n const dish = res.locals.dish;\n const { data: { name, description, price, image_url } = {} } = req.body;\n\n if (dish.name !== name) {\n dish.name = name\n }\n if (dish.description !== description) {\n dish.description = description\n }\n if (dish.price !== price) {\n dish.price = price\n }\n if (dish.image_url !== image_url) {\n dish.image_url = image_url\n }\n \n res.json( {data: dish})\n \n}",
"function updateCrocodile () {\n emit('updateAnimal', {\n type: 'crocodile',\n value: document.getElementById('crocodile').value\n })\n }",
"async price_update() {}",
"async function update(req, res) {\n await Habit.findByIdAndUpdate(req.params.id, req.body, {\n new: true\n }, function (err, habit) {\n res.json(habit);\n\n })\n}",
"function updateLike(quote){\n fetch(SERVER_DATA + `/${quote.id}`, {\n method: 'PATCH',\n headers: {'Content-Type' : 'application/json'},\n body: JSON.stringify(quote)\n })\n .then(response => response.json())\n}",
"update_drone_stats(){\n this.update_location(new_location);\n this.update_sensor();\n this.update_battery(); // send drone info to remote maybe\n }",
"function update(box) {\n console.log(\"CLICKED\", box.id, box.checked);\n var request = new XMLHttpRequest();\n request.open('PUT', 'http://localhost:4000/checkboxes/'+box.id, true);\n request.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n request.send(\"value=\"+box.checked)\n }",
"function updateDevice(device, payload){\n device.user_id = payload.user_id;\n device.uuid = payload.uuid;\n device.os_id = payload.os_id;\n device.createdAt = payload.createdAt;\n device.modifiedAt = Date.now();\n device.model = payload.model;\n}",
"update () {\n Spark.post('/settings/shopify', this.form)\n .then(() => {\n\n // Bus.$emit('updateShopify');\n this.connectShopify()\n\n })\n }",
"function updateRobotStatus (updatedData) {\n updatedData['Time'] = new Date();\n updatedData['Arduino Attached'] = serverStatus.hasArduino;\n\n socket.broadcast.emit('robot status', { 'data': updatedData });\n}",
"function updateDog(id) {\n var x = document.forms[\"editdogform\"][\"name\"].value;\n var y = document.forms[\"editdogform\"][\"birthdate\"].value;\n var z = document.forms[\"editdogform\"][\"breed\"].value;\n\n if (x == \"\") {\n alert(\"Name must be filled out\");\n return false;\n }\n else if (y == \"\") {\n alert(\"Birthdate must be entered\");\n return false;\n }\n else if (z == \"\") {\n alert(\"Breed must be filled out\");\n return false;\n }\n else {\n $.ajax({\n url: '/dogs/' + id,\n type: 'PUT',\n data: $('#editdogform').serialize(),\n success: function (result) {\n window.location.replace(\"./\");\n }\n })\n }\n}",
"function updateEgg() {\r\n id(\"egg-view\").classList.add(\"hidden\");\r\n id(\"face-view\").classList.remove(\"hidden\");\r\n let finalType = id(\"final\");\r\n if (this.id === \"plain\") {\r\n finalType.src = \"img/plain_egg.png\";\r\n } else if (this.id === \"sunny\") {\r\n finalType.src = \"img/sunny_egg.png\";\r\n } else {\r\n finalType.src = \"img/cracked_egg.png\";\r\n }\r\n id(\"cute\").addEventListener(\"click\", finalEgg);\r\n id(\"sad\").addEventListener(\"click\", finalEgg);\r\n id(\"heart\").addEventListener(\"click\", finalEgg);\r\n }",
"function updatePicture(req, res, next) {\n db.none('update pics set name=$1, description=$2, img=$3 where id=$4', [req.body.name, req.body.description, req.body.img, parseInt(req.body.id)])\n .then(function () {\n res.status(200)\n .json({\n status: 'success',\n message: 'updated picture'\n });\n })\n .catch(function (err) {\n return next(err);\n });\n}",
"function updatePetInfoInHtml() {\n $('.name').text(pet_info['name']);\n $('.weight').text(pet_info['weight']);\n $('.happiness').text(pet_info['happiness']);\n }",
"update(name){\r\n\t\tvar playerIndex = \"player\"+playerCount;\r\n\t\tdatabase.ref(playerIndex).set({\r\n\t\t\tname : name\r\n\t\t})\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moveAt(event.pageX, shiftX, setRangeLeft, rangeRef); | function onMouseMove(event) {
moveAt(event.pageX, shiftX, setRangeLeft, rangeRef);
} | [
"function getXmovement(fromIndex,toIndex){if(fromIndex==toIndex){return'none';}if(fromIndex>toIndex){return'left';}return'right';}",
"moveAround() {\r\n\r\n\r\n }",
"function movement() {\n trayX = constrain(trayX, 70, width - 70); \n if (keyIsDown(LEFT_ARROW)) {\n trayX -= 3;\n } else if (keyIsDown(RIGHT_ARROW)) {\n trayX += 3;\n }\n}",
"moveSlotSlider(index, newWidth) {\n var left_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[2]).position.x;\n var rigth_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[3]).position.x;\n this.selected_slot = this.group.getObjectById(this.closet_slots_faces_ids[index]);\n if (index == 0) {\n let newPosition = left_closet_face_x_value + newWidth;\n this.selected_slot.position.x = newPosition;\n } else {\n var positionLefthSlot = this.group.getObjectById(this.closet_slots_faces_ids[index - 1]).position.x;\n if (positionLefthSlot + newWidth >= rigth_closet_face_x_value) {\n this.selected_slot.position.x = positionLefthSlot;\n } else {\n this.selected_slot.position.x = positionLefthSlot + newWidth;\n }\n }\n }",
"move() {\n //update position based on mouse\n this.x = mouseX;\n this.y = mouseY;\n //prevent the crosshairs from going off the edge of the screen (or past the vertical mask)\n this.x = constrain(this.x, 0, width);\n this.y = constrain(this.y, 0, cockpitVerticalMask);\n //increase shield health slowly, constraining it within max and min\n this.shieldHealth += .09 * this.maxShieldHealth / 100;\n this.shieldHealth = constrain(this.shieldHealth, 0, this.maxShieldHealth);\n\n }",
"function swimLeftFast(e) {\n var s = e.target;\n s.x -= 4;\n}",
"function moveLeft(){\n gMeme.currText.x -= 15;\n}",
"moveTo(x, y) {\n let coordinates = this.getXY();\n this.x = x + coordinates.x;\n this.y = y + coordinates.y;\n }",
"press(x,y) {\n this.pressing = true;\n this.moveLinear(x,y-100,x,y);\n }",
"handlePositionChangeEvent() {\n\n }",
"function on_mouse_move_editor(event)\n{\n\t// first get the mouse coordinates in pixels\n\tvar mouse_coordinates = get_relative_mouse_coordinates(event);\n\n\t// then convert them to tile units\n\tvar x = pixel_to_tile(mouse_coordinates.x);\n\tvar y = pixel_to_tile(mouse_coordinates.y);\n\n\t// select it\n\teditor_select(x, y, editor_context);\n}",
"function horizontalLinePosition(p_event) {\n\tdocument.getElementById('horizontal-resize-line').style.left = p_event.pageX;\n}",
"function drag() {\n var newStageX = self.mouseX - startX + oldStageX;\n var newStageY = self.mouseY - startY + oldStageY;\n\n if (newStageX != self.stageX || newStageY != self.stageY) {\n lastStageX2 = lastStageX;\n lastStageY2 = lastStageY;\n\n lastStageX = newStageX;\n lastStageY = newStageY;\n\n self.stageX = newStageX;\n self.stageY = newStageY;\n self.dispatch('drag');\n }\n }",
"function moveAt(pageX, pageY) {\n ball.style.left = pageX - ball.offsetWidth / 2 + 'px';\n ball.style.top = pageY - ball.offsetHeight / 2 + 'px';\n }",
"function move() {\n\t\tfor (var i = 0; i < oA.length; i++) {\n\t\t\tif(oA[i].offsetLeft == 0){\n\t\t\t\tif (i == oA.length-1) {\n\t\t\t\t\toA[0].style.left = 0 + 'px';\n\t\t\t\t}else{\n\t\t\t\t\toA[i+1].style.left = 1200 + 'px';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\toA[i].style.left =oA[i].offsetLeft-1200+'px';\n//\t\t\tclearInterval(stop);\n\t\t};\n//\t\tif (oA[0].offsetLeft == 0) {\n//\t\t\toA[1].style.left = 1200 + 'px';\n//\t\t}\n//\t\tif (oA[1].offsetLeft == 0) {\n//\t\t\toA[2].style.left = 1200 + 'px';\n//\t\t}\n//\t\tif (oA[2].offsetLeft == 0) {\n//\t\t\toA[0].style.left = 1200 + 'px';\n//\t\t}\n\t}",
"function moveRight(){\n gMeme.currText.x += 15;\n}",
"moveToStartingPosition() {\r\n this.currentLocation.x = this.startingPosition.x;\r\n this.currentLocation.y = this.startingPosition.y;\r\n }",
"function moveAt(pageX, pageY) {\n ball.style.left = pageX - ball.offsetWidth / 2 + 'px';\n ball.style.top = pageY - ball.offsetHeight / 2 + 'px';\n }",
"mover() {\n\n // Desloca o Pterossauro '1px' pra esquerda\n this.element.style.right = (parseFloat(this.element.style.right) + pixels_to_move) + \"px\";\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect if the HTML or the BODY tags has a [mdthemesdisabled] attribute If yes, then immediately disable all theme stylesheet generation and DOM injection | function detectDisabledThemes($mdThemingProvider) {
var isDisabled = !!document.querySelector('[md-themes-disabled]');
$mdThemingProvider.disableTheming(isDisabled);
} | [
"async addTheme(){\n //If there is no page styling already\n if(!document.querySelector('.eggy-theme') && this.options.styles){\n //Create the style tag\n let styles = document.createElement('style');\n //Add a class\n styles.classList.add('eggy-theme');\n //Populate it\n styles.innerHTML = '{{CSS_THEME}}';\n //Add to the head\n document.querySelector('head').appendChild(styles);\n }\n //Resolve\n return;\n }",
"function isLightMode(designSystem) {\n return !isDarkMode(designSystem);\n}",
"switchToWYSIWYG() {\n this.$containerEl.removeClass('te-md-mode');\n this.$containerEl.addClass('te-ww-mode');\n }",
"function applyTheme(themeName) {\n document.body.classList = '';\n document.body.classList.add(themeName);\n document.cookie = 'theme=' + themeName;\n }",
"function ssw_js_validate_theme() {\n \n var theme_button = document.getElementById('ssw-steps').select_theme;\n var theme_button_count = -1;\n\n for (var i=theme_button.length-1; i > -1; i--) {\n if (theme_button[i].checked) {theme_button_count = i; i = -1;}\n }\n if (theme_button_count > -1) {\n document.getElementById(\"ssw-themes-error\").style.display=\"none\"; \n return true;\n }\n else {\n document.getElementById(\"ssw-themes-error-label\").innerHTML=ssw_theme_error_msg;\n document.getElementById(\"ssw-themes-error\").style.display=\"block\"; \n return false;\n }\n}",
"get isDarkTheme() {\n if (this._isDarkTheme == null) {\n this._isDarkTheme = localStorage.getItem('theme') === 'dark' || false;\n }\n return this._isDarkTheme;\n }",
"function hideThemesDisableDial() {\r\n $('.available-themes-block').addClass('hide-first-av-content');\r\n}",
"_onThemeChanged() {\n this._changeStylesheet();\n if (!this._disableRedisplay)\n this._updateAppearancePreferences();\n }",
"function switchThemes(){\n var entirePage = document.getElementById( 'document-body' );\n if( entirePage.classList.contains( 'lightTheme' ) ){\n entirePage.classList.remove( 'lightTheme' );\n entirePage.classList.add( 'darkTheme' );\n document.cookie = \"theme=darkTheme;path=/\";\n }\n else if( entirePage.classList.contains( 'darkTheme' ) ){\n entirePage.classList.remove( 'darkTheme' );\n entirePage.classList.add( 'lightTheme' );\n document.cookie = \"theme=lightTheme;path=/\";\n }\n}",
"disable_style() {\n this.enabledStyles.pop();\n }",
"function determineDarkMode() {\n (userPreferences.darkMode) ? darkMode(true) : {};\n}",
"injectTheme(themeId){\n //helper function to clone a style\n function cloneStyle(style) {\n var s = document.createElement('style');\n s.id = style.id;\n s.textContent = style.textContent;\n return s;\n }\n\n var n = document.querySelector(themeId);\n this.shadowRoot.appendChild(cloneStyle(n));\n }",
"function _cleanPage() {\n document.body.style.fontFamily = '';\n document.getElementsByTagName('head')[0].innerHTML = '';\n}",
"function removeBodyClasses() {\n dom.removeClass(\n [document.documentElement, document.body],\n [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]\n )\n}",
"function unuseTheme(value) {\n _Array__WEBPACK_IMPORTED_MODULE_13__[\"remove\"](_Registry__WEBPACK_IMPORTED_MODULE_1__[\"registry\"].themes, value);\n }",
"function setTheme(themValueObj) {\n for (const key in themValueObj) {\n document.documentElement.style.setProperty(`--${key}`, themValueObj[key]);\n }\n}",
"function setupTheme() {\n var theme = interactive.theme;\n\n if (arrays[\"a\" /* default */].isArray(theme)) {\n // [\"a\", \"b\"] => \"lab-theme-a lab-theme-b\"\n theme = theme.map(function (el) {\n return 'lab-theme-' + el;\n }).join(' ');\n } else if (theme) {\n theme = 'lab-theme-' + theme;\n } else {\n theme = '';\n }\n\n $interactiveContainer.alterClass('lab-theme-*', theme);\n }",
"function dublincoreChangeState() {\n\tvar tbutton = document.getElementById(\"dublincore-toolbarbutton\");\n\tvar sbutton = document.getElementById(\"dublincore-statusbarbutton\");\n\tif (tbutton) tbutton.disabled = true;\n\tsbutton.disabled = true;\n\t\n\t// quick check of metas\n\tvar metas = window.content.document.getElementsByTagName(\"meta\");\n\tvar links = window.content.document.getElementsByTagName(\"link\");\n\n\tif ((dc_crawler(metas,'name','content',dcElements,'dc.')) ||\n\t\t(dc_crawler(metas,'name','content',dcElementTerms,'dcterms.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElements,'dc.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElementTerms,'dcterms.'))) {\n\n\t\tif (tbutton) tbutton.disabled = false;\n\t\tsbutton.disabled = false;\n\n\t}\n}",
"function disabledCssCheck() {\n // check color style of 'cssCheck' div tag (should be set to red)\n if(window.getComputedStyle(document.getElementById(\"cssCheck\"), null)[\"color\"] == \"rgb(255, 39, 39)\" || \n window.getComputedStyle(document.getElementById(\"cssCheck\"), null)[\"color\"] == \"rgb(255, 0, 0)\"){\n return true;\n }\n return false;\n}",
"function set_features_enabled(){\n var featuresmap = {\n color: '.form-group:has(input#colorinput)',\n period: '.form-group:has(input#period)',\n intensity: '.form-group:has(input#intensity)'\n };\n for (feature in featuresmap) {\n var selector = $(featuresmap[feature]);\n var enabled = false;\n if (data.pattern != null) {\n enabled = (patterns[data.pattern]['features'][feature]);\n }\n if (enabled) {\n //$(selector).removeAttr('disabled');\n if (!selector.is(':visible')){\n selector.show();\n }\n } else {\n //$(selector).attr('disabled', true);\n if (selector.is(':visible')){\n selector.hide();\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example: label(resource(r_1_XX_),satiation). >> r_1_xx has_label satiation or label(entity(e1),food). | function translateResourceLabel(terms){
var name = terms[0].terms[0].predicate;
var label = terms[1].predicate;
var readWriteValue = "private"
if(terms[2] !== undefined){
//if it has a read write value
readWriteValue = terms[2].predicate;
}
return {"l": [name], "relation":"has_label", "r":[label], "readWrite" : readWriteValue}
//return translateSimpleTriple("has_label",terms);
} | [
"_label(label) {\n return `${label}${label && this.required ? '*' : ''}`;\n }",
"function isObligatoryLabel(label){\t\r\n\treturn obligatoryDataElementsLabel.includes(label);\r\n}",
"label(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.label : null;\n }",
"function CLC_Content_FindLabelText(target){\r\n var logicalLineage = CLC_GetLogicalLineage(target);\r\n var labelText = \"\";\r\n for (var i=0; i < logicalLineage.length; i++){\r\n if (logicalLineage[i].tagName && (logicalLineage[i].tagName.toLowerCase() == \"label\")){\r\n labelText = labelText + \" \" + logicalLineage[i].textContent;\r\n }\r\n }\r\n return labelText;\r\n }",
"function TLabel(){}",
"createLabelForFeature(feature) {\n //Return if labels are not desired for this area type\n if (!this.hasLabels) {\n return;\n }\n //Add arc label to label layer\n this.labelLayer.addLabelForFeature(feature);\n }",
"renderLabel(elements, label, side) {\n if (!label) return false;\n\n const { labelAppearance } = this.props;\n\n if (this.labelShouldWrapElement(side)) {\n elements.addOn(side, label);\n const labelClass = classNames(labelAppearance, `${side} wrapped`);\n // wrap in a <label> to get click behavior\n elements.wrap(\"label\", labelClass);\n // wrap in a span to avoid SUI rendering problem\n elements.wrap(\"span\");\n }\n else {\n const labelClass = classNames(\"ui\", labelAppearance, \"label\");\n const labelElement = elements.createWrapped(\"label\", labelClass, label);\n elements.addOn(side, labelElement);\n }\n return true;\n }",
"function setNationalLabel(label, nationalData) {\n\n if (label.search(\"Percentage\") > -1) {\n\n return \"National \" + Math.round(nationalData * 100) + \"%\";\n }\n\n else {\n return \"National \" + nationalData;\n }\n}",
"function getLabel(id) {\n var label = jQuery(\"#\" + id + \"_label\");\n if (label) {\n return label.text();\n }\n else {\n return \"\";\n }\n}",
"_getFilterLabels(label, field)\r\n {\r\n var templateChoice = _.template($(this.options.templateFilterChoice).html());\r\n var templateInput = _.template($(this.options.templateFilterMultipleEnum).html());\r\n var labelCollection = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__GLOBAL_RESOURCELABEL_COLLECTION);\r\n var project = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__PROJECT_GET_ACTIVE);\r\n var project_resources = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__RESOURCES_CURRENT, {data: {project: project.id}});\r\n var labels = new Set();\r\n project_resources.each(function (resource) {\r\n resource.attributes.labels.forEach(function ({ url }) {\r\n labels.add(url);\r\n });\r\n });\r\n var filtered_collection = labelCollection.filter(function (resource) { return labels.has(resource.attributes.url); });\r\n var labelModels = filtered_collection.map((label) => {\r\n return {\r\n label: label.get('name'),\r\n value: label.get('uuid')\r\n };\r\n });\r\n var htmlChoice = templateChoice({label: label, field: field});\r\n var htmlInput = templateInput({label: label, field: field, values: labelModels});\r\n return {collectionItem: htmlChoice, input: htmlInput};\r\n }",
"function activeLabel(label) {\n d3.select(`.${label}`).classed(\"active\", true).classed(\"inactive\", false);\n}",
"defineLabel() {\r\n // TODO: remove, can only branch to outer blocks, no purpose in defining a label before the block. \r\n return this._controlFlowVerifier.defineLabel();\r\n }",
"function inactiveLabel(label) {\n d3.select(`.${label}`).classed(\"active\", false).classed(\"inactive\", true);\n}",
"function lite(Obj, lite)\n{\n\tconsole.log(\"TODO: fired LabelLite log\");\n\t//return all styles to normal on all the labels\n\tvar allLabels = \n\t\td3.selectAll(\"#\" + Obj.labels.id).selectAll(\".descLabel\");\n\t//TODO what I need is a better way to know which collection\n\t//of labels to turn off. Doing it by class seems lame.\n\tallLabels\n\t.style(\"color\",null)\n\t//setting a style to null removes the special\n\t//style property from the tag entirely.\n\t//TODO: make the lit and unlit classes\n\t.style(\"font-weight\",null)\n\t.style(\"background-color\",\"\");\n\tvar allBullets = \n\t\td3.selectAll(\"#\" + Obj.labels.id);\n\t//turn all the text back to white, and circles to black\n\tallBullets.selectAll(\"text\").style(\"fill\",\"white\");\n\tallBullets.selectAll(\"circle\").attr(\"class\",\"steps\")\n\t\t;\n\t\t\n\t//highlight the selected label(s)\n\t\n\tvar setLabels = d3.selectAll(\"#\" + Obj.labels.id + lite);\n\tif(setLabels) \n\t\t{\n\t\tsetLabels.selectAll(\"circle\")\n\t\t.attr(\"class\",\"stepsLit\");\n\t\t//highlight the one selected circle and any others\n\t\t//with the same lite index\n\t\tsetLabels.selectAll(\"text\").style(\"fill\",\"#1d95ae\");\n\t\tsetLabels.selectAll(\".descLabel\")\n\t\t//.transition().duration(100)\n\t\t// this renders badly from Chrome refresh bug\n\t\t//we'll have to figure out how to get transitions\n\t\t//back in - maybe just foreign objects?\n\t\t.style(\"color\", \"#1d95ae\")\n\t\t.style(\"font-weight\", \"600\")\n\t\t.style(\"background-color\", \"#e3effe\");\n\t\n\t\t} \n\telse {\n\tconsole.log(\"Invalid key. No label \" + liteKey);\n\t\t}\n}",
"function TKR_prepLabelAC() {\n var i = 0;\n while ($('label'+i)) {\n TKR_validateLabel($('label'+i));\n i++;\n }\n}",
"label(text, size = -1) {\n //TODO\n }",
"function hiLiteLabel(axis, clicked){\r\n d3.selectAll(\".aText\")\r\n .filter(\".\" + axis)\r\n .filter(\".active\")\r\n .classed(\"inactive\", true)\r\n \r\n clicked.classed(\"inactive\", false).classed(\"active\", true);\r\n}",
"function getLabel(item) {\n\tvar span = angular.element(item).find('span').eq(0);\n\treturn angular.element(span).text();\n }",
"visitLabel_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Engine(canvas): Constructor. Args: canvas: the element used to draw. | function Engine(canvas) {
var self = this;
/*
* PRIVATE MEMBER
*/
var ctx = null; // context of the canvas
var sprites = null; // all sprites
var clickables = null; // all clickable sprites
var mouse_objs = null;
/*
* PUBLIC MEMBER
*/
this.canvas = canvas; // the <canvas> element
/*
* PRIVILEGED PUBLIC METHODS
*/
/*
* init
* Initialize the engine.
* size: the size of the canvas
*/
this.init = function (size) {
this.canvas.width = size[0];
this.canvas.height = size[1];
ctx = this.canvas.getContext("2d");
sprites = [];
clickables = [];
mouse_objs = [];
// Enable mouse event detection
this.canvas.addEventListener("click", handler.onclick, false);
this.canvas.addEventListener("mousemove", handler.onmousemove, false);
};
/*
* create_sprite(xy, size, depth, type)
* Create a new sprite and return.
* Args:
* xy, size: the geometrical properties of the new sprite
* depth:
* type: should be a valid value from Sprite.TypeEnum
*/
this.create_sprite = function (xy, size, depth, type) {
var spr = new Sprite(this, xy, size, depth, type);
sprites.push(spr);
return spr;
};
this.get_sprite = function (spr) {
if (typeof spr === "string") {
// TODO: add sprite name support
} else if (spr instanceof Sprite) {
for (var i = 0; i < sprites.length; i++) {
if (spr === sprites[i]) {
return sprites[i];
}
}
}
};
var find_sprite = function (sprite, collection) {
for (var i = 0; i < collection.length; i++) {
if (collection[i].sprite === sprite) {
return i;
}
}
return -1;
};
this.remove_sprite = function (spr) {
if (typeof spr === "string") {
this.remove_sprite(this.get_sprite(spr));
} else if (spr instanceof Sprite) {
for (var i = 0; i < sprites.length; i++) {
if (spr === sprites[i]) {
sprites.splice(i, 1);
break;
}
}
i = find_sprite(spr, clickables);
if (i >= 0) {
clickables.splice(i, 1);
}
i = find_sprite(spr, mouse_objs);
if (i >= 0) {
mouse_objs.splice(i, 1);
}
}
};
/*
* render
* Redraw the canvas.
*/
this.render = function () {
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// draw sprites in descending order of their depth.
sprites.sort(function (a, b) { return - (a.depth - b.depth); });
for (var i = 0; i < sprites.length; i++) {
sprites[i].render(ctx);
}
};
/*
* register_event(sprite, event_name, spec)
* Register a sprite to handle events. Usually, a callback function is
* provided and should be called when such an event happens.
* Args:
* sprite:
* event_name: can be "load", "click", etc.
* spec: extra specifications of registration
*/
this.register_event = function (sprite, event_name, spec) {
switch (event_name) {
case "load":
// TODO: if necessary, this will be encapsulated by a separate
// "load_image" method
// spec = { type: "img", src: "...", callback: function(event, img) }
var img = document.createElement("img");
img.addEventListener("load",
function (event) {
spec.callback.apply(sprite, [event, img]);
},
false);
img.src = spec.src;
break;
case "click":
// spec = { callback: function (event) }
clickables.push({
sprite: sprite,
callback: spec.callback
});
break;
case "mousemove":
// spec = { callback: function (event) }
var i = find_sprite(sprite, mouse_objs);
if (i >= 0) {
mouse_objs[i].callback_mousemove = spec.callback;
} else {
mouse_objs.push({
sprite: sprite,
on: false,
callback_mousemove: spec.callback,
callback_mouseout: null
});
}
break;
case "mouseout":
// spec = { callback: function (event) }
var i = find_sprite(sprite, mouse_objs);
if (i >= 0) {
mouse_objs[i].callback_mouseout = spec.callback;
} else {
mouse_objs.push({
sprite: sprite,
on: false,
callback_mousemove: null,
callback_mouseout: spec.callback
});
}
break;
default:
throw new Error("register_event: unknown event type: " + event_name);
}
};
var in_rect = function (point_xy, rect) {
var x = point_xy[0], y = point_xy[1];
return (rect[0] <= x && x <= rect[0] + rect[2] &&
rect[1] <= y && y <= rect[1] + rect[3]);
};
var get_mouse_xy = function (event) {
// Get the mouse position relative to the canvas element.
var x, y;
if (event.layerX || event.layerX === 0) { // Firefox
x = event.layerX;
y = event.layerY;
} else if (event.offsetX || event.offsetX === 0) { // Chrome, Opera
x = event.offsetX;
y = event.offsetY;
}
return [x, y];
};
/*
* PRIVATE EVENT HANDLERS
* Handle all the events. Call the approriate callback functions.
*/
var handler = {
onclick: function (event) {
var clicked = null;
var min_depth = Engine.MaxDepth + 1;
for (var i = 0; i < clickables.length; i++) {
var rect = clickables[i].sprite.topleft.concat(clickables[i].sprite.size);
if (in_rect(get_mouse_xy(event), rect)) {
if (min_depth > clickables[i].sprite.depth) {
clicked = clickables[i];
min_depth = clicked.sprite.depth;
}
}
}
if (clicked) {
clicked.callback.call(clicked.sprite, event, get_mouse_xy(event));
}
},
onmousemove: function (event) {
for (var i = 0; i < mouse_objs.length; i++) {
var obj = mouse_objs[i];
var rect = obj.sprite.topleft.concat(obj.sprite.size);
if (in_rect(get_mouse_xy(event), rect)) {
if (!obj.on) {
// TODO: add mouseenter
}
obj.on = true;
if (obj.callback_mousemove) {
obj.callback_mousemove.call(obj.sprite, event, get_mouse_xy(event));
}
} else if (obj.on) {
obj.on = false;
if (obj.callback_mouseout) {
obj.callback_mouseout.call(obj.sprite, event, get_mouse_xy(event));
}
}
}
}
};
} | [
"bindElements(canvasEl) {\n this.canvas = new MainCanvas(canvasEl);\n }",
"initCanvas() {\n // Create new canvas object.\n this._canvasContainer = document.getElementById(this._canvasId);\n if (!this._canvasContainer)\n throw new Error(`Canvas \"${this._canvasId}\" not found`);\n // Get rendering context.\n this._canvas = this._canvasContainer.getContext('2d');\n // Register canvas interaction event handlers.\n this._canvasContainer.addEventListener('mousedown', (event) => this.canvasMouseDown(event));\n this._canvasContainer.addEventListener('mouseup', (event) => this.canvasMouseUp(event));\n this._canvasContainer.addEventListener('mousemove', (event) => this.canvasMouseMove(event));\n this._canvasContainer.addEventListener('wheel', (event) => this.canvasScrollWheel(event));\n // Get width and height of canvas.\n this._canvasWidth = this._canvasContainer.width;\n this._canvasHeight = this._canvasContainer.height;\n }",
"function CanvasController() {\n // Define the canvas reference and canvas context\n const canvas = document.querySelector('canvas');\n\n // Get the window size dimensions\n this.width = window.width * window.scale;\n this.height = window.height * window.scale;\n\n // Set the canvas dimensions to the window size\n canvas.width = this.width;\n canvas.height = this.height;\n\n // Define the offscreen canvas reference that mirrors the main canvas\n // This is done to optimize image rendering and performance\n const offscreenCanvas = canvas.transferControlToOffscreen();\n\n // Set the offscreen canvas dimensions to the window size\n offscreenCanvas.width = this.width;\n offscreenCanvas.height = this.height;\n\n // Define the offscreen canvas context\n // Since transferControlToOffscreen is used on the offscreen canvas, all\n // drawing will be done with this context\n this.context = offscreenCanvas.getContext('2d');\n\n // Define the canvas context drawing methods\n this.drawImage = canvasContext.drawImage(this);\n\n log.controller.canvas.init.success();\n}",
"function EngineInstrumentation(\n /**\n * Define the instrumented engine.\n */\n engine) {\n this.engine = engine;\n this._captureGPUFrameTime = false;\n this._gpuFrameTime = new PerfCounter();\n this._captureShaderCompilationTime = false;\n this._shaderCompilationTime = new PerfCounter();\n // Observers\n this._onBeginFrameObserver = null;\n this._onEndFrameObserver = null;\n this._onBeforeShaderCompilationObserver = null;\n this._onAfterShaderCompilationObserver = null;\n }",
"buildCanvas(){\r\n $(this.parent).append($(`\r\n <canvas id=\"mobcanvas\">\r\n <p>Désolé, votre navigateur ne supporte pas Canvas. Mettez-vous à jour</p>\r\n </canvas>\r\n `));\r\n }",
"function EngineCore(){\n this.State = new EngineState();\n this.TimeKeeper = new TimeKeeper();\n this.Matrices = {};\n this.MatStack = new Stack();\n this.Shaders = {};\n this.Objects = {};\n this.Textures = {};\n this.ShaderVars = {};\n this.Fonts = {};\n this.Extensions = {};\n this.World = {};\n this.Cameras = [];\n this.AnimPlayer = new AnimPlayer();\n //==============================================================================\n //Initializes the Graphics Engine\n //==============================================================================\n this.init = function(){\n canvas = document.getElementById('WebGL', {antialias:true});\n try{\n gl = canvas.getContext(\"experimental-webgl\");\n //Extensions====================================================================\n this.Extensions.aniso = gl.getExtension(\"EXT_texture_filter_anisotropic\");\n //==============================================================================\n //Event Listeners here==========================================================\n document.addEventListener(\"visibilitychange\", Engine.pause, false);\n //==============================================================================\n this.LoadShaders(['Unlit', 'Lit']);\n this.LoadMeshData(['Monkey']);\n this.LoadExtraTex(['CalibriWhite', 'VerdanaWhite']);\n Engine.Fonts['Calibri'] = new fontInfo('Calibri');\n Engine.Fonts['Verdana'] = new fontInfo('Verdana');\n this.Cameras.push(new Camera(this.Cameras.length));\n this.Cameras[0].transform.position = vec3.fromValues(0,0,3);\n this.Matrices.ModelMatrix = mat4.create();\n this.Matrices.NormalMatrix = mat4.create();\n this.Matrices.MVPMatrix = mat4.create();\n this.Matrices.TempMatrix = mat4.create();\n gl.clearColor(0.3,0.3,0.3,1);\n gl.enable(gl.CULL_FACE);\n gl.enable(gl.DEPTH_TEST);\n this.State.initialized = true;\n doneLoading();\n }\n catch(e){\n canvas.style.display = 'none';\n doneLoading();\n }\n }\n //==============================================================================\n //Draws current frame on canvas\n //Avoid all 'this' references, as this function is part of update which uses callbacks\n //==============================================================================\n this.renderFrame = function(){\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n //Reset matrices\n mat4.identity(Engine.Matrices.ModelMatrix);\n //Set view to current active camera\n Engine.Cameras[Engine.State.ActiveCamera].setView();\n //Push default matrices to top of stack\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n\n for (var obj in Engine.World){\n if(Engine.World.hasOwnProperty(obj) && Engine.Shaders[Engine.World[obj].Shader].compiled!=false && Engine.World[obj].initialized){\n //Pop fresh model and mvp Matrices\n Engine.Matrices.MVPMatrix = Engine.MatStack.pop();\n Engine.Matrices.ModelMatrix = Engine.MatStack.pop();\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n //Create an alias for the current object\n var obj = Engine.World[obj];\n //Set shader for current object\n gl.useProgram(Engine.Shaders[obj.Shader].Program);\n //Perform per object transformations here\n Engine.evalTransform(obj);\n //Apply perspective distortion\n mat4.multiply(Engine.Matrices.MVPMatrix, Engine.Matrices.MVPMatrix, Engine.Matrices.ModelMatrix);\n //Bind attributes\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.position);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Position, 3, gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.uv);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_UV, 2, gl.FLOAT, false, 0, 0);\n if(Engine.Shaders[obj.Shader].Attributes.a_Normal >= 0){\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.normal);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Normal, 3, gl.FLOAT, false, 0, 0);\n }\n //Call draw\n obj.draw();\n }}\n }\n //==============================================================================\n //Primary render loop\n //Avoid all 'this' references, as this function uses a callback\n //==============================================================================\n var inter = window.performance.now();\n this.Update = function(){\n var begin = window.performance.now();\n inter = window.performance.now() - inter;\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n //Call any runtime logic here\n frame = requestAnimationFrame(Engine.Update, canvas);\n Engine.renderFrame();\n Engine.TimeKeeper.update();\n Engine.AnimPlayer.update();\n Engine.TimeKeeper.frameTime = (window.performance.now()-begin).toFixed(2);\n Engine.TimeKeeper.interFrameTime = inter.toFixed(2);\n inter = window.performance.now();\n }\n //==============================================================================\n //Download And Compile Shader Code From Server.\n //Shaders must use the (shaderName)_(f/v).glsl naming convention\n //==============================================================================\n this.LoadShaders = function(ShaderNames){\n console.group(\"Shader Loading\");\n ShaderNames.forEach(function(element){\n console.log(\"Requesting Shader: \"+element);\n this.Shaders[element] = new Shader(element);\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Download and bind mesh data from server\n //==============================================================================\n this.LoadMeshData = function(MeshNames){\n console.group(\"Mesh Loading\");\n MeshNames.forEach(function(element){\n console.groupCollapsed(\"Mesh: \"+element);\n this.Objects[element] = new Mesh(element);\n this.Objects[element].load();\n console.groupEnd();\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Dowload and bind extra textures form server\n //==============================================================================\n this.LoadExtraTex = function(TexNames){\n TexNames.forEach(function(element){\n LoadTex((\"Resources/Textures/\"+element+\".png\"), element, Engine);\n }, this);\n }\n //==============================================================================\n //Pause the engine when window has lost focus\n //==============================================================================\n this.pause = function(){\n if(document.hidden){\n cancelAnimationFrame(frame);\n }\n else{\n Engine.TimeKeeper.lastFrame = window.performance.now();\n requestAnimationFrame(Engine.Update, canvas);\n }\n }\n //==============================================================================\n //Take an object and instance it into the world\n //==============================================================================\n this.Instantiate = function(obj, trans = null){\n var instanceName = (obj.tag)+'.'+((obj.numinstances)++).toString();\n obj.instances.push(instanceName);\n this.World[instanceName] = this.Duplicate(obj, instanceName, trans);\n return instanceName;\n }\n //==============================================================================\n //Duplicate an object. Return duplicate.\n //==============================================================================\n this.Duplicate = function(obj, name, trans){\n var newObj = new Mesh(name);\n newObj.Buffer = obj.Buffer;\n newObj.Textures = obj.Textures;\n if(trans != undefined){newObj.transform.copy(trans);}\n else{newObj.transform.copy(obj.transform);}\n newObj.Shader = obj.Shader;\n newObj.initialized = obj.initialized;\n return newObj;\n }\n //==============================================================================\n //recursive function to evaluate an object's tranform based on its parent\n //==============================================================================\n this.evalTransform = function(obj){\n if(obj.parent != null){\n this.evalTransform(obj.parent);\n }\n obj.transform.applyParent(Engine.Matrices.ModelMatrix);\n obj.transform.apply(Engine.Matrices.ModelMatrix);\n }\n}",
"setupCanvas(canvas){\n this.canvas.loadFromJSON(canvas, () => {\n this.canvas.renderAll(); \n });\n }",
"function Canvas() {\r\n var buffer, canvasWidth, canvasHeight, transform, dataView, ii, args, originPoint, alpha;\r\n \r\n args = splitArguments(arguments);\r\n \r\n if (args.length === 1 && args[0].length) {\r\n args = args[0];\r\n }\r\n \r\n // ANTS_TAG : change after serialization changes!\r\n if (args[0] && args[0].constructor === ArrayBuffer && args[0].byteLength > 29) {\r\n dataView = new DataView(args[0]);\r\n canvasWidth = dataView.getFloat32(0);\r\n canvasHeight = (dataView.byteLength - 28) / (canvasWidth << 2);\r\n transform = new AffineTransform(dataView.getFloat32(dataView.byteLength - 24), dataView\r\n .getFloat32(dataView.byteLength - 20), dataView.getFloat32(dataView.byteLength - 16), dataView\r\n .getFloat32(dataView.byteLength - 12), dataView.getFloat32(dataView.byteLength - 8), dataView\r\n .getFloat32(dataView.byteLength - 4));\r\n buffer = new DataView(new ArrayBuffer((canvasHeight * canvasWidth) << 2));\r\n \r\n for (ii = 4; ii < (dataView.byteLength - 24); ii += 4) {\r\n buffer.setUint32(ii - 4, dataView.getUint32(ii));\r\n }\r\n buffer = buffer.buffer;\r\n // ANTS_TAG : temporary stub!\r\n originPoint = new Point(0, 0);\r\n alpha = 1;\r\n dataView = null;\r\n }\r\n else {\r\n canvasWidth = (!isNaN(args[0]) ? args[0] : 1);\r\n canvasHeight = (!isNaN(args[1]) ? args[1] : 1);\r\n buffer = ((args[2] && (args[2].constructor === ArrayBuffer)) ? args[2] : new ArrayBuffer(\r\n (canvasHeight * canvasWidth) << 2));\r\n transform = ((args[3] && args[3].type && args[3].type() === \"workerUtility.AffineTransform\")\r\n ? args[3]\r\n : new AffineTransform());\r\n originPoint = ((args[4] && args[4].type && args[4].type() === \"workerUtility.Point\") ? args[4] : new Point());\r\n alpha = ((!isNaN(args[5]) && args[5].constructor === Number) ? args[5] : 1);\r\n }\r\n \r\n if (alpha > 1 || alpha < 0) {\r\n commonUtility.logger.warn(\"Alpha parameter could be in range [0;1]. You set up : \" + alpha);\r\n // throw new WrongArgumentException(\"Alpha parameter could be in\r\n // range [0;1]. You set up : \" + alpha);\r\n alpha = 1;\r\n }\r\n \r\n this.affineTM = function() {\r\n return transform;\r\n };\r\n \r\n this.internalWidth = function() {\r\n return canvasWidth;\r\n };\r\n \r\n this.internalHeight = function() {\r\n return canvasHeight;\r\n };\r\n \r\n this.arrayBuffer = function() {\r\n return buffer;\r\n };\r\n this.origin = function() {\r\n return originPoint;\r\n };\r\n this.getAlpha = function() {\r\n return alpha;\r\n };\r\n this.setAlpha = function(value) {\r\n if (isNaN(value) || value.c !== Number.constructor) {\r\n throw new WrongArgumentException(\"Please proper set up input argument of alpha paramener!\");\r\n }\r\n if (value > 1 || value < 0) {\r\n commonUtility.logger.warn(\"Alpha parameter could be in range [0;1]. You set up : \" + alpha);\r\n // throw new WrongArgumentException(\"Alpha parameter could be in\r\n // range [0;1]. You set up : \" + alpha);\r\n alpha = 1;\r\n return;\r\n }\r\n alpha = value;\r\n };\r\n }",
"function init()\n{\n\t//\tInitialize the canvas and context\n\tcanvas = document.getElementById(\"mainCanvas\");\n\tctx = canvas.getContext(\"2d\");\n\tctx.font = \"100pt Verdana\";\n\tcanvas.width = TILE_S * COLS;\n\tcanvas.height = TILE_S * ROWS;\n\tcanvas.setAttribute(\"tabIndex\", \"0\");\n\tcanvas.focus();\n\n\n\tcanvas.addEventListener(\"keydown\",keyDownHandler);\n\tcanvas.addEventListener(\"keyup\",keyUpHandler);\n\n\t//\tInitialize actors\n\n\t// Bernie\n\thero = new Square(0, 0, 150, 228, 'img/Bernie.png', \"img/BernieJumping.png\");\n\tapplyDraw(hero);\n\tapplyGravity(hero, GRAVITY);\n\tactors.push(hero);\n\n\tmakeCostumes();\n\n}",
"constructor(elem, options) {\n\t\tvar self = this;\n\t\tthis.elem = elem;\n\t\tthis.bg = options.background || 'transparent';\n\t\tthis.canvas = document.createElement('canvas');\n\t\tthis.ctx = this.canvas.getContext('2d');\n\t\twindow.addEventListener('resize', function() {self.resize();});\n\t\tthis.elem.appendChild(this.canvas);\n\t\tthis.snow = [];\n\t\tthis.windForce = options.windForce || 2;\n\t\tthis.windDir = options.windDir || 1;\n\t\tthis.numFlakes = options.flakes || 100;\n\t\tthis.floatRange = options.floatRange || 1;\n\t\tthis.radiusRange = options.radiusRange || [2, 5];\n\t\tthis.speedMult = options.speedMult || 15;\n\t\tthis.alphaRange = options.alphaRange || [.7, 1];\n\t\tthis.color = options.color || 'white';\n\t\tthis.updateCanvas();\n\t\tfor(var i = 0;i<this.numFlakes;i++) {\n\t\t\tthis.addFlake(this.random(0,this.canvas.width),this.random(0,this.canvas.height));\n\t\t}\n\t\tthis.drawFlakes();\n\t}",
"static paintCanvas() {\n\t\tctx.fillStyle = backgroundColor;\n\t\tctx.fillRect(0, 0, W, H);\n\t}",
"function dce_setup_canvas(cwidth, cheight) {\n\n\tctx = null;\n\tcanvas = null;\n\tcanvas_container = null;\n\n\t// setup canvas\n\tcanvas = document.createElement('canvas');\n\n\tcanvas.id = \"gfxctx\";\n\tcanvas.width = cwidth;\n\tcanvas.height = cheight;\n\n\t// setup container\n\tcanvas_container = document.createElement('div');\n\n\tcanvas_container.id = \"gfxctx_container\";\n\tcanvas_container.style.width = cwidth + \"px\";\n\tcanvas_container.style.height = cheight + \"px\";\n\tcanvas_container.style.margin = \"0px auto\";\n\n\tcanvas_container.appendChild(canvas);\n\tdocument.body.appendChild(canvas_container);\n\n\tctx = canvas.getContext(\"2d\");\n\n}",
"function mCreateCanvas() {\n createCanvas(...[...arguments]);\n pixelDensity(1);\n mPage = createGraphics(width, height, WEBGL);\n\tmPage.pixelDensity(1);\n}",
"function Engine(viewport, tileFunc, w, h) {\n this.viewport = viewport;\n this.tileFunc = tileFunc;\n this.w = w;\n this.h = h;\n this.refreshCache = true;\n this.cacheEnabled = false;\n this.transitionDuration = 0;\n this.cachex = 0;\n this.cachey = 0;\n this.tileCache = new Array(viewport.h);\n this.tileCache2 = new Array(viewport.h);\n for (var j = 0; j < viewport.h; ++j) {\n this.tileCache[j] = new Array(viewport.w);\n this.tileCache2[j] = new Array(viewport.w);\n }\n }",
"function initCanvas() {\n canvas = document.getElementById('graphCanvas')\n drawingContext = canvas.getContext(\"2d\");\n canvas.style.height = CANVAS_HEIGHT + \"px\";\n canvas.width = CANVAS_WIDTH;\n canvas.height = CANVAS_HEIGHT;\n}",
"function setup() {\n\tcreateCanvas(800, 700);\n\tengine = Engine.create();\n\tworld = engine.world;\n\n paper = new PaperBall(30,100,40);\n ground = new Ground(400,690,800,60);\n\n\n\t\n \n}",
"constructor(canvas, path){\n this.canvas = canvas;\n this.ctx = canvas.getContext('2d');\n var img = new Image();\n img.onload = e =>{\n this.renderInitial();\n };\n this.img = img;\n img.src = path;\n }",
"function root(element, name)\r\n{\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\telement is supposed to be a scene but this object does not expect it to be all it\r\n\tneeds is the width/height of the object it will fit into\r\n\t--------------------------------------------------------------------------------------*/\r\n\t//var w = element?( (typeof element.width === 'function') ? element.width() : 0): 0;\r\n\t//var h = element?( (typeof element.height === 'function') ? element.height() : 0): 0;\r\n\tvar w = element?( element.width ? element.width : 0): 0;\r\n\tvar h = element?( element.height ? element.height : 0): 0;\r\n\t\r\n\tthis.width = function(){ return w;}\t\r\n\tthis.height = function(){ return h;}\t\r\n\r\n\t/*--------------------------------------------------------------------------------------\r\n\twill handle resize event from the object it binds to as it will resize itself to \r\n\talways fit to it. note that canvas don't fire up resize event so the canvas of the\r\n\tscene this object binds to must have a custom event that fires up upon resize \r\n\t--------------------------------------------------------------------------------------*/\r\n\telement.addEventListener(\"resize\", function(e)\r\n\t{\r\n\t\tw = e?(e.detail.width? e.detail.width : 0): 0;\r\n\t\th = e?(e.detail.height? e.detail.height : 0): 0;\t\r\n\r\n\t\t// fire up event handler\r\n\t\tfor (var i = 0; i < resizeEvents.length; i++){ resizeEvents[i]({elem: this, name: name, w: w, h: h}); } \r\n\t}.bind(this));\r\n\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\tassign event handlers\r\n\t--------------------------------------------------------------------------------------*/\r\n\tvar resizeEvents = [];\r\n\tvar drawEvents = [];\r\n\tvar mouseupEvents = [];\r\n\tvar mousedownEvents = [];\r\n\tvar mouseleaveEvents = [];\r\n\tvar mousedragEvents = [];\r\n\tvar mousemoveEvents = [];\r\n\tvar mouseoverEvents = [];\r\n\tthis.addEventListener = function(e, f)\r\n\t{\r\n\t\tif (e === \"resize\"){ resizeEvents.push(f); }\t\t\r\n\t\tif (e === \"draw\"){ drawEvents.push(f); }\t\t\r\n\t\tif (e === \"mouseup\"){ mouseupEvents.push(f); }\t\t\r\n\t\tif (e === \"mousedown\"){ mousedownEvents.push(f); }\t\t\r\n\t\tif (e === \"mouseleave\"){ mouseleaveEvents.push(f); }\t\t\r\n\t\tif (e === \"mousedrag\"){ mousedragEvents.push(f); }\r\n\t\tif (e === \"mousemove\"){ mousemoveEvents.push(f); }\r\n\t\tif (e === \"mouseover\"){ mouseoverEvents.push(f); }\r\n\t}\r\n\t\r\n\tthis.removeEventListener = function(e, f)\r\n\t{\r\n\t\tif (e === \"resize\"){ for (var i = 0; i < resizeEvents.length; i++){ if (resizeEvents[i] == f){ resizeEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"draw\"){ for (var i = 0; i < drawEvents.length; i++){ if (drawEvents[i] == f){ drawEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mouseup\"){ for (var i = 0; i < mouseupEvents.length; i++){ if (mouseupEvents[i] == f){ mouseupEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mousedown\"){ for (var i = 0; i < mousedownEvents.length; i++){ if (mousedownEvents[i] == f){ mousedownEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mouseleave\"){ for (var i = 0; i < mouseleaveEvents.length; i++){ if (mouseleaveEvents[i] == f){ mouseleaveEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mousedrag\"){ for (var i = 0; i < mousedragEvents.length; i++){ if (mousedragEvents[i] == f){ mousedragEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mousemove\"){ for (var i = 0; i < mousemoveEvents.length; i++){ if (mousemoveEvents[i] == f){ mousemoveEvents.splice(i,1); return; }}}\t\t\t\r\n\t\tif (e === \"mouseover\"){ for (var i = 0; i < mouseoverEvents.length; i++){ if (mouseoverEvents[i] == f){ mouseoverEvents.splice(i,1); return; }}}\t\t\t\r\n\t}\t\r\n\r\n\t/*--------------------------------------------------------------------------------------\r\n\tholds child objects. bottom child is at start of array, and top child is at the end\r\n\t--------------------------------------------------------------------------------------*/\r\n\tvar children = [];\t\r\n\tthis.addChild = function(child){ children.push(child); }\r\n\tthis.removeChild = function(child){\tfor (var i = 0; i < children.length; i++) { if ( children[i] == child) { children.splice(i, 1); return; }}}\r\n\tthis.getNumChildren = function(){ return children.length; }\r\n\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\tthis object doesn't really get rendered. its main purpose is to occupy the scene it \r\n\tbinds to. this function is used to render its child objects instead. however, an it \r\n\tfires up a render event to allow application option in case users choose to\r\n\t--------------------------------------------------------------------------------------*/\r\n\tthis.draw = function()\r\n\t{\t\t\r\n\t\tfor (var i = 0; i < drawEvents.length; i++){ drawEvents[i]({elem: this, name: name, w: w, h: h}); } \t\t\r\n\t\tfor(var i = 0; i < children.length; i++){if (children[i].draw) children[i].draw();}\t\t\t\t\t\r\n\t}\r\n\t\t \r\n\t/*--------------------------------------------------------------------------------------\r\n\ttests if mouse cursor is within its bounds (collision detection against mouse)\r\n\t--------------------------------------------------------------------------------------*/\r\n\tthis.intersect = function(mx, my)\r\n\t{\r\n\t\tif (mx > w) return false;\r\n\t\tif (my > h) return false;\r\n\t\tif (mx < 0) return false;\r\n\t\tif (my < 0) return false;\t\t\r\n\t\treturn true;\r\n\t}\t\r\n\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\ttakes the given child object t and if it exist in children list will be moved to top\r\n\t--------------------------------------------------------------------------------------*/\r\n\tthis.sendChildToTop = function(t)\r\n\t{\r\n\t\tfor (var i = 0; i < children.length; i++)\r\n\t\t{\r\n\t\t\tif(children[i] == t)\r\n\t\t\t{\r\n\t\t\t\tchildren.splice(i,1);\r\n\t\t\t\tchildren.push(t);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*--------------------------------------------------------------------------------------\r\n\twith given mouse cursor coordinate, it finds the top child that intersects with it, \r\n\tstarting from the top. it recursively (optional) checks through descendants until the \r\n\tyoungest that intersect is found. any child that intersects will also be moved to\r\n\tto top (optional)\r\n\treturns the child (or descendant) that is found to intersect with mouse cursor.\r\n\treturns null if no child (or descendant) if found to intersect\r\n\t--------------------------------------------------------------------------------------*/\r\n\tthis.findTopChildAtPoint = function(mx, my, recursive, top)\r\n\t{\r\n\t\tfor (var i = children.length - 1; i >= 0; i--)\r\n\t\t{ \r\n\t\t\tif (typeof children[i].hide === 'function'){ if (children[i].hide()) continue; }\r\n\t\t\tif (children[i].intersect(mx, my))\r\n\t\t\t{ \r\n\t\t\t\t// send this child to top. also, set i to top child\r\n\t\t\t\tif (top) \r\n\t\t\t\t{\r\n\t\t\t\t\tthis.sendChildToTop(children[i]);\t\t\t\t\t\r\n\t\t\t\t\ti = children.length - 1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// recursively do this...\r\n\t\t\t\tif (typeof children[i].findTopChildAtPoint === 'function' && recursive) \r\n\t\t\t\t{\t\t\t\t\t\r\n\t\t\t\t\tvar t = children[i].findTopChildAtPoint(mx, my, recursive, top);\r\n\t\t\t\t\tif (t) return t;\t\t\t\t\t\t\t\r\n\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\treturn children[i]; \r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*--------------------------------------------------------------------------------------\r\n\t_mousemove points to a top child where mouse cursor hovers when mouse button\r\n\tis released (mouse over)\r\n\t_mousedown points to a child where the mouse cursor hovers when mouse button is pressed\r\n\t--------------------------------------------------------------------------------------*/\r\n\tvar _mousedown = 0;\r\n\tvar _mousemove = 0;\r\n\t\r\n\t\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\tlisten to \"mousemove\" event on the element it binds to.\r\n\t--------------------------------------------------------------------------------------*/\r\n\telement.addEventListener(\"mousemove\", function(e)\r\n\t{ \r\n\t\t// calculate the mouse cursor's relative position to element we are bound to\r\n\t\tvar r = element.getBoundingClientRect();\r\n\t\tvar mx = e.pageX - r.left; \r\n\t\tvar my = e.pageY - r.top; \r\n\t\t\r\n\t\t// if there's a child that mouse cursor has click to while mouse is moving, \r\n\t\t// this child should track the mouse movement.\r\n\t\tif (_mousedown)\r\n\t\t{\r\n\t\t\tif(_mousedown.onmousedrag){_mousedown.onmousedrag(mx, my, e.movementX, e.movementY);}\r\n\t\t}\r\n\t\t// otherwise, find the top child that mouse cursor intersects with and set it as \r\n\t\t// \"mousemove\" child\t\t\r\n\t\telse\r\n\t\t{\t\t\r\n\t\t\t// we are only looking for top child (immediate), grand childrens are not included. \r\n\t\t\tvar t = this.findTopChildAtPoint(mx, my, false, false);\t\t\r\n\r\n\t\t\t// if the top child intersecting with mouse cursor is not the same as the previous child,\r\n\t\t\t// it means that the mouse cursor is now hovering on a new child. call \"mouse leave\" event\r\n\t\t\t// on previous child so it can handle this event\r\n\t\t\tif (t != _mousemove)\r\n\t\t\t{ \r\n\t\t\t\tif(_mousemove){ if(_mousemove.onmouseleave) _mousemove.onmouseleave(); }\r\n\t\t\t\t\r\n\t\t\t\t// if t is one of the root's active child, fire up \"mouse over\" event\r\n\t\t\t\tif(t){ if(t.onmouseover) t.onmouseover(); }\t\r\n\t\t\t\t\r\n\t\t\t\t// if t does not exist, we mousever in root. trigger event only if root isn't mousemove ui before\r\n\t\t\t\t//else{ if(_mousemove != this) this.onmouseover(); }\r\n\t\t\t}\t\t\r\n\t\t\t\r\n\t\t\t// update pointer to new child where mouse hovers and call \"mouse move\" event \r\n\t\t\tif (t)_mousemove = t;\r\n\t\t\telse _mousemove = this;\r\n\t\t\tif (_mousemove){if(_mousemove.onmousemove) _mousemove.onmousemove(mx, my, e.movementX, e.movementY);}\t\t\r\n\t\t}\t\t\r\n\t\r\n\t}.bind(this));\t\r\n\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\tlisten to \"mousedown\" event on the element it binds to.\r\n\t--------------------------------------------------------------------------------------*/\r\n\telement.addEventListener(\"mousedown\", function(e)\r\n\t{ \r\n\t\t// calculate the mouse cursor's relative position to element we are bound to\r\n\t\tvar r = element.getBoundingClientRect();\r\n\t\tvar mx = e.pageX - r.left; \r\n\t\tvar my = e.pageY - r.top; \r\n\t\t\r\n\t\t// find the top ui (including this) that the mouse button has click to and call its event\r\n\t\t//_mousedown = this.findTopAtPoint(mx, my, true);\r\n\t\t_mousedown = this.findTopChildAtPoint(mx, my, true, true);\r\n\t\tif (!_mousedown) _mousedown = this; \r\n\t\t\r\n\t\tif (_mousedown){ if (_mousedown.onmousedown) _mousedown.onmousedown(mx, my); }\r\n\t}.bind(this));\t\t\r\n\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\tlisten to \"mouseup\" event on the element it binds to.\r\n\t--------------------------------------------------------------------------------------*/\r\n\tdocument.addEventListener(\"mouseup\", function(e)\r\n\t{ \r\n\t\t// calculate the mouse cursor's relative position to element we are bound to\r\n\t\tvar r = element.getBoundingClientRect();\r\n\t\tvar mx = e.pageX - r.left; \r\n\t\tvar my = e.pageY - r.top; \r\n\t\t\t\t\r\n\t\t// if mouse button clicked into a child...\r\n\t\tif(_mousedown)\r\n\t\t{\r\n\t\t\t// is mouse cursor still hovering the child it click to?\r\n\t\t\tif (_mousedown.intersect)\r\n\t\t\t{\r\n\t\t\t\t\t// if yes, let the child handle \"mouseup\" event\r\n\t\t\t\t\tif (_mousedown.intersect(mx, my)){if (_mousedown.onmouseup) _mousedown.onmouseup(mx, my);}\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t// otherwise, let the child handle \"mouse leave\" event\r\n\t\t\t\t\telse{ if (_mousedown.onmouseleave) _mousedown.onmouseleave(); }\r\n\t\t\t}\r\n\t\t\t// if mouse cursor is now hovering on another child...\r\n\t\t\telse{if (_mousedown.onmouseleave) _mousedown.onmouseleave();}\r\n\t\t}\r\n\t\t_mousedown = 0;\r\n\t}.bind(this));\t\t\t\r\n\t\r\n\t// handle event when this frame is being dragged by a mouse when it clicks and hold to it\r\n\t// dx/dy is the delta movement of mouse between previous and current onmousedrag event occurence\r\n\tthis.onmousedrag = function(mx, my, dx, dy)\r\n\t{ \r\n\t\tfor (var i = 0; i < mousedragEvents.length; i++){ mousedragEvents[i]({elem: this, name: name, x: mx, y: my, dx: dx, dy: dy}); }\r\n\t}\t\r\n\r\n\t// handle event when mouse button is clicked into this frame\r\n\tthis.onmousedown = function(mx, my)\r\n\t{ \r\n\t\tfor (var i = 0; i < mousedownEvents.length; i++){ mousedownEvents[i]({elem: this, name: name, x: mx, y: my}); }\r\n\t}\t\r\n\t\t\t\r\n\t// handle event when mouse is moving on top of this frame\r\n\tthis.onmouseup = function(mx, my)\r\n\t{ \r\n\t\tfor (var i = 0; i < mouseupEvents.length; i++){ mouseupEvents[i]({elem: this, name: name, x: mx, y: my}); }\r\n\t}\t\r\n\t\r\n\t// handle event when mouse just moved inside this frame's extents\r\n\tthis.onmouseover = function()\r\n\t{ \r\n\t\tfor (var i = 0; i < mouseoverEvents.length; i++){ mouseoverEvents[i]({elem: this, name: name}); }\r\n\t}\t\r\n\t\r\n\t// handle event when mouse is moving on top of root\r\n\tthis.onmousemove = function(mx, my, dx, dy)\r\n\t{ \r\n\t\tfor (var i = 0; i < mousemoveEvents.length; i++){ mousemoveEvents[i]({elem: this, name: name, x: mx, y: my, dx: dx, dy: dy}); }\r\n\t}\t\t\r\n}",
"paint() {\n var ctx = this.canvas.getContext(\"2d\");\n ctx.fillStyle = this.backgroundColor;\n ctx.fillRect(0,0,this.canvas.width,this.canvas.height);\n this.draw(ctx);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an XML request to populateTypes.php Sends XML request, apply callback. | function getTypes(button, callback)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "populateTypes.php?q=", true);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// defensive check
if (typeof callback === "function") {
// apply() sets the meaning of "this" in the callback
callback.apply(xmlhttp);
}
}
};
xmlhttp.send();
return false
} | [
"function getAddressTypes(callback) {\n\n let addressTypeRequest = createRequest('GET', '/addresstypes', 'application/json');\n\n let req = http.get(addressTypeRequest, function (response) {\n let addressResult = '';\n response.on('data', (chunk) => {\n addressResult += chunk;\n });\n response.on('end', () => {\n try {\n switch(response.statusCode) {\n case 200: {\n let addressTypeList = JSON.parse(addressResult).addressTypes;\n addressTypeList.forEach(function (addressType) {\n addressTypes[addressType.addressType] = addressType.id;\n });\n logger.debug('Listed address types successfully.');\n callback();\n break;\n }\n case 401: {\n logger.error('User is unauthorized. Exiting.', addressResult);\n keepAliveAgent.destroy();\n }\n case 500: {\n logger.error('Internal server error. Exiting.', addressResult);\n keepAliveAgent.destroy();\n }\n default: {\n logger.warn('Failed to list address types.', addressResult);\n callback();\n break;\n }\n }\n } catch (e) {\n logger.error('Failed to get address type list. Reason: ', e.message);\n callback();\n }\n });\n }).on('error', (e) => {\n logger.error('Failed to list address types.', e.message);\n });\n}",
"function loadXML(e) {\n var url = e.parameter.url;\n var xml = UrlFetchApp.fetch(url).getContentText();\n var document = XmlService.parse(xml); \n var entries = document.getRootElement().getChildren();\n var all_types = new Array();\n \n for (var i = 0; i < entries.length; i++) {\n all_types[i] = new Object();\n all_types[i].name = entries[i].getChildText('name');\n all_types[i].color = entries[i].getChildText('color');\n all_types[i].attributes = new Array();\n var children = entries[i].getChildren('attribute');\n for (var j = 0; j < children.length; j++) {\n all_types[i].attributes[j] = new Object();\n all_types[i].attributes[j].name = children[j].getText();\n var char = children[j].getAttribute('char');\n if(char != null)\n all_types[i].attributes[j].char = char.getValue();\n var pattern = children[j].getAttribute('pattern');\n if(pattern != null)\n all_types[i].attributes[j].pattern = pattern.getValue();\n var overridable = children[j].getAttribute('overridable');\n if(overridable != null && overridable.getValue() == 'true') {\n all_types[i].attributes[j].overridable = overridable.getValue(); \n }\n var manual = children[j].getAttribute('manual');\n if(manual != null && manual.getValue() == 'true') {\n all_types[i].attributes[j].manual = manual.getValue(); \n }\n } \n }\n \n updateButtons(all_types);\n initCache(all_types);\n DocumentApp.getUi().alert('Sidebar customised');\n}",
"function XML_(){\n let url = `https://${domain}/API/Account/${rad_id}/${APIendpoint}.json?offset=${pagenr}`;\n if (relation.length > 0) {\n url += `&load_relations=[${relation}]`;\n }\n if (query.length > 0) {\n url += query;\n }\n console.log(url);\n let uri = encodeURI(url);\n let e = new XMLHttpRequest();\n e.open(\"GET\", uri, document.getElementById('fasthands').checked),\n e.onload = function(){\n if ( e.status >= 200 && e.status < 400 ){\n t = JSON.parse(e.responseText);\n if (report === 'OrderNumbers') {\n unparse_();\n } else {\n parse_Data_();\n }\n }\n },\n e.send();\n }",
"function showAllFundingTypes() {\r\n xmlhttpFundingType = createXMLHttpRequestHandler();\r\n xmlhttpFundingType.onreadystatechange = function() {\r\n if (xmlhttpFundingType.readyState == 4 && xmlhttpFundingType.status == 200) {\r\n document.getElementById(\"funding_type_selection\").innerHTML = \"\";\r\n $( \"#funding_type_selection\" ).append(xmlhttpFundingType.responseText);\r\n }\r\n };\r\n xmlhttpFundingType.open(\"GET\",\"findFundingType.php?get_all=1\",true);\r\n xmlhttpFundingType.send(); \r\n}",
"function createXML() {\n var typeChecker, request;\n showSpinner(\"verify-spin\");\n typeChecker = $('option:selected').val();\n\tconsole.log(\"typechecker is \" + typeChecker + \" \" + document.location.pathname);\n\tconsole.log(\"isXML \" + document.forms.isXML.value);\n\n //make ajax request to create XML file\n request = $.ajax({\n url : PHP_SCRIPT,\n type : \"POST\",\n data : {\"function\" : \"xml\", \"guid\" : uploadGUID, \"script\" : typeChecker}\n });\n\n\t//wait for ajax request to complete before continuing\n request.done(function (response) {\n if (response === \"SUCCESS\") {\n \t\tconsole.log(\"create XML success\");\n\t \tcreateGameFiles();\n } else {\n\t\tconsole.log(\"create XML fail \" + response);\n\n $('#verify-spin').html(\"<a style='color:red' target='_blank' \" +\n \"href='scripts/utilities.php\" +\n \"?function=displayError&file=\" + response + \"&id=\" + uploadGUID + \"\\'>Error</a>\");\n }\n });\n}",
"initRequest() {\n this.$.rssAjax.generateRequest()\n }",
"function FillLanguagesCallBack(data, request) {\n FillDropDowns(\"Language\", data);\n}",
"function GetDocumentTypes()\n{\n\t$.ajax({\n\t\turl: action_url + 'GetDocumentTypes/' + UserId,\n\t\ttype: \"POST\",\n\t\tsuccess: function(Result)\n\t\t{\n\t\t\t$.each(Result.DocumentTypes, function(index, value)\n\t\t\t{\n\t\t\t\talert(value.id + \", \" + value.type);\n\t\t\t});\n\t\t}\n\t});\n}",
"function xmlHttp_handle_ulist_populate(){\n\tif(xmlHttp.readyState == 4 && xmlHttp.status == 200){\n\t\tpopulate_list_from_xml(xmlHttp.responseText, 'user_list');\n\t\tcleanup();\n\t}\n}",
"updateTypes() {\n let rawTypesByCategory = this.codenvyAPI.getProjectType().getTypesByCategory();\n this.typesByCategory = [];\n for (let categoryName in rawTypesByCategory) {\n this.typesByCategory.push({ category: categoryName, types: rawTypesByCategory[categoryName] });\n }\n // broadcast event\n this.$rootScope.$broadcast('create-project-blank:initialized');\n\n }",
"function initTypes() {\n // Boolean for production/file supplied/online or not\n var online = false;\n var json_raw_data = null;\n var var_types_url = null;\n if (online) {\n // Retrieve from dataverse API\n } else {\n // Read from local'\n var_types_url = \"../../data/preprocess_4_v1-0.json\";\n }\n\n d3.json(var_types_url, function(json_data) {\n var json_variables = json_data['variables'];\n // Loop through all the variables\n for(var key in json_variables) {\n var current_variable = json_variables[key];\n // Boolean\n if (current_variable['binary'] == 'yes') {\n types_for_vars[key] = 'Boolean';\n } else {\n var current_variable_nature = current_variable['nature'];\n if (current_variable_nature == 'ordinal') {\n // Numerical\n types_for_vars[key] = 'Numerical';\n } else if (current_variable_nature == 'nominal') {\n // Categorical\n types_for_vars[key] = 'Categorical';\n }\n }\n }\n generate_modal4();\n });\n}",
"function create_filter() {\n\t//If a filter name was entered\n\tif($(\"#filter_name\").val() !== '') {\n\t\t\n\t\t//Get the user name\n\t\tvar user = \"test_user\";\t\n\t\tvar filter_name = $(\"#filter_name\").val();\n\t\t\t\n\t\t//XML generation\n\t\tvar xml = '<xml version=\"1.0\"><user>' + user + '</user>' +\n\t\t\t\t\t'<filter_name>' + filter_name + '</filter_name>';\n\t\t\t\t\t\n\t\tvar i = 0;\n\t\t//For each selected option, get the name, the value and the button value\n\t\t$(\"select.sub-select\").each(function() {\n\t\t\txml += '<filter>' +\n\t\t\t\t\t'<field_name>' + (this.id) + '</field_name>' +\n\t\t\t\t\t'<field_value>' + ($(this).val()) + '</field_value>';\n\t\t\t\n\t\t\t//Add a button value to the XML if there are more than a field and except for the 1st field (no button). Then, close the filter.\n\t\t\tif((i !== 0) && (\".label-sub-select\")) {\n\t\t\t\txml += '<button_value>' + ($('#and_or_button' + i).bootstrapSwitch('state')) + '</button_value>' +\n\t\t\t\t\t\t'</filter>';\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t//Else add an \"0\" button value and close the filter\n\t\t\telse {\n\t\t\t\txml += '<button_value></button_value>' +\n\t\t\t\t\t\t'</filter>';\n\t\t\t\ti++;\n\t\t\t}\t\n\t\t});\n\t\t//Close the xml\n\t\txml += '</xml>';\n\n\t\t// AJAX call (json callback, here)\n\t\tvar request = $.ajax({\n\t\t\t\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\t\t\t\turl: \"model/reporting/set_filters.php\",\n\t\t\t\t\t\t\t\tdata: xml,\n\t\t\t\t\t\t\t\tcontentType: \"text/xml; charset=utf-8\",\n\t\t\t\t\t\t\t\tdataType: \"xml\",\n\t\t\t\t\t\t\t\tsuccess: OnSuccess,\n\t\t\t\t\t\t\t\terror: OnError\n\t\t});\n\n\t\t//If success, complete the select with the list of sites or display the error message\n\t\tfunction OnSuccess(data,status,request) {\n\n\t\t\tvar error = $(request.responseText).find(\"error\").text();\t\n\t\t\tvar success = $(request.responseText).find(\"success\").text();\t\n\t\t\t\n\t\t\t// If there are no errors, print the success message\n\t\t\tif ((error == \"\") && (success !== \"\")){\n\t\t\t\tmessage = $(request.responseText).find(\"success\").eq(0).text();\n\t\t\t\tDeleteMessage();\n\t\t\t\tCreateMessage(\"green\", message, 0.5, 3, 0.5);\n\t\t\t}\n\t\t\t//Else print the error message\n\t\t\telse if ((error !== \"\") && (success == \"\")){\n\t\t\t\tmessage = $(request.responseText).find(\"error\").eq(0).text();\n\t\t\t\tDeleteMessage();\n\t\t\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//Else : error\n\t\tfunction OnError(request, data, status) {\t\t\t\t\n\t\t\tmessage = \"Network problem: XHR didn't work (perhaps, incorrect URL is called).\";\n\t\t\tDeleteMessage();\n\t\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t\t}\t\n\t}\n\t//Else : error\n\telse {\t\t\t\t\n\t\tmessage = \"Please, enter a filter name.\";\n\t\tDeleteMessage();\n\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t}\t\n}",
"function initializeTyperCode () {\n // Create new request\n var resp = new XMLHttpRequest ();\n \n // Event trigger on response answer received or timeout\n resp.onreadystatechange = function() {\n // Answer received \n if (resp.readyState == 4) {\n // Success\n if (resp.status == 200) {\n // Send response text to helper\n initializeTyperCode_handle (resp.responseText);\n // Fail\n } else {\n // Send null (failure) to helper\n initializeTyperCode_handle (null);\n }\n }\n };\n \n // Send request\n resp.open (\"GET\", typerFile);\n resp.send ();\n}",
"function create_filter_list_select(select) {\n\t\n\t//Get the user name\n\tvar user = \"test_user\";\t\n\t\n\t//Indicates the filter_name to get (if empty, get the list of all the filter names)\n\tvar filter_name = \"\";\t\n\t\t\t\n\t//XML generation (user parameter = \"\" to get back to the list the filters of one user only)\n\tvar xml = '<xml version=\"1.0\">' +\n\t\t\t\t'<user>' + user + '</user>' +\n\t\t\t\t'<parameter>' + filter_name + '</parameter>' +\n\t\t\t\t'<user_parameter></user_parameter>' +\n\t\t\t'</xml>';\n\n\t// AJAX call (json callback, here)\n\tvar request = $.ajax({\n\t\t\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\t\t\turl: \"model/reporting/get_filters.php\",\n\t\t\t\t\t\t\tdata: xml,\n\t\t\t\t\t\t\tcontentType: \"text/xml; charset=utf-8\",\n\t\t\t\t\t\t\tdataType: \"xml\",\n\t\t\t\t\t\t\tsuccess: OnSuccess,\n\t\t\t\t\t\t\terror: OnError\n\t});\n\n\t//If success, complete the select with the list of sites or display the error message\n\tfunction OnSuccess(data,status,request) {\n\n\t\tvar error = $(request.responseText).find(\"error\").text();\t\n\t\t\n\t\t// If there are no errors, complete the select field\n\t\tif (error == \"\"){\n\t\t\t//Get the number of filter to include on the list\n\t\t\tvar filters_number = $(request.responseText).find(\"filter_name\").length;\n\t\t\t\n\t\t\t//Get each filter name and insert it into an option; then, into a select\n\t\t\tfor (i = 0; i < filters_number; i++) {\n\t\t\t\tvar filter_name = $(request.responseText).find(\"filter_name\").eq(i).text()\n\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\toption.innerHTML = filter_name;\n\t\t\t\toption.value = filter_name;\n\t\t\t\toption.id = \"pre_set_filters_option\" + i;\n\t\t\t\toption.className = \"user_filters\";\n\t\n\t\t\t\tselect.append(option);\n\t\t\t}\n\t\t}\n\t\t//Else print the error message\n\t\telse if (error !== \"\"){\n\t\t\tmessage = $(request.responseText).find(\"error\").text();\n\t\t\tDeleteMessage();\n\t\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t\t}\n\t}\n\t\n\t//Else : error\n\tfunction OnError(request, data, status) {\t\t\t\t\n\t\tmessage = \"Network problem: XHR didn't work (perhaps, incorrect URL is called).\";\n\t\tDeleteMessage();\n\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t}\n}",
"function uploadXML(){\n\tvar fileInput = document.getElementById('fileInput');\n\tvar file = fileInput.files[0];\n\tvar textType = /xml.*/;\n\n\t//get extension of filename and store it in global variable\n\tvar fileTypeValue=$(\"#fileInput\").val();\n\tvar newfilename = fileTypeValue.split(/(\\\\|\\/)/g).pop();\n\tvar ext = newfilename.split(\".\");\n\tvar fileName = fileTypeValue.split('\\\\').pop();\n\tApplication = ext.pop();\n\n\tif($(\"#clearCanvasCheckbox\").is(\":checked\")){\n\t\tclearCanvas();\t\t\t\t\n\t}\n\n\tif (file.type.match(textType)) {\n\t\tvar reader = new FileReader();\n\t\treader.onload = function(e) {\n\t\t\tgetDataFromXML(reader.result);\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\tloading('hide');\n\t\t\t\t$(\"#loadConfig\").dialog('destroy');\n\t\t\t}\n\t\t\t$(\"#configPopUp\").dialog('destroy');\n\t\t\t$(\"#fileType\").dialog('destroy');\n\t\t}\n\n\t\treader.readAsText(file);\t\n\t}else if(Application == \"titan\"){ \n\t\tloadTitanFromLocDir(fileName);\t\n\t}else {\n\t\talert(\"File not supported!\");\n\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\tloading('hide');\n\t\t\t$(\"#loadConfig\").dialog('destroy');\n\t\t}\n\t\t$(\"#configPopUp\").dialog('destroy');\n\t\t$(\"#fileType\").dialog('destroy');\n\t}\n}",
"function getFields(callback)\n{\n xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", \"populateFields.php?q=\" , true);\n xmlhttp.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n // defensive check\n if (typeof callback === \"function\") {\n // apply() sets the meaning of \"this\" in the callback\n callback.apply(xmlhttp);\n }\n }\n };\n xmlhttp.send();\n}",
"function findSpecialAbilityTemplatesQuery(str, callback) {\n var result;\n var suggestions;\n\n if (window.XMLHttpRequest) {\n xmlhttp=new XMLHttpRequest();\n } else {\n xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n xmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n result = xmlhttp.responseText;\n suggestions = JSON.parse(result);\n callback(suggestions);\n }\n }\n\n var params = \"get_special_abilities_suggestions=\".concat(str);\n xmlhttp.open(\"POST\", \"create-character.php\", true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.send(params);\n}",
"visitXmltype_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function FillGenresCallBack(data) \n{\n \n FillDropDowns(\"Genre\", data);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check whether width is already present in array | function CheckArrayContainsW(w) {
for (var i = 0; i < arrWidth.length; i++) {
if (arrWidth[i] == w || arrWidth[i] + 2 == w || arrWidth[i] - 2 == w)
return arrWidth[i];
}
} | [
"function InsertIntoArray(w) {\r\n //insert first element\r\n if (arrWidth.length == 0) {\r\n arrWidth[0] = w; \r\n return;\r\n }\r\n var eleExist = false;\r\n for (var i = 0; i < arrWidth.length; i++) {\r\n if (arrWidth[i] == w || arrWidth[i] + 2 == w || arrWidth[i] - 2 == w)\r\n eleExist = true;\r\n }\r\n //insert only if not already exist\r\n if (!eleExist)\r\n arrWidth[arrWidth.length] = w;\r\n}",
"function hasLength (data, value) {\n return assigned(data) && data.length === value;\n }",
"function IsArrayLike(x) {\r\n return x && typeof x.length == \"number\" && (!x.length || typeof x[0] != \"undefined\");\r\n }",
"checkForcedWidth() {\n var maximum_string_width = 0;\n\n for(var i=0;i<this.dispatcher.split_words.length;i++) {\n var block = this.dispatcher.split_words[i];\n if(block.match(/^\\s+$/)) { // только строка из пробелов совершает word-break, так что её не проверяем\n continue;\n }\n if(maximum_string_width < this.getStringWidth(block)) {\n maximum_string_width = this.getStringWidth(block);\n }\n }\n\n for(var i=0;i<99;i++) {\n var proposed_width = i * this.border_size;\n if(proposed_width > maximum_string_width) {\n this.forced_width = i;\n break;\n }\n }\n }",
"function checkWindowWidthSm() {\n\t\tvar e = window, \n a = 'inner';\n if (!('innerWidth' in window )) {\n a = 'client';\n e = document.documentElement || document.body;\n }\n if ( e[ a+'Width' ] <= breakpoint ) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"_checkAttributeArray() {\n const {\n value\n } = this;\n const limit = Math.min(4, this.size);\n\n if (value && value.length >= limit) {\n let valid = true;\n\n switch (limit) {\n case 4:\n valid = valid && Number.isFinite(value[3]);\n\n case 3:\n valid = valid && Number.isFinite(value[2]);\n\n case 2:\n valid = valid && Number.isFinite(value[1]);\n\n case 1:\n valid = valid && Number.isFinite(value[0]);\n break;\n\n default:\n valid = false;\n }\n\n if (!valid) {\n throw new Error(`Illegal attribute generated for ${this.id}`);\n }\n }\n }",
"isFull() {\r\n\t\treturn (this.emptyCells.size() == 0);\r\n\t}",
"function checkDuplicate(arr){\n return (new Set(arr)).size !== arr.length\n}",
"function findPerimeter(length, width) {\n let x = length * 2 + width * 2;\n if (x > 20) {\n console.log(`True. The perimeter is ${x}`)\n } else { console.log(`False. The perimeter is ${x}`) }\n}",
"checkCols(){\n\t\tthis.checkBounds();\n\t\tthis.checkBlocks();\n\t}",
"set requestedWidth(value) {}",
"function CheckForHorizontalCollision(){\r\n \r\n var tetrominoCopy = curTetromino;\r\n var collision = false;\r\n\r\n // Cycle through all Tetromino squares\r\n for(var i = 0; i < tetrominoCopy.length; i++)\r\n {\r\n \r\n var square = tetrominoCopy[i];\r\n var x = square[0] + startX;\r\n var y = square[1] + startY;\r\n\r\n \r\n if (direction == DIRECTION.LEFT){\r\n x--;\r\n }else if (direction == DIRECTION.RIGHT){\r\n x++;\r\n }\r\n\r\n \r\n var stoppedShapeVal = stoppedShapeArray[x][y];\r\n\r\n \r\n if (typeof stoppedShapeVal === 'string')\r\n {\r\n collision=true;\r\n break;\r\n }\r\n }\r\n\r\n return collision;\r\n}",
"isFull() {\n return this.size == this.maxSize;\n }",
"function inBox(arr) {\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tfor (let j = 0; j < arr[i].length; j++) {\n\t\t\tif (arr[i][j] === \"*\") {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}",
"function is_medium( vp_width ) {\n return vp_width > $(40).toCleanPx() && vp_width <= $(58.75).toCleanPx(); \n}",
"function costas_verify ( array ){\n var result;\n var diff_array = array_diff_vector( array );\n var array_set = set_of_values( array );\n var diff_array_set = set_of_values( diff_array );\n //console.log( 'diff_array length', diff_array.length );\n //console.log( 'diff_array_set length', diff_array_set.length );\n return ( diff_array.length === diff_array_set.length && array_set.length === array.length );\n}",
"function validateArrayValueUnique (arr){\r\n var i = 0, j = 0;\r\n while (undefined !== arr[i]){\r\n j = i + 1;\r\n while(undefined !== arr[j]){\r\n if (arr[i] == arr[j]) {\r\n return false;\r\n }\r\n ++j;\r\n }\r\n ++i;\r\n }\r\n return true;\r\n}",
"function arrLength(array){\n return array.length;\n}",
"function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
5. update the any one existing Mentors | editMentor() {} | [
"function addSkillToMentors(mentorsArr, newSkill) {\n mentorsArr.forEach((obj) => {\n obj.addSkill(newSkill);\n });\n}",
"update(numTarjeta, modificaciones) {\n return this.findOneAndUpdate({ numTarjeta: numTarjeta }, modificaciones, { multi: true });\n }",
"updateMonsterData(monsterData) {\n console.log(\"Updating monster info...\");\n this.updateTeamData(this.contentRows, \".simRight\", monsterData);\n }",
"addMentor(newMentor) {\n let allMentors = this.getMentorList();\n if (this.getMentorByName(newMentor.name)) {\n return false;\n } else {\n allMentors.push(newMentor);\n const newFileData = JSON.stringify(allMentors, null, 4); // converting object into string with space 4\n fs.writeFileSync(this.mentorsList, newFileData); // writing in the JSON file\n return true;\n }\n }",
"updateEmergencyPhoneNumber(username,phoneNumber){cov_idmd2e41v.f[15]++;cov_idmd2e41v.s[17]++;Citizen.updateOne({username:username},{phoneNumber:phoneNumber},err=>{cov_idmd2e41v.f[16]++;});}",
"update(newPerson) {\n // condLog(\"Update the Ahnentafel object\", newPerson);\n\n if (newPerson && newPerson._data.Id) {\n this.primaryPerson = newPerson;\n }\n if (this.primaryPerson) {\n // this.PrimaryID = newPerson._data.Id\n this.list = [0, this.primaryPerson._data.Id]; // initialize the Array\n this.listByPerson = new Array(); // initialize the Array\n this.listByPerson[this.primaryPerson._data.Id] = 1; // add the primary person to the list\n\n if (this.primaryPerson._data.Father && this.primaryPerson._data.Father > 0) {\n this.addToAhnenTafel(this.primaryPerson._data.Father, 2);\n }\n if (this.primaryPerson._data.Mother && this.primaryPerson._data.Mother > 0) {\n this.addToAhnenTafel(this.primaryPerson._data.Mother, 3);\n }\n this.listAll(); // sends message to the condLog for validation - this could be commented out and not hurt anything\n }\n }",
"function updateAll()\n{\n\t//\tUpdate actors\n\tfor (i = 0; i < actors.length; ++i) {\n\t\tactors[i].update();\n\t}\n}",
"set objectives(newObjectives) {\n this._objectives = newObjectives;\n for (i=0; i<this.newObjectives.length; i++) {\n scorm.set(`cmi.interactions.${this.index}.objectives.$[i}.id`, this._objectives[i].id);\n }\n scorm.save();\n }",
"function _updateAuthor()\n {\n MODEL.instance.author(_authorField.value);\n }",
"deleteMentor (mentorName) {\n let allMentors = this.getMentorList();\n if (this.getMentorByName(mentorName)) {\n allMentors = allMentors.filter(course=> course.name != mentorName);\n const newFileData = JSON.stringify(allMentors, null, 4); // converting object into string with space 4\n fs.writeFileSync(this.mentorsList, newFileData); // writing in the JSON file\n return true;\n } else {\n \n return false;\n }\n }",
"function promoteEmployee(id,callback)\n{\n db.run(\"UPDATE Employees SET role='Manager' WHERE rowid=?\",\n [id],\n function(err) { callback(); });\n}",
"party__update(party){\n this.digimons = party.digimons;\n for(const index in party.configuration){\n this.digimons[party.configuration[index].id].start_time = this.elapsed;\n this.digimons[party.configuration[index].id].background = party.configuration[index].bkg;\n this.digimons[party.configuration[index].id].bond_count = 0;\n this.digimons[party.configuration[index].id].light = party.configuration[index].light;\n }\n /* recebe digimons e adiciona o basico necessario relativo a pendulum, bkg, light, time, etc */\n}",
"async update(prosumers, consumers) {\r\n this.prosumers = prosumers;\r\n this.consumers = consumers;\r\n\r\n //if the powerplant is stopped or started the production is 0\r\n if(this.powerPlantStatus == \"Stopped\" || this.powerPlantStatus == \"Started\") {\r\n this.production = 0;\r\n } else {\r\n this.production = gaussian(config.managerProductionAverageValue, config.managerProductionStdvValue).ppf(Math.random()); \r\n }\r\n this.bufferBattery.setCapacity(this.production * this.bufferRatio);\r\n this.bufferBatteryCapacity = this.bufferBattery.getCapacity();\r\n this.prodToMarket = this.production * this.marketRatio;\r\n\r\n this.updateBlackoutList();\r\n \r\n //update manager in database and in simulation\r\n const updatedManager = await Managers.findOne({username: this.username});\r\n updatedManager.production = this.production;\r\n this.bufferRatio = updatedManager.bufferRatio/100;\r\n this.marketRatio = updatedManager.marketRatio/100;\r\n this.electricityPrice = updatedManager.electricityPrice;\r\n this.powerPlantStatus = updatedManager.powerPlantStatus;\r\n updatedManager.bufferBatteryCapacity = this.bufferBatteryCapacity;\r\n updatedManager.blackoutList = this.blackoutList;\r\n await updatedManager.save();\r\n\r\n this.market.update(this.prosumers, this.consumers, this.electricityPrice, this.prodToMarket);\r\n }",
"function updateIngredients(base) {\n ingredients.forEach(ingredient => ingredient.updateAmount(base));\n}",
"updateProjectiles() {\r\n //remvoe projectiles\r\n for (let [index, projectile] of this.projectileList.entries()) {\r\n if (projectile.toDelete) this.projectileList.splice(index, 1);\r\n }\r\n\r\n //update projectiles\r\n for (let projectile of this.projectileList) {\r\n projectile.update();\r\n }\r\n }",
"function modifyMgrMgrSel(empl) {\n const employee = empl;\n db.query(\n \"SELECT id, first_name, last_name FROM employee\",\n function (err, res) {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"And who will be their new leader?\",\n name: \"modifyMgrChangedM\",\n choices: function () {\n const choiceArrayMgr = [];\n for (let i = 0; i < res.length; i++) {\n choiceArrayMgr.push(\n `${res[i].id} | ${res[i].first_name} ${res[i].last_name}`\n );\n }\n return choiceArrayMgr;\n },\n },\n ])\n .then(function (people) {\n const mgr = parseInt(people.modifyMgrChangedM.slice(0, 5));\n const changingEmpl = employee;\n\n if (mgr === changingEmpl) {\n console.log(\n `Looks like you have the same manager and employee id. Please try again.`\n );\n modifyMgrEmplSel();\n } else {\n db.query(\n \"UPDATE employee SET manager_id = ? WHERE id = ?\",\n [mgr, changingEmpl],\n function (err, res) {\n if (err) {\n } else {\n console.log(`All set, thanks!`);\n firstQ();\n }\n }\n );\n }\n });\n }\n );\n}",
"function updateSponsors() {\n const files = fs.readdirSync(__dirname + '/../src/.vuepress/public/sponsors')\n const logos = {}\n files.forEach(file => {\n if (/\\.(svg|png)$/.test(file)) {\n const id = file.substring(0, file.lastIndexOf('.'))\n logos[id] = 'sponsors/' + file\n }\n })\n fetch('https://opencollective.com/assemblyscript/members/all.json')\n .then(res => res.json())\n .then(json => {\n const seen = new Map()\n const sponsors = json\n .map(item => {\n item.username = item.profile.substring(item.profile.lastIndexOf('/') + 1)\n return item\n })\n .filter(item => {\n if (seen.has(item.username)) return false\n seen.set(item.username, item.totalAmountDonated)\n return item.isActive && item.totalAmountDonated > 0\n })\n .map(item => {\n const inherits = sponsorInherits[item.username]\n if (Array.isArray(inherits)) {\n for (let othername of inherits) {\n json\n .filter(otheritem => otheritem.username == othername)\n .forEach(otheritem => item.totalAmountDonated += otheritem.totalAmountDonated)\n seen.delete(othername)\n }\n }\n return item\n })\n .filter(item => !sponsorExcludes.includes(item.username) && seen.has(item.username))\n .sort((a, b) => b.totalAmountDonated - a.totalAmountDonated)\n .map(item => {\n const logoSize = getLogoSize(item)\n const logo = logos[item.username] || 'https://images.opencollective.com/' + item.username + '/avatar/' + logoSize + '.jpg'\n const link = item.totalAmountDonated >= tiers.bronze.minAmount\n ? item.website || item.profile\n : item.profile\n return {\n // id: item.MemberId,\n name: item.name,\n logo: logo,\n link: link,\n amount: item.totalAmountDonated\n }\n })\n fs.writeFileSync(__dirname + '/../data/sponsors.json', JSON.stringify(sponsors, null, 2))\n })\n .catch(err => {\n console.error(err.stack)\n process.exit(1)\n })\n}",
"function updateSeminar(req, res) {\n Seminar.findOneAndUpdate({ _id: req.params.SeminarId}, req.body, {new: true}, (err, Seminar) => {\n if (err) {\n res.send(err);\n }\n res.json(Seminar);\n });\n}",
"function uppdatMemberInAppData(e){\n\n const originalName =e.target.closest('.member-in-list').querySelector('.memebr-name').textContent;\n\n const newList = {\n name:e.target.closest('.member-in-list').querySelector('.new-member-name').value\n };\n\n appData.members.forEach((member)=>{\n if(member.name===originalName){\n member.name=newList.name;\n }\n })\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays a JSONformatted representation of domain list data | function gotTheDomainListData2(data) {
var z = data;
alert(JSON.stringify(data));
} | [
"function getDomainInfo(){\n\tvar url = getURL(\"ConfigEditor\",\"JSON\");\n\tif(globalDeviceType == \"Mobile\"){\n loading('show');\n }\n\tvar InfoType = \"JSON\";\n\tvar query = {\"QUERY\":[{\"user\":globalUserName}]};\n query = JSON.stringify(query);\n\tconsole\n\t$.ajax({\n\t\turl: url,\n\t\tdata : {\n\t\t\t\"action\": \"domaininfo\",\n\t\t\t\"query\": query//\"user=\"+globalUserName,\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tif(globalDeviceType == \"Mobile\"){\n \t\tloading('hide');\n\t\t }\n\t\t\twindow['variable' + dynamicDomain[pageCanvas] ] = \"Auto\"\n\t\t\tdata = $.trim(data);\n\t\t\tvar domainArray = [];\n\t\t\tvar zoneArray = [];\n\t\t\tvar groupArrat = [];\n\t\t\tif(InfoType == \"XML\"){\n\t\t\t\tvar parser = new DOMParser();\n\t\t\t\tvar xmlDoc = parser.parseFromString(data , \"text/xml\" );\n\t\t\t\tvar mainconfig = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\t\t\tvar domain = xmlDoc.getElementsByTagName('DOMAIN');\n\t\t\t\tvar selVal='<option value=\"\" data-placeholder=\"true\">Resource Domain</option>';\n\t\t\t\tvar startUpDom = mainconfig[0].getAttribute('StartUpDomain');\n\t\t\t\tfor(var a=0; a < domain.length; a++){\n\t if(startUpDom == domain[a].getAttribute('DomainName')){\n \t var sel = 'selected';\n \t }else{\n \t var sel = '';\n \t}\n\t selVal += \"<option \"+sel+\" value='\"+domain[a].getAttribute('DomainName')+\"'>\"+domain[a].getAttribute('DomainName')+\"</option>\";\n \t}\n\t\t\t}else{\n\t\t\t\tvar dat = data.replace(/'/g,'\"');\n var dat2 = $.parseJSON(dat);\n\t\t\t\tvar domain = dat2.MAINCONFIG[0].DOMAIN;\n\t\t\t\tvar startUpDom = dat2.MAINCONFIG[0].StartUpDomain;\n\t\t\t\tfor(var a=0; a < domain.length; a++){\n if(startUpDom == domain[a].DomainName){\n var sel = 'selected';\n }else{\n var sel = '';\n }\n selVal += \"<option \"+sel+\" value='\"+domain[a].DomainName+\"'>\"+domain[a].DomainName+\"</option>\";\n }\n\t\t\t}\n\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\tif(domain.length <= 1 ){\n\t\t\t\t\t$(\"#resDomChkbox\").hide();\n\t\t\t\t\t$('#resDomSelect').selectmenu('disable');\n\t\t\t\t}\n\t\t\t\t$(\"#resDomSelect\").html(selVal).selectmenu( \"refresh\" );\n\t\t\t\t$(\"#resDomSelect\").parent().css({\"width\":\"100px\"});\n\t\t\t}else{\n\t\t\t\t$(\"#resDomSelect\").html(selVal);\n\t\t\t\tif(domain.length <= 1 ){\n\t\t\t\t\t$(\".squaredTwo\").hide();\n\t\t\t\t\t$('#resDomSelect').attr('disabled',true);\n\t\t\t\t\t$('#resDomSelect').css({\"background\":\"#ccc\"});\n\t\t\t\t\twindow['variable' + dynamicDomain[pageCanvas] ] = $('#resDomSelect').val();\n\t\t\t\t\tdomainFlag = true;\n\t\t\t\t}\n\t\t\t\t$(\"#resDomSelect\").parent().css({\"width\":\"100px\"});\t\t\t\n\t\t\t\t//$(\"#resDomSelect\").attr('disabled', true);\n\t\t\t}\n\t\t}\n\t});\n}",
"function showStravaActivities(){\n var lengthActivities = activities.length;\n if (lengthActivities > 0) {\n var listHTML = '<ul>';\n\n for (var i = 0; i < lengthActivities; ++i) {\n console.log(activities[i].id); \n listHTML += '<li>' + activities[i].name + \" - \" + activities[i].date + \" - \" + activities[i].id + '</li>';\n }\n\n listHTML += '</ul>';\n $( \".listActivities\" ).append( listHTML );\n }\n}",
"function jsonToDl(data, child) {\n var ret, key, value, row, display;\n\n if (typeof data === 'string') {\n data = parseJSON(data);\n }\n\n if (!data) {\n return;\n }\n\n ret = $('<dl />');\n\n if (!child) {\n ret.addClass('adminMeta');\n }\n\n function clickHandler(e) {\n var $this;\n\n e.stopPropagation();\n\n $this = $(this);\n\n $this.toggle(function () {\n $this\n .removeClass('collapsible')\n .addClass('expandable');\n }, function () {\n $this\n .removeClass('expandable')\n .addClass('collapsible');\n });\n $this.next().toggle();\n }\n\n for (key in data) {\n if (data.hasOwnProperty(key)) {\n\t\t\t\tif (key === 'display') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n row = $('<dt />').text(key);\n\n row.appendTo(ret);\n\n if (data[key] == null) {\n continue;\n }\n if (typeof data[key] !== 'object') {\n $('<dd />')\n .text(data[key])\n .appendTo(ret);\n } else {\n row\n .addClass('collapsible')\n .click(clickHandler);\n\n $('<dd />')\n .html(jsonToDl(data[key], true))\n .appendTo(ret);\n\n }\n }\n }\n\n return ret;\n }",
"function list(req, res) {\n res.json({ data: dishes });\n}",
"function getDomains() {\n var domains = new Array();\n $(\"#edit-field-domain-access :checked\").each(function(index, obj) {\n domains.push(obj.value);\n });\n setOptions(domains);\n }",
"function displayAutocomplete(data) {\t\n\tconst pages = data.query.pages;\n\t\n\t//Create a datalist option for each search item found.\n\tconst searchResultHtml = Object.keys(pages).map( function(key){\n\t\tconst { title } = pages[key];\n\t\treturn html = ` <option value=\"${title}\">${title}</option> `;\n\t});\t\n\t//Put all datalist option search result item in input datalist.\t\n\tsearchDatalist.innerHTML = searchResultHtml.join(\"\");\n}",
"function displayEmployees(data) {\n employees = data;\n appendEmployeHTMLStringToDOM(employees);\n}",
"function CompanyList()\n{\n\tHandleList.call(this, \"CompanyList\");\n}",
"function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}",
"function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}",
"function showList(a_oItems, g_nLoc){\n \n var s_List = \"\"; \n for (var i=0; i< a_oItems.length; i++){\n s_List = s_List + \"\\n\" + a_oItems[i].Name(g_nLoc); \n } \n return s_List; \n}",
"GetMailingLists(domain, name) {\n let url = `/email/domain/${domain}/mailingList?`;\n const queryParams = new query_params_1.default();\n if (name) {\n queryParams.set('name', name);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function showGroupName(){\n\tvar url = \"https://\"+CURRENT_IP+\"/cgi-bin/NFast_3-0/CGI/RESERVATIONMANAGER/FastConsoleCgi.py?action=getgroupnamelist&query={'QUERY':[{'username':'\"+globalUserName+\"'}]}\";\n\t\t$.ajax({\n\t\turl: url,\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData : false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\t\tconsole.log(\"getGROUP\",data)\n\t\t\t\tfor (var i = 0; i< json.data[0].row.length; i++ ){\n\t\t\t\t\tvar groupname = json.data[0].row[i].GroupName;\n\t\t\t\t\tvar hostname =\tjson.data[0].row[i].HostName;\n\t\t\t\t\tvar usermember = json.data[0].row[i].UserMember;\n\t\t\t\tstr += \"<li style='font-size:10px;list-style:none;cursor:pointer;text-align:left;margin-left:4px;' class='createdGroup'>\"+groupname+\"</li>\"\t\t\t\t\n\t\t\t\t}\n\t\t\t\t$('#grouplist').html(str);\n\t\t\t}\n\t});\n}",
"function renderDogOwnersList(dogOwners) {\n $('#client-info-list').html(dogOwners.map(dogOwnerToHtml));\n\n // Takes each individual dog owner and displays the requested info\n function dogOwnerToHtml(dogOwner) {\n let notesShorten = dogOwner.notes;\n if (notesShorten.length > 120) {\n notesShorten = `${dogOwner.notes.substring(0, 120)}...`;\n }\n return `\n <div id=\"dogOwner-card\" class=\"dogOwner-card\" dogOwner-id-data=\"${dogOwner.id}\">\n <ul class=\"client-info\">\n <div class=\"row client-header\">\n <div class=\"col-3\">\n <li class=\"dogOwner-card-header dogOwner-name\">${dogOwner.firstName} ${dogOwner.lastName}</li>\n </div>\n <div class=\"col-3\"\n <li><button id=\"delete-dogOwner-btn\" class=\"delete-btn\">Delete</button></li>\n </div>\n </div>\n <li class=\"dogOwner-card-dogName\">Dog(s): ${dogOwner.dogNames}</li>\n <li class=\"dogOwner-card-address\">Address: ${dogOwner.address}</li>\n <li class=\"dogOwner-card-notes\">Notes: ${notesShorten}</li>\n </ul>\n </div>\n `;\n }\n}",
"function questions_html(){\n let html = \"<ol>\";\n let nr = 0;\n if ( Object.keys( self.questions ).length > 0 ) for (const answers of Object.values( self.questions )){\n nr += 1;\n html += \"<li>\";\n if ( self.headers && self.headers[ nr ] ) html += \"<b>\"+ self.headers[ nr ] +\"</b>\";\n html += \"<ol type='a'>\";\n for (const answer of Object.values(answers)){\n html += \"<li>\" + answer + \"</li>\";\n }\n html += \"</ol></li>\";\n }\n html += \"</ol>\";\n return html;\n }",
"function _build_object_dl(data) {\n\tvar dl = document.createElement('DL');\n\tfor (var property in data) {\n\t\tif (data.hasOwnProperty(property) && property != 'datestamp') {\n\t\t\tvar dd = document.createElement('DD');\n\t\t\tvar dt = document.createElement('DT');\n\t\t\tdt.innerHTML = property;\n\t\t\tif(typeof(data[property]) == 'object') {\n\t\t\t\tvar idl = _build_object_dl(data[property]);\n\t\t\t\tdd.appendChild(idl);\n\t\t\t} else {\n\t\t\t\tdd.innerHTML = data[property];\n\t\t\t}\n\t\t\tdl.appendChild(dt);\n\t\t\tdl.appendChild(dd);\n\t\t}\n\t}\n\treturn dl;\n}",
"ListOfDomainTask(domain, _function, status) {\n let url = `/me/task/domain?`;\n const queryParams = new query_params_1.default();\n if (domain) {\n queryParams.set('domain', domain);\n }\n if (_function) {\n queryParams.set('function', _function.toString());\n }\n if (status) {\n queryParams.set('status', status.toString());\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"async renderListData(viewXml) {\n const q = List(this, \"renderlistdata(@viewXml)\");\n q.query.set(\"@viewXml\", `'${viewXml}'`);\n const data = await spPost(q);\n return JSON.parse(data);\n }",
"function buildList() {\n $log.debug(\"Building list...\");\n vm.list = Object.keys(queryFields); //get the keys\n vm.definitions = queryFields;\n $log.debug(vm.definitions);\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.